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

fix: reset usage when a PTY exits

Aaron Coville2b96d5d007e3
diff --git a/src/main/index.ts b/src/main/index.ts
index 5944af45..01496d2e 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -448,6 +448,8 @@ function teardownPty(id: string): void {
try { workerWake.forget(agentId, id); } catch { /* best-effort */ }
// Drop breaker state so a dead agent can't leak/zombie a tripped level.
try { breaker.forget(agentId); } catch { /* best-effort */ }
+ // A replacement using this id needs a new usage counter, not the dead PTY's.
+ try { telemetry.forgetAgent(agentId); } catch { /* best-effort */ }
// W1 — kill this agent's proxy-bridge sidecar (qwen), if any, so a dead
// PTY never leaves an orphan loopback listener. No-op for non-proxy agents.
try { hive.stopProxyBridge(agentId); } catch (e) { console.error('[hive] stopProxyBridge failed:', e); }
diff --git a/src/main/telemetry.ts b/src/main/telemetry.ts
index d0c0928e..29dee3a2 100644
--- a/src/main/telemetry.ts
+++ b/src/main/telemetry.ts
@@ -206,6 +206,25 @@ export class TelemetryCollector {
return () => this.apiErrorSubs.delete(cb);
}
+ /** Drop an agent's live usage so a respawn starts with a fresh counter.
+ * Clears the in-memory accumulation only — the on-disk cost ledger and the
+ * transcript fallback are untouched, so lifetime spending still reports. The
+ * span ring goes too: it is keyed by agent id, so a replacement would
+ * otherwise inherit the dead agent's tool waterfall.
+ *
+ * Known edge: metrics are delivered asynchronously, so a batch already in
+ * flight when the PTY dies can land after this call and recreate the dead
+ * session's entries. The window is milliseconds and the next teardown
+ * clears it, so it is left unguarded rather than carrying a tombstone. */
+ forgetAgent(agentId: string): void {
+ const sessionIds = this.agentSessions.get(agentId);
+ if (sessionIds) {
+ for (const sessionId of sessionIds) this.sessions.delete(sessionId);
+ }
+ this.agentSessions.delete(agentId);
+ this.spans.delete(agentId);
+ }
+
/** Recent tool spans for the per-agent waterfall (#7B.2), oldest→newest. */
getSpans(agentId: string): ToolSpan[] {
return this.spans.get(agentId)?.slice() ?? [];
diff --git a/test/telemetry-forget-agent.test.cjs b/test/telemetry-forget-agent.test.cjs
new file mode 100644
index 00000000..fdea3cb3
--- /dev/null
+++ b/test/telemetry-forget-agent.test.cjs
@@ -0,0 +1,108 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const loadTs = require('./load-ts.cjs');
+
+const { TelemetryCollector } = loadTs('src/main/telemetry.ts');
+
+function tokenBatch(agentId, sessionId, output) {
+ return {
+ resourceMetrics: [{
+ resource: { attributes: [{ key: 'agent.id', value: { stringValue: agentId } }] },
+ scopeMetrics: [{
+ metrics: [{
+ name: 'claude_code.token.usage',
+ sum: {
+ dataPoints: [{
+ asInt: String(output),
+ attributes: [
+ { key: 'session.id', value: { stringValue: sessionId } },
+ { key: 'type', value: { stringValue: 'output' } },
+ { key: 'model', value: { stringValue: 'claude-sonnet-5' } }
+ ]
+ }]
+ }
+ }]
+ }]
+ }]
+ };
+}
+
+async function postMetrics(endpoint, body) {
+ const response = await fetch(`${endpoint}/v1/metrics`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(body)
+ });
+ assert.equal(response.status, 200);
+ await response.text();
+}
+
+test('forgetAgent resets usage before the same agent id is respawned', async (t) => {
+ const telemetry = new TelemetryCollector({ host: '127.0.0.1', port: 0 });
+ await telemetry.start();
+ t.after(() => telemetry.stop());
+ const endpoint = telemetry.endpoint();
+
+ await postMetrics(endpoint, tokenBatch('agent-1', 'dead-session', 900));
+ assert.equal(telemetry.getAgentUsage('agent-1').output, 900);
+
+ telemetry.forgetAgent('agent-1');
+
+ await postMetrics(endpoint, tokenBatch('agent-1', 'respawn-session', 10));
+ assert.equal(telemetry.getAgentUsage('agent-1').output, 10);
+});
+
+test('forgetAgent drops the dead session so its total cannot resurrect', async (t) => {
+ const telemetry = new TelemetryCollector({ host: '127.0.0.1', port: 0 });
+ await telemetry.start();
+ t.after(() => telemetry.stop());
+ const endpoint = telemetry.endpoint();
+
+ await postMetrics(endpoint, tokenBatch('agent-1', 'dead-session', 900));
+ assert.equal(telemetry.getAgentUsage('agent-1').output, 900);
+
+ telemetry.forgetAgent('agent-1');
+
+ // A late or duplicate sample for the SAME session id must accumulate from
+ // zero, not re-attach the forgotten 900. Deleting only agentSessions and
+ // leaving the sessions entry behind would let the dead total resurrect the
+ // moment any further metric arrives for that session — reinstating the very
+ // inherited usage this reset exists to clear.
+ await postMetrics(endpoint, tokenBatch('agent-1', 'dead-session', 10));
+ assert.equal(telemetry.getAgentUsage('agent-1').output, 10);
+});
+
+test('forgetAgent keeps usage for other agents', async (t) => {
+ const telemetry = new TelemetryCollector({ host: '127.0.0.1', port: 0 });
+ await telemetry.start();
+ t.after(() => telemetry.stop());
+ const endpoint = telemetry.endpoint();
+
+ await postMetrics(endpoint, tokenBatch('agent-1', 'session-1', 500));
+ await postMetrics(endpoint, tokenBatch('agent-2', 'session-2', 700));
+
+ telemetry.forgetAgent('agent-1');
+
+ assert.equal(telemetry.getAgentUsage('agent-1'), null);
+ assert.equal(telemetry.getAgentUsage('agent-2').output, 700);
+});
+
+test('teardown resets telemetry when it forgets breaker state', () => {
+ const indexPath = require('node:path').join(__dirname, '..', 'src', 'main', 'index.ts');
+ const rawSource = require('node:fs').readFileSync(indexPath, 'utf8');
+ const activeSource = rawSource
+ .replace(/\/\*[\s\S]*?\*\//g, '')
+ .split('\n')
+ .map((line) => line.replace(/\/\/.*$/, ''))
+ .join('\n');
+ // Bounded to the teardown block: an unbounded slice would also match the call
+ // if it were moved into any later function in the file.
+ const start = activeSource.indexOf('breaker.forget(agentId)');
+ const end = activeSource.indexOf('hive.stopProxyBridge(agentId)', start);
+ assert.ok(start !== -1 && end > start, 'teardown block not found in index.ts');
+ const afterBreakerReset = activeSource.slice(start, end);
+
+ assert.match(afterBreakerReset, /telemetry\.forgetAgent\(agentId\)/);
+});