Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.
TypeScript
feat(observability): measure how often a wake produces nothing
Xialie Zhuang748a856b9a85
diff --git a/server/src/__integration__/wake-economics.test.ts b/server/src/__integration__/wake-economics.test.tsnew file mode 100644index 0000000..ea40f10--- /dev/null+++ b/server/src/__integration__/wake-economics.test.ts@@ -0,0 +1,169 @@+/**+ * `getWakeEconomics` against a real Postgres.+ *+ * The query is the whole point of this file. It anti-joins agent_runs to+ * messages over a time window and aggregates in SQL, and this repo has a+ * documented history of a single mis-shaped query starving the pool — so it+ * gets executed for real rather than reasoned about.+ *+ * The metric: a run is SILENT when the agent posted nothing into the+ * conversation that woke it, within ten minutes of the run starting. Same+ * definition @yetone used to publish the 26.3% group figure in #70, so the two+ * numbers are comparable.+ */+import { after, before, beforeEach, test } from 'node:test'+import assert from 'node:assert/strict'+import { randomUUID } from 'node:crypto'+import { pool } from '../db/pool.js'+import { getWakeEconomics } from '../agents/observability.js'+import { ensureSchemaOnce, resetAllTables, seedCompanyWithAgent, teardownAll } from './_helpers.js'++before(async () => { await ensureSchemaOnce() })+beforeEach(async () => { await resetAllTables() })+after(async () => { await teardownAll() })++async function seedConvo(companyId: string, kind: 'group' | 'direct', members: string[]): Promise<string> {+ const id = `conv-${randomUUID().slice(0, 8)}`+ await pool.query(+ `INSERT INTO conversations (id, kind, title, members, tag, company_id)+ VALUES ($1, $2, $3, $4::jsonb, $5, $6)`,+ [id, kind, `wake-econ ${kind}`, JSON.stringify(members), kind === 'direct' ? 'human' : 'group', companyId],+ )+ return id+}++/** A completed run that spent tokens, triggered by `convoId`. */+async function seedRun(args: {+ companyId: string; agentId: string; convoId: string; minutesAgo?: number; tokens?: number+}): Promise<string> {+ const id = `run-${randomUUID().slice(0, 8)}`+ const tokens = args.tokens ?? 1000+ await pool.query(+ `INSERT INTO agent_runs+ (id, agent_id, company_id, trigger, status, model,+ input_tokens, cached_input_tokens, cache_creation_tokens, output_tokens, started_at)+ VALUES ($1, $2, $3, $4::jsonb, 'completed', 'gpt-5.5',+ $5, 0, 0, 100, NOW() - ($6::double precision * INTERVAL '1 minute'))`,+ [id, args.agentId, args.companyId,+ JSON.stringify({ source: 'message.new', conversationIds: [args.convoId] }),+ tokens, args.minutesAgo ?? 5],+ )+ return id+}++/** A reply from `authorId`, offset from the run's start. */+async function seedReply(args: {+ companyId: string; convoId: string; authorId: string; minutesAgo: number+}): Promise<void> {+ await pool.query(+ `INSERT INTO messages (id, conversation_id, author_id, kind, body, sequence, company_id, created_at)+ VALUES ($1, $2, $3, 'text', 'on it', 1, $4, NOW() - ($5::double precision * INTERVAL '1 minute'))`,+ [`m-${randomUUID().slice(0, 8)}`, args.convoId, args.authorId, args.companyId, args.minutesAgo],+ )+}++const bucket = (e: Awaited<ReturnType<typeof getWakeEconomics>>, kind: string) =>+ e.buckets.find((b) => b.conversationKind === kind)++test('a run that produced no reply counts as silent', async () => {+ const { companyId, agentId } = await seedCompanyWithAgent()+ const convo = await seedConvo(companyId, 'group', [agentId])+ await seedRun({ companyId, agentId, convoId: convo, minutesAgo: 5 })++ const g = bucket(await getWakeEconomics({ companyId }), 'group')+ assert.equal(g?.runs, 1)+ assert.equal(g?.silentRuns, 1)+ assert.equal(g?.silentRate, 1)+ assert.ok((g?.silentSpendUsd ?? 0) > 0, 'a silent run still cost tokens')+})++test('a run whose agent replied inside the window is not silent', async () => {+ const { companyId, agentId } = await seedCompanyWithAgent()+ const convo = await seedConvo(companyId, 'group', [agentId])+ await seedRun({ companyId, agentId, convoId: convo, minutesAgo: 5 })+ await seedReply({ companyId, convoId: convo, authorId: agentId, minutesAgo: 4 })++ const g = bucket(await getWakeEconomics({ companyId }), 'group')+ assert.equal(g?.runs, 1)+ assert.equal(g?.silentRuns, 0)+ assert.equal(g?.silentSpendUsd, 0, 'an answered run contributes no silent spend')+})++test('a reply after the ten-minute window still counts as silent', async () => {+ // The window is what makes the metric mean "this wake answered", rather than+ // "the agent eventually said something in that room".+ const { companyId, agentId } = await seedCompanyWithAgent()+ const convo = await seedConvo(companyId, 'group', [agentId])+ await seedRun({ companyId, agentId, convoId: convo, minutesAgo: 30 })+ await seedReply({ companyId, convoId: convo, authorId: agentId, minutesAgo: 5 })++ const g = bucket(await getWakeEconomics({ companyId }), 'group')+ assert.equal(g?.silentRuns, 1)+})++test("another agent's reply does not rescue this run", async () => {+ const { companyId, agentId } = await seedCompanyWithAgent()+ const { agentId: peer } = await seedCompanyWithAgent({ companyId })+ const convo = await seedConvo(companyId, 'group', [agentId, peer])+ await seedRun({ companyId, agentId, convoId: convo, minutesAgo: 5 })+ await seedReply({ companyId, convoId: convo, authorId: peer, minutesAgo: 4 })++ const g = bucket(await getWakeEconomics({ companyId }), 'group')+ assert.equal(g?.silentRuns, 1, 'silence is per-agent — the peer answering is exactly the waste being counted')+})++test('group and direct are reported separately', async () => {+ // A DM legitimately answers far more often; averaging the two would hide the+ // group number this exists to track.+ const { companyId, agentId } = await seedCompanyWithAgent()+ const group = await seedConvo(companyId, 'group', [agentId])+ const dm = await seedConvo(companyId, 'direct', [agentId])+ await seedRun({ companyId, agentId, convoId: group, minutesAgo: 5 })+ await seedRun({ companyId, agentId, convoId: dm, minutesAgo: 5 })+ await seedReply({ companyId, convoId: dm, authorId: agentId, minutesAgo: 4 })++ const e = await getWakeEconomics({ companyId })+ assert.equal(bucket(e, 'group')?.silentRate, 1)+ assert.equal(bucket(e, 'direct')?.silentRate, 0)+})++test('a run that never reached the model is not counted at all', async () => {+ // An orphaned 0-token row never spent a big brain; calling it a silent wake+ // would inflate the very number this tracks.+ const { companyId, agentId } = await seedCompanyWithAgent()+ const convo = await seedConvo(companyId, 'group', [agentId])+ await seedRun({ companyId, agentId, convoId: convo, minutesAgo: 5, tokens: 0 })++ const e = await getWakeEconomics({ companyId })+ assert.equal(bucket(e, 'group'), undefined)+})++test('another company never leaks in', async () => {+ const mine = await seedCompanyWithAgent()+ const theirs = await seedCompanyWithAgent()+ const convo = await seedConvo(theirs.companyId, 'group', [theirs.agentId])+ await seedRun({ companyId: theirs.companyId, agentId: theirs.agentId, convoId: convo, minutesAgo: 5 })++ const e = await getWakeEconomics({ companyId: mine.companyId })+ assert.deepEqual(e.buckets, [])+})++test('the window filters out older runs', async () => {+ const { companyId, agentId } = await seedCompanyWithAgent()+ const convo = await seedConvo(companyId, 'group', [agentId])+ await seedRun({ companyId, agentId, convoId: convo, minutesAgo: 60 * 5 })++ assert.deepEqual((await getWakeEconomics({ companyId, sinceHours: 1 })).buckets, [])+ assert.equal(bucket(await getWakeEconomics({ companyId, sinceHours: 24 }), 'group')?.runs, 1)+})++test('agentId narrows to one agent', async () => {+ const { companyId, agentId } = await seedCompanyWithAgent()+ const { agentId: peer } = await seedCompanyWithAgent({ companyId })+ const convo = await seedConvo(companyId, 'group', [agentId, peer])+ await seedRun({ companyId, agentId, convoId: convo, minutesAgo: 5 })+ await seedRun({ companyId, agentId: peer, convoId: convo, minutesAgo: 5 })++ assert.equal(bucket(await getWakeEconomics({ companyId }), 'group')?.runs, 2)+ assert.equal(bucket(await getWakeEconomics({ companyId, agentId }), 'group')?.runs, 1)+})diff --git a/server/src/agents/observability.ts b/server/src/agents/observability.tsindex 1295ad6..447b97d 100644--- a/server/src/agents/observability.ts+++ b/server/src/agents/observability.ts@@ -538,3 +538,154 @@ export async function getTriageEconomics(args: {recent,}}++/** How long after a wake we still count a post as "this run answered".+ * Ten minutes is the window @yetone used to publish the 26.3% figure in #70;+ * keeping it identical is what makes this surface comparable to that number+ * rather than a second, differently-shaped statistic. */+const SILENT_WINDOW_MS = 10 * 60_000++export interface SilentWakeBucket {+ /** 'group' | 'direct' — a DM legitimately answers far more often, so the two+ * must never be averaged into one rate. */+ conversationKind: string+ runs: number+ silentRuns: number+ silentRate: number+ /** Big-brain spend on the silent runs, priced at query time from the stored+ * token counts (same rule as the triage ledger: tokens are real, prices are+ * live). */+ silentSpendUsd: number+}++export interface WakeEconomics {+ sinceHours: number+ buckets: SilentWakeBucket[]+ /** Any price used was a seed/fallback rather than an operator-supplied rate.+ * The RATIOS are measured either way; only the dollars are modelled. */+ costEstimated: boolean+}++/** How often a wake produced nothing.+ *+ * A run counts as SILENT when the agent posted no message into any of the+ * conversations that woke it, within SILENT_WINDOW_MS of the run starting.+ * That is the whole point of #70: a group message wakes every member, each+ * reasons over the same room, and most of them conclude it was not theirs —+ * after the big brain has already been paid.+ *+ * This exists so that decision stops needing a hand-written query. The routing+ * change in #92 is meant to move this number; without a surface, "did it work"+ * is an argument rather than a measurement.+ *+ * Deliberately NOT a counterfactual: it reports what happened, not what would+ * have been saved. The one modelled quantity is the dollar column, and+ * `costEstimated` says so. */+export async function getWakeEconomics(args: {+ companyId: string+ agentId?: string | null+ sinceHours?: number+}): Promise<WakeEconomics> {+ const sinceHours = Math.min(720, Math.max(1, args.sinceHours ?? 24))+ const ms = sinceHours * 3_600_000+ const agentFilter = args.agentId ? 'AND r.agent_id = $4' : ''+ const params: unknown[] = [args.companyId, ms, SILENT_WINDOW_MS]+ if (args.agentId) params.push(args.agentId)++ // One aggregate, grouped in SQL — never a row per run in JS. Runs are reached+ // through idx_agent_runs_company_started; the silence probe is an anti-join+ // per (conversation, agent, window), which idx_messages_convo_created serves.+ // Only runs that actually spent tokens are counted: an orphaned 0-token row+ // never reached the model, so calling it a "silent wake" would inflate the+ // very number this exists to track.+ const { rows } = await pool.query<{+ conversation_kind: string+ runs: number+ silent_runs: number+ model: string | null+ input_tokens: string+ cached_tokens: string+ cache_creation_tokens: string+ output_tokens: string+ }>(+ `WITH run_convo AS (+ SELECT r.id, r.agent_id, r.started_at, r.model,+ r.input_tokens, r.cached_input_tokens, r.cache_creation_tokens, r.output_tokens,+ (SELECT cid FROM jsonb_array_elements_text(r.trigger->'conversationIds') AS cid LIMIT 1) AS conversation_id+ FROM agent_runs r+ WHERE r.company_id = $1+ AND r.started_at > NOW() - ($2::double precision * INTERVAL '1 millisecond')+ AND (r.input_tokens + r.cached_input_tokens + r.output_tokens) > 0+ ${agentFilter}+ )+ SELECT COALESCE(c.kind, 'group') AS conversation_kind,+ rc.model,+ count(*)::int AS runs,+ count(*) FILTER (+ WHERE NOT EXISTS (+ SELECT 1 FROM messages m+ WHERE m.conversation_id = rc.conversation_id+ AND m.author_id = rc.agent_id+ AND m.created_at >= rc.started_at+ AND m.created_at < rc.started_at + ($3::double precision * INTERVAL '1 millisecond')+ )+ )::int AS silent_runs,+ COALESCE(sum(rc.input_tokens) FILTER (WHERE NOT EXISTS (+ SELECT 1 FROM messages m+ WHERE m.conversation_id = rc.conversation_id AND m.author_id = rc.agent_id+ AND m.created_at >= rc.started_at+ AND m.created_at < rc.started_at + ($3::double precision * INTERVAL '1 millisecond')+ )), 0)::bigint AS input_tokens,+ COALESCE(sum(rc.cached_input_tokens) FILTER (WHERE NOT EXISTS (+ SELECT 1 FROM messages m+ WHERE m.conversation_id = rc.conversation_id AND m.author_id = rc.agent_id+ AND m.created_at >= rc.started_at+ AND m.created_at < rc.started_at + ($3::double precision * INTERVAL '1 millisecond')+ )), 0)::bigint AS cached_tokens,+ COALESCE(sum(rc.cache_creation_tokens) FILTER (WHERE NOT EXISTS (+ SELECT 1 FROM messages m+ WHERE m.conversation_id = rc.conversation_id AND m.author_id = rc.agent_id+ AND m.created_at >= rc.started_at+ AND m.created_at < rc.started_at + ($3::double precision * INTERVAL '1 millisecond')+ )), 0)::bigint AS cache_creation_tokens,+ COALESCE(sum(rc.output_tokens) FILTER (WHERE NOT EXISTS (+ SELECT 1 FROM messages m+ WHERE m.conversation_id = rc.conversation_id AND m.author_id = rc.agent_id+ AND m.created_at >= rc.started_at+ AND m.created_at < rc.started_at + ($3::double precision * INTERVAL '1 millisecond')+ )), 0)::bigint AS output_tokens+ FROM run_convo rc+ LEFT JOIN conversations c ON c.id = rc.conversation_id+ GROUP BY conversation_kind, rc.model`,+ params,+ )++ const byKind = new Map<string, { runs: number; silent: number; usd: number }>()+ let anyEstimated = false+ for (const r of rows) {+ const { usd, estimated } = effectiveCostUsd(r.model, {+ inputTokens: Number(r.input_tokens),+ cachedInputTokens: Number(r.cached_tokens),+ cacheCreationTokens: Number(r.cache_creation_tokens),+ outputTokens: Number(r.output_tokens),+ })+ if (estimated) anyEstimated = true+ const cur = byKind.get(r.conversation_kind) ?? { runs: 0, silent: 0, usd: 0 }+ cur.runs += r.runs+ cur.silent += r.silent_runs+ cur.usd += usd+ byKind.set(r.conversation_kind, cur)+ }++ return {+ sinceHours,+ costEstimated: anyEstimated,+ buckets: [...byKind].map(([conversationKind, v]) => ({+ conversationKind,+ runs: v.runs,+ silentRuns: v.silent,+ silentRate: v.runs > 0 ? v.silent / v.runs : 0,+ silentSpendUsd: v.usd,+ })).sort((a, b) => b.runs - a.runs),+ }+}diff --git a/server/src/api/router.ts b/server/src/api/router.tsindex 9989663..24dd5de 100644--- a/server/src/api/router.ts+++ b/server/src/api/router.ts@@ -9,7 +9,7 @@ import { createPoll, castVote, closePoll, PollError } from '../polls.js'import { env } from '../env.js'import { startConvene, getActiveConvene } from '../agents/convene.js'import { fetchImageBytes } from '../agents/image-fetcher.js'-import { getTriageEconomics } from '../agents/observability.js'+import { getTriageEconomics, getWakeEconomics } from '../agents/observability.js'import { BUSY_STATUS_LEASE_MS } from '../status.js'import { notifyMessage, computeMessageRecipients } from '../push.js'import { randomUUID, randomBytes, createHash, timingSafeEqual } from 'node:crypto'@@ -4768,6 +4768,18 @@ api.get('/agents/observability/triage', async (req, res) => {res.json(await getTriageEconomics({ companyId: tenant, agentId, sinceHours }))})+// How often does a wake produce nothing? A group message wakes every member and+// most conclude it was not theirs — after the big brain has already been paid.+// Split group vs direct, because a DM legitimately answers far more often and+// averaging the two hides the number that matters.+api.get('/agents/observability/wakes', async (req, res) => {+ const { companyId: tenant } = await requireDevtools(req)+ const agentId = typeof req.query.agentId === 'string' && req.query.agentId.trim() ? req.query.agentId.trim() : null+ const rawHours = Number(req.query.sinceHours ?? 24)+ const sinceHours = Math.max(1, Math.min(720, Number.isFinite(rawHours) ? rawHours : 24))+ res.json(await getWakeEconomics({ companyId: tenant, agentId, sinceHours }))+})+// Universal LLM-spend ledger rollup by purpose × model × source. Answers the// question "which business logic burned the most sub2api tokens?" — bucketed// per purpose so the operator can target optimization at the actual hot spot