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: statusLine-driven context gauge - fresh-session reset, real limits, no probe

Gulum84e3d6ece991
diff --git a/src/main/hive.ts b/src/main/hive.ts
index 0cc287e8..f06ade4e 100644
--- a/src/main/hive.ts
+++ b/src/main/hive.ts
@@ -373,6 +373,12 @@ export class HiveManager {
hooks: [{ type: 'command', command: cmd }]
});
return {
+ // The status line gets the session status JSON after every response —
+ // including context_window.{total_input_tokens,context_window_size},
+ // the only clean programmatic source for the session's REAL context
+ // window. The shim prints a compact in-terminal gauge and forwards the
+ // payload to the harness (agent-card context gauge, exact limit).
+ statusLine: { type: 'command', command: `${cmd} --status`, padding: 0 },
hooks: {
Stop: [entry()],
SubagentStop: [entry()],
@@ -858,6 +864,7 @@ write there become searchable by every agent. You don't run \`mine\` yourself.
const HOOK_SHIM = `#!/usr/bin/env node
'use strict';
const net = require('net');
+const isStatus = process.argv.includes('--status');
let data = '';
process.stdin.setEncoding('utf8');
process.stdin.on('data', (d) => { data += d; });
@@ -866,6 +873,31 @@ process.stdin.on('end', () => {
try { payload = JSON.parse(data || '{}'); } catch (_) {}
if (!payload.agent_id) payload.agent_id = process.env.AGENT_ID || null;
const sock = process.env.HIVE_SOCK;
+ if (isStatus) {
+ // Status-line mode: Claude Code pipes the session status JSON (incl.
+ // context_window.total_input_tokens / .context_window_size) after every
+ // response. Print the in-terminal gauge IMMEDIATELY (the TUI is waiting),
+ // then forward the payload to the harness fire-and-forget so the agent
+ // card's context gauge updates push-based, with the EXACT window size.
+ payload.hook_event_name = 'Status';
+ const cw = payload.context_window || {};
+ const used = cw.total_input_tokens, size = cw.context_window_size;
+ if (typeof used === 'number' && typeof size === 'number' && size > 0) {
+ const pct = Math.round((used / size) * 100);
+ process.stdout.write('ctx ' + Math.round(used / 1000) + 'k/' + Math.round(size / 1000) + 'k (' + pct + '%)');
+ }
+ if (sock) {
+ try {
+ const c = net.createConnection(sock, () => { c.end(JSON.stringify(payload) + '\\n'); });
+ c.on('error', () => {});
+ c.on('close', () => process.exit(0));
+ } catch (_) { process.exit(0); }
+ } else {
+ process.exit(0);
+ }
+ setTimeout(() => process.exit(0), 1500).unref();
+ return;
+ }
if (!sock) { process.exit(0); }
let resp = '';
const done = (code) => { if (resp) process.stdout.write(resp); process.exit(code); };
diff --git a/src/main/hooks.ts b/src/main/hooks.ts
index ab47a497..fbac95ad 100644
--- a/src/main/hooks.ts
+++ b/src/main/hooks.ts
@@ -24,6 +24,8 @@ interface HookPayload {
agent_id?: string | null;
session_id?: string;
transcript_path?: string;
+ /** Status-line payloads only: the session's live context accounting. */
+ context_window?: { total_input_tokens?: number; context_window_size?: number };
cwd?: string;
tool_name?: string;
tool_input?: unknown;
@@ -97,6 +99,25 @@ export class HookServer {
this.transcriptPaths.set(agentId, p.transcript_path);
}
+ // Status-line payloads carry the session's EXACT context accounting —
+ // current tokens AND the real window size (200k vs 1M, which nothing else
+ // exposes). Forward to the renderer for the agent-card context gauge.
+ // Handled FIRST and returned early: this is pure telemetry from the
+ // statusLine shim, not a real hook boundary — it must never trip the
+ // HALT gate or feed the breaker's loop detector below.
+ if (event === 'Status') {
+ const cw = p.context_window;
+ if (agentId && cw && typeof cw.total_input_tokens === 'number'
+ && typeof cw.context_window_size === 'number' && cw.context_window_size > 0) {
+ this.getWebContents()?.send('hive:contextUpdate', {
+ agentId,
+ tokens: cw.total_input_tokens,
+ limit: cw.context_window_size
+ });
+ }
+ return {};
+ }
+
// 7C.3 — a graceful operator HALT overrides everything (incl. the inbox
// drain below): stop the agent CLEANLY at this hook boundary rather than
// killing the PTY. session_id is in the payload for a later --resume.
diff --git a/src/main/index.ts b/src/main/index.ts
index 7829477b..7fdc1bbb 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1024,12 +1024,15 @@ ipcMain.handle('app:resetAll', () => {
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.
+// path is learned from the agent's hook payloads (SessionStart fires right at
+// spawn), so this works even when several agents share one cwd. Null until the
+// first hook fires; a known-but-empty transcript reads as 0 so a freshly
+// (re)started session zeroes the gauge instead of leaving a stale value up.
ipcMain.handle('hive:agentContext', (_evt, agentId: unknown) => {
if (typeof agentId !== 'string') return null;
const tp = hookServer.transcriptPath(agentId);
- return tp ? readContextTokens(tp) : null;
+ if (!tp) return null;
+ return readContextTokens(tp) ?? 0;
});
// ─── IPC: live telemetry (the OTel collector — the locked usage-provider seam) ─
diff --git a/src/preload/index.ts b/src/preload/index.ts
index d44d7060..2c77dc87 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -373,6 +373,15 @@ const api = {
ipcRenderer.on('hive:hookEvent', listener);
return () => ipcRenderer.removeListener('hive:hookEvent', listener);
},
+ /** Push-based context accounting from the status line: live tokens + the
+ * session's EXACT context-window size. Same pattern as onHiveHookEvent. */
+ onHiveContextUpdate: (
+ cb: (e: { agentId: string; tokens: number; limit: number }) => void
+ ): (() => void) => {
+ const listener = (_e: IpcRendererEvent, payload: { agentId: string; tokens: number; limit: number }) => cb(payload);
+ ipcRenderer.on('hive:contextUpdate', listener);
+ return () => ipcRenderer.removeListener('hive:contextUpdate', listener);
+ },
onHiveMessage: (cb: (e: HiveRouteEvent) => void): (() => void) => {
const listener = (_e: IpcRendererEvent, payload: HiveRouteEvent) => cb(payload);
ipcRenderer.on('hive:message', listener);
diff --git a/src/renderer/src/hooks/useHive.ts b/src/renderer/src/hooks/useHive.ts
index e2bcf6fe..f12db5af 100644
--- a/src/renderer/src/hooks/useHive.ts
+++ b/src/renderer/src/hooks/useHive.ts
@@ -349,22 +349,26 @@ export function useHive(config: HarnessConfig | null): void {
});
}, []);
- // 2c) Context gauge (#11/#12): 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 limit.
+ // 2c) Context gauge backfill: poll each live agent's current context size
+ // (tokens) from its session transcript — only until the status line
+ // (effect 2d) has delivered exact numbers for that agent.
useEffect(() => {
if (!config?.onboardingComplete) return;
const poll = async () => {
const { agents, updateAgent } = useStore.getState();
for (const a of agents) {
if (!a.ptyId) continue;
+ // The status line pushes exact numbers after every response (effect
+ // 2d) — this transcript poll only backfills agents whose status line
+ // hasn't fired yet (e.g. freshly restored, no response so far).
+ if (a.contextLimit !== undefined) 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 hinted = /1m/i.test(a.model ?? '') ? 1_000_000 : 200_000;
+ const limit = Math.max(hinted, ctx > 200_000 ? 1_000_000 : 0);
const progress = Math.max(0, Math.min(8, Math.round((ctx / limit) * 8)));
- updateAgent(a.id, { contextTokens: ctx, contextLimit: limit, progress });
+ updateAgent(a.id, { contextTokens: ctx, progress });
} catch { /* ignore — try again next tick */ }
}
};
@@ -373,6 +377,16 @@ export function useHive(config: HarnessConfig | null): void {
return () => { clearTimeout(t); clearInterval(iv); };
}, [config?.onboardingComplete]);
+ // 2d) Push-based context gauge: the status-line shim forwards the session's
+ // EXACT context accounting (tokens + real window size) after every
+ // response — no probing, no transcript guesswork.
+ useEffect(() => {
+ return window.cth.onHiveContextUpdate(({ agentId, tokens, limit }) => {
+ const progress = Math.max(0, Math.min(8, Math.round((tokens / limit) * 8)));
+ useStore.getState().updateAgent(agentId, { contextTokens: tokens, contextLimit: limit, progress });
+ });
+ }, []);
+
// 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 a3b4a1f6..9c2dd45e 100644
--- a/src/renderer/src/hooks/usePtyParser.ts
+++ b/src/renderer/src/hooks/usePtyParser.ts
@@ -36,6 +36,12 @@ const BLOCK_HINTS = [
/\[y\/n\]/i,
];
+// The /context output prints "235.3k/1m tokens (24%)" — sniff the DENOMINATOR
+// to learn the session's true context-window size. This is the only reliable
+// source for sessions on the CLI-default model: the "[1m]" alias exists only
+// inside Claude Code; the API model id in the transcript is plain.
+const CONTEXT_LIMIT_RE = /[\d.,]+k\s*\/\s*([\d.]+)([km])\s+tokens/i;
+
/**
* Subscribe to a pty stream and update the agent's avatar state based on what
* scrolls past. This is a stopgap until we wire real Claude Code hooks — it
@@ -83,6 +89,20 @@ export function usePtyParser(agentId: string) {
const text = chunk.replace(ANSI_RE, '');
if (!text.trim()) return;
+ // Passive context-limit sniffing from /context output (the gauge poll
+ // sends one probe per session; a manual /context works too). The limit
+ // only ever ratchets up — contextLimit is volatile across respawns.
+ const lim = CONTEXT_LIMIT_RE.exec(text);
+ if (lim) {
+ const value = parseFloat(lim[1]) * (lim[2].toLowerCase() === 'm' ? 1_000_000 : 1_000);
+ if (value >= 100_000) {
+ const agent = useStore.getState().agents.find((a) => a.id === agentId);
+ if (agent && value > (agent.contextLimit ?? 0)) {
+ updateAgent(agentId, { contextLimit: value });
+ }
+ }
+ }
+
// The "esc to interrupt" footer is only shown while a turn is in progress.
const running = /esc to interrupt/i.test(text);
diff --git a/src/renderer/src/store/store.ts b/src/renderer/src/store/store.ts
index 4ff3d51e..17cd2575 100644
--- a/src/renderer/src/store/store.ts
+++ b/src/renderer/src/store/store.ts
@@ -178,12 +178,14 @@ const LS_QUEUES = 'cth.messageQueues';
const LS_ENRICH = 'cth.enrichEnabled';
// Fields that are large or transient — not worth persisting across reloads.
-type PersistedAgent = Omit<Agent, 'recentAssistantText' | 'recentTextTs' | 'blockReason'>;
+// contextTokens/contextLimit describe a LIVE session; persisting them showed a
+// dead session's context gauge after a restart until the poll caught up.
+type PersistedAgent = Omit<Agent, 'recentAssistantText' | 'recentTextTs' | 'blockReason' | 'contextTokens' | 'contextLimit'>;
function persistAgents(agents: Agent[], selectedId: string | null): void {
try {
- const slim: PersistedAgent[] = agents.map(({ recentAssistantText, recentTextTs, blockReason, ...rest }) => {
- void recentAssistantText; void recentTextTs; void blockReason;
+ const slim: PersistedAgent[] = agents.map(({ recentAssistantText, recentTextTs, blockReason, contextTokens, contextLimit, ...rest }) => {
+ void recentAssistantText; void recentTextTs; void blockReason; void contextTokens; void contextLimit;
return rest;
});
window.localStorage.setItem(LS_AGENTS, JSON.stringify(slim));
@@ -200,6 +202,7 @@ function loadPersistedAgents(): Agent[] {
// Reset volatile run-state; the PTY stream / mock loop will repopulate it.
return parsed.map((a) => ({
...a,
+ progress: 0,
status: 'idle',
action: 'reconnecting…',
currentStation: 'desk',
@@ -213,8 +216,8 @@ function loadPersistedAgents(): Agent[] {
function persistArchived(archived: Agent[]): void {
try {
- const slim: PersistedAgent[] = archived.map(({ recentAssistantText, recentTextTs, blockReason, ...rest }) => {
- void recentAssistantText; void recentTextTs; void blockReason;
+ const slim: PersistedAgent[] = archived.map(({ recentAssistantText, recentTextTs, blockReason, contextTokens, contextLimit, ...rest }) => {
+ void recentAssistantText; void recentTextTs; void blockReason; void contextTokens; void contextLimit;
return rest;
});
window.localStorage.setItem(LS_ARCHIVED, JSON.stringify(slim));