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.

Revert PR #608 pending careful review (#610)

Deece23cf697d9f
diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjs
index 211a4cf36..fee9c9d09 100644
--- a/cli/hook/notify.mjs
+++ b/cli/hook/notify.mjs
@@ -79,9 +79,6 @@ function argValue(name, fallback) {
return fallback
}
-// Set by the claude PreToolUse gate branch; written to stdout at exit (see the finally block).
-let gateOutput = null
-
function argEngine() {
const i = process.argv.indexOf('--engine')
const value = i !== -1 ? process.argv[i + 1] : ''
@@ -239,35 +236,6 @@ function readStdin() {
})
}
-// Like post(), but resolves the parsed JSON reply (or null). Used where the daemon's answer matters:
-// the destructive-action gate hands a permissionDecision back through PreToolUse.
-function postJson(port, path, body) {
- return new Promise((resolve) => {
- const payload = JSON.stringify(body)
- const credential = readHookCredential()
- if (!credential) { resolve(null); return }
- const req = http.request(
- {
- host: '127.0.0.1', port, path, method: 'POST',
- headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload), 'X-Harness-Hook-Token': credential },
- timeout: Math.max(1, Math.min(1500, remainingBudget())),
- },
- (res) => {
- let text = ''
- res.setEncoding('utf8')
- res.on('data', (chunk) => { if (text.length < 65536) text += chunk })
- res.on('end', () => {
- if (!((res.statusCode || 0) >= 200 && (res.statusCode || 0) < 300)) { resolve(null); return }
- try { resolve(JSON.parse(text)) } catch { resolve(null) }
- })
- },
- )
- req.on('error', () => resolve(null))
- req.on('timeout', () => { req.destroy(); resolve(null) })
- req.end(payload)
- })
-}
-
function boundedPrompt(prompt) {
// An oversized/escape-heavy prompt must still announce its submission so the daemon
// clears earlier scope. Keep the serialized field within the hook receiver's bounds.
@@ -1513,33 +1481,6 @@ async function main() {
return
}
- // Claude's PreToolUse is installed ONLY by `harness gate install` (lib/hooks.ts installGateHook). The
- // daemon classifies the tool call against the machine's action policy; a non-allow verdict goes back
- // on stdout in the shape Claude Code reads, so the engine shows its own permission prompt (which the
- // question watcher mirrors to the device). Silence, on any failure, means allow: the gate must never
- // wedge a session because the daemon was busy.
- if (engine === 'claude' && event === 'PreToolUse') {
- if (typeof input.tool_use_id !== 'string' || typeof input.tool_name !== 'string') return
- const reply = await postJson(port, '/api/hook/tool-start', {
- sessionId: input.session_id,
- toolUseId: input.tool_use_id,
- toolName: input.tool_name,
- input: input.tool_input,
- ...mutationFields,
- })
- const gate = reply && reply.gate
- if (gate && (gate.decision === 'ask' || gate.decision === 'deny')) {
- gateOutput = JSON.stringify({
- hookSpecificOutput: {
- hookEventName: 'PreToolUse',
- permissionDecision: gate.decision,
- permissionDecisionReason: `Harness gate: ${gate.reason || gate.rule || 'machine policy'}`,
- },
- })
- }
- return
- }
-
if (engine === 'cursor' && event === 'preToolUse') {
if (input.tool_name === 'Task' && typeof input.tool_use_id === 'string') {
await persistCursorTask(input)
@@ -1676,6 +1617,5 @@ main()
Promise.resolve(acknowledgeMemoryOutput()).catch(() => {}).finally(() => process.exit(0))
})
else if (e === 'cursor' || e === 'hermes' || e === 'agy' || e === 'copilot') process.stdout.write('{}\n', () => process.exit(0))
- else if (gateOutput) process.stdout.write(gateOutput + '\n', () => process.exit(0)) // claude PreToolUse gate verdict
else process.exit(0)
})
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index b58ccda38..fd08dd788 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -186,11 +186,6 @@ const DEVICE_AGENT_NAME_MAX_BYTES = 39 // device project_t.name[40], including t
const DEVICE_ELLIPSIS = '…'
export type Frame = Record<string, unknown>
-
-/** A `clip_push` payload after validation (fleet/control.ts; first written by Fred Nix in the nixfred fork). */
-export interface ClipPush { text?: string; file?: { name: string; base64: string }; from: string }
-export const CLIP_TEXT_MAX = 1_000_000
-export const CLIP_FILE_MAX_B64 = 34_000_000 // ~25 MB decoded
type OutboundEnvelope = Record<string, unknown>
export interface LocalClientSink {
@@ -561,8 +556,6 @@ export class BackendSocket {
Promise<{ ok: true; id: string } | { ok: false; error: string; detail: string }>) | null = null
/** Called on `dsh_remove` — cli.ts uninstalls the harness from this machine. */
onDshRemove: ((id: string) => { ok: true } | { ok: false; error: string; detail: string }) | null = null
- /** A paired peer pushed text or a file to this machine's clipboard / drop folder (`harness clip push`). */
- onClipPush: ((push: ClipPush) => Promise<{ ok: true; detail: string } | { ok: false; error: string }>) | null = null
/** Called on `remote_terminal_handoff` — cli.ts names the agent whose tile is that tmux pane, or null. */
onTerminalHandoff: ((tmuxPane: string) => string | null) | null = null
/** What the daemon knows about an agent's DSH companions (viewer URL, verdict); null when nothing. */
@@ -2570,21 +2563,6 @@ export class BackendSocket {
return
}
- case 'clip_push': {
- // Sealed end to end (a MACHINE_REQUESTS type), so only a paired peer reaches here. Sizes are
- // bounded before anything touches the clipboard or the disk.
- if (!this.onClipPush) { reply(type, requestId, { error: 'UNSUPPORTED' }); return }
- const text = typeof payload.text === 'string' ? payload.text : undefined
- const file = payload.file && typeof payload.file === 'object' ? payload.file as { name?: unknown; base64?: unknown } : undefined
- if (text !== undefined && text.length > CLIP_TEXT_MAX) { reply(type, requestId, { error: 'CLIP_TOO_LARGE', detail: `text over ${CLIP_TEXT_MAX} chars` }); return }
- if (file && (typeof file.name !== 'string' || typeof file.base64 !== 'string' || file.base64.length > CLIP_FILE_MAX_B64)) { reply(type, requestId, { error: 'CLIP_TOO_LARGE', detail: `file over ${Math.round(CLIP_FILE_MAX_B64 * 3 / 4 / 1048576)} MB or malformed` }); return }
- if (text === undefined && !file) { reply(type, requestId, { error: 'CLIP_EMPTY' }); return }
- void this.onClipPush({ text, file: file ? { name: file.name as string, base64: file.base64 as string } : undefined, from: typeof payload.from === 'string' ? payload.from.slice(0, 64) : 'peer' })
- .then((out) => reply(type, requestId, out))
- .catch((error) => reply(type, requestId, { error: 'INTERNAL', detail: error instanceof Error ? error.message : String(error) }))
- return
- }
-
case 'dsh_remove': {
// Uninstall a harness from THIS machine: the clone under ~/.harness/dsh goes (a linked
// install loses only its link), the index forgets it, and a `dsh_list` after this no
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index c1e023d70..88e24ad5a 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -304,7 +304,6 @@ import {
import { probeGatewayRuntime } from './lib/gatewayRuntime.js'
import { probeGridAssignment, sameGridAssignment } from './lib/gridAssignment.js'
import { agentFrame, lastActivityAt, type AgentFrame } from './lib/agentFrame.js'
-import { FleetControl, type FleetSessionLike } from './fleet/control.js'
import { agentTokenUsage } from './lib/agentTokenUsage.js'
import { SessionInputController } from './lib/sessionInput.js'
import { DeviceResultJournal } from './lib/autonomous-device/resultJournal.js'
@@ -455,24 +454,7 @@ Machine:
harness stop stop the background adapter (keeps the SSO session)
harness reset stop the adapter and clear local CLI state
harness status show whether it's running (+ version)
- harness attention [--kanban] every agent's state: working, waiting on you, needs permission, failed, done
- harness stop-all [--except=<agentId>]
- cancel every agent's turn on this computer (the panic stop)
- harness gate init|install|uninstall|status|reload
- opt-in Claude guard: ask before git push, rm -rf, sudo …; refuse disk
- writes and ~/.ssh (policy: ~/.harness/cli/data/action-policy.json)
- harness spend status|set --agent-usd=N --day-usd=N|on|off
- per-agent and per-day spend caps; a pane over its cap is held (off by default)
- harness capabilities this computer's GPU, load, power, heat, lid and toolchains
- harness placement [--gpu] [--min-vram=MB] [--interactive]
- whether this computer should take a job like that
- harness subs [--force] | subs set <claude|codex|grok|kimi> <on|off>
- each AI plan's weekly use, banked against an even pace, and which to use next
- harness dispatch --machine=<id> --repo=<path there> [--engine=claude] [--branch=x] "brief"
- hand a bounded job to a linked machine; \`harness dispatches\` lists them
- harness clip push --machine=<id> [--file=<path>] [text]
- clipboard or a file (25 MB) to a linked machine, sealed end to end
- harness logs export zip the last 7 days of logs (app, CLI, dial, daemon) to the Desktop
+ harness logs export zip the last 7 days of logs (app, CLI, dial, daemon) to the Desktop
harness tui all of Harness in this terminal: swarms, panes, every machine (⌥O ⌥P ⌥N)
harness new [agent] [@machine] [folder|name] [-- task]
make a harness from a shell: \`harness new\` is claude here; see \`harness new -h\`
@@ -2495,10 +2477,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
): void => {
if (events.length) queuedSessionEvents.push({ sessionId, events, opts })
}
- // The fleet controls (attention, stop-all, local commands; cli/src/fleet/control.ts). Built next to the
- // hook server below; the taps before that point reach it through this slot, so an event that lands
- // during start-up is dropped instead of reaching an object that does not exist yet.
- let fleetControlRef: FleetControl | null = null
/**
* A turn died inside the engine instead of finishing. Neither devin nor commandcode has a StopFailure
* hook, so nothing else would tell the clients: the web would sit on the typing indicator and the
@@ -2512,7 +2490,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
deviceMessage = message,
): void => {
console.log(`[turn] ${sid(sessionId)} aborted by ${engine} error · ${preview(message)}`)
- fleetControlRef?.attention.failed(agentIdFor(sessionId), message)
backend.send({ type: 'error', agentId: agentIdFor(sessionId), dbSessionId: sessionId, payload: { message } })
backend.sendCommander({
type: 'commander_event',
@@ -2967,7 +2944,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// Hold the working state across the gap too: the CLI needs a moment to move to the next question, and
// that gap is exactly where the stale recap used to flash back.
const target = payload.sessionId || payload.agentId
- if (typeof target === 'string' && target) { showAwaitingAnswer(target); fleetControlRef?.attention.answered(agentIdFor(target)) }
+ if (typeof target === 'string' && target) showAwaitingAnswer(target)
// Returned so the client that answered hears a refusal — STALE_QUESTION when the dialog changed
// before its answer arrived — as `question_response_result`.
return questions.answer(payload)
@@ -2986,7 +2963,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
isDriving: (sessionId) => questions.isDriving(sessionId),
onQuestion: (sessionId, requestId, shaped, detail) => {
deviceInput.setUserAction(agentIdFor(sessionId), true)
- fleetControlRef?.attention.question(agentIdFor(sessionId), detail?.permission === true, shaped[0]?.q ?? '')
questions.remember(requestId, sessionId)
showAwaitingAnswer(sessionId)
const asked = {
@@ -3241,7 +3217,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
backend.runtimeProfileProvider = (session) => runtimeProfiles.selectedModel(session)
backend.dshFrameProvider = dshFrameContext
backend.onDshRemove = (id) => removeDsh(id)
- backend.onClipPush = (push) => fleetControlRef ? fleetControlRef.clipReceive(push) : Promise.resolve({ ok: false as const, error: 'STARTING' })
// `harness remote` names the tile it was typed in by its tmux pane; the registry knows whose it is.
backend.onTerminalHandoff = (tmuxPane) => registry.advertised()
.find((session) => session.tmuxPane === tmuxPane
@@ -3348,7 +3323,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// The phone notifies on neither. Absent = false, so a client that predates these reads every end as
// it always did.
if (event.type === 'turn_ended') {
- if (!opts?.resumed && !opts?.replay) fleetControlRef?.attention.turnEnded(agentId, { aborted: event.payload.aborted === true })
if (opts?.resumed || opts?.replay) frame.replay = true
// The pair harness is the daemon talking to you, not work finishing: no app notifies on it.
if (isSubagentSession(sessionId) || isPairHarnessSession(sessionId)) frame.subagent = true
@@ -3364,7 +3338,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
}
if (event.type === 'turn_started') {
if (daemons.on()) zooTurnCounter.started(sessionId, { replay: !!(opts?.resumed || opts?.replay) })
- if (!opts?.resumed && !opts?.replay) fleetControlRef?.attention.turnStarted(agentId, event.payload.userMessage)
turnStartedAt.set(sessionId, Date.now())
console.log(`[turn] ${sid(sessionId)} started · engine=${registry.bySession(sessionId)?.engine ?? 'claude'} · bytes=${Buffer.byteLength(event.payload.userMessage, 'utf8')}`)
input.onTurnStarted(agentIdFor(sessionId), event.payload.userMessage)
@@ -4211,23 +4184,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
return { status: 200, body: withStaleMarker(cached.body, cached.fetchedAt) }
}
- // Built here so the hook server below can hand it tool calls, and everything after can tap it.
- const fleetSession = (s: RegisteredSession): FleetSessionLike => ({
- agentId: s.agentId, sessionId: s.sessionId, engine: s.engine, active: s.active, tmuxPane: s.tmuxPane,
- cwd: s.cwd ?? undefined, transcriptPath: s.transcriptPath ?? undefined, model: (s as { model?: string | null }).model ?? null, name: projectDisplayName(s),
- })
- const fleetControl = new FleetControl({
- machineId: () => backend.machineId,
- machineName: () => terminalHintMachineName(),
- sessions: () => registry.advertised().map(fleetSession),
- sendLocal: (frame) => backend.sendLocal(frame),
- sendError: (agentId, dbSessionId, message) => backend.send({ type: 'error', agentId, dbSessionId, payload: { message } }),
- cancelAgent: (agentId, confirmed) => cancelAgent(agentId, confirmed),
- tokenUsage: (s) => { const r = registry.resolve(s.agentId); return r ? agentTokenUsage.get(r) : null },
- // A getter: the port is known once the hook server below has bound, and only `gate install` asks.
- hookPort: () => hookPort,
- })
- fleetControlRef = fleetControl
const { server: hookServer, port: hookPort, localSocket } = await startHookServer(daemonPort(), {
onPromptContext: async (agentId, prompt) => {
@@ -4250,10 +4206,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
return result
},
onCommandBar: commandBarService,
- onAttention: () => fleetControl.attentionPayload(),
- onSubscriptions: () => fleetControl.subs.collect(),
- onStopAll: (except) => fleetControl.stopAll(except),
- onFleet: (action, args) => fleetControl.command(action, args),
onAutonomousDeviceRequest: async (method, target, body) => {
if (!autonomousDeviceService) return { status: 503, body: { error: { code: 'UNAVAILABLE', message: 'Autonomous device service is starting' } } }
return autonomousDeviceLocalRequest({
@@ -4351,14 +4303,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {
},
onToolStart: ({ sessionId, toolUseId, toolName, input: toolInput }) => {
if (toolName === 'Task') onCursorTaskStart(sessionId, toolUseId, toolInput)
- // The destructive-action gate: classify against the machine policy; the verdict rides back to the
- // hook script, which turns ask/deny into the engine's own permission prompt.
- return fleetControl.gate(sessionId, agentIdFor(sessionId), toolName, toolInput)
},
onTurnStop: ({ sessionId, status }) => {
const session = registry.resolve(sessionId)
if (!session) return
- if (status === 'error') fleetControl.attention.failed(session.agentId, 'engine ended the turn with an error')
if (session.engine === 'cursor') {
void (async () => {
await cursorTaskHooks.wait(sessionId)
@@ -4725,27 +4673,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
},
},
)
- // The fleet dispatcher and clip push ride the same pool the window uses to reach a linked machine:
- // one E2EE-terminated session per machine, frames fanned out to whoever attached.
- fleetControl.setRelayLink(async (machineId) => {
- const listeners = new Set<(frame: { type: string; payload: Record<string, unknown> }) => void>()
- const sink = {
- sendFrame: (frame: Record<string, unknown>) => {
- const payload = (frame.payload && typeof frame.payload === 'object' ? frame.payload : {}) as Record<string, unknown>
- // The event correlator puts agentId on the frame and in the payload; keep it reachable either way.
- const shaped = { type: String(frame.type ?? ''), payload: typeof frame.agentId === 'string' && !payload.agentId ? { ...payload, agentId: frame.agentId } : payload }
- for (const cb of listeners) cb(shaped)
- return true
- },
- sendBinary: () => true,
- }
- const session = await relayPool.acquire(machineId, env.AUTONOMOUS_ENV, { type: 'machine_select', payload: { machineId } }, sink, () => { listeners.clear() })
- return {
- send: (frame) => session.send(frame as unknown as Record<string, unknown>),
- onFrame: (cb) => { listeners.add(cb); return () => { listeners.delete(cb) } },
- close: () => session.detach(),
- }
- })
// Every machine and phone linked to this one, directly or through another member, trusts every other:
// rosters are swapped over any session that opens, and pushed on whenever they change.
groupSyncer = new GroupSyncer({
@@ -5391,7 +5318,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// The window looked at a harness, so the dial's drawer row for it is stale.
// The dial's own tap already reaches the window (`agent.open`); this is the
// return leg, and the pair is what keeps the badge and the pill equal.
- onAgentSeen: (agentId, readToken) => { fleetControlRef?.attention.seen(agentId); void cableRef?.agentSeen(agentId, readToken) },
+ onAgentSeen: (agentId, readToken) => { void cableRef?.agentSeen(agentId, readToken) },
// Agents the window has a tile for. A finished turn on one of these is
// already in front of the person, so the dial updates its tile in silence
// rather than beeping about something being looked at.
@@ -6132,7 +6059,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const sessionId = record?.sessionId ?? id
const st = turnStates.get(sessionId)
if (st) st.turnOpen = false
- fleetControlRef?.attention.cancelled(record?.agentId ?? sessionId)
codexNormalizers.get(sessionId)?.closeTurn()
cursorNormalizers.get(sessionId)?.closeTurn()
opencodeReaders.get(sessionId)?.closeTurn()
@@ -7186,11 +7112,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {
console.log(`[msg] ${sid(sessionId)} slash-command adapted for engine=${engine}`)
}
console.log(`[msg] ${sid(sessionId)} recv · engine=${engine} · bytes=${Buffer.byteLength(adapted, 'utf8')}`)
- // The spend brake (off until `harness spend set`): a pane over its cap is held and the web is told why.
- if (record && fleetControl.spendCheck(fleetSession(record)).action === 'pause') {
- console.log(`[msg] ${sid(sessionId)} held by the spend brake`)
- return
- }
input.submit(record?.agentId ?? sessionId, adapted, deliveryId, tabId)
}
backend.onMessage = (id, content, deliveryId, tabId) => submitAgent(id, content, deliveryId, tabId)
@@ -8013,98 +7934,6 @@ async function daemonCall(method: 'GET' | 'POST', path: string, body?: unknown):
return { res, json }
}
-/**
- * The fleet commands (cli/src/fleet/control.ts; first written by Fred Nix in the nixfred fork): every one
- * is a POST to the daemon's local /api/fleet with an action name, so the CLI never needs the registry or
- * the E2EE state. `--json` prints the raw reply.
- */
-async function fleetCommand(cmd: string, args: string[], flags: string[]): Promise<void> {
- const json = flags.includes('--json')
- const flag = (name: string): string | undefined => flags.find((f) => f.startsWith(`--${name}=`))?.slice(name.length + 3)
- const num = (name: string): number | null | undefined => { const v = flag(name); if (v === undefined) return undefined; if (v === 'off' || v === 'null') return null; const n = Number(v); return Number.isFinite(n) ? n : undefined }
- let action = cmd
- let body: Record<string, unknown> = {}
- switch (cmd) {
- case 'attention': break
- case 'stop-all': body = { except: flag('except') ?? args[0] ?? null }; break
- case 'gate': action = `gate-${args[0] ?? 'status'}`; break
- case 'spend': {
- action = `spend-${args[0] ?? 'status'}`
- if (action === 'spend-set') body = { perAgentUsd: num('agent-usd'), perAgentTokens: num('agent-tokens'), perDayUsd: num('day-usd'), perDayTokens: num('day-tokens'), warnAt: num('warn-at') ?? undefined, ...(flags.includes('--off') ? { enabled: false } : flags.includes('--on') ? { enabled: true } : {}) }
- if (action === 'spend-off') { action = 'spend-set'; body = { enabled: false } }
- if (action === 'spend-on') { action = 'spend-set'; body = { enabled: true } }
- break
- }
- case 'dispatch': {
- const brief = args.join(' ')
- if (!brief || !flag('machine') || !flag('repo')) { console.error('Usage: harness dispatch --machine=<machineId> --repo=</path/on/that/machine> [--engine=claude] [--branch=name] [--dsh=id] "brief"'); process.exit(1) }
- body = { machine: flag('machine'), repo: flag('repo'), engine: flag('engine') ?? 'claude', branch: flag('branch') ?? '', dsh: flag('dsh') ?? '', brief }
- break
- }
- case 'dispatches': break
- case 'clip': {
- // harness clip push --machine=<id> [--file=path] [text]; with neither text nor file, the local clipboard is sent.
- if (args[0] !== 'push' || !flag('machine')) { console.error('Usage: harness clip push --machine=<machineId> [--file=<path>] [text]'); process.exit(1) }
- action = 'clip-push'
- const filePath = flag('file')
- if (filePath) {
- const { readFileSync: rf, statSync: st } = await import('node:fs')
- if (st(filePath).size > 25 * 1024 * 1024) { console.error('✗ file is over 25 MB'); process.exit(1) }
- body = { machine: flag('machine'), file: { name: filePath.split('/').pop() ?? 'file', base64: rf(filePath).toString('base64') } }
- } else {
- let text = args.slice(1).join(' ')
- if (!text) {
- const { execFileSync } = await import('node:child_process')
- for (const [tool, a] of [['wl-paste', ['--no-newline']], ['xclip', ['-selection', 'clipboard', '-o']], ['pbpaste', []]] as Array<[string, string[]]>) {
- try { text = execFileSync(tool, a, { encoding: 'utf8', timeout: 3000 }); break } catch { /* next tool */ }
- }
- }
- if (!text) { console.error('✗ nothing to push: give text, --file, or put something on the clipboard'); process.exit(1) }
- body = { machine: flag('machine'), text }
- }
- break
- }
- case 'capabilities': break
- case 'placement': body = { needsGpu: flags.includes('--gpu'), interactive: flags.includes('--interactive'), minFreeVramMb: num('min-vram') ?? undefined }; break
- case 'subs': {
- // harness subs [--json] [--force] | harness subs set <claude|codex|grok|kimi> <on|off>
- if (args[0] === 'set') {
- if (!args[1] || !['on', 'off'].includes(args[2] ?? '')) { console.error('Usage: harness subs set <claude|codex|grok|kimi> <on|off>'); process.exit(1) }
- action = 'subs-set'; body = { id: args[1], enabled: args[2] }
- } else body = { force: flags.includes('--force') }
- break
- }
- default: action = args[0] ?? ''; body = {}; if (!action) { console.error('Usage: harness fleet <action> [--key=value ...]'); process.exit(1) }
- for (const f of flags) { const m = /^--([a-zA-Z-]+)=(.*)$/.exec(f); if (m) body[m[1]!] = m[2] }
- }
- const { res, json: reply } = await daemonCall('POST', '/api/fleet', { action, ...body })
- if (json) { console.log(JSON.stringify(reply, null, 2)); process.exit(res.ok ? 0 : 1) }
- if (!res.ok || reply.ok === false) { console.error(`✗ ${String(reply.error ?? res.statusText)}`); process.exit(1) }
- const result = reply.result as unknown
- if (action === 'attention' && result && typeof result === 'object') {
- const r = result as { hostname: string; summary: { state: string; count: number }; agents: Array<{ glyph: string; name: string; engine: string; state: string; label: string; detail: string }> }
- if (flags.includes('--kanban')) {
- // Columns in the order a person works them: what needs me, what broke, what finished, what runs.
- const columns: Array<[string, string[]]> = [['NEEDS YOU', ['permission', 'waiting']], ['FAILED', ['failed']], ['DONE, UNREVIEWED', ['done']], ['WORKING', ['working']], ['IDLE', ['idle', 'offline']]]
- for (const [title, states] of columns) {
- const rows = r.agents.filter((a) => states.includes(a.state))
- if (!rows.length) continue
- console.log(`${title} (${rows.length})`)
- for (const a of rows) console.log(` ${a.glyph} ${a.name.padEnd(28)} ${a.engine.padEnd(10)}${a.detail ? ` ${a.detail}` : ''}`)
- }
- return
- }
- console.log(`${r.hostname}: ${r.summary.count} ${r.summary.state}`)
- for (const a of r.agents) console.log(` ${a.glyph} ${a.name.padEnd(28)} ${a.engine.padEnd(10)} ${a.label}${a.detail ? ` ${a.detail}` : ''}`)
- return
- }
- if ((action === 'subs' || action === 'subs-set') && result && typeof result === 'object' && Array.isArray((result as { lines?: unknown }).lines)) {
- for (const line of (result as { lines: string[] }).lines) console.log(line)
- return
- }
- console.log(typeof result === 'string' ? result : JSON.stringify(result, null, 2))
-}
-
/** `harness pair <code>` — send a browser/device pairing code to the running daemon (localhost). */
async function pairCommand(code: string | undefined): Promise<void> {
if (!code) {
@@ -9330,10 +9159,6 @@ switch (cmd) {
case 'reset':
resetCommand().catch(onError)
break
- case 'attention': case 'stop-all': case 'gate': case 'spend': case 'capabilities': case 'placement': case 'subs':
- case 'dispatch': case 'dispatches': case 'clip': case 'fleet':
- fleetCommand(cmd, args, flags).catch(onError)
- break
case 'status':
status().catch(onError)
break
diff --git a/cli/src/fleet/control.spec.ts b/cli/src/fleet/control.spec.ts
deleted file mode 100644
index f1dc4e157..000000000
--- a/cli/src/fleet/control.spec.ts
+++ /dev/null
@@ -1,161 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT), as nixfredWiring.spec.ts.
-
-import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
-import { tmpdir } from 'node:os'
-import { join } from 'node:path'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { FleetControl, type FleetControlDeps, type FleetSessionLike } from './control.js'
-
-vi.mock('../lib/hooks.js', () => ({ installGateHook: () => 'installed', uninstallGateHook: () => 'removed', gateHookInstalled: () => false }))
-
-const session = (agentId: string, extra: Partial<FleetSessionLike> = {}): FleetSessionLike => ({
- agentId, sessionId: `s-${agentId}`, engine: 'claude', active: true, tmuxPane: '%3', cwd: '/tmp/proj', name: agentId, model: 'claude-sonnet', ...extra,
-})
-
-describe('FleetControl', () => {
- let dir: string
- let sent: Array<{ type: string; payload: Record<string, unknown> }>
- let cancelled: string[]
- let errors: string[]
- let sessions: FleetSessionLike[]
- let tokens: number
- let fleet: FleetControl
- let now: number
-
- const deps = (): FleetControlDeps => ({
- dataDir: dir,
- machineId: () => 'm-1',
- machineName: () => 'gus',
- sessions: () => sessions,
- sendLocal: (f) => { sent.push(f) },
- sendError: (_a, _s, m) => { errors.push(m) },
- cancelAgent: async (id) => { cancelled.push(id); return true },
- tokenUsage: () => ({ totalTokens: tokens }),
- hookPort: () => 18473,
- now: () => now,
- })
-
- beforeEach(() => {
- dir = mkdtempSync(join(tmpdir(), 'fleet-'))
- sent = []; cancelled = []; errors = []; tokens = 0; now = Date.UTC(2026, 8, 26, 16, 0)
- sessions = [session('a'), session('b')]
- fleet = new FleetControl(deps())
- })
- afterEach(() => { rmSync(dir, { recursive: true, force: true }) })
-
- it('turns attention changes into a local frame with a summary and glyphs', () => {
- fleet.attention.turnStarted('a', 'fix login')
- fleet.attention.question('b', true, 'Bash: git push')
- const last = sent.at(-1)!
- expect(last.type).toBe('attention')
- const p = last.payload as { hostname: string; summary: { state: string; agentId: string }; agents: Array<{ agentId: string; state: string; glyph: string }> }
- expect(p.hostname).toBe('gus')
- expect(p.summary).toMatchObject({ state: 'permission', agentId: 'b' })
- expect(p.agents.map((a) => `${a.agentId}:${a.state}:${a.glyph}`)).toEqual(['b:permission:!', 'a:working:~'])
- })
-
- it('gate asks on a push, allows a plain command, and marks the agent as needing permission', () => {
- expect(fleet.gate('s-a', 'a', 'Bash', { command: 'git status' }).decision).toBe('allow')
- const v = fleet.gate('s-a', 'a', 'Bash', { command: 'git push origin main' })
- expect(v).toMatchObject({ decision: 'ask', rule: 'git push' })
- expect(fleet.attention.get('a')?.state).toBe('permission')
- })
-
- it('spend brake pauses the pane once the per-agent cap is hit and tells the web', () => {
- fleet.spendSet({ perAgentUsd: 1, perDayUsd: null })
- tokens = 100_000
- expect(fleet.spendCheck(session('a')).action).toBe('run')
- tokens = 400_000 // sonnet: 320k in * 3 + 80k out * 15 per M = 0.96 + 1.2 = 2.16 USD
- const v = fleet.spendCheck(session('a'))
- expect(v.action).toBe('pause')
- expect(errors[0]).toMatch(/Spend brake paused: agent at \$2\.16 of \$1/)
- expect(fleet.attention.get('a')).toMatchObject({ state: 'waiting' })
- expect(JSON.parse(readFileSync(join(dir, 'spend-caps.json'), 'utf8')).perAgentUsd).toBe(1)
- const row = (fleet.attentionPayload().agents as Array<{ agentId: string; spend: { usd: number; fraction: number } | null }>).find((r) => r.agentId === 'a')
- expect(row?.spend).toMatchObject({ usd: 2.16, fraction: 1.5 })
- })
-
- it('leaves the spend brake off until a cap is set', () => {
- tokens = 50_000_000
- expect(fleet.spendCheck(session('a')).action).toBe('run')
- expect(errors).toEqual([])
- })
-
- it('stopAll cancels every active agent but the one kept', async () => {
- const out = await fleet.stopAll('b')
- expect(out.cancelled).toEqual(['a'])
- expect(cancelled).toEqual(['a'])
- expect(fleet.attention.get('a')?.state).toBe('idle')
- })
-
- it('dispatches a job over a relay link and reads the result off the worker text', async () => {
- type F = { type: string; payload: Record<string, unknown> }
- const sentFrames: F[] = []
- const link: { push: ((f: F) => void) | null } = { push: null }
- fleet.setRelayLink(async () => ({
- send: async (f) => {
- sentFrames.push(f)
- if (f.type === 'agent_create') setTimeout(() => link.push?.({ type: 'agent_create_result', payload: { requestId: f.payload.requestId, creationId: f.payload.creationId, agentId: 'remote-1' } }), 5)
- },
- onFrame: (cb) => { link.push = cb; return () => { link.push = null } },
- close: () => {},
- }))
- const rec = await fleet.dispatch('m-2', { machineId: 'm-2', brief: 'add a README badge', repo: '/srv/proj', engine: 'claude', branchName: 'badge' })
- expect(rec.finishedAt).toBeNull()
- await new Promise((r) => setTimeout(r, 40))
- expect(sentFrames[0]?.type).toBe('agent_create')
- expect(String(sentFrames[0]?.payload.prompt)).toContain('DISPATCH_RESULT:')
- link.push?.({ type: 'text_delta', payload: { agentId: 'remote-1', content: 'Done. DISPATCH_RESULT: {"branch":"badge","diffStat":"1 file changed","summary":"README badge added","ok":true}\n' } })
- link.push?.({ type: 'turn_ended', payload: { agentId: 'remote-1' } })
- await new Promise((r) => setTimeout(r, 40))
- const listed = (await fleet.command('dispatches', {}) as { dispatches: Array<typeof rec> }).dispatches
- expect(listed[0]?.agentId).toBe('remote-1')
- expect(listed[0]?.result).toMatchObject({ ok: true, branch: 'badge', summary: 'README badge added' })
- expect(listed[0]?.finishedAt).not.toBeNull()
- })
-
- it('receives a clip push: text to the clipboard, a file into the drop folder without overwriting', async () => {
- const clip: string[] = []
- const other = new FleetControl({ ...deps(), clipWrite: async (t) => { clip.push(t) }, dropDir: join(dir, 'drop') })
- expect(await other.clipReceive({ text: 'hello from vic', from: 'vic' })).toEqual({ ok: true, detail: '14 chars on the clipboard' })
- expect(clip).toEqual(['hello from vic'])
- const b64 = Buffer.from('payload').toString('base64')
- const first = await other.clipReceive({ file: { name: '../evil name.txt', base64: b64 }, from: 'vic' })
- const second = await other.clipReceive({ file: { name: '../evil name.txt', base64: b64 }, from: 'vic' })
- expect(first).toMatchObject({ ok: true, detail: join(dir, 'drop', 'evil name.txt') })
- expect(second).toMatchObject({ ok: true, detail: join(dir, 'drop', 'evil name-1.txt') })
- expect(readFileSync(join(dir, 'drop', 'evil name.txt'), 'utf8')).toBe('payload')
- expect(await other.clipReceive({ from: 'vic' })).toEqual({ ok: false, error: 'CLIP_EMPTY' })
- })
-
- it('pushes text to a linked machine and returns its reply', async () => {
- const link: { push: ((f: { type: string; payload: Record<string, unknown> }) => void) | null } = { push: null }
- const sentFrames: Array<{ type: string; payload: Record<string, unknown> }> = []
- fleet.setRelayLink(async () => ({
- send: async (f) => { sentFrames.push(f); setTimeout(() => link.push?.({ type: 'clip_push_result', payload: { requestId: f.payload.requestId, ok: true, detail: '5 chars on the clipboard' } }), 5) },
- onFrame: (cb) => { link.push = cb; return () => { link.push = null } },
- close: () => {},
- }))
- const out = await fleet.clipPush('m-2', { text: 'hello' })
- expect(out).toMatchObject({ ok: true, detail: '5 chars on the clipboard' })
- expect(sentFrames[0]).toMatchObject({ type: 'clip_push', payload: { text: 'hello', from: 'gus' } })
- })
-
- it('refuses dispatch and clip push before the relay pool exists', async () => {
- await expect(fleet.dispatch('m-2', { machineId: 'm-2', brief: 'x', repo: '/r', engine: 'claude', branchName: 'b' })).rejects.toThrow(/no relay link/)
- await expect(fleet.command('clip-push', { machine: 'm-2' })).rejects.toThrow(/needs machine and text or file/)
- })
-
- it('exposes the local command surface', async () => {
- await expect(fleet.command('nope', {})).rejects.toThrow(/unknown fleet action/)
- const att = await fleet.command('attention', {}) as { agents: unknown[] }
- expect(att.agents).toHaveLength(2)
- const stopped = await fleet.command('stop-all', { except: 'a' }) as { cancelled: string[] }
- expect(stopped.cancelled).toEqual(['b'])
- const status = await fleet.command('gate-status', {}) as { enabled: boolean; rules: number; installed: boolean }
- expect(status).toMatchObject({ enabled: true, installed: false })
- expect(status.rules).toBeGreaterThan(10)
- const caps = await fleet.command('spend-set', { perDayUsd: 42 }) as { caps: { perDayUsd: number; enabled: boolean } }
- expect(caps.caps).toMatchObject({ perDayUsd: 42, enabled: true })
- })
-})
diff --git a/cli/src/fleet/control.ts b/cli/src/fleet/control.ts
deleted file mode 100644
index dc9d28ba1..000000000
--- a/cli/src/fleet/control.ts
+++ /dev/null
@@ -1,436 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT), where it was
-// `nixfredWiring.ts`. Ported here without the device firmware frames, Orca watch mode or Hermes parts.
-
-/**
- * The fleet controls, wired as one object the daemon calls at a handful of points. Everything here is
- * built from pure modules (lib/attention, ...) so the daemon's own files change as little as possible:
- *
- * attention turn/question/cancel taps → `attention` frames to local windows, `GET /api/attention`
- * stop-all cancel every agent turn on this machine (`POST /api/stop-all`, `harness stop-all`)
- * gate tool-start → policy verdict (Claude PreToolUse permissionDecision), `harness gate`
- * spend submit → pause when caps are hit; ledger persisted per day, `harness spend`
- * caps GPU, load, power, heat, lid, toolchains; whether this machine should take a job
- * subs every AI plan's weekly use against an even pace, `harness subs`, `GET /api/subscriptions`
- * dispatch a bounded job to a linked machine over the daemon's own E2EE relay, `harness dispatch`
- * clip clipboard or a file to a linked machine, sealed end to end, `harness clip push`
- * commands the `harness <command>` local API behind `POST /api/fleet`
- */
-import { existsSync, mkdirSync, promises as fsp, readFileSync, renameSync, writeFileSync } from 'node:fs'
-import { join } from 'node:path'
-import { env } from '../config/env.js'
-import { AttentionTracker, summarizeAttention, type AttentionRow } from '../lib/attention.js'
-import { DEFAULT_POLICY, evaluateToolCall, parsePolicy, type ActionPolicy, type GateVerdict } from '../lib/actionPolicy.js'
-import { DEFAULT_CAPS, decideSpend, emptyLedger, parseCaps, recordUsage, type BrakeVerdict, type SpendCaps, type SpendLedger } from '../lib/spendBrake.js'
-import { gateHookInstalled, installGateHook, uninstallGateHook } from '../lib/hooks.js'
-import { decidePlacement, describeCapabilities, readMachineCapabilities, type MachineCapabilities, type PlacementRequest } from '../lib/machineCapabilities.js'
-import { describeSubscriptions, SubscriptionsService, type ProviderId } from './subscriptions/index.js'
-import { nodeSubscriptionsDeps } from './subscriptions/nodeDeps.js'
-import { DISPATCH_RESULT_TYPE, createRemoteAgentBackend, jobPrompt, type DispatchResult, type JobSpec, type MachineLink, type WireFrame } from './remoteOrchestratorBackend.js'
-
-export interface FleetSessionLike {
- agentId: string
- sessionId: string
- engine: string
- active: boolean
- tmuxPane?: string
- cwd?: string
- transcriptPath?: string
- model?: string | null
- name: string
-}
-
-export interface FleetControlDeps {
- dataDir?: string
- machineId: () => string
- machineName: () => string
- sessions: () => FleetSessionLike[]
- /** Push a frame to every local window (desktop). */
- sendLocal: (frame: { type: string; payload: Record<string, unknown> }) => void
- /** Push an error message frame to the web for one agent. */
- sendError: (agentId: string, sessionId: string, message: string) => void
- cancelAgent: (agentId: string, confirmed: boolean) => Promise<boolean>
- tokenUsage: (s: FleetSessionLike) => { totalTokens: number | null } | null
- hookPort: () => number
- now?: () => number
- /** Write to this machine's clipboard (default: wl-copy, xclip or pbcopy, whichever is present). */
- clipWrite?: (text: string) => Promise<void>
- /** Where pushed files land (default ~/Downloads/harness-drop or HARNESS_DROP_DIR). */
- dropDir?: string
-}
-
-/** A live, E2EE-terminated link to one linked machine, as the daemon's relay pool hands it out. */
-export interface RelayLink {
- send(frame: WireFrame): Promise<void>
- onFrame(cb: (frame: WireFrame) => void): () => void
- close(): void
-}
-
-export interface DispatchRecord {
- id: string
- machineId: string
- job: JobSpec
- startedAt: number
- finishedAt: number | null
- agentId: string | null
- result: DispatchResult | null
- error: string | null
-}
-
-const DISPATCH_RESULT_RE = /DISPATCH_RESULT:\s*(\{[\s\S]*\})/
-
-/**
- * Turn a relay link into the MachineLink the dispatcher library expects, and synthesize the
- * `dispatch_result` frame from the worker's own text: the remote agent prints one
- * `DISPATCH_RESULT: {json}` line, which arrives here as text_delta events; at turn_ended for that
- * agent the line is parsed and re-emitted as if the worker had sent a result frame. No new wire type,
- * no worker-side change, and the relay never sees the plaintext.
- */
-export function machineLinkFromRelay(machineId: string, link: RelayLink): MachineLink & { close(): void } {
- const text = new Map<string, string>()
- const listeners = new Set<(f: WireFrame) => void>()
- const emit = (f: WireFrame): void => { for (const cb of listeners) cb(f) }
- const off = link.onFrame((frame) => {
- const p = frame.payload ?? {}
- const agentId = typeof p.agentId === 'string' ? p.agentId : ''
- if (frame.type === 'text_delta' && agentId && typeof p.content === 'string') {
- text.set(agentId, ((text.get(agentId) ?? '') + p.content).slice(-20_000))
- } else if (frame.type === 'turn_ended' && agentId) {
- const m = DISPATCH_RESULT_RE.exec(text.get(agentId) ?? '')
- text.delete(agentId)
- if (m) {
- let parsed: Record<string, unknown> = {}
- try { parsed = JSON.parse(m[1]!) as Record<string, unknown> } catch { parsed = { summary: 'DISPATCH_RESULT line was not valid JSON', ok: false } }
- emit({ type: DISPATCH_RESULT_TYPE, payload: { agentId, ...parsed } })
- }
- }
- emit(frame)
- })
- return {
- machineId,
- send: (frame) => { void link.send(frame) },
- onFrame: (cb) => { listeners.add(cb); return () => { listeners.delete(cb) } },
- close: () => { off(); link.close() },
- }
-}
-
-function readJson<T>(file: string): T | null {
- try { return JSON.parse(readFileSync(file, 'utf8')) as T } catch { return null }
-}
-function writeJson(file: string, value: unknown): void {
- mkdirSync(join(file, '..'), { recursive: true })
- const tmp = `${file}.${process.pid}.tmp`
- writeFileSync(tmp, JSON.stringify(value, null, 2) + '\n')
- renameSync(tmp, file)
-}
-
-export class FleetControl {
- readonly attention: AttentionTracker
- protected readonly dataDir: string
- protected readonly now: () => number
- private policy: ActionPolicy
- private caps: SpendCaps
- private ledger: SpendLedger
- private capsCache: { at: number; value: MachineCapabilities } | null = null
- /** Subscription meters (ported from Burn Bar): weekly used, banked, reset, next plan to use. */
- readonly subs: SubscriptionsService
- private subsTimer: NodeJS.Timeout | null = null
- private relayLink: ((machineId: string) => Promise<RelayLink>) | null = null
- private readonly dispatches = new Map<string, DispatchRecord>()
-
- /** Installed by the daemon once its relay pool exists (it is built after this object). */
- setRelayLink(fn: (machineId: string) => Promise<RelayLink>): void { this.relayLink = fn }
-
- constructor(protected readonly deps: FleetControlDeps) {
- this.now = deps.now ?? Date.now
- this.dataDir = deps.dataDir ?? env.ADAPTER_DATA_DIR
- mkdirSync(this.dataDir, { recursive: true })
- this.attention = new AttentionTracker(this.now)
- this.policy = this.loadPolicy()
- this.caps = this.loadCaps()
- this.ledger = readJson<SpendLedger>(this.file('spend-ledger.json')) ?? emptyLedger(this.now())
- this.attention.onChange(() => this.pushAttention())
- // Subscription meters: one pass a minute (each network provider is asked at most every 4 min), so
- // the attention payload's compact block stays fresh for the bar; HARNESS_SUBS_WATCH=0 turns it off.
- this.subs = new SubscriptionsService(nodeSubscriptionsDeps(this.dataDir))
- if (process.env.HARNESS_SUBS_WATCH !== '0' && !process.env.VITEST) {
- this.subsTimer = setInterval(() => { void this.pollSubscriptions() }, Number(process.env.HARNESS_SUBS_MS) || 60_000)
- this.subsTimer.unref()
- setTimeout(() => { void this.pollSubscriptions() }, 2_000).unref()
- }
- }
-
- /** Collect every enabled subscription. Never throws. */
- async pollSubscriptions(force = false): Promise<unknown> {
- try {
- return await this.subs.collect(force)
- } catch (e) {
- console.log(`[subs] collect failed: ${e instanceof Error ? e.message : String(e)}`)
- return null
- }
- }
-
- protected file(name: string): string { return join(this.dataDir, name) }
-
- // ── attention ───────────────────────────────────────────────────────────────────────────────────
-
- snapshot(): AttentionRow[] { return this.attention.snapshot(this.deps.sessions(), this.deps.machineName()) }
-
- attentionPayload(): Record<string, unknown> {
- // Each agent carries the name of the first policy lane its name matches (planner, publisher ...),
- // so the bar can show the role beside the state.
- const lanes = this.policy.lanes ?? []
- const agents = this.snapshot().map((row) => {
- const spent = this.ledger.agents[row.agentId]
- const cap = this.caps.enabled ? this.caps.perAgentUsd : null
- // Spend rides on the row so the bar can draw it as the ring's outer arc: fraction of the
- // per-agent cap when one is set, else null (no arc).
- const spend = spent ? { usd: Number(spent.usd.toFixed(2)), tokens: spent.input + spent.output, fraction: cap ? Math.min(1.5, spent.usd / cap) : null } : null
- return { ...row, lane: lanes.find((l) => { try { return new RegExp(l.agent, 'i').test(row.name) } catch { return false } })?.name ?? null, spend }
- })
- return { machineId: this.deps.machineId(), hostname: this.deps.machineName(), at: this.now(), summary: summarizeAttention(agents), agents, subscriptions: this.subs?.compact() ?? null }
- }
-
- /** Every local window hears each real transition; the bar widget polls `GET /api/attention` instead. */
- protected pushAttention(): void {
- this.deps.sendLocal({ type: 'attention', payload: this.attentionPayload() })
- }
-
- // ── gate ────────────────────────────────────────────────────────────────────────────────────────
-
- private loadPolicy(): ActionPolicy {
- const raw = readJson<unknown>(this.file('action-policy.json'))
- if (raw === null) return DEFAULT_POLICY
- const parsed = parsePolicy(raw)
- if (parsed.ok) return parsed.policy
- console.error(`[gate] action-policy.json ignored: ${parsed.problems.join('; ')}`)
- return DEFAULT_POLICY
- }
-
- /** A tool call is about to run: classify it. Only reached when `harness gate install` added the hook. */
- gate(sessionId: string, agentId: string, toolName: string, input: unknown): GateVerdict {
- const agentName = this.deps.sessions().find((s) => s.agentId === agentId)?.name ?? ''
- const verdict = evaluateToolCall(this.policy, toolName, input, agentName)
- if (verdict.decision !== 'allow') {
- console.log(`[gate] ${agentId} ${sessionId} ${toolName} → ${verdict.decision} (${verdict.rule})`)
- if (verdict.decision === 'ask') this.attention.question(agentId, true, verdict.reason)
- }
- return verdict
- }
-
- gateStatus(): Record<string, unknown> {
- return { installed: gateHookInstalled(), enabled: this.policy.enabled, rules: this.policy.rules.length, file: this.file('action-policy.json'), fileExists: existsSync(this.file('action-policy.json')) }
- }
-
- gateInit(): string { const f = this.file('action-policy.json'); if (!existsSync(f)) writeJson(f, DEFAULT_POLICY); this.policy = this.loadPolicy(); return f }
-
- // ── spend ───────────────────────────────────────────────────────────────────────────────────────
-
- private loadCaps(): SpendCaps {
- const raw = readJson<unknown>(this.file('spend-caps.json'))
- if (raw === null) return DEFAULT_CAPS
- const parsed = parseCaps(raw)
- if (parsed.ok) return parsed.caps
- console.error(`[spend] spend-caps.json ignored: ${parsed.problems.join('; ')}`)
- return DEFAULT_CAPS
- }
-
- /** Record what this agent has used so far, then decide whether its next turn may run. */
- spendCheck(s: FleetSessionLike): BrakeVerdict {
- const usage = this.deps.tokenUsage(s)
- const total = usage?.totalTokens ?? 0
- // The engines report a total; treat a fifth as output, which is where most of the money goes.
- this.ledger = recordUsage(this.ledger, { agentId: s.agentId, model: s.model ?? null, input: Math.round(total * 0.8), output: Math.round(total * 0.2), now: this.now() })
- writeJson(this.file('spend-ledger.json'), this.ledger)
- const verdict = decideSpend(this.caps, this.ledger, s.agentId)
- if (verdict.action !== 'run') console.log(`[spend] ${s.agentId} ${verdict.action}: ${verdict.reason}`)
- if (verdict.action === 'pause') {
- this.attention.question(s.agentId, false, `spend brake: ${verdict.reason}`)
- this.deps.sendError(s.agentId, s.sessionId, `Spend brake ${verdict.reason}. Raise the cap with "harness spend set" to continue.`)
- }
- return verdict
- }
-
- spendStatus(): Record<string, unknown> {
- return { caps: this.caps, day: this.ledger.day, agents: Object.values(this.ledger.agents).map((a) => ({ agentId: a.agentId, model: a.model, tokens: a.input + a.output, usd: Number(a.usd.toFixed(4)) })) }
- }
-
- spendSet(patch: Partial<SpendCaps>): SpendCaps {
- // Setting a cap is asking for the brake: the default is off (subscription users pay no list price).
- const setsCap = ['perAgentUsd', 'perAgentTokens', 'perDayUsd', 'perDayTokens'].some((k) => typeof (patch as Record<string, unknown>)[k] === 'number')
- const next = { ...this.caps, ...(setsCap && patch.enabled === undefined ? { enabled: true } : {}), ...patch, version: 1 as const }
- const parsed = parseCaps(next)
- if (!parsed.ok) throw new Error(parsed.problems.join('; '))
- this.caps = parsed.caps
- writeJson(this.file('spend-caps.json'), this.caps)
- return this.caps
- }
-
- // ── machine capabilities ───────────────────────────────────────────────────────────────────────
-
- async capabilities(maxAgeMs = 30_000): Promise<MachineCapabilities> {
- if (this.capsCache && this.now() - this.capsCache.at < maxAgeMs) return this.capsCache.value
- const value = await readMachineCapabilities()
- this.capsCache = { at: this.now(), value }
- return value
- }
-
- placement(req: PlacementRequest): Promise<{ ok: boolean; reasons: string[]; caps: string }> {
- return this.capabilities().then((caps) => ({ ...decidePlacement(caps, req), caps: describeCapabilities(caps) }))
- }
-
- // ── clipboard and file drop between paired machines ────────────────────────────────────────────
-
- private async clipWrite(text: string): Promise<void> {
- if (this.deps.clipWrite) return this.deps.clipWrite(text)
- const { spawn } = await import('node:child_process')
- const candidates: Array<[string, string[]]> = process.platform === 'darwin' ? [['pbcopy', []]] : [['wl-copy', []], ['xclip', ['-selection', 'clipboard']]]
- for (const [cmd, args] of candidates) {
- const ok = await new Promise<boolean>((resolve) => {
- const child = spawn(cmd, args, { stdio: ['pipe', 'ignore', 'ignore'] })
- child.on('error', () => resolve(false))
- child.on('exit', (code) => resolve(code === 0))
- child.stdin.end(text)
- })
- if (ok) return
- }
- throw new Error('no clipboard tool (wl-copy, xclip or pbcopy) worked')
- }
-
- /** A paired machine pushed text or a file here. Text goes to the clipboard; a file lands in the drop folder. */
- async clipReceive(push: { text?: string; file?: { name: string; base64: string }; from: string }): Promise<{ ok: true; detail: string } | { ok: false; error: string }> {
- try {
- if (push.file) {
- const dir = this.deps.dropDir ?? process.env.HARNESS_DROP_DIR ?? join(process.env.HOME ?? '/tmp', 'Downloads', 'harness-drop')
- await fsp.mkdir(dir, { recursive: true })
- // Basename only, then a conservative character set, then no leading dots: a name can never
- // climb out of the drop folder or hide as a dotfile.
- const base = push.file.name.split(/[\\/]/).filter(Boolean).pop() ?? 'file'
- const safe = base.replace(/[^\w.@ -]+/g, '_').replace(/^\.+/, '').slice(0, 120) || 'file'
- let target = join(dir, safe)
- for (let i = 1; existsSync(target); i += 1) target = join(dir, safe.replace(/(\.[^.]*)?$/, `-${i}$1`))
- await fsp.writeFile(target, Buffer.from(push.file.base64, 'base64'))
- console.log(`[clip] file from ${push.from} -> ${target}`)
- return { ok: true, detail: target }
- }
- if (push.text !== undefined) {
- await this.clipWrite(push.text)
- console.log(`[clip] text from ${push.from}: ${push.text.length} chars`)
- return { ok: true, detail: `${push.text.length} chars on the clipboard` }
- }
- return { ok: false, error: 'CLIP_EMPTY' }
- } catch (err) {
- return { ok: false, error: err instanceof Error ? err.message : String(err) }
- }
- }
-
- /** Push text or a file to a linked machine over the relay link; waits for its reply. */
- async clipPush(machineId: string, push: { text?: string; file?: { name: string; base64: string } }, timeoutMs = 15_000): Promise<Record<string, unknown>> {
- if (!this.relayLink) throw new Error('clip push is not available: no relay link')
- const link = await this.relayLink(machineId)
- const requestId = `clip-${this.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`
- try {
- const reply = new Promise<Record<string, unknown>>((resolve, reject) => {
- const timer = setTimeout(() => { off(); reject(new Error(`no reply from ${machineId} in ${timeoutMs} ms`)) }, timeoutMs)
- const off = link.onFrame((f) => {
- if (f.type === 'clip_push_result' && f.payload.requestId === requestId) { clearTimeout(timer); off(); resolve(f.payload) }
- })
- })
- await link.send({ type: 'clip_push', payload: { requestId, ...push, from: this.deps.machineName() } })
- const out = await reply
- console.log(`[clip] push to ${machineId}: ${push.file ? push.file.name : `${push.text?.length ?? 0} chars`} -> ${String(out.error ?? out.detail ?? 'ok')}`)
- return out
- } finally { link.close() }
- }
-
- // ── fleet dispatcher ───────────────────────────────────────────────────────────────────────────
-
- /** Hand a bounded job to a linked machine; returns at once with a record that fills in as it runs. */
- async dispatch(machineId: string, job: JobSpec): Promise<DispatchRecord> {
- if (!this.relayLink) throw new Error('dispatch is not available: no relay link')
- const id = `d-${this.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`
- job = { ...job, machineId }
- const record: DispatchRecord = { id, machineId, job, startedAt: this.now(), finishedAt: null, agentId: null, result: null, error: null }
- this.dispatches.set(id, record)
- console.log(`[dispatch] ${id} -> ${machineId}: ${job.brief.slice(0, 120)}`)
- void (async () => {
- let link: (MachineLink & { close(): void }) | null = null
- try {
- link = machineLinkFromRelay(machineId, await this.relayLink!(machineId))
- const backend = createRemoteAgentBackend(link, { now: this.now })
- const created = await backend.create({ engine: job.engine, cwd: job.repo, prompt: jobPrompt(job), branchName: job.branchName, ...(job.dsh ? { dsh: job.dsh } : {}) })
- record.agentId = created.agentId
- record.result = await backend.awaitResult(created.agentId, { timeoutMs: job.timeoutMs ?? 60 * 60 * 1000 })
- } catch (err) {
- record.error = err instanceof Error ? err.message : String(err)
- } finally {
- record.finishedAt = this.now()
- link?.close()
- console.log(`[dispatch] ${id} done: ${(record.error ?? record.result?.summary ?? '').slice(0, 300)}`)
- void fsp.appendFile(this.file('dispatches.jsonl'), JSON.stringify(record) + '\n').catch(() => {})
- }
- })()
- return record
- }
-
- // ── panic stop ─────────────────────────────────────────────────────────────────────────────────
-
- async stopAll(exceptAgentId: string | null): Promise<{ cancelled: string[] }> {
- const cancelled: string[] = []
- for (const s of this.deps.sessions()) {
- if (!s.active || s.agentId === exceptAgentId) continue
- try { if (await this.deps.cancelAgent(s.agentId, true)) cancelled.push(s.agentId) } catch { /* next */ }
- this.attention.cancelled(s.agentId)
- }
- console.log(`[fleet] panic stop: cancelled ${cancelled.length} agent(s), kept ${exceptAgentId ?? 'none'}`)
- return { cancelled }
- }
-
- // ── the local command surface (`POST /api/fleet`) ──────────────────────────────────────────────
-
- async command(action: string, args: Record<string, unknown>): Promise<unknown> {
- const str = (k: string): string => (typeof args[k] === 'string' ? args[k] as string : '')
- switch (action) {
- case 'attention': return this.attentionPayload()
- case 'stop-all': return this.stopAll(str('except') || null)
- case 'gate-status': return this.gateStatus()
- case 'gate-init': return { file: this.gateInit() }
- case 'gate-install': return { result: installGateHook(this.deps.hookPort()), ...this.gateStatus() }
- case 'gate-uninstall': return { result: uninstallGateHook(), ...this.gateStatus() }
- case 'gate-reload': this.policy = this.loadPolicy(); return this.gateStatus()
- case 'spend-status': return this.spendStatus()
- case 'spend-set': {
- const patch: Partial<SpendCaps> = {}
- for (const k of ['perAgentUsd', 'perAgentTokens', 'perDayUsd', 'perDayTokens', 'warnAt'] as const) {
- if (args[k] === null) patch[k] = null as never
- else if (typeof args[k] === 'number') patch[k] = args[k] as never
- }
- if (typeof args.enabled === 'boolean') patch.enabled = args.enabled
- return { caps: this.spendSet(patch) }
- }
- case 'capabilities': return { ...(await this.capabilities(0)), line: describeCapabilities(await this.capabilities()) }
- case 'placement': return this.placement(args as PlacementRequest)
- case 'subs': { const r = await this.subs.collect(args.force === true || args.force === 'true'); return { ...r, lines: describeSubscriptions(r) } }
- case 'dispatch': {
- const job: JobSpec = { machineId: str('machine'), brief: str('brief'), repo: str('repo'), engine: str('engine') || 'claude', branchName: str('branch') || `dispatch/${this.now().toString(36)}`, ...(str('dsh') ? { dsh: str('dsh') } : {}) }
- if (!job.brief || !job.repo || !str('machine')) throw new Error('dispatch needs machine, repo and brief')
- return this.dispatch(str('machine'), job)
- }
- case 'dispatches': return { dispatches: [...this.dispatches.values()].sort((a, b) => b.startedAt - a.startedAt) }
- case 'clip-push': {
- const file = args.file && typeof args.file === 'object' ? args.file as { name: string; base64: string } : undefined
- const text = typeof args.text === 'string' ? args.text : undefined
- if (!str('machine') || (!file && text === undefined)) throw new Error('clip-push needs machine and text or file')
- return this.clipPush(str('machine'), { ...(text !== undefined ? { text } : {}), ...(file ? { file } : {}) })
- }
- case 'subs-set': {
- const on = args.enabled === true || args.enabled === 'on' || args.enabled === 'true'
- await this.subs.setEnabled(str('id') as ProviderId, on)
- const r = await this.subs.collect(true)
- return { ...r, lines: describeSubscriptions(r) }
- }
- default: throw new Error(`unknown fleet action: ${action}`)
- }
- }
-}
-
-export type { AttentionRow, GateVerdict, BrakeVerdict }
diff --git a/cli/src/fleet/remoteOrchestratorBackend.spec.ts b/cli/src/fleet/remoteOrchestratorBackend.spec.ts
deleted file mode 100644
index cf32cfe46..000000000
--- a/cli/src/fleet/remoteOrchestratorBackend.spec.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-import { describe, expect, it, vi } from 'vitest'
-import type { MachineCapabilities } from '../lib/machineCapabilities.js'
-import { DISPATCH_RESULT_TYPE, createRemoteAgentBackend, dispatchJob, jobPrompt, placementFilter, type MachineLink, type WireFrame } from './remoteOrchestratorBackend.js'
-
-function fakeLink(machineId = 'mind') {
- const sent: WireFrame[] = []
- const cbs = new Set<(f: WireFrame) => void>()
- const link: MachineLink = {
- machineId,
- send: (f) => { sent.push(f) },
- onFrame: (cb) => { cbs.add(cb); return () => { cbs.delete(cb) } },
- }
- return { link, sent, emit: (f: WireFrame) => { for (const cb of cbs) cb(f) } }
-}
-
-describe('createRemoteAgentBackend', () => {
- it('creates an agent over agent_create and correlates the result by requestId', async () => {
- const { link, sent, emit } = fakeLink()
- const b = createRemoteAgentBackend(link, { requestId: (() => { let i = 0; return () => `r${++i}` })() })
- const p = b.create({ engine: 'claude', cwd: '/w', prompt: 'do it', branchName: 'feat/x' })
- expect(sent[0]).toMatchObject({ type: 'agent_create', payload: { requestId: 'r2', creationId: 'r1', engine: 'claude', cwd: '/w', prompt: 'do it', branchName: 'feat/x' } })
- emit({ type: 'agent_create_result', payload: { requestId: 'r2', agentId: 'ag-9' } })
- await expect(p).resolves.toEqual({ agentId: 'ag-9' })
- await b.send('ag-9', 'more')
- await b.cancel('ag-9')
- expect(sent.slice(1)).toEqual([{ type: 'message', payload: { agentId: 'ag-9', content: 'more' } }, { type: 'cancel', payload: { agentId: 'ag-9' } }])
- b.close()
- })
-
- it('accepts a result echoing only creationId, and surfaces an error payload', async () => {
- const { link, emit } = fakeLink()
- const b = createRemoteAgentBackend(link, { requestId: (() => { let i = 0; return () => `r${++i}` })() })
- const p = b.create({ engine: 'codex', cwd: '/w', prompt: 'x' })
- emit({ type: 'agent_create_result', payload: { creationId: 'r1', id: 'ag-1' } })
- await expect(p).resolves.toEqual({ agentId: 'ag-1' })
- const p2 = b.create({ engine: 'codex', cwd: '/w', prompt: 'x' })
- emit({ type: 'agent_create_result', payload: { requestId: 'r4', error: 'ENGINE_MISSING' } })
- await expect(p2).rejects.toThrow('ENGINE_MISSING')
- b.close()
- })
-
- it('times out a create that never answers', async () => {
- vi.useFakeTimers()
- try {
- const { link } = fakeLink()
- const b = createRemoteAgentBackend(link, { timeoutMs: 50 })
- const p = b.create({ engine: 'claude', cwd: '/w', prompt: 'x' })
- const assertion = expect(p).rejects.toThrow('timed out after 50 ms')
- await vi.advanceTimersByTimeAsync(60)
- await assertion
- b.close()
- } finally { vi.useRealTimers() }
- })
-
- it('resolves awaitResult from a dispatch_result frame, before or after the wait starts', async () => {
- const { link, emit } = fakeLink()
- const b = createRemoteAgentBackend(link)
- emit({ type: DISPATCH_RESULT_TYPE, payload: { agentId: 'early', summary: 'done', branch: 'b', diffStat: '1 file' } })
- await expect(b.awaitResult('early')).resolves.toEqual({ agentId: 'early', summary: 'done', branch: 'b', diffStat: '1 file', ok: true })
- const late = b.awaitResult('late', { timeoutMs: 1000 })
- emit({ type: DISPATCH_RESULT_TYPE, payload: { agentId: 'late', summary: 'failed', ok: false } })
- await expect(late).resolves.toMatchObject({ ok: false, summary: 'failed' })
- b.close()
- })
-
- it('reads status through session_get and returns null on failure', async () => {
- const { link, emit, sent } = fakeLink()
- const b = createRemoteAgentBackend(link, { requestId: () => 'q1', timeoutMs: 20 })
- const p = b.agent('ag-1')
- expect(sent[0]).toEqual({ type: 'session_get', payload: { requestId: 'q1', agentId: 'ag-1' } })
- emit({ type: 'session_get_result', payload: { requestId: 'q1', status: 'active', summary: 's' } })
- await expect(p).resolves.toEqual({ status: 'active', summary: 's' })
- await expect(b.agent('ag-2')).resolves.toBeNull()
- b.close()
- })
-
- it('dispatchJob composes create, brief and result', async () => {
- const { link, sent, emit } = fakeLink('blu')
- const b = createRemoteAgentBackend(link, { requestId: () => 'k' })
- const p = dispatchJob(b, { brief: 'Add ring animation', repo: '/w/pulse', branchName: 'feat/rings', engine: 'claude', machineId: 'blu', timeoutMs: 5000 })
- expect(sent[0]!.payload.prompt).toBe(jobPrompt({ brief: 'Add ring animation', repo: '/w/pulse', branchName: 'feat/rings', engine: 'claude', machineId: 'blu' }))
- expect(String(sent[0]!.payload.prompt)).toContain('DISPATCH_RESULT:')
- emit({ type: 'agent_create_result', payload: { requestId: 'k', agentId: 'w1' } })
- emit({ type: DISPATCH_RESULT_TYPE, payload: { agentId: 'w1', summary: 'rings added', branch: 'feat/rings' } })
- await expect(p).resolves.toMatchObject({ agentId: 'w1', branch: 'feat/rings' })
- b.close()
- })
-})
-
-const caps = (over: Partial<MachineCapabilities> & { free?: number; util?: number }): MachineCapabilities => ({
- at: 0, hostname: 'h', cpu: { cores: 8, load1: 1, load5: 1 },
- gpus: over.free === undefined ? [] : [{ name: 'g', vramTotalMb: 12000, vramUsedMb: 12000 - over.free, utilizationPct: over.util ?? 0 }],
- power: { onAc: true, batteryPct: null }, thermal: { maxC: 50 }, lid: 'unknown', toolchains: {}, ...over,
-})
-
-describe('placementFilter', () => {
- it('drops machines that refuse the job and orders the rest by free VRAM then load', () => {
- const out = placementFilter([
- { machineId: 'vic', caps: caps({ free: 4000 }) },
- { machineId: 'gus', caps: caps({ free: 10000, util: 90 }) },
- { machineId: 'mind', caps: caps({ free: 20000 }) },
- { machineId: 'blu', caps: caps({}) },
- ], { needsGpu: true })
- expect(out.map((c) => c.machineId)).toEqual(['mind', 'vic'])
- expect(out[0]!.reasons).toEqual([])
- })
-})
diff --git a/cli/src/fleet/remoteOrchestratorBackend.ts b/cli/src/fleet/remoteOrchestratorBackend.ts
deleted file mode 100644
index 931fabed5..000000000
--- a/cli/src/fleet/remoteOrchestratorBackend.ts
+++ /dev/null
@@ -1,183 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-/**
- * The fleet dispatcher's building block: an orchestrator-shaped backend (create, send, cancel,
- * agent) that runs on ANOTHER linked machine over the existing E2EE relay session. It speaks the
- * wire types the daemon already has (`agent_create`, `message`, `cancel`, `session_get`) plus one
- * new one the worker side emits when a dispatched job finishes: `dispatch_result`.
- *
- * `MachineLink` is the seam: the daemon wires it to a RemoteRelayPool session; tests script it.
- */
-import { decidePlacement, type MachineCapabilities, type PlacementRequest } from '../lib/machineCapabilities.js'
-
-export interface WireFrame { type: string; payload: Record<string, unknown> }
-
-export interface MachineLink {
- machineId: string
- send(frame: WireFrame): void
- onFrame(cb: (frame: WireFrame) => void): () => void
-}
-
-export interface RemoteCreateInput {
- engine: string
- cwd: string
- prompt: string
- dsh?: string
- branchName?: string
- creationId?: string
-}
-
-export interface DispatchResult {
- agentId: string
- branch?: string
- diffStat?: string
- summary: string
- ok: boolean
-}
-
-export interface RemoteAgentBackend {
- machineId: string
- create(input: RemoteCreateInput): Promise<{ agentId: string }>
- send(agentId: string, text: string): Promise<void>
- cancel(agentId: string): Promise<void>
- agent(agentId: string): Promise<{ status: string; summary?: string } | null>
- awaitResult(agentId: string, opts?: { timeoutMs?: number }): Promise<DispatchResult>
- close(): void
-}
-
-export interface BackendOptions {
- timeoutMs?: number
- requestId?: () => string
- now?: () => number
-}
-
-/** The worker side emits this when a dispatched agent reports done. Exported so the daemon reuses it. */
-export const DISPATCH_RESULT_TYPE = 'dispatch_result'
-
-class Timeout extends Error { constructor(what: string, ms: number) { super(`${what} timed out after ${ms} ms`) } }
-
-export function createRemoteAgentBackend(link: MachineLink, opts: BackendOptions = {}): RemoteAgentBackend {
- const timeoutMs = opts.timeoutMs ?? 30_000
- let seq = 0
- const nextId = opts.requestId ?? (() => `rq-${link.machineId}-${++seq}`)
- const pending = new Map<string, { resolve: (p: Record<string, unknown>) => void; reject: (e: Error) => void; timer: ReturnType<typeof setTimeout> }>()
- const results = new Map<string, DispatchResult>()
- const waiters = new Map<string, Array<(r: DispatchResult) => void>>()
-
- const off = link.onFrame((frame) => {
- if (frame.type === DISPATCH_RESULT_TYPE) {
- const p = frame.payload
- const agentId = String(p.agentId ?? '')
- if (!agentId) return
- const r: DispatchResult = {
- agentId, summary: String(p.summary ?? ''), ok: p.ok !== false,
- ...(typeof p.branch === 'string' ? { branch: p.branch } : {}),
- ...(typeof p.diffStat === 'string' ? { diffStat: p.diffStat } : {}),
- }
- results.set(agentId, r)
- for (const w of waiters.get(agentId) ?? []) w(r)
- waiters.delete(agentId)
- return
- }
- if (!frame.type.endsWith('_result')) return
- const rid = frame.payload.requestId
- const key = typeof rid === 'string' ? rid : typeof frame.payload.creationId === 'string' ? frame.payload.creationId : ''
- const p = key ? pending.get(key) : undefined
- if (!p) return
- pending.delete(key)
- clearTimeout(p.timer)
- if (typeof frame.payload.error === 'string') p.reject(new Error(`${frame.type}: ${frame.payload.error}`))
- else p.resolve(frame.payload)
- })
-
- const rpc = (type: string, payload: Record<string, unknown>, key: string): Promise<Record<string, unknown>> =>
- new Promise((resolve, reject) => {
- const timer = setTimeout(() => { pending.delete(key); reject(new Timeout(type, timeoutMs)) }, timeoutMs)
- pending.set(key, { resolve, reject, timer })
- link.send({ type, payload })
- })
-
- return {
- machineId: link.machineId,
- async create(input) {
- const creationId = input.creationId ?? nextId()
- const requestId = nextId()
- const payload: Record<string, unknown> = { requestId, creationId, engine: input.engine, cwd: input.cwd, prompt: input.prompt, ...(input.dsh ? { dsh: input.dsh } : {}), ...(input.branchName ? { branchName: input.branchName } : {}) }
- // Correlate by requestId first; a daemon that echoes only creationId still matches.
- const p = rpc('agent_create', payload, requestId)
- pending.set(creationId, pending.get(requestId)!)
- const res = await p
- pending.delete(creationId)
- const agentId = typeof res.agentId === 'string' ? res.agentId : typeof res.id === 'string' ? res.id : ''
- if (!agentId) throw new Error('agent_create_result carried no agentId')
- return { agentId }
- },
- async send(agentId, text) { link.send({ type: 'message', payload: { agentId, content: text } }) },
- async cancel(agentId) { link.send({ type: 'cancel', payload: { agentId } }) },
- async agent(agentId) {
- const requestId = nextId()
- try {
- const res = await rpc('session_get', { requestId, agentId }, requestId)
- const status = typeof res.status === 'string' ? res.status : 'unknown'
- return { status, ...(typeof res.summary === 'string' ? { summary: res.summary } : {}) }
- } catch { return null }
- },
- awaitResult(agentId, o = {}) {
- const done = results.get(agentId)
- if (done) return Promise.resolve(done)
- const ms = o.timeoutMs ?? timeoutMs
- return new Promise((resolve, reject) => {
- const timer = setTimeout(() => {
- waiters.set(agentId, (waiters.get(agentId) ?? []).filter((w) => w !== onResult))
- reject(new Timeout(`dispatch_result for ${agentId}`, ms))
- }, ms)
- const onResult = (r: DispatchResult) => { clearTimeout(timer); resolve(r) }
- waiters.set(agentId, [...(waiters.get(agentId) ?? []), onResult])
- })
- },
- close() {
- off()
- for (const p of pending.values()) { clearTimeout(p.timer); p.reject(new Error('link closed')) }
- pending.clear()
- },
- }
-}
-
-export interface JobSpec {
- brief: string
- repo: string
- branchName: string
- engine: string
- machineId: string
- dsh?: string
- timeoutMs?: number
-}
-
-/** The worker-side brief: what the remote agent is told, and how it is told to report back. */
-export function jobPrompt(job: JobSpec): string {
- return [
- `You are a dispatched worker on machine ${job.machineId}. Work only inside this worktree on branch ${job.branchName}.`,
- '', '## Brief', job.brief, '',
- '## When done',
- 'Commit your work on this branch. Then print exactly one line starting with DISPATCH_RESULT: followed by JSON',
- '{"summary": "<one paragraph: what changed, what is left, open questions>"}. Do not push.',
- ].join('\n')
-}
-
-export async function dispatchJob(backend: RemoteAgentBackend, job: JobSpec): Promise<DispatchResult> {
- const { agentId } = await backend.create({ engine: job.engine, cwd: job.repo, prompt: jobPrompt(job), branchName: job.branchName, ...(job.dsh ? { dsh: job.dsh } : {}) })
- return backend.awaitResult(agentId, { timeoutMs: job.timeoutMs ?? 60 * 60 * 1000 })
-}
-
-export interface Candidate { machineId: string; caps: MachineCapabilities }
-
-/** Machines that can take the job, best first (most free VRAM, then lowest load). */
-export function placementFilter(candidates: Candidate[], req: PlacementRequest): Array<Candidate & { reasons: string[] }> {
- const ok = candidates
- .map((c) => ({ ...c, ...decidePlacement(c.caps, req) }))
- .filter((c) => c.ok)
- .map(({ ok: _ok, ...c }) => c)
- const freeVram = (c: Candidate) => Math.max(0, ...c.caps.gpus.map((g) => g.vramTotalMb - g.vramUsedMb))
- const loadPerCore = (c: Candidate) => (c.caps.cpu.cores ? c.caps.cpu.load1 / c.caps.cpu.cores : 0)
- return ok.sort((a, b) => freeVram(b) - freeVram(a) || loadPerCore(a) - loadPerCore(b))
-}
diff --git a/cli/src/fleet/subscriptions/index.spec.ts b/cli/src/fleet/subscriptions/index.spec.ts
deleted file mode 100644
index 2b8fb80bc..000000000
--- a/cli/src/fleet/subscriptions/index.spec.ts
+++ /dev/null
@@ -1,122 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-import { describe, expect, it } from 'vitest'
-import { describeSubscriptions, SubscriptionsService, type SubscriptionsDeps } from './index.js'
-import type { ProviderReading } from './providers.js'
-
-const HOUR = 3_600_000
-const DAY = 86_400_000
-const NOW = Date.UTC(2026, 8, 30, 12)
-
-function reading(id: ProviderReading['id'], over: Partial<ProviderReading> = {}): ProviderReading {
- return { id, name: id[0]!.toUpperCase() + id.slice(1), state: 'ok', plan: '', limits: [], snapshot: false, measuredAt: NOW, status: '', help: '', ...over }
-}
-/** A week that is `gone` of the way through with `used` spent. */
-const week = (used: number, gone: number) => ({ label: 'Weekly (7-day)', percent: used, resetsAt: new Date(NOW + 7 * DAY * (1 - gone)).toISOString() })
-
-function service(readings: Partial<Record<ProviderReading['id'], ProviderReading>>, files: Record<string, string> = {}) {
- let now = NOW
- const deps: SubscriptionsDeps = {
- dataDir: '/d',
- now: () => now,
- readers: {
- claude: async () => readings.claude ?? reading('claude', { state: 'not-detected' }),
- codex: async () => readings.codex ?? reading('codex', { state: 'not-detected' }),
- grok: async () => readings.grok ?? reading('grok', { state: 'not-detected' }),
- kimi: async () => readings.kimi ?? reading('kimi', { state: 'not-detected' }),
- },
- readFile: async (p) => files[p] ?? null,
- writeFile: async (p, d) => { files[p] = d },
- }
- return { svc: new SubscriptionsService(deps), files, tick: (ms: number) => { now += ms } }
-}
-
-describe('the subscriptions payload', () => {
- it('lists all four providers, not-detected ones included, and never the local GPU', async () => {
- const { svc } = service({})
- const p = await svc.collect()
- expect(p.subs.map((s) => s.id)).toEqual(['claude', 'codex', 'grok', 'kimi'])
- expect(p.subs.every((s) => s.state === 'not-detected' && s.primary === null)).toBe(true)
- expect(p.guide.pick).toBe('')
- expect(JSON.stringify(p)).not.toMatch(/"local"/)
- })
-
- it('weekly used, signed banked, reset and pace sentence on the card', async () => {
- const { svc } = service({ claude: reading('claude', { plan: 'Max 20x', limits: [{ label: 'Session (5-hour)', percent: 0.07, resetsAt: new Date(NOW + HOUR).toISOString() }, week(0.3, 0.5)] }) })
- const c = (await svc.collect()).subs[0]!
- expect(c.primary!.label).toBe('Weekly (7-day)')
- expect(c.primary!.used).toBeCloseTo(0.3, 6)
- expect(c.primary!.bankedSigned).toBeCloseTo(0.2, 3)
- expect(c.primary!.banked).toBeCloseTo(0.2, 3)
- expect(c.primary!.tone).toBe('banked')
- expect(c.primary!.sentence).toMatch(/20% banked/)
- expect(c.primary!.resetsInMs).toBeCloseTo(3.5 * DAY, -4)
- expect(c.windows).toHaveLength(2)
- })
-
- it('over pace: negative banked, amber or red, with a come-back timer', async () => {
- const { svc } = service({ codex: reading('codex', { limits: [week(0.6, 0.3)] }) })
- const c = (await svc.collect()).subs[1]!.primary!
- expect(c.bankedSigned).toBeCloseTo(-0.3, 3)
- expect(c.tone).toBe('red')
- expect(c.comeBackMs).toBeGreaterThan(0)
- expect(c.sentence).toMatch(/over pace/i)
- expect(c.sentence).toMatch(/back on pace in/)
- })
-
- it('a month is judged when there is no week (Kimi)', async () => {
- const { svc } = service({ kimi: reading('kimi', { limits: [{ label: 'Session (5-hour)', percent: 0.09, resetsAt: new Date(NOW + HOUR).toISOString() }, { label: 'Monthly (total)', percent: 0.07, resetsAt: new Date(NOW + 19 * DAY).toISOString() }] }) })
- expect((await svc.collect()).subs[3]!.primary!.label).toBe('Monthly (total)')
- })
-
- it('names the next sub when there is a real choice', async () => {
- const { svc } = service({ claude: reading('claude', { limits: [week(0.6, 0.3)] }), grok: reading('grok', { snapshot: true, limits: [week(0.02, 0.51)] }) })
- const p = await svc.collect()
- expect(p.guide.pick).toBe('grok')
- expect(p.guide.verdict).toMatch(/Grok/)
- expect(p.subs.find((s) => s.id === 'grok')!.isPick).toBe(true)
- })
-
- it('a disabled sub is left out of the verdict and never read', async () => {
- let read = 0
- const { svc } = service({ grok: reading('grok', { limits: [week(0.02, 0.51)] }) })
- const orig = (svc as unknown as { deps: SubscriptionsDeps }).deps.readers.grok
- ;(svc as unknown as { deps: SubscriptionsDeps }).deps.readers.grok = async (d) => { read++; return orig(d) }
- await svc.setEnabled('grok', false)
- const p = await svc.collect()
- expect(read).toBe(0)
- expect(p.subs.find((s) => s.id === 'grok')!.state).toBe('disabled')
- expect(p.settings.enabled.grok).toBe(false)
- })
-
- it('persists settings and rate samples in its own data dir', async () => {
- const { svc, files, tick } = service({ claude: reading('claude', { limits: [week(0.3, 0.5)] }) })
- await svc.setEnabled('kimi', false)
- await svc.collect()
- tick(10 * 60_000)
- await svc.collect()
- expect(JSON.parse(files['/d/subscriptions.json']!).enabled.kimi).toBe(false)
- expect(files['/d/subscription-samples.jsonl']!.trim().split('\n').length).toBe(2)
- })
-
- it('rejects an unknown provider id', async () => {
- const { svc } = service({})
- await expect(svc.setEnabled('local' as never, true)).rejects.toThrow(/unknown/)
- })
-
- it('describes itself in plain lines for `harness subs`', async () => {
- const { svc } = service({ claude: reading('claude', { plan: 'Max 20x', limits: [week(0.3, 0.5)] }) })
- const lines = describeSubscriptions(await svc.collect())
- expect(lines[0]).toMatch(/Claude/)
- expect(lines.join('\n')).toMatch(/30% used/)
- expect(lines.join('\n')).toMatch(/Codex\s+not detected/)
- })
-
- it('a compact summary rides on the attention payload', async () => {
- const { svc } = service({ claude: reading('claude', { limits: [week(0.3, 0.5)] }) })
- await svc.collect()
- const c = svc.compact()!
- expect(c.subs[0]).toMatchObject({ id: 'claude', tone: 'banked' })
- expect(c.subs).toHaveLength(1)
- })
-})
diff --git a/cli/src/fleet/subscriptions/index.ts b/cli/src/fleet/subscriptions/index.ts
deleted file mode 100644
index 4ee4c2660..000000000
--- a/cli/src/fleet/subscriptions/index.ts
+++ /dev/null
@@ -1,299 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-/**
- * Subscriptions: every AI plan on this machine on one screen. Weekly percent used, percent banked
- * against an even pace, the reset, a come-back timer when over pace, and which plan to use next.
- *
- * The math and the provider sources are ported from Burn Bar (https://github.com/nixfred/burnbar, by
- * nixfred, MIT). Burn Bar does not have to be installed: nothing here calls it or reads its files.
- *
- * Served by the daemon as `GET /api/subscriptions`, `POST /api/fleet {action: "subs"}`, a compact
- * block on the attention payload, and `harness subs [--json]`.
- * State lives in the daemon's data dir: `subscriptions.json` (which plans are switched on) and
- * `subscription-samples.jsonl` (the percentages over time, which is what a burn rate is made of).
- */
-import { guidePick, paceFor, paceLive, parseIsoMs, spanWords, windowId, type Guide, type LimitRow, type Pace, type Sample } from './pace.js'
-import { PROVIDERS, READERS, type ProviderDeps, type ProviderId, type ProviderReading } from './providers.js'
-
-export * from './pace.js'
-export * from './providers.js'
-
-const SAMPLE_MAX_AGE_MS = 40 * 86_400_000
-const SAMPLE_MIN_GAP_MS = 5 * 60_000
-/** Network providers are asked at most this often; Anthropic rate-limits eager pollers. */
-const NETWORK_TTL_MS = 4 * 60_000
-const LOCAL_TTL_MS = 30_000
-/** A snapshot has to be this far ahead before it is advice (Burn Bar's snapshot margin). */
-const SNAPSHOT_MIN_BANK = 0.1
-
-export type CardState = ProviderReading['state'] | 'disabled'
-/** banked = green; on-pace = neutral; amber = over pace; red = well over or spent. */
-export type Tone = 'banked' | 'on-pace' | 'amber' | 'red' | 'unknown'
-
-export interface PrimaryWindow {
- label: string
- used: number
- resetsAt: string
- resetsInMs: number
- windowMs: number
- elapsed: number
- /** elapsed - used: positive = banked, negative = ahead of the clock (over pace). */
- bankedSigned: number
- banked: number
- bankedMs: number
- behind: number
- over: boolean
- spent: boolean
- comeBackAt: number
- comeBackMs: number
- room: number
- ratio: number
- tone: Tone
- sentence: string
- pace: Pace
-}
-
-export interface SubscriptionCard {
- id: ProviderId
- name: string
- state: CardState
- enabled: boolean
- plan: string
- snapshot: boolean
- measuredAt: number
- status: string
- help: string
- primary: PrimaryWindow | null
- windows: LimitRow[]
- /** A short window (5-hour session) is nearly full: this plan would stop you right now. */
- blocked: boolean
- isPick: boolean
-}
-
-export interface SubscriptionsPayload {
- at: number
- subs: SubscriptionCard[]
- guide: Guide & { verdict: string }
- settings: SubscriptionSettings
-}
-
-export interface SubscriptionSettings { enabled: Record<ProviderId, boolean> }
-
-export interface SubscriptionsDeps {
- dataDir: string
- now(): number
- readers: Record<ProviderId, (deps: ProviderDeps) => Promise<ProviderReading>>
- providerDeps?: ProviderDeps
- readFile(path: string): Promise<string | null>
- writeFile(path: string, data: string): Promise<void>
-}
-
-const SETTINGS_FILE = 'subscriptions.json'
-const SAMPLES_FILE = 'subscription-samples.jsonl'
-const pct = (n: number): string => `${Math.round(n * 100)}%`
-
-/** The window a plan is judged by: weekly, else the monthly pool, else the first non-session window. */
-export function primaryLimit(rows: LimitRow[]): LimitRow | null {
- const session = (l: string) => /session|5-hour/i.test(l)
- return rows.find((r) => /^weekly/i.test(r.label)) ?? rows.find((r) => /monthly \(total\)/i.test(r.label)) ?? rows.find((r) => !session(r.label)) ?? null
-}
-
-function toneOf(live: ReturnType<typeof paceLive>): Tone {
- if (!live) return 'unknown'
- if (live.spent) return 'red'
- if (live.over) return live.elapsed > 0 && live.used / live.elapsed > 1.25 ? 'red' : 'amber'
- if (live.banked >= 0.005) return 'banked'
- return 'on-pace'
-}
-
-function sentenceOf(live: NonNullable<ReturnType<typeof paceLive>>): string {
- const reset = `Resets in ${spanWords(live.leftMs)}.`
- if (live.spent) return `Spent. Back at the reset in ${spanWords(live.leftMs)}.`
- if (live.over) return `${pct(live.behind)} over pace. Stop now and you are back on pace in ${spanWords(live.comeBackMs)}. ${reset}`
- if (live.banked >= 0.005) return `${pct(live.banked)} banked, about ${spanWords(live.bankedMs)} of even pace in hand. ${reset}`
- return `On pace. ${reset}`
-}
-
-export class SubscriptionsService {
- private settings: SubscriptionSettings | null = null
- private samples: Map<string, Sample[]> | null = null
- private cache = new Map<ProviderId, { at: number; reading: ProviderReading }>()
- private previousPick = ''
- private last: SubscriptionsPayload | null = null
-
- constructor(private readonly deps: SubscriptionsDeps) {}
-
- private path(name: string): string { return `${this.deps.dataDir.replace(/\/+$/, '')}/${name}` }
-
- async getSettings(): Promise<SubscriptionSettings> {
- if (this.settings) return this.settings
- const enabled = Object.fromEntries(PROVIDERS.map((p) => [p.id, true])) as Record<ProviderId, boolean>
- try {
- const raw = JSON.parse((await this.deps.readFile(this.path(SETTINGS_FILE))) ?? '{}') as { enabled?: Record<string, unknown> }
- for (const p of PROVIDERS) if (typeof raw.enabled?.[p.id] === 'boolean') enabled[p.id] = raw.enabled[p.id] as boolean
- } catch { /* a bad file keeps the defaults */ }
- this.settings = { enabled }
- return this.settings
- }
-
- async setEnabled(id: ProviderId, on: boolean): Promise<SubscriptionSettings> {
- if (!PROVIDERS.some((p) => p.id === id)) throw new Error(`unknown subscription: ${String(id)}`)
- const s = await this.getSettings()
- s.enabled[id] = on
- await this.deps.writeFile(this.path(SETTINGS_FILE), JSON.stringify(s, null, 2))
- return s
- }
-
- private async loadSamples(): Promise<Map<string, Sample[]>> {
- if (this.samples) return this.samples
- const out = new Map<string, Sample[]>()
- const floor = this.deps.now() - SAMPLE_MAX_AGE_MS
- for (const line of ((await this.deps.readFile(this.path(SAMPLES_FILE))) ?? '').split('\n')) {
- if (!line.trim()) continue
- try {
- const r = JSON.parse(line) as { ts: number; key: string; pct: number; resets: number }
- if (!(r.ts >= floor) || !(r.pct >= 0 && r.pct <= 1) || typeof r.key !== 'string') continue
- const list = out.get(r.key) ?? []
- list.push([Number(r.ts), Number(r.pct), Number(r.resets) || 0])
- out.set(r.key, list)
- } catch { /* a malformed line is skipped, never fatal */ }
- }
- for (const v of out.values()) v.sort((a, b) => a[0] - b[0])
- this.samples = out
- return out
- }
-
- private async saveSamples(): Promise<void> {
- if (!this.samples) return
- const floor = this.deps.now() - SAMPLE_MAX_AGE_MS
- const lines: string[] = []
- for (const [key, pts] of this.samples) for (const [ts, p, resets] of pts) if (ts >= floor) lines.push(JSON.stringify({ ts, key, pct: Math.round(p * 1e6) / 1e6, resets }))
- await this.deps.writeFile(this.path(SAMPLES_FILE), lines.length ? `${lines.join('\n')}\n` : '')
- }
-
- private async read(id: ProviderId, force: boolean): Promise<ProviderReading> {
- const now = this.deps.now()
- const hit = this.cache.get(id)
- const ttl = id === 'claude' || id === 'kimi' ? NETWORK_TTL_MS : LOCAL_TTL_MS
- if (hit && !force && now - hit.at < ttl) return hit.reading
- let fresh: ProviderReading
- try { fresh = await this.deps.readers[id](this.deps.providerDeps as ProviderDeps) } catch (e) {
- fresh = { id, name: PROVIDERS.find((p) => p.id === id)!.name, state: 'error', plan: '', limits: [], snapshot: false, measuredAt: 0, status: 'reader failed', help: '' }
- void e
- }
- // A failed probe keeps the last good figure rather than blanking it, and says so.
- if (fresh.state === 'error' && hit?.reading.state === 'ok') fresh = { ...hit.reading, status: `last known; ${fresh.status}` }
- this.cache.set(id, { at: now, reading: fresh })
- return fresh
- }
-
- /** Read every enabled provider and build the payload. `force` skips the per-provider TTL. */
- async collect(force = false): Promise<SubscriptionsPayload> {
- const now = this.deps.now()
- const settings = await this.getSettings()
- const samples = await this.loadSamples()
- let dirty = false
- const cards: SubscriptionCard[] = []
- for (const p of PROVIDERS) {
- const enabled = settings.enabled[p.id]
- if (!enabled) {
- cards.push({ id: p.id, name: p.name, state: 'disabled', enabled, plan: '', snapshot: false, measuredAt: 0, status: 'Switched off in settings', help: '', primary: null, windows: [], blocked: false, isPick: false })
- continue
- }
- const r = await this.read(p.id, force)
- let primary: PrimaryWindow | null = null
- let blocked = false
- for (const row of r.limits) {
- const key = `${p.id}|${row.label.slice(0, 64)}`
- const resets = windowId(parseIsoMs(row.resetsAt))
- const pts = samples.get(key) ?? []
- const paceBlock = paceFor(row, pts, !r.snapshot, now)
- if (row.percent >= 0 && resets) {
- const lastPt = pts[pts.length - 1]
- if (!lastPt || lastPt[2] !== resets || Math.abs(lastPt[1] - row.percent) > 1e-9 || now - lastPt[0] >= SAMPLE_MIN_GAP_MS) {
- pts.push([now, row.percent, resets])
- samples.set(key, pts)
- dirty = true
- }
- }
- if (/session|5-hour/i.test(row.label) && row.percent >= 0 && parseIsoMs(row.resetsAt) > now) {
- const rate = paceBlock.ratePerHour
- if (row.percent >= 0.9 || (rate > 0 && (1 - row.percent) / rate < 0.5)) blocked = true
- }
- if (row === primaryLimit(r.limits)) {
- const live = paceLive(row.percent, paceBlock.resetsMs, paceBlock.windowMs, now)
- if (live) {
- primary = {
- label: row.label, used: live.used, resetsAt: row.resetsAt, resetsInMs: live.leftMs, windowMs: live.windowMs,
- elapsed: live.elapsed, bankedSigned: live.bankedSigned, banked: live.banked, bankedMs: live.bankedMs, behind: live.behind,
- over: live.over, spent: live.spent, comeBackAt: live.comeBackAt, comeBackMs: live.comeBackMs, room: live.room,
- ratio: paceBlock.ratio, tone: toneOf(live), sentence: sentenceOf(live), pace: paceBlock,
- }
- }
- }
- }
- cards.push({ id: p.id, name: p.name, state: r.state, enabled, plan: r.plan, snapshot: r.snapshot, measuredAt: r.measuredAt, status: r.status, help: r.help, primary, windows: r.limits, blocked, isPick: false })
- }
- if (dirty) await this.saveSamples().catch(() => {})
- const present = cards.filter((c) => c.state !== 'disabled' && c.state !== 'not-detected')
- const guide = guidePick(present.map((c) => ({
- id: c.id,
- live: c.primary ? paceLive(c.primary.used, c.primary.pace.resetsMs, c.primary.windowMs, now) : null,
- fresh: !!c.primary,
- blocked: c.blocked,
- minBank: c.snapshot ? SNAPSHOT_MIN_BANK : undefined,
- })), this.previousPick)
- this.previousPick = guide.pick
- const name = (id: string) => PROVIDERS.find((p) => p.id === id)?.name ?? id
- let verdict = ''
- if (guide.pick) {
- const top = cards.find((c) => c.id === guide.pick)!
- top.isPick = true
- verdict = guide.urgent
- ? `Use ${name(guide.pick)} next: ${pct(1 - top.primary!.used)} unspent and it resets in ${spanWords(top.primary!.resetsInMs)}. Use it or lose it.`
- : `Use ${name(guide.pick)} next: the most room, ${guide.room.toFixed(1)}x an even pace.`
- if (guide.next) verdict += ` Then ${name(guide.next)}.`
- } else if (guide.count < 2) {
- verdict = guide.count === 1 ? 'One subscription here, so there is nothing to choose between.' : 'No subscriptions detected on this machine.'
- } else if (guide.rest.length) {
- const first = guide.rest[0]!
- verdict = `No plan is clearly ahead. ${name(first.id)} is back on pace first, in ${spanWords(Math.max(0, first.comeBackAt - now))}.`
- } else {
- verdict = 'Every plan is on pace; no clear pick.'
- }
- this.last = { at: now, subs: cards, guide: { ...guide, verdict }, settings }
- return this.last
- }
-
- /** The last payload, trimmed for the attention frame (the bar and the device). */
- compact(): { at: number; pick: string; verdict: string; subs: Array<{ id: ProviderId; name: string; used: number; bankedSigned: number; tone: Tone; resetsInMs: number; comeBackMs: number }> } | null {
- if (!this.last) return null
- return {
- at: this.last.at,
- pick: this.last.guide.pick,
- verdict: this.last.guide.verdict,
- subs: this.last.subs.filter((s) => s.primary).map((s) => ({
- id: s.id, name: s.name, used: s.primary!.used, bankedSigned: s.primary!.bankedSigned, tone: s.primary!.tone,
- resetsInMs: s.primary!.resetsInMs, comeBackMs: s.primary!.comeBackMs,
- })),
- }
- }
-}
-
-/** Plain lines for `harness subs`. */
-export function describeSubscriptions(p: SubscriptionsPayload): string[] {
- const lines: string[] = []
- for (const s of p.subs) {
- const head = `${s.isPick ? '>' : ' '} ${s.name.padEnd(7)}`
- if (s.state === 'disabled') { lines.push(`${head} off (harness subs set ${s.id} on)`); continue }
- if (s.state === 'not-detected') { lines.push(`${head} not detected`); continue }
- if (!s.primary) { lines.push(`${head} ${s.state}${s.status ? `: ${s.status}` : ''}${s.help ? ` (${s.help})` : ''}`); continue }
- const w = s.primary
- const bank = w.bankedSigned >= 0 ? `${pct(w.bankedSigned)} banked` : `${pct(-w.bankedSigned)} over pace`
- lines.push(`${head} ${s.plan ? `${s.plan} ` : ''}${w.label}: ${pct(w.used)} used, ${bank}, resets in ${spanWords(w.resetsInMs)}${s.snapshot ? ' (snapshot)' : ''}`)
- lines.push(` ${w.sentence}`)
- if (s.status) lines.push(` ${s.status}`)
- }
- lines.push('', p.guide.verdict)
- return lines
-}
diff --git a/cli/src/fleet/subscriptions/nodeDeps.ts b/cli/src/fleet/subscriptions/nodeDeps.ts
deleted file mode 100644
index 5f44295de..000000000
--- a/cli/src/fleet/subscriptions/nodeDeps.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-/** The real machine behind ProviderDeps and SubscriptionsDeps. Read-only except the daemon's own data dir. */
-import { execFile } from 'node:child_process'
-import { promises as fsp } from 'node:fs'
-import { homedir } from 'node:os'
-import { READERS, type ProviderDeps } from './providers.js'
-import type { SubscriptionsDeps } from './index.js'
-
-export function nodeProviderDeps(): ProviderDeps {
- return {
- home: homedir(),
- platform: process.platform,
- env: process.env,
- now: () => Date.now(),
- readFile: async (p) => { try { return await fsp.readFile(p, 'utf8') } catch { return null } },
- readTail: async (p, bytes) => {
- let fh: fsp.FileHandle | null = null
- try {
- fh = await fsp.open(p, 'r')
- const { size } = await fh.stat()
- const len = Math.min(size, bytes)
- const buf = Buffer.alloc(len)
- await fh.read(buf, 0, len, size - len)
- return buf.toString('utf8')
- } catch { return null } finally { await fh?.close().catch(() => {}) }
- },
- listDir: async (p) => { try { return await fsp.readdir(p) } catch { return [] } },
- exists: async (p) => { try { await fsp.stat(p); return true } catch { return false } },
- fetchJson: async (url, headers, timeoutMs) => {
- const res = await fetch(url, { headers, signal: AbortSignal.timeout(timeoutMs) })
- let body: unknown = null
- try { body = await res.json() } catch { body = null }
- return { status: res.status, body }
- },
- execFile: (cmd, args, timeoutMs) => new Promise((resolve) => {
- execFile(cmd, args, { timeout: timeoutMs, encoding: 'utf8', maxBuffer: 256 * 1024 }, (err, stdout) => resolve(err ? null : stdout))
- }),
- }
-}
-
-export function nodeSubscriptionsDeps(dataDir: string): SubscriptionsDeps {
- return {
- dataDir,
- now: () => Date.now(),
- readers: READERS,
- providerDeps: nodeProviderDeps(),
- readFile: async (p) => { try { return await fsp.readFile(p, 'utf8') } catch { return null } },
- writeFile: async (p, d) => {
- const tmp = `${p}.${process.pid}.tmp`
- await fsp.writeFile(tmp, d, { mode: 0o600 })
- await fsp.rename(tmp, p)
- },
- }
-}
diff --git a/cli/src/fleet/subscriptions/pace.spec.ts b/cli/src/fleet/subscriptions/pace.spec.ts
deleted file mode 100644
index e295f5ccc..000000000
--- a/cli/src/fleet/subscriptions/pace.spec.ts
+++ /dev/null
@@ -1,297 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-/**
- * The pace and banked arithmetic, mirroring Burn Bar's own suites
- * (github.com/nixfred/burnbar tests/test_pace_math.py and tests/test_guidance.cjs) case for case,
- * so the port answers every question the original answers, with the same numbers.
- */
-import { describe, expect, it } from 'vitest'
-import {
- burndownSeries, clockSpan, guidePick, paceFor, paceLive, recentRatePerHour, SERIES_MAX_POINTS,
- spanWords, windowId, windowMsFor, type Sample,
-} from './pace.js'
-
-const HOUR = 3_600_000
-const DAY = 86_400_000
-const WEEK = 7 * DAY
-const MONTH = 30 * DAY
-const NOW = 1_789_900_000_000 // 2026-09-20 UTC
-const iso = (ms: number): string => new Date(ms).toISOString()
-const utc = (y: number, m: number, d: number): number => Date.UTC(y, m - 1, d)
-
-describe('window length (burnbar WindowLengthTests)', () => {
- it('reads the length off the label when the provider states it', () => {
- expect(windowMsFor('Session (5-hour)', NOW, 0)).toBe(5 * HOUR)
- expect(windowMsFor('Weekly (7-day)', NOW, 0)).toBe(7 * DAY)
- })
- it('a month is the calendar month before the reset, not thirty days', () => {
- expect(windowMsFor('Monthly (total)', utc(2027, 3, 1), 0)).toBe(28 * DAY)
- expect(windowMsFor('Monthly (total)', utc(2028, 3, 1), 0)).toBe(29 * DAY)
- })
- it('an unlabelled window is measured from the previous reset', () => {
- expect(windowMsFor('Quota', NOW + DAY, NOW - 2 * DAY)).toBe(3 * DAY)
- })
- it('an unlabelled window with no history is unknown, not a guess', () => {
- expect(windowMsFor('Quota', NOW + DAY, 0)).toBe(0)
- })
-})
-
-describe('rate (burnbar RateTests)', () => {
- const rate = (pts: Array<[number, number]>) => recentRatePerHour(pts.map(([t, p]) => [t, p, 1] as Sample))
- it('a straight line is its slope per hour', () => {
- expect(rate([[NOW - 2 * HOUR, 0.1], [NOW - HOUR, 0.2], [NOW, 0.3]])).toBeCloseTo(0.1, 6)
- })
- it('one sample cannot be a rate', () => { expect(rate([[NOW, 0.4]])).toBeNull() })
- it('two ticks seconds apart cannot be a rate', () => { expect(rate([[NOW - 5000, 0.4], [NOW, 0.41]])).toBeNull() })
- it('a percentage that went down is a reset, not a negative burn', () => {
- expect(rate([[NOW - 2 * HOUR, 0.9], [NOW, 0.05]])).toBeNull()
- })
- it('samples older than the rate window are not part of the rate', () => {
- expect(rate([[NOW - 20 * HOUR, 0], [NOW - HOUR, 0.5], [NOW, 0.6]])).toBeCloseTo(0.1, 6)
- })
-})
-
-describe('window id (burnbar WindowIdTests)', () => {
- it('the same window stated with jitter is one window', () => {
- const base = NOW + 6 * DAY
- expect(new Set([0, 53, 407, 828, 950].map((ms) => windowId(base + ms))).size).toBe(1)
- })
- it('windows a minute apart stay different', () => {
- expect(windowId(NOW + 6 * DAY)).not.toBe(windowId(NOW + 6 * DAY + 60_000))
- })
-})
-
-describe('burndown series (burnbar BurndownSeriesTests)', () => {
- it('is normalised and ends on the present', () => {
- const resets = windowId(NOW + 3 * DAY)
- const start = resets - WEEK
- const s = burndownSeries([[start + DAY, 0.1, resets], [start + 2 * DAY, 0.25, resets]], resets, WEEK, 0.4, NOW)
- expect(s).toHaveLength(3)
- expect(s[0]![0]).toBeCloseTo(1 / 7, 3)
- expect(s[0]![1]).toBeCloseTo(0.1, 5)
- expect(s[2]![0]).toBeCloseTo((NOW - start) / WEEK, 3)
- expect(s[2]![1]).toBeCloseTo(0.4, 5)
- for (const [x, y] of s) { expect(x).toBeGreaterThanOrEqual(0); expect(x).toBeLessThanOrEqual(1); expect(y).toBeLessThanOrEqual(1) }
- })
- it('never lets another window leak into this line', () => {
- const resets = windowId(NOW + 3 * DAY)
- const s = burndownSeries([[NOW - DAY, 0.9, resets - WEEK], [NOW - HOUR, 0.2, resets]], resets, WEEK, 0.22, NOW)
- expect(s.map((p) => Math.round(p[1] * 100) / 100)).toEqual([0.2, 0.22])
- })
- it('thins a long window rather than shipping it whole', () => {
- const resets = windowId(NOW + DAY)
- const start = resets - WEEK
- const pts: Sample[] = Array.from({ length: 1499 }, (_, i) => [start + (i + 1) * 300_000, (i + 1) / 2000, resets])
- const s = burndownSeries(pts, resets, WEEK, 0.76, NOW)
- expect(s.length).toBeLessThanOrEqual(SERIES_MAX_POINTS)
- expect(s[s.length - 1]![1]).toBeCloseTo(0.76, 5)
- })
- it('no samples is still a point the card can draw', () => {
- const s = burndownSeries([], windowId(NOW + 3 * DAY), WEEK, 0.05, NOW)
- expect(s).toHaveLength(1)
- expect(s[0]![1]).toBeCloseTo(0.05, 5)
- })
-})
-
-describe('pace (burnbar PaceTests and ReviewFixTests)', () => {
- const row = (pct: number, resets: number, label = 'Weekly (7-day)') => ({ label, percent: pct, resetsAt: iso(resets) })
- it('on pace is one', () => {
- const p = paceFor(row(0.5, NOW + 3.5 * DAY), [], true, NOW)
- expect(p.ratio).toBeCloseTo(1, 3)
- expect(p.elapsed).toBeCloseTo(0.5, 3)
- })
- it('a blown window has no allowance and recovers only at the reset', () => {
- const resets = windowId(NOW + 6 * DAY)
- const p = paceFor(row(1, resets), [], true, NOW)
- expect(p.ratio).toBeGreaterThan(1)
- expect(p.allowancePerHour).toBe(0)
- expect(p.backOnPaceAt).toBe(resets)
- })
- it('half spent early comes back on pace midway through the window', () => {
- const resets = windowId(NOW + 6 * DAY)
- expect(paceFor(row(0.5, resets), [], true, NOW).backOnPaceAt).toBe(resets - 3.5 * DAY)
- })
- it('the first moments of a window hold the ratio rather than divide by zero', () => {
- const p = paceFor(row(0.01, NOW + 7 * DAY - 60_000), [], true, NOW)
- expect(p.ratio).toBe(-1)
- expect(p.elapsed).toBeGreaterThanOrEqual(0)
- })
- it('a window already past its reset carries no pace', () => {
- const p = paceFor(row(0.4, NOW - HOUR), [], true, NOW)
- expect(p.windowMs).toBe(0)
- expect(p.ratio).toBe(-1)
- })
- it('a missing percentage carries no pace', () => {
- const p = paceFor(row(-1, NOW + DAY), [], true, NOW)
- expect(p.ratio).toBe(-1)
- expect(p.allowancePerHour).toBe(-1)
- })
- it('a snapshot row gets a ratio but never a rate', () => {
- const p = paceFor(row(0.3, NOW + 3.5 * DAY), [[NOW - 2 * HOUR, 0.1, 1], [NOW, 0.3, 1]], false, NOW)
- expect(p.ratio).toBeGreaterThan(0)
- expect(p.ratePerHour).toBe(-1)
- expect(p.projected).toBe(-1)
- })
- it('at this rate projects past the reset and names the dry moment', () => {
- const resets = windowId(NOW + 10 * HOUR)
- const pts: Sample[] = [[NOW - 2 * HOUR, 0.2, resets], [NOW - HOUR, 0.3, resets], [NOW, 0.4, resets]]
- const p = paceFor(row(0.4, resets), pts, true, NOW)
- expect(p.ratePerHour).toBeCloseTo(0.1, 6)
- expect(p.projected).toBeCloseTo(1.4, 2)
- expect((p.dryAt - NOW) / HOUR).toBeCloseTo(6, 3)
- })
- it('a rate that still lands inside the window names no dry moment', () => {
- const resets = windowId(NOW + 10 * HOUR)
- const p = paceFor(row(0.12, resets), [[NOW - 2 * HOUR, 0.1, resets], [NOW, 0.12, resets]], true, NOW)
- expect(p.projected).toBeLessThan(1)
- expect(p.dryAt).toBe(0)
- })
- it('an on-pace sub is not told to stop in a day', () => {
- const resets = windowId(NOW + 3.5 * DAY)
- const even = 1 / 7 / 24
- const p = paceFor(row(0.5, resets), [[NOW - 2 * HOUR, 0.5 - 2 * even, resets], [NOW, 0.5, resets]], true, NOW)
- expect(p.stopInMs).toBe(-1)
- })
- it('a fast burn still gets its stop time', () => {
- const resets = windowId(NOW + 3.5 * DAY)
- const p = paceFor(row(0.3, resets), [[NOW - 2 * HOUR, 0.2, resets], [NOW, 0.3, resets]], true, NOW)
- expect(p.stopInMs).toBeGreaterThan(0)
- expect(p.stopInMs).toBeLessThan(24 * HOUR)
- })
- it('a five-hour window has no daily ceiling', () => {
- expect(paceFor(row(0.5, NOW + HOUR, 'Session (5-hour)'), [], true, NOW).todayCeiling).toBe(-1)
- })
-})
-
-const NOW2 = 1_800_000_000_000
-const win = (used: number, gone: number, span = WEEK) => paceLive(used, NOW2 + span * (1 - gone), span, NOW2)
-
-describe('banked and come-back (burnbar test_guidance.cjs)', () => {
- it('ahead: banked is elapsed minus used, in plan share and in time', () => {
- const w = win(0.02, 0.51)!
- expect(w.banked).toBeCloseTo(0.49, 9)
- expect(w.bankedSigned).toBeCloseTo(0.49, 9)
- expect(w.bankedMs).toBeCloseTo(0.49 * WEEK, 0)
- expect(w.behind).toBe(0)
- expect(w.comeBackAt).toBe(0)
- expect(w.room).toBeCloseTo(0.98 / 0.49, 9)
- })
- it('behind: no banked figure, a negative signed bank, and a moment to come back', () => {
- const w = win(0.09, 0.05)!
- expect(w.banked).toBe(0)
- expect(w.bankedSigned).toBeCloseTo(-0.04, 9)
- expect(w.behind).toBeCloseTo(0.04, 9)
- expect(w.comeBackMs).toBeCloseTo(0.04 * WEEK, 0)
- expect(w.comeBackAt).toBeGreaterThan(NOW2)
- expect(w.comeBackAt).toBeLessThan(w.resetsMs)
- })
- it('time off brings a sub back, and the promised come-back moment is when it flips', () => {
- const reset = NOW2 + 5 * DAY
- const before = paceLive(0.3, reset, WEEK, NOW2)!
- const later = paceLive(0.3, reset, WEEK, NOW2 + 2 * DAY)!
- expect(before.behind).toBeGreaterThan(0)
- expect(later.banked).toBeGreaterThan(0.25)
- expect(paceLive(0.3, reset, WEEK, before.comeBackAt + 1000)!.behind).toBe(0)
- })
- it('spent out comes back at the reset, never before', () => {
- const w = win(1, 0.13)!
- expect(w.spent).toBe(true)
- expect(w.comeBackAt).toBe(w.resetsMs)
- expect(w.room).toBe(0)
- })
- it('spent while ahead of the clock still comes back at the reset', () => {
- const w = win(0.996, 0.999)!
- expect(w.spent).toBe(true)
- expect(w.banked).toBe(0)
- expect(w.comeBackAt).toBe(w.resetsMs)
- expect(win(0.997, 0.997)!.comeBackAt).toBe(win(0.997, 0.997)!.resetsMs)
- })
- it('inside 5% of an even spend is on pace, not over', () => {
- expect(win(0.5, 0.48)!.over).toBe(false)
- expect(win(0.09, 0.05)!.over).toBe(true)
- expect(win(0.004, 0.001)!.over).toBe(false)
- })
- it('claims nothing about a window that cannot be read', () => {
- for (const [p, r, s] of [[-1, NOW2 + DAY, WEEK], [NaN, NOW2 + DAY, WEEK], [0.5, 0, WEEK], [0.5, NOW2 + DAY, 0], [0.5, NOW2 - 1, WEEK]])
- expect(paceLive(p!, r!, s!, NOW2)).toBeNull()
- })
-})
-
-const row = (id: string, used: number, gone: number, opts: { span?: number; fresh?: boolean; blocked?: boolean; minBank?: number } = {}) =>
- ({ id, live: win(used, gone, opts.span ?? WEEK), fresh: opts.fresh ?? true, blocked: opts.blocked ?? false, minBank: opts.minBank })
-
-describe('which sub next (burnbar guidePick)', () => {
- it('one subscription is never suggested', () => {
- const g = guidePick([row('kimi', 0.05, 0.6, { span: MONTH })], '')
- expect(g.count).toBe(1)
- expect(g.pick).toBe('')
- })
- it('with two, the one with room is the right one', () => {
- const g = guidePick([row('claude', 0.09, 0.05), row('grok', 0.02, 0.51)], '')
- expect(g.pick).toBe('grok')
- expect(g.rest.map((r) => r.id)).toEqual(['claude'])
- })
- it('with four, a week and a month are ranked on the same scale', () => {
- const g = guidePick([row('claude', 0.09, 0.05), row('codex', 1, 0.13), row('grok', 0.02, 0.51), row('kimi', 0.05, 0.16, { span: MONTH })], '')
- expect(g.pick).toBe('grok')
- expect(g.next).toBe('kimi')
- expect(g.ahead).toBe(2)
- expect(g.rest.map((r) => r.id)).toEqual(['claude', 'codex'])
- })
- it('use it or lose it: a close reset with budget unspent wins, and says so', () => {
- const g = guidePick([row('grok', 0.02, 0.51), row('codex', 0.6, 0.95)], '')
- expect(g.pick).toBe('codex')
- expect(g.urgent).toBe(true)
- })
- it('urgent is about the calendar', () => {
- const fourDays = 1 - (4 * DAY) / MONTH
- const g = guidePick([row('kimi', 0.3, fourDays, { span: MONTH }), row('claude', 0.9, 0.5)], '')
- expect(g.pick).toBe('kimi')
- expect(g.urgent).toBe(false)
- const twoDays = 1 - (2 * DAY) / MONTH
- expect(guidePick([row('kimi', 0.3, twoDays, { span: MONTH }), row('claude', 0.9, 0.5)], '').urgent).toBe(true)
- expect(guidePick([row('grok', 0.93, 0.97), row('claude', 0.9, 0.5)], '').urgent).toBe(false)
- })
- it('a snapshot has to be further ahead before it is suggested', () => {
- const snap = (bank: number, min: number) => row('grok', 0.5 - bank, 0.5, { minBank: min })
- expect(guidePick([snap(0.06, 0.1), row('claude', 0.9, 0.5)], '').pick).toBe('')
- expect(guidePick([snap(0.12, 0.1), row('claude', 0.9, 0.5)], '').pick).toBe('grok')
- })
- it('the sub being suggested keeps the job down to half the threshold', () => {
- const thin = row('kimi', 0.485, 0.5, { span: MONTH })
- expect(guidePick([thin, row('claude', 0.9, 0.5)], '').pick).toBe('')
- expect(guidePick([thin, row('claude', 0.9, 0.5)], 'kimi').pick).toBe('kimi')
- })
- it('is never a sub that is stale, blocked, spent or unreadable', () => {
- expect(guidePick([row('claude', 0.5, 0.5), row('grok', 0.02, 0.6, { fresh: false })], '').pick).toBe('')
- expect(guidePick([row('claude', 0.1, 0.6, { blocked: true }), row('codex', 0.7, 0.5)], '').pick).toBe('')
- expect(guidePick([{ id: 'claude', live: null, fresh: true, blocked: false }, row('kimi', 0.05, 0.4, { span: MONTH })], '').pick).toBe('kimi')
- })
- it('everyone behind: no suggestion, and the first one back is named', () => {
- const g = guidePick([row('claude', 0.3, 0.1), row('codex', 0.2, 0.15)], '')
- expect(g.pick).toBe('')
- expect(g.rest[0]!.id).toBe('codex')
- })
- it('a hair of banked budget is not advice', () => {
- expect(guidePick([row('claude', 0.49, 0.5), row('codex', 0.3, 0.31)], '').pick).toBe('')
- })
- it('does not flap between two near-equal subs', () => {
- const a = row('grok', 0.2, 0.6)
- const b = row('kimi', 0.19, 0.6, { span: MONTH })
- expect(guidePick([a, b], '').pick).toBe('kimi')
- expect(guidePick([a, b], 'grok').pick).toBe('grok')
- expect(guidePick([a, row('kimi', 0.02, 0.6, { span: MONTH })], 'grok').pick).toBe('kimi')
- })
-})
-
-describe('spans', () => {
- it('clocks run, spans read like advice', () => {
- expect(clockSpan(3 * DAY + 9 * HOUR + 12 * 60e3 + 45e3)).toBe('3d 09:12:45')
- expect(clockSpan(7 * HOUR + 13 * 60e3 + 22e3)).toBe('7:13:22')
- expect(clockSpan(-5)).toBe('0:00')
- expect(spanWords(3 * DAY + 10 * HOUR + 22 * 60e3)).toBe('3d 10h')
- expect(spanWords(6 * HOUR + 40 * 60e3)).toBe('6h 40m')
- expect(spanWords(2 * DAY)).toBe('2d')
- expect(spanWords(20e3)).toBe('under a minute')
- })
-})
diff --git a/cli/src/fleet/subscriptions/pace.ts b/cli/src/fleet/subscriptions/pace.ts
deleted file mode 100644
index 3929abf1f..000000000
--- a/cli/src/fleet/subscriptions/pace.ts
+++ /dev/null
@@ -1,308 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-/**
- * Budget pace for a subscription window: am I over, how much have I banked, when can I come back,
- * and which subscription should I reach for next.
- *
- * Ported from Burn Bar (https://github.com/nixfred/burnbar, MIT): `bin/burnbar-collect` (pace_for,
- * window_ms_for, recent_rate_per_hour, burndown_series, window_id) and `BarWidget.qml` (paceLive,
- * guidePick, spanWords, clockSpan). The arithmetic is kept identical so the two agree to the number;
- * Burn Bar itself is not required, called or read.
- *
- * On budget means EVEN PACE across the window: a tenth of the way in, a tenth of the plan is a fair
- * spend. With used fraction p, window length L and time left r:
- *
- * elapsed e = (L - r) / L
- * pace ratio R = p / e 1.0 is exactly on pace, above it is over
- * banked e - p (signed) positive = unspent share an even pace allowed by now,
- * negative = how far ahead of the clock the spend is
- * allowance (1 - p) / r what may still burn per hour and make it to the reset
- * forecast p + rate * r above 1.0 the window runs dry early
- * come back at reset - L * (1 - p) the moment the even-pace line catches up, if you stop now
- * room (1 - p) / (1 - e) same scale for a week and a month; ranks the next sub
- *
- * Unknowns are -1 (a figure that cannot be measured) or 0 (a moment that does not apply), never an
- * invented number. Every percentage is the provider's own.
- */
-
-export const HOUR_MS = 3_600_000
-export const DAY_MS = 86_400_000
-export const RATE_WINDOW_MS = 120 * 60_000
-export const RATE_MIN_SPAN_MS = 10 * 60_000
-export const DAILY_MIN_WINDOW_MS = 36 * HOUR_MS
-export const SERIES_MAX_POINTS = 48
-
-/** [timestampMs, usedFraction, windowId] */
-export type Sample = [number, number, number]
-
-export interface LimitRow {
- label: string
- /** 0..1, or -1 when unknown. */
- percent: number
- /** ISO time, or '' when unknown. */
- resetsAt: string
- /** Start of the window when the provider states it (Grok does). */
- startsAt?: string
-}
-
-export interface Pace {
- windowMs: number
- resetsMs: number
- elapsed: number
- ratio: number
- allowancePerHour: number
- ratePerHour: number
- projected: number
- dryAt: number
- backOnPaceAt: number
- todayCeiling: number
- stopInMs: number
- stopAtMs: number
- series: Array<[number, number]>
-}
-
-export function parseIsoMs(raw: unknown): number {
- const s = String(raw ?? '').trim()
- if (!s) return 0
- const ms = Date.parse(s)
- return Number.isFinite(ms) ? ms : 0
-}
-
-/** 0..1 or -1. A boolean is never a percentage. */
-export function normPercent(value: unknown): number {
- if (typeof value === 'boolean' || value === null || value === undefined || value === '') return -1
- const n = Number(value)
- if (!Number.isFinite(n) || n < 0 || n > 1) return -1
- return n
-}
-
-/** Which window instance this is, to the minute: providers restate the same reset with ms jitter. */
-export function windowId(resetsMs: number): number {
- return Math.floor(resetsMs / 60_000) * 60_000
-}
-
-/** How long a window is: from the label when stated, else the distance from the previous reset. */
-export function windowMsFor(label: string, resetsMs: number, prevResetsMs: number): number {
- const text = String(label || '').toLowerCase()
- const m = /(\d+)\s*-\s*(hour|day)/.exec(text)
- if (m) return Number(m[1]) * (m[2] === 'hour' ? HOUR_MS : DAY_MS)
- if (text.includes('week')) return 7 * DAY_MS
- if (text.includes('month')) {
- if (resetsMs) {
- // Step back one calendar month from the reset so a February window is February long.
- const end = new Date(resetsMs)
- let y = end.getUTCFullYear()
- let mo = end.getUTCMonth() - 1
- if (mo < 0) { mo = 11; y -= 1 }
- const daysIn = new Date(Date.UTC(y, mo + 1, 0)).getUTCDate()
- const day = Math.min(end.getUTCDate(), daysIn)
- const start = Date.UTC(y, mo, day, end.getUTCHours(), end.getUTCMinutes(), end.getUTCSeconds(), end.getUTCMilliseconds())
- return Math.max(DAY_MS, resetsMs - start)
- }
- return 30 * DAY_MS
- }
- if (text.includes('session')) return 5 * HOUR_MS
- if (text.includes('daily') || text.includes('day')) return DAY_MS
- if (prevResetsMs && resetsMs > prevResetsMs) return resetsMs - prevResetsMs
- return 0
-}
-
-/** Least-squares slope over the last two hours, as fraction per hour; null when it cannot carry one. */
-export function recentRatePerHour(points: Sample[]): number | null {
- if (points.length < 2) return null
- const floor = points[points.length - 1]![0] - RATE_WINDOW_MS
- const pts = points.filter(([t]) => t >= floor).map(([t, p]) => [t, p] as const)
- if (pts.length < 2 || pts[pts.length - 1]![0] - pts[0]![0] < RATE_MIN_SPAN_MS) return null
- for (let i = 1; i < pts.length; i++) if (pts[i]![1] < pts[i - 1]![1] - 1e-9) return null
- const n = pts.length
- const mt = pts.reduce((a, [t]) => a + t, 0) / n
- const mp = pts.reduce((a, [, p]) => a + p, 0) / n
- const denom = pts.reduce((a, [t]) => a + (t - mt) ** 2, 0)
- if (denom <= 0) return null
- const slope = pts.reduce((a, [t, p]) => a + (t - mt) * (p - mp), 0) / denom
- return Math.max(0, slope * HOUR_MS)
-}
-
-const r5 = (n: number): number => Math.round(n * 1e5) / 1e5
-
-/** This window's samples as [x, y] in 0..1, thinned, always ending on the present. */
-export function burndownSeries(points: Sample[], resets: number, window: number, pctNow: number, now: number): Array<[number, number]> {
- const start = resets - window
- let mine = points.filter(([t, , r]) => r === resets && t >= start && t <= now)
- if (mine.length > SERIES_MAX_POINTS - 1) {
- const step = mine.length / (SERIES_MAX_POINTS - 1)
- mine = Array.from({ length: SERIES_MAX_POINTS - 1 }, (_, i) => mine[Math.floor(i * step)]!)
- }
- const out: Array<[number, number]> = mine.map(([t, p]) => [r5((t - start) / window), r5(p)])
- out.push([r5(Math.min(1, Math.max(0, (now - start) / window))), r5(pctNow)])
- return out
-}
-
-/** The collector-side pace block for one limit row (Burn Bar's pace_for). */
-export function paceFor(row: LimitRow, points: Sample[], live: boolean, now: number): Pace {
- const out: Pace = {
- windowMs: 0, resetsMs: 0, elapsed: -1, ratio: -1, allowancePerHour: -1, ratePerHour: -1, projected: -1,
- dryAt: 0, backOnPaceAt: 0, todayCeiling: -1, stopInMs: -1, stopAtMs: 0, series: [],
- }
- const pct = row.percent
- const resets = windowId(parseIsoMs(row.resetsAt))
- if (typeof pct !== 'number' || !(pct >= 0) || !resets) return out
- let prev = 0
- for (const [, , r] of points) if (r && r < resets) prev = Math.max(prev, r)
- const starts = parseIsoMs(row.startsAt)
- let window = starts && starts < resets ? resets - starts : windowMsFor(row.label, resets, prev)
- const leftMs = resets - now
- if (window <= 0 || leftMs <= 0) return out
- window = Math.max(window, 1)
- out.windowMs = window
- out.resetsMs = resets
- out.series = burndownSeries(points, resets, window, pct, now)
- const elapsed = Math.min(1, Math.max(0, (window - leftMs) / window))
- out.elapsed = elapsed
- const hoursLeft = leftMs / HOUR_MS
- out.allowancePerHour = Math.max(0, (1 - pct) / hoursLeft)
- // Hold the ratio until the window is one percent old: any spend divides by ~0 before that.
- if (elapsed >= 0.01) out.ratio = pct / elapsed
- const rate = live ? recentRatePerHour(points.filter((p) => p[2] === resets)) : null
- if (rate !== null) {
- out.ratePerHour = rate
- out.projected = pct + rate * hoursLeft
- if (rate > 0 && out.projected > 1) out.dryAt = Math.trunc(now + ((1 - pct) / rate) * HOUR_MS)
- }
- if (out.ratio > 1) out.backOnPaceAt = Math.trunc(resets - window * (1 - pct))
- if (window >= DAILY_MIN_WINDOW_MS && hoursLeft > 0) {
- const ceiling = Math.max(0, (1 - pct) * Math.min(1, 24 / hoursLeft))
- out.todayCeiling = ceiling
- // Only a stop that lands inside the day (and the window) is advice; an on-pace sub lasts ~24h.
- if (rate !== null && rate > 0.0005) {
- const hours = ceiling / rate
- if (hours < 24 && hours * HOUR_MS < leftMs) {
- out.stopInMs = Math.trunc(hours * HOUR_MS)
- out.stopAtMs = Math.trunc(now + hours * HOUR_MS)
- }
- }
- }
- return out
-}
-
-export interface LivePace {
- used: number
- elapsed: number
- leftMs: number
- windowMs: number
- resetsMs: number
- /** Share of the plan an even pace would have used by now and did not; 0 when not ahead. */
- banked: number
- /** elapsed - used: positive when banked, negative when over pace. */
- bankedSigned: number
- bankedMs: number
- behind: number
- over: boolean
- comeBackAt: number
- comeBackMs: number
- room: number
- spent: boolean
-}
-
-/** Where one window stands right now (Burn Bar's paceLive). Null when the window cannot be read. */
-export function paceLive(percent: number, resetsMs: number, windowMs: number, nowMs: number): LivePace | null {
- const p0 = Number(percent), reset = Number(resetsMs), span = Number(windowMs), now = Number(nowMs)
- if (!(p0 >= 0) || !(reset > 0) || !(span > 0) || !(now > 0) || now >= reset) return null
- const p = Math.min(1, p0)
- const left = reset - now
- const e = Math.max(0, Math.min(1, 1 - left / span))
- const out: LivePace = {
- used: p, elapsed: e, leftMs: left, windowMs: span, resetsMs: reset, banked: 0, bankedSigned: e - p, bankedMs: 0,
- behind: 0, over: false, comeBackAt: 0, comeBackMs: 0, room: 0, spent: p >= 0.995,
- }
- if (out.spent) {
- // Decided first: a plan can be spent while still ahead of the clock; it only comes back at the reset.
- out.behind = Math.max(0, p - e)
- out.over = true
- out.comeBackAt = reset
- out.comeBackMs = left
- } else if (e > p) {
- out.banked = e - p
- out.bankedMs = out.banked * span
- } else if (p > e) {
- out.behind = p - e
- // Over means more than 5% past an even spend and by at least a whole percent of the plan.
- out.over = out.behind > 0.01 && (e <= 0 || p / e > 1.05)
- out.comeBackAt = Math.min(reset, reset - span * (1 - p))
- out.comeBackMs = Math.max(0, out.comeBackAt - now)
- }
- out.room = e < 1 ? (1 - p) / (1 - e) : 0
- return out
-}
-
-export interface GuideRow { id: string; live: LivePace | null; fresh: boolean; blocked: boolean; minBank?: number }
-export interface Guide {
- count: number
- pick: string
- next: string
- urgent: boolean
- room: number
- ahead: number
- rest: Array<{ id: string; comeBackAt: number; spent: boolean; behind: number }>
-}
-
-/**
- * Which subscription to reach for next (Burn Bar's guidePick). Only a sub that is ahead is ever
- * suggested; the most room wins, which becomes earliest-deadline-first as a reset nears with budget
- * unspent. One sub alone is never suggested. The previous pick sticks until another is clearly better.
- */
-export function guidePick(rows: GuideRow[], previousId: string): Guide {
- const MIN_BANK = 0.02, STICK = 1.15
- const LOSE_IT_MS = 72 * HOUR_MS, LOSE_IT_SHARE = 0.15, LOSE_IT_LEFT = 0.1
- const out: Guide = { count: 0, pick: '', next: '', urgent: false, room: 0, rest: [], ahead: 0 }
- const ok: GuideRow[] = []
- for (const r of rows) {
- if (!r || !r.id) continue
- out.count++
- if (!r.live || !r.fresh) continue
- if (r.live.over || r.live.spent) out.rest.push({ id: r.id, comeBackAt: r.live.comeBackAt, spent: r.live.spent, behind: r.live.behind })
- let need = r.minBank && r.minBank > 0 ? r.minBank : MIN_BANK
- if (r.id === previousId) need *= 0.5
- if (r.live.spent || r.blocked || !(r.live.banked >= need)) continue
- ok.push(r)
- }
- out.ahead = ok.length
- out.rest.sort((a, b) => a.comeBackAt - b.comeBackAt)
- if (out.count < 2 || ok.length === 0) return out
- ok.sort((a, b) => {
- if (b.live!.room !== a.live!.room) return b.live!.room - a.live!.room
- if (b.live!.banked !== a.live!.banked) return b.live!.banked - a.live!.banked
- return a.live!.leftMs - b.live!.leftMs
- })
- if (previousId && previousId !== ok[0]!.id) {
- const i = ok.findIndex((r, idx) => idx > 0 && r.id === previousId)
- if (i > 0 && ok[0]!.live!.room < ok[i]!.live!.room * STICK) ok.unshift(ok.splice(i, 1)[0]!)
- }
- const top = ok[0]!.live!
- out.pick = ok[0]!.id
- out.room = top.room
- out.urgent = top.leftMs <= Math.min(LOSE_IT_MS, top.windowMs * LOSE_IT_SHARE) && 1 - top.used >= LOSE_IT_LEFT
- out.next = ok.length > 1 ? ok[1]!.id : ''
- return out
-}
-
-/** "3d 09:12:45", "7:13:22", "13:05". */
-export function clockSpan(ms: number): string {
- const total = Math.max(0, Math.floor(Number(ms) / 1000))
- if (!(total >= 0)) return '0:00'
- const d = Math.floor(total / 86400), h = Math.floor((total % 86400) / 3600), m = Math.floor((total % 3600) / 60), s = total % 60
- const two = (n: number) => (n < 10 ? '0' : '') + n
- if (d > 0) return `${d}d ${two(h)}:${two(m)}:${two(s)}`
- if (h > 0) return `${h}:${two(m)}:${two(s)}`
- return `${m}:${two(s)}`
-}
-
-/** "3d 10h", "6h 40m", "45m": two units at most. */
-export function spanWords(ms: number): string {
- const mins = Math.max(0, Math.round(Number(ms) / 60000))
- if (!(mins >= 1)) return 'under a minute'
- const d = Math.floor(mins / 1440), h = Math.floor((mins % 1440) / 60), m = mins % 60
- if (d > 0) return h > 0 ? `${d}d ${h}h` : `${d}d`
- if (h > 0) return m > 0 ? `${h}h ${m}m` : `${h}h`
- return `${m}m`
-}
diff --git a/cli/src/fleet/subscriptions/providers.spec.ts b/cli/src/fleet/subscriptions/providers.spec.ts
deleted file mode 100644
index 279cbf810..000000000
--- a/cli/src/fleet/subscriptions/providers.spec.ts
+++ /dev/null
@@ -1,156 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-import { describe, expect, it } from 'vitest'
-import { readClaude, readCodex, readGrok, readKimi, type ProviderDeps } from './providers.js'
-
-const NOW = Date.UTC(2026, 8, 30, 12)
-const HOME = '/h'
-
-function deps(files: Record<string, string>, over: Partial<ProviderDeps> = {}): ProviderDeps & { calls: Array<{ url: string; headers: Record<string, string> }> } {
- const calls: Array<{ url: string; headers: Record<string, string> }> = []
- return {
- calls,
- home: HOME,
- platform: 'linux',
- env: {},
- now: () => NOW,
- readFile: async (p) => (p in files ? files[p]! : null),
- readTail: async (p, bytes) => (p in files ? files[p]!.slice(-bytes) : null),
- listDir: async (p) => {
- const prefix = p.endsWith('/') ? p : `${p}/`
- const names = new Set<string>()
- for (const f of Object.keys(files)) if (f.startsWith(prefix)) names.add(f.slice(prefix.length).split('/')[0]!)
- return [...names]
- },
- exists: async (p) => Object.keys(files).some((f) => f === p || f.startsWith(`${p}/`)),
- fetchJson: async (url, headers) => { calls.push({ url, headers }); return { status: 599, body: null } },
- execFile: async () => null,
- ...over,
- }
-}
-
-describe('provider absent: not detected, never an error', () => {
- it('claude, codex, grok and kimi on an empty machine', async () => {
- const d = deps({})
- for (const r of [await readClaude(d), await readCodex(d), await readGrok(d), await readKimi(d)]) {
- expect(r.state).toBe('not-detected')
- expect(r.limits).toEqual([])
- }
- expect(d.calls).toHaveLength(0) // nothing leaves the machine when nothing is configured
- })
- it('claude installed but not logged in is not configured', async () => {
- const r = await readClaude(deps({ '/h/.claude/settings.json': '{}' }))
- expect(r.state).toBe('not-configured')
- expect(r.help).toMatch(/claude/)
- })
-})
-
-describe('claude', () => {
- const creds = JSON.stringify({ claudeAiOauth: { accessToken: 'sk-ant-oat01-SECRETSECRETSECRET', rateLimitTier: 'default_claude_max_20x', subscriptionType: 'max' } })
- it('reads the OAuth usage endpoint with the local token and maps percent-scale rows', async () => {
- const d = deps({ '/h/.claude/.credentials.json': creds }, {
- fetchJson: async (url, headers) => {
- d.calls.push({ url, headers })
- return { status: 200, body: { five_hour: { utilization: 7, resets_at: '2026-09-30T15:00:00Z' }, seven_day: { utilization: 32, resets_at: '2026-10-04T10:00:00Z' } } }
- },
- })
- const r = await readClaude(d)
- expect(d.calls[0]!.url).toBe('https://api.anthropic.com/api/oauth/usage')
- expect(d.calls[0]!.headers.Authorization).toMatch(/^Bearer /)
- expect(r.state).toBe('ok')
- expect(r.plan).toBe('Max 20x')
- expect(r.limits).toEqual([
- { label: 'Session (5-hour)', percent: 0.07, resetsAt: '2026-09-30T15:00:00.000Z' },
- { label: 'Weekly (7-day)', percent: 0.32, resetsAt: '2026-10-04T10:00:00.000Z' },
- ])
- expect(JSON.stringify(r)).not.toContain('SECRET')
- })
- it('an HTTP error says so and never echoes the token', async () => {
- const d = deps({ '/h/.claude/.credentials.json': creds }, { fetchJson: async () => ({ status: 429, body: null }) })
- const r = await readClaude(d)
- expect(r.state).toBe('error')
- expect(r.status).toMatch(/429/)
- expect(JSON.stringify(r)).not.toContain('SECRET')
- })
- it('on macOS the token comes from the login keychain, read only', async () => {
- const seen: string[][] = []
- const d = deps({ '/h/.claude/x': '' }, {
- platform: 'darwin',
- execFile: async (cmd, args) => { seen.push([cmd, ...args]); return creds },
- fetchJson: async () => ({ status: 200, body: { seven_day: { utilization: 0.5, resets_at: '2026-10-04T10:00:00Z' } } }),
- })
- const r = await readClaude(d)
- expect(seen[0]).toEqual(['security', 'find-generic-password', '-s', 'Claude Code-credentials', '-w'])
- expect(r.limits[0]!.percent).toBe(0.5)
- })
-})
-
-describe('codex', () => {
- const line = (ts: string, rl: unknown) => JSON.stringify({ timestamp: ts, type: 'event_msg', payload: { type: 'token_count', rate_limits: rl } })
- it('takes the newest rate_limits snapshot from the newest rollout, no network', async () => {
- const f = '/h/.codex/sessions/2026/09/30/rollout-2026-09-30T10-00-00-abc.jsonl'
- const old = '/h/.codex/sessions/2026/09/29/rollout-2026-09-29T10-00-00-abc.jsonl'
- const d = deps({
- [old]: line('2026-09-29T10:00:00Z', { primary: { used_percent: 1, window_minutes: 10080, resets_at: 1791308664 } }),
- [f]: [
- line('2026-09-30T10:00:00Z', { primary: { used_percent: 12, window_minutes: 10080, resets_at: 1791308664 } }),
- line('2026-09-30T11:00:00Z', { primary: { used_percent: 16, window_minutes: 10080, resets_at: 1791308664 }, secondary: { used_percent: 40, window_minutes: 300, resets_at: 1790780000 }, plan_type: 'pro' }),
- '{"not json',
- ].join('\n'),
- })
- const r = await readCodex(d)
- expect(r.state).toBe('ok')
- expect(r.plan).toBe('pro')
- expect(r.limits[0]).toEqual({ label: 'Weekly (7-day)', percent: 0.16, resetsAt: new Date(1791308664000).toISOString() })
- expect(r.limits[1]!.label).toBe('Session (5-hour)')
- expect(r.measuredAt).toBe(Date.parse('2026-09-30T11:00:00Z'))
- expect(d.calls).toHaveLength(0)
- })
- it('sessions but no snapshot yet is detected with a remedy', async () => {
- const r = await readCodex(deps({ '/h/.codex/sessions/2026/09/30/rollout-x.jsonl': '{}' }))
- expect(r.state).toBe('not-configured')
- })
-})
-
-describe('grok', () => {
- it('reads the newest billing snapshot, with its own period start', async () => {
- const snap = (pct: number, end: string) => JSON.stringify({ ts: '2026-09-28T02:03:03.932Z', msg: 'billing: fetched credits config', ctx: { config: { creditUsagePercent: pct, currentPeriod: { start: '2026-09-24T03:10:03Z', end } }, subscriptionTier: 'SuperGrok Plus' } })
- const r = await readGrok(deps({ '/h/.grok/logs/unified.jsonl': ['{"msg":"other"}', snap(1, '2026-10-01T03:10:03Z'), snap(3, '2026-10-01T03:10:03Z')].join('\n') }))
- expect(r.state).toBe('ok')
- expect(r.snapshot).toBe(true)
- expect(r.plan).toBe('SuperGrok Plus')
- expect(r.limits).toEqual([{ label: 'Weekly (7-day)', percent: 0.03, resetsAt: '2026-10-01T03:10:03.000Z', startsAt: '2026-09-24T03:10:03.000Z' }])
- })
- it('a snapshot with no percentage is unknown, never a confident zero', async () => {
- const line = JSON.stringify({ ts: '2026-09-28T02:03:03Z', msg: 'billing: fetched credits config', ctx: { config: { currentPeriod: { end: '2026-10-01T03:10:03Z' } } } })
- const r = await readGrok(deps({ '/h/.grok/logs/unified.jsonl': line }))
- expect(r.limits[0]!.percent).toBe(-1)
- })
- it('a window that has reset since the snapshot says so', async () => {
- const line = JSON.stringify({ ts: '2026-09-20T02:03:03Z', msg: 'billing: fetched credits config', ctx: { config: { creditUsagePercent: 50, currentPeriod: { end: '2026-09-25T03:10:03Z' } } } })
- const r = await readGrok(deps({ '/h/.grok/logs/unified.jsonl': line }))
- expect(r.status).toMatch(/reset/)
- })
-})
-
-describe('kimi', () => {
- const usages = { limits: [{ window: { duration: 300, timeUnit: 'TIME_UNIT_MINUTE' }, detail: { limit: '100', used: '9', resetTime: '2026-09-30T08:43:48Z' } }], usages: { limit_5h: { used_ratio: 0, reset_time: '2026-09-30T08:43:47Z' }, limit_month_total: { used_ratio: 0.0711, reset_time: '2026-10-19T00:00:00Z' }, limit_month_code: { used_ratio: 0, reset_time: '2026-10-19T00:00:00Z' } } }
- it('uses KIMI_API_KEY from ~/.env and maps the request window and month', async () => {
- const d = deps({ '/h/.env': '# x\nKIMI_API_KEY="kimi-secret-key-value"\nOTHER=1\n' }, {
- fetchJson: async (url, headers) => { d.calls.push({ url, headers }); return { status: 200, body: usages } },
- })
- const r = await readKimi(d)
- expect(d.calls[0]!.url).toBe('https://api.kimi.com/coding/v1/usages')
- expect(r.state).toBe('ok')
- expect(r.limits.map((l) => l.label)).toEqual(['Session (5-hour)', 'Monthly (total)', 'Monthly (code)'])
- expect(r.limits[0]!.percent).toBeCloseTo(0.09, 9)
- expect(r.limits[1]!.percent).toBeCloseTo(0.0711, 9)
- expect(JSON.stringify(r)).not.toContain('kimi-secret')
- })
- it('refuses a non-https base URL rather than sending the key in clear', async () => {
- const d = deps({}, { env: { KIMI_API_KEY: 'k', KIMI_BASE_URL: 'http://evil.example' } })
- const r = await readKimi(d)
- expect(r.state).toBe('error')
- expect(d.calls).toHaveLength(0)
- })
-})
diff --git a/cli/src/fleet/subscriptions/providers.ts b/cli/src/fleet/subscriptions/providers.ts
deleted file mode 100644
index 2d150aee6..000000000
--- a/cli/src/fleet/subscriptions/providers.ts
+++ /dev/null
@@ -1,316 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-/**
- * One reader per subscription provider. Each answers the same question, "what does this plan's own
- * meter say right now", from the one source that provider really publishes, and says plainly when the
- * provider is not on this machine at all.
- *
- * Sources, ported from Burn Bar (https://github.com/nixfred/burnbar) and the collectors it reads, but
- * reimplemented here so neither Burn Bar nor Omarchy has to be installed (Linux or macOS):
- *
- * Claude GET https://api.anthropic.com/api/oauth/usage with the Claude Code login's own OAuth token,
- * read from ~/.claude/.credentials.json (or $CLAUDE_CONFIG_DIR), or on macOS from the login
- * keychain item "Claude Code-credentials" via `security find-generic-password -w`.
- * Codex no network: the newest `rate_limits` snapshot Codex itself writes into its session rollouts
- * under ~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl (or $CODEX_HOME).
- * Grok no network: the newest "billing: fetched credits config" line in ~/.grok/logs/unified.jsonl
- * (or $GROK_HOME). A snapshot: Grok writes it when Grok starts, not on every use.
- * Kimi GET {KIMI_BASE_URL or https://api.kimi.com/coding/v1}/usages with KIMI_API_KEY from the
- * environment or a KIMI_API_KEY= line in ~/.env.
- *
- * Every credential read is local and read-only. A token only ever goes into the Authorization header of
- * its own provider's HTTPS request: it is never returned, logged, or put on a command line.
- */
-import { normPercent, parseIsoMs, type LimitRow } from './pace.js'
-
-export type ProviderId = 'claude' | 'codex' | 'grok' | 'kimi'
-export const PROVIDERS: ReadonlyArray<{ id: ProviderId; name: string }> = [
- { id: 'claude', name: 'Claude' },
- { id: 'codex', name: 'Codex' },
- { id: 'grok', name: 'Grok' },
- { id: 'kimi', name: 'Kimi' },
-]
-
-export type ReadingState = 'ok' | 'not-detected' | 'not-configured' | 'error'
-
-export interface ProviderReading {
- id: ProviderId
- name: string
- state: ReadingState
- plan: string
- limits: LimitRow[]
- /** A snapshot cannot be re-measured on demand (Grok): it needs a bigger margin before it is advice. */
- snapshot: boolean
- measuredAt: number
- /** One short line for the card: why a figure is missing, or its age. Never contains a secret. */
- status: string
- /** The remedy, when there is one. */
- help: string
-}
-
-export interface ProviderDeps {
- home: string
- platform: NodeJS.Platform
- env: Record<string, string | undefined>
- now(): number
- /** Whole file as text, or null when missing or unreadable. */
- readFile(path: string): Promise<string | null>
- /** The last `bytes` of a file as text, or null. */
- readTail(path: string, bytes: number): Promise<string | null>
- /** Entry names, or [] when missing. */
- listDir(path: string): Promise<string[]>
- exists(path: string): Promise<boolean>
- fetchJson(url: string, headers: Record<string, string>, timeoutMs: number): Promise<{ status: number; body: unknown }>
- /** stdout, or null on any failure. Used only for the macOS keychain read. */
- execFile(cmd: string, args: string[], timeoutMs: number): Promise<string | null>
-}
-
-const nameOf = (id: ProviderId): string => PROVIDERS.find((p) => p.id === id)!.name
-const reading = (id: ProviderId, state: ReadingState, extra: Partial<ProviderReading> = {}): ProviderReading =>
- ({ id, name: nameOf(id), state, plan: '', limits: [], snapshot: false, measuredAt: 0, status: '', help: '', ...extra })
-const join = (...parts: string[]): string => parts.join('/').replace(/\/+/g, '/')
-const isoOrEmpty = (v: unknown): string => { const ms = resetMs(v); return ms ? new Date(ms).toISOString() : '' }
-
-/** A reset as epoch seconds, epoch ms, or ISO text. */
-function resetMs(v: unknown): number {
- if (v === null || v === undefined || v === '') return 0
- if (typeof v === 'number' || /^\d+$/.test(String(v).trim())) {
- const n = Number(v)
- if (!Number.isFinite(n) || n <= 0) return 0
- return n < 1e12 ? n * 1000 : n
- }
- return parseIsoMs(v)
-}
-
-function asObj(v: unknown): Record<string, unknown> | null {
- return v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : null
-}
-
-// ── Claude ───────────────────────────────────────────────────────────────────────────────────────
-
-export const CLAUDE_USAGE_URL = 'https://api.anthropic.com/api/oauth/usage'
-
-function claudePlan(tier: string, sub: string): string {
- const m = /max_(\d+x)/i.exec(tier)
- if (m) return `Max ${m[1]}`
- return sub ? sub[0]!.toUpperCase() + sub.slice(1) : ''
-}
-
-export async function readClaude(deps: ProviderDeps): Promise<ProviderReading> {
- const dir = deps.env.CLAUDE_CONFIG_DIR || join(deps.home, '.claude')
- let raw = await deps.readFile(join(dir, '.credentials.json'))
- if (!raw && deps.platform === 'darwin') raw = await deps.execFile('security', ['find-generic-password', '-s', 'Claude Code-credentials', '-w'], 5000)
- let login: Record<string, unknown> | null = null
- try { login = asObj(asObj(JSON.parse(raw ?? 'null'))?.claudeAiOauth) } catch { login = null }
- const token = typeof login?.accessToken === 'string' ? login.accessToken : ''
- if (!token) {
- if (!(await deps.exists(dir))) return reading('claude', 'not-detected')
- return reading('claude', 'not-configured', { status: 'No Claude Code login found', help: 'Run `claude` and sign in with a Claude subscription' })
- }
- const plan = claudePlan(String(login?.rateLimitTier ?? ''), String(login?.subscriptionType ?? ''))
- let res: { status: number; body: unknown }
- try {
- res = await deps.fetchJson(CLAUDE_USAGE_URL, { Authorization: `Bearer ${token}`, 'anthropic-beta': 'oauth-2025-04-20', Accept: 'application/json' }, 10_000)
- } catch { res = { status: 0, body: null } }
- if (res.status !== 200) {
- const why = res.status === 0 || res.status >= 599 ? 'could not reach Anthropic' : `usage endpoint returned ${res.status}`
- return reading('claude', 'error', { plan, status: `Claude ${why}`, help: res.status === 401 ? 'Run `claude` and sign in again' : '' })
- }
- const body = asObj(res.body) ?? {}
- const weekly = asObj(body.seven_day_oauth_apps) ?? asObj(body.seven_day)
- const session = asObj(body.five_hour)
- // One payload speaks one convention: any value >= 1 means the whole payload is percent-scaled.
- const rawVals = [session?.utilization, weekly?.utilization].map((v) => Number(v))
- const percentScale = rawVals.some((v) => v >= 1)
- const norm = (v: unknown): number => {
- const n = Number(v)
- if (!(n >= 0)) return -1
- return Math.min(1, percentScale || n > 1 ? n / 100 : n)
- }
- const limits: LimitRow[] = []
- if (session && norm(session.utilization) >= 0) limits.push({ label: 'Session (5-hour)', percent: norm(session.utilization), resetsAt: isoOrEmpty(session.resets_at) })
- if (weekly && norm(weekly.utilization) >= 0) limits.push({ label: 'Weekly (7-day)', percent: norm(weekly.utilization), resetsAt: isoOrEmpty(weekly.resets_at) })
- if (!limits.length) return reading('claude', 'error', { plan, status: 'Anthropic returned no limits' })
- return reading('claude', 'ok', { plan, limits, measuredAt: deps.now() })
-}
-
-// ── Codex ────────────────────────────────────────────────────────────────────────────────────────
-
-const CODEX_TAIL_BYTES = 512 * 1024
-const CODEX_FILES_TO_TRY = 6
-
-function codexLabel(mins: number): string {
- if (mins === 10080) return 'Weekly (7-day)'
- if (mins === 300) return 'Session (5-hour)'
- if (mins && mins % 1440 === 0) return `${mins / 1440}-day window`
- if (mins && mins % 60 === 0) return `${mins / 60}-hour window`
- return mins ? `${mins}m window` : 'Limit'
-}
-
-/** The newest rollout files, newest first, walking YYYY/MM/DD in descending order. */
-async function newestRollouts(deps: ProviderDeps, root: string, want: number): Promise<string[]> {
- const out: string[] = []
- const desc = (xs: string[]) => xs.filter((x) => /^\d+$/.test(x)).sort((a, b) => Number(b) - Number(a))
- for (const y of desc(await deps.listDir(root))) {
- for (const m of desc(await deps.listDir(join(root, y)))) {
- for (const d of desc(await deps.listDir(join(root, y, m)))) {
- const files = (await deps.listDir(join(root, y, m, d))).filter((f) => f.startsWith('rollout-') && f.endsWith('.jsonl')).sort().reverse()
- for (const f of files) { out.push(join(root, y, m, d, f)); if (out.length >= want) return out }
- }
- }
- }
- return out
-}
-
-export async function readCodex(deps: ProviderDeps): Promise<ProviderReading> {
- const home = deps.env.CODEX_HOME || join(deps.home, '.codex')
- const root = join(home, 'sessions')
- if (!(await deps.exists(root))) return reading('codex', 'not-detected')
- // Rollout names sort by start time, but a long session keeps writing into an older file, so the
- // newest few are all read and the snapshot with the latest timestamp wins.
- let best: { at: number; rl: Record<string, unknown> } | null = null
- for (const file of await newestRollouts(deps, root, CODEX_FILES_TO_TRY)) {
- const text = await deps.readTail(file, CODEX_TAIL_BYTES)
- if (!text) continue
- const lines = text.split('\n')
- for (let i = lines.length - 1; i >= 0; i--) {
- const line = lines[i]!
- if (!line.includes('"rate_limits"')) continue
- let obj: Record<string, unknown> | null
- try { obj = asObj(JSON.parse(line)) } catch { continue }
- const rl = asObj(asObj(obj?.payload)?.rate_limits) ?? asObj(obj?.rate_limits)
- if (!rl || !asObj(rl.primary)) continue
- const at = parseIsoMs(obj?.timestamp)
- if (!best || at > best.at) best = { at, rl }
- break
- }
- }
- if (!best) return reading('codex', 'not-configured', { status: 'No Codex rate-limit snapshot yet', help: 'Run one Codex turn signed in with a ChatGPT plan' })
- const limits: LimitRow[] = []
- for (const key of ['primary', 'secondary']) {
- const w = asObj(best.rl[key])
- if (!w || w.used_percent === undefined || w.used_percent === null) continue
- let resets = resetMs(w.resets_at)
- // Older Codex builds wrote a relative reset; anchor it to the line's own timestamp.
- if (!resets && Number(w.resets_in_seconds) > 0 && best.at) resets = best.at + Number(w.resets_in_seconds) * 1000
- limits.push({ label: codexLabel(Number(w.window_minutes) || 0), percent: normPercent(Number(w.used_percent) / 100), resetsAt: resets ? new Date(resets).toISOString() : '' })
- }
- // Weekly first, so the card judges the plan by its week.
- limits.sort((a, b) => (/^weekly/i.test(b.label) ? 1 : 0) - (/^weekly/i.test(a.label) ? 1 : 0))
- const plan = typeof best.rl.plan_type === 'string' ? best.rl.plan_type : ''
- const open = limits.some((l) => parseIsoMs(l.resetsAt) > deps.now())
- return reading('codex', 'ok', {
- plan, limits, measuredAt: best.at,
- status: open ? '' : 'Codex window has reset since the last turn; run Codex to refresh',
- })
-}
-
-// ── Grok ─────────────────────────────────────────────────────────────────────────────────────────
-
-const GROK_TAIL_BYTES = 8 * 1024 * 1024
-const GROK_MARK = 'billing: fetched credits config'
-
-export async function readGrok(deps: ProviderDeps): Promise<ProviderReading> {
- const home = deps.env.GROK_HOME || join(deps.home, '.grok')
- if (!(await deps.exists(home))) return reading('grok', 'not-detected')
- const text = await deps.readTail(join(home, 'logs', 'unified.jsonl'), GROK_TAIL_BYTES)
- let latest: { config: Record<string, unknown>; tier: string; at: number } | null = null
- for (const line of (text ?? '').split('\n')) {
- if (!line.includes(GROK_MARK)) continue
- let e: Record<string, unknown> | null
- try { e = asObj(JSON.parse(line)) } catch { continue }
- if (!e || e.msg !== GROK_MARK) continue
- const ctx = asObj(e.ctx)
- const config = asObj(ctx?.config)
- if (!config) continue
- latest = { config, tier: typeof ctx?.subscriptionTier === 'string' ? ctx.subscriptionTier : '', at: parseIsoMs(e.ts) }
- }
- if (!latest) return reading('grok', 'not-configured', { snapshot: true, status: 'No Grok billing snapshot yet', help: 'Start Grok once while signed in' })
- const period = asObj(latest.config.currentPeriod) ?? {}
- const end = isoOrEmpty(period.end ?? latest.config.billingPeriodEnd)
- const start = isoOrEmpty(period.start ?? latest.config.billingPeriodStart)
- const raw = latest.config.creditUsagePercent
- // Grok logs 0..100. A config without the figure is unknown, not a confident 0%.
- const percent = raw === undefined || raw === null || typeof raw === 'boolean' ? -1 : normPercent(Number(raw) / 100)
- const row: LimitRow = { label: 'Weekly (7-day)', percent, resetsAt: end }
- if (start) row.startsAt = start
- const open = !end || parseIsoMs(end) > deps.now()
- return reading('grok', 'ok', {
- plan: latest.tier, limits: [row], snapshot: true, measuredAt: latest.at,
- status: open ? '' : 'Grok window has reset since the last snapshot; start Grok to refresh',
- })
-}
-
-// ── Kimi ─────────────────────────────────────────────────────────────────────────────────────────
-
-export const KIMI_DEFAULT_BASE = 'https://api.kimi.com/coding/v1'
-
-/** KEY from the environment, else a KEY= line in ~/.env. Only the named keys are ever looked at. */
-async function envOrDotenv(deps: ProviderDeps, key: string): Promise<string> {
- const v = (deps.env[key] ?? '').trim()
- if (v) return v
- const text = await deps.readFile(join(deps.home, '.env'))
- for (const raw of (text ?? '').split('\n')) {
- const line = raw.trim().replace(/^export\s+/, '')
- if (line.startsWith(`${key}=`)) return line.slice(key.length + 1).trim().replace(/^["']|["']$/g, '')
- }
- return ''
-}
-
-function kimiWindowLabel(w: Record<string, unknown> | null): string {
- let n = Number(w?.duration) || 0
- let unit = String(w?.timeUnit ?? '').replace('TIME_UNIT_', '').toLowerCase()
- if (n <= 0 || !unit) return ''
- if (unit === 'minute' && n % 60 === 0) { n /= 60; unit = 'hour' }
- return `${n}-${unit}`
-}
-
-/** Burn Bar's rows from Kimi's /usages: the request window binds the session; the month is the budget. */
-export function kimiLimitsFromUsages(raw: unknown): LimitRow[] {
- const body = asObj(raw) ?? {}
- const out: LimitRow[] = []
- const seen = new Set<string>()
- for (const entry of Array.isArray(body.limits) ? body.limits : []) {
- const e = asObj(entry)
- const label = kimiWindowLabel(asObj(e?.window))
- const detail = asObj(e?.detail) ?? {}
- const limit = Number(detail.limit) || 0
- const used = Number(detail.used) || 0
- if (!label || limit <= 0) continue
- seen.add(label)
- out.push({ label: `Session (${label})`, percent: Math.max(0, Math.min(1, used / limit)), resetsAt: isoOrEmpty(detail.resetTime) })
- }
- const names: Array<[string, string, string]> = [['limit_5h', 'Session (5-hour)', '5-hour'], ['limit_month_total', 'Monthly (total)', ''], ['limit_month_code', 'Monthly (code)', '']]
- const usages = asObj(body.usages) ?? {}
- for (const [key, label, span] of names) {
- const e = asObj(usages[key])
- if (!e || (span && seen.has(span))) continue
- const ratio = Number(e.used_ratio)
- if (!Number.isFinite(ratio)) continue
- out.push({ label, percent: Math.max(0, Math.min(1, ratio)), resetsAt: isoOrEmpty(e.reset_time) })
- }
- return out
-}
-
-export async function readKimi(deps: ProviderDeps): Promise<ProviderReading> {
- const key = await envOrDotenv(deps, 'KIMI_API_KEY')
- if (!key) return reading('kimi', 'not-detected')
- const base = ((await envOrDotenv(deps, 'KIMI_BASE_URL')) || KIMI_DEFAULT_BASE).replace(/\/+$/, '')
- // The key never travels in clear text, except to this machine itself.
- if (!/^https:\/\//.test(base) && !/^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?\//.test(`${base}/`)) {
- return reading('kimi', 'error', { status: 'KIMI_BASE_URL must be https', help: 'Fix KIMI_BASE_URL' })
- }
- let res: { status: number; body: unknown }
- try { res = await deps.fetchJson(`${base}/usages`, { Authorization: `Bearer ${key}`, Accept: 'application/json' }, 8000) } catch { res = { status: 0, body: null } }
- if (res.status !== 200) {
- const why = res.status === 0 || res.status >= 599 ? 'could not reach Kimi' : `usages endpoint returned ${res.status}`
- return reading('kimi', 'error', { status: `Kimi ${why}`, help: res.status === 401 ? 'Check KIMI_API_KEY' : '' })
- }
- const limits = kimiLimitsFromUsages(res.body)
- if (!limits.length) return reading('kimi', 'error', { status: 'Kimi returned no limits' })
- return reading('kimi', 'ok', { limits, measuredAt: deps.now() })
-}
-
-export const READERS: Record<ProviderId, (deps: ProviderDeps) => Promise<ProviderReading>> = {
- claude: readClaude, codex: readCodex, grok: readGrok, kimi: readKimi,
-}
diff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.ts
index 0568b8dd6..50b846a42 100644
--- a/cli/src/hookNotify.spec.ts
+++ b/cli/src/hookNotify.spec.ts
@@ -1169,20 +1169,3 @@ describe('hook notify Command Code re-registration', () => {
expect(requests.map((r) => r.url)).toEqual(['/api/hook/turn-stop'])
})
})
-
-// The destructive-action gate (cli/src/lib/actionPolicy.ts; first written by Fred Nix in the nixfred fork).
-describe('claude PreToolUse gate', () => {
- const input = { hook_event_name: 'PreToolUse', session_id: 'claude-session', tool_name: 'Bash', tool_use_id: 'toolu_1', tool_input: { command: 'git push origin main' } }
- it('turns the daemon\'s ask verdict into Claude\'s own permission prompt', async () => {
- const { port, requests } = await collect({ ok: true, gate: { decision: 'ask', rule: 'git push', reason: 'git push needs your approval' } })
- const stdout = await runHook({ port, tmuxPane: '%7', input })
- expect(JSON.parse(stdout)).toEqual({ hookSpecificOutput: {
- hookEventName: 'PreToolUse', permissionDecision: 'ask', permissionDecisionReason: 'Harness gate: git push needs your approval',
- } })
- expect(requests.find((r) => r.url === '/api/hook/tool-start')?.body).toMatchObject({ sessionId: 'claude-session', toolName: 'Bash', input: { command: 'git push origin main' } })
- })
- it('stays silent (allow) when the daemon says nothing about the call', async () => {
- const { port } = await collect({ ok: true })
- expect(await runHook({ port, tmuxPane: '%7', input })).toBe('')
- })
-})
diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.ts
index 987044f48..293795607 100644
--- a/cli/src/hookServer.spec.ts
+++ b/cli/src/hookServer.spec.ts
@@ -802,44 +802,3 @@ describe('the device history and dismiss endpoints', () => {
expect((await post({ confirm: true, head: 'x' })).status).toBe(400)
})
})
-
-describe('fleet controls: /api/attention, /api/stop-all, /api/fleet', () => {
- const local = { 'content-type': 'application/json', 'x-adapter-local': '1' }
- it('serves the attention snapshot read-only, and an empty one when nothing is wired', async () => {
- const { base } = await start({ onAttention: () => ({ agents: [{ agentId: 'a', state: 'waiting' }] }) })
- expect(await (await fetch(`${base}/api/attention`)).json()).toEqual({ agents: [{ agentId: 'a', state: 'waiting' }] })
- server?.close()
- const bare = await start()
- expect(await (await fetch(`${bare.base}/api/attention`)).json()).toEqual({ agents: [] })
- })
- it('runs the panic stop only for a local caller, keeping the agent named', async () => {
- const onStopAll = vi.fn(async () => ({ cancelled: ['b'] }))
- const { base } = await start({ onStopAll })
- expect((await fetch(`${base}/api/stop-all`, { method: 'POST', body: '{}' })).status).toBe(403)
- expect(onStopAll).not.toHaveBeenCalled()
- const res = await fetch(`${base}/api/stop-all`, { method: 'POST', headers: local, body: JSON.stringify({ except: 'a' }) })
- expect(await res.json()).toEqual({ cancelled: ['b'] })
- expect(onStopAll).toHaveBeenCalledExactlyOnceWith('a')
- })
- it('hands a named action to the fleet handler and reports its error', async () => {
- const onFleet = vi.fn(async (action: string) => { if (action === 'boom') throw new Error('no such thing'); return { action } })
- const { base } = await start({ onFleet })
- const ok = await fetch(`${base}/api/fleet`, { method: 'POST', headers: local, body: JSON.stringify({ action: 'attention', x: 1 }) })
- expect(await ok.json()).toEqual({ ok: true, result: { action: 'attention' } })
- expect(onFleet).toHaveBeenCalledWith('attention', { x: 1 })
- const bad = await fetch(`${base}/api/fleet`, { method: 'POST', headers: local, body: JSON.stringify({ action: 'boom' }) })
- expect(bad.status).toBe(400)
- expect(await bad.json()).toEqual({ ok: false, error: 'no such thing' })
- expect((await fetch(`${base}/api/fleet`, { method: 'POST', headers: local, body: JSON.stringify({}) })).status).toBe(400)
- })
-})
-
-describe('fleet controls: /api/subscriptions', () => {
- it('serves the plans when wired, and says unavailable otherwise', async () => {
- const { base } = await start({ onSubscriptions: async () => ({ subs: [{ id: 'claude', used: 0.4 }] }) })
- expect(await (await fetch(`${base}/api/subscriptions?force=0`)).json()).toEqual({ subs: [{ id: 'claude', used: 0.4 }] })
- server?.close()
- const bare = await start()
- expect((await fetch(`${bare.base}/api/subscriptions`)).status).toBe(503)
- })
-})
diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.ts
index 162a391f5..2928a960e 100644
--- a/cli/src/hookServer.ts
+++ b/cli/src/hookServer.ts
@@ -13,7 +13,6 @@ import { hermesSessionSource, isHermesInteractiveSource } from './engines/hermes
import { hermesDbPath, listHermesHomes } from './engines/hermes/home.js'
import { isRecentlyDeleted } from './lib/deletedSessions.js'
import { registry, type RegisterInput, type RegisteredSession } from './lib/registry.js'
-import type { GateVerdict } from './lib/actionPolicy.js'
import { LOCAL_WEB_HTML } from './webui.js'
import { sid } from './lib/log.js'
import { VERSION } from './version.js'
@@ -116,15 +115,7 @@ export interface HookServerHandlers {
toolUseId: string
toolName: string
input: unknown
- }) => void | GateVerdict | Promise<void | GateVerdict>
- /** GET /api/attention: every agent's attention state for the bar widget and other local readers. */
- onAttention?: () => unknown
- /** GET /api/subscriptions: every plan's weekly used, banked, reset and the next-plan verdict. */
- onSubscriptions?: () => Promise<unknown>
- /** POST /api/stop-all: cancel every agent's turn except one (the panic stop). */
- onStopAll?: (exceptAgentId: string | null) => Promise<{ cancelled: string[] }>
- /** POST /api/fleet {action, ...args}: the local command surface behind the fleet `harness` commands. */
- onFleet?: (action: string, args: Record<string, unknown>) => Promise<unknown>
+ }) => void
onTurnStop?: (body: {
sessionId: string
status?: string
@@ -509,38 +500,6 @@ export function startHookServer(
if (req.method === 'GET' && url === '/api/status') {
json(200, handlers.onStatus ? await handlers.onStatus() : { supported: false }); return
}
- // Attention snapshot for the bar widget and any local reader: loopback only, read-only, no
- // secrets (names, engines, states). Same trust as /api/status.
- if (req.method === 'GET' && url === '/api/attention') {
- json(200, handlers.onAttention ? handlers.onAttention() : { agents: [] }); return
- }
- if (req.method === 'GET' && (url === '/api/subscriptions' || url.startsWith('/api/subscriptions?'))) {
- if (!handlers.onSubscriptions) { json(503, { error: 'UNAVAILABLE' }); return }
- try { json(200, await handlers.onSubscriptions()) } catch (e) { json(500, { error: e instanceof Error ? e.message : 'INTERNAL' }) }
- return
- }
- // Panic stop: every agent's turn is cancelled except the one named. Mutating, so the same
- // same-origin guard as the other local mutations.
- if (req.method === 'POST' && url === '/api/stop-all') {
- if (!localOk) { json(403, { error: 'FORBIDDEN' }); return }
- if (!handlers.onStopAll) { json(503, { error: 'UNAVAILABLE' }); return }
- let body: { except?: string } = {}
- try { const raw = await readBody(req); body = raw ? JSON.parse(raw) as { except?: string } : {} } catch { json(400, { error: 'bad json' }); return }
- try { json(200, await handlers.onStopAll(typeof body.except === 'string' && body.except ? body.except : null)) }
- catch (e) { json(500, { error: e instanceof Error ? e.message : 'INTERNAL' }) }
- return
- }
- if (req.method === 'POST' && url === '/api/fleet') {
- if (!localOk) { json(403, { error: 'FORBIDDEN' }); return }
- if (!handlers.onFleet) { json(503, { error: 'UNAVAILABLE' }); return }
- let body: { action?: unknown } & Record<string, unknown>
- try { body = JSON.parse(await readBody(req)) as typeof body } catch { json(400, { error: 'bad json' }); return }
- if (typeof body.action !== 'string' || !/^[a-z][a-z0-9-]{1,40}$/.test(body.action)) { json(400, { error: 'MISSING_ACTION' }); return }
- const { action, ...args } = body
- try { json(200, { ok: true, result: await handlers.onFleet(action, args) }) }
- catch (e) { json(400, { ok: false, error: e instanceof Error ? e.message : String(e) }) }
- return
- }
if (req.method === 'GET' && url === '/api/logs') {
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); res.end(handlers.onLogs ? handlers.onLogs() : ''); return
}
@@ -713,24 +672,16 @@ export function startHookServer(
body = parsed
} catch { json(400, { error: 'bad json' }); return }
if (!await verifiedBoundMutation(body, handlers)) { json(403, { error: 'UNBOUND_HOOK' }); return }
- let gate: GateVerdict | undefined
if (body.sessionId && body.toolUseId && body.toolName) {
console.log(`[hooks] ${sid(body.sessionId)} tool-start · tool=${body.toolName}`)
- try {
- const verdict = await handlers.onToolStart?.({
- sessionId: body.sessionId,
- toolUseId: body.toolUseId,
- toolName: body.toolName,
- input: body.input,
- })
- if (verdict && verdict.decision !== 'allow') gate = verdict
- } catch (e) {
- console.error('[hooks] tool-start handler failed:', e instanceof Error ? e.message : e)
- }
+ handlers.onToolStart?.({
+ sessionId: body.sessionId,
+ toolUseId: body.toolUseId,
+ toolName: body.toolName,
+ input: body.input,
+ })
}
- // The gate verdict rides back to the hook script, which turns it into the engine's own
- // permission prompt. Allow is the absence of the field, so an older script sees `{ok:true}`.
- json(200, gate ? { ok: true, gate } : { ok: true })
+ json(200, { ok: true })
return
}
diff --git a/cli/src/lib/actionPolicy.spec.ts b/cli/src/lib/actionPolicy.spec.ts
deleted file mode 100644
index b9ca31919..000000000
--- a/cli/src/lib/actionPolicy.spec.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-import { describe, expect, it } from 'vitest'
-import { DEFAULT_POLICY, claudePreToolUseOutput, evaluateToolCall, flattenToolInput, parsePolicy } from './actionPolicy.js'
-
-const bash = (command: string) => evaluateToolCall(DEFAULT_POLICY, 'Bash', { command })
-
-describe('evaluateToolCall with the default policy', () => {
- it('allows ordinary commands', () => {
- expect(bash('git status && npm test').decision).toBe('allow')
- expect(bash('ls -la ~/Projects').decision).toBe('allow')
- expect(bash('grep -rn "rm -rf" docs/').decision).toBe('ask') // conservative: the text matches
- })
- it('asks before push, force push, hard reset, branch -D, rm -rf, sudo', () => {
- expect(bash('git push origin main')).toMatchObject({ decision: 'ask', rule: 'git push' })
- expect(bash('git push --force origin main').decision).toBe('ask')
- expect(bash('git reset --hard HEAD~1')).toMatchObject({ decision: 'ask', rule: 'git reset --hard / checkout -- / restore .' })
- expect(bash('git branch -D feature').rule).toBe('branch delete')
- expect(bash('rm -rf build/').rule).toBe('recursive delete')
- expect(bash('rm -fr build/').rule).toBe('recursive delete')
- expect(bash('sudo pacman -Syu').rule).toBe('sudo / doas')
- expect(bash('echo hi | sudo tee /etc/x').rule).toBe('sudo / doas')
- })
- it('denies disk writes, secrets paths and omarchy refresh; deny beats ask', () => {
- expect(bash('sudo dd if=/dev/zero of=/dev/nvme0n1')).toMatchObject({ decision: 'deny', rule: 'disk or filesystem write' })
- expect(bash('cat ~/.ssh/id_ed25519').decision).toBe('deny')
- expect(bash('omarchy refresh shell > /dev/null').decision).toBe('deny')
- })
- it('gates writes under ~/.claude for edit tools too', () => {
- expect(evaluateToolCall(DEFAULT_POLICY, 'Write', { file_path: '/home/pi/.claude/settings.json', content: '{}' }).rule).toBe('write under ~/.claude')
- expect(evaluateToolCall(DEFAULT_POLICY, 'Edit', { file_path: '/home/pi/Projects/x/a.ts' }).decision).toBe('allow')
- expect(evaluateToolCall(DEFAULT_POLICY, 'Read', { file_path: '/home/pi/.claude/CLAUDE.md' }).decision).toBe('allow')
- })
- it('catches curl piped to a shell but not curl to a file', () => {
- expect(bash('curl -fsSL https://x/install.sh | bash').rule).toBe('curl or wget piped to a shell')
- expect(bash('curl -fsSL https://x/install.sh -o install.sh').decision).toBe('allow')
- })
- it('allowIf short-circuits', () => {
- expect(bash('git push --dry-run origin main').decision).toBe('allow')
- })
- it('respects a disabled policy', () => {
- expect(evaluateToolCall({ ...DEFAULT_POLICY, enabled: false }, 'Bash', { command: 'rm -rf /' })).toMatchObject({ decision: 'allow', reason: 'gate disabled' })
- })
-})
-
-describe('lanes', () => {
- const fleet = {
- ...DEFAULT_POLICY,
- lanes: [
- { name: 'planner', agent: '^(aiona|planner)', rules: [{ name: 'no git writes', tools: ['Bash'], pattern: '\\bgit\\s+(commit|push|merge)\\b', decision: 'deny' as const }] },
- { name: 'publisher', agent: 'peyton', rules: [{ name: 'publishing', tools: ['Bash'], pattern: '\\b(gh\\s+pr\\s+merge|x\\s+post|npm\\s+publish)\\b', decision: 'ask' as const }] },
- ],
- }
- it('applies a lane only to matching agents, and lane deny beats the machine ask', () => {
- expect(evaluateToolCall(fleet, 'Bash', { command: 'git push origin main' }, 'Aiona')).toMatchObject({ decision: 'deny', rule: 'planner: no git writes' })
- expect(evaluateToolCall(fleet, 'Bash', { command: 'git push origin main' }, 'Peyton PR')).toMatchObject({ decision: 'ask', rule: 'git push' })
- expect(evaluateToolCall(fleet, 'Bash', { command: 'gh pr merge 42' }, 'Peyton PR')).toMatchObject({ decision: 'ask', rule: 'publisher: publishing' })
- expect(evaluateToolCall(fleet, 'Bash', { command: 'gh pr merge 42' }, 'Jasmine').decision).toBe('allow')
- expect(evaluateToolCall(fleet, 'Bash', { command: 'git commit -m x' }).decision).toBe('allow') // no agent name, no lane
- })
- it('validates lanes', () => {
- const bad = parsePolicy({ ...DEFAULT_POLICY, lanes: [{ name: '', agent: '(', rules: 'x' }] })
- expect(bad.ok).toBe(false)
- if (!bad.ok) expect(bad.problems).toEqual(['lanes[0].name missing', 'lanes[0].agent is not a valid regex', 'lanes[0].rules must be an array'])
- })
-})
-
-describe('flattenToolInput', () => {
- it('flattens nested objects and arrays, bounded depth', () => {
- expect(flattenToolInput({ a: 'x', b: [1, { c: 'y' }], d: null })).toBe('x\n1\ny\n')
- expect(flattenToolInput('plain')).toBe('plain')
- })
-})
-
-describe('parsePolicy', () => {
- it('accepts the default and rejects broken rules with specific problems', () => {
- expect(parsePolicy(DEFAULT_POLICY)).toEqual({ ok: true, policy: DEFAULT_POLICY })
- const bad = parsePolicy({ version: 2, enabled: 'yes', rules: [{ name: '', pattern: '(', decision: 'maybe', tools: [1] }] })
- expect(bad.ok).toBe(false)
- if (!bad.ok) expect(bad.problems).toEqual([
- 'version must be 1', 'enabled must be a boolean', 'rules[0].name missing',
- 'rules[0].pattern is not a valid regex', 'rules[0].decision must be ask or deny', 'rules[0].tools must be strings',
- ])
- })
-})
-
-describe('claudePreToolUseOutput', () => {
- it('is null for allow and the documented shape otherwise', () => {
- expect(claudePreToolUseOutput({ decision: 'allow', rule: null, reason: '' })).toBeNull()
- expect(claudePreToolUseOutput({ decision: 'ask', rule: 'git push', reason: 'git push needs your approval' })).toEqual({
- hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'ask', permissionDecisionReason: 'Harness gate: git push needs your approval' },
- })
- })
-})
diff --git a/cli/src/lib/actionPolicy.ts b/cli/src/lib/actionPolicy.ts
deleted file mode 100644
index d7263a1b2..000000000
--- a/cli/src/lib/actionPolicy.ts
+++ /dev/null
@@ -1,152 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-/**
- * The destructive-action gate. A per-machine policy file names tool calls that must be asked about or
- * refused before the engine runs them. The decision is handed back through the engine's own hook
- * (Claude Code PreToolUse `permissionDecision`), so the prompt appears in the terminal and reaches the
- * device through the question watcher that already mirrors permission dialogs. Nothing here executes;
- * it only classifies.
- */
-export type GateDecision = 'allow' | 'ask' | 'deny'
-
-export interface GateRule {
- /** Human name, shown as the reason. */
- name: string
- /** Tool names this applies to; empty means every tool. */
- tools?: string[]
- /** Regex (source) matched against the flattened tool input. */
- pattern: string
- decision: Exclude<GateDecision, 'allow'>
-}
-
-/**
- * A lane: rules that apply only to agents whose name matches. This is how a fleet says "the planner
- * never pushes, the publisher never posts without me": one policy file, one lane per role, the
- * machine-wide rules still apply underneath.
- */
-export interface GateLane {
- name: string
- /** Regex (source) matched case-insensitively against the agent's display name. */
- agent: string
- rules: GateRule[]
-}
-
-export interface ActionPolicy {
- version: 1
- enabled: boolean
- rules: GateRule[]
- /** Substrings that, when present in the flattened input, always allow (for known-safe wrappers). */
- allowIf?: string[]
- lanes?: GateLane[]
-}
-
-const HOME = '(?:~|\\$HOME|/home/[^/\\s]+|/Users/[^/\\s]+)'
-
-/** What `harness gate init` writes when no policy file exists: ask before risky writes, refuse the unrecoverable. */
-export const DEFAULT_POLICY: ActionPolicy = {
- version: 1,
- enabled: true,
- rules: [
- { name: 'git push', tools: ['Bash'], pattern: '\\bgit\\s+push\\b', decision: 'ask' },
- { name: 'force push', tools: ['Bash'], pattern: '\\bgit\\s+push\\b[^\\n]*(--force|-f\\b|\\+\\S)', decision: 'ask' },
- { name: 'git reset --hard / checkout -- / restore .', tools: ['Bash'], pattern: '\\bgit\\s+(reset\\s+--hard|checkout\\s+--\\s|restore\\s+\\.|clean\\s+-\\w*f)', decision: 'ask' },
- { name: 'branch delete', tools: ['Bash'], pattern: '\\bgit\\s+branch\\s+-D\\b', decision: 'ask' },
- { name: 'recursive delete', tools: ['Bash'], pattern: '\\brm\\s+(-[a-zA-Z]*r[a-zA-Z]*f|-[a-zA-Z]*f[a-zA-Z]*r|-r\\b|-R\\b)', decision: 'ask' },
- { name: 'sudo / doas', tools: ['Bash'], pattern: '(^|[\\s;&|])(sudo|doas)\\s', decision: 'ask' },
- { name: 'disk or filesystem write', tools: ['Bash'], pattern: '\\b(mkfs(\\.\\w+)?\\b|dd\\s+if=|wipefs\\b|fdisk\\b|parted\\b)', decision: 'deny' },
- { name: 'curl or wget piped to a shell', tools: ['Bash'], pattern: '\\b(curl|wget)\\b[^\\n|]*\\|\\s*(sudo\\s+)?(ba|z|da)?sh\\b', decision: 'ask' },
- { name: 'world-writable chmod', tools: ['Bash'], pattern: '\\bchmod\\s+(-R\\s+)?[0-7]?777\\b', decision: 'ask' },
- { name: 'kill everything', tools: ['Bash'], pattern: '\\b(pkill|killall)\\s+(-9\\s+)?(-f\\s+)?["\']?(claude|codex|tmux|harness|node)\\b', decision: 'ask' },
- { name: 'write under ~/.claude', tools: ['Bash', 'Write', 'Edit', 'MultiEdit', 'NotebookEdit'], pattern: `${HOME}/\\.claude/`, decision: 'ask' },
- { name: 'write under ~/.ssh or ~/.env', tools: ['Bash', 'Write', 'Edit', 'MultiEdit'], pattern: `${HOME}/(\\.ssh/|\\.env\\b|\\.gnupg/)`, decision: 'deny' },
- { name: 'systemd unit or service change', tools: ['Bash'], pattern: '\\bsystemctl\\s+(--user\\s+)?(enable|disable|mask|stop|restart)\\b', decision: 'ask' },
- { name: 'omarchy refresh (factory reset)', tools: ['Bash'], pattern: '\\bomarchy\\s+refresh\\b|omarchy-refresh-', decision: 'deny' },
- ],
- allowIf: ['--dry-run'],
-}
-
-/** Flatten any tool input into one searchable string (command, file_path, content, nested fields). */
-export function flattenToolInput(input: unknown, depth = 0): string {
- if (input == null) return ''
- if (typeof input === 'string') return input
- if (typeof input === 'number' || typeof input === 'boolean') return String(input)
- if (depth > 4) return ''
- if (Array.isArray(input)) return input.map((v) => flattenToolInput(v, depth + 1)).join('\n')
- if (typeof input === 'object') return Object.values(input as Record<string, unknown>).map((v) => flattenToolInput(v, depth + 1)).join('\n')
- return ''
-}
-
-export interface GateVerdict { decision: GateDecision; rule: string | null; reason: string }
-
-const compiled = new WeakMap<GateRule, RegExp>()
-function regex(rule: GateRule): RegExp {
- let re = compiled.get(rule)
- if (!re) { re = new RegExp(rule.pattern, 'i'); compiled.set(rule, re) }
- return re
-}
-
-const laneRegex = new WeakMap<GateLane, RegExp>()
-function laneMatches(lane: GateLane, agentName: string): boolean {
- let re = laneRegex.get(lane)
- if (!re) { re = new RegExp(lane.agent, 'i'); laneRegex.set(lane, re) }
- return re.test(agentName)
-}
-
-/** Deny beats ask beats allow. An `allowIf` substring short-circuits to allow. Lane rules run first. */
-export function evaluateToolCall(policy: ActionPolicy, toolName: string, input: unknown, agentName = ''): GateVerdict {
- if (!policy.enabled) return { decision: 'allow', rule: null, reason: 'gate disabled' }
- const text = flattenToolInput(input)
- if (!text) return { decision: 'allow', rule: null, reason: 'no input' }
- for (const safe of policy.allowIf ?? []) if (text.includes(safe)) return { decision: 'allow', rule: null, reason: `allowIf ${safe}` }
- let verdict: GateVerdict = { decision: 'allow', rule: null, reason: 'no rule matched' }
- const laneRules = (policy.lanes ?? []).filter((l) => agentName && laneMatches(l, agentName)).flatMap((l) => l.rules.map((r) => ({ ...r, name: `${l.name}: ${r.name}` })))
- for (const rule of [...laneRules, ...policy.rules]) {
- if (rule.tools && rule.tools.length && !rule.tools.includes(toolName)) continue
- if (!regex(rule).test(text)) continue
- if (rule.decision === 'deny') return { decision: 'deny', rule: rule.name, reason: `${rule.name} is refused by the machine policy` }
- if (verdict.decision === 'allow') verdict = { decision: 'ask', rule: rule.name, reason: `${rule.name} needs your approval` }
- }
- return verdict
-}
-
-/** Validate a parsed policy file; returns the policy or a list of problems. Unknown fields are kept. */
-export function parsePolicy(raw: unknown): { ok: true; policy: ActionPolicy } | { ok: false; problems: string[] } {
- const problems: string[] = []
- if (!raw || typeof raw !== 'object') return { ok: false, problems: ['policy must be an object'] }
- const p = raw as Record<string, unknown>
- if (p.version !== 1) problems.push('version must be 1')
- if (typeof p.enabled !== 'boolean') problems.push('enabled must be a boolean')
- if (!Array.isArray(p.rules)) problems.push('rules must be an array')
- else p.rules.forEach((r, i) => {
- const rule = r as Record<string, unknown>
- if (typeof rule.name !== 'string' || !rule.name) problems.push(`rules[${i}].name missing`)
- if (typeof rule.pattern !== 'string') problems.push(`rules[${i}].pattern missing`)
- else { try { new RegExp(rule.pattern) } catch { problems.push(`rules[${i}].pattern is not a valid regex`) } }
- if (rule.decision !== 'ask' && rule.decision !== 'deny') problems.push(`rules[${i}].decision must be ask or deny`)
- if (rule.tools !== undefined && (!Array.isArray(rule.tools) || rule.tools.some((t) => typeof t !== 'string'))) problems.push(`rules[${i}].tools must be strings`)
- })
- if (p.allowIf !== undefined && (!Array.isArray(p.allowIf) || p.allowIf.some((t) => typeof t !== 'string'))) problems.push('allowIf must be strings')
- if (p.lanes !== undefined) {
- if (!Array.isArray(p.lanes)) problems.push('lanes must be an array')
- else p.lanes.forEach((l, i) => {
- const lane = l as Record<string, unknown>
- if (typeof lane.name !== 'string' || !lane.name) problems.push(`lanes[${i}].name missing`)
- if (typeof lane.agent !== 'string') problems.push(`lanes[${i}].agent missing`)
- else { try { new RegExp(lane.agent) } catch { problems.push(`lanes[${i}].agent is not a valid regex`) } }
- if (!Array.isArray(lane.rules)) problems.push(`lanes[${i}].rules must be an array`)
- })
- }
- return problems.length ? { ok: false, problems } : { ok: true, policy: raw as ActionPolicy }
-}
-
-/** The JSON Claude Code expects on a PreToolUse hook's stdout for a non-allow verdict. */
-export function claudePreToolUseOutput(v: GateVerdict): Record<string, unknown> | null {
- if (v.decision === 'allow') return null
- return {
- hookSpecificOutput: {
- hookEventName: 'PreToolUse',
- permissionDecision: v.decision,
- permissionDecisionReason: `Harness gate: ${v.reason}`,
- },
- }
-}
diff --git a/cli/src/lib/attention.spec.ts b/cli/src/lib/attention.spec.ts
deleted file mode 100644
index 5cf988c10..000000000
--- a/cli/src/lib/attention.spec.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-import { describe, expect, it } from 'vitest'
-import { AttentionTracker, summarizeAttention } from './attention.js'
-
-const s = (agentId: string, active = true, engine = 'claude') => ({ agentId, sessionId: `s-${agentId}`, engine, active, tmuxPane: '%1', name: agentId })
-
-describe('AttentionTracker', () => {
- it('walks a turn: working, waiting, working, done, then reviewed', () => {
- let t = 1000
- const tr = new AttentionTracker(() => t)
- const seen: string[] = []
- tr.onChange((e, prev) => seen.push(`${prev ?? 'none'}>${e.state}`))
- tr.turnStarted('a', 'fix the login flow')
- t = 2000; tr.question('a', false, 'Which branch?')
- t = 3000; tr.answered('a')
- t = 4000; tr.turnEnded('a')
- t = 5000; tr.seen('a')
- expect(seen).toEqual(['none>working', 'working>waiting', 'waiting>working', 'working>done', 'done>idle'])
- expect(tr.get('a')).toEqual({ agentId: 'a', state: 'idle', since: 5000, detail: 'reviewed' })
- })
- it('keeps `since` when the state repeats and ignores identical sets', () => {
- let t = 10
- const tr = new AttentionTracker(() => t)
- let changes = 0
- tr.onChange(() => changes++)
- tr.turnStarted('a', 'x'); t = 20; tr.turnStarted('a', 'x')
- expect(changes).toBe(1)
- expect(tr.get('a')?.since).toBe(10)
- })
- it('permission is its own state and answered() only clears asking states', () => {
- const tr = new AttentionTracker(() => 1)
- tr.question('a', true, 'Bash: git push')
- expect(tr.get('a')?.state).toBe('permission')
- tr.turnEnded('a')
- tr.answered('a')
- expect(tr.get('a')?.state).toBe('done')
- })
- it('failed and cancelled are distinct from done', () => {
- const tr = new AttentionTracker(() => 1)
- tr.turnEnded('a', { error: 'API 529 overloaded' })
- tr.turnEnded('b', { aborted: true })
- expect(tr.get('a')).toMatchObject({ state: 'failed', detail: 'API 529 overloaded' })
- expect(tr.get('b')).toMatchObject({ state: 'idle', detail: 'cancelled' })
- })
- it('snapshot orders by priority, marks inactive sessions offline, and carries glyph and label', () => {
- let t = 1
- const tr = new AttentionTracker(() => t++)
- tr.turnStarted('w'); tr.question('q', false); tr.question('p', true); tr.turnEnded('d'); tr.failed('f', 'boom')
- const rows = tr.snapshot([s('w'), s('q'), s('p'), s('d'), s('f'), s('o', false), s('n')], 'gus')
- expect(rows.map((r) => `${r.agentId}:${r.state}`)).toEqual(['p:permission', 'q:waiting', 'f:failed', 'd:done', 'w:working', 'n:idle', 'o:offline'])
- expect(rows[0]).toMatchObject({ glyph: '!', label: 'needs permission', machine: 'gus', tmuxPane: '%1' })
- expect(rows.at(-1)).toMatchObject({ glyph: '.', detail: '' })
- })
- it('summarizes a fleet by the most urgent state', () => {
- const tr = new AttentionTracker(() => 1)
- tr.turnStarted('a'); tr.turnStarted('b'); tr.question('c', false)
- const rows = tr.snapshot([s('a'), s('b'), s('c')], 'gus')
- expect(summarizeAttention(rows)).toEqual({ state: 'waiting', count: 1, agentId: 'c' })
- expect(summarizeAttention([])).toEqual({ state: 'offline', count: 0, agentId: null })
- })
-})
diff --git a/cli/src/lib/attention.ts b/cli/src/lib/attention.ts
deleted file mode 100644
index 0f0e40c33..000000000
--- a/cli/src/lib/attention.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-/**
- * One typed answer to "what does this agent need from me right now", derived from signals the daemon
- * already has: turn start/end, the question watcher, permission dialogs, cancels, engine errors and
- * whether a window has looked at the agent since it finished. Today the frame only says active or
- * offline; the bar, the device, the brakes and the inbox all need this instead.
- *
- * Pure: no I/O. The daemon feeds it and asks for snapshots. Every state carries a non-colour glyph and a
- * short label so a screen with no colour, or a person who cannot tell red from green, reads the same thing.
- */
-export type AttentionState = 'working' | 'waiting' | 'permission' | 'failed' | 'done' | 'idle' | 'offline'
-
-export interface AttentionEntry {
- agentId: string
- state: AttentionState
- since: number
- detail: string
-}
-
-export interface AttentionRow extends AttentionEntry {
- name: string
- engine: string
- machine: string
- sessionId: string
- tmuxPane: string | null
- glyph: string
- label: string
-}
-
-export const ATTENTION_GLYPH: Record<AttentionState, string> = {
- working: '~', waiting: '?', permission: '!', failed: 'x', done: '*', idle: '-', offline: '.',
-}
-export const ATTENTION_LABEL: Record<AttentionState, string> = {
- working: 'working', waiting: 'waiting on you', permission: 'needs permission', failed: 'failed',
- done: 'done, unreviewed', idle: 'idle', offline: 'offline',
-}
-
-/** States that deserve a human's attention, in priority order (first wins when summarising a fleet). */
-export const ATTENTION_PRIORITY: AttentionState[] = ['permission', 'waiting', 'failed', 'done', 'working', 'idle', 'offline']
-
-export interface AttentionSessionLike {
- agentId: string
- sessionId: string
- engine: string
- active: boolean
- tmuxPane?: string
- name: string
-}
-
-export class AttentionTracker {
- private readonly entries = new Map<string, AttentionEntry>()
- private readonly listeners = new Set<(row: AttentionEntry, previous: AttentionState | null) => void>()
-
- constructor(private readonly now: () => number = Date.now) {}
-
- onChange(cb: (row: AttentionEntry, previous: AttentionState | null) => void): () => void {
- this.listeners.add(cb)
- return () => { this.listeners.delete(cb) }
- }
-
- get(agentId: string): AttentionEntry | undefined { return this.entries.get(agentId) }
-
- /** Set the state; a no-op when unchanged so listeners only hear real transitions. */
- set(agentId: string, state: AttentionState, detail = ''): AttentionEntry {
- const prev = this.entries.get(agentId)
- if (prev && prev.state === state && prev.detail === detail) return prev
- const entry: AttentionEntry = { agentId, state, since: prev?.state === state ? prev.since : this.now(), detail }
- this.entries.set(agentId, entry)
- for (const cb of this.listeners) cb(entry, prev?.state ?? null)
- return entry
- }
-
- turnStarted(agentId: string, userMessage = ''): void { this.set(agentId, 'working', userMessage.slice(0, 120)) }
- question(agentId: string, permission: boolean, detail = ''): void { this.set(agentId, permission ? 'permission' : 'waiting', detail.slice(0, 120)) }
- answered(agentId: string): void { if (this.isAsking(agentId)) this.set(agentId, 'working', 'answer delivered') }
- turnEnded(agentId: string, opts: { aborted?: boolean; error?: string } = {}): void {
- if (opts.error) this.set(agentId, 'failed', opts.error.slice(0, 120))
- else if (opts.aborted) this.set(agentId, 'idle', 'cancelled')
- else this.set(agentId, 'done', '')
- }
- failed(agentId: string, message: string): void { this.set(agentId, 'failed', message.slice(0, 120)) }
- cancelled(agentId: string): void { this.set(agentId, 'idle', 'cancelled') }
- /** A window showed this agent: "done, unreviewed" is reviewed now. Other states are unchanged. */
- seen(agentId: string): void { if (this.entries.get(agentId)?.state === 'done') this.set(agentId, 'idle', 'reviewed') }
- offline(agentId: string): void { this.set(agentId, 'offline', '') }
- forget(agentId: string): void { this.entries.delete(agentId) }
-
- isAsking(agentId: string): boolean {
- const s = this.entries.get(agentId)?.state
- return s === 'waiting' || s === 'permission'
- }
-
- /** Rows for every session the daemon advertises, in fleet priority order then by recency. */
- snapshot(sessions: AttentionSessionLike[], machine: string): AttentionRow[] {
- const rows = sessions.map((s): AttentionRow => {
- const e = this.entries.get(s.agentId)
- const state: AttentionState = !s.active ? 'offline' : e?.state ?? 'idle'
- return {
- agentId: s.agentId, sessionId: s.sessionId, engine: s.engine, machine, name: s.name,
- tmuxPane: s.tmuxPane ?? null,
- state, since: e?.since ?? 0, detail: state === 'offline' ? '' : e?.detail ?? '',
- glyph: ATTENTION_GLYPH[state], label: ATTENTION_LABEL[state],
- }
- })
- return rows.sort((a, b) => ATTENTION_PRIORITY.indexOf(a.state) - ATTENTION_PRIORITY.indexOf(b.state) || b.since - a.since)
- }
-}
-
-/** The one thing a fleet-level indicator shows: the most urgent state present, and how many share it. */
-export function summarizeAttention(rows: AttentionRow[]): { state: AttentionState; count: number; agentId: string | null } {
- for (const state of ATTENTION_PRIORITY) {
- const hits = rows.filter((r) => r.state === state)
- if (hits.length) return { state, count: hits.length, agentId: hits[0]!.agentId }
- }
- return { state: 'offline', count: 0, agentId: null }
-}
diff --git a/cli/src/lib/e2ee/applicationFrames.ts b/cli/src/lib/e2ee/applicationFrames.ts
index d629ec927..0bb3cc505 100644
--- a/cli/src/lib/e2ee/applicationFrames.ts
+++ b/cli/src/lib/e2ee/applicationFrames.ts
@@ -18,9 +18,7 @@ const FLEET_REQUESTS = new Set(['grid_fleet_capabilities', 'grid_fleet_run', 'gr
'grid_fleet_models_list', 'grid_fleet_model_download', 'grid_fleet_model_start', 'grid_fleet_model_stop'])
const FLEET_RESULTS = new Set([...FLEET_REQUESTS].map(type => `${type}_result`))
// `group_sync`: the trust-group roster exchange (groupSyncer.ts) — keys, so always sealed.
-// `clip_push`: clipboard and file drop between paired machines (fleet/control.ts) is user content, sealed
-// the same way (core.ts itself is a pinned interop keystone and stays untouched).
-const MACHINE_REQUESTS = new Set(['agent_purge', 'agent_worktree_delete', 'agents_cleanup_preview', 'agent_close', 'git_project_info', 'git_pull_request', 'machine_resources', 'api_connections', 'group_sync', 'phone_pair', 'viewer_surface', 'orchestrator', 'clip_push', ...OWNER_COMMAND_TYPES])
+const MACHINE_REQUESTS = new Set(['agent_purge', 'agent_worktree_delete', 'agents_cleanup_preview', 'agent_close', 'git_project_info', 'git_pull_request', 'machine_resources', 'api_connections', 'group_sync', 'phone_pair', 'viewer_surface', 'orchestrator', ...OWNER_COMMAND_TYPES])
const MACHINE_RESULTS = new Set([...MACHINE_REQUESTS].map(type => `${type}_result`))
/** The pair brain, machine to machine (daemons/BRAIN.md). A watch carries question text and recaps; the
* writes (answer, send, stop, start, pause, resume) act on a harness through the owning machine's floor
diff --git a/cli/src/lib/hooks.spec.ts b/cli/src/lib/hooks.spec.ts
index d332b672b..22526d591 100644
--- a/cli/src/lib/hooks.spec.ts
+++ b/cli/src/lib/hooks.spec.ts
@@ -602,37 +602,3 @@ describe('Hermes hook allowlist', () => {
expect(new Set(ours.map((a) => a.event)).size).toBe(ours.length)
})
})
-
-// The opt-in destructive-action gate hook (first written by Fred Nix in the nixfred fork).
-describe('Claude gate hook (harness gate install)', () => {
- let home = ''
- const settingsFile = () => join(home, '.claude', 'settings.json')
- const read = () => JSON.parse(readFileSync(settingsFile(), 'utf8')) as { hooks: Record<string, Array<{ matcher?: string; hooks: Array<{ command: string }> }>> }
- beforeEach(() => { home = mkdtempSync(join(tmpdir(), 'adapter-claude-gate-')); vi.stubEnv('HOME', home) })
- afterEach(() => { vi.unstubAllEnvs(); rmSync(home, { recursive: true, force: true }) })
-
- it('installs PreToolUse beside a foreign one, reports unchanged, and uninstalls only its own block', async () => {
- mkdirSync(join(home, '.claude'), { recursive: true })
- writeFileSync(settingsFile(), JSON.stringify({ hooks: { PreToolUse: [{ matcher: 'Bash', hooks: [{ type: 'command', command: 'my-own-guard' }] }] } }))
- const { installGateHook, uninstallGateHook, gateHookInstalled } = await loadHooks()
- expect(gateHookInstalled()).toBe(false)
- expect(installGateHook(18473)).toBe('installed')
- expect(installGateHook(18473)).toBe('unchanged')
- expect(gateHookInstalled()).toBe(true)
- const blocks = read().hooks.PreToolUse
- expect(blocks.map((b) => b.hooks[0]!.command)).toEqual(['my-own-guard', expect.stringContaining('notify.mjs')])
- expect(blocks[1]).toMatchObject({ matcher: 'Bash|Write|Edit|MultiEdit|NotebookEdit' })
- expect(uninstallGateHook()).toBe('removed')
- expect(read().hooks.PreToolUse.map((b) => b.hooks[0]!.command)).toEqual(['my-own-guard'])
- expect(uninstallGateHook()).toBe('absent')
- })
-
- it('keeps an installed gate on the session hooks\' port, and never adds one by itself', async () => {
- const { installGateHook, installSessionHooks } = await loadHooks()
- installSessionHooks(18473)
- expect(read().hooks.PreToolUse).toBeUndefined()
- installGateHook(18473)
- installSessionHooks(18599)
- expect(read().hooks.PreToolUse[0]!.hooks[0]!.command).toContain('--port 18599')
- })
-})
diff --git a/cli/src/lib/hooks.ts b/cli/src/lib/hooks.ts
index a52082d8d..146756464 100644
--- a/cli/src/lib/hooks.ts
+++ b/cli/src/lib/hooks.ts
@@ -129,15 +129,6 @@ export function installSessionHooks(port: number): void {
settings.hooks[event] = [...foreign, { hooks: [{ type: 'command', command: cmd, timeout: 5 }] }]
}
- // The opt-in gate hook (installGateHook) runs the same command: keep its path and port in step with
- // the session hooks, but never add it here — only `harness gate install` does that.
- const gateBlocks = Array.isArray(settings.hooks[GATE_EVENT]) ? settings.hooks[GATE_EVENT] : []
- if (gateBlocks.some((b) => isOurs(b) && b.hooks.some((h) => isOurs({ hooks: [h] }) && h.command !== cmd))) {
- settings.hooks[GATE_EVENT] = gateBlocks.map((b) => isOurs(b) ? { ...b, hooks: b.hooks.map((h) => isOurs({ hooks: [h] }) ? { ...h, command: cmd } : h) } : b)
- changed = true
- updated = true
- }
-
if (!changed) {
console.log('[hooks] Claude session + turn (Stop/StopFailure) hooks already installed')
return
@@ -157,58 +148,6 @@ export function installSessionHooks(port: number): void {
}
}
-/**
- * The destructive-action gate for Claude Code (lib/actionPolicy.ts; first written by Fred Nix in the
- * nixfred fork): a PreToolUse hook on the tools that can change the world. OPT-IN (`harness gate
- * install`), never part of `harness start`: it edits a person's own Claude settings, and the gate only
- * earns its place once a policy has been read and agreed to. The same notify script serves it; the
- * daemon answers with a `permissionDecision` the engine understands.
- */
-export const GATE_EVENT = 'PreToolUse'
-export const GATE_MATCHER = 'Bash|Write|Edit|MultiEdit|NotebookEdit'
-
-export function installGateHook(port: number): 'installed' | 'updated' | 'unchanged' | 'failed' {
- let settings: Settings = {}
- try { settings = JSON.parse(readFileSync(SETTINGS_PATH, 'utf-8')) as Settings } catch { /* start empty */ }
- if (!settings.hooks || typeof settings.hooks !== 'object') settings.hooks = {}
- const cmd = command(port, 'claude')
- const blocks = Array.isArray(settings.hooks[GATE_EVENT]) ? settings.hooks[GATE_EVENT] : []
- const foreign = blocks.filter((b) => !isOurs(b))
- const ours = blocks.filter(isOurs)
- const existingCmd = ours[0]?.hooks?.find((h) => isOurs({ hooks: [h] }))?.command
- const state = ours.length === 0 ? 'installed' : (existingCmd !== cmd || ours[0]?.matcher !== GATE_MATCHER || ours.length > 1) ? 'updated' : 'unchanged'
- if (state === 'unchanged') return state
- settings.hooks[GATE_EVENT] = [...foreign, { matcher: GATE_MATCHER, hooks: [{ type: 'command', command: cmd, timeout: 5 }] }]
- try {
- mkdirSync(dirname(SETTINGS_PATH), { recursive: true })
- writeJsonAtomic(SETTINGS_PATH, settings)
- console.log(`[gate] ${state} Claude PreToolUse gate hook → ${SETTINGS_PATH} (takes effect on the next claude session start)`)
- return state
- } catch (err) {
- console.error('[gate] failed to write settings.json:', err)
- return 'failed'
- }
-}
-
-export function uninstallGateHook(): 'removed' | 'absent' | 'failed' {
- let settings: Settings = {}
- try { settings = JSON.parse(readFileSync(SETTINGS_PATH, 'utf-8')) as Settings } catch { return 'absent' }
- const blocks = Array.isArray(settings.hooks?.[GATE_EVENT]) ? settings.hooks![GATE_EVENT] : []
- const foreign = blocks.filter((b) => !isOurs(b))
- if (foreign.length === blocks.length) return 'absent'
- if (foreign.length) settings.hooks![GATE_EVENT] = foreign
- else delete settings.hooks![GATE_EVENT]
- try { writeJsonAtomic(SETTINGS_PATH, settings); return 'removed' } catch (err) { console.error('[gate] failed to write settings.json:', err); return 'failed' }
-}
-
-export function gateHookInstalled(): boolean {
- try {
- const settings = JSON.parse(readFileSync(SETTINGS_PATH, 'utf-8')) as Settings
- const blocks = Array.isArray(settings.hooks?.[GATE_EVENT]) ? settings.hooks![GATE_EVENT] : []
- return blocks.some(isOurs)
- } catch { return false }
-}
-
function writeJsonAtomic(file: string, value: unknown): void {
mkdirSync(dirname(file), { recursive: true })
const tmp = `${file}.${process.pid}.tmp`
diff --git a/cli/src/lib/machineCapabilities.spec.ts b/cli/src/lib/machineCapabilities.spec.ts
deleted file mode 100644
index fc8f2de66..000000000
--- a/cli/src/lib/machineCapabilities.spec.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-import { describe, expect, it } from 'vitest'
-import {
- decidePlacement, describeCapabilities, parseNvidiaSmi, readMachineCapabilities,
- type CapabilityReaders, type MachineCapabilities,
-} from './machineCapabilities.js'
-
-function readers(over: Partial<CapabilityReaders> & { files?: Record<string, string>; dirs?: Record<string, string[]> } = {}): CapabilityReaders {
- const files = over.files ?? {}
- const dirs = over.dirs ?? {}
- return {
- nvidiaSmi: over.nvidiaSmi ?? (async () => { throw new Error('no nvidia-smi') }),
- readFile: over.readFile ?? (async (p) => { if (p in files) return files[p]!; throw new Error('ENOENT ' + p) }),
- listDir: over.listDir ?? (async (p) => { if (p in dirs) return dirs[p]!; throw new Error('ENOENT ' + p) }),
- which: over.which ?? (async (c) => c === 'git'),
- hostname: over.hostname ?? (() => 'testbox'),
- loadavg: over.loadavg ?? (() => [0.5, 0.4, 0.3]),
- cores: over.cores ?? (() => 8),
- now: over.now ?? (() => 1700000000000),
- }
-}
-
-describe('parseNvidiaSmi', () => {
- it('parses one line per card and tolerates blanks', () => {
- const out = parseNvidiaSmi('NVIDIA GeForce RTX 5070 Laptop GPU, 12227, 1834, 7\n\n')
- expect(out).toEqual([{ name: 'NVIDIA GeForce RTX 5070 Laptop GPU', vramTotalMb: 12227, vramUsedMb: 1834, utilizationPct: 7 }])
- })
- it('returns an empty list for empty output', () => {
- expect(parseNvidiaSmi('')).toEqual([])
- })
-})
-
-describe('readMachineCapabilities', () => {
- it('reads GPU, power, thermal, lid and toolchains from injected readers', async () => {
- const caps = await readMachineCapabilities(readers({
- nvidiaSmi: async () => 'RTX 4050, 6141, 512, 3',
- dirs: { '/sys/class/power_supply': ['AC', 'BAT1'], '/sys/class/thermal': ['thermal_zone0', 'cooling_device0'], '/proc/acpi/button/lid': ['LID0'] },
- files: {
- '/sys/class/power_supply/AC/type': 'Mains\n', '/sys/class/power_supply/AC/online': '0\n',
- '/sys/class/power_supply/BAT1/type': 'Battery\n', '/sys/class/power_supply/BAT1/capacity': '42\n', '/sys/class/power_supply/BAT1/status': 'Discharging\n',
- '/sys/class/thermal/thermal_zone0/temp': '67000\n',
- '/proc/acpi/button/lid/LID0/state': 'state: closed\n',
- },
- }))
- expect(caps.gpus[0]?.vramUsedMb).toBe(512)
- expect(caps.power).toEqual({ onAc: false, batteryPct: 42 })
- expect(caps.thermal.maxC).toBe(67)
- expect(caps.lid).toBe('closed')
- expect(caps.toolchains.git).toBe(true)
- expect(caps.toolchains.flutter).toBe(false)
- expect(caps.hostname).toBe('testbox')
- })
- it('degrades to no GPU, AC, unknown lid on a headless box without sysfs entries', async () => {
- const caps = await readMachineCapabilities(readers())
- expect(caps.gpus).toEqual([])
- expect(caps.power).toEqual({ onAc: true, batteryPct: null })
- expect(caps.thermal.maxC).toBeNull()
- expect(caps.lid).toBe('unknown')
- })
-})
-
-const base: MachineCapabilities = {
- at: 0, hostname: 'gus', cpu: { cores: 24, load1: 2, load5: 2 },
- gpus: [{ name: 'RTX 5070', vramTotalMb: 12227, vramUsedMb: 2000, utilizationPct: 5 }],
- power: { onAc: true, batteryPct: 100 }, thermal: { maxC: 55 }, lid: 'open',
- toolchains: { git: true, node: true, flutter: false },
-}
-
-describe('decidePlacement', () => {
- it('accepts an empty request on a healthy machine', () => {
- expect(decidePlacement(base, {})).toEqual({ ok: true, reasons: [] })
- })
- it('refuses GPU work on a busy card and says why', () => {
- const busy = { ...base, gpus: [{ ...base.gpus[0]!, utilizationPct: 85 }] }
- const d = decidePlacement(busy, { needsGpu: true })
- expect(d.ok).toBe(false)
- expect(d.reasons).toEqual(['GPU busy at 85%'])
- })
- it('refuses when free VRAM is under the minimum', () => {
- const d = decidePlacement(base, { needsGpu: true, minFreeVramMb: 11000 })
- expect(d.reasons[0]).toMatch(/10227 MB free, needs 11000 MB/)
- })
- it('refuses GPU work where there is no GPU', () => {
- expect(decidePlacement({ ...base, gpus: [] }, { needsGpu: true }).reasons).toEqual(['no GPU on this machine'])
- })
- it('refuses batch work on battery unless allowed, and a closed lid on a laptop', () => {
- const laptop = { ...base, power: { onAc: false, batteryPct: 30 }, lid: 'closed' as const }
- expect(decidePlacement(laptop, {}).reasons).toEqual(['on battery', 'lid closed on a laptop'])
- expect(decidePlacement(laptop, { allowOnBattery: true, allowLidClosed: true }).ok).toBe(true)
- })
- it('lets interactive work through a closed lid (external monitor) but not battery', () => {
- const laptop = { ...base, power: { onAc: false, batteryPct: 30 }, lid: 'closed' as const }
- expect(decidePlacement(laptop, { interactive: true }).reasons).toEqual(['on battery'])
- })
- it('flags CPU overload, heat and missing toolchains', () => {
- const hot = { ...base, cpu: { cores: 4, load1: 9, load5: 8 }, thermal: { maxC: 95 } }
- const d = decidePlacement(hot, { toolchains: ['flutter', 'git'] })
- expect(d.reasons).toEqual(['CPU load 9.0 over 4 cores', 'thermal 95C', 'missing flutter'])
- })
-})
-
-describe('describeCapabilities', () => {
- it('renders one line', () => {
- expect(describeCapabilities(base)).toBe('gus: RTX 5070 10227/12227MB free 5%, load 2.0/24, AC 55C, lid open')
- expect(describeCapabilities({ ...base, gpus: [], power: { onAc: false, batteryPct: 12 }, thermal: { maxC: null } }))
- .toBe('gus: no GPU, load 2.0/24, battery 12%, lid open')
- })
-})
diff --git a/cli/src/lib/machineCapabilities.ts b/cli/src/lib/machineCapabilities.ts
deleted file mode 100644
index 081291baa..000000000
--- a/cli/src/lib/machineCapabilities.ts
+++ /dev/null
@@ -1,168 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-import { execFile } from 'node:child_process'
-import { promises as fs } from 'node:fs'
-import { cpus, loadavg } from 'node:os'
-
-/**
- * What this machine can take right now: GPU memory and load, CPU load, power source, thermal
- * headroom, lid state and which toolchains are on PATH. Read on demand, never cached for long,
- * because the whole point is to refuse work on a card that just got busy or a laptop that just
- * went to battery. Every reader is injectable so the placement rules are testable without a GPU.
- */
-export interface GpuCapability {
- name: string
- vramTotalMb: number
- vramUsedMb: number
- utilizationPct: number
-}
-
-export interface MachineCapabilities {
- at: number
- hostname: string
- cpu: { cores: number; load1: number; load5: number }
- gpus: GpuCapability[]
- power: { onAc: boolean; batteryPct: number | null }
- thermal: { maxC: number | null }
- lid: 'open' | 'closed' | 'unknown'
- toolchains: Record<string, boolean>
-}
-
-export interface CapabilityReaders {
- nvidiaSmi: () => Promise<string>
- readFile: (path: string) => Promise<string>
- listDir: (path: string) => Promise<string[]>
- which: (cmd: string) => Promise<boolean>
- hostname: () => string
- loadavg: () => number[]
- cores: () => number
- now: () => number
-}
-
-export const TOOLCHAINS_TO_PROBE = ['node', 'python3', 'git', 'gh', 'tmux', 'flutter', 'qs', 'docker', 'cargo', 'bun', 'uv']
-
-const run = (cmd: string, args: string[], timeout = 3000): Promise<string> =>
- new Promise((resolve, reject) => {
- execFile(cmd, args, { timeout, maxBuffer: 1 << 20 }, (err, stdout) => (err ? reject(err) : resolve(String(stdout))))
- })
-
-export const systemReaders: CapabilityReaders = {
- nvidiaSmi: () => run('nvidia-smi', ['--query-gpu=name,memory.total,memory.used,utilization.gpu', '--format=csv,noheader,nounits']),
- readFile: (p) => fs.readFile(p, 'utf8'),
- listDir: (p) => fs.readdir(p),
- which: async (cmd) => { try { await run('sh', ['-c', `command -v ${cmd}`]); return true } catch { return false } },
- hostname: () => process.env.HOSTNAME ?? require('node:os').hostname(),
- loadavg,
- cores: () => cpus().length,
- now: () => Date.now(),
-}
-
-export function parseNvidiaSmi(csv: string): GpuCapability[] {
- return csv.split('\n').map((l) => l.trim()).filter(Boolean).map((line) => {
- const [name = '', total = '0', used = '0', util = '0'] = line.split(',').map((s) => s.trim())
- return { name, vramTotalMb: Number(total) || 0, vramUsedMb: Number(used) || 0, utilizationPct: Number(util) || 0 }
- })
-}
-
-async function readPower(r: CapabilityReaders): Promise<MachineCapabilities['power']> {
- let onAc = true
- let batteryPct: number | null = null
- let supplies: string[] = []
- try { supplies = await r.listDir('/sys/class/power_supply') } catch { return { onAc, batteryPct } }
- for (const s of supplies) {
- const base = `/sys/class/power_supply/${s}`
- let type = ''
- try { type = (await r.readFile(`${base}/type`)).trim() } catch { continue }
- if (type === 'Mains') {
- try { onAc = (await r.readFile(`${base}/online`)).trim() === '1' } catch { /* keep default */ }
- } else if (type === 'Battery') {
- try { batteryPct = Number((await r.readFile(`${base}/capacity`)).trim()) } catch { /* unknown */ }
- // A battery that is discharging means no mains, even when no Mains supply is exposed.
- try { if ((await r.readFile(`${base}/status`)).trim() === 'Discharging') onAc = false } catch { /* ignore */ }
- }
- }
- return { onAc, batteryPct }
-}
-
-async function readThermal(r: CapabilityReaders): Promise<number | null> {
- let zones: string[] = []
- try { zones = await r.listDir('/sys/class/thermal') } catch { return null }
- let max: number | null = null
- for (const z of zones) {
- if (!z.startsWith('thermal_zone')) continue
- try {
- const milli = Number((await r.readFile(`/sys/class/thermal/${z}/temp`)).trim())
- if (Number.isFinite(milli)) max = Math.max(max ?? -Infinity, milli / 1000)
- } catch { /* zone without a reading */ }
- }
- return max
-}
-
-async function readLid(r: CapabilityReaders): Promise<MachineCapabilities['lid']> {
- let lids: string[] = []
- try { lids = await r.listDir('/proc/acpi/button/lid') } catch { return 'unknown' }
- for (const l of lids) {
- try {
- const state = await r.readFile(`/proc/acpi/button/lid/${l}/state`)
- if (/closed/i.test(state)) return 'closed'
- if (/open/i.test(state)) return 'open'
- } catch { /* next lid */ }
- }
- return 'unknown'
-}
-
-export async function readMachineCapabilities(r: CapabilityReaders = systemReaders): Promise<MachineCapabilities> {
- let gpus: GpuCapability[] = []
- try { gpus = parseNvidiaSmi(await r.nvidiaSmi()) } catch { gpus = [] }
- const [power, maxC, lid] = await Promise.all([readPower(r), readThermal(r), readLid(r)])
- const toolchains: Record<string, boolean> = {}
- await Promise.all(TOOLCHAINS_TO_PROBE.map(async (t) => { toolchains[t] = await r.which(t) }))
- const [load1 = 0, load5 = 0] = r.loadavg()
- return { at: r.now(), hostname: r.hostname(), cpu: { cores: r.cores(), load1, load5 }, gpus, power, thermal: { maxC }, lid, toolchains }
-}
-
-/** What a job asks of a machine. Everything optional: an empty request fits anywhere that is up. */
-export interface PlacementRequest {
- needsGpu?: boolean
- minFreeVramMb?: number
- interactive?: boolean
- allowOnBattery?: boolean
- allowLidClosed?: boolean
- maxLoadPerCore?: number
- toolchains?: string[]
-}
-
-export interface PlacementDecision { ok: boolean; reasons: string[] }
-
-export const GPU_BUSY_UTILIZATION_PCT = 60
-export const HOT_C = 90
-
-/** Pure rule check: refuse work the machine should not take, and say exactly why. */
-export function decidePlacement(caps: MachineCapabilities, req: PlacementRequest): PlacementDecision {
- const reasons: string[] = []
- if (req.needsGpu) {
- if (caps.gpus.length === 0) reasons.push('no GPU on this machine')
- else {
- const best = caps.gpus.reduce((a, b) => (b.vramTotalMb - b.vramUsedMb > a.vramTotalMb - a.vramUsedMb ? b : a))
- const free = best.vramTotalMb - best.vramUsedMb
- if (req.minFreeVramMb !== undefined && free < req.minFreeVramMb) reasons.push(`GPU has ${free} MB free, needs ${req.minFreeVramMb} MB`)
- if (best.utilizationPct >= GPU_BUSY_UTILIZATION_PCT) reasons.push(`GPU busy at ${best.utilizationPct}%`)
- }
- }
- if (!req.allowOnBattery && !caps.power.onAc) reasons.push('on battery')
- if (!req.allowLidClosed && !req.interactive && caps.lid === 'closed' && caps.power.batteryPct !== null) reasons.push('lid closed on a laptop')
- const perCore = caps.cpu.cores > 0 ? caps.cpu.load1 / caps.cpu.cores : 0
- const maxLoad = req.maxLoadPerCore ?? 1.5
- if (perCore > maxLoad) reasons.push(`CPU load ${caps.cpu.load1.toFixed(1)} over ${caps.cpu.cores} cores`)
- if (caps.thermal.maxC !== null && caps.thermal.maxC >= HOT_C) reasons.push(`thermal ${caps.thermal.maxC.toFixed(0)}C`)
- for (const t of req.toolchains ?? []) if (!caps.toolchains[t]) reasons.push(`missing ${t}`)
- return { ok: reasons.length === 0, reasons }
-}
-
-/** Compact one-line summary for logs, the device and the bar. */
-export function describeCapabilities(c: MachineCapabilities): string {
- const gpu = c.gpus[0] ? `${c.gpus[0].name} ${c.gpus[0].vramTotalMb - c.gpus[0].vramUsedMb}/${c.gpus[0].vramTotalMb}MB free ${c.gpus[0].utilizationPct}%` : 'no GPU'
- const power = c.power.onAc ? 'AC' : `battery ${c.power.batteryPct ?? '?'}%`
- const heat = c.thermal.maxC === null ? '' : ` ${c.thermal.maxC.toFixed(0)}C`
- return `${c.hostname}: ${gpu}, load ${c.cpu.load1.toFixed(1)}/${c.cpu.cores}, ${power}${heat}, lid ${c.lid}`
-}
diff --git a/cli/src/lib/spendBrake.spec.ts b/cli/src/lib/spendBrake.spec.ts
deleted file mode 100644
index 301da1885..000000000
--- a/cli/src/lib/spendBrake.spec.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-import { describe, expect, it } from 'vitest'
-import { DEFAULT_CAPS, dayKey, decideSpend, emptyLedger, estimateUsd, parseCaps, priceFor, recordUsage } from './spendBrake.js'
-
-// 2026-09-26T03:30:00Z is 23:30 on the 25th in New York.
-const NIGHT = Date.UTC(2026, 8, 26, 3, 30)
-const MORNING = Date.UTC(2026, 8, 26, 12, 0)
-
-describe('prices', () => {
- it('matches by family substring with a fallback', () => {
- expect(priceFor('claude-opus-4-1')).toEqual({ input: 15, output: 75 })
- expect(priceFor('qwen2.5-coder:14b-local').input).toBe(0)
- expect(priceFor('mystery-model')).toEqual({ input: 3, output: 15 })
- expect(estimateUsd({ input: 1_000_000, output: 100_000 }, priceFor('sonnet'))).toBeCloseTo(4.5)
- })
-})
-
-describe('ledger', () => {
- it('keys days in the given time zone and rolls over at its local midnight', () => {
- const tz = 'America/New_York'
- expect(dayKey(NIGHT, tz)).toBe('2026-09-25')
- expect(dayKey(MORNING, tz)).toBe('2026-09-26')
- let l = recordUsage(emptyLedger(NIGHT, tz), { agentId: 'a', model: 'sonnet', input: 500_000, output: 50_000, now: NIGHT }, undefined, tz)
- expect(l.agents.a?.usd).toBeCloseTo(2.25)
- l = recordUsage(l, { agentId: 'b', model: 'sonnet', input: 100, output: 10, now: MORNING }, undefined, tz)
- expect(l.day).toBe('2026-09-26')
- expect(Object.keys(l.agents)).toEqual(['b'])
- })
-})
-
-describe('decideSpend', () => {
- const caps = { ...DEFAULT_CAPS, enabled: true, perAgentUsd: 10, perDayUsd: 20 }
- it('runs, warns at 80 percent, pauses at the cap, naming the tightest cap', () => {
- let l = recordUsage(emptyLedger(MORNING), { agentId: 'a', model: 'sonnet', input: 1_000_000, output: 100_000, now: MORNING }) // $4.50
- expect(decideSpend(caps, l, 'a').action).toBe('run')
- l = recordUsage(l, { agentId: 'a', model: 'sonnet', input: 2_000_000, output: 150_000, now: MORNING }) // $8.25
- expect(decideSpend(caps, l, 'a')).toMatchObject({ action: 'warn', fraction: 0.825 })
- l = recordUsage(l, { agentId: 'a', model: 'sonnet', input: 3_000_000, output: 100_000, now: MORNING }) // $10.50
- const v = decideSpend(caps, l, 'a')
- expect(v.action).toBe('pause')
- expect(v.reason).toBe('paused: agent at $10.50 of $10')
- })
- it('the day cap pauses a cheap agent when others spent the budget', () => {
- let l = recordUsage(emptyLedger(MORNING), { agentId: 'big', model: 'opus', input: 1_000_000, output: 100_000, now: MORNING }) // $22.50
- l = recordUsage(l, { agentId: 'small', model: 'haiku', input: 1000, output: 100, now: MORNING })
- const v = decideSpend(caps, l, 'small')
- expect(v.action).toBe('pause')
- expect(v.reason).toMatch(/machine at \$22\.50 of \$20 today/)
- })
- it('disabled or capless means run', () => {
- const l = emptyLedger(MORNING)
- expect(decideSpend({ ...caps, enabled: false }, l, 'a').action).toBe('run')
- expect(decideSpend({ ...caps, perAgentUsd: null, perDayUsd: null }, l, 'a').reason).toBe('no caps set')
- })
-})
-
-describe('parseCaps', () => {
- it('validates shape', () => {
- expect(parseCaps(DEFAULT_CAPS).ok).toBe(true)
- const bad = parseCaps({ version: 1, enabled: true, perAgentUsd: -1, perAgentTokens: null, perDayUsd: 'x', perDayTokens: null, warnAt: 2 })
- expect(bad.ok).toBe(false)
- if (!bad.ok) expect(bad.problems).toEqual(['perAgentUsd must be null or a non-negative number', 'perDayUsd must be null or a non-negative number', 'warnAt must be in (0, 1]'])
- })
-})
diff --git a/cli/src/lib/spendBrake.ts b/cli/src/lib/spendBrake.ts
deleted file mode 100644
index 89c1d75be..000000000
--- a/cli/src/lib/spendBrake.ts
+++ /dev/null
@@ -1,118 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-/**
- * Spend brake: token and dollar caps per agent, per machine and per day that pause a pane instead of
- * letting an overnight Loop run up a bill. The daemon already counts tokens per agent
- * (lib/agentTokenUsage.ts) but has no price table and nothing that stops; this is both, pure.
- */
-export interface PriceUsdPerMillion { input: number; output: number }
-
-/** Rough list prices, USD per million tokens, by model family substring. First match wins. */
-export const DEFAULT_PRICES: Array<{ match: string; price: PriceUsdPerMillion }> = [
- { match: 'opus', price: { input: 15, output: 75 } },
- { match: 'sonnet', price: { input: 3, output: 15 } },
- { match: 'haiku', price: { input: 0.8, output: 4 } },
- { match: 'gpt-5', price: { input: 1.25, output: 10 } },
- { match: 'o3', price: { input: 2, output: 8 } },
- { match: 'codex', price: { input: 1.5, output: 6 } },
- { match: 'grok', price: { input: 3, output: 15 } },
- { match: 'gemini', price: { input: 1.25, output: 10 } },
- { match: 'kimi', price: { input: 0.6, output: 2.5 } },
- { match: 'local', price: { input: 0, output: 0 } },
- { match: 'ollama', price: { input: 0, output: 0 } },
-]
-export const FALLBACK_PRICE: PriceUsdPerMillion = { input: 3, output: 15 }
-
-export function priceFor(model: string | null | undefined, table = DEFAULT_PRICES): PriceUsdPerMillion {
- const m = (model ?? '').toLowerCase()
- for (const row of table) if (m.includes(row.match)) return row.price
- return FALLBACK_PRICE
-}
-
-export function estimateUsd(tokens: { input: number; output: number }, price: PriceUsdPerMillion): number {
- return (tokens.input * price.input + tokens.output * price.output) / 1_000_000
-}
-
-export interface SpendCaps {
- version: 1
- enabled: boolean
- /** Per agent for its lifetime. */
- perAgentUsd: number | null
- perAgentTokens: number | null
- /** Per machine per local calendar day. */
- perDayUsd: number | null
- perDayTokens: number | null
- /** Warn at this fraction of any cap (0.8 = 80 percent). */
- warnAt: number
-}
-
-export const DEFAULT_CAPS: SpendCaps = { version: 1, enabled: false, perAgentUsd: null, perAgentTokens: null, perDayUsd: null, perDayTokens: null, warnAt: 0.8 }
-
-export interface AgentSpend { agentId: string; model: string | null; input: number; output: number; usd: number; updatedAt: number }
-
-export interface BrakeVerdict {
- action: 'run' | 'warn' | 'pause'
- reason: string
- agentUsd: number
- dayUsd: number
- /** 0..1 of the tightest cap consumed; > 1 when over. */
- fraction: number
-}
-
-export interface SpendLedger {
- day: string
- agents: Record<string, AgentSpend>
-}
-
-/** The calendar day a reading belongs to, in this machine's own time zone unless one is named. */
-export function dayKey(now: number, timeZone?: string): string {
- return new Intl.DateTimeFormat('en-CA', { ...(timeZone ? { timeZone } : {}), year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date(now))
-}
-
-export function emptyLedger(now: number, timeZone?: string): SpendLedger { return { day: dayKey(now, timeZone), agents: {} } }
-
-/** Fold a usage reading into the ledger, starting a new day when the calendar turns. */
-export function recordUsage(ledger: SpendLedger, reading: { agentId: string; model: string | null; input: number; output: number; now: number }, prices = DEFAULT_PRICES, timeZone?: string): SpendLedger {
- const day = dayKey(reading.now, timeZone)
- const base = ledger.day === day ? ledger : emptyLedger(reading.now, timeZone)
- const usd = estimateUsd({ input: reading.input, output: reading.output }, priceFor(reading.model, prices))
- return { ...base, agents: { ...base.agents, [reading.agentId]: { agentId: reading.agentId, model: reading.model, input: reading.input, output: reading.output, usd, updatedAt: reading.now } } }
-}
-
-export function dayTotals(ledger: SpendLedger): { usd: number; tokens: number } {
- let usd = 0, tokens = 0
- for (const a of Object.values(ledger.agents)) { usd += a.usd; tokens += a.input + a.output }
- return { usd, tokens }
-}
-
-/** Should this agent's next turn run, run with a warning, or be paused? */
-export function decideSpend(caps: SpendCaps, ledger: SpendLedger, agentId: string): BrakeVerdict {
- const agent = ledger.agents[agentId]
- const agentUsd = agent?.usd ?? 0
- const agentTokens = agent ? agent.input + agent.output : 0
- const day = dayTotals(ledger)
- if (!caps.enabled) return { action: 'run', reason: 'brake disabled', agentUsd, dayUsd: day.usd, fraction: 0 }
- const fractions: Array<[number, string]> = []
- if (caps.perAgentUsd) fractions.push([agentUsd / caps.perAgentUsd, `agent at $${agentUsd.toFixed(2)} of $${caps.perAgentUsd}`])
- if (caps.perAgentTokens) fractions.push([agentTokens / caps.perAgentTokens, `agent at ${agentTokens} of ${caps.perAgentTokens} tokens`])
- if (caps.perDayUsd) fractions.push([day.usd / caps.perDayUsd, `machine at $${day.usd.toFixed(2)} of $${caps.perDayUsd} today`])
- if (caps.perDayTokens) fractions.push([day.tokens / caps.perDayTokens, `machine at ${day.tokens} of ${caps.perDayTokens} tokens today`])
- if (!fractions.length) return { action: 'run', reason: 'no caps set', agentUsd, dayUsd: day.usd, fraction: 0 }
- const [fraction, reason] = fractions.reduce((a, b) => (b[0] > a[0] ? b : a))
- if (fraction >= 1) return { action: 'pause', reason: `paused: ${reason}`, agentUsd, dayUsd: day.usd, fraction }
- if (fraction >= caps.warnAt) return { action: 'warn', reason: `warning: ${reason}`, agentUsd, dayUsd: day.usd, fraction }
- return { action: 'run', reason, agentUsd, dayUsd: day.usd, fraction }
-}
-
-export function parseCaps(raw: unknown): { ok: true; caps: SpendCaps } | { ok: false; problems: string[] } {
- const problems: string[] = []
- if (!raw || typeof raw !== 'object') return { ok: false, problems: ['caps must be an object'] }
- const c = raw as Record<string, unknown>
- if (c.version !== 1) problems.push('version must be 1')
- if (typeof c.enabled !== 'boolean') problems.push('enabled must be a boolean')
- for (const k of ['perAgentUsd', 'perAgentTokens', 'perDayUsd', 'perDayTokens'] as const) {
- if (c[k] !== null && !(typeof c[k] === 'number' && c[k] >= 0)) problems.push(`${k} must be null or a non-negative number`)
- }
- if (!(typeof c.warnAt === 'number' && c.warnAt > 0 && c.warnAt <= 1)) problems.push('warnAt must be in (0, 1]')
- return problems.length ? { ok: false, problems } : { ok: true, caps: raw as SpendCaps }
-}
diff --git a/desktop/design/attention-motion.md b/desktop/design/attention-motion.md
deleted file mode 100644
index 7f69e0989..000000000
--- a/desktop/design/attention-motion.md
+++ /dev/null
@@ -1,56 +0,0 @@
-# Attention motion and branding
-
-The pane frame, the spend ring, the fleet overview and the boot splash share one visual language.
-They were designed and first built by Fred Nix ([@nixfred](https://github.com/nixfred)) in his fork,
-[github.com/nixfred/openharness](https://github.com/nixfred/openharness) (MIT). His rule: a lot of
-graphics are welcome, but never a graphic that carries no function. Every ring, arc or glow here
-answers a question a person has at that moment; where a screen is only text, it stays text.
-
-## The language
-
-- **One ring per agent, everywhere.** Its colour and motion are the agent's attention state, as the
- daemon reports it (`cli/src/lib/attention.ts`, the local `attention` frame): working, waiting on
- you, needs permission, failed, done (unreviewed), idle, offline.
-- **Arcs are quantities.** Spend runs from 0 to 100 percent of a cap, turns amber at 80 percent and
- holds red at the cap. Never a bare number where an arc can be read.
-- **Glow is urgency.** Only what needs a person next glows.
-- **Scanlines and grain** only on idle or transition screens, at 6 to 10 percent, never over text.
-- **Colour is never the only signal.** Every state also has a glyph (`~ ? ! x * - .`) and a word.
-- **Motion never moves the layout.** Every painter draws over or around its child at the child's
- size. Every animation sits behind one reduced-motion switch (`Motion` in `lib/fleet/neon.dart`):
- the platform's setting or `HARNESS_REDUCED_MOTION=1`. Loops stop while the window is unfocused
- and whenever nothing is live.
-- **Neon follows the palette.** Accent comes from the app palette; with the Omarchy palette chosen,
- yellow, red and green come from the Omarchy theme file when they still read as those colours.
-
-## Surfaces
-
-- **Pane frame** (`lib/widgets/attention_glow.dart`): working sweeps an accent comet around the border
- (2.4 s a lap), waiting breathes yellow, permission and failed pulse red with a scan band down the
- side edges (inside the border, never over text; failed opens with a double flash), done draws its
- border once in green, then holds. Colours cross-fade over 280 ms. Idle and offline draw nothing.
-- **Spend ring** (`lib/fleet/spend_ring.dart`): rings the engine mark in the pane header once a
- per-agent cap is set (`harness spend set`). While the agent waits on you, the mark becomes your
- avatar inside a ring in the state colour.
-- **Fleet overview** (`lib/fleet/`, command bar "Fleet overview" or Ctrl+Shift+G): a hub, one hexagon
- per machine, agents as rings around it. Agents orbit only while one works there; packets flow out
- along a link while work runs and back in the state colour while an agent there waits on you.
- Click an agent to open it.
-- **Boot splash** (`lib/branding/boot_splash.dart`): off by default. With a boot logo chosen in
- Settings ▸ Appearance it lights up once on a cold launch, 1.5 s, skippable by a click or any key;
- reduced motion shows a still logo. `HARNESS_NO_SPLASH=1` turns it off regardless.
-
-## Settings keys (`state.json`, written by Settings ▸ Appearance)
-
-| Key | Values | Default |
-|---|---|---|
-| `brand_boot_logo` | `omarchy`, `harness`, `custom`, `none` | unset: no splash |
-| `brand_boot_logo_path` | copy of the chosen SVG or PNG under `~/.harness/desktop-app-v2/brand/` | unset |
-| `brand_avatar` | `generic`, `initials`, `system`, `custom` | `generic` (a neutral person glyph) |
-| `brand_avatar_path` | cached copy of the chosen image under the same `brand/` folder | unset |
-| `brand_avatar_initials` | up to three letters, upper case | empty |
-
-Custom files must be SVG or PNG, at most 2 MB, with real content (PNG signature, `<svg` tag). A
-rejected file leaves the previous choice in place; a chosen file that has gone means no splash. The
-Omarchy logo is offered only where `/usr/share/omarchy/logo.svg` exists, and `system` (the avatar from
-`~/.face`) only where that file exists. Nothing of Omarchy's is bundled.
diff --git a/desktop/lib/app_shell.dart b/desktop/lib/app_shell.dart
index b6dd25a6d..da647d110 100644
--- a/desktop/lib/app_shell.dart
+++ b/desktop/lib/app_shell.dart
@@ -38,7 +38,6 @@ import 'widgets/new_device_notice.dart';
import 'widgets/update_notice.dart';
import 'widgets/window_chrome.dart';
import 'sharing/shared_agent_location.dart';
-import 'branding/boot_splash.dart';
import 'sharing/shared_agent_page.dart';
import 'viewer/viewer_location.dart';
import 'viewer/viewer_page.dart';
@@ -155,14 +154,10 @@ class HarnessApp extends StatelessWidget {
builder: (context, child) {
final app = child ?? const SizedBox.shrink();
final framed = frame?.call(app) ?? app;
- // The chosen boot logo lights up once on a cold launch while the app
- // builds underneath (lib/branding/boot_splash.dart); off by default.
- return BootSplash(
- child: _GridTokenScope(
- child: keymap == null
- ? framed
- : KeymapProvider(keymap: keymap!, child: framed),
- ),
+ return _GridTokenScope(
+ child: keymap == null
+ ? framed
+ : KeymapProvider(keymap: keymap!, child: framed),
);
},
home: StatsLifecycle(
diff --git a/desktop/lib/branding/boot_splash.dart b/desktop/lib/branding/boot_splash.dart
deleted file mode 100644
index c65a85cd3..000000000
--- a/desktop/lib/branding/boot_splash.dart
+++ /dev/null
@@ -1,224 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-import 'dart:async';
-import 'dart:io' show Platform;
-import 'dart:math' as math;
-import 'dart:ui' as ui;
-
-import 'package:flutter/foundation.dart';
-import 'package:flutter/material.dart';
-import 'package:flutter/services.dart';
-import 'brand_mark.dart';
-import 'brand_prefs.dart';
-import '../fleet/neon.dart';
-
-/// The cold-launch splash, off until a boot logo is chosen in Settings, Appearance (the Harness
-/// icon, the system's own Omarchy wordmark read from /usr/share/omarchy at runtime, or a picture)
-/// lights up in the theme's accent: a bloom that breathes, a shimmer band cut at the Omarchy
-/// chamfer's 45 degrees, one scan line down the screen, then a quick handoff.
-///
-/// It says one thing, "the app is up and following your theme", and gets out of the way:
-/// - the app builds and runs underneath from the first frame, so nothing waits on the splash;
-/// - 1.5 s end to end, a click or any key skips it to a 180 ms fade;
-/// - once per process: a window re-opened (the widget rebuilt) never shows it again;
-/// - reduced motion: a static, lit logo held for 0.9 s, still skippable;
-/// - boot logo "None", or `HARNESS_NO_SPLASH=1`, turns it off.
-class BootSplash extends StatefulWidget {
- const BootSplash({super.key, required this.child, this.brand});
-
- final Widget child;
-
- /// Where the logo choice comes from; the app's [brandPrefsStore] when null.
- final BrandPrefsStore? brand;
-
- static const overlayKey = ValueKey('boot-splash');
- static const total = Duration(milliseconds: 1500);
- static const reducedHold = Duration(milliseconds: 900);
-
- static bool _shown = false;
- static final bool _disabled = const bool.fromEnvironment('HARNESS_NO_SPLASH') || (!kIsWeb && Platform.environment['HARNESS_NO_SPLASH'] == '1');
-
- @visibleForTesting
- static void debugReset() => _shown = false;
-
- @override
- State<BootSplash> createState() => BootSplashState();
-}
-
-class BootSplashState extends State<BootSplash> with SingleTickerProviderStateMixin {
- late final AnimationController _c = AnimationController(vsync: this, duration: BootSplash.total);
- bool _visible = false;
- bool _animated = true;
- Timer? _hold;
- late ResolvedLogo _logo;
-
- /// False under reduced motion: the logo is drawn once and held.
- bool get animated => _animated;
-
- @override
- void initState() {
- super.initState();
- _logo = (widget.brand ?? brandPrefsStore).resolveBootLogo();
- if (!BootSplash._shown && !BootSplash._disabled && _logo.kind != BootLogo.none) {
- BootSplash._shown = true;
- _visible = true;
- HardwareKeyboard.instance.addHandler(_onKey);
- _c.addStatusListener((s) {
- if (s == AnimationStatus.completed) _finish();
- });
- }
- }
-
- @override
- void didChangeDependencies() {
- super.didChangeDependencies();
- if (!_visible || _c.isAnimating || _hold != null) return;
- _animated = !Motion.reducedOf(context);
- if (_animated) {
- _c.forward();
- } else {
- _c.value = 0.6; // a lit, settled frame
- _hold = Timer(BootSplash.reducedHold, _finish);
- }
- }
-
- bool _onKey(KeyEvent e) {
- if (!_visible) return false;
- if (e is KeyDownEvent) skip();
- return true; // the skipping key never reaches the app underneath
- }
-
- /// Jump to the handoff; a no-op once it is under way.
- void skip() {
- if (!_visible) return;
- _hold?.cancel();
- if (!_animated) return _finish();
- if (_c.value >= 0.84) return;
- _c.animateTo(1, duration: const Duration(milliseconds: 180), curve: Curves.easeOut);
- }
-
- void _finish() {
- if (!_visible) return;
- HardwareKeyboard.instance.removeHandler(_onKey);
- if (mounted) setState(() => _visible = false);
- }
-
- @override
- void dispose() {
- _hold?.cancel();
- HardwareKeyboard.instance.removeHandler(_onKey);
- _c.dispose();
- super.dispose();
- }
-
- @override
- Widget build(BuildContext context) {
- if (!_visible) return widget.child;
- return Stack(
- fit: StackFit.expand,
- children: [
- widget.child,
- GestureDetector(
- key: BootSplash.overlayKey,
- behavior: HitTestBehavior.opaque,
- onTap: skip,
- child: RepaintBoundary(
- child: AnimatedBuilder(animation: _c, builder: (context, _) => _frame(_c.value)),
- ),
- ),
- ],
- );
- }
-
- Widget _frame(double t) {
- final neon = Neon.current();
- double seg(double a, double b) => ((t - a) / (b - a)).clamp(0.0, 1.0);
- final enter = Curves.easeOutCubic.transform(seg(0, 0.28));
- final exit = Curves.easeInCubic.transform(seg(0.82, 1));
- final breath = 0.5 - 0.5 * math.cos(seg(0.1, 0.82) * 2 * math.pi * 1.5);
- final bloom = _animated ? enter * (0.45 + 0.4 * breath) : 0.7;
- final shimmer = _animated ? seg(0.22, 0.7) : -1.0;
- final scan = _animated ? seg(0.05, 0.62) : -1.0;
- const h = 100.0;
- BrandLogo mark(double glow) => BrandLogo(logo: _logo, accent: neon.accent, glow: glow, height: h);
- final aspect = mark(0).aspect;
- return Opacity(
- opacity: 1 - exit,
- child: ColoredBox(
- color: neon.background,
- child: CustomPaint(
- painter: _SplashPainter(accent: neon.accent, scan: scan, frame: _animated ? seg(0.08, 0.5) : 1, box: Size(h * aspect + 60, h + 60)),
- child: Center(
- child: Transform.scale(
- scale: (_animated ? 0.94 + 0.06 * enter : 1) + 0.05 * exit,
- child: Opacity(
- opacity: _animated ? enter : 1,
- child: Stack(
- clipBehavior: Clip.none,
- children: [
- // The chosen logo with its bloom breathing.
- mark(bloom),
- if (shimmer >= 0 && shimmer < 1)
- Positioned.fill(
- child: ShaderMask(
- blendMode: BlendMode.srcATop,
- shaderCallback: (r) => LinearGradient(
- begin: Alignment.topLeft,
- end: Alignment.bottomRight,
- colors: [Colors.transparent, Colors.white.withValues(alpha: 0.85), Colors.transparent],
- stops: [(shimmer * 1.4 - 0.25).clamp(0.0, 1.0), (shimmer * 1.4 - 0.15).clamp(0.0, 1.0), (shimmer * 1.4 - 0.05).clamp(0.0, 1.0)],
- ).createShader(Rect.fromLTWH(0, 0, r.width, r.width)), // square rect: the band runs at 45 degrees
- child: mark(0),
- ),
- ),
- ],
- ),
- ),
- ),
- ),
- ),
- ),
- );
- }
-}
-
-class _SplashPainter extends CustomPainter {
- const _SplashPainter({required this.accent, required this.scan, required this.frame, required this.box});
-
- final Size box;
-
- final Color accent;
- final double scan; // 0..1 down the screen, <0 when none
- final double frame; // 0..1 how much of the chamfered frame is drawn
-
- @override
- void paint(Canvas canvas, Size size) {
- // Scanlines at 7 percent: a transition screen, and they stay off the wordmark's own pixels
- // only by being faint (design/attention-motion.md allows them on transition screens).
- final lines = Paint()..color = accent.withValues(alpha: 0.07);
- for (var y = 0.0; y < size.height; y += 3) {
- canvas.drawRect(Rect.fromLTWH(0, y, size.width, 1), lines);
- }
- if (scan >= 0 && scan < 1) {
- final y = size.height * scan;
- canvas.drawRect(
- Rect.fromLTWH(0, y - 24, size.width, 48),
- Paint()
- ..shader = ui.Gradient.linear(Offset(0, y - 24), Offset(0, y + 24), [accent.withValues(alpha: 0), accent.withValues(alpha: 0.18), accent.withValues(alpha: 0)], const [0, 0.5, 1]),
- );
- }
- // The chamfered frame around the wordmark draws itself, the Omarchy bevel as the border.
- final rect = Rect.fromCenter(center: size.center(Offset.zero), width: box.width, height: box.height);
- final metric = chamferPath(rect, 18).computeMetrics().first;
- canvas.drawPath(
- metric.extractPath(0, metric.length * frame),
- Paint()
- ..style = PaintingStyle.stroke
- ..strokeWidth = 1.5
- ..color = accent.withValues(alpha: 0.55),
- );
- }
-
- @override
- bool shouldRepaint(_SplashPainter old) => old.accent != accent || old.scan != scan || old.frame != frame || old.box != box;
-}
diff --git a/desktop/lib/branding/brand_mark.dart b/desktop/lib/branding/brand_mark.dart
deleted file mode 100644
index ec1dffda4..000000000
--- a/desktop/lib/branding/brand_mark.dart
+++ /dev/null
@@ -1,95 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-import 'dart:io';
-import 'dart:ui' as ui;
-
-import 'package:flutter/material.dart';
-import 'package:flutter_svg/flutter_svg.dart';
-
-import 'brand_prefs.dart';
-
-/// The bundled stock Harness icon: the fallback everywhere a logo cannot be drawn.
-const harnessIconAsset = 'assets/app_icon.png';
-
-/// A boot logo with the glow treatment, whichever logo was chosen. A monochrome system
-/// wordmark (Omarchy's ships black) is tinted with the accent; a custom or stock image keeps its own
-/// colours. The glow is always the accent: a blurred silhouette behind the mark at [glow] strength.
-/// Any file that fails to load draws the Harness icon instead.
-class BrandLogo extends StatelessWidget {
- const BrandLogo({super.key, required this.logo, required this.accent, this.glow = 0.6, this.height = 100});
-
- final ResolvedLogo logo;
- final Color accent;
- final double glow;
- final double height;
-
- /// Width over height the logo is laid out at (Omarchy's wordmark is 1215 x 285).
- double get aspect => logo.kind == BootLogo.omarchy ? 1215 / 285 : 1;
-
- Widget _harness() => Image.asset(harnessIconAsset, fit: BoxFit.contain);
-
- Widget _mark({required bool tint}) {
- final path = logo.path;
- final filter = tint ? ColorFilter.mode(accent, BlendMode.srcIn) : null;
- if (logo.kind == BootLogo.harness || path == null) {
- return tint ? ColorFiltered(colorFilter: filter!, child: _harness()) : _harness();
- }
- if (logo.isSvg) {
- return SvgPicture.file(File(path), fit: BoxFit.contain, colorFilter: filter, errorBuilder: (_, _, _) => _harness());
- }
- final img = Image.file(File(path), fit: BoxFit.contain, errorBuilder: (_, _, _) => _harness());
- return tint ? ColorFiltered(colorFilter: filter!, child: img) : img;
- }
-
- @override
- Widget build(BuildContext context) {
- if (logo.kind == BootLogo.none) return const SizedBox.shrink();
- return SizedBox(
- width: height * aspect,
- height: height,
- child: Stack(
- clipBehavior: Clip.none,
- fit: StackFit.expand,
- children: [
- Opacity(
- opacity: glow.clamp(0.0, 1.0),
- child: ImageFiltered(imageFilter: ui.ImageFilter.blur(sigmaX: 14, sigmaY: 14, tileMode: TileMode.decal), child: _mark(tint: true)),
- ),
- _mark(tint: logo.kind == BootLogo.omarchy),
- ],
- ),
- );
- }
-}
-
-/// The person an agent is waiting on, as a circle: their picture cropped to the circle,
-/// their initials, or a neutral glyph. Never anyone's real face by default.
-class AvatarBadge extends StatelessWidget {
- const AvatarBadge({super.key, required this.avatar, required this.size, required this.color, required this.background});
-
- final ResolvedAvatar avatar;
- final double size;
- final Color color, background;
-
- @override
- Widget build(BuildContext context) {
- final generic = Icon(Icons.person_outline, size: size * 0.78, color: color);
- final Widget inner = switch (avatar.kind) {
- AvatarSource.initials => FittedBox(
- child: Padding(
- padding: const EdgeInsets.all(2),
- child: Text(avatar.initials, style: TextStyle(fontFamily: 'monospace', fontWeight: FontWeight.w700, color: color)),
- ),
- ),
- AvatarSource.system || AvatarSource.custom when avatar.path != null => avatar.path!.toLowerCase().endsWith('.svg')
- ? SvgPicture.file(File(avatar.path!), fit: BoxFit.cover, errorBuilder: (_, _, _) => generic)
- // Decoded at the size it is drawn (cached by Flutter's image cache), cropped to the circle.
- : Image.file(File(avatar.path!), fit: BoxFit.cover, cacheWidth: (size * 3).round(), errorBuilder: (_, _, _) => generic),
- _ => generic,
- };
- return SizedBox.square(
- dimension: size,
- child: ClipOval(child: ColoredBox(color: background, child: Center(child: inner))),
- );
- }
-}
diff --git a/desktop/lib/branding/brand_prefs.dart b/desktop/lib/branding/brand_prefs.dart
deleted file mode 100644
index badb48c72..000000000
--- a/desktop/lib/branding/brand_prefs.dart
+++ /dev/null
@@ -1,220 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-import 'dart:async';
-import 'dart:convert';
-import 'dart:io';
-
-import 'package:flutter/foundation.dart';
-
-import '../core/harness_file_store.dart';
-import '../core/local_key_value_store.dart';
-
-/// What the cold-launch splash shows. [omarchy] reads the system's own wordmark at runtime
-/// (`/usr/share/omarchy/logo.svg`); nothing of Omarchy's is bundled in this repo.
-enum BootLogo { omarchy, harness, custom, none }
-
-/// What sits inside the ring of an agent that waits on you.
-enum AvatarSource { generic, initials, system, custom }
-
-@immutable
-class BrandPrefs {
- const BrandPrefs({this.bootLogo, this.customLogoPath, this.avatar = AvatarSource.generic, this.avatarPath, this.initials = ''});
-
- /// Null until chosen, which means no splash: a person turns it on in Settings ▸ Appearance.
- final BootLogo? bootLogo;
- final String? customLogoPath;
- final AvatarSource avatar;
- final String? avatarPath;
- final String initials;
-
- BrandPrefs copyWith({BootLogo? bootLogo, String? customLogoPath, AvatarSource? avatar, String? avatarPath, String? initials}) => BrandPrefs(
- bootLogo: bootLogo ?? this.bootLogo,
- customLogoPath: customLogoPath ?? this.customLogoPath,
- avatar: avatar ?? this.avatar,
- avatarPath: avatarPath ?? this.avatarPath,
- initials: initials ?? this.initials,
- );
-
- @override
- bool operator ==(Object other) =>
- other is BrandPrefs && other.bootLogo == bootLogo && other.customLogoPath == customLogoPath && other.avatar == avatar && other.avatarPath == avatarPath && other.initials == initials;
- @override
- int get hashCode => Object.hash(bootLogo, customLogoPath, avatar, avatarPath, initials);
-}
-
-/// The logo the splash will actually draw, after every fallback.
-@immutable
-class ResolvedLogo {
- const ResolvedLogo(this.kind, [this.path]);
- final BootLogo kind;
-
- /// A file on disk for [BootLogo.omarchy] and [BootLogo.custom]; null for the bundled Harness icon.
- final String? path;
- bool get isSvg => path?.toLowerCase().endsWith('.svg') ?? false;
-}
-
-@immutable
-class ResolvedAvatar {
- const ResolvedAvatar(this.kind, {this.path, this.initials = ''});
- final AvatarSource kind;
- final String? path;
- final String initials;
-}
-
-/// Boot logo and personal avatar, stored beside the other appearance settings. Keys:
-/// `brand_boot_logo`, `brand_boot_logo_path`, `brand_avatar`, `brand_avatar_path`,
-/// `brand_avatar_initials`. Picked files are validated (SVG or PNG, at most 2 MB, real content) and
-/// copied into `<data dir>/brand/`, so moving or deleting the original never breaks the app. Every
-/// read falls back: a missing file means the default, never an error.
-class BrandPrefsStore extends ValueNotifier<BrandPrefs> {
- BrandPrefsStore({LocalKeyValueStore? storage, Directory? dataDir, this.omarchyLogoPath = '/usr/share/omarchy/logo.svg', String? systemAvatarPath})
- : _storage = storage ?? HarnessFileStore.shared,
- _dataDir = dataDir ?? Directory('${_home()}/.harness/desktop-app-v2/brand'),
- systemAvatarPath = systemAvatarPath ?? '${_home()}/.face',
- super(const BrandPrefs());
-
- static String _home() => kIsWeb ? '' : (Platform.environment['HOME'] ?? Platform.environment['USERPROFILE'] ?? '');
-
- static const bootLogoKey = 'brand_boot_logo';
- static const bootLogoPathKey = 'brand_boot_logo_path';
- static const avatarKey = 'brand_avatar';
- static const avatarPathKey = 'brand_avatar_path';
- static const initialsKey = 'brand_avatar_initials';
- static const maxBytes = 2 * 1024 * 1024;
-
- final LocalKeyValueStore _storage;
- final Directory _dataDir;
- final String omarchyLogoPath;
- final String systemAvatarPath;
-
- bool get omarchyAvailable => !kIsWeb && File(omarchyLogoPath).existsSync();
- bool get systemAvatarAvailable => !kIsWeb && File(systemAvatarPath).existsSync();
-
- Future<void> load() async {
- try {
- final saved = <String, String?>{};
- for (final k in [bootLogoKey, bootLogoPathKey, avatarKey, avatarPathKey, initialsKey]) {
- saved[k] = await _storage.read(k);
- }
- value = BrandPrefs(
- bootLogo: BootLogo.values.where((e) => e.name == saved[bootLogoKey]).firstOrNull,
- customLogoPath: saved[bootLogoPathKey],
- avatar: AvatarSource.values.where((e) => e.name == saved[avatarKey]).firstOrNull ?? AvatarSource.generic,
- avatarPath: saved[avatarPathKey],
- initials: saved[initialsKey] ?? '',
- );
- } catch (_) {
- // Unreadable settings leave the defaults in place.
- }
- }
-
- ResolvedLogo resolveBootLogo() {
- // No splash until somebody picks a logo; a picked image that has gone shows none either.
- const fallback = ResolvedLogo(BootLogo.none);
- switch (value.bootLogo) {
- case null:
- case BootLogo.none:
- return fallback;
- case BootLogo.harness:
- return const ResolvedLogo(BootLogo.harness);
- case BootLogo.omarchy:
- return omarchyAvailable ? ResolvedLogo(BootLogo.omarchy, omarchyLogoPath) : const ResolvedLogo(BootLogo.harness);
- case BootLogo.custom:
- final p = value.customLogoPath;
- return p != null && !kIsWeb && File(p).existsSync() ? ResolvedLogo(BootLogo.custom, p) : fallback;
- }
- }
-
- ResolvedAvatar resolveAvatar() {
- const generic = ResolvedAvatar(AvatarSource.generic);
- switch (value.avatar) {
- case AvatarSource.generic:
- return generic;
- case AvatarSource.initials:
- return value.initials.isEmpty ? generic : ResolvedAvatar(AvatarSource.initials, initials: value.initials);
- case AvatarSource.system:
- return systemAvatarAvailable ? ResolvedAvatar(AvatarSource.system, path: systemAvatarPath) : generic;
- case AvatarSource.custom:
- final p = value.avatarPath;
- return p != null && !kIsWeb && File(p).existsSync() ? ResolvedAvatar(AvatarSource.custom, path: p) : generic;
- }
- }
-
- Future<void> setBootLogo(BootLogo logo) async {
- value = value.copyWith(bootLogo: logo);
- await _storage.write(bootLogoKey, logo.name);
- }
-
- /// Validates and copies [source]; returns a message for the person on failure (choice unchanged).
- Future<String?> setCustomLogo(String source) async {
- final copied = await _import(source, 'boot-logo');
- if (copied.error != null) return copied.error;
- value = value.copyWith(bootLogo: BootLogo.custom, customLogoPath: copied.path);
- await _storage.write(bootLogoPathKey, copied.path!);
- await _storage.write(bootLogoKey, BootLogo.custom.name);
- return null;
- }
-
- Future<void> setAvatar(AvatarSource source) async {
- value = value.copyWith(avatar: source);
- await _storage.write(avatarKey, source.name);
- }
-
- /// Up to three letters, upper case. Empty goes back to the generic glyph.
- Future<void> setInitials(String raw) async {
- final clean = raw.replaceAll(RegExp(r'\s+'), '').toUpperCase();
- final initials = clean.length > 3 ? clean.substring(0, 3) : clean;
- value = value.copyWith(initials: initials, avatar: initials.isEmpty ? AvatarSource.generic : AvatarSource.initials);
- await _storage.write(initialsKey, initials);
- await _storage.write(avatarKey, value.avatar.name);
- }
-
- Future<String?> setCustomAvatar(String source) async {
- final copied = await _import(source, 'avatar');
- if (copied.error != null) return copied.error;
- value = value.copyWith(avatar: AvatarSource.custom, avatarPath: copied.path);
- await _storage.write(avatarPathKey, copied.path!);
- await _storage.write(avatarKey, AvatarSource.custom.name);
- return null;
- }
-
- /// A problem with [path] as an image, or null when it is a real SVG or PNG under [maxBytes].
- static Future<String?> validateImage(String path) async {
- final f = File(path);
- if (!await f.exists()) return 'That file no longer exists.';
- final ext = path.toLowerCase().split('.').last;
- if (ext != 'svg' && ext != 'png') return 'Choose an SVG or PNG image.';
- final size = await f.length();
- if (size > maxBytes) return 'That image is larger than 2 MB.';
- final head = await f.openRead(0, 512).fold<List<int>>([], (a, b) => a..addAll(b));
- final ok = ext == 'png'
- ? head.length >= 8 && listEquals(head.sublist(0, 8), const [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])
- : utf8.decode(head, allowMalformed: true).contains('<svg');
- return ok ? null : 'That is not a valid ${ext.toUpperCase()} file.';
- }
-
- Future<({String? path, String? error})> _import(String source, String name) async {
- try {
- final problem = await validateImage(source);
- if (problem != null) return (path: null, error: problem);
- await _dataDir.create(recursive: true);
- final ext = source.toLowerCase().split('.').last;
- // A fresh name each time, so a cached decode of the previous image is never shown again.
- final dest = File('${_dataDir.path}/$name-${DateTime.now().microsecondsSinceEpoch}.$ext');
- await File(source).copy(dest.path);
- for (final old in _dataDir.listSync().whereType<File>()) {
- if (old.path != dest.path && old.uri.pathSegments.last.startsWith('$name-')) {
- try {
- old.deleteSync();
- } catch (_) {}
- }
- }
- return (path: dest.path, error: null);
- } catch (e) {
- return (path: null, error: 'Could not use that file: $e');
- }
- }
-}
-
-/// The app's one instance, loaded in `loadPersistedSettings()`.
-final brandPrefsStore = BrandPrefsStore();
diff --git a/desktop/lib/branding/brand_section.dart b/desktop/lib/branding/brand_section.dart
deleted file mode 100644
index dbec5f734..000000000
--- a/desktop/lib/branding/brand_section.dart
+++ /dev/null
@@ -1,154 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-import 'dart:async';
-
-import 'package:file_selector/file_selector.dart';
-import 'package:flutter/material.dart';
-
-import '../shared/theme/app_theme.dart' as grid;
-import '../shared/widgets/section_heading.dart';
-import 'brand_mark.dart';
-import 'brand_prefs.dart';
-import '../fleet/neon.dart';
-
-/// Picks an image file; replaced in tests.
-typedef ImagePicker = Future<String?> Function();
-
-Future<String?> pickSvgOrPng() async {
- final file = await openFile(acceptedTypeGroups: const [XTypeGroup(label: 'SVG or PNG image', extensions: ['svg', 'png'])]);
- return file?.path;
-}
-
-/// Settings, Appearance: the boot logo and the avatar shown to agents waiting on you.
-class BrandSection extends StatefulWidget {
- const BrandSection({super.key, this.store, this.pick = pickSvgOrPng});
-
- final BrandPrefsStore? store;
- final ImagePicker pick;
-
- @override
- State<BrandSection> createState() => _BrandSectionState();
-}
-
-class _BrandSectionState extends State<BrandSection> {
- BrandPrefsStore get _store => widget.store ?? brandPrefsStore;
- String? _logoError, _avatarError;
- late final _initials = TextEditingController(text: _store.value.initials);
-
- @override
- void dispose() {
- _initials.dispose();
- super.dispose();
- }
-
- Future<void> _pickLogo() async {
- final path = await widget.pick();
- if (path == null) return;
- final error = await _store.setCustomLogo(path);
- if (mounted) setState(() => _logoError = error);
- }
-
- Future<void> _pickAvatar() async {
- final path = await widget.pick();
- if (path == null) return;
- final error = await _store.setCustomAvatar(path);
- if (mounted) setState(() => _avatarError = error);
- }
-
- Widget _chip(String label, bool selected, VoidCallback? onTap, {String? tooltip}) {
- final chip = ChoiceChip(label: Text(label), selected: selected, onSelected: onTap == null ? null : (_) => onTap());
- return tooltip == null ? chip : Tooltip(message: tooltip, child: chip);
- }
-
- @override
- Widget build(BuildContext context) {
- grid.AppTheme.watch(context);
- final neon = Neon.current();
- final muted = TextStyle(fontSize: 12, color: neon.foreground.withValues(alpha: 0.6));
- final error = TextStyle(fontSize: 12, color: neon.red);
- return ValueListenableBuilder<BrandPrefs>(
- valueListenable: _store,
- builder: (context, prefs, _) {
- final logo = _store.resolveBootLogo();
- final avatar = _store.resolveAvatar();
- return Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- const SectionHeading('Boot logo'),
- const SizedBox(height: 6),
- Text('Off by default. Pick a logo to show it for about a second and a half when the app starts; click or press any key to skip it.', style: muted),
- const SizedBox(height: 12),
- Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Expanded(
- child: Wrap(spacing: 8, runSpacing: 8, children: [
- // Offered only where Omarchy is installed: its wordmark is read from the system.
- if (_store.omarchyAvailable)
- _chip('Omarchy', logo.kind == BootLogo.omarchy, () => unawaited(_store.setBootLogo(BootLogo.omarchy))),
- _chip('Harness', logo.kind == BootLogo.harness, () => unawaited(_store.setBootLogo(BootLogo.harness))),
- _chip('Custom…', logo.kind == BootLogo.custom, () => unawaited(_pickLogo()), tooltip: 'An SVG or PNG, up to 2 MB'),
- _chip('None', logo.kind == BootLogo.none, () => unawaited(_store.setBootLogo(BootLogo.none))),
- ]),
- ),
- const SizedBox(width: 16),
- // Preview with the same glow the splash uses.
- Container(
- width: 200,
- height: 72,
- color: neon.background,
- alignment: Alignment.center,
- child: logo.kind == BootLogo.none
- ? Text('no splash', style: muted)
- : FittedBox(child: Padding(padding: const EdgeInsets.all(14), child: BrandLogo(logo: logo, accent: neon.accent, height: 44))),
- ),
- ],
- ),
- if (_logoError != null) Padding(padding: const EdgeInsets.only(top: 8), child: Text(_logoError!, style: error)),
- const SizedBox(height: 24),
- const SectionHeading('Your avatar'),
- const SizedBox(height: 6),
- Text('Drawn inside the ring of any agent that is waiting on you.', style: muted),
- const SizedBox(height: 12),
- Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Expanded(
- child: Wrap(spacing: 8, runSpacing: 8, crossAxisAlignment: WrapCrossAlignment.center, children: [
- _chip('Generic', avatar.kind == AvatarSource.generic, () => unawaited(_store.setAvatar(AvatarSource.generic))),
- _chip('Initials', prefs.avatar == AvatarSource.initials, () => unawaited(_store.setAvatar(AvatarSource.initials))),
- if (_store.systemAvatarAvailable)
- _chip('System avatar', avatar.kind == AvatarSource.system, () => unawaited(_store.setAvatar(AvatarSource.system)), tooltip: 'Use ${_store.systemAvatarPath}'),
- _chip('Custom image…', avatar.kind == AvatarSource.custom, () => unawaited(_pickAvatar()), tooltip: 'An SVG or PNG, up to 2 MB, cropped to a circle'),
- if (prefs.avatar == AvatarSource.initials)
- SizedBox(
- width: 90,
- child: TextField(
- controller: _initials,
- maxLength: 3,
- decoration: const InputDecoration(isDense: true, counterText: '', hintText: 'AB'),
- onChanged: (v) => unawaited(_store.setInitials(v)),
- ),
- ),
- ]),
- ),
- const SizedBox(width: 16),
- SizedBox(
- width: 200,
- child: Center(
- child: DecoratedBox(
- decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: neon.yellow, width: 2)),
- child: Padding(padding: const EdgeInsets.all(3), child: AvatarBadge(avatar: avatar, size: 40, color: neon.yellow, background: neon.background)),
- ),
- ),
- ),
- ],
- ),
- if (_avatarError != null) Padding(padding: const EdgeInsets.only(top: 8), child: Text(_avatarError!, style: error)),
- const SizedBox(height: 24),
- ],
- );
- },
- );
- }
-}
diff --git a/desktop/lib/core/startup.dart b/desktop/lib/core/startup.dart
index dc7dc2fdb..352cf9fdd 100644
--- a/desktop/lib/core/startup.dart
+++ b/desktop/lib/core/startup.dart
@@ -1,4 +1,3 @@
-import '../branding/brand_prefs.dart';
import '../shared/theme/appearance_prefs_store.dart';
import '../stats/harness_stats.dart';
import '../terminal/terminal_font_store.dart';
@@ -26,7 +25,6 @@ Future<void> loadPersistedSettings({
AlertSoundStore? alertSounds,
ScreenAlertStore? screenAlerts,
DesktopNotificationStore? desktopNotifications,
- BrandPrefsStore? brand,
}) async {
// Independent stores may load together, but all must finish before runApp.
// Font and appearance share a serialized file store; each reads its related
@@ -48,7 +46,5 @@ Future<void> loadPersistedSettings({
(alertSounds ?? alertSoundStore).load(),
(screenAlerts ?? screenAlertStore).load(),
(desktopNotifications ?? desktopNotificationStore).load(),
- // Before the first frame, so the boot splash knows whether, and which logo, to draw.
- (brand ?? brandPrefsStore).load(),
]);
}
diff --git a/desktop/lib/desktop_workspace.dart b/desktop/lib/desktop_workspace.dart
index 9d9f5da32..8320c2502 100644
--- a/desktop/lib/desktop_workspace.dart
+++ b/desktop/lib/desktop_workspace.dart
@@ -1,15 +1,12 @@
import 'package:flutter/widgets.dart';
-import 'fleet/fleet_overview.dart';
import 'screens/swarm_screen.dart';
import 'state/app_state.dart';
/// The signed-in screen of a native build. A browser build compiles
/// `web/web_entry.dart` in its place (the conditional import in `main.dart`),
-/// so native code never reaches `lib/web/`. The fleet overview (Ctrl+Shift+G)
-/// wraps the native workspace only.
-Widget authenticatedWorkspace(AppNotifier app) =>
- FleetOverviewHost(app: app, child: SwarmScreen(notifier: app));
+/// so native code never reaches `lib/web/`.
+Widget authenticatedWorkspace(AppNotifier app) => SwarmScreen(notifier: app);
/// A native build draws nothing around its screens.
Widget appFrame(Widget app) => app;
diff --git a/desktop/lib/fleet/fleet_graph.dart b/desktop/lib/fleet/fleet_graph.dart
deleted file mode 100644
index b255a168e..000000000
--- a/desktop/lib/fleet/fleet_graph.dart
+++ /dev/null
@@ -1,390 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-import 'dart:math' as math;
-
-import 'package:flutter/material.dart';
-
-import '../state/attention_state.dart';
-import '../branding/brand_mark.dart';
-import '../branding/brand_prefs.dart';
-import 'neon.dart';
-
-/// One agent as the fleet graph draws it.
-@immutable
-class FleetAgent {
- const FleetAgent({required this.id, required this.name, required this.state, this.lane, this.spendFraction});
- final String id, name;
- final AgentAttention state;
- final String? lane;
- final double? spendFraction;
-
- @override
- bool operator ==(Object other) => other is FleetAgent && other.id == id && other.name == name && other.state == state && other.lane == lane && other.spendFraction == spendFraction;
- @override
- int get hashCode => Object.hash(id, name, state, lane, spendFraction);
-}
-
-/// One machine and its agents.
-@immutable
-class FleetMachine {
- const FleetMachine({required this.id, required this.name, required this.connected, this.local = false, this.agents = const []});
- final String id, name;
- final bool connected, local;
- final List<FleetAgent> agents;
-
- @override
- bool operator ==(Object other) =>
- other is FleetMachine && other.id == id && other.name == name && other.connected == connected && other.local == local && _listEq(other.agents, agents);
- @override
- int get hashCode => Object.hash(id, name, connected, local, Object.hashAll(agents));
-}
-
-bool _listEq<T>(List<T> a, List<T> b) {
- if (a.length != b.length) return false;
- for (var i = 0; i < a.length; i++) {
- if (a[i] != b[i]) return false;
- }
- return true;
-}
-
-const _priority = [AgentAttention.permission, AgentAttention.waiting, AgentAttention.failed, AgentAttention.done, AgentAttention.working, AgentAttention.idle, AgentAttention.offline];
-
-bool _live(AgentAttention s) => s == AgentAttention.working || s == AgentAttention.waiting || s == AgentAttention.permission || s == AgentAttention.failed;
-
-/// Where every node sits at phase 0. Machines on an ellipse around the hub, agents on a small orbit
-/// around their machine; all inside the canvas whatever its size.
-class FleetLayout {
- FleetLayout._(this.hub, this.machines, this.agents, this.machineRadius, this.orbit);
-
- final Offset hub;
- final Map<String, Offset> machines;
- final Map<String, Offset> agents;
- final double machineRadius, orbit;
-
- static FleetLayout compute(Size size, List<FleetMachine> fleet, {double phase = 0}) {
- final hub = size.center(Offset.zero);
- final n = math.max(1, fleet.length);
- final most = fleet.fold<int>(1, (m, f) => math.max(m, f.agents.length));
- final machineRadius = (math.min(size.width, size.height) * 0.07).clamp(14.0, 30.0);
- final orbit = machineRadius + (most > 6 ? 30.0 : 24.0);
- final margin = orbit + 12;
- final rx = math.max(0.0, size.width / 2 - margin), ry = math.max(0.0, size.height / 2 - margin - 10);
- final machines = <String, Offset>{};
- final agents = <String, Offset>{};
- for (var i = 0; i < fleet.length; i++) {
- final m = fleet[i];
- final a = -math.pi / 2 + 2 * math.pi * i / n;
- final c = fleet.length == 1 ? hub + Offset(0, ry * 0.35) : hub + Offset(rx * math.cos(a), ry * math.sin(a));
- machines[m.id] = c;
- final k = m.agents.length;
- // Busy machines turn: the orbit's motion is the machine's activity.
- final spin = m.agents.any((g) => g.state == AgentAttention.working) ? phase * 2 * math.pi : 0.0;
- for (var j = 0; j < k; j++) {
- final b = -math.pi / 2 + 2 * math.pi * j / k + spin;
- agents[m.agents[j].id] = c + Offset(orbit * math.cos(b), orbit * math.sin(b));
- }
- }
- return FleetLayout._(hub, machines, agents, machineRadius, orbit);
- }
-}
-
-/// The fleet at a glance. The hub is this window; each hexagon a machine (dashed link when
-/// it is not connected); each ring an agent in its attention colour and glyph.
-///
-/// Motion carries the state, nothing else moves:
-/// - a machine's agents orbit it only while one of them is working;
-/// - packets flow hub to machine along a link while work runs there, and machine to hub, in the
-/// state colour, while an agent there waits on you or needs permission (direction = who waits on whom);
-/// - waiting rings breathe, permission and failed rings pulse, working rings carry a sweep arc.
-/// The whole graph stops (one static frame) when nothing is live, the window is unfocused, or
-/// reduced motion is on. Tapping an agent calls [onAgentTap].
-class FleetGraph extends StatefulWidget {
- const FleetGraph({super.key, required this.machines, this.onAgentTap, this.hubLabel = 'this app', this.brand});
-
- /// The avatar drawn inside the ring of an agent waiting on you; the app's store when null.
- final BrandPrefsStore? brand;
-
- final List<FleetMachine> machines;
- final ValueChanged<String>? onAgentTap;
- final String hubLabel;
-
- @override
- State<FleetGraph> createState() => _FleetGraphState();
-}
-
-class _FleetGraphState extends State<FleetGraph> with SingleTickerProviderStateMixin {
- late final AnimationController _clock = AnimationController(vsync: this, duration: const Duration(seconds: 12));
- bool _reduced = false;
- Size _size = Size.zero;
-
- bool get _anyLive => widget.machines.any((m) => m.agents.any((a) => _live(a.state)));
-
- @override
- void initState() {
- super.initState();
- WindowFocus.instance.addListener(_sync);
- }
-
- @override
- void didChangeDependencies() {
- super.didChangeDependencies();
- _reduced = Motion.reducedOf(context);
- _sync();
- }
-
- @override
- void didUpdateWidget(FleetGraph old) {
- super.didUpdateWidget(old);
- _sync();
- }
-
- void _sync() {
- final run = _anyLive && !_reduced && WindowFocus.instance.value;
- if (run && !_clock.isAnimating) {
- _clock.repeat();
- } else if (!run && _clock.isAnimating) {
- _clock.stop();
- }
- }
-
- @override
- void dispose() {
- WindowFocus.instance.removeListener(_sync);
- _clock.dispose();
- super.dispose();
- }
-
- void _tap(TapUpDetails d) {
- final cb = widget.onAgentTap;
- if (cb == null) return;
- final l = FleetLayout.compute(_size, widget.machines, phase: _clock.value);
- String? best;
- var bestD = 18.0;
- l.agents.forEach((id, p) {
- final dd = (p - d.localPosition).distance;
- if (dd < bestD) {
- bestD = dd;
- best = id;
- }
- });
- if (best != null) cb(best!);
- }
-
- @override
- Widget build(BuildContext context) {
- final neon = Neon.current();
- final all = [for (final m in widget.machines) ...m.agents];
- final counts = <AgentAttention, int>{};
- for (final a in all) {
- counts[a.state] = (counts[a.state] ?? 0) + 1;
- }
- final top = _priority.where((s) => (counts[s] ?? 0) > 0).firstOrNull;
- final mono = TextStyle(fontFamily: 'monospace', fontSize: 12, color: neon.foreground.withValues(alpha: 0.85));
- return Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Padding(
- padding: const EdgeInsets.fromLTRB(12, 8, 12, 4),
- child: Row(
- children: [
- if (top != null)
- Text('${attentionGlyph(top)} ${counts[top]} ${attentionLabel(top)}', style: mono.copyWith(color: neon.of(top), fontWeight: FontWeight.w700))
- else
- Text('- 0 no agents', style: mono),
- const Spacer(),
- // Legend: glyph and word for every state on screen, so colour is never the only signal.
- for (final s in _priority)
- if (s != top && (counts[s] ?? 0) > 0)
- Padding(
- padding: const EdgeInsets.only(left: 12),
- child: Text('${attentionGlyph(s)} ${counts[s]} ${attentionLabel(s)}', style: mono.copyWith(color: neon.of(s).withValues(alpha: 1))),
- ),
- ],
- ),
- ),
- Expanded(
- child: LayoutBuilder(builder: (context, c) {
- _size = c.biggest;
- final asking = [for (final m in widget.machines) ...m.agents.where((a) => a.state == AgentAttention.waiting || a.state == AgentAttention.permission)];
- final avatar = (widget.brand ?? brandPrefsStore).resolveAvatar();
- return Stack(
- children: [
- GestureDetector(
- onTapUp: _tap,
- child: RepaintBoundary(
- child: CustomPaint(
- size: c.biggest,
- painter: FleetPainter(machines: widget.machines, clock: _clock, neon: neon, hubLabel: widget.hubLabel, reduced: _reduced),
- ),
- ),
- ),
- // Who they wait on: the person's avatar inside each asking agent's ring.
- if (asking.isNotEmpty)
- IgnorePointer(
- child: AnimatedBuilder(
- animation: _clock,
- builder: (context, _) {
- final l = FleetLayout.compute(c.biggest, widget.machines, phase: _reduced ? 0 : _clock.value);
- return Stack(children: [
- for (final a in asking)
- if (l.agents[a.id] case final p?)
- Positioned(
- left: p.dx - 7,
- top: p.dy - 7,
- child: AvatarBadge(avatar: avatar, size: 14, color: neon.of(a.state), background: neon.background),
- ),
- ]);
- },
- ),
- ),
- ],
- );
- }),
- ),
- ],
- );
- }
-}
-
-class FleetPainter extends CustomPainter {
- FleetPainter({required this.machines, required this.clock, required this.neon, required this.hubLabel, required this.reduced}) : super(repaint: clock);
-
- final List<FleetMachine> machines;
- final Animation<double> clock;
- final Neon neon;
- final String hubLabel;
- final bool reduced;
-
- Path _hex(Offset c, double r) {
- final p = Path();
- for (var i = 0; i < 6; i++) {
- final a = math.pi / 6 + i * math.pi / 3;
- final v = c + Offset(r * math.cos(a), r * math.sin(a));
- i == 0 ? p.moveTo(v.dx, v.dy) : p.lineTo(v.dx, v.dy);
- }
- return p..close();
- }
-
- void _label(Canvas canvas, String text, Offset at, Color color, {double size = 11, bool bold = false, double max = 120}) {
- final tp = TextPainter(
- text: TextSpan(text: text, style: TextStyle(fontFamily: 'monospace', fontSize: size, color: color, fontWeight: bold ? FontWeight.w700 : FontWeight.w400)),
- textDirection: TextDirection.ltr,
- maxLines: 1,
- ellipsis: '…',
- )..layout(maxWidth: max);
- tp.paint(canvas, at - Offset(tp.width / 2, 0));
- tp.dispose();
- }
-
- @override
- void paint(Canvas canvas, Size size) {
- final t = reduced ? 0.0 : clock.value;
- final l = FleetLayout.compute(size, machines, phase: t);
- // Faint scanlines behind the graph (design/attention-motion.md: 6 to 10 percent, never over text).
- final scan = Paint()..color = neon.accent.withValues(alpha: 0.06);
- for (var y = 0.0; y < size.height; y += 4) {
- canvas.drawRect(Rect.fromLTWH(0, y, size.width, 1), scan);
- }
-
- // Links and their packets.
- for (final m in machines) {
- final c = l.machines[m.id]!;
- final link = Paint()
- ..strokeWidth = 1.5
- ..color = (m.connected ? neon.accent : neon.foreground).withValues(alpha: m.connected ? 0.45 : 0.18);
- if (m.connected) {
- canvas.drawLine(l.hub, c, link);
- } else {
- final d = c - l.hub;
- final len = d.distance;
- for (var s = 0.0; s < len; s += 10) {
- canvas.drawLine(l.hub + d * (s / len), l.hub + d * (math.min(s + 5, len) / len), link);
- }
- }
- if (!m.connected) continue;
- final working = m.agents.any((a) => a.state == AgentAttention.working);
- final asking = m.agents.map((a) => a.state).where((s) => s == AgentAttention.permission || s == AgentAttention.waiting || s == AgentAttention.failed).toList()
- ..sort((a, b) => _priority.indexOf(a) - _priority.indexOf(b));
- void packets(Offset from, Offset to, Color color, double speed) {
- for (var k = 0; k < 3; k++) {
- final u = ((t * speed) + k / 3) % 1.0;
- final p = Offset.lerp(from, to, u)!;
- canvas.drawCircle(p, 3, Paint()..color = color.withValues(alpha: 0.9 * math.sin(u * math.pi))..maskFilter = const MaskFilter.blur(BlurStyle.normal, 2));
- }
- }
-
- if (working && !reduced) packets(l.hub, c, neon.accent, 6);
- if (asking.isNotEmpty && !reduced) packets(c, l.hub, neon.of(asking.first), 8);
- }
-
- // Hub.
- final hubR = l.machineRadius * 0.75;
- canvas.drawPath(chamferPath(Rect.fromCircle(center: l.hub, radius: hubR), hubR * 0.4), Paint()..color = neon.background);
- canvas.drawPath(chamferPath(Rect.fromCircle(center: l.hub, radius: hubR), hubR * 0.4), Paint()
- ..style = PaintingStyle.stroke
- ..strokeWidth = 1.5
- ..color = neon.accent);
- _label(canvas, hubLabel, l.hub + Offset(0, hubR + 4), neon.foreground.withValues(alpha: 0.7));
-
- // Machines and agents.
- for (final m in machines) {
- final c = l.machines[m.id]!;
- final top = m.agents.map((a) => a.state).fold<AgentAttention?>(null, (best, s) => best == null || _priority.indexOf(s) < _priority.indexOf(best) ? s : best);
- final hex = _hex(c, l.machineRadius);
- canvas.drawPath(hex, Paint()..color = neon.background);
- if (top != null && (top == AgentAttention.permission || top == AgentAttention.waiting || top == AgentAttention.failed)) {
- // Glow is urgency: only a machine with an agent waiting on you glows.
- canvas.drawPath(hex, Paint()
- ..style = PaintingStyle.stroke
- ..strokeWidth = 6
- ..color = neon.of(top).withValues(alpha: 0.35)
- ..maskFilter = const MaskFilter.blur(BlurStyle.outer, 10));
- }
- canvas.drawPath(hex, Paint()
- ..style = PaintingStyle.stroke
- ..strokeWidth = m.local ? 2.5 : 1.5
- ..color = m.connected ? neon.accent : neon.foreground.withValues(alpha: 0.3));
- _label(canvas, m.name, c - const Offset(0, 7), m.connected ? neon.foreground : neon.foreground.withValues(alpha: 0.4), bold: true, max: l.machineRadius * 2 - 4, size: 10);
- _label(canvas, '${m.agents.length}', c + const Offset(0, 1), neon.foreground.withValues(alpha: 0.6), size: 10);
- for (final a in m.agents) {
- _agent(canvas, l.agents[a.id]!, a, t);
- }
- }
- }
-
- void _agent(Canvas canvas, Offset p, FleetAgent a, double t) {
- const r = 9.0;
- final color = neon.of(a.state);
- final ring = Paint()
- ..style = PaintingStyle.stroke
- ..strokeWidth = 2
- ..color = color;
- canvas.drawCircle(p, r, Paint()..color = neon.background);
- final wave = 0.5 - 0.5 * math.cos(t * 2 * math.pi * 6); // ~2 s breaths on a 12 s clock
- switch (a.state) {
- case AgentAttention.working:
- canvas.drawCircle(p, r, ring..color = color.withValues(alpha: 0.3));
- canvas.drawArc(Rect.fromCircle(center: p, radius: r), t * 2 * math.pi * 12, math.pi * 0.8, false, ring..color = color);
- case AgentAttention.waiting || AgentAttention.permission || AgentAttention.failed:
- final k = reduced ? 1.0 : wave;
- canvas.drawCircle(p, r + 2 + 3 * k, Paint()..color = color.withValues(alpha: 0.18 + 0.25 * k)..maskFilter = const MaskFilter.blur(BlurStyle.normal, 5));
- canvas.drawCircle(p, r, ring);
- case AgentAttention.done:
- canvas.drawCircle(p, r, Paint()..color = color.withValues(alpha: 0.85));
- case AgentAttention.idle || AgentAttention.offline:
- canvas.drawCircle(p, r, ring..strokeWidth = 1);
- }
- final f = a.spendFraction;
- if (f != null) {
- canvas.drawArc(Rect.fromCircle(center: p, radius: r + 3.5), -math.pi / 2, 2 * math.pi * f.clamp(0.0, 1.0), false, Paint()
- ..style = PaintingStyle.stroke
- ..strokeWidth = 1.5
- ..color = neon.spend(f));
- }
- _label(canvas, attentionGlyph(a.state), p - const Offset(0, 7), a.state == AgentAttention.done ? neon.background : color, size: 11, bold: true);
- _label(canvas, a.lane == null ? a.name : '${a.name} ${a.lane![0].toUpperCase()}', p + const Offset(0, r + 3), neon.foreground.withValues(alpha: 0.75), size: 9, max: 90);
- }
-
- @override
- bool shouldRepaint(FleetPainter old) => old.machines != machines && !_listEq(old.machines, machines) || old.neon != neon || old.reduced != reduced || old.hubLabel != hubLabel;
-}
diff --git a/desktop/lib/fleet/fleet_overview.dart b/desktop/lib/fleet/fleet_overview.dart
deleted file mode 100644
index 6de8acbd4..000000000
--- a/desktop/lib/fleet/fleet_overview.dart
+++ /dev/null
@@ -1,183 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-import 'package:flutter/material.dart';
-import 'package:flutter/services.dart';
-
-import '../core/models.dart' show ConnectionStatus;
-import '../state/app_state.dart';
-import '../state/attention_state.dart';
-import 'fleet_graph.dart';
-import 'neon.dart';
-
-/// The fleet as [FleetGraph] reads it, built from the machines this window knows and the
-/// local daemon's attention frame. A machine's agents take their state from the frame; an agent the
-/// frame does not cover (another machine's, until that daemon's frame is relayed) reads idle when
-/// its machine is connected and offline when not, which is all this window can honestly say.
-List<FleetMachine> fleetFrom(AppNotifier app) {
- final attention = app.attention;
- final seen = <String>{};
- final out = <FleetMachine>[];
- for (final m in app.machines) {
- final st = app.stateOf(m.machineId);
- if (st == null) continue;
- final connected = st.connectionStatus == ConnectionStatus.connected;
- final agents = <FleetAgent>[];
- for (final a in st.agents) {
- final row = attention.of(a.id);
- seen.add(a.id);
- agents.add(FleetAgent(
- id: a.id,
- name: row?.name.isNotEmpty == true ? row!.name : a.name,
- state: row?.state ?? (connected ? AgentAttention.idle : AgentAttention.offline),
- lane: row?.lane,
- spendFraction: row?.spendFraction,
- ));
- }
- out.add(FleetMachine(id: m.machineId, name: m.displayName, connected: connected, local: st.isLocalMachine, agents: agents));
- }
- // Rows the frame carries that no machine lists yet (a session starting up) go on the local machine.
- final orphans = [for (final r in attention.rows) if (!seen.contains(r.agentId)) FleetAgent(id: r.agentId, name: r.name.isEmpty ? r.agentId : r.name, state: r.state, lane: r.lane, spendFraction: r.spendFraction)];
- if (orphans.isNotEmpty) {
- final i = out.indexWhere((m) => m.local);
- if (i >= 0) {
- final m = out[i];
- out[i] = FleetMachine(id: m.id, name: m.name, connected: m.connected, local: true, agents: [...m.agents, ...orphans]);
- } else {
- out.add(FleetMachine(id: 'local', name: attention.hostname.isEmpty ? 'this machine' : attention.hostname, connected: true, local: true, agents: orphans));
- }
- }
- return out;
-}
-
-/// Hosts the fleet overview above the workspace. Opened from the command bar ("Fleet overview") or
-/// Ctrl+Shift+G; Escape, the close button or a click outside the panel closes it. The panel is a
-/// fixed size inside the window: nothing in it scrolls (motion never moves the layout).
-class FleetOverviewHost extends StatelessWidget {
- const FleetOverviewHost({super.key, required this.app, required this.child});
-
- final AppNotifier app;
- final Widget child;
-
- @override
- Widget build(BuildContext context) {
- return CallbackShortcuts(
- bindings: {
- const SingleActivator(LogicalKeyboardKey.keyG, control: true, shift: true): () => app.fleetOverviewOpen.value = !app.fleetOverviewOpen.value,
- },
- child: Stack(
- fit: StackFit.expand,
- children: [
- child,
- ValueListenableBuilder<bool>(
- valueListenable: app.fleetOverviewOpen,
- builder: (context, open, _) => open ? _FleetPanel(app: app) : const SizedBox.shrink(),
- ),
- ],
- ),
- );
- }
-}
-
-class _FleetPanel extends StatelessWidget {
- const _FleetPanel({required this.app});
- final AppNotifier app;
-
- void _close() => app.fleetOverviewOpen.value = false;
-
- @override
- Widget build(BuildContext context) {
- final neon = Neon.current();
- return CallbackShortcuts(
- bindings: {const SingleActivator(LogicalKeyboardKey.escape): _close},
- child: Focus(
- autofocus: true,
- child: GestureDetector(
- behavior: HitTestBehavior.opaque,
- onTap: _close,
- child: ColoredBox(
- color: Colors.black.withValues(alpha: 0.55),
- child: Center(
- child: GestureDetector(
- onTap: () {}, // clicks inside the panel stay inside
- child: FractionallySizedBox(
- widthFactor: 0.78,
- heightFactor: 0.78,
- child: CustomPaint(
- foregroundPainter: _ChamferFrame(neon.accent),
- child: ClipPath(
- clipper: _ChamferClip(),
- child: ColoredBox(
- color: neon.background,
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Padding(
- padding: const EdgeInsets.fromLTRB(16, 10, 6, 0),
- child: Row(
- children: [
- Text('FLEET', style: TextStyle(fontFamily: 'monospace', fontSize: 12, letterSpacing: 3, fontWeight: FontWeight.w700, color: neon.accent)),
- const SizedBox(width: 12),
- Expanded(
- child: Text('machines, their agents and what each needs; click an agent to open it',
- maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 12, color: neon.foreground.withValues(alpha: 0.55))),
- ),
- IconButton(tooltip: 'Close (Esc)', icon: const Icon(Icons.close, size: 16), color: neon.foreground, onPressed: _close),
- ],
- ),
- ),
- Expanded(
- child: ListenableBuilder(
- listenable: Listenable.merge([app, app.attention]),
- builder: (context, _) => FleetGraph(
- machines: fleetFrom(app),
- hubLabel: 'this window',
- onAgentTap: (agentId) {
- final m = fleetFrom(app).where((m) => m.agents.any((a) => a.id == agentId)).firstOrNull;
- _close();
- if (m != null && m.id != 'local') app.openAgentFromDial(m.id, agentId, intent: AttachIntent.person);
- },
- ),
- ),
- ),
- ],
- ),
- ),
- ),
- ),
- ),
- ),
- ),
- ),
- ),
- ),
- );
- }
-}
-
-class _ChamferClip extends CustomClipper<Path> {
- @override
- Path getClip(Size size) => chamferPath(Offset.zero & size, 18);
- @override
- bool shouldReclip(_ChamferClip old) => false;
-}
-
-class _ChamferFrame extends CustomPainter {
- const _ChamferFrame(this.color);
- final Color color;
- @override
- void paint(Canvas canvas, Size size) {
- final p = chamferPath((Offset.zero & size).deflate(0.75), 18);
- canvas.drawPath(p, Paint()
- ..style = PaintingStyle.stroke
- ..strokeWidth = 6
- ..color = color.withValues(alpha: 0.25)
- ..maskFilter = const MaskFilter.blur(BlurStyle.outer, 12));
- canvas.drawPath(p, Paint()
- ..style = PaintingStyle.stroke
- ..strokeWidth = 1.5
- ..color = color);
- }
-
- @override
- bool shouldRepaint(_ChamferFrame old) => old.color != color;
-}
diff --git a/desktop/lib/fleet/neon.dart b/desktop/lib/fleet/neon.dart
deleted file mode 100644
index 26c8e5e6f..000000000
--- a/desktop/lib/fleet/neon.dart
+++ /dev/null
@@ -1,108 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-import 'dart:io' show Platform;
-
-import 'package:flutter/foundation.dart';
-import 'package:flutter/widgets.dart';
-
-import '../shared/theme/color_palette.dart';
-import '../state/attention_state.dart';
-import '../shared/theme/app_theme.dart' as grid;
-
-/// The neon every animated surface in the app draws with (design/attention-motion.md, "the language").
-///
-/// Accent comes from the app palette (the Omarchy palette follows the live theme). Yellow, red and
-/// green come from the Omarchy theme file when the theme's colour still reads as that colour, else
-/// from fixed fallbacks: a theme that maps `red` to a green (some do) would otherwise make a
-/// permission request look like a working agent, and the colour is the state.
-@immutable
-class Neon {
- const Neon({required this.accent, required this.yellow, required this.red, required this.green, required this.foreground, required this.background});
-
- final Color accent, yellow, red, green, foreground, background;
-
- static const fallbackYellow = Color(0xFFEAB308);
- static const fallbackRed = Color(0xFFEF4444);
- static const fallbackGreen = Color(0xFF22C55E);
-
- static Neon current() {
- final p = grid.AppTheme.palette.value;
- return Neon(
- accent: p.accent,
- yellow: themed('yellow', fallbackYellow, 35, 70),
- red: themed('red', fallbackRed, 335, 20),
- green: themed('green', fallbackGreen, 90, 170),
- foreground: p.foreground,
- background: p.background,
- );
- }
-
- /// The theme's [key] colour when its hue sits in [lo]..[hi] degrees (wrapping) and it is not grey.
- @visibleForTesting
- static Color themed(String key, Color fallback, double lo, double hi, {Color? Function(String)? read}) {
- final c = (read ?? OmarchyLivePalette.color)(key);
- if (c == null) return fallback;
- final hsv = HSVColor.fromColor(c);
- if (hsv.saturation < 0.35) return fallback;
- final h = hsv.hue;
- final inRange = lo <= hi ? (h >= lo && h <= hi) : (h >= lo || h <= hi);
- return inRange ? c : fallback;
- }
-
- /// The one colour per attention state, shared by pane borders, rings and the fleet graph.
- Color of(AgentAttention s) => switch (s) {
- AgentAttention.working => accent,
- AgentAttention.waiting => yellow,
- AgentAttention.permission || AgentAttention.failed => red,
- AgentAttention.done => green,
- AgentAttention.idle => foreground.withValues(alpha: 0.35),
- AgentAttention.offline => foreground.withValues(alpha: 0.15),
- };
-
- /// Spend arc colour: accent, amber from 80 percent, red at the cap (design/attention-motion.md "arcs are quantities").
- Color spend(double fraction) => fraction >= 1 ? red : fraction >= 0.8 ? yellow : accent;
-
- @override
- bool operator ==(Object other) =>
- other is Neon && other.accent == accent && other.yellow == yellow && other.red == red && other.green == green && other.foreground == foreground && other.background == background;
-
- @override
- int get hashCode => Object.hash(accent, yellow, red, green, foreground, background);
-}
-
-/// The one reduced-motion switch (design/attention-motion.md: "every animation sits behind one switch").
-/// On when the platform asks for no animations, or when `HARNESS_REDUCED_MOTION=1` is set in the
-/// environment or at build time. Tests set [override].
-abstract final class Motion {
- static bool? override;
- static final bool _env = const bool.fromEnvironment('HARNESS_REDUCED_MOTION') || (!kIsWeb && Platform.environment['HARNESS_REDUCED_MOTION'] == '1');
-
- static bool reducedOf(BuildContext context) => override ?? (_env || (MediaQuery.maybeDisableAnimationsOf(context) ?? false));
-}
-
-/// Whether the window has focus, so looping animations can stop while nobody is looking.
-/// Driven by the app lifecycle (desktop embedders report focus loss as `inactive`). Starts true.
-class WindowFocus extends ValueNotifier<bool> with WidgetsBindingObserver {
- WindowFocus._() : super(true) {
- WidgetsBinding.instance.addObserver(this);
- final s = WidgetsBinding.instance.lifecycleState;
- if (s != null) value = s == AppLifecycleState.resumed;
- }
-
- static WindowFocus? _instance;
- static WindowFocus get instance => _instance ??= WindowFocus._();
-
- @override
- void didChangeAppLifecycleState(AppLifecycleState state) => value = state == AppLifecycleState.resumed;
-}
-
-/// The Omarchy chamfer (two-step bevel on the top-left and bottom-right corners) as a path, the shape
-/// the wordmark's letters carry. Used for hexagon-free tiles and the splash frame.
-Path chamferPath(Rect r, double c) => Path()
- ..moveTo(r.left + c, r.top)
- ..lineTo(r.right, r.top)
- ..lineTo(r.right, r.bottom - c)
- ..lineTo(r.right - c, r.bottom)
- ..lineTo(r.left, r.bottom)
- ..lineTo(r.left, r.top + c)
- ..close();
diff --git a/desktop/lib/fleet/spend_ring.dart b/desktop/lib/fleet/spend_ring.dart
deleted file mode 100644
index 459fee60b..000000000
--- a/desktop/lib/fleet/spend_ring.dart
+++ /dev/null
@@ -1,230 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-import 'dart:math' as math;
-
-import 'package:flutter/material.dart';
-
-import '../state/attention_state.dart';
-import '../branding/brand_mark.dart';
-import '../branding/brand_prefs.dart';
-import 'neon.dart';
-
-/// The per-agent spend arc drawn around the pane header's engine mark (design/attention-motion.md, "arcs
-/// are quantities"). Present only when a per-agent cap is set (the daemon sends `spend.fraction`).
-/// Accent below 80 percent, amber from 80, red at the cap. The child keeps its size: the arc is
-/// painted outside it, so the header's layout never moves.
-///
-/// While the agent waits on you (a question or a permission request) the mark is replaced by your
-/// avatar inside a ring in the state colour: the header says who it is waiting on, not just that it
-/// waits. The avatar is the one chosen in Settings, Appearance ([BrandPrefsStore]).
-class SpendRing extends StatefulWidget {
- const SpendRing({super.key, required this.attention, required this.agentId, required this.child, this.gap = 3, this.brand});
-
- final AttentionState attention;
- final String agentId;
- final Widget child;
- final double gap;
- final BrandPrefsStore? brand;
-
- @override
- State<SpendRing> createState() => _SpendRingState();
-}
-
-class _SpendRingState extends State<SpendRing> {
- double? _fraction;
- double? _usd;
- AgentAttention? _state;
-
- BrandPrefsStore get _brand => widget.brand ?? brandPrefsStore;
-
- bool get _asking => _state == AgentAttention.waiting || _state == AgentAttention.permission;
-
- @override
- void initState() {
- super.initState();
- widget.attention.addListener(_onFrame);
- _brand.addListener(_onBrand);
- _read();
- }
-
- void _onBrand() {
- if (_asking && mounted) setState(() {});
- }
-
- @override
- void didUpdateWidget(SpendRing old) {
- super.didUpdateWidget(old);
- if (!identical(old.attention, widget.attention)) {
- old.attention.removeListener(_onFrame);
- widget.attention.addListener(_onFrame);
- }
- _read();
- }
-
- bool _read() {
- final row = widget.attention.of(widget.agentId);
- final f = row?.spendFraction, u = row?.spendUsd, st = row?.state;
- if (f == _fraction && u == _usd && st == _state) return false;
- _fraction = f;
- _usd = u;
- _state = st;
- return true;
- }
-
- void _onFrame() {
- if (_read() && mounted) setState(() {});
- }
-
- @override
- void dispose() {
- widget.attention.removeListener(_onFrame);
- _brand.removeListener(_onBrand);
- super.dispose();
- }
-
- @override
- Widget build(BuildContext context) {
- final f = _fraction;
- if (_asking) return _avatar(context, f);
- if (f == null) return widget.child;
- final pct = (f * 100).round();
- final usd = _usd == null ? '' : '\$${_usd!.toStringAsFixed(2)} spent, ';
- return Tooltip(
- message: '$usd$pct% of the cap',
- child: Stack(
- clipBehavior: Clip.none,
- alignment: Alignment.center,
- children: [
- widget.child,
- Positioned(
- left: -widget.gap - 2,
- top: -widget.gap - 2,
- right: -widget.gap - 2,
- bottom: -widget.gap - 2,
- child: IgnorePointer(child: SpendArc(fraction: f)),
- ),
- ],
- ),
- );
- }
-}
-
-extension on _SpendRingState {
- Widget _avatar(BuildContext context, double? f) {
- final neon = Neon.current();
- final color = neon.of(_state!);
- final label = _state == AgentAttention.permission ? 'Needs your permission' : 'Waiting on you';
- return Tooltip(
- message: f == null ? label : '$label, ${(f * 100).round()}% of the spend cap',
- child: Stack(
- clipBehavior: Clip.none,
- alignment: Alignment.center,
- children: [
- // Same footprint as the mark it replaces, so the header does not move.
- Opacity(opacity: 0, child: widget.child),
- Positioned.fill(
- child: AvatarBadge(avatar: _brand.resolveAvatar(), size: 17, color: color, background: neon.background),
- ),
- Positioned(
- left: -widget.gap - 2,
- top: -widget.gap - 2,
- right: -widget.gap - 2,
- bottom: -widget.gap - 2,
- child: IgnorePointer(
- child: f == null
- ? CustomPaint(painter: SpendArcPainter(fraction: 1, color: color, track: color, stroke: 2))
- : SpendArc(fraction: f),
- ),
- ),
- ],
- ),
- );
- }
-}
-
-/// A 0..100 percent arc that eases to its new value, turns amber at 80 percent and holds red at the
-/// cap, where it pulses once (the moment it crosses) and then stays still.
-class SpendArc extends StatefulWidget {
- const SpendArc({super.key, required this.fraction, this.stroke = 2});
-
- final double fraction;
- final double stroke;
-
- @override
- State<SpendArc> createState() => _SpendArcState();
-}
-
-class _SpendArcState extends State<SpendArc> with SingleTickerProviderStateMixin {
- late final AnimationController _pulse = AnimationController(vsync: this, duration: const Duration(milliseconds: 700), value: 1);
-
- @override
- void didUpdateWidget(SpendArc old) {
- super.didUpdateWidget(old);
- if (old.fraction < 1 && widget.fraction >= 1 && !Motion.reducedOf(context)) _pulse.forward(from: 0);
- }
-
- @override
- void dispose() {
- _pulse.dispose();
- super.dispose();
- }
-
- @override
- Widget build(BuildContext context) {
- final neon = Neon.current();
- final reduced = Motion.reducedOf(context);
- return RepaintBoundary(
- child: TweenAnimationBuilder<double>(
- tween: Tween(end: widget.fraction),
- duration: reduced ? Duration.zero : const Duration(milliseconds: 450),
- curve: Curves.easeOutCubic,
- builder: (context, f, _) => AnimatedBuilder(
- animation: _pulse,
- builder: (context, _) => CustomPaint(
- painter: SpendArcPainter(
- fraction: f,
- color: neon.spend(f),
- track: neon.foreground.withValues(alpha: 0.12),
- stroke: widget.stroke,
- pulse: _pulse.value,
- ),
- ),
- ),
- ),
- );
- }
-}
-
-class SpendArcPainter extends CustomPainter {
- const SpendArcPainter({required this.fraction, required this.color, required this.track, required this.stroke, this.pulse = 1});
-
- final double fraction;
- final Color color, track;
- final double stroke;
-
- /// 0..1 through the cap-crossing pulse; 1 when none is running.
- final double pulse;
-
- @override
- void paint(Canvas canvas, Size size) {
- final r = Rect.fromCircle(center: size.center(Offset.zero), radius: math.min(size.width, size.height) / 2 - stroke / 2);
- final p = Paint()
- ..style = PaintingStyle.stroke
- ..strokeWidth = stroke
- ..strokeCap = StrokeCap.round;
- canvas.drawArc(r, 0, 2 * math.pi, false, p..color = track);
- final sweep = 2 * math.pi * fraction.clamp(0.0, 1.0);
- if (pulse < 1) {
- final t = math.sin(pulse * math.pi);
- canvas.drawArc(r.inflate(2 * t), -math.pi / 2, sweep, false, Paint()
- ..style = PaintingStyle.stroke
- ..strokeWidth = stroke + 3 * t
- ..color = color.withValues(alpha: 0.5 * t)
- ..maskFilter = MaskFilter.blur(BlurStyle.normal, 4 * t + 0.01));
- }
- canvas.drawArc(r, -math.pi / 2, sweep, false, p..color = color);
- }
-
- @override
- bool shouldRepaint(SpendArcPainter old) => old.fraction != fraction || old.color != color || old.track != track || old.stroke != stroke || old.pulse != pulse;
-}
diff --git a/desktop/lib/settings/appearance/palette_section.dart b/desktop/lib/settings/appearance/palette_section.dart
index 42b0ba1c9..41be81cd6 100644
--- a/desktop/lib/settings/appearance/palette_section.dart
+++ b/desktop/lib/settings/appearance/palette_section.dart
@@ -36,19 +36,14 @@ class PaletteSection extends StatelessWidget {
spacing: 12,
runSpacing: 12,
children: [
- for (final palette in HarnessPalette.offered)
+ for (final palette in HarnessPalette.values)
SizedBox(
width: width,
child: _PaletteChoice(
palette: palette,
selected: prefs.palette == palette,
- onChoose: () {
- // Re-read the Omarchy theme file so a theme switch shows on pick.
- if (palette == HarnessPalette.omarchy) {
- OmarchyLivePalette.refresh();
- }
- unawaited(preferences.setPalette(palette));
- },
+ onChoose: () =>
+ unawaited(preferences.setPalette(palette)),
),
),
],
diff --git a/desktop/lib/settings/sections/appearance_section.dart b/desktop/lib/settings/sections/appearance_section.dart
index ad7fdabb8..6ae4370b4 100644
--- a/desktop/lib/settings/sections/appearance_section.dart
+++ b/desktop/lib/settings/sections/appearance_section.dart
@@ -1,6 +1,5 @@
import 'package:flutter/material.dart';
-import '../../branding/brand_section.dart';
import '../../shared/theme/app_theme.dart' as grid;
import '../appearance/palette_section.dart';
import '../../shared/theme/appearance_prefs_store.dart';
@@ -22,8 +21,6 @@ class AppearanceSection extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
PaletteSection(store: store),
- // Boot logo (off by default) and the avatar shown to agents waiting on you.
- const BrandSection(),
// Room under the last card so a scrolled-to-bottom pane does not end
// flush against the window edge.
const SizedBox(height: 8),
diff --git a/desktop/lib/shared/theme/color_palette.dart b/desktop/lib/shared/theme/color_palette.dart
index 19cf244b0..59ea94b6e 100644
--- a/desktop/lib/shared/theme/color_palette.dart
+++ b/desktop/lib/shared/theme/color_palette.dart
@@ -2,8 +2,6 @@ import 'dart:ui' show Brightness;
import 'package:flutter/painting.dart';
-import '../../theme/omarchy_theme.dart';
-
/// Coordinated workspace colors. These feed the existing design-system tokens,
/// native tabs/search, and terminal defaults; they do not change agent state.
///
@@ -83,20 +81,6 @@ enum HarnessPalette {
search: Color(0xff3c3129),
accent: Color(0xffe6c39e),
),
- // Follows the Omarchy theme on this computer (theme/omarchy_theme.dart; first written by Fred Nix
- // in the nixfred fork). These constants are Graphite's, the fallback for a missing file or key.
- omarchy(
- 'Omarchy',
- 'Follows your Omarchy theme',
- background: Color(0xff181818),
- panel: Color(0xff141414),
- card: Color(0xff1e1e1e),
- hover: Color(0xff252525),
- workspace: Color(0xff282828),
- tabBar: Color(0xff1c1c1c),
- search: Color(0xff2c2c2c),
- accent: Color(0xffbdcbdc),
- ),
// The light palettes mirror the dark ones' layering: the workspace gutter and
// tab bar sit a step darker than the terminal ground, cards a step lighter.
// Their accents are deep rather than pale, since an accent is drawn as text,
@@ -134,43 +118,23 @@ enum HarnessPalette {
this.label,
this.description, {
this.brightness = Brightness.dark,
- this._foreground = const Color(0xfff5f5f5),
- required this._background,
- required this._panel,
- required this._card,
- required this._hover,
- required this._workspace,
- required this._tabBar,
- required this._search,
- required this._accent,
+ this.foreground = const Color(0xfff5f5f5),
+ required this.background,
+ required this.panel,
+ required this.card,
+ required this.hover,
+ required this.workspace,
+ required this.tabBar,
+ required this.search,
+ required this.accent,
});
final String label, description;
final Brightness brightness;
- final Color _foreground;
- final Color _background, _panel, _card, _hover, _workspace, _tabBar, _search, _accent;
-
- // Every preset answers with its own constants; `omarchy` answers from the live Omarchy theme file,
- // falling back to its constants when the file is missing or a key is absent.
- Color _live(String key, Color fallback) =>
- this == omarchy ? (OmarchyLivePalette.color(key) ?? fallback) : fallback;
- Color get foreground => _live('foreground', _foreground);
- Color get background => _live('background', _background);
- Color get panel => _live('darker_background', _panel);
- Color get card => _live('lighter_background', _card);
- Color get hover => _live('lighter_background', _hover);
- Color get workspace => _live('dark_background', _workspace);
- Color get tabBar => _live('darker_background', _tabBar);
- Color get search => _live('lighter_background', _search);
- Color get accent => _live('accent', _accent);
+ final Color foreground;
+ final Color background, panel, card, hover, workspace, tabBar, search, accent;
bool get isDark => brightness == Brightness.dark;
- /// The palettes the picker offers here: Omarchy only where there is a theme to follow.
- static List<HarnessPalette> get offered => [
- for (final palette in values)
- if (palette != omarchy || omarchyInstalled()) palette,
- ];
-
static HarnessPalette fromId(String? id) =>
values.where((palette) => palette.name == id).firstOrNull ?? graphite;
@@ -185,11 +149,3 @@ enum HarnessPalette {
'dark': isDark ? 1 : 0,
};
}
-
-/// The Omarchy theme's colours, read once and on demand. `refresh()` re-reads the file (the palette
-/// picker calls it when Omarchy is chosen, so a theme switch shows on the next pick).
-abstract final class OmarchyLivePalette {
- static Map<String, Color>? _colors;
- static Color? color(String key) => (_colors ??= readOmarchyColors())[key];
- static void refresh() => _colors = readOmarchyColors();
-}
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 5b452ea51..5de9a8164 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -76,7 +76,6 @@ import 'take_over.dart';
import '../widgets/engine_identity.dart'
show allEngines, engineIdentity, isTerminalEngine;
import '../store/store_screen.dart' show openStoreAgent;
-import 'attention_state.dart';
import 'dial_status.dart';
import 'grid_pictures.dart';
import 'model_start_watch.dart';
@@ -2942,13 +2941,6 @@ class AppNotifier extends ChangeNotifier {
/// frames from the local daemon; its own notifier, so the row rebuilds
/// without dragging the whole rail through a machine-list rebuild.
final DialState dial;
-
- /// Per-agent attention from the local daemon's `attention` frame (cli/src/fleet/control.ts):
- /// drives the pane frame and the fleet overview.
- final AttentionState attention = AttentionState();
-
- /// Whether the fleet overview panel is showing (lib/fleet/fleet_overview.dart).
- final ValueNotifier<bool> fleetOverviewOpen = ValueNotifier(false);
final AgentPreference agentPreference;
final ProjectHistory projectHistory;
@@ -14995,10 +14987,6 @@ class AppNotifier extends ChangeNotifier {
// ── the dial, over the cable, forwarded by the local daemon ──────────────────────────────────
// Local-only frames (backend.sendLocal in the harness CLI): they describe a hand at THIS desk, so
// they never reach the cloud web audience, who may be sitting at another computer entirely.
- case 'attention':
- // What each agent needs from a person; drives the pane frame and the fleet overview.
- attention.apply(payload);
- return;
case 'dial_status':
// The dial came, went, or started taking an update. Its own notifier —
// see [dial] — so nothing else in the window rebuilds for it.
diff --git a/desktop/lib/state/attention_state.dart b/desktop/lib/state/attention_state.dart
deleted file mode 100644
index b931d9750..000000000
--- a/desktop/lib/state/attention_state.dart
+++ /dev/null
@@ -1,130 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-import 'package:flutter/foundation.dart';
-
-/// What each agent needs from a person, as the local daemon's `attention` frame reports it
-/// (cli/src/lib/attention.ts). Its own notifier, like [DialState], so a state change only
-/// rebuilds the panes that draw it.
-enum AgentAttention { working, waiting, permission, failed, done, idle, offline }
-
-AgentAttention attentionFromWire(Object? v) => switch (v) {
- 'working' => AgentAttention.working,
- 'waiting' => AgentAttention.waiting,
- 'permission' => AgentAttention.permission,
- 'failed' => AgentAttention.failed,
- 'done' => AgentAttention.done,
- 'offline' => AgentAttention.offline,
- _ => AgentAttention.idle,
- };
-
-/// Same glyphs and words as cli/src/lib/attention.ts (ATTENTION_GLYPH, ATTENTION_LABEL).
-String attentionGlyph(AgentAttention s) => switch (s) {
- AgentAttention.working => '~',
- AgentAttention.waiting => '?',
- AgentAttention.permission => '!',
- AgentAttention.failed => 'x',
- AgentAttention.done => '*',
- AgentAttention.idle => '-',
- AgentAttention.offline => '.',
- };
-
-String attentionLabel(AgentAttention s) => switch (s) {
- AgentAttention.working => 'working',
- AgentAttention.waiting => 'waiting on you',
- AgentAttention.permission => 'needs permission',
- AgentAttention.failed => 'failed',
- AgentAttention.done => 'done, unreviewed',
- AgentAttention.idle => 'idle',
- AgentAttention.offline => 'offline',
- };
-
-@immutable
-class AttentionRow {
- const AttentionRow({
- required this.agentId,
- required this.state,
- this.detail = '',
- this.spendFraction,
- this.spendUsd,
- this.name = '',
- this.machine = '',
- this.lane,
- });
- final String agentId;
- final AgentAttention state;
- final String detail;
- final double? spendFraction;
- final double? spendUsd;
-
- /// Display name, host name and policy lane as the daemon sends them (empty or null when absent).
- final String name;
- final String machine;
- final String? lane;
-
- /// The glyph and word every state carries so colour is never the only signal (design/attention-motion.md).
- String get glyph => attentionGlyph(state);
- String get label => attentionLabel(state);
-
- /// Needs a person now: the pane glows for these and only these.
- bool get needsYou => state == AgentAttention.waiting || state == AgentAttention.permission || state == AgentAttention.failed;
-
- // Value equality, so an identical frame (one arrives every second) does not repaint every pane.
- @override
- bool operator ==(Object other) =>
- other is AttentionRow &&
- other.agentId == agentId &&
- other.state == state &&
- other.detail == detail &&
- other.spendFraction == spendFraction &&
- other.spendUsd == spendUsd &&
- other.name == name &&
- other.machine == machine &&
- other.lane == lane;
-
- @override
- int get hashCode => Object.hash(agentId, state, detail, spendFraction, spendUsd, name, machine, lane);
-}
-
-class AttentionState extends ChangeNotifier {
- final Map<String, AttentionRow> _rows = {};
-
- AttentionRow? of(String agentId) => _rows[agentId];
-
- /// Every row from the last frame, in the daemon's priority order.
- Iterable<AttentionRow> get rows => _rows.values;
-
- /// The host that sent the last frame (`hostname` on the payload), empty before the first one.
- String get hostname => _hostname;
- String _hostname = '';
-
- /// Replace from one `attention` frame payload. Unknown shapes are ignored, never thrown.
- void apply(Map<String, dynamic> payload) {
- final agents = payload['agents'];
- if (agents is! List) return;
- final next = <String, AttentionRow>{};
- for (final a in agents) {
- if (a is! Map) continue;
- final id = a['agentId'];
- if (id is! String || id.isEmpty) continue;
- final spend = a['spend'];
- String str(Object? v) => v is String ? v : '';
- next[id] = AttentionRow(
- agentId: id,
- state: attentionFromWire(a['state']),
- detail: str(a['detail']),
- spendFraction: spend is Map && spend['fraction'] is num ? (spend['fraction'] as num).toDouble() : null,
- spendUsd: spend is Map && spend['usd'] is num ? (spend['usd'] as num).toDouble() : null,
- name: str(a['name']),
- machine: str(a['machine']),
- lane: a['lane'] is String ? a['lane'] as String : null,
- );
- }
- final host = payload['hostname'] is String ? payload['hostname'] as String : _hostname;
- if (mapEquals(_rows, next) && host == _hostname) return;
- _hostname = host;
- _rows
- ..clear()
- ..addAll(next);
- notifyListeners();
- }
-}
diff --git a/desktop/lib/state/command_bar_catalog.dart b/desktop/lib/state/command_bar_catalog.dart
index e88759526..1427c371d 100644
--- a/desktop/lib/state/command_bar_catalog.dart
+++ b/desktop/lib/state/command_bar_catalog.dart
@@ -170,24 +170,6 @@ List<CommandBarAction> buildCommandBarCatalog(
return null;
},
),
- CommandBarAction(
- id: 'app:fleet',
- kind: CommandKind.command,
- title: 'Fleet overview',
- detail:
- 'Every machine and its agents as a live graph, coloured by what each one needs from you. Ctrl+Shift+G.',
- automatic: true,
- phrases: [
- 'fleet',
- 'fleet overview',
- 'show the fleet',
- 'machines and agents',
- ],
- perform: (_) async {
- app.fleetOverviewOpen.value = true;
- return null;
- },
- ),
CommandBarAction(
id: 'create:general',
kind: CommandKind.create,
diff --git a/desktop/lib/theme/omarchy_theme.dart b/desktop/lib/theme/omarchy_theme.dart
deleted file mode 100644
index 27b484e7f..000000000
--- a/desktop/lib/theme/omarchy_theme.dart
+++ /dev/null
@@ -1,49 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-//
-// Omarchy theme following for the Harness desktop app. Reads
-// ~/.local/state/omarchy/current/theme/colors.toml, a flat file of `key = "#rrggbb"` lines
-// (blue, yellow, red, green, background, foreground, accent and friends). The `omarchy` palette
-// (shared/theme/color_palette.dart) answers from it; nothing of Omarchy's is bundled.
-
-import 'dart:io';
-
-import 'package:flutter/painting.dart';
-
-const String omarchyColorsPath = '.local/state/omarchy/current/theme/colors.toml';
-
-/// Parse `key = "#hex"` lines. Six or eight hex digits, quotes and the hash optional.
-Map<String, Color> parseOmarchyColors(String text) {
- final out = <String, Color>{};
- final re = RegExp(r'^\s*([A-Za-z0-9_]+)\s*=\s*"?#?([0-9a-fA-F]{6}|[0-9a-fA-F]{8})"?', multiLine: true);
- for (final m in re.allMatches(text)) {
- final hex = m.group(2)!;
- final argb = hex.length == 6 ? int.parse('ff$hex', radix: 16) : int.parse(hex, radix: 16);
- out[m.group(1)!.toLowerCase()] = Color(argb);
- }
- return out;
-}
-
-/// Read the current theme file, or an empty map when Omarchy is not installed.
-Map<String, Color> readOmarchyColors({String? home}) {
- final h = home ?? Platform.environment['HOME'];
- if (h == null) return const {};
- final f = File('$h/$omarchyColorsPath');
- try {
- if (!f.existsSync()) return const {};
- return parseOmarchyColors(f.readAsStringSync());
- } catch (_) {
- return const {};
- }
-}
-
-/// Whether this computer runs Omarchy, judged by its theme file. The palette picker only offers the
-/// Omarchy palette where there is a theme to follow.
-bool omarchyInstalled({String? home}) {
- final h = home ?? Platform.environment['HOME'];
- if (h == null) return false;
- try {
- return File('$h/$omarchyColorsPath').existsSync();
- } catch (_) {
- return false;
- }
-}
diff --git a/desktop/lib/widgets/attention_glow.dart b/desktop/lib/widgets/attention_glow.dart
deleted file mode 100644
index e119478c2..000000000
--- a/desktop/lib/widgets/attention_glow.dart
+++ /dev/null
@@ -1,333 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-import 'dart:math' as math;
-import 'dart:ui' as ui;
-
-import 'package:flutter/material.dart';
-
-import '../fleet/neon.dart';
-import '../state/attention_state.dart';
-
-/// What a pane's frame does for one attention state. Each motion answers one question:
-/// sweep "is it still working?", breathe "is it waiting on me?", alarm "is something blocked or
-/// broken?", fill "did it just finish?". Idle and offline draw nothing, so a quiet desk stays quiet.
-enum AttentionMotion { sweep, breathe, alarm, fill, none }
-
-/// The pane's attention frame, painted over the child and never resizing it (motion never moves the layout).
-///
-/// - working: a short accent gradient runs around the border, 2.4 s a lap.
-/// - waiting: the border and an outer glow breathe in yellow.
-/// - permission / failed: a red pulse with a bright scan band that travels down the two side
-/// edges. The band lives in the border, never over the terminal's text (design/attention-motion.md). Failed opens
-/// with the device's double flash.
-/// - done: the border draws itself once around the pane in green, then holds still. It keeps
-/// holding after the pane has been looked at (`idle`, reviewed) until the agent's next turn, so a
-/// finished pane reads green whenever it is not the one in front of you.
-/// - Colour changes between states cross-fade over 280 ms instead of snapping.
-/// - The focused pane draws no frame at all: its blue focus border is the only one on it.
-///
-/// Loops stop while the window is unfocused or reduced motion is on (then every state is a steady
-/// border). The painter sits in its own layer, so the terminal repainting never repaints the frame
-/// and a frame tick never repaints the terminal. [AttentionState] rows are value-equal, so the
-/// once-a-second frame that changes nothing rebuilds nothing here.
-class AttentionGlow extends StatefulWidget {
- const AttentionGlow({super.key, required this.attention, required this.agentId, required this.child, this.reducedMotion = false, this.focused = false});
-
- final AttentionState attention;
- final String agentId;
- final Widget child;
-
- /// The pane holds focus: its own focus border shows, so the attention frame steps aside.
- final bool focused;
-
- /// Forces reduced motion on; the platform setting and HARNESS_REDUCED_MOTION also turn it on.
- final bool reducedMotion;
-
- static AttentionMotion motionFor(AgentAttention s) => switch (s) {
- AgentAttention.working => AttentionMotion.sweep,
- AgentAttention.waiting => AttentionMotion.breathe,
- AgentAttention.permission || AgentAttention.failed => AttentionMotion.alarm,
- AgentAttention.done => AttentionMotion.fill,
- AgentAttention.idle || AgentAttention.offline => AttentionMotion.none,
- };
-
- /// Kept for callers of the first version (the bar legend, tests).
- static Color colorFor(AgentAttention s, ColorScheme scheme) => switch (s) {
- AgentAttention.permission || AgentAttention.failed => scheme.error,
- AgentAttention.waiting => Neon.fallbackYellow,
- _ => Colors.transparent,
- };
-
- @override
- State<AttentionGlow> createState() => _AttentionGlowState();
-}
-
-class _AttentionGlowState extends State<AttentionGlow> with TickerProviderStateMixin {
- // One loop clock for sweep, breathe and alarm; one one-shot clock for the done fill and the
- // failed double flash; one for the colour cross-fade. All three sit idle unless a state needs them.
- late final AnimationController _loop = AnimationController(vsync: this, duration: const Duration(milliseconds: 2400));
- late final AnimationController _once = AnimationController(vsync: this, duration: const Duration(milliseconds: 900), value: 1);
- late final AnimationController _fade = AnimationController(vsync: this, duration: const Duration(milliseconds: 280), value: 1);
- late final Listenable _tick = Listenable.merge([_loop, _once, _fade]);
-
- AttentionRow? _row;
- // The state the frame draws, which is not always the daemon's: nothing on the focused pane, and a
- // finished turn that has been looked at (idle, reviewed) still reads as done.
- AgentAttention? _shown;
- Color _from = Colors.transparent, _to = Colors.transparent;
- bool _reduced = false;
-
- AgentAttention? _shownFor(AttentionRow? r) {
- if (r == null || widget.focused) return null;
- if (r.state == AgentAttention.idle && r.detail == 'reviewed') return AgentAttention.done;
- return r.state;
- }
-
- @override
- void initState() {
- super.initState();
- _row = widget.attention.of(widget.agentId);
- _shown = _shownFor(_row);
- widget.attention.addListener(_onFrame);
- WindowFocus.instance.addListener(_syncLoop);
- // Once a fade out of the last state ends, drop the painter layer altogether.
- _fade.addStatusListener((s) {
- if (s == AnimationStatus.completed && mounted) setState(() {});
- });
- }
-
- @override
- void didChangeDependencies() {
- super.didChangeDependencies();
- _reduced = widget.reducedMotion || Motion.reducedOf(context);
- _to = _colorOf(_shown);
- if (_fade.value == 1) _from = _to;
- _syncLoop();
- }
-
- @override
- void didUpdateWidget(AttentionGlow old) {
- super.didUpdateWidget(old);
- if (!identical(old.attention, widget.attention)) {
- old.attention.removeListener(_onFrame);
- widget.attention.addListener(_onFrame);
- }
- _reduced = widget.reducedMotion || Motion.reducedOf(context);
- if (old.agentId != widget.agentId || !identical(old.attention, widget.attention)) {
- _onFrame();
- } else if (old.focused != widget.focused) {
- // Focus moved: show or hide the frame without replaying the done draw or the failed flash.
- _show(_shownFor(_row), animateOnce: false);
- if (mounted) setState(() {});
- }
- _syncLoop();
- }
-
- Color _colorOf(AgentAttention? s) =>
- s == null || AttentionGlow.motionFor(s) == AttentionMotion.none ? Colors.transparent : Neon.current().of(s);
-
- void _onFrame() {
- final next = widget.attention.of(widget.agentId);
- if (next == _row) return; // value-equal: nothing changed, nothing repaints
- final realChange = next?.state != _row?.state;
- _row = next;
- // The one-shot (done draw, failed flash) plays for a turn that just ended, not for a pane that
- // was looked at and is now showing its result again.
- _show(_shownFor(next), animateOnce: realChange);
- _syncLoop();
- if (mounted) setState(() {});
- }
-
- void _show(AgentAttention? next, {required bool animateOnce}) {
- if (next == _shown) return;
- _shown = next;
- // Cross-fade from whatever colour is on screen now.
- _from = Color.lerp(_from, _to, _fade.value) ?? _to;
- _to = _colorOf(next);
- if (_reduced) {
- _fade.value = 1;
- } else {
- _fade.forward(from: 0);
- }
- if (animateOnce && !_reduced && (next == AgentAttention.done || next == AgentAttention.failed)) {
- _once.duration = Duration(milliseconds: next == AgentAttention.done ? 900 : 520);
- _once.forward(from: 0);
- } else {
- _once.value = 1;
- }
- }
-
- void _syncLoop() {
- final motion = _shown == null ? AttentionMotion.none : AttentionGlow.motionFor(_shown!);
- final loops = motion == AttentionMotion.sweep || motion == AttentionMotion.breathe || motion == AttentionMotion.alarm;
- final run = loops && !_reduced && WindowFocus.instance.value;
- if (run && !_loop.isAnimating) {
- _loop.duration = Duration(milliseconds: switch (motion) { AttentionMotion.sweep => 2400, AttentionMotion.alarm => 1100, _ => 2200 });
- _loop.repeat();
- } else if (!run && _loop.isAnimating) {
- _loop.stop();
- }
- }
-
- @override
- void dispose() {
- widget.attention.removeListener(_onFrame);
- WindowFocus.instance.removeListener(_syncLoop);
- _loop.dispose();
- _once.dispose();
- _fade.dispose();
- super.dispose();
- }
-
- @override
- Widget build(BuildContext context) {
- final shown = _shown;
- final motion = shown == null ? AttentionMotion.none : AttentionGlow.motionFor(shown);
- // One tree shape whether a frame is drawn or not: switching shapes would rebuild the terminal
- // underneath from scratch every time the frame came or went (each focus change, each state).
- return RepaintBoundary(
- child: AnimatedBuilder(
- animation: _tick,
- child: RepaintBoundary(child: widget.child),
- builder: (context, child) => CustomPaint(
- foregroundPainter: motion == AttentionMotion.none && _fade.value == 1
- ? null
- : AttentionBorderPainter(
- motion: motion,
- color: Color.lerp(_from, _to, Curves.easeOut.transform(_fade.value)) ?? _to,
- phase: _loop.value,
- progress: _once.value,
- failed: shown == AgentAttention.failed,
- reduced: _reduced,
- ),
- child: child,
- ),
- ),
- );
- }
-}
-
-/// Paints one pane's attention frame. Value-equal, so an unchanged frame is never repainted.
-class AttentionBorderPainter extends CustomPainter {
- const AttentionBorderPainter({required this.motion, required this.color, required this.phase, required this.progress, this.failed = false, this.reduced = false});
-
- final AttentionMotion motion;
- final Color color;
-
- /// 0..1 around the loop clock.
- final double phase;
-
- /// 0..1 through a one-shot (done fill, failed flash); 1 when none is running.
- final double progress;
- final bool failed;
- final bool reduced;
-
- static const double width = 2;
-
- @override
- void paint(Canvas canvas, Size size) {
- if (color.a == 0) return;
- final rect = (Offset.zero & size).deflate(width / 2);
- final stroke = Paint()
- ..style = PaintingStyle.stroke
- ..strokeWidth = width;
- if (reduced) {
- if (motion == AttentionMotion.none) return;
- canvas.drawRect(rect, stroke..color = color.withValues(alpha: motion == AttentionMotion.sweep ? 0.5 : 0.9));
- return;
- }
- switch (motion) {
- case AttentionMotion.none:
- // Only reached while the colour fades out of a previous state.
- canvas.drawRect(rect, stroke..color = color.withValues(alpha: 0.6));
- case AttentionMotion.sweep:
- _sweep(canvas, rect, stroke);
- case AttentionMotion.breathe:
- final t = 0.5 - 0.5 * math.cos(phase * 2 * math.pi);
- _glow(canvas, rect, 0.18 + 0.30 * t, 8 + 10 * t);
- canvas.drawRect(rect, stroke..color = color.withValues(alpha: 0.55 + 0.4 * t));
- case AttentionMotion.alarm:
- _alarm(canvas, rect, stroke);
- case AttentionMotion.fill:
- _fill(canvas, rect, stroke);
- }
- }
-
- void _glow(Canvas canvas, Rect rect, double alpha, double blur) {
- canvas.drawRect(
- rect,
- Paint()
- ..style = PaintingStyle.stroke
- ..strokeWidth = 4
- ..color = color.withValues(alpha: alpha)
- ..maskFilter = MaskFilter.blur(BlurStyle.outer, blur),
- );
- }
-
- void _sweep(Canvas canvas, Rect rect, Paint stroke) {
- // A dim steady frame so the pane reads as "live", and a bright comet running around it.
- canvas.drawRect(rect, Paint()
- ..style = PaintingStyle.stroke
- ..strokeWidth = 1
- ..color = color.withValues(alpha: 0.22));
- final a = phase * 2 * math.pi;
- final shader = SweepGradient(
- center: Alignment.center,
- transform: GradientRotation(a),
- colors: [color.withValues(alpha: 0), color.withValues(alpha: 0), color.withValues(alpha: 0.35), color, color.withValues(alpha: 0)],
- stops: const [0, 0.72, 0.9, 0.985, 1],
- ).createShader(rect);
- canvas.drawRect(rect, stroke..shader = shader);
- }
-
- void _alarm(Canvas canvas, Rect rect, Paint stroke) {
- // Failed opens with two quick flashes, then settles into the pulse (design/attention-motion.md, device failed screen).
- if (failed && progress < 1) {
- final on = (progress * 4).floor().isEven;
- canvas.drawRect(rect, stroke..color = color.withValues(alpha: on ? 1 : 0.15));
- if (on) _glow(canvas, rect, 0.6, 18);
- return;
- }
- final t = math.pow(0.5 - 0.5 * math.cos(phase * 2 * math.pi), 2).toDouble();
- _glow(canvas, rect, 0.25 + 0.4 * t, 10 + 8 * t);
- canvas.drawRect(rect, Paint()
- ..style = PaintingStyle.stroke
- ..strokeWidth = width
- ..color = color.withValues(alpha: 0.7 + 0.3 * t));
- // The scan band: a bright 48 px segment sliding down both side edges, inside the border only.
- final y = rect.top + (rect.height + 96) * phase - 48;
- final band = Rect.fromLTRB(rect.left - 2, y - 48, rect.right + 2, y + 48);
- final shader = ui.Gradient.linear(band.topCenter, band.bottomCenter, [color.withValues(alpha: 0), Colors.white.withValues(alpha: 0.9), color.withValues(alpha: 0)], const [0, 0.5, 1]);
- final edge = Paint()
- ..style = PaintingStyle.stroke
- ..strokeWidth = width + 1
- ..shader = shader;
- canvas.save();
- canvas.clipRect(band);
- canvas.drawLine(rect.topLeft, rect.bottomLeft, edge);
- canvas.drawLine(rect.topRight, rect.bottomRight, edge);
- canvas.restore();
- }
-
- void _fill(Canvas canvas, Rect rect, Paint stroke) {
- final p = Curves.easeInOutCubic.transform(progress.clamp(0.0, 1.0));
- // Drawn clockwise from the top-left corner, like the device's done ring filling.
- final path = Path()..addRect(rect);
- final metric = path.computeMetrics().first;
- canvas.drawPath(metric.extractPath(0, metric.length * p), stroke..color = color);
- if (p < 1) {
- final head = metric.getTangentForOffset(metric.length * p)?.position;
- if (head != null) canvas.drawCircle(head, 3.5, Paint()..color = Colors.white.withValues(alpha: 0.9)..maskFilter = const MaskFilter.blur(BlurStyle.normal, 3));
- } else {
- // Settled: a quieter green frame that says "finished, not yet looked at".
- canvas.drawRect(rect, Paint()
- ..style = PaintingStyle.stroke
- ..strokeWidth = 1
- ..color = color.withValues(alpha: 0.35));
- }
- }
-
- @override
- bool shouldRepaint(AttentionBorderPainter old) =>
- old.motion != motion || old.color != color || old.phase != phase || old.progress != progress || old.failed != failed || old.reduced != reduced;
-}
diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dart
index b4ab59592..9ec137277 100644
--- a/desktop/lib/widgets/terminal_panel.dart
+++ b/desktop/lib/widgets/terminal_panel.dart
@@ -35,8 +35,6 @@ import '../terminal/terminal_text.dart';
import '../terminal/terminal_link_opener.dart';
import '../terminal/remote_media_download.dart';
import '../terminal/terminal_links.dart';
-import 'attention_glow.dart';
-import '../fleet/spend_ring.dart';
import '../terminal/terminal_session.dart';
import '../terminal/terminal_theme.dart';
import '../terminal/terminal_theme_store.dart';
@@ -2122,13 +2120,7 @@ class _TerminalPanelState extends State<TerminalPanel>
// underneath them all would stack with theirs.
final paneOpacity = PaneOpacity.of(context);
final chromeFill = PaneOpacity.fill(context, grid.AppPalette.windowBg);
- // The pane frame follows what its agent needs from a person (the daemon's attention frame);
- // the focused pane keeps only its own focus border.
- return AttentionGlow(
- attention: widget.notifier.attention,
- agentId: session.agentId,
- focused: widget.focused,
- child: KeymapRegion(
+ return KeymapRegion(
contextKind: KeymapContext.terminal,
composing: () =>
_focusNode.hasFocus &&
@@ -2406,7 +2398,6 @@ class _TerminalPanelState extends State<TerminalPanel>
],
),
),
- ),
);
}
@@ -2829,15 +2820,10 @@ class _TerminalHeader extends StatelessWidget {
children: [
if (leadingStatus)
statusButton()
+ else if (agent != null && showIdentityMark)
+ EngineMark.forAgent(agent, size: 17)
else if (showIdentityMark)
- // The spend arc rings the engine mark when a per-agent cap is set.
- SpendRing(
- attention: notifier.attention,
- agentId: session.agentId,
- child: agent != null
- ? EngineMark.forAgent(agent, size: 17)
- : EngineMark(engine: session.engineId, size: 17),
- ),
+ EngineMark(engine: session.engineId, size: 17),
if (leadingStatus || showIdentityMark)
SizedBox(width: leadingStatus ? 6 : 10),
Expanded(
diff --git a/desktop/test/attention_glow_test.dart b/desktop/test/attention_glow_test.dart
deleted file mode 100644
index 1f23c4bd4..000000000
--- a/desktop/test/attention_glow_test.dart
+++ /dev/null
@@ -1,52 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-import 'package:flutter/material.dart';
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/state/attention_state.dart';
-import 'package:harness/widgets/attention_glow.dart';
-
-Map<String, dynamic> frame(String state, {num? fraction}) => {
- 'agents': [
- {'agentId': 'a', 'state': state, 'detail': 'Which branch?', if (fraction != null) 'spend': {'fraction': fraction}},
- ],
- };
-
-void main() {
- test('AttentionState parses a frame, notifies once per real change, ignores junk', () {
- final s = AttentionState();
- var n = 0;
- s.addListener(() => n++);
- s.apply(frame('waiting', fraction: 0.5));
- s.apply(frame('waiting', fraction: 0.5));
- expect(n, 1);
- expect(s.of('a')?.state, AgentAttention.waiting);
- expect(s.of('a')?.spendFraction, 0.5);
- expect(s.of('a')?.needsYou, isTrue);
- s.apply({'agents': 'nope'});
- expect(n, 1);
- s.apply(frame('working'));
- expect(s.of('a')?.needsYou, isFalse);
- expect(attentionFromWire('mystery'), AgentAttention.idle);
- });
-
- testWidgets('AttentionGlow paints a steady 2 px frame under reduced motion, nothing when idle', (tester) async {
- final s = AttentionState();
- await tester.pumpWidget(MaterialApp(
- home: Center(child: AttentionGlow(attention: s, agentId: 'a', reducedMotion: true, child: const SizedBox(width: 100, height: 60))),
- ));
- AttentionBorderPainter? painter() => tester
- .widgetList<CustomPaint>(find.byType(CustomPaint))
- .map((w) => w.foregroundPainter)
- .whereType<AttentionBorderPainter>()
- .firstOrNull;
- expect(painter(), isNull);
- s.apply(frame('permission'));
- await tester.pump();
- expect(painter()!.reduced, isTrue);
- expect(AttentionBorderPainter.width, 2);
- expect(tester.getSize(find.byType(SizedBox)), const Size(100, 60));
- s.apply(frame('idle'));
- await tester.pump();
- expect(painter(), isNull);
- });
-}
diff --git a/desktop/test/attention_motion_test.dart b/desktop/test/attention_motion_test.dart
deleted file mode 100644
index 25a8b35c5..000000000
--- a/desktop/test/attention_motion_test.dart
+++ /dev/null
@@ -1,259 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-import 'package:flutter/material.dart';
-import 'package:flutter/services.dart';
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/branding/boot_splash.dart';
-import 'package:harness/branding/brand_prefs.dart';
-import 'package:harness/fleet/fleet_graph.dart';
-import 'package:harness/fleet/neon.dart';
-import 'package:harness/fleet/spend_ring.dart';
-import 'package:harness/state/attention_state.dart';
-import 'package:harness/widgets/attention_glow.dart';
-
-Map<String, dynamic> frame(String state, {num? fraction, num? usd, int at = 1}) => {
- 'hostname': 'host-a',
- 'at': at,
- 'agents': [
- {
- 'agentId': 'a',
- 'name': 'planner-1',
- 'machine': 'host-a',
- 'lane': 'planner',
- 'state': state,
- 'detail': 'Which branch?',
- if (fraction != null || usd != null) 'spend': {'fraction': fraction, 'usd': usd},
- },
- ],
- };
-
-AttentionBorderPainter? borderPainter(WidgetTester tester) {
- for (final w in tester.widgetList<CustomPaint>(find.byType(CustomPaint))) {
- if (w.foregroundPainter is AttentionBorderPainter) return w.foregroundPainter as AttentionBorderPainter;
- }
- return null;
-}
-
-Widget pane(AttentionState s, {bool reduced = false}) => MaterialApp(
- home: Center(
- child: AttentionGlow(attention: s, agentId: 'a', reducedMotion: reduced, child: const SizedBox(width: 200, height: 120)),
- ),
- );
-
-void main() {
- tearDown(() => Motion.override = null);
-
- group('attention rows', () {
- test('carry name, machine, lane and usd; a frame that only moves `at` notifies nobody', () {
- final s = AttentionState();
- var n = 0;
- s.addListener(() => n++);
- s.apply(frame('working', fraction: 0.4, usd: 2.5, at: 1));
- s.apply(frame('working', fraction: 0.4, usd: 2.5, at: 2));
- expect(n, 1);
- final r = s.of('a')!;
- expect((r.name, r.machine, r.lane, r.spendUsd, r.glyph, r.label), ('planner-1', 'host-a', 'planner', 2.5, '~', 'working'));
- expect(s.hostname, 'host-a');
- });
- });
-
- group('neon', () {
- test('a theme colour is used only while it still reads as that colour', () {
- Color? greenRed(String _) => const Color(0xFF50F872);
- Color? realRed(String _) => const Color(0xFFFF3355);
- expect(Neon.themed('red', Neon.fallbackRed, 335, 20, read: greenRed), Neon.fallbackRed);
- expect(Neon.themed('red', Neon.fallbackRed, 335, 20, read: realRed), const Color(0xFFFF3355));
- expect(Neon.themed('red', Neon.fallbackRed, 335, 20, read: (_) => null), Neon.fallbackRed);
- });
-
- test('spend colour: accent, amber from 80 percent, red at the cap', () {
- const n = Neon(accent: Color(0xFF00FFFF), yellow: Color(0xFFFFFF00), red: Color(0xFFFF0000), green: Color(0xFF00FF00), foreground: Colors.white, background: Colors.black);
- expect(n.spend(0.5), n.accent);
- expect(n.spend(0.8), n.yellow);
- expect(n.spend(1.0), n.red);
- expect(n.spend(1.4), n.red);
- });
- });
-
- group('pane attention', () {
- test('every state maps to one motion', () {
- expect(AttentionGlow.motionFor(AgentAttention.working), AttentionMotion.sweep);
- expect(AttentionGlow.motionFor(AgentAttention.waiting), AttentionMotion.breathe);
- expect(AttentionGlow.motionFor(AgentAttention.permission), AttentionMotion.alarm);
- expect(AttentionGlow.motionFor(AgentAttention.failed), AttentionMotion.alarm);
- expect(AttentionGlow.motionFor(AgentAttention.done), AttentionMotion.fill);
- expect(AttentionGlow.motionFor(AgentAttention.idle), AttentionMotion.none);
- expect(AttentionGlow.motionFor(AgentAttention.offline), AttentionMotion.none);
- });
-
- testWidgets('idle paints nothing and schedules no frames', (tester) async {
- final s = AttentionState();
- await tester.pumpWidget(pane(s));
- expect(borderPainter(tester), isNull);
- s.apply(frame('idle'));
- await tester.pump();
- await tester.pump(const Duration(seconds: 1));
- expect(borderPainter(tester), isNull);
- expect(tester.binding.hasScheduledFrame, isFalse);
- });
-
- testWidgets('working sweeps, waiting breathes, permission alarms; child never resized', (tester) async {
- final s = AttentionState();
- await tester.pumpWidget(pane(s));
- for (final (wire, motion) in [('working', AttentionMotion.sweep), ('waiting', AttentionMotion.breathe), ('permission', AttentionMotion.alarm)]) {
- s.apply(frame(wire));
- await tester.pump();
- await tester.pump(const Duration(milliseconds: 400));
- final p = borderPainter(tester)!;
- expect(p.motion, motion, reason: wire);
- expect(tester.binding.hasScheduledFrame, isTrue, reason: '$wire loops');
- expect(tester.getSize(find.byType(SizedBox).last), const Size(200, 120));
- }
- });
-
- testWidgets('done plays its fill once, then stops asking for frames', (tester) async {
- final s = AttentionState();
- await tester.pumpWidget(pane(s));
- s.apply(frame('working'));
- await tester.pump();
- s.apply(frame('done'));
- await tester.pump();
- expect(borderPainter(tester)!.motion, AttentionMotion.fill);
- await tester.pump(const Duration(milliseconds: 300));
- expect(borderPainter(tester)!.progress, inExclusiveRange(0, 1));
- await tester.pumpAndSettle();
- expect(borderPainter(tester)!.progress, 1);
- expect(tester.binding.hasScheduledFrame, isFalse);
- });
-
- testWidgets('reduced motion: a steady border, no looping frames', (tester) async {
- final s = AttentionState();
- await tester.pumpWidget(pane(s, reduced: true));
- s.apply(frame('permission'));
- await tester.pump();
- await tester.pump(const Duration(milliseconds: 400));
- final p = borderPainter(tester)!;
- expect(p.reduced, isTrue);
- await tester.pumpAndSettle();
- expect(tester.binding.hasScheduledFrame, isFalse);
- });
-
- testWidgets('loops pause while the window is unfocused', (tester) async {
- final s = AttentionState();
- await tester.pumpWidget(pane(s));
- s.apply(frame('working'));
- await tester.pump();
- tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
- await tester.pump();
- await tester.pumpAndSettle();
- expect(tester.binding.hasScheduledFrame, isFalse);
- tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
- await tester.pump();
- expect(tester.binding.hasScheduledFrame, isTrue);
- });
- });
-
- group('spend ring', () {
- testWidgets('hidden without a cap, drawn with the right colour when there is one', (tester) async {
- final s = AttentionState();
- await tester.pumpWidget(MaterialApp(home: Center(child: SpendRing(attention: s, agentId: 'a', child: const SizedBox(width: 17, height: 17)))));
- expect(find.byType(SpendArc), findsNothing);
- s.apply(frame('working', fraction: 0.9, usd: 4.5));
- await tester.pump();
- await tester.pumpAndSettle();
- final arc = tester.widget<SpendArc>(find.byType(SpendArc));
- expect(arc.fraction, 0.9);
- expect(tester.getSize(find.byType(SpendRing)), const Size(17, 17));
- expect(find.byTooltip(r'$4.50 spent, 90% of the cap'), findsOneWidget);
- });
- });
-
- group('fleet graph', () {
- final machines = [
- const FleetMachine(id: 'host-a', name: 'host-a', connected: true, local: true, agents: [
- FleetAgent(id: 'a', name: 'planner-1', state: AgentAttention.working, lane: 'planner'),
- FleetAgent(id: 'b', name: 'checker', state: AgentAttention.waiting),
- ]),
- const FleetMachine(id: 'host-b', name: 'host-b', connected: false, agents: [FleetAgent(id: 'c', name: 'drafter', state: AgentAttention.offline)]),
- ];
-
- test('layout keeps every node inside the canvas', () {
- const size = Size(640, 420);
- final l = FleetLayout.compute(size, machines);
- expect(l.machines.length, 2);
- expect(l.agents.length, 3);
- for (final p in [...l.machines.values, ...l.agents.values]) {
- expect((Offset.zero & size).contains(p), isTrue, reason: '$p');
- }
- });
-
- testWidgets('animates only while some agent is live, and has a word for every state', (tester) async {
- await tester.pumpWidget(MaterialApp(home: Scaffold(body: FleetGraph(machines: machines))));
- await tester.pump(const Duration(milliseconds: 100));
- expect(tester.binding.hasScheduledFrame, isTrue);
- expect(find.textContaining('? 1'), findsOneWidget);
- await tester.pumpWidget(MaterialApp(home: Scaffold(body: FleetGraph(machines: [machines[1]]))));
- await tester.pumpAndSettle();
- expect(tester.binding.hasScheduledFrame, isFalse);
- });
- });
-
- group('boot splash', () {
- // The splash is off until a logo is chosen; these cover a person who picked the Harness icon.
- setUp(() {
- BootSplash.debugReset();
- brandPrefsStore.value = const BrandPrefs(bootLogo: BootLogo.harness);
- });
- tearDown(() => brandPrefsStore.value = const BrandPrefs());
-
- testWidgets('stays off when no logo has been chosen', (tester) async {
- brandPrefsStore.value = const BrandPrefs();
- await tester.pumpWidget(const MaterialApp(home: BootSplash(child: Text('app'))));
- expect(find.byKey(BootSplash.overlayKey), findsNothing);
- expect(find.text('app'), findsOneWidget);
- });
-
- testWidgets('shows once per process, then hands off inside 1.8 s', (tester) async {
- await tester.pumpWidget(const MaterialApp(home: BootSplash(child: Text('app'))));
- expect(find.byKey(BootSplash.overlayKey), findsOneWidget);
- expect(find.text('app'), findsOneWidget, reason: 'the app builds underneath, never delayed');
- await tester.pump(const Duration(milliseconds: 1800));
- await tester.pump();
- expect(find.byKey(BootSplash.overlayKey), findsNothing);
- await tester.pumpWidget(const MaterialApp(home: BootSplash(key: ValueKey(2), child: Text('app'))));
- expect(find.byKey(BootSplash.overlayKey), findsNothing, reason: 'a re-opened window is not a cold launch');
- });
-
- testWidgets('a click skips it', (tester) async {
- await tester.pumpWidget(const MaterialApp(home: BootSplash(child: Text('app'))));
- await tester.pump(const Duration(milliseconds: 200));
- await tester.tap(find.byKey(BootSplash.overlayKey));
- // The fade starts on the next frame and takes 180 ms, far short of the full 1.5 s.
- await tester.pump(const Duration(milliseconds: 16));
- await tester.pump(const Duration(milliseconds: 200));
- await tester.pump();
- expect(find.byKey(BootSplash.overlayKey), findsNothing);
- });
-
- testWidgets('a key skips it', (tester) async {
- await tester.pumpWidget(const MaterialApp(home: BootSplash(child: Text('app'))));
- await tester.pump(const Duration(milliseconds: 200));
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- // The fade starts on the next frame and takes 180 ms, far short of the full 1.5 s.
- await tester.pump(const Duration(milliseconds: 16));
- await tester.pump(const Duration(milliseconds: 200));
- await tester.pump();
- expect(find.byKey(BootSplash.overlayKey), findsNothing);
- });
-
- testWidgets('reduced motion shows a static logo', (tester) async {
- Motion.override = true;
- await tester.pumpWidget(const MaterialApp(home: BootSplash(child: Text('app'))));
- await tester.pump(const Duration(milliseconds: 100));
- expect(tester.state<BootSplashState>(find.byType(BootSplash)).animated, isFalse);
- await tester.pump(const Duration(milliseconds: 1800));
- await tester.pump();
- expect(find.byKey(BootSplash.overlayKey), findsNothing);
- });
- });
-}
diff --git a/desktop/test/brand_prefs_test.dart b/desktop/test/brand_prefs_test.dart
deleted file mode 100644
index 657480b0f..000000000
--- a/desktop/test/brand_prefs_test.dart
+++ /dev/null
@@ -1,169 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-import 'dart:io';
-
-import 'package:flutter/material.dart';
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/core/local_key_value_store.dart';
-import 'package:harness/branding/boot_splash.dart';
-import 'package:harness/branding/brand_prefs.dart';
-import 'package:harness/branding/brand_section.dart';
-
-class _Memory implements LocalKeyValueStore {
- final Map<String, String> data = {};
- @override
- Future<String?> read(String key) async => data[key];
- @override
- Future<void> write(String key, String value) async => data[key] = value;
- @override
- Future<void> delete(String key) async => data.remove(key);
-}
-
-// Generic placeholders only: an 8x8 PNG header and a tiny SVG. No personal assets.
-final _png = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, ...List.filled(64, 0)];
-const _svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><rect width="10" height="10"/></svg>';
-
-void main() {
- late Directory tmp;
- late _Memory mem;
- var n = 0;
- BrandPrefsStore store({bool omarchy = true, bool face = false}) {
- final sys = Directory('${tmp.path}/sys${n++}')..createSync(recursive: true);
- final logo = File('${sys.path}/logo.svg');
- final faceFile = File('${sys.path}/.face');
- if (omarchy) logo.writeAsStringSync(_svg);
- if (face) faceFile.writeAsBytesSync(_png);
- return BrandPrefsStore(storage: mem, dataDir: Directory('${tmp.path}/data'), omarchyLogoPath: logo.path, systemAvatarPath: faceFile.path);
- }
-
- setUp(() {
- tmp = Directory.systemTemp.createTempSync('brand');
- mem = _Memory();
- });
- tearDown(() => tmp.deleteSync(recursive: true));
-
- group('boot logo', () {
- test('is off until chosen, with or without Omarchy on the machine', () async {
- final a = store();
- await a.load();
- expect(a.value.bootLogo, isNull, reason: 'nothing chosen yet');
- expect(a.resolveBootLogo().kind, BootLogo.none);
- final b = store(omarchy: false);
- await b.load();
- expect(b.resolveBootLogo().kind, BootLogo.none);
- expect(b.omarchyAvailable, isFalse);
- });
-
- test('a saved Omarchy choice falls back to Harness on a machine without Omarchy', () async {
- mem.data[BrandPrefsStore.bootLogoKey] = 'omarchy';
- final s = store(omarchy: false);
- await s.load();
- expect(s.resolveBootLogo().kind, BootLogo.harness);
- });
-
- test('custom: validated, copied into the data dir, and a missing copy falls back', () async {
- final s = store();
- await s.load();
- final src = File('${tmp.path}/mine.png')..writeAsBytesSync(_png);
- expect(await s.setCustomLogo(src.path), isNull);
- expect(s.value.bootLogo, BootLogo.custom);
- final r = s.resolveBootLogo();
- expect(r.kind, BootLogo.custom);
- expect(r.path, startsWith('${tmp.path}/data'));
- expect(mem.data[BrandPrefsStore.bootLogoKey], 'custom');
- File(r.path!).deleteSync();
- expect(s.resolveBootLogo().kind, BootLogo.none, reason: 'no splash when the custom file is gone');
- });
-
- test('custom files are rejected by size and type, and the old choice is kept', () async {
- final s = store();
- await s.load();
- final big = File('${tmp.path}/big.png')..writeAsBytesSync([..._png, ...List.filled(BrandPrefsStore.maxBytes, 0)]);
- final txt = File('${tmp.path}/notes.txt')..writeAsStringSync('hello');
- final fake = File('${tmp.path}/fake.png')..writeAsStringSync('not a png');
- expect(await s.setCustomLogo(big.path), contains('2 MB'));
- expect(await s.setCustomLogo(txt.path), contains('SVG or PNG'));
- expect(await s.setCustomLogo(fake.path), contains('not a valid'));
- expect(await s.setCustomLogo('${tmp.path}/missing.svg'), isNotNull);
- expect(s.value.bootLogo, isNull);
- });
-
- test('an SVG custom logo is accepted; None is remembered', () async {
- final s = store();
- await s.load();
- final src = File('${tmp.path}/mark.svg')..writeAsStringSync(_svg);
- expect(await s.setCustomLogo(src.path), isNull);
- expect(s.resolveBootLogo().isSvg, isTrue);
- await s.setBootLogo(BootLogo.none);
- final again = store();
- await again.load();
- expect(again.resolveBootLogo().kind, BootLogo.none);
- });
- });
-
- group('avatar', () {
- test('default is the generic glyph; initials are kept short and upper case', () async {
- final s = store();
- await s.load();
- expect(s.resolveAvatar().kind, AvatarSource.generic);
- await s.setInitials(' ab c ');
- expect(s.resolveAvatar().kind, AvatarSource.initials);
- expect(s.resolveAvatar().initials, 'ABC');
- await s.setInitials('');
- expect(s.resolveAvatar().kind, AvatarSource.generic);
- });
-
- test('the system avatar is offered only when ~/.face exists, and falls back when it goes', () async {
- final none = store();
- await none.load();
- expect(none.systemAvatarAvailable, isFalse);
- final s = store(face: true);
- await s.load();
- expect(s.systemAvatarAvailable, isTrue);
- await s.setAvatar(AvatarSource.system);
- expect(s.resolveAvatar().kind, AvatarSource.system);
- File(s.systemAvatarPath).deleteSync();
- expect(s.resolveAvatar().kind, AvatarSource.generic);
- });
-
- test('a custom avatar is validated and cached in the data dir', () async {
- final s = store();
- await s.load();
- final src = File('${tmp.path}/me.png')..writeAsBytesSync(_png);
- expect(await s.setCustomAvatar(src.path), isNull);
- final r = s.resolveAvatar();
- expect(r.kind, AvatarSource.custom);
- expect(r.path, startsWith('${tmp.path}/data'));
- expect(await s.setCustomAvatar('${tmp.path}/nope.gif'), isNotNull);
- expect(s.resolveAvatar().kind, AvatarSource.custom);
- });
- });
-
- group('widgets', () {
- testWidgets('the splash never shows when the choice is None', (tester) async {
- BootSplash.debugReset();
- final s = store();
- await tester.runAsync(() async {
- await s.load();
- await s.setBootLogo(BootLogo.none);
- });
- await tester.pumpWidget(MaterialApp(home: BootSplash(brand: s, child: const Text('app'))));
- expect(find.byKey(BootSplash.overlayKey), findsNothing);
- });
-
- testWidgets('the Appearance pickers list the choices; Omarchy only where it is installed', (tester) async {
- final s = store(omarchy: false);
- await tester.runAsync(s.load);
- await tester.pumpWidget(MaterialApp(home: Scaffold(body: SingleChildScrollView(child: BrandSection(store: s)))));
- for (final label in ['Harness', 'Custom…', 'None', 'Generic', 'Initials', 'Custom image…']) {
- expect(find.text(label), findsWidgets, reason: label);
- }
- expect(find.text('System avatar'), findsNothing, reason: 'no ~/.face here');
- expect(find.widgetWithText(ChoiceChip, 'Omarchy'), findsNothing, reason: 'no Omarchy logo here');
- await tester.tap(find.widgetWithText(ChoiceChip, 'None'));
- await tester.runAsync(() => Future<void>.delayed(const Duration(milliseconds: 20)));
- await tester.pump();
- expect(s.value.bootLogo, BootLogo.none);
- });
- });
-}
diff --git a/desktop/test/omarchy_palette_test.dart b/desktop/test/omarchy_palette_test.dart
deleted file mode 100644
index c828ddc93..000000000
--- a/desktop/test/omarchy_palette_test.dart
+++ /dev/null
@@ -1,49 +0,0 @@
-// Originally written by Fred Nix (@nixfred) in github.com/nixfred/openharness (MIT).
-
-import 'dart:io';
-
-import 'package:flutter/painting.dart';
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness/shared/theme/color_palette.dart';
-import 'package:harness/theme/omarchy_theme.dart';
-
-void main() {
- test('presets keep their own constants', () {
- expect(HarnessPalette.graphite.accent, const Color(0xffbdcbdc));
- expect(HarnessPalette.midnight.background, const Color(0xff171b29));
- expect(HarnessPalette.fromId('omarchy'), HarnessPalette.omarchy);
- });
-
- test('parses an Omarchy colors.toml and the omarchy palette falls back to Graphite when empty', () {
- final c = parseOmarchyColors('mode = "dark"\naccent = "#82FB9C"\nbackground = "#0b0f14"\n');
- expect(c['accent'], const Color(0xff82fb9c));
- expect(c['background'], const Color(0xff0b0f14));
- final home = Directory.systemTemp.createTempSync('no-omarchy-');
- expect(readOmarchyColors(home: home.path), isEmpty);
- home.deleteSync(recursive: true);
- });
-
- test('the omarchy palette answers from the live theme file', () {
- OmarchyLivePalette.refresh();
- final live = readOmarchyColors();
- if (live.isEmpty) {
- expect(HarnessPalette.omarchy.accent, HarnessPalette.graphite.accent);
- } else {
- expect(HarnessPalette.omarchy.accent, live['accent'] ?? HarnessPalette.graphite.accent);
- expect(HarnessPalette.omarchy.background, live['background'] ?? HarnessPalette.graphite.background);
- }
- expect(HarnessPalette.omarchy.label, 'Omarchy');
- });
-
- test('the picker offers Omarchy only where a theme file exists', () {
- final home = Directory.systemTemp.createTempSync('omarchy-home-');
- expect(omarchyInstalled(home: home.path), isFalse);
- File('${home.path}/$omarchyColorsPath')
- ..createSync(recursive: true)
- ..writeAsStringSync('accent = "#82FB9C"\n');
- expect(omarchyInstalled(home: home.path), isTrue);
- home.deleteSync(recursive: true);
- expect(HarnessPalette.offered.contains(HarnessPalette.omarchy), omarchyInstalled());
- expect(HarnessPalette.offered, containsAll(HarnessPalette.values.where((p) => p != HarnessPalette.omarchy)));
- });
-}
diff --git a/integrations/omarchy/harness-pulse/AgentRing.qml b/integrations/omarchy/harness-pulse/AgentRing.qml
deleted file mode 100644
index 8bcdd3119..000000000
--- a/integrations/omarchy/harness-pulse/AgentRing.qml
+++ /dev/null
@@ -1,399 +0,0 @@
-import QtQuick
-import QtQuick.Shapes
-import QtQuick.Effects
-import qs.Commons
-
-// One agent, one ring. Fixed footprint (rings animate in place, never the row).
-//
-// Every motion is a state, so a glance reads it without the tooltip:
-// working comet with a fading trail circles clockwise (the agent is moving)
-// waiting yellow halo breathes out from the ring (it wants you, not urgently)
-// permission red strobe burst plus a chromatic glitch, repeating (it is blocked on you)
-// failed one strobe and glitch burst on entry, then a steady thin red ring with a
-// small glitch tick every 6 s (still broken, not shouting)
-// done the core fills with a burst and a shockwave ring, then holds still
-// offline dim dashed ring, no motion
-// idle the ring shrinks to a dot, no motion
-// Animators run on the render thread; nothing repaints per frame on the GUI thread and nothing
-// runs in idle, offline or a settled done ring.
-Item {
- id: ring
-
- property var agent: ({})
- property int size: 18
- property bool reducedMotion: false
- property var theme: ({})
- property bool showGlyph: reducedMotion
- // A picture of the person the agent is waiting on, shown inside the ring only while the agent
- // waits or needs permission. If the picture is missing or unreadable, avatarInitials shows
- // instead; both empty means a plain ring.
- property string avatarPath: ""
- property string avatarInitials: ""
- /** Working ring colour: "Accent" (theme accent), "Cyan" or "Green". */
- property string workingColor: "Accent"
-
- readonly property string state: agent && agent.state ? agent.state : "idle"
- // Spend as a fraction of the per-agent cap, or -1 when no cap is set: drawn as the outer arc.
- readonly property real spendFraction: agent && agent.spend && agent.spend.fraction !== null && agent.spend.fraction !== undefined ? Number(agent.spend.fraction) : -1
- readonly property bool hasSpend: spendFraction >= 0
- readonly property bool waitingOnPerson: state === "waiting" || state === "permission"
- readonly property bool avatarReady: avatarPath !== "" && avatar.status === Image.Ready
- readonly property bool showAvatar: waitingOnPerson && (avatarReady || avatarInitials !== "")
- readonly property bool motion: !reducedMotion
- readonly property color accent: Color.accent
- readonly property color urgent: theme.yellow ? theme.yellow : Color.urgent
- readonly property color danger: theme.red ? theme.red : Color.urgent
- readonly property color okay: theme.green ? theme.green : Color.accent
- readonly property color glitchA: theme.cyan ? theme.cyan : accent
- readonly property color glitchB: theme.magenta ? theme.magenta : danger
- readonly property color dim: Qt.rgba(Color.foreground.r, Color.foreground.g, Color.foreground.b, 0.28)
-
- readonly property color stateColor: {
- switch (state) {
- case "working": return workingColor === "Cyan" ? "#22d3ee" : workingColor === "Green" ? okay : accent
- case "waiting": return urgent
- case "permission": return danger
- case "failed": return danger
- case "done": return okay
- case "offline": return dim
- default: return Qt.rgba(Color.foreground.r, Color.foreground.g, Color.foreground.b, 0.55)
- }
- }
-
- readonly property real lineWidth: state === "failed" ? 1.5 : 2.2
- // The outer edge belongs to the spend arc when a cap is set; the state ring sits one line in.
- readonly property real ringDiameter: size - (hasSpend ? 4.4 : 1.0)
-
- // Idle shrinks to a dot; waiting and permission breathe. Scale only, never width.
- property real breath: 1.0
- readonly property real coreScale: state === "idle" ? 0.42 : breath
- property real fill: state === "done" ? 1.0 : 0.0
- property real flash: 1.0
-
- width: size
- height: size
-
- Behavior on fill { NumberAnimation { duration: ring.motion ? 420 : 0; easing.type: Easing.OutBack } }
-
- SequentialAnimation on breath {
- running: ring.motion && ring.waitingOnPerson
- loops: Animation.Infinite
- NumberAnimation { from: 1.0; to: 1.08; duration: 600; easing.type: Easing.InOutSine }
- NumberAnimation { from: 1.08; to: 1.0; duration: 600; easing.type: Easing.InOutSine }
- onRunningChanged: if (!running) ring.breath = 1.0
- }
-
- onStateChanged: {
- if (!motion) return
- if (state === "failed") failBurst.restart()
- else if (state === "done") doneBurst.restart()
- }
-
- // ---- Waiting / permission halo: a soft disc that breathes outward behind the ring. ----
- Rectangle {
- id: halo
- anchors.centerIn: parent
- width: ring.size; height: ring.size; radius: width / 2
- color: Qt.rgba(ring.stateColor.r, ring.stateColor.g, ring.stateColor.b, 0.35)
- visible: ring.motion && ring.waitingOnPerson
- opacity: 0
- scale: 1
- SequentialAnimation {
- running: halo.visible
- loops: Animation.Infinite
- ParallelAnimation {
- ScaleAnimator { target: halo; from: 0.7; to: 1.3; duration: 1200; easing.type: Easing.OutSine }
- OpacityAnimator { target: halo; from: 0.8; to: 0.0; duration: 1200; easing.type: Easing.OutSine }
- }
- PauseAnimation { duration: ring.state === "permission" ? 200 : 600 }
- }
- }
-
- // ---- Strobe: a hard red flash disc (permission repeats it, failed fires it once). ----
- Rectangle {
- id: strobe
- anchors.centerIn: parent
- width: ring.size; height: ring.size; radius: width / 2
- color: ring.danger
- opacity: 0
- visible: ring.motion && (ring.state === "permission" || ring.state === "failed")
- }
-
- // ---- Chromatic glitch ghosts: two offset copies of the ring in cyan and magenta. ----
- Rectangle {
- id: ghostA
- anchors.centerIn: parent
- transform: Translate { id: ghostAShift; x: 0 }
- width: ring.ringDiameter; height: width; radius: width / 2
- color: "transparent"
- border.width: ring.lineWidth
- border.color: ring.glitchA
- opacity: 0
- visible: strobe.visible
- }
- Rectangle {
- id: ghostB
- anchors.centerIn: parent
- transform: Translate { id: ghostBShift; x: 0 }
- width: ring.ringDiameter; height: width; radius: width / 2
- color: "transparent"
- border.width: ring.lineWidth
- border.color: ring.glitchB
- opacity: 0
- visible: strobe.visible
- }
-
- // One chromatic glitch: ghosts split left and right, the core jitters, all snap back (90 ms).
- SequentialAnimation {
- id: glitch
- PropertyAction { target: ghostA; property: "opacity"; value: 0.85 }
- PropertyAction { target: ghostB; property: "opacity"; value: 0.85 }
- PropertyAction { target: ghostAShift; property: "x"; value: -1.5 }
- PropertyAction { target: ghostBShift; property: "x"; value: 1.5 }
- PropertyAction { target: coreShift; property: "x"; value: 1 }
- PauseAnimation { duration: 50 }
- PropertyAction { target: ghostAShift; property: "x"; value: 1 }
- PropertyAction { target: ghostBShift; property: "x"; value: -1 }
- PropertyAction { target: coreShift; property: "x"; value: -1 }
- PauseAnimation { duration: 40 }
- PropertyAction { target: coreShift; property: "x"; value: 0 }
- PropertyAction { target: ghostA; property: "opacity"; value: 0 }
- PropertyAction { target: ghostB; property: "opacity"; value: 0 }
- }
-
- // Permission: three strobes and a glitch, every 1.6 s, until someone answers.
- SequentialAnimation {
- running: ring.motion && ring.state === "permission"
- loops: Animation.Infinite
- OpacityAnimator { target: strobe; from: 0; to: 0.9; duration: 50 }
- OpacityAnimator { target: strobe; from: 0.9; to: 0; duration: 90 }
- OpacityAnimator { target: strobe; from: 0; to: 0.9; duration: 50 }
- OpacityAnimator { target: strobe; from: 0.9; to: 0; duration: 90 }
- OpacityAnimator { target: strobe; from: 0; to: 0.9; duration: 50 }
- OpacityAnimator { target: strobe; from: 0.9; to: 0; duration: 90 }
- ScriptAction { script: glitch.restart() }
- PauseAnimation { duration: 1180 }
- }
-
- // Failed: two flashes and a glitch on entry, then only a glitch tick every 6 s.
- SequentialAnimation {
- id: failBurst
- OpacityAnimator { target: strobe; from: 0; to: 0.9; duration: 50 }
- OpacityAnimator { target: strobe; from: 0.9; to: 0; duration: 90 }
- PauseAnimation { duration: 80 }
- OpacityAnimator { target: strobe; from: 0; to: 0.9; duration: 50 }
- OpacityAnimator { target: strobe; from: 0.9; to: 0; duration: 90 }
- ScriptAction { script: glitch.restart() }
- }
- SequentialAnimation {
- running: ring.motion && ring.state === "failed"
- loops: Animation.Infinite
- PauseAnimation { duration: 6000 }
- ScriptAction { script: glitch.restart() }
- }
-
- // ---- Done: shockwave ring expands once as the core fills. ----
- Rectangle {
- id: shockwave
- anchors.centerIn: parent
- width: ring.size; height: ring.size; radius: width / 2
- color: "transparent"
- border.width: 1.5
- border.color: ring.okay
- opacity: 0
- visible: ring.motion
- }
- ParallelAnimation {
- id: doneBurst
- ScaleAnimator { target: shockwave; from: 0.5; to: 1.35; duration: 520; easing.type: Easing.OutCubic }
- OpacityAnimator { target: shockwave; from: 1.0; to: 0.0; duration: 520; easing.type: Easing.OutCubic }
- }
-
- // ---- Spend arc: the outer edge, 0 to 100 percent of the cap. Amber at 80, red at the cap. ----
- Shape {
- id: spendShape
- anchors.fill: parent
- visible: ring.hasSpend
- preferredRendererType: Shape.CurveRenderer
- property real sweep: Math.min(1, Math.max(0, ring.spendFraction)) * 360
- Behavior on sweep { NumberAnimation { duration: ring.motion ? 700 : 0; easing.type: Easing.OutCubic } }
- ShapePath {
- strokeWidth: 1.2
- strokeColor: Qt.rgba(Color.foreground.r, Color.foreground.g, Color.foreground.b, 0.12)
- fillColor: "transparent"
- PathAngleArc { centerX: ring.size / 2; centerY: ring.size / 2; radiusX: ring.size / 2 - 0.7; radiusY: radiusX; startAngle: 0; sweepAngle: 360 }
- }
- ShapePath {
- strokeWidth: 1.2
- capStyle: ShapePath.RoundCap
- fillColor: "transparent"
- strokeColor: ring.spendFraction >= 1 ? ring.danger : ring.spendFraction >= 0.8 ? ring.urgent : Qt.rgba(ring.accent.r, ring.accent.g, ring.accent.b, 0.85)
- PathAngleArc { centerX: ring.size / 2; centerY: ring.size / 2; radiusX: ring.size / 2 - 0.7; radiusY: radiusX; startAngle: -90; sweepAngle: spendShape.sweep }
- }
- }
-
- // ---- The state ring itself. ----
- Item {
- id: core
- anchors.centerIn: parent
- transform: Translate { id: coreShift; x: 0 }
- width: ring.ringDiameter
- height: ring.ringDiameter
- scale: ring.coreScale
- opacity: ring.flash
- Behavior on scale { enabled: ring.motion && !ring.waitingOnPerson; NumberAnimation { duration: 260; easing.type: Easing.OutCubic } }
-
- // Base ring. Working dims it so the comet reads; offline dashes it.
- Rectangle {
- anchors.fill: parent
- radius: width / 2
- color: "transparent"
- visible: ring.state !== "offline"
- border.width: ring.lineWidth
- border.color: ring.state === "working"
- ? Qt.rgba(ring.stateColor.r, ring.stateColor.g, ring.stateColor.b, ring.motion ? 0.22 : 1.0)
- : ring.stateColor
- Behavior on border.color { ColorAnimation { duration: ring.motion ? 220 : 0 } }
- }
- Shape {
- anchors.fill: parent
- visible: ring.state === "offline"
- preferredRendererType: Shape.CurveRenderer
- ShapePath {
- strokeWidth: 1.2
- strokeColor: ring.dim
- fillColor: "transparent"
- strokeStyle: ShapePath.DashLine
- dashPattern: [1.5, 2]
- PathAngleArc { centerX: core.width / 2; centerY: core.height / 2; radiusX: core.width / 2 - 0.6; radiusY: radiusX; startAngle: 0; sweepAngle: 360 }
- }
- }
-
- // Working: a comet head with a fading trail, rotating on the render thread.
- Item {
- id: comet
- anchors.fill: parent
- visible: ring.motion && ring.state === "working"
- RotationAnimator on rotation {
- running: comet.visible
- loops: Animation.Infinite
- from: 0; to: 360; duration: 1800
- }
- Shape {
- anchors.fill: parent
- preferredRendererType: Shape.CurveRenderer
- id: cometShape
- readonly property real cr: comet.width / 2 - ring.lineWidth / 2
- ShapePath {
- strokeWidth: ring.lineWidth; fillColor: "transparent"; capStyle: ShapePath.FlatCap
- strokeColor: Qt.rgba(ring.accent.r, ring.accent.g, ring.accent.b, 0.12)
- PathAngleArc { centerX: comet.width / 2; centerY: comet.height / 2; radiusX: cometShape.cr; radiusY: cometShape.cr; startAngle: -210; sweepAngle: 40 }
- }
- ShapePath {
- strokeWidth: ring.lineWidth; fillColor: "transparent"; capStyle: ShapePath.FlatCap
- strokeColor: Qt.rgba(ring.accent.r, ring.accent.g, ring.accent.b, 0.3)
- PathAngleArc { centerX: comet.width / 2; centerY: comet.height / 2; radiusX: cometShape.cr; radiusY: cometShape.cr; startAngle: -170; sweepAngle: 30 }
- }
- ShapePath {
- strokeWidth: ring.lineWidth; fillColor: "transparent"; capStyle: ShapePath.FlatCap
- strokeColor: Qt.rgba(ring.accent.r, ring.accent.g, ring.accent.b, 0.6)
- PathAngleArc { centerX: comet.width / 2; centerY: comet.height / 2; radiusX: cometShape.cr; radiusY: cometShape.cr; startAngle: -140; sweepAngle: 25 }
- }
- ShapePath {
- strokeWidth: ring.lineWidth; fillColor: "transparent"; capStyle: ShapePath.RoundCap
- strokeColor: ring.accent
- PathAngleArc { centerX: comet.width / 2; centerY: comet.height / 2; radiusX: cometShape.cr; radiusY: cometShape.cr; startAngle: -115; sweepAngle: 25 }
- }
- }
- // Bright head at 12 o'clock with a glow, so the leading edge is unmistakable.
- Rectangle {
- width: ring.lineWidth + 1.6; height: width; radius: width / 2
- x: comet.width / 2 - width / 2
- y: ring.lineWidth / 2 - height / 2
- color: Qt.lighter(ring.accent, 1.5)
- layer.enabled: true
- layer.effect: MultiEffect { shadowEnabled: true; shadowColor: ring.accent; shadowBlur: 0.6; shadowHorizontalOffset: 0; shadowVerticalOffset: 0 }
- }
- }
- // Reduced motion working: a static half arc so the state still reads.
- Shape {
- anchors.fill: parent
- visible: !ring.motion && ring.state === "working"
- preferredRendererType: Shape.CurveRenderer
- ShapePath {
- strokeWidth: ring.lineWidth; fillColor: "transparent"
- strokeColor: ring.accent
- PathAngleArc { centerX: core.width / 2; centerY: core.height / 2; radiusX: core.width / 2 - ring.lineWidth / 2; radiusY: radiusX; startAngle: -90; sweepAngle: 180 }
- }
- }
-
- // Done: the core fills to a solid dot.
- Rectangle {
- anchors.centerIn: parent
- width: parent.width; height: parent.height; radius: width / 2
- color: ring.okay
- scale: ring.fill
- visible: ring.fill > 0.01
- }
- }
-
- // The face of the person being waited on, round-masked inside the ring. Fades in and out; the
- // ring itself is unchanged so the footprint never moves.
- Item {
- id: avatarHolder
- anchors.centerIn: parent
- width: ring.size - 6
- height: ring.size - 6
- visible: opacity > 0
- opacity: ring.showAvatar ? 1.0 : 0.0
- scale: ring.breath
- Behavior on opacity { NumberAnimation { duration: ring.reducedMotion ? 0 : 220 } }
- Image {
- id: avatar
- anchors.fill: parent
- source: ring.avatarPath !== "" ? "file://" + ring.avatarPath : ""
- fillMode: Image.PreserveAspectCrop
- asynchronous: true
- cache: true
- visible: false
- }
- Rectangle {
- id: avatarMask
- anchors.fill: parent
- radius: width / 2
- color: "white"
- visible: false
- layer.enabled: true
- }
- MultiEffect {
- anchors.fill: parent
- visible: ring.avatarReady
- source: avatar
- maskEnabled: true
- maskSource: avatarMask
- }
- // Fallback: initials on a disc in the state colour.
- Rectangle {
- anchors.fill: parent
- radius: width / 2
- visible: !ring.avatarReady
- color: Qt.rgba(ring.stateColor.r, ring.stateColor.g, ring.stateColor.b, 0.85)
- Text {
- anchors.centerIn: parent
- text: ring.avatarInitials
- color: Color.background
- font.pixelSize: Math.max(6, parent.height * (ring.avatarInitials.length > 1 ? 0.48 : 0.62))
- font.bold: true
- }
- }
- }
-
- Text {
- anchors.centerIn: parent
- visible: ring.showGlyph && !ring.showAvatar
- text: ring.agent && ring.agent.glyph ? ring.agent.glyph : ""
- color: ring.state === "done" ? Color.background : ring.stateColor
- font.pixelSize: Math.max(8, ring.size * 0.55)
- font.bold: true
- }
-}
diff --git a/integrations/omarchy/harness-pulse/FleetView.qml b/integrations/omarchy/harness-pulse/FleetView.qml
deleted file mode 100644
index aeaf19547..000000000
--- a/integrations/omarchy/harness-pulse/FleetView.qml
+++ /dev/null
@@ -1,682 +0,0 @@
-pragma ComponentBehavior: Bound
-import QtQuick
-import QtQuick.Shapes
-import QtQuick.Effects
-import qs.Commons
-import "Model.js" as Model
-
-// The popup: a live fleet view. Fixed size; nothing in here scrolls except the bounded activity
-// ticker, which scrolls in place. Every animation answers a question:
-// orbit turning something on that machine is working (stops when nothing is)
-// hub glow and tether something on that machine needs you
-// spend gauges sweeping how much of each agent's cap is used (redrawn from zero on open)
-// triangle pulsing two agents touched the same file, folder or branch inside the hour
-// ticker slide-in what just changed, newest on top
-// hexagon charging how far through the 2 s hold-to-stop you are
-// All motion stops while the popup is closed, and reducedMotion freezes it (values still show).
-Item {
- id: fleet
-
- property var agents: []
- property var alerts: []
- property var subs: []
- property string subsPick: ""
- property string hostname: ""
- property bool daemonUp: false
- property bool active: false
- property bool reducedMotion: false
- property string workingColor: "Accent"
- property var theme: ({})
- property string lastStop: ""
- property string logoMode: "Harness" // Omarchy, Harness, Custom or None
- property string logoPath: ""
- property int nowMs: Date.now()
- signal stopAllRequested()
-
- readonly property bool motion: active && !reducedMotion
- readonly property color accent: Color.accent
- readonly property color fg: Color.foreground
- readonly property color urgent: theme.yellow ? theme.yellow : Color.urgent
- readonly property color danger: theme.red ? theme.red : Color.urgent
- readonly property color okay: theme.green ? theme.green : Color.accent
- readonly property color faint: Qt.rgba(fg.r, fg.g, fg.b, 0.14)
- readonly property color muted: Qt.rgba(fg.r, fg.g, fg.b, 0.55)
- readonly property var groups: Model.groupByMachine(agents, hostname).slice(0, 3)
- readonly property var counts: Model.stateCounts(agents)
-
- function colorFor(state) {
- switch (state) {
- case "working": return accent
- case "waiting": return urgent
- case "permission": return danger
- case "failed": return danger
- case "done": return okay
- case "offline": return Qt.rgba(fg.r, fg.g, fg.b, 0.28)
- default: return muted
- }
- }
- function hexPoints(cx, cy, r) {
- var pts = []
- for (var i = 0; i <= 6; i++) {
- var a = Math.PI / 180 * (60 * i - 90)
- pts.push(Qt.point(cx + r * Math.cos(a), cy + r * Math.sin(a)))
- }
- return pts
- }
-
- // Spend gauges redraw from zero each time the popup opens, so the quantity is drawn, not stamped.
- property bool revealed: false
- onActiveChanged: {
- revealed = false
- if (active) revealTimer.restart()
- }
- Timer { id: revealTimer; interval: 60; onTriggered: fleet.revealed = true }
-
- implicitWidth: 480
- implicitHeight: column.implicitHeight
-
- // Faint scanlines on the orbit field only (idle texture, never over text), 8 percent.
- Column {
- id: column
- width: parent.width
- spacing: 10
-
- // ---------------- Header: title, daemon, state chips, collision badge ----------------
- Item {
- width: parent.width
- height: 26
- Row {
- anchors.verticalCenter: parent.verticalCenter
- spacing: 8
- Text {
- text: fleet.daemonUp ? "⬡" : "⬢"
- color: fleet.daemonUp ? fleet.accent : fleet.muted
- font.pixelSize: 18
- anchors.verticalCenter: parent.verticalCenter
- }
- Column {
- anchors.verticalCenter: parent.verticalCenter
- Text { text: "HARNESS FLEET"; color: fleet.fg; font.pixelSize: 11; font.bold: true; font.letterSpacing: 2 }
- Text {
- text: fleet.daemonUp ? (fleet.agents.length + " agents on " + fleet.groups.length + " machine" + (fleet.groups.length === 1 ? "" : "s")) : "daemon not running"
- color: fleet.muted; font.pixelSize: 10
- }
- }
- }
- Row {
- anchors.right: badge.left
- anchors.rightMargin: 10
- anchors.verticalCenter: parent.verticalCenter
- spacing: 6
- Repeater {
- model: ["permission", "waiting", "failed", "working", "done"]
- delegate: Rectangle {
- id: chip
- required property string modelData
- readonly property int n: fleet.counts[chip.modelData] || 0
- height: 18
- width: chipText.implicitWidth + 12
- radius: 9
- color: chip.n > 0 ? Qt.rgba(fleet.colorFor(chip.modelData).r, fleet.colorFor(chip.modelData).g, fleet.colorFor(chip.modelData).b, 0.16) : "transparent"
- border.width: 1
- border.color: chip.n > 0 ? fleet.colorFor(chip.modelData) : fleet.faint
- Text {
- id: chipText
- anchors.centerIn: parent
- text: Model.glyphFor(chip.modelData) + " " + chip.n
- color: chip.n > 0 ? fleet.colorFor(chip.modelData) : fleet.muted
- font.pixelSize: 10
- font.bold: chip.n > 0
- }
- }
- }
- }
- // Collision badge: a red triangle that pulses while an alert is live. Its slot is always
- // reserved so the header never shifts; with no alert it is a faint outline.
- Item {
- id: badge
- anchors.right: parent.right
- anchors.verticalCenter: parent.verticalCenter
- width: 26; height: 24
- readonly property bool live: fleet.alerts.length > 0
- Shape {
- id: tri
- anchors.fill: parent
- preferredRendererType: Shape.CurveRenderer
- transformOrigin: Item.Center
- ShapePath {
- strokeWidth: 1.6
- joinStyle: ShapePath.RoundJoin
- strokeColor: badge.live ? fleet.danger : fleet.faint
- fillColor: badge.live ? Qt.rgba(fleet.danger.r, fleet.danger.g, fleet.danger.b, 0.25) : "transparent"
- PathPolyline { path: [Qt.point(13, 2), Qt.point(24.5, 22), Qt.point(1.5, 22), Qt.point(13, 2)] }
- }
- }
- Rectangle {
- id: triGlow
- anchors.centerIn: parent
- width: 30; height: 30; radius: 15
- color: "transparent"
- border.width: 2
- border.color: fleet.danger
- opacity: 0
- visible: badge.live && fleet.motion
- }
- SequentialAnimation {
- running: badge.live && fleet.motion
- loops: Animation.Infinite
- ParallelAnimation {
- ScaleAnimator { target: tri; from: 1.0; to: 1.15; duration: 240; easing.type: Easing.OutQuad }
- ScaleAnimator { target: triGlow; from: 0.6; to: 1.4; duration: 700; easing.type: Easing.OutCubic }
- OpacityAnimator { target: triGlow; from: 0.9; to: 0; duration: 700; easing.type: Easing.OutCubic }
- }
- ScaleAnimator { target: tri; from: 1.15; to: 1.0; duration: 300; easing.type: Easing.InOutQuad }
- PauseAnimation { duration: 600 }
- onRunningChanged: if (!running) tri.scale = 1
- }
- Text {
- anchors.horizontalCenter: parent.horizontalCenter
- y: 9
- text: badge.live ? String(fleet.alerts.length) : "△"
- visible: badge.live
- color: fleet.fg
- font.pixelSize: 10
- font.bold: true
- }
- }
- }
-
- // ---------------- Orbit field: one hub per machine, agents in orbit ----------------
- Rectangle {
- id: field
- width: parent.width
- height: 176
- radius: 10
- color: Qt.rgba(fleet.fg.r, fleet.fg.g, fleet.fg.b, 0.03)
- border.width: 1
- border.color: fleet.faint
- clip: true
-
- // Scanlines: 8 percent, static, never over text (the machine label sits below the lines' tile).
- Column {
- anchors.fill: parent
- opacity: 0.08
- spacing: 3
- Repeater {
- model: Math.floor(field.height / 3)
- delegate: Rectangle { width: field.width; height: 1; color: fleet.accent }
- }
- }
-
- // Idle / connecting: the chosen logo and one line of status. While the daemon is down the logo
- // breathes (still trying); with the daemon up and no agents it holds still (nothing to do).
- Column {
- anchors.centerIn: parent
- spacing: 10
- visible: fleet.groups.length === 0
- Item {
- id: logoBox
- anchors.horizontalCenter: parent.horizontalCenter
- // A wordmark gets a wide box, the hexagon a square one; the column height stays the same.
- width: imageOk ? 200 : 64; height: 64
- visible: fleet.logoMode !== "None"
- readonly property string imagePath: fleet.logoMode === "Omarchy" ? "/usr/share/omarchy/logo.svg"
- : fleet.logoMode === "Custom" ? fleet.logoPath : ""
- readonly property bool imageOk: logoImage.status === Image.Ready
- opacity: 0.85
- SequentialAnimation on opacity {
- running: fleet.motion && !fleet.daemonUp && logoBox.visible
- loops: Animation.Infinite
- NumberAnimation { from: 0.85; to: 0.3; duration: 1200; easing.type: Easing.InOutSine }
- NumberAnimation { from: 0.3; to: 0.85; duration: 1200; easing.type: Easing.InOutSine }
- onRunningChanged: if (!running) logoBox.opacity = 0.85
- }
- Image {
- id: logoImage
- anchors.fill: parent
- source: logoBox.imagePath !== "" ? "file://" + logoBox.imagePath : ""
- sourceSize.width: 400; sourceSize.height: 128
- fillMode: Image.PreserveAspectFit
- asynchronous: true
- visible: false
- }
- MultiEffect {
- anchors.fill: parent
- source: logoImage
- visible: logoBox.imageOk
- // Tint to the theme so the Omarchy mark follows the palette like everything else.
- brightness: fleet.logoMode === "Omarchy" ? 1.0 : 0.0
- colorization: fleet.logoMode === "Omarchy" ? 1.0 : 0.0
- colorizationColor: fleet.accent
- }
- // Harness mark (and the fallback when an image logo cannot be read): a drawn hexagon.
- Shape {
- anchors.fill: parent
- visible: !logoBox.imageOk
- preferredRendererType: Shape.CurveRenderer
- ShapePath {
- strokeWidth: 2.5
- joinStyle: ShapePath.RoundJoin
- strokeColor: fleet.accent
- fillColor: "transparent"
- PathPolyline { path: fleet.hexPoints(logoBox.width / 2, 32, 28) }
- }
- ShapePath {
- strokeWidth: 1.2
- joinStyle: ShapePath.RoundJoin
- strokeColor: Qt.rgba(fleet.accent.r, fleet.accent.g, fleet.accent.b, 0.5)
- fillColor: Qt.rgba(fleet.accent.r, fleet.accent.g, fleet.accent.b, 0.12)
- PathPolyline { path: fleet.hexPoints(logoBox.width / 2, 32, 16) }
- }
- }
- }
- Text {
- anchors.horizontalCenter: parent.horizontalCenter
- text: fleet.daemonUp ? "No agents. Nothing is moving, so nothing animates." : "Connecting to the Harness daemon..."
- color: fleet.muted
- font.pixelSize: 11
- }
- }
-
- Row {
- anchors.centerIn: parent
- spacing: 4
- Repeater {
- model: fleet.groups
- delegate: Item {
- id: tile
- required property var modelData
- readonly property var group: modelData
- readonly property int n: Math.min(8, group.agents.length)
- width: Math.min(156, (field.width - 16) / Math.max(1, fleet.groups.length))
- height: field.height
- readonly property real cx: width / 2
- readonly property real cy: 78
- readonly property real orbitR: 56
-
- // Orbit angle. Turns only while something on this machine works (one turn per 24 s).
- property real angle: 0
- NumberAnimation on angle {
- running: fleet.motion && tile.group.working
- loops: Animation.Infinite
- from: 0; to: 360; duration: 24000
- }
-
- // Orbit track, dashed.
- Shape {
- anchors.fill: parent
- preferredRendererType: Shape.CurveRenderer
- ShapePath {
- strokeWidth: 1
- strokeColor: tile.group.working ? Qt.rgba(fleet.accent.r, fleet.accent.g, fleet.accent.b, 0.35) : fleet.faint
- fillColor: "transparent"
- strokeStyle: ShapePath.DashLine
- dashPattern: [2, 4]
- PathAngleArc { centerX: tile.cx; centerY: tile.cy; radiusX: tile.orbitR; radiusY: tile.orbitR; startAngle: 0; sweepAngle: 360 }
- }
- }
-
- // Tethers from the hub to every agent that needs a person: they breathe with the hub.
- Repeater {
- model: tile.n
- delegate: Shape {
- id: tether
- required property int index
- readonly property var a: tile.group.agents[index]
- readonly property real rad: Math.PI / 180 * (tile.angle + index * 360 / tile.n - 90)
- anchors.fill: parent
- visible: a && (a.state === "waiting" || a.state === "permission" || a.state === "failed")
- opacity: hubGlow.opacity * 0.9 + 0.25
- preferredRendererType: Shape.CurveRenderer
- ShapePath {
- strokeWidth: 1.2
- strokeColor: fleet.colorFor(tether.a ? tether.a.state : "idle")
- fillColor: "transparent"
- startX: tile.cx; startY: tile.cy
- PathLine { x: tile.cx + (tile.orbitR - 10) * Math.cos(tether.rad); y: tile.cy + (tile.orbitR - 10) * Math.sin(tether.rad) }
- }
- }
- }
-
- // Hub: a hexagon for the machine. Glows (urgency) when anything on it needs you.
- Rectangle {
- id: hubGlow
- x: tile.cx - 30; y: tile.cy - 30
- width: 60; height: 60; radius: 30
- color: Qt.rgba(fleet.urgent.r, fleet.urgent.g, fleet.urgent.b, 0.22)
- visible: tile.group.needsYou
- opacity: 0.5
- SequentialAnimation on opacity {
- running: fleet.motion && tile.group.needsYou
- loops: Animation.Infinite
- NumberAnimation { from: 0.25; to: 0.9; duration: 900; easing.type: Easing.InOutSine }
- NumberAnimation { from: 0.9; to: 0.25; duration: 900; easing.type: Easing.InOutSine }
- }
- layer.enabled: visible
- layer.effect: MultiEffect { blurEnabled: true; blur: 0.8; blurMax: 24 }
- }
- Shape {
- anchors.fill: parent
- preferredRendererType: Shape.CurveRenderer
- ShapePath {
- strokeWidth: 1.8
- joinStyle: ShapePath.RoundJoin
- strokeColor: tile.group.needsYou ? fleet.urgent : fleet.accent
- fillColor: Qt.rgba(Color.background.r, Color.background.g, Color.background.b, 0.9)
- PathPolyline { path: fleet.hexPoints(tile.cx, tile.cy, 24) }
- }
- }
- Text {
- x: tile.cx - width / 2; y: tile.cy - height / 2
- width: 44
- horizontalAlignment: Text.AlignHCenter
- elide: Text.ElideMiddle
- text: tile.group.machine
- color: fleet.fg
- font.pixelSize: tile.group.machine.length > 7 ? 8 : 10
- font.bold: tile.group.machine === fleet.hostname
- }
-
- // Agent nodes: the same ring as the bar, upright, riding the orbit.
- Repeater {
- model: tile.n
- delegate: AgentRing {
- required property int index
- readonly property real rad: Math.PI / 180 * (tile.angle + index * 360 / tile.n - 90)
- size: 20
- x: tile.cx + tile.orbitR * Math.cos(rad) - width / 2
- y: tile.cy + tile.orbitR * Math.sin(rad) - height / 2
- agent: tile.group.agents[index] || ({})
- reducedMotion: !fleet.motion
- showGlyph: !fleet.motion
- theme: fleet.theme
- workingColor: fleet.workingColor
- }
- }
-
- Text {
- anchors.horizontalCenter: parent.horizontalCenter
- anchors.bottom: parent.bottom
- anchors.bottomMargin: 4
- text: tile.group.agents.length + " agent" + (tile.group.agents.length === 1 ? "" : "s")
- color: fleet.muted
- font.pixelSize: 10
- }
- }
- }
- }
- }
-
- // ---------------- Subscriptions: weekly use per plan, banked below (harness subs) ----------------
- Item {
- width: parent.width
- height: 82
- Text {
- id: spendLabel
- text: "THIS WEEK"
- color: fleet.muted
- font.pixelSize: 9; font.bold: true; font.letterSpacing: 2
- }
- Text {
- anchors.left: spendLabel.right; anchors.leftMargin: 8
- visible: gaugeRow.count === 0
- text: "no subscriptions detected"
- color: fleet.muted
- font.pixelSize: 10
- }
- Row {
- y: 14
- spacing: 6
- Repeater {
- id: gaugeRow
- model: fleet.subs.slice(0, 8)
- delegate: Item {
- id: gauge
- required property var modelData
- readonly property real f: Math.max(0, Number(modelData.used) || 0)
- readonly property real banked: Number(modelData.banked) || 0
- // Over pace (negative banked) is the warning, not raw use: 60 percent used on day six is fine.
- readonly property color tone: f >= 1 ? fleet.danger : banked < -0.1 ? fleet.danger : banked < 0 ? fleet.urgent : fleet.accent
- width: 64; height: 68
- property real shown: fleet.revealed ? Math.min(1, f) : 0
- Behavior on shown { NumberAnimation { duration: fleet.motion ? 900 : 0; easing.type: Easing.OutCubic } }
- Shape {
- id: gaugeShape
- width: 40; height: 40
- anchors.horizontalCenter: parent.horizontalCenter
- preferredRendererType: Shape.CurveRenderer
- ShapePath {
- strokeWidth: 4; capStyle: ShapePath.RoundCap; fillColor: "transparent"
- strokeColor: fleet.faint
- PathAngleArc { centerX: 20; centerY: 20; radiusX: 17; radiusY: 17; startAngle: 135; sweepAngle: 270 }
- }
- ShapePath {
- strokeWidth: 4; capStyle: ShapePath.RoundCap; fillColor: "transparent"
- strokeColor: gauge.tone
- PathAngleArc { centerX: 20; centerY: 20; radiusX: 17; radiusY: 17; startAngle: 135; sweepAngle: Math.max(0.1, 270 * gauge.shown) }
- }
- }
- // At or over the cap the gauge pulses once per second (the brake is on).
- Rectangle {
- anchors.centerIn: gaugeShape
- width: 40; height: 40; radius: 20
- color: "transparent"; border.width: 2; border.color: fleet.danger
- visible: gauge.f >= 1
- opacity: 0.2
- SequentialAnimation on opacity {
- running: fleet.motion && gauge.f >= 1
- loops: Animation.Infinite
- NumberAnimation { from: 0.9; to: 0.0; duration: 1000; easing.type: Easing.OutCubic }
- }
- }
- Text {
- anchors.centerIn: gaugeShape
- text: Math.round(gauge.f * 100) + "%"
- color: gauge.tone
- font.pixelSize: 9; font.bold: true
- }
- Text {
- anchors.horizontalCenter: parent.horizontalCenter
- anchors.bottom: parent.bottom
- width: parent.width
- horizontalAlignment: Text.AlignHCenter
- elide: Text.ElideRight
- text: (fleet.subsPick === gauge.modelData.id ? "▸ " : "") + gauge.modelData.name
- color: fleet.subsPick === gauge.modelData.id ? fleet.accent : fleet.muted
- font.pixelSize: 9
- }
- Text {
- anchors.horizontalCenter: parent.horizontalCenter
- y: 40
- text: (gauge.banked >= 0 ? "+" : "") + Math.round(gauge.banked * 100) + "% banked"
- color: gauge.banked >= 0 ? fleet.okay : gauge.tone
- font.pixelSize: 8
- }
- }
- }
- }
- }
-
- // ---------------- Collisions: fixed two lines, always reserved ----------------
- Column {
- width: parent.width
- height: 30
- Repeater {
- model: 2
- delegate: Text {
- required property int index
- readonly property var alert: fleet.alerts[index]
- width: parent.width
- elide: Text.ElideRight
- text: alert ? "△ " + alert.kind + ": " + alert.detail : (index === 0 ? "no collisions in the last hour" : "")
- color: alert ? fleet.danger : fleet.muted
- font.pixelSize: 10
- font.family: "monospace"
- }
- }
- }
-
- // ---------------- Activity ticker: bounded, scrolls in place ----------------
- Rectangle {
- width: parent.width
- height: 96
- radius: 8
- color: Qt.rgba(fleet.fg.r, fleet.fg.g, fleet.fg.b, 0.03)
- border.width: 1
- border.color: fleet.faint
- ListView {
- id: ticker
- anchors.fill: parent
- anchors.margins: 6
- clip: true
- spacing: 1
- model: tickerModel
- boundsBehavior: Flickable.StopAtBounds
- add: Transition {
- enabled: fleet.motion
- NumberAnimation { property: "x"; from: -24; to: 0; duration: 260; easing.type: Easing.OutCubic }
- NumberAnimation { property: "opacity"; from: 0; to: 1; duration: 260 }
- }
- displaced: Transition {
- enabled: fleet.motion
- NumberAnimation { property: "y"; duration: 200; easing.type: Easing.OutCubic }
- }
- delegate: Row {
- required property string t
- required property string glyph
- required property string st
- required property string who
- required property string what
- required property int index
- spacing: 6
- height: 16
- opacity: index === 0 ? 1.0 : 0.8
- Text { text: parent.t; color: fleet.muted; font.pixelSize: 10; font.family: "monospace" }
- Text { text: parent.glyph; color: fleet.colorFor(parent.st); font.pixelSize: 11; font.bold: true; width: 12 }
- Text { text: parent.who; color: fleet.fg; font.pixelSize: 10; font.bold: true }
- Text { text: parent.what; color: fleet.muted; font.pixelSize: 10; width: 300; elide: Text.ElideRight }
- }
- Text {
- anchors.centerIn: parent
- visible: ticker.count === 0
- text: "activity shows here as agents change state"
- color: fleet.muted
- font.pixelSize: 10
- }
- }
- }
-
- // ---------------- Hold-to-stop hexagon ----------------
- Item {
- width: parent.width
- height: 56
-
- Item {
- id: stopHex
- width: 52; height: 52
- property real hold: 0
- readonly property real c: 26
- readonly property real r: 23
- readonly property bool charging: stopMouse.pressed && fleet.daemonUp
-
- NumberAnimation on hold {
- id: charge
- running: false
- from: 0; to: 1; duration: 2000
- onFinished: if (stopHex.hold >= 1) { fleet.stopAllRequested(); drain.restart() }
- }
- NumberAnimation on hold { id: drain; running: false; to: 0; duration: fleet.reducedMotion ? 0 : 240; easing.type: Easing.OutCubic }
-
- // Charge core: the inner hexagon grows with the hold.
- Shape {
- anchors.fill: parent
- preferredRendererType: Shape.CurveRenderer
- scale: stopHex.hold
- visible: stopHex.hold > 0.01
- ShapePath {
- strokeWidth: 0
- strokeColor: "transparent"
- fillColor: Qt.rgba(fleet.danger.r, fleet.danger.g, fleet.danger.b, 0.25 + 0.5 * stopHex.hold)
- PathPolyline { path: fleet.hexPoints(stopHex.c, stopHex.c, stopHex.r - 3) }
- }
- }
- // Six edges, dim at rest; each lights as the hold passes its sixth.
- Repeater {
- model: 6
- delegate: Shape {
- id: edge
- required property int index
- readonly property var p: fleet.hexPoints(stopHex.c, stopHex.c, stopHex.r)
- readonly property bool lit: stopHex.hold * 6 > index
- anchors.fill: parent
- preferredRendererType: Shape.CurveRenderer
- ShapePath {
- strokeWidth: edge.lit ? 3 : 1.6
- capStyle: ShapePath.RoundCap
- strokeColor: edge.lit ? fleet.danger : Qt.rgba(fleet.danger.r, fleet.danger.g, fleet.danger.b, fleet.daemonUp ? 0.55 : 0.2)
- fillColor: "transparent"
- startX: edge.p[edge.index].x; startY: edge.p[edge.index].y
- PathLine { x: edge.p[edge.index + 1].x; y: edge.p[edge.index + 1].y }
- }
- }
- }
- // Crackle: a dashed hexagon spinning around the charge while held.
- Shape {
- id: crackle
- anchors.fill: parent
- visible: stopHex.charging && !fleet.reducedMotion
- preferredRendererType: Shape.CurveRenderer
- RotationAnimator on rotation { running: crackle.visible; loops: Animation.Infinite; from: 0; to: 360; duration: 900 }
- ShapePath {
- strokeWidth: 1
- strokeColor: Qt.lighter(fleet.danger, 1.4)
- fillColor: "transparent"
- strokeStyle: ShapePath.DashLine
- dashPattern: [1, 5]
- PathPolyline { path: fleet.hexPoints(stopHex.c, stopHex.c, stopHex.r + 2) }
- }
- }
- Text {
- anchors.centerIn: parent
- text: "■"
- color: stopHex.hold > 0.5 ? fleet.fg : fleet.danger
- font.pixelSize: 14
- }
- MouseArea {
- id: stopMouse
- anchors.fill: parent
- enabled: fleet.daemonUp
- onPressed: { drain.stop(); charge.from = stopHex.hold; charge.duration = Math.max(1, 2000 * (1 - stopHex.hold)); charge.restart() }
- onReleased: { if (charge.running) { charge.stop(); drain.restart() } }
- onCanceled: { charge.stop(); drain.restart() }
- }
- }
- Column {
- anchors.left: stopHex.right
- anchors.leftMargin: 12
- anchors.verticalCenter: parent.verticalCenter
- spacing: 2
- Text {
- text: stopHex.charging ? "STOPPING IN " + (2 * (1 - stopHex.hold)).toFixed(1) + " S, RELEASE TO CANCEL" : "HOLD 2 S TO STOP EVERY AGENT"
- color: stopHex.charging ? fleet.danger : fleet.fg
- font.pixelSize: 10; font.bold: true; font.letterSpacing: 1
- }
- Text {
- text: fleet.lastStop !== "" ? fleet.lastStop : "on " + (fleet.hostname || "this machine") + ", cancels every running turn"
- color: fleet.muted
- font.pixelSize: 10
- }
- }
- }
- }
-
- ListModel { id: tickerModel }
- // Bounded ticker: newest on top, at most 40 rows kept.
- function pushEvents(list) {
- for (var i = 0; i < list.length; i++) {
- var e = list[i]
- tickerModel.insert(0, { t: Model.clock(e.at), glyph: e.glyph, st: e.state, who: e.name + (e.machine ? "@" + e.machine : ""), what: e.text })
- }
- while (tickerModel.count > 40) tickerModel.remove(tickerModel.count - 1)
- }
-}
diff --git a/integrations/omarchy/harness-pulse/Model.js b/integrations/omarchy/harness-pulse/Model.js
deleted file mode 100644
index 9439b7bef..000000000
--- a/integrations/omarchy/harness-pulse/Model.js
+++ /dev/null
@@ -1,159 +0,0 @@
-.pragma library
-
-// Attention states the daemon emits. Anything unknown renders as idle.
-var STATES = ["working", "waiting", "permission", "failed", "done", "idle", "offline"];
-
-// Glyphs are the non-colour channel (accessibility, reducedMotion).
-var GLYPHS = {
- working: "◐", // half circle
- waiting: "?",
- permission: "!",
- failed: "✗", // ballot x
- done: "●", // filled circle
- idle: "○", // ring
- offline: "·" // middle dot
-};
-
-function normaliseState(s) {
- return STATES.indexOf(s) >= 0 ? s : "idle";
-}
-
-function glyphFor(state) {
- return GLYPHS[normaliseState(state)] || GLYPHS.idle;
-}
-
-// Parse one JSON line from pulse-feed. Returns {ok, agents, hostname, error}.
-function parseFeedLine(line) {
- try {
- var d = JSON.parse(line);
- if (!d || typeof d !== "object") return { ok: false, agents: [], error: "bad payload" };
- if (d.error) return { ok: false, agents: [], error: String(d.error) };
- var agents = Array.isArray(d.agents) ? d.agents : [];
- var alerts = Array.isArray(d.alerts) ? d.alerts : [];
- return {
- ok: true,
- hostname: d.hostname || "",
- // Weekly subscription use from the daemon (harness subs): used and banked are fractions.
- subs: d.subscriptions && Array.isArray(d.subscriptions.subs) ? d.subscriptions.subs.map(function (x) {
- return { id: String(x.id || ""), name: String(x.name || x.id || ""), used: Number(x.used) || 0,
- banked: Number(x.bankedSigned) || 0, tone: String(x.tone || ""), resetsInMs: Number(x.resetsInMs) || 0 };
- }) : [],
- pick: d.subscriptions ? String(d.subscriptions.pick || "") : "",
- // Collision alerts from the daemon: two agents on one file, folder or branch inside the hour.
- alerts: alerts.map(function (x) {
- return { kind: String(x.kind || ""), detail: String(x.detail || ""), at: Number(x.at) || 0 };
- }),
- agents: agents.map(function (a) {
- return {
- agentId: String(a.agentId || ""),
- name: String(a.name || a.agentId || "agent"),
- engine: String(a.engine || ""),
- machine: String(a.machine || d.hostname || ""),
- state: normaliseState(a.state),
- since: Number(a.since) || 0,
- detail: String(a.detail || ""),
- label: String(a.label || a.state || ""),
- glyph: a.glyph ? String(a.glyph) : glyphFor(a.state),
- lane: a.lane ? String(a.lane) : "",
- spend: a.spend && typeof a.spend === "object"
- ? { usd: Number(a.spend.usd) || 0, tokens: Number(a.spend.tokens) || 0,
- fraction: (a.spend.fraction === null || a.spend.fraction === undefined) ? null : Number(a.spend.fraction) }
- : null
- };
- })
- };
- } catch (e) {
- return { ok: false, agents: [], error: "parse: " + e };
- }
-}
-
-// Rank: what needs a person first. Permission and waiting float left.
-var RANK = { permission: 0, waiting: 1, failed: 2, done: 3, working: 4, idle: 5, offline: 6 };
-
-function sortAgents(agents) {
- return agents.slice().sort(function (a, b) {
- var r = RANK[a.state] - RANK[b.state];
- if (r !== 0) return r;
- return a.since - b.since;
- });
-}
-
-// Six-digit hex colours from colors.toml, keyed by name (blue, yellow, red...).
-function parseThemeColors(text) {
- var out = {};
- var re = /^\s*([A-Za-z0-9_]+)\s*=\s*"?#?([0-9a-fA-F]{6})"?/gm;
- var m;
- while ((m = re.exec(text)) !== null) out[m[1].toLowerCase()] = "#" + m[2];
- return out;
-}
-
-function ago(sinceMs, nowMs) {
- if (!sinceMs) return "";
- var s = Math.max(0, Math.round((nowMs - sinceMs) / 1000));
- if (s < 60) return s + "s";
- if (s < 3600) return Math.round(s / 60) + "m";
- return Math.round(s / 3600) + "h";
-}
-
-// Fleet view: agents grouped by machine, this host first, then by name. Each group carries
-// whether anything on it needs a person, so the hub can glow.
-function groupByMachine(agents, hostname) {
- var groups = {};
- var order = [];
- for (var i = 0; i < agents.length; i++) {
- var m = agents[i].machine || hostname || "local";
- if (!groups[m]) { groups[m] = { machine: m, agents: [], needsYou: false, working: false, spendUsd: 0 }; order.push(m); }
- var g = groups[m];
- g.agents.push(agents[i]);
- if (agents[i].state === "waiting" || agents[i].state === "permission" || agents[i].state === "failed") g.needsYou = true;
- if (agents[i].state === "working") g.working = true;
- if (agents[i].spend && agents[i].spend.usd) g.spendUsd += agents[i].spend.usd;
- }
- order.sort(function (a, b) {
- if (a === hostname) return -1;
- if (b === hostname) return 1;
- return a < b ? -1 : a > b ? 1 : 0;
- });
- return order.map(function (m) { return groups[m]; });
-}
-
-// Count per state, for the header chips.
-function stateCounts(agents) {
- var out = { working: 0, waiting: 0, permission: 0, failed: 0, done: 0, idle: 0, offline: 0 };
- for (var i = 0; i < agents.length; i++) out[agents[i].state] = (out[agents[i].state] || 0) + 1;
- return out;
-}
-
-// Activity ticker: compare the previous {agentId: state} map with the new agents and return one
-// event per change. First sight of an agent is an event too ("joined"). Returns {events, map}.
-function diffStates(prevMap, agents, nowMs) {
- var map = {};
- var events = [];
- for (var i = 0; i < agents.length; i++) {
- var a = agents[i];
- var key = a.agentId || (a.machine + "/" + a.name);
- map[key] = a.state;
- var before = prevMap ? prevMap[key] : undefined;
- if (before === a.state) continue;
- events.push({
- at: nowMs,
- name: a.name,
- machine: a.machine,
- state: a.state,
- glyph: glyphFor(a.state),
- text: before === undefined ? "joined, " + (a.label || a.state) : before + " > " + (a.label || a.state)
- });
- }
- if (prevMap) {
- for (var k in prevMap) {
- if (map[k] === undefined) events.push({ at: nowMs, name: k.split("/").pop(), machine: "", state: "offline", glyph: glyphFor("offline"), text: "left the fleet" });
- }
- }
- return { events: events, map: map };
-}
-
-function clock(ms) {
- var d = new Date(ms);
- function two(n) { return n < 10 ? "0" + n : "" + n; }
- return two(d.getHours()) + ":" + two(d.getMinutes()) + ":" + two(d.getSeconds());
-}
diff --git a/integrations/omarchy/harness-pulse/Panel.qml b/integrations/omarchy/harness-pulse/Panel.qml
deleted file mode 100644
index 2416e826c..000000000
--- a/integrations/omarchy/harness-pulse/Panel.qml
+++ /dev/null
@@ -1,378 +0,0 @@
-import QtQuick
-import QtQuick.Controls
-import QtQuick.Shapes
-import Quickshell
-import Quickshell.Io
-import qs.Commons
-import qs.Ui
-import "Model.js" as Model
-
-Panel {
- id: root
- moduleName: "pi.harness-pulse"
- ipcTarget: "harness-pulse"
- // The shared Panel IPC gives `open`, `close` and `toggle` on harness-pulse for the fleet popup.
- manageIpc: true
-
- // The bar (Omarchy's or menubar-overload) draws tooltips itself and only for a target whose
- // tooltipHovered is true; a tooltip drawn inside the widget is clipped to the bar's height.
- property bool tooltipHovered: false
- function hoverTip(text) { tooltipHovered = true; if (bar && bar.showTooltip) bar.showTooltip(root, text) }
- function unhoverTip() { tooltipHovered = false; if (bar && bar.hideTooltip) bar.hideTooltip(root) }
-
- readonly property int refreshIntervalSec: {
- var v = Number(setting("refreshIntervalSec", 1))
- return isFinite(v) ? Math.max(1, Math.min(30, Math.round(v))) : 1
- }
- readonly property int maxAgents: {
- var v = Number(setting("maxAgents", 8))
- return isFinite(v) ? Math.max(1, Math.min(24, Math.round(v))) : 8
- }
- readonly property bool reducedMotion: setting("reducedMotion", false) === true
- readonly property string workingColor: String(setting("workingColor", "Accent"))
- readonly property bool showMachine: setting("showMachine", true) !== false
- readonly property string focusWindowClass: String(setting("focusWindowClass", "com.autonomous.harness"))
- // The face shown inside a ring that waits on you. "Auto": avatarPath when set, else ~/.face, else
- // initials. "Initials": always initials. "None": plain ring. Nothing personal ships in the plugin.
- readonly property string avatarMode: String(setting("avatar", "Auto") || "Auto")
- readonly property string avatarSetting: String(setting("avatarPath", "") || "")
- readonly property string homeDir: Quickshell.env("HOME") || ""
- function expandHome(p) { return p.indexOf("~/") === 0 ? root.homeDir + p.substring(1) : p }
- // The candidate picture is probed once here, so a missing ~/.face costs one warning, not one per ring.
- readonly property string avatarPath: avatarProbe.status === Image.Ready ? avatarCandidate : ""
- Image { id: avatarProbe; visible: false; asynchronous: true; sourceSize.width: 64; sourceSize.height: 64; source: root.avatarCandidate !== "" ? "file://" + root.avatarCandidate : "" }
- readonly property string avatarCandidate: avatarMode !== "Auto" ? ""
- : (avatarSetting !== "" ? expandHome(avatarSetting) : (homeDir !== "" ? homeDir + "/.face" : ""))
- readonly property string avatarInitials: {
- if (avatarMode === "None") return ""
- var s = String(setting("avatarInitials", "") || "").trim()
- if (s === "") s = String(Quickshell.env("USER") || "").substring(0, 1)
- return s.substring(0, 2).toUpperCase()
- }
- // Logo for the popup's idle and connecting states: Omarchy (read from the system at runtime,
- // never bundled), Harness (a drawn hexagon mark), Custom (logoPath) or None.
- readonly property string logoMode: String(setting("logo", "Harness") || "Harness")
- readonly property string logoPath: expandHome(String(setting("logoPath", "") || ""))
- readonly property int ringSize: {
- var v = Number(setting("ringSize", 18))
- return isFinite(v) ? Math.max(12, Math.min(28, Math.round(v))) : 18
- }
-
- property var agents: []
- property var alerts: []
- property var subs: []
- property string subsPick: ""
- property string lastStop: ""
- property string hostname: ""
- property string lastError: ""
- property bool daemonUp: false
- property var theme: ({})
- property int nowMs: Date.now()
- // agentId -> last state, for the fleet view activity ticker.
- property var lastStates: null
-
- readonly property string helperPath: {
- var p = Qt.resolvedUrl("pulse-feed").toString()
- return p.indexOf("file://") === 0 ? p.substring(7) : p
- }
-
- // The bar row never grows: a fixed slot per ring up to maxAgents, plus a status glyph.
- readonly property int slotWidth: ringSize + 6
- // "Summary" (default): one ring for the most urgent agent plus a count. "Rings": one ring per agent.
- readonly property bool summaryBar: String(setting("barMode", "Summary")) !== "Rings"
- readonly property int needsYou: agents.filter(function (a) { return a.state === "waiting" || a.state === "permission" }).length
- readonly property int workingCount: agents.filter(function (a) { return a.state === "working" }).length
- readonly property string countText: needsYou > 0 ? String(needsYou) : String(agents.length)
- readonly property int countWidth: summaryBar && agents.length > 0 ? countText.length * Math.max(7, ringSize * 0.5) + 6 : 0
- // One short line: bar tooltips render inside the bar's window, so a second line is clipped.
- readonly property string fleetSummary: {
- if (!daemonUp) return "Harness daemon not running"
- if (agents.length === 0) return "Harness: no agents"
- var parts = [agents.length + " agent" + (agents.length === 1 ? "" : "s")]
- if (needsYou > 0) parts.push(needsYou + " waiting on you")
- if (workingCount > 0) parts.push(workingCount + " working")
- return "Harness · " + parts.join(" · ")
- }
-
- implicitWidth: statusGlyph.width + 4 + (collisionBadge.visible ? collisionBadge.width + 4 : 0) + (summaryBar ? slotWidth + countWidth : Math.max(1, Math.min(maxAgents, agents.length)) * slotWidth)
- implicitHeight: ringSize + 4
-
- // Theme palette (yellow/red/green) for the state colours; shell Color.* for the rest.
- FileView {
- id: themeFile
- path: Quickshell.env("HOME") + "/.local/state/omarchy/current/theme/colors.toml"
- watchChanges: true
- preload: false
- onLoaded: root.theme = Model.parseThemeColors(text())
- onFileChanged: reload()
- }
- Component.onCompleted: themeFile.reload()
-
- // The clock only ticks while a tooltip or the popup could show it.
- Timer { interval: 1000; running: true; repeat: true; onTriggered: root.nowMs = Date.now() }
-
- // pulse-feed polls the daemon and prints one JSON line per poll; exit 3 means daemon down.
- Process {
- id: feed
- command: ["python3", root.helperPath, "--interval", String(root.refreshIntervalSec)]
- running: true
- stdout: SplitParser {
- onRead: function (line) {
- var r = Model.parseFeedLine(line)
- if (!r.ok) { root.lastError = r.error; root.daemonUp = false; return }
- root.lastError = ""
- root.daemonUp = true
- root.hostname = r.hostname
- root.agents = Model.sortAgents(r.agents)
- root.alerts = r.alerts || []
- root.subs = r.subs || []
- root.subsPick = r.pick || ""
- var d = Model.diffStates(root.lastStates, root.agents, Date.now())
- root.lastStates = d.map
- if (d.events.length > 0) fleetView.pushEvents(d.events)
- }
- }
- onExited: function (code) {
- root.daemonUp = false
- // A minute without the daemon: the last roster is stale, so drop it rather than show ghosts.
- if (code === 3) { root.agents = []; root.alerts = []; root.lastStates = null }
- if (code === 3) root.lastError = "Harness daemon not running"
- else if (code !== 0) root.lastError = "pulse-feed exited " + code
- restart.start()
- }
- }
- Timer { id: restart; interval: 5000; repeat: false; onTriggered: feed.running = true }
-
- // Hyprland with a Lua config (0.56+, Omarchy 4) reads `hyprctl dispatch X` as `hl.dispatch(X)` and
- // refuses the classic `focuswindow class:...` form; older Hyprland knows only that form. Try the Lua
- // dispatcher first and fall back, so the same widget focuses the window on either.
- Process {
- id: focus
- command: ["sh", "-c",
- "hyprctl dispatch \"hl.dsp.focus({ window = 'class:^($1)$' })\" 2>/dev/null | grep -qx ok || hyprctl dispatch focuswindow \"class:^($1)$\"",
- "focus", root.focusWindowClass]
- running: false
- }
-
- Row {
- id: row
- anchors.verticalCenter: parent.verticalCenter
- spacing: 0
-
- // Status glyph: the daemon itself. Non-colour, one character.
- Text {
- id: statusGlyph
- anchors.verticalCenter: parent.verticalCenter
- text: root.daemonUp ? "⬡" : "⬢" // hexagon outline vs filled
- color: root.daemonUp ? Color.foreground : Qt.rgba(Color.foreground.r, Color.foreground.g, Color.foreground.b, 0.35)
- font.pixelSize: root.ringSize * 0.7
- Behavior on color { ColorAnimation { duration: root.reducedMotion ? 0 : 220 } }
-
- // Hold-to-stop: press and hold the hexagon for two seconds to cancel every agent turn on this
- // machine. A red ring drains around the hexagon while held; release early and nothing happens.
- property real hold: 0
- NumberAnimation on hold {
- id: holdAnim
- running: false
- from: 0; to: 1; duration: 2000
- onFinished: { if (statusGlyph.hold >= 1) { stopAll.running = true; statusGlyph.hold = 0 } }
- }
- // Shape, not Canvas: a Canvas repainted per frame flickers on the bar.
- Shape {
- id: holdArc
- anchors.centerIn: parent
- width: root.ringSize + 4; height: root.ringSize + 4
- visible: statusGlyph.hold > 0
- preferredRendererType: Shape.CurveRenderer
- ShapePath {
- strokeWidth: 2
- capStyle: ShapePath.RoundCap
- fillColor: "transparent"
- strokeColor: (root.theme && root.theme.red) ? root.theme.red : Color.urgent
- PathAngleArc { centerX: holdArc.width / 2; centerY: holdArc.height / 2; radiusX: holdArc.width / 2 - 1.5; radiusY: radiusX; startAngle: -90; sweepAngle: (1 - statusGlyph.hold) * 360 }
- }
- }
- MouseArea {
- anchors.fill: parent
- enabled: root.daemonUp
- hoverEnabled: true
- acceptedButtons: Qt.LeftButton | Qt.RightButton
- property double pressedAt: 0
- // A quick click opens the fleet popup; only a 2 s hold stops agents. Right-click also opens it.
- onPressed: function (mouse) {
- if (mouse.button === Qt.RightButton) return
- pressedAt = Date.now(); statusGlyph.hold = 0; holdAnim.restart()
- }
- onReleased: function (mouse) {
- holdAnim.stop(); statusGlyph.hold = 0
- if (mouse.button === Qt.RightButton || Date.now() - pressedAt < 400) root.toggle()
- }
- onCanceled: { holdAnim.stop(); statusGlyph.hold = 0 }
- onEntered: root.hoverTip(root.lastStop !== "" ? root.lastStop : "Click: fleet · Hold 2 s: stop all")
- onExited: root.unhoverTip()
- }
- }
- Process {
- id: stopAll
- command: ["python3", root.helperPath, "--stop-all"]
- running: false
- stdout: SplitParser {
- onRead: function (line) {
- try { var d = JSON.parse(line); root.lastStop = d.cancelled ? "Stopped " + d.cancelled.length + " agent(s)" : "Stop failed: " + (d.error || "unknown") }
- catch (e) { root.lastStop = "Stop failed" }
- }
- }
- }
- Item { width: 4; height: 1 }
-
- // Collision badge: two agents on one file, folder or branch in the last hour. Only present when
- // there is something to say, so the bar stays quiet otherwise (it takes a fixed slot only
- // while visible, and the ring row shifts by one glyph, never by a layout reflow).
- Text {
- id: collisionBadge
- anchors.verticalCenter: parent.verticalCenter
- visible: root.alerts.length > 0
- text: "△" + (root.alerts.length > 1 ? String(root.alerts.length) : "")
- color: (root.theme && root.theme.red) ? root.theme.red : Color.urgent
- font.pixelSize: root.ringSize * 0.7
- font.bold: true
- opacity: 1.0
- SequentialAnimation on opacity {
- running: collisionBadge.visible && !root.reducedMotion
- loops: Animation.Infinite
- NumberAnimation { from: 1.0; to: 0.45; duration: 900; easing.type: Easing.InOutSine }
- NumberAnimation { from: 0.45; to: 1.0; duration: 900; easing.type: Easing.InOutSine }
- }
- MouseArea {
- anchors.fill: parent
- hoverEnabled: true
- onEntered: root.hoverTip((function () {
- var lines = []
- for (var i = 0; i < root.alerts.length && i < 6; i++) lines.push(root.alerts[i].kind + ": " + root.alerts[i].detail)
- return lines.slice(0, 1).join("").slice(0, 60)
- })())
- onExited: root.unhoverTip()
- }
- }
- Item { width: collisionBadge.visible ? 4 : 0; height: 1 }
-
- Repeater {
- model: root.summaryBar ? (root.agents.length > 0 ? 1 : 0) : Math.min(root.maxAgents, root.agents.length)
- delegate: Item {
- required property int index
- readonly property var agent: root.agents[index] || ({})
- width: root.slotWidth + (root.summaryBar ? root.countWidth : 0)
- height: root.ringSize + 4
-
- Text {
- id: countLabel
- visible: root.summaryBar
- anchors.right: parent.right
- anchors.verticalCenter: parent.verticalCenter
- text: root.countText
- color: root.needsYou > 0 ? agentRing.stateColor : Color.foreground
- opacity: root.needsYou > 0 ? 1 : 0.6
- font.pixelSize: Math.max(10, root.ringSize - 6)
- font.bold: root.needsYou > 0
- }
-
- // A soft dot travels along the row toward a ring that waits on you (leads the eye on wide bars).
- Rectangle {
- id: pulseDot
- width: 4; height: 4; radius: 2
- y: parent.height / 2 - 2
- color: agentRing.stateColor
- opacity: 0
- visible: !root.reducedMotion && (agent.state === "waiting" || agent.state === "permission")
- SequentialAnimation on x {
- running: pulseDot.visible
- loops: Animation.Infinite
- PropertyAction { target: pulseDot; property: "opacity"; value: 0.0 }
- NumberAnimation { from: -root.slotWidth * 2; to: root.slotWidth / 2 - 2; duration: 900; easing.type: Easing.InOutQuad }
- PropertyAction { target: pulseDot; property: "opacity"; value: 0.0 }
- PauseAnimation { duration: 1500 }
- }
- SequentialAnimation on opacity {
- running: pulseDot.visible
- loops: Animation.Infinite
- NumberAnimation { from: 0; to: 0.85; duration: 300 }
- NumberAnimation { from: 0.85; to: 0; duration: 600 }
- PauseAnimation { duration: 1500 }
- }
- }
-
- AgentRing {
- id: agentRing
- anchors.verticalCenter: parent.verticalCenter
- x: (root.slotWidth - width) / 2
- size: root.ringSize
- agent: parent.agent
- reducedMotion: root.reducedMotion
- theme: root.theme
- avatarPath: root.avatarPath
- avatarInitials: root.avatarInitials
- workingColor: root.workingColor
- }
-
- MouseArea {
- anchors.fill: parent
- hoverEnabled: true
- acceptedButtons: Qt.LeftButton | Qt.RightButton
- // Left and right: the fleet popup (the Harness app is optional; Orca users never open it).
- onClicked: root.toggle()
- onEntered: root.hoverTip(root.summaryBar ? root.fleetSummary : (agent.name || "agent") + " · " + (agent.label || agent.state) + (agent.since ? " " + Model.ago(agent.since, root.nowMs) : ""))
- onExited: root.unhoverTip()
- }
- }
- }
- }
-
- MouseArea {
- anchors.fill: parent
- enabled: root.agents.length === 0
- hoverEnabled: true
- acceptedButtons: Qt.LeftButton | Qt.RightButton
- onClicked: root.toggle()
- onEntered: root.hoverTip(root.fleetSummary)
- onExited: root.unhoverTip()
- }
-
- // ---- Fleet popup: right-click the widget (or `toggle` over IPC). ----
- KeyboardPanel {
- id: popup
- anchorItem: row
- owner: root
- bar: root.bar
- open: root.opened
- focusTarget: keyCatcher
- contentWidth: popup.fittedContentWidth(480)
- contentHeight: popup.fittedContentHeight(fleetView.implicitHeight, 620)
-
- PanelKeyCatcher {
- id: keyCatcher
- anchors.fill: parent
- onCloseRequested: root.close()
- onTabRequested: function (direction) { root.switchPanel(direction) }
-
- FleetView {
- id: fleetView
- anchors.fill: parent
- agents: root.agents
- alerts: root.alerts
- subs: root.subs
- subsPick: root.subsPick
- hostname: root.hostname
- daemonUp: root.daemonUp
- active: root.opened
- reducedMotion: root.reducedMotion
- workingColor: root.workingColor
- theme: root.theme
- logoMode: root.logoMode
- logoPath: root.logoPath
- lastStop: root.lastStop
- nowMs: root.nowMs
- onStopAllRequested: stopAll.running = true
- }
- }
- }
-}
diff --git a/integrations/omarchy/harness-pulse/README.md b/integrations/omarchy/harness-pulse/README.md
deleted file mode 100644
index 81da029c4..000000000
--- a/integrations/omarchy/harness-pulse/README.md
+++ /dev/null
@@ -1,96 +0,0 @@
-# Harness Pulse (pi.harness-pulse)
-
-An [Omarchy](https://omarchy.org) bar widget: one ring per coding agent this computer's Harness
-daemon runs, on the bar. Written by Fred Nix ([@nixfred](https://github.com/nixfred)) in his fork,
-[github.com/nixfred/openharness](https://github.com/nixfred/openharness) (MIT).
-
-It shows the agents the Harness app shows — the daemon's own agents — and nothing else.
-
-State language on the bar (every animation sits behind the `reducedMotion` setting, and every state
-also has a glyph so colour is never the only signal):
-
-- working: a comet with a fading three-step trail and a glowing head circles clockwise (1.8 s a turn)
-- waiting on you: the ring breathes (1.0 to 1.08, 1.2 s), a soft halo swells out of it in the theme
- yellow, and a dot travels along the bar toward it
-- permission: the same breath and halo in theme red, plus a repeating red strobe (three flashes) and a
- chromatic glitch
-- failed: two strobes and a glitch on entry, then a steady thin red ring with one glitch tick every 6 s
-- done, unreviewed: the core fills to a solid dot with an overshoot and a shockwave ring, then holds
-- offline: a dim dashed ring, no motion
-- idle: the ring shrinks to a dot, no motion
-- spend: the outer arc, 0 to 100 percent of the per-agent cap (`harness spend set`); theme yellow from
- 80 percent, red at the cap
-
-Rings never change the row height or width; all motion is scale, opacity, rotation or a translate
-inside a fixed slot. Animations use Shape paths and render-thread animators, not Canvas, and nothing
-runs in idle, offline or a settled done ring.
-
-The daemon glyph at the left is a hexagon: outline when the daemon is up, filled when it is not.
-**Hold it 2 s to stop every agent on this machine** (`harness stop-all`); a red ring drains while held
-and releasing early cancels.
-
-Left-click a ring to focus the Harness window (Hyprland's Lua dispatcher on 0.56+, `focuswindow` on
-older versions; change `focusWindowClass` if the class differs). Hover for name, engine, machine,
-lane, state, spend and detail.
-
-## Fleet view (right-click, or IPC)
-
-Right-click the widget, or run `qs ipc call harness-pulse toggle` (also `open`, `close`). Escape
-closes it. The popup has a fixed size and never scrolls; only the activity ticker scrolls, in place.
-
-- Orbit field: one hexagon hub per machine, its agents riding a dashed orbit as the same rings as the
- bar. The orbit turns only while something works. The hub glows and a tether reaches out to every
- agent that waits on you, needs permission or failed.
-- State chips: a count per state with its glyph.
-- Spend: one 270 degree gauge per agent with a cap. Gauges sweep up from zero each time the popup
- opens, and one at or over its cap pulses red.
-- Activity ticker: every state change, newest on top. Bounded at 40 rows.
-- Hold-to-stop hexagon: press and hold. The six edges light one by one; release early and it drains.
-- Idle and connecting: the chosen logo (see `logo`), breathing while the daemon is not answering.
-
-All popup motion stops while the popup is closed.
-
-## Settings
-
-All settings are in the bar's widget settings (manifest `schema`), stored in
-`~/.config/omarchy/shell.json` under the widget.
-
-| Setting | Default | What it does |
-|---|---|---|
-| `reducedMotion` | `false` | Stops every animation on the bar and in the fleet view. |
-| `ringSize` | `18` | Ring diameter in logical px, 12 to 28. |
-| `maxAgents` | `8` | Rings on the bar, most urgent first (1 to 24). |
-| `refreshIntervalSec` | `1` | How often `pulse-feed` polls the daemon (1 to 30 s). |
-| `showMachine` | `true` | Show `@machine` in ring tooltips. |
-| `focusWindowClass` | `com.autonomous.harness` | Window class a left-click focuses. |
-| `avatar` | `Auto` | The face inside a ring that waits on you. `Auto`: `avatarPath` when set, else `~/.face`, else initials. `Initials`: always initials. `None`: a plain ring. |
-| `avatarPath` | empty | Picture for `Auto`, round-cropped. `~/` is expanded. |
-| `avatarInitials` | empty | One or two letters for the initials disc. Empty uses the first letter of `$USER`. |
-| `logo` | `Harness` | Idle and connecting logo in the fleet view: `Harness`, `Omarchy` (read from `/usr/share/omarchy/logo.svg` at runtime; nothing is bundled), `Custom` (`logoPath`) or `None`. |
-| `logoPath` | empty | Image for `logo: Custom` (SVG or PNG). `~/` is expanded. |
-
-## Data
-
-`pulse-feed` (python3, no dependencies) polls `GET /api/attention` on the local daemon, over its Unix
-socket `~/.harness/cli/data/daemon-18473.sock` first and 127.0.0.1:18473 second, once per
-`refreshIntervalSec`, and prints one JSON line per poll. Nothing leaves the machine. Exit 3 means the
-daemon was unreachable for a minute; the widget restarts the feed every 5 s. `HARNESS_PORT` and
-`HARNESS_SOCKET` override the defaults. The hold-to-stop calls `POST /api/stop-all` the same way.
-
-## Install
-
-From a checkout of this repository, on the Omarchy machine:
-
-```
-cp -r integrations/omarchy/harness-pulse ~/.config/omarchy/plugins/pi.harness-pulse
-omarchy restart shell
-```
-
-Never `omarchy refresh`: that is a factory reset of the bar. Add the widget with the bar's own IPC if
-it does not appear:
-
-```
-omarchy-shell shell putBarWidget pi.harness-pulse '{"section":"right","index":1}'
-```
-
-`Super + Shift + Space` shows the bar if it is hidden.
diff --git a/integrations/omarchy/harness-pulse/manifest.json b/integrations/omarchy/harness-pulse/manifest.json
deleted file mode 100644
index 6b637fb1c..000000000
--- a/integrations/omarchy/harness-pulse/manifest.json
+++ /dev/null
@@ -1,155 +0,0 @@
-{
- "schemaVersion": 1,
- "id": "pi.harness-pulse",
- "name": "Harness Pulse",
- "version": "0.3.0",
- "author": "Fred Nix",
- "description": "One ring per coding agent on every linked Harness machine. Working throws a comet, waiting breathes a halo toward you, permission strobes red with a glitch, done fills with a burst, failed flashes then holds, offline sits dim. Right-click for a live fleet view: machines with agents in orbit, spend gauges, an activity ticker and a hold-to-stop hexagon. Reads the local Harness daemon's attention feed; nothing leaves the machine.",
- "kinds": [
- "bar-widget"
- ],
- "entryPoints": {
- "barWidget": "Panel.qml"
- },
- "barWidget": {
- "displayName": "Harness Pulse",
- "description": "Agent attention rings for OpenHarness: which agent is working, which one is waiting on you, which one finished. Right-click for the fleet view.",
- "category": "Development",
- "allowMultiple": false,
- "defaultSection": "right",
- "defaults": {
- "refreshIntervalSec": 1,
- "maxAgents": 8,
- "reducedMotion": false,
- "showMachine": true,
- "focusWindowClass": "com.autonomous.harness",
- "ringSize": 18,
- "avatar": "Auto",
- "avatarPath": "",
- "avatarInitials": "",
- "logo": "Harness",
- "logoPath": "",
- "workingColor": "Accent",
- "barMode": "Summary"
- },
- "schema": [
- {
- "key": "barMode",
- "type": "enum",
- "label": "Bar layout",
- "options": [
- "Summary",
- "Rings"
- ],
- "description": "Summary: one ring for the most urgent agent and a count. Rings: one ring per agent.",
- "defaultValue": "Summary"
- },
- {
- "key": "reducedMotion",
- "type": "boolean",
- "label": "Reduced motion",
- "description": "Stops every animation on the bar and in the fleet view. States still read from colour, a glyph and a word.",
- "defaultValue": false
- },
- {
- "key": "workingColor",
- "type": "enum",
- "label": "Working ring colour",
- "options": [
- "Accent",
- "Cyan",
- "Green"
- ],
- "description": "Colour of a ring while its agent works. Accent follows your theme.",
- "defaultValue": "Accent"
- },
- {
- "key": "ringSize",
- "type": "integer",
- "label": "Ring size (px)",
- "min": 12,
- "max": 28,
- "step": 1,
- "defaultValue": 18
- },
- {
- "key": "maxAgents",
- "type": "integer",
- "label": "Rings on the bar",
- "description": "Most urgent first; the rest are in the fleet view.",
- "min": 1,
- "max": 24,
- "step": 1,
- "defaultValue": 8
- },
- {
- "key": "refreshIntervalSec",
- "type": "integer",
- "label": "Refresh interval (seconds)",
- "min": 1,
- "max": 30,
- "step": 1,
- "defaultValue": 1
- },
- {
- "key": "showMachine",
- "type": "boolean",
- "label": "Show machine in tooltips",
- "defaultValue": true
- },
- {
- "key": "focusWindowClass",
- "type": "string",
- "label": "Harness window class",
- "description": "Left-click on a ring focuses the window with this class.",
- "defaultValue": "com.autonomous.harness"
- },
- {
- "key": "avatar",
- "type": "enum",
- "label": "Face in a waiting ring",
- "options": [
- "Auto",
- "Initials",
- "None"
- ],
- "description": "Auto: the picture below, else ~/.face, else your initials. Initials: always initials. None: a plain ring.",
- "defaultValue": "Auto"
- },
- {
- "key": "avatarPath",
- "type": "path",
- "label": "Avatar picture",
- "description": "Any square-ish image; it is round-cropped. Empty uses ~/.face.",
- "defaultValue": ""
- },
- {
- "key": "avatarInitials",
- "type": "string",
- "label": "Initials",
- "description": "One or two letters. Empty uses the first letter of your user name.",
- "defaultValue": ""
- },
- {
- "key": "logo",
- "type": "enum",
- "label": "Idle and connecting logo",
- "options": [
- "Harness",
- "Omarchy",
- "Custom",
- "None"
- ],
- "description": "Shown in the fleet view when there are no agents or the daemon is not answering. Omarchy reads /usr/share/omarchy/logo.svg at runtime.",
- "defaultValue": "Harness"
- },
- {
- "key": "logoPath",
- "type": "path",
- "label": "Custom logo",
- "description": "Image used when the logo is Custom (SVG or PNG).",
- "defaultValue": ""
- }
- ]
- }
-}
diff --git a/integrations/omarchy/harness-pulse/pulse-feed b/integrations/omarchy/harness-pulse/pulse-feed
deleted file mode 100755
index cef4b3fdf..000000000
--- a/integrations/omarchy/harness-pulse/pulse-feed
+++ /dev/null
@@ -1,113 +0,0 @@
-#!/usr/bin/env python3
-"""pulse-feed: poll the local Harness daemon's attention feed and print one JSON line per poll.
-
-Tries the Unix socket first (~/.harness/cli/data/daemon-<port>.sock, HTTP over AF_UNIX), then
-127.0.0.1:<port>. Exit 0 on a clean stop, 3 when the daemon cannot be reached for a whole
-minute. Never prints anything that is not a JSON object.
-"""
-import argparse
-import http.client
-import json
-import os
-import socket
-import sys
-import time
-
-PORT = int(os.environ.get("HARNESS_PORT", "18473"))
-SOCK = os.path.expanduser(os.environ.get("HARNESS_SOCKET", f"~/.harness/cli/data/daemon-{PORT}.sock"))
-PATH = "/api/attention"
-UNREACHABLE_LIMIT_SEC = 60
-
-
-class UnixHTTPConnection(http.client.HTTPConnection):
- def __init__(self, path, timeout=2.0):
- super().__init__("localhost", timeout=timeout)
- self.unix_path = path
-
- def connect(self):
- s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
- s.settimeout(self.timeout)
- s.connect(self.unix_path)
- self.sock = s
-
-
-def fetch_once():
- errors = []
- conns = []
- if os.path.exists(SOCK):
- conns.append(("unix", lambda: UnixHTTPConnection(SOCK)))
- conns.append(("tcp", lambda: http.client.HTTPConnection("127.0.0.1", PORT, timeout=2.0)))
- for name, make in conns:
- try:
- c = make()
- c.request("GET", PATH, headers={"Host": f"127.0.0.1:{PORT}", "Accept": "application/json"})
- r = c.getresponse()
- body = r.read()
- c.close()
- if r.status != 200:
- errors.append(f"{name}: HTTP {r.status}")
- continue
- return json.loads(body.decode("utf-8", "replace")), None
- except (OSError, http.client.HTTPException, ValueError) as e:
- errors.append(f"{name}: {e.__class__.__name__}")
- return None, "; ".join(errors) or "unreachable"
-
-
-def stop_all():
- """Panic stop: POST /api/stop-all. Prints one JSON line, exit 0 on success, 1 otherwise."""
- headers = {"Host": f"127.0.0.1:{PORT}", "Content-Type": "application/json", "x-adapter-local": "1"}
- conns = []
- if os.path.exists(SOCK):
- conns.append(lambda: UnixHTTPConnection(SOCK))
- conns.append(lambda: http.client.HTTPConnection("127.0.0.1", PORT, timeout=5.0))
- for make in conns:
- try:
- c = make()
- c.request("POST", "/api/stop-all", body="{}", headers=headers)
- r = c.getresponse()
- body = r.read().decode("utf-8", "replace")
- c.close()
- print(body, flush=True)
- return 0 if r.status == 200 else 1
- except (OSError, http.client.HTTPException):
- continue
- print(json.dumps({"error": "unreachable"}), flush=True)
- return 1
-
-
-def main():
- ap = argparse.ArgumentParser()
- ap.add_argument("--interval", type=float, default=1.0)
- ap.add_argument("--once", action="store_true")
- ap.add_argument("--stop-all", action="store_true")
- a = ap.parse_args()
- if a.stop_all:
- sys.exit(stop_all())
- interval = max(0.5, a.interval)
- down_since = None
- while True:
- data, err = fetch_once()
- if data is not None:
- down_since = None
- out = {"hostname": data.get("hostname", ""), "machineId": data.get("machineId", ""),
- "at": data.get("at", int(time.time() * 1000)), "agents": data.get("agents", []),
- "alerts": data.get("alerts", []), "subscriptions": data.get("subscriptions")}
- else:
- down_since = down_since or time.time()
- out = {"error": err, "agents": []}
- if time.time() - down_since > UNREACHABLE_LIMIT_SEC:
- print(json.dumps(out), flush=True)
- sys.exit(3)
- print(json.dumps(out), flush=True)
- if a.once:
- return
- time.sleep(interval)
-
-
-if __name__ == "__main__":
- try:
- main()
- except KeyboardInterrupt:
- pass
- except BrokenPipeError:
- sys.exit(0)