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(telemetry): count human-sent messages, closing the activation funnel

chaitanyagiric1756662ba31
diff --git a/TELEMETRY.md b/TELEMETRY.md
index 25b72d9a..2a576800 100644
--- a/TELEMETRY.md
+++ b/TELEMETRY.md
@@ -32,9 +32,34 @@ The events:
| `agent_spawn_failed` | `provider`; `reason` is one of `cli_missing`, `cwd_missing`, `already_running`, `spawn_error` | A requested spawn did not start an agent |
| `agent_install_started` | `provider`; `rung` is one of `npm`, `node-then-npm`, `native` | The engine CLI was missing, so the bundled auto-installer began |
| `agent_install_finished` | `provider`; `rung` as above; `outcome` is one of `agent_launched`, `install_failed` | The auto-installer exited |
+| `message_sent` | `surface` — one of `terminal`, `composer`, `steer`, `hive` | Each time **you** send a message to an agent. A count of messages and nothing else: the message itself is never read, measured, or hashed |
| `feature_used` | `feature` — one of `slack_trigger`, `webhook_trigger`, `hire_install`, `voice_dictation` | At most once per feature per app session |
| `session_ended` | `duration_bucket` — one of `<5m`, `5-30m`, `30m-2h`, `2-8h`, `8h+` | On quit (coarse bucket, never raw duration) |
+### About `message_sent`
+
+This is the one event that fires while you work, so it is worth being precise
+about what it does and does not do.
+
+- It counts **one event per message you send**, at the moment you send it. It is
+ counted at the *submit* — the Enter or the Send button — never per keystroke.
+ The app does not report what you type as you type it.
+- `surface` says only *where* you sent it from: `terminal` (typed into an
+ agent's terminal), `composer` (the agent's message queue box), `steer` (the
+ steer field on the agent control strip), or `hive` (a dispatch, thread reply,
+ or ASK ME answer).
+- Messages **agents send each other** are not counted. Only messages that came
+ from a person are.
+- No property carries the message. There is no text, no length, no character
+ count, no first-N-characters, and no hash of the body — the event has exactly
+ one property and it is the surface name above. The channel the app uses to
+ report it does not accept a message argument at all, so there is no shape in
+ which the content could be sent by mistake.
+
+It exists to answer one question: after someone gets an agent running, do they
+ever actually talk to it? Without it, an agent that was started and then ignored
+is indistinguishable from one being used every day.
+
## What is never sent
No prompts. No agent transcripts or output. No file paths, repo names, branch
diff --git a/src/main/analytics.ts b/src/main/analytics.ts
index a6f75947..1c7d501d 100644
--- a/src/main/analytics.ts
+++ b/src/main/analytics.ts
@@ -81,6 +81,11 @@ const EVENTS: Record<string, ReadonlySet<string>> = {
* `install_failed` (non-zero exit — e.g. an installer that cannot complete
* unattended). This is the signal that a first agent never actually started. */
agent_install_finished: new Set<string>(['provider', 'rung', 'outcome']),
+ /** ── The end of the activation funnel (v0.4.7): a HUMAN sent a message to an
+ * agent. Counted at the SUBMIT boundary, never per keystroke — see
+ * MESSAGE_SURFACES for the four places a person can send one. Carries a COUNT
+ * and nothing else: no text, no length, no hash. `surface` is a closed enum. */
+ message_sent: new Set<string>(['surface']),
/** Coarse feature adoption; `feature` is a fixed enum (see FEATURES), fired
* at most once per feature per app session. */
feature_used: new Set<string>(['feature']),
@@ -107,6 +112,39 @@ export type InstallRung = 'npm' | 'node-then-npm' | 'native';
/** The only values `agent_install_finished.outcome` may take. */
export type InstallOutcome = 'agent_launched' | 'install_failed';
+/** The only values `message_sent.surface` may take — the four places a HUMAN can
+ * send a message to an agent:
+ *
+ * - `terminal` — typed straight into the agent's terminal and submitted with
+ * Enter (terminalPool's submit boundary, NOT `pty:write`, which fires on
+ * every keystroke and would count typing, not messages).
+ * - `composer` — the per-agent message queue composer.
+ * - `steer` — the steer box on the agent control strip.
+ * - `hive` — a hive message sent by the human (Command Center dispatch,
+ * a thread reply, an ASK ME answer). Agent-to-agent hive traffic is NOT
+ * counted: `hive:send` carries a `from` and only `'human'` qualifies.
+ *
+ * Closed enum, same rule as every other property here. */
+export const MESSAGE_SURFACES = ['terminal', 'composer', 'steer', 'hive'] as const;
+export type MessageSurface = typeof MESSAGE_SURFACES[number];
+
+/** The subset of MESSAGE_SURFACES the RENDERER is allowed to name over IPC.
+ *
+ * `steer` and `hive` are counted in main, at the IPC handlers that already
+ * receive them, so the renderer must not be able to name those two — otherwise
+ * a future renderer call site could double-count a message main has already
+ * counted. `terminal` and `composer` are the only submits main cannot see for
+ * itself, so they are the only ones that cross the bridge. */
+const RENDERER_MESSAGE_SURFACES: ReadonlySet<string> = new Set<string>(['terminal', 'composer']);
+
+/** Validate a surface arriving from the renderer. Everything crossing that seam
+ * is untrusted input, and `track()`'s allowlist filters property KEYS but not
+ * property VALUES — so without this an unrecognised string would ride along as
+ * a free-form value, exactly what TELEMETRY.md promises never happens. */
+export function isRendererMessageSurface(v: unknown): v is MessageSurface {
+ return typeof v === 'string' && RENDERER_MESSAGE_SURFACES.has(v);
+}
+
export interface AnalyticsInitOptions {
/** Directory for the install-id file (userData). Created if missing. */
stateDir: string;
@@ -225,6 +263,14 @@ export class Analytics {
}
}
+ /** One human-sent message. NOT deduped — unlike trackFeature this IS a usage
+ * meter, and the count is the whole point. Re-checks the enum at runtime
+ * because the `terminal`/`composer` surfaces originate in the renderer. */
+ trackMessageSent(surface: MessageSurface): void {
+ if (!(MESSAGE_SURFACES as readonly string[]).includes(surface)) return;
+ this.track('message_sent', { surface });
+ }
+
/** feature_used with per-session dedup (adoption signal, not a usage meter). */
trackFeature(feature: AnalyticsFeature): void {
if (this.featuresSeen.has(feature)) return;
diff --git a/src/main/index.ts b/src/main/index.ts
index f0147e3c..0e33d8c9 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -55,7 +55,7 @@ import { initCompletionWatcher } from './realtimeCompletionWatcher';
import type { TaskCard, InboxMessage } from './realtimeCompletionWatcher';
import { TelemetryCollector } from './telemetry';
import { CostLedgerTotals } from './costLifetime';
-import { analytics } from './analytics';
+import { analytics, isRendererMessageSurface } from './analytics';
import type { SpawnFailReason } from './analytics';
import { IntegrationBroker } from './integrationBroker';
import * as integrations from './integrations';
@@ -2963,6 +2963,25 @@ ipcMain.handle('pty:kill', (_evt, id: string) => {
});
ipcMain.handle('pty:list', () => ptyManager.list());
+// ─── IPC: analytics (the ONE renderer-facing seam) ──────────────────────────
+/** Count one human-sent message (TELEMETRY.md → `message_sent`). A COUNT, and
+ * nothing else: this channel takes no text, no length and no id, so there is
+ * no shape in which message content could cross it.
+ *
+ * This is the only analytics event the renderer can cause. It exists because
+ * two of the four send surfaces — a line typed into the agent's terminal, and
+ * the queue composer — are submits main cannot observe: the `pty:write` handler
+ * above fires on EVERY KEYSTROKE, so counting there would produce a keystroke
+ * meter, not a message count. `steer` and `hive` are counted at their own IPC
+ * handlers in this file and are rejected here (isRendererMessageSurface) so
+ * they can never be counted twice. The event name is fixed here, not passed
+ * in: the renderer chooses a surface, never an event. */
+ipcMain.handle('analytics:messageSent', (_evt, surface: unknown) => {
+ if (!isRendererMessageSurface(surface)) return { ok: false };
+ analytics.trackMessageSent(surface);
+ return { ok: true };
+});
+
// Resolve a pasted Claude session id to the cwd it originally ran in, so the Add
// Agent dialog can auto-fill the folder for a resume (#2 zero-step resume). Reads
// the cwd from a transcript record; null when the id is invalid/unknown.
@@ -3391,7 +3410,13 @@ ipcMain.handle('hive:messages', (_evt, opts: unknown) =>
);
ipcMain.handle('hive:send', (_evt, partial: Partial<HiveMessage>, from: unknown) => {
if (!hive.enabled()) return { ok: false, error: 'hive disabled (no harnessHome)' };
- const msg = hive.send(partial ?? {}, typeof from === 'string' ? from : 'system');
+ const sender = typeof from === 'string' ? from : 'system';
+ const msg = hive.send(partial ?? {}, sender);
+ // Count only what a PERSON sent. Every renderer surface that dispatches on a
+ // human's behalf passes 'human' (Command Center dispatch, thread replies, ASK
+ // ME answers); agent-to-agent traffic passes the agent id and would swamp the
+ // number. Counted AFTER the send so a rejected message is never counted.
+ if (sender === 'human') analytics.trackMessageSent('hive');
return { ok: true, message: msg };
});
ipcMain.handle('hive:addTask', (_evt, task: unknown) => {
@@ -3861,6 +3886,10 @@ ipcMain.handle('control:gateTool', (_evt, agentId: unknown, tool: unknown, on: u
ipcMain.handle('control:steer', (_evt, agentId: unknown, text: unknown) => {
if (typeof agentId !== 'string' || typeof text !== 'string') return null;
control.steer(agentId, text);
+ // A steer typed into the control strip is a human message. Counted HERE, at
+ // the IPC seam, and deliberately not inside control.steer(): closingTime and
+ // the voice action layer call that directly, and neither is a person typing.
+ analytics.trackMessageSent('steer');
return control.snapshot(agentId);
});
ipcMain.handle('control:halt', (_evt, agentId: unknown) => {
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 1d2a21f6..2c7e63d2 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -565,6 +565,15 @@ export interface PreservedWorktreeSnapshot {
const api = {
version: __APP_VERSION__,
+ // ─── Analytics ───────────────────────────────────────────────────────────
+ /** Count ONE human-sent message (TELEMETRY.md → `message_sent`). Carries a
+ * surface name and nothing else — no text, no length, no agent id — and main
+ * accepts only 'terminal' and 'composer' here (steer and hive are counted in
+ * main, at their own handlers). Never awaited by callers and never allowed to
+ * throw: a telemetry hiccup must not break sending a message. */
+ trackMessageSent: (surface: 'terminal' | 'composer'): Promise<void> =>
+ ipcRenderer.invoke('analytics:messageSent', surface).then(() => undefined, () => undefined),
+
// ─── PTY ─────────────────────────────────────────────────────────────────
/** `cwd` in the result is the TILDE-EXPANDED absolute path main actually spawned
* into — the renderer stores that, not the raw `~/…` the user typed. */
diff --git a/src/renderer/src/components/MessageQueueComposer.tsx b/src/renderer/src/components/MessageQueueComposer.tsx
index fd5dfff8..9e69d85e 100644
--- a/src/renderer/src/components/MessageQueueComposer.tsx
+++ b/src/renderer/src/components/MessageQueueComposer.tsx
@@ -140,6 +140,12 @@ export function MessageQueueComposer({ agent }: MessageQueueComposerProps) {
: 'Attached files:\n') + attachments.map((a) => `- ${a.path} (${a.name})`).join('\n')
: text;
enqueueMessage(agent.id, body);
+ // Counted HERE, at the composer's submit, and NOT inside enqueueMessage:
+ // that store action is also how work orders, Slack inbound, nudges and
+ // compact commands reach an agent, and none of those is a person sending a
+ // message. Past the isComposingKey guard in onKey, so an IME candidate
+ // Enter never counts. (TELEMETRY.md → message_sent)
+ void window.cth.trackMessageSent('composer');
setText('');
setAttachments([]);
};
diff --git a/src/renderer/src/components/terminalPool.ts b/src/renderer/src/components/terminalPool.ts
index 28ec7727..2376e5a4 100644
--- a/src/renderer/src/components/terminalPool.ts
+++ b/src/renderer/src/components/terminalPool.ts
@@ -343,6 +343,14 @@ export function acquireTerminal(ptyId: string, theme?: ThemeMap, fontSize = 14):
// Bracketed paste is still user-owned draft text; remove only its wrapper so
// pasted content marks the prompt dirty instead of looking automation-safe.
const input = data.replace(/\x1b\[200~/g, '').replace(/\x1b\[201~/g, '');
+ // A PASTE is never a submit: the TUI drops its newlines into the input box
+ // and waits for a real Enter. xterm rewrites pasted newlines to "\r", so
+ // without this a five-line paste would look like five submitted messages —
+ // and the Enter that actually sends it would then be a sixth. (TELEMETRY.md
+ // → message_sent; the paste's own Enter keystroke arrives as its own chunk
+ // and is counted there.)
+ const pasted = data.includes('\x1b[200~');
+ let submitted = false;
for (let i = 0; i < input.length; i++) {
const ch = input[i];
if (ch === '\r' || ch === '\n') {
@@ -361,7 +369,10 @@ export function acquireTerminal(ptyId: string, theme?: ThemeMap, fontSize = 14):
entry.automationBlocked = true;
entry.automationBlockedAt = Date.now();
}
- if (t.length >= 2) entry.onPrompt?.(t);
+ if (t.length >= 2) {
+ entry.onPrompt?.(t);
+ submitted = true;
+ }
} else if (ch === '\x7f' || ch === '\b') {
entry.lineBuf = entry.lineBuf.slice(0, -1);
} else if (ch === '\x1b') {
@@ -370,6 +381,11 @@ export function acquireTerminal(ptyId: string, theme?: ThemeMap, fontSize = 14):
entry.lineBuf += ch;
}
}
+ // ONE message per input chunk, at the SUBMIT boundary — not per keystroke
+ // (that is what `pty:write` sees, and counting there would meter typing) and
+ // not per line inside a paste. This is the only place the renderer can cause
+ // an analytics event; it sends a surface name and nothing else.
+ if (submitted && !pasted) void window.cth.trackMessageSent('terminal');
entry.inputDirty = entry.lineBuf.length > 0;
// Re-stamped on every keystroke, so the staleness clock measures time since
// the user last touched the draft — not since they started it.
diff --git a/test/telemetry-message-count.test.cjs b/test/telemetry-message-count.test.cjs
new file mode 100644
index 00000000..b55f05b0
--- /dev/null
+++ b/test/telemetry-message-count.test.cjs
@@ -0,0 +1,286 @@
+'use strict';
+
+// message_sent (v0.4.7) — the end of the activation funnel: a COUNT of the
+// messages a HUMAN sends to an agent, and nothing else.
+//
+// Three things are asserted here, and the third is the one that matters most:
+//
+// 1. the event passes the analytics allowlist, enforces its closed `surface`
+// enum, stays anonymous, and is suppressed by every opt-out;
+// 2. the counter counts at the SUBMIT boundary, not per keystroke;
+// 3. the WIRING. A miscounted event is a wrong number, which someone notices.
+// A mis-WIRED one records zero forever while CI stays green, and reads as
+// "nobody talks to their agents" — the fails-open shape this repo has been
+// bitten by repeatedly. So the IPC channel name, the surface literals at
+// each call site, and the doc/code lockstep are all asserted against the
+// source text (index.ts imports electron and cannot load under plain node —
+// the same pattern the rest of the suite uses for main-process wiring).
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const loadTs = require('./load-ts.cjs');
+
+globalThis.__POSTHOG_KEY__ = 'test-key';
+globalThis.__POSTHOG_HOST__ = 'https://example.invalid';
+delete process.env.DO_NOT_TRACK;
+
+const captured = [];
+class FakePostHog {
+ capture(payload) { captured.push(payload); }
+ async shutdown() {}
+}
+const posthogPath = require.resolve('posthog-node');
+require.cache[posthogPath] = {
+ id: posthogPath, filename: posthogPath, loaded: true, exports: { PostHog: FakePostHog }
+};
+
+const { Analytics, MESSAGE_SURFACES, isRendererMessageSurface } = loadTs('src/main/analytics.ts');
+
+const read = (rel) => fs.readFileSync(path.resolve(__dirname, '..', rel), 'utf8');
+const main = read('src/main/index.ts');
+const preload = read('src/preload/index.ts');
+const telemetryDoc = read('TELEMETRY.md');
+
+function bootedAnalytics(opts = {}) {
+ const a = new Analytics();
+ a.init({
+ stateDir: fs.mkdtempSync(path.join(os.tmpdir(), 'md-msg-count-')),
+ appVersion: '0.4.7',
+ enabled: opts.enabled !== false
+ });
+ captured.length = 0; // drop first_run / app_launched from init
+ return a;
+}
+
+const messageEvents = () => captured.filter((c) => c.event === 'message_sent');
+
+// ── the event and its closed enum ────────────────────────────────────────────
+
+test('every surface in the enum is accepted and lands as the surface property', () => {
+ const a = bootedAnalytics();
+ for (const surface of MESSAGE_SURFACES) a.trackMessageSent(surface);
+ assert.deepEqual(messageEvents().map((c) => c.properties.surface), [...MESSAGE_SURFACES]);
+ assert.equal(messageEvents()[0].properties.app_version, '0.4.7');
+});
+
+test('a surface outside the enum sends nothing at all', () => {
+ const a = bootedAnalytics();
+ // Not "sends the event with the property dropped" — sends NOTHING. track()'s
+ // allowlist filters property KEYS, not VALUES, so a bad value would otherwise
+ // ride along as free-form text, which TELEMETRY.md promises never happens.
+ for (const junk of ['slack', '', 'TERMINAL', '/Users/someone/secret-repo', null, 42, {}]) {
+ a.trackMessageSent(junk);
+ }
+ assert.equal(messageEvents().length, 0);
+});
+
+test('the event carries a count and nothing else — no content in any shape', () => {
+ const a = bootedAnalytics();
+ // The one and only property is `surface`. Anything a future call site tried to
+ // smuggle alongside it — text, a length, a hash — is dropped by the allowlist.
+ a.track('message_sent', {
+ surface: 'composer',
+ text: 'deploy the thing to prod',
+ length: '24',
+ body_hash: 'ab12cd34',
+ agent_id: 'kevin-mt6kt4po'
+ });
+ const props = messageEvents()[0].properties;
+ assert.equal(props.surface, 'composer');
+ for (const k of ['text', 'length', 'body_hash', 'agent_id']) {
+ assert.equal(props[k], undefined, `${k} must never be sent`);
+ }
+ // …and the properties that DO survive are only the surface plus the common
+ // stamp every event already carries. This catches a new leak by exhaustion,
+ // not by naming it in advance.
+ assert.deepEqual(
+ Object.keys(props).sort(),
+ ['$ip', '$process_person_profile', 'app_version', 'arch', 'os', 'surface']
+ );
+});
+
+test('it is a meter, not an adoption flag: repeats are not deduped', () => {
+ // feature_used dedups per session on purpose; this one must not, or the count
+ // the founder asked for would flatten to "at least one message, ever".
+ const a = bootedAnalytics();
+ for (let i = 0; i < 5; i++) a.trackMessageSent('terminal');
+ assert.equal(messageEvents().length, 5);
+});
+
+test('the event stays anonymous by construction', () => {
+ const a = bootedAnalytics();
+ a.trackMessageSent('hive');
+ assert.equal(messageEvents()[0].properties.$process_person_profile, false);
+ assert.equal(messageEvents()[0].properties.$ip, null);
+});
+
+// ── every opt-out suppresses it, like every other event ──────────────────────
+
+test('the Settings opt-out suppresses it at boot', () => {
+ const a = bootedAnalytics({ enabled: false });
+ a.trackMessageSent('composer');
+ assert.equal(messageEvents().length, 0);
+});
+
+test('flipping the Settings switch off mid-session stops it instantly', () => {
+ const a = bootedAnalytics();
+ a.trackMessageSent('composer');
+ a.setEnabled(false);
+ a.trackMessageSent('composer');
+ a.trackMessageSent('terminal');
+ assert.equal(messageEvents().length, 1, 'only the pre-opt-out message counts');
+ a.setEnabled(true);
+ a.trackMessageSent('steer');
+ assert.equal(messageEvents().length, 2, 'and it resumes when switched back on');
+});
+
+test('DO_NOT_TRACK suppresses it, re-checked at send so it cannot be raced', () => {
+ const a = bootedAnalytics();
+ process.env.DO_NOT_TRACK = '1';
+ try {
+ a.trackMessageSent('terminal');
+ assert.equal(messageEvents().length, 0);
+ } finally {
+ delete process.env.DO_NOT_TRACK;
+ }
+});
+
+test('a build with no PostHog key never sends it', () => {
+ const key = globalThis.__POSTHOG_KEY__;
+ globalThis.__POSTHOG_KEY__ = '';
+ try {
+ const a = bootedAnalytics();
+ a.trackMessageSent('terminal');
+ assert.equal(messageEvents().length, 0);
+ } finally {
+ globalThis.__POSTHOG_KEY__ = key;
+ }
+});
+
+test('nothing is counted after the session has ended', () => {
+ const a = bootedAnalytics();
+ return a.endSession().then(() => {
+ a.trackMessageSent('terminal');
+ assert.equal(messageEvents().length, 0);
+ });
+});
+
+// ── the renderer seam: narrower than the enum, on purpose ────────────────────
+
+test('the renderer may name only the two surfaces main cannot see for itself', () => {
+ assert.equal(isRendererMessageSurface('terminal'), true);
+ assert.equal(isRendererMessageSurface('composer'), true);
+ // steer and hive are counted in main at their own IPC handlers. If the
+ // renderer could name them too, a future call site would double-count.
+ assert.equal(isRendererMessageSurface('steer'), false);
+ assert.equal(isRendererMessageSurface('hive'), false);
+ for (const junk of ['', 'slack', null, undefined, 7, {}, ['terminal']]) {
+ assert.equal(isRendererMessageSurface(junk), false, `junk: ${String(junk)}`);
+ }
+});
+
+// ── WIRING: the part that fails open ─────────────────────────────────────────
+
+test('the renderer IPC channel name is identical on both sides of the bridge', () => {
+ // A typo here is silent in both directions and the counter reads zero forever.
+ const CHANNEL = "'analytics:messageSent'";
+ assert.ok(main.includes(`ipcMain.handle(${CHANNEL}`), 'main must handle the channel');
+ assert.ok(preload.includes(`ipcRenderer.invoke(${CHANNEL}`), 'preload must invoke the same channel');
+});
+
+test('the renderer cannot name the event, only the surface', () => {
+ // The channel takes a surface and the handler hard-codes the event name, so a
+ // compromised or buggy renderer cannot invent an event or attach a property.
+ assert.match(main, /ipcMain\.handle\('analytics:messageSent', \(_evt, surface: unknown\) => \{/);
+ assert.match(main, /if \(!isRendererMessageSurface\(surface\)\) return \{ ok: false \};/);
+ assert.match(main, /analytics\.trackMessageSent\(surface\);/);
+});
+
+test('the bridge takes a surface and nothing that could carry a message', () => {
+ const sig = preload.match(/trackMessageSent: \(([^)]*)\)/);
+ assert.ok(sig, 'preload must expose trackMessageSent');
+ assert.equal(sig[1], "surface: 'terminal' | 'composer'", 'one closed-enum argument, no text parameter');
+});
+
+test('a telemetry failure can never break sending a message', () => {
+ // The bridge swallows both outcomes, and both call sites are fire-and-forget.
+ assert.match(preload, /ipcRenderer\.invoke\('analytics:messageSent', surface\)\.then\(\(\) => undefined, \(\) => undefined\)/);
+});
+
+test('the terminal counts at the submit boundary, not at pty:write', () => {
+ const pool = read('src/renderer/src/components/terminalPool.ts');
+ // pty:write fires on every keystroke — counting there is the keystroke trap.
+ assert.ok(!main.includes("ipcMain.handle('pty:write'") ||
+ !/pty:write[\s\S]{0,400}?trackMessageSent/.test(main), 'pty:write must not count messages');
+ // The count sits in the onData handler, gated on an actual submitted line.
+ assert.match(pool, /if \(submitted && !pasted\) void window\.cth\.trackMessageSent\('terminal'\);/);
+ // …and `submitted` is only ever set where a non-trivial line was flushed.
+ assert.match(pool, /if \(t\.length >= 2\) \{\s*entry\.onPrompt\?\.\(t\);\s*submitted = true;\s*\}/);
+ // …and a bracketed paste is excluded, so a multi-line paste is not N messages.
+ assert.match(pool, /const pasted = data\.includes\('\\x1b\[200~'\);/);
+});
+
+test('the composer counts its own submit, not the shared enqueue action', () => {
+ const composer = read('src/renderer/src/components/MessageQueueComposer.tsx');
+ // enqueueMessage is also how work orders, Slack inbound, nudges and compact
+ // commands reach an agent. Counting inside it would count all of those.
+ assert.match(composer, /enqueueMessage\(agent\.id, body\);\n(?:\s*\/\/.*\n)*\s*void window\.cth\.trackMessageSent\('composer'\);/);
+ const store = read('src/renderer/src/store/store.ts');
+ assert.ok(!store.includes('trackMessageSent'), 'the store action must not count');
+});
+
+test('the composer inherits the IME guard instead of restating it', () => {
+ const composer = read('src/renderer/src/components/MessageQueueComposer.tsx');
+ // An Enter that picks an IME candidate is not a submit. The count sits inside
+ // queueIt(), which the key handler only reaches past isComposingKey — so a
+ // Japanese or Chinese user cannot inflate their own count on candidate
+ // selection. Assert the guard is still the first thing that handler does.
+ assert.match(composer, /const onKey = \(e: KeyboardEvent<HTMLTextAreaElement>\) => \{\s*if \(isComposingKey\(e\)\) return;/);
+});
+
+test('only human hive messages are counted, never agent-to-agent traffic', () => {
+ assert.match(main, /if \(sender === 'human'\) analytics\.trackMessageSent\('hive'\);/);
+ // Counted at the IPC handler, which is the only place `from` exists; hive.send
+ // itself is called all over main by agents.
+ const hive = read('src/main/hive.ts');
+ assert.ok(!hive.includes('trackMessageSent'), 'hive.ts must not count');
+});
+
+test('steer is counted at the IPC seam, not inside control.steer', () => {
+ assert.match(main, /control\.steer\(agentId, text\);\n(?:\s*\/\/.*\n)*\s*analytics\.trackMessageSent\('steer'\);/);
+ // closingTime and the voice action layer call control.steer directly and are
+ // not a person typing; counting inside control.ts would sweep them in.
+ const control = read('src/main/control.ts');
+ assert.ok(!control.includes('trackMessageSent'), 'control.ts must not count');
+});
+
+// ── doc/code lockstep ────────────────────────────────────────────────────────
+
+test('TELEMETRY.md documents message_sent and every value of its enum', () => {
+ assert.ok(telemetryDoc.includes('`message_sent`'), 'the event must be in the doc');
+ for (const surface of MESSAGE_SURFACES) {
+ assert.ok(telemetryDoc.includes(`\`${surface}\``), `surface ${surface} must be documented`);
+ }
+});
+
+test('every event in the allowlist is described in TELEMETRY.md, and vice versa', () => {
+ // The published policy and the code have contradicted each other twice in this
+ // repo's history. This makes a third contradiction fail the build instead of
+ // shipping: the doc's event table and the allowlist must name the same events.
+ const analyticsSrc = read('src/main/analytics.ts');
+ const block = analyticsSrc.slice(
+ analyticsSrc.indexOf('const EVENTS'),
+ analyticsSrc.indexOf('/** The only values `feature_used')
+ );
+ const inCode = [...block.matchAll(/^\s{2}([a-z_]+): new Set<string>/gm)].map((m) => m[1]);
+ assert.ok(inCode.includes('message_sent') && inCode.length >= 10, `parsed events: ${inCode}`);
+
+ const rows = telemetryDoc.slice(telemetryDoc.indexOf('The events:'), telemetryDoc.indexOf('### About'));
+ const inDoc = [...rows.matchAll(/^\| `([a-z_]+)` \|/gm)].map((m) => m[1]);
+
+ assert.deepEqual(inCode.slice().sort(), inDoc.slice().sort(),
+ 'analytics.ts EVENTS and the TELEMETRY.md table must list exactly the same events');
+});