Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

feat: repurpose the agent-card progress bar as a context gauge (closes #11)

Gulum9f98dc994468
diff --git a/src/main/hooks.ts b/src/main/hooks.ts
index 966dd0e0..d3587a71 100644
--- a/src/main/hooks.ts
+++ b/src/main/hooks.ts
@@ -21,6 +21,7 @@ interface HookPayload {
hook_event_name?: string;
agent_id?: string | null;
session_id?: string;
+ transcript_path?: string;
cwd?: string;
tool_name?: string;
tool_input?: unknown;
@@ -35,6 +36,10 @@ interface HookPayload {
export class HookServer {
private server: Server | null = null;
+ /** agentId → the live session's transcript file, learned from hook payloads.
+ * Lets the harness read per-agent telemetry (e.g. current context size)
+ * even when several agents share one cwd. */
+ private transcriptPaths = new Map<string, string>();
constructor(
private hive: HiveManager,
@@ -73,9 +78,17 @@ export class HookServer {
try { if (sock && existsSync(sock)) rmSync(sock); } catch { /* noop */ }
}
+ /** The transcript file of an agent's CURRENT session, if any hook has fired. */
+ transcriptPath(agentId: string): string | undefined {
+ return this.transcriptPaths.get(agentId);
+ }
+
private handle(p: HookPayload): unknown {
const agentId = p.agent_id ?? undefined;
const event = p.hook_event_name ?? 'Unknown';
+ if (agentId && typeof p.transcript_path === 'string' && p.transcript_path) {
+ this.transcriptPaths.set(agentId, p.transcript_path);
+ }
if ((event === 'Stop' || event === 'SubagentStop') && agentId) {
// Loop guard: a previous Stop hook already blocked this turn → let it stop.
diff --git a/src/main/index.ts b/src/main/index.ts
index c92c4aac..d515cbc4 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -16,7 +16,7 @@ import { HiveManager, type AgentMeta, type HiveMessage, type HiveTask } from './
import { HookServer } from './hooks';
import { MemoryManager } from './memory';
import { enrichMessage } from './assistant';
-import { readAgentUsage } from './transcript';
+import { readAgentUsage, readContextTokens } from './transcript';
import { listIssues, listCIRuns } from './github';
import { SlackWebhookServer } from './slack';
@@ -505,6 +505,14 @@ ipcMain.handle('app:resetAll', () => {
// ─── IPC: token telemetry (real usage + est. cost from CC transcripts) ───────
ipcMain.handle('hive:agentUsage', (_evt, cwd: unknown) =>
typeof cwd === 'string' ? readAgentUsage(cwd) : null);
+// Current context size (tokens) of an agent's LIVE session — the transcript
+// path is learned from the agent's hook payloads, so this works even when
+// several agents share one cwd. Null until the first hook fires.
+ipcMain.handle('hive:agentContext', (_evt, agentId: unknown) => {
+ if (typeof agentId !== 'string') return null;
+ const tp = hookServer.transcriptPath(agentId);
+ return tp ? readContextTokens(tp) : null;
+});
// ─── IPC: scheduled missions (recurring auto-dispatch) ──────────────────────
ipcMain.handle('missions:list', () => readConfig().missions ?? []);
diff --git a/src/main/transcript.ts b/src/main/transcript.ts
index 3dcccdc8..0c729ba6 100644
--- a/src/main/transcript.ts
+++ b/src/main/transcript.ts
@@ -1,4 +1,4 @@
-import { existsSync, readdirSync, readFileSync } from 'node:fs';
+import { closeSync, existsSync, fstatSync, openSync, readSync, readdirSync, readFileSync } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
@@ -76,3 +76,48 @@ export function readAgentUsage(cwd: string): AgentUsage {
function num(v: unknown): number {
return typeof v === 'number' && Number.isFinite(v) ? v : 0;
}
+
+/** Current context size (tokens) of a live session: the token accounting of the
+ * LAST assistant message in its transcript — input + cache read/write is what
+ * the model just consumed as context, plus its output which joins the context
+ * for the next turn. Tail-reads the file (transcripts grow to many MB), so a
+ * poll stays cheap. Returns null when the transcript is missing/unreadable or
+ * holds no assistant message yet. */
+const CONTEXT_TAIL_BYTES = 256 * 1024;
+
+export function readContextTokens(transcriptPath: string): number | null {
+ try {
+ if (!existsSync(transcriptPath)) return null;
+ const fd = openSync(transcriptPath, 'r');
+ try {
+ const size = fstatSync(fd).size;
+ const len = Math.min(size, CONTEXT_TAIL_BYTES);
+ if (len === 0) return null;
+ const buf = Buffer.alloc(len);
+ readSync(fd, buf, 0, len, size - len);
+ const lines = buf.toString('utf8').split('\n');
+ // Scan from the end; the very first chunk line may be cut mid-record and
+ // simply fails to parse, which is fine.
+ for (let i = lines.length - 1; i >= 0; i--) {
+ const trimmed = lines[i].trim();
+ if (!trimmed) continue;
+ let rec: { type?: unknown; message?: { usage?: Record<string, unknown> } };
+ try {
+ rec = JSON.parse(trimmed);
+ } catch {
+ continue;
+ }
+ if (rec.type !== 'assistant') continue;
+ const u = rec.message?.usage;
+ if (!u) continue;
+ return num(u.input_tokens) + num(u.output_tokens)
+ + num(u.cache_creation_input_tokens) + num(u.cache_read_input_tokens);
+ }
+ return null;
+ } finally {
+ closeSync(fd);
+ }
+ } catch {
+ return null;
+ }
+}
diff --git a/src/preload/index.ts b/src/preload/index.ts
index fd78f405..2ed73d55 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -281,6 +281,11 @@ const api = {
* Claude Code transcripts. Returns null for an invalid cwd. */
agentUsage: (cwd: string): Promise<AgentUsage | null> =>
ipcRenderer.invoke('hive:agentUsage', cwd),
+ /** Current context size (tokens) of an agent's live session, read from the
+ * last assistant message of its transcript. Null until the agent's hooks
+ * have fired at least once (the transcript path is learned from them). */
+ agentContext: (agentId: string): Promise<number | null> =>
+ ipcRenderer.invoke('hive:agentContext', agentId),
// ─── Task kanban (hive/tasks.json) ───────────────────────────────────────
/** Overwrite the hive task ledger with the full task list and commit it. */
diff --git a/src/renderer/src/components/AgentCard.tsx b/src/renderer/src/components/AgentCard.tsx
index 7721f4be..bb6addeb 100644
--- a/src/renderer/src/components/AgentCard.tsx
+++ b/src/renderer/src/components/AgentCard.tsx
@@ -11,7 +11,12 @@ export interface AgentCardProps {
status: StatusKind;
project: string;
action?: string;
- progress?: number; // 0..8 segments filled
+ /** Context gauge: 0..8 segments filled (session context ÷ context limit). */
+ progress?: number;
+ /** Live context size (tokens) — shown in the gauge tooltip. */
+ contextTokens?: number;
+ /** Context-window limit (tokens) assumed for the agent's model. */
+ contextLimit?: number;
selected?: boolean;
/** The orchestrator — gets a persistent accent frame + GOD tag so it stands out. */
isGod?: boolean;
@@ -20,8 +25,11 @@ export interface AgentCardProps {
onClick?: () => void;
}
+const fmtK = (n: number): string => `${Math.round(n / 1000)}k`;
+
export function AgentCard({
- name, character, accent, status, project, action, progress = 0, selected, isGod, onClick
+ name, character, accent, status, project, action, progress = 0,
+ contextTokens, contextLimit, selected, isGod, onClick
}: AgentCardProps) {
// The god is always framed (stands out from the row); others only when selected.
const framed = isGod || selected;
@@ -92,12 +100,20 @@ export function AgentCard({
}}>{/* The "idle" badge already conveys idle — don't echo "awaiting". */
(status === 'idle' ? '' : action) || ' '}</div>
- <div style={{ display: 'flex', gap: 2, marginTop: 2 }}>
+ {/* Context gauge: how full the session's context window is. Accent
+ while comfortable, lemon from 6/8 (~75%), coral from 7/8 —
+ "compaction imminent". */}
+ <div
+ style={{ display: 'flex', gap: 2, marginTop: 2 }}
+ title={contextTokens !== undefined && contextLimit
+ ? `Context: ${fmtK(contextTokens)} / ${fmtK(contextLimit)} tokens (${Math.round((contextTokens / contextLimit) * 100)}%)`
+ : 'Context gauge — fills once the agent reports activity'}
+ >
{Array.from({ length: 8 }).map((_, i) => (
<div key={i} style={{
width: 14, height: 6,
background: i < progress
- ? `var(--cth-${accent})`
+ ? (progress >= 7 ? 'var(--cth-coral)' : progress >= 6 ? 'var(--cth-lemon)' : `var(--cth-${accent})`)
: 'var(--cth-cream-200)',
boxShadow: 'inset 0 0 0 1px var(--cth-ink-900)'
}}/>
diff --git a/src/renderer/src/components/AgentStrip.tsx b/src/renderer/src/components/AgentStrip.tsx
index 6f50d7ee..eef8645c 100644
--- a/src/renderer/src/components/AgentStrip.tsx
+++ b/src/renderer/src/components/AgentStrip.tsx
@@ -32,6 +32,8 @@ export function AgentStrip() {
project={a.project}
action={a.action}
progress={a.progress}
+ contextTokens={a.contextTokens}
+ contextLimit={a.contextLimit}
selected={a.id === selectedId}
isGod={a.isGod}
isAssistant={a.isAssistant}
diff --git a/src/renderer/src/hooks/useHive.ts b/src/renderer/src/hooks/useHive.ts
index 56ac33b7..66e40731 100644
--- a/src/renderer/src/hooks/useHive.ts
+++ b/src/renderer/src/hooks/useHive.ts
@@ -265,6 +265,30 @@ export function useHive(config: HarnessConfig | null): void {
});
}, []);
+ // 2b) Context gauge: poll each live agent's current context size (tokens)
+ // from its session transcript and map it onto the agent card's 8-segment
+ // bar — a fuel gauge for how close the session is to its context limit.
+ useEffect(() => {
+ if (!config?.onboardingComplete) return;
+ const poll = async () => {
+ const { agents, updateAgent } = useStore.getState();
+ for (const a of agents) {
+ if (!a.ptyId) continue;
+ try {
+ const ctx = await window.cth.agentContext(a.id);
+ if (ctx === null) continue;
+ // 1M-context models advertise it in the model id (e.g. "[1m]").
+ const limit = /1m/i.test(a.model ?? '') ? 1_000_000 : 200_000;
+ const progress = Math.max(0, Math.min(8, Math.round((ctx / limit) * 8)));
+ updateAgent(a.id, { contextTokens: ctx, contextLimit: limit, progress });
+ } catch { /* ignore — try again next tick */ }
+ }
+ };
+ const t = setTimeout(poll, 3000); // first fill shortly after boot
+ const iv = setInterval(poll, 15000);
+ return () => { clearTimeout(t); clearInterval(iv); };
+ }, [config?.onboardingComplete]);
+
// 3) Wake idle agents holding unread inbox messages. The assistant is
// send-only (it never receives inbox mail), so it's excluded.
useEffect(() => {
diff --git a/src/renderer/src/hooks/usePtyParser.ts b/src/renderer/src/hooks/usePtyParser.ts
index 93d18028..a3b4a1f6 100644
--- a/src/renderer/src/hooks/usePtyParser.ts
+++ b/src/renderer/src/hooks/usePtyParser.ts
@@ -99,13 +99,14 @@ export function usePtyParser(agentId: string) {
const station = TOOL_TO_STATION[lastTool] ?? 'desk';
const carrying = TOOLKIND_BY_NAME[lastTool] ?? undefined;
const summary = lastArg ? `${lastTool.toLowerCase()} ${lastArg}` : lastTool.toLowerCase();
+ // NOTE: `progress` deliberately untouched — it's the context gauge now
+ // (filled by the useHive context poll), not a per-task meter.
updateAgent(agentId, {
status: 'working',
action: summary,
description: summary,
currentStation: station,
- carrying,
- progress: 0 // we can grow this with a counter later
+ carrying
});
// Mirror into the in-app feed so the mock terminal view shows it too if
// ever toggled — harmless for real ptys.
diff --git a/src/renderer/src/store/store.ts b/src/renderer/src/store/store.ts
index 4c14f9ff..3e53c561 100644
--- a/src/renderer/src/store/store.ts
+++ b/src/renderer/src/store/store.ts
@@ -64,6 +64,11 @@ export interface Agent {
/** When git isolation is enabled, the dedicated worktree path the agent runs
* in (its own `agent/<id>` branch); undefined for shared-cwd agents. */
worktreePath?: string;
+ /** Live context size of the agent's Claude session (tokens), polled from its
+ * transcript. Drives the context gauge on the agent card. */
+ contextTokens?: number;
+ /** The context-window limit assumed for this agent's model (tokens). */
+ contextLimit?: number;
/** True once this agent's terminal was closed. Archived agents are retained
* (in the store's `archivedAgents` list + the hive registry) but flagged and
* kept off the floor; only live-PTY agents are 'active'. */