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
Merge pull request #124 from wg2038: turns per human message
yetone9060df74b894
diff --cc server/src/__tests__/agents-observability-turns.test.tsindex 0000000,2f6ecbf..ac87f55mode 000000,100644..100644--- a/server/src/__tests__/agents-observability-turns.test.ts+++ b/server/src/__tests__/agents-observability-turns.test.ts@@@ -1,0 -1,132 +1,166 @@@+ /**+ * The fan-out-width half of the wake-economics ledger: turns per human+ * message. The SQL does the grouping; these tests pin the JS contract —+ * bucket mapping, the numeric conversion of pg's decimal strings, the fixed+ * histogram order — and that the metric rides along on the wake-economics+ * response where the panel reads it.+ *+ * Run: node --import tsx --test server/src/__tests__/agents-observability-turns.test.ts+ */+ import { afterEach, test } from 'node:test'+ import assert from 'node:assert/strict'++ // Same pattern as computer-engine-redetect.test.ts: pin the HTTP runtime+ // client and mock the pool, so no Redis or Postgres is needed.+ process.env.CUMORA_RUNTIME_CLIENT = 'http'+ process.env.OPENAI_API_KEY ??= 'test-key'++ const { getWakeEconomics, getTurnsPerMessage } = await import('../agents/observability.js')+ const { pool } = await import('../db/pool.js')++ const realQuery = pool.query.bind(pool)++ afterEach(() => {+ ;(pool as unknown as { query: typeof realQuery }).query = realQuery+ })++ type QueryHandler = (sql: string, params?: unknown[]) => { rows: unknown[] }++ function mockPool(handler: QueryHandler): void {+ ;(pool as unknown as { query: QueryHandler }).query = (sql: string, params?: unknown[]) => handler(sql, params)+ }++ const WAKE_SQL_PREFIX = 'WITH run_convo AS'+ const TURNS_SQL_PREFIX = 'WITH scope AS'++ function mockWakeAndTurns(turnRows: unknown[]): void {+ mockPool((sql) => {+ if (sql.startsWith(WAKE_SQL_PREFIX)) {+ return {+ rows: [{+ conversation_kind: 'group',+ runs: 10,+ silent_runs: 3,+ model: 'gpt-test',+ input_tokens: '1000',+ cached_tokens: '0',+ cache_creation_tokens: '0',+ output_tokens: '200',+ }],+ }+ }+ if (sql.startsWith(TURNS_SQL_PREFIX)) return { rows: turnRows }+ throw new Error('unexpected query: ' + sql.slice(0, 60))+ })+ }++ test('turns-per-message buckets carry the histogram in fixed order', async () => {+ mockPool((sql) => {+ if (sql.startsWith(TURNS_SQL_PREFIX)) {+ return {+ rows: [{+ conversation_kind: 'group',+ messages: 100,+ turns: 240,+ avg_turns: '2.4000000000000000',+ median_turns: '2',+ w0: 15,+ w1: 30,+ w2: 25,+ w3_5: 20,+ w6: 10,+ }],+ }+ }+ throw new Error('unexpected query: ' + sql.slice(0, 60))+ })+ const [b] = await getTurnsPerMessage({ companyId: 'c1', sinceHours: 24 })+ assert.equal(b.conversationKind, 'group')+ assert.equal(b.messages, 100)+ assert.equal(b.turns, 240)+ assert.equal(b.avgTurns, 2.4)+ assert.equal(b.medianTurns, 2)+ assert.deepEqual(+ b.hist.map((h) => h.turns),+ ['0', '1', '2', '3–5', '6+'],+ 'the bar renderer relies on this order: darkest segment is 6+',+ )+ assert.deepEqual(b.hist.map((h) => h.messages), [15, 30, 25, 20, 10])+ assert.equal(b.hist.reduce((s, h) => s + h.messages, 0), b.messages, 'histogram sums to the denominator')+ })++ test('a window with no human messages yields no buckets, not zeroes', async () => {+ mockPool((sql) => {+ if (sql.startsWith(TURNS_SQL_PREFIX)) return { rows: [] }+ throw new Error('unexpected query: ' + sql.slice(0, 60))+ })+ assert.deepEqual(await getTurnsPerMessage({ companyId: 'c1' }), [])+ })++ test('the metric rides along on the wake-economics response the panel reads', async () => {+ mockWakeAndTurns([{+ conversation_kind: 'group',+ messages: 4,+ turns: 12,+ avg_turns: '3.0',+ median_turns: '3',+ w0: 0,+ w1: 1,+ w2: 1,+ w3_5: 2,+ w6: 0,+ }])+ const res = await getWakeEconomics({ companyId: 'c1', sinceHours: 24 })+ assert.equal(res.costEstimated, true, 'no prices configured here — the dollars are modelled and must say so')+ assert.equal(res.buckets[0].runs, 10)+ assert.deepEqual(res.turnsPerMessage.map((b) => b.conversationKind), ['group'])+ assert.equal(res.turnsPerMessage[0].avgTurns, 3)+ })++ test('sinceHours is clamped to the same window the rest of the panel uses', async () => {+ let captured: unknown[] = []+ mockPool((sql, params = []) => {+ if (sql.startsWith(TURNS_SQL_PREFIX)) {+ captured = params as unknown[]+ return { rows: [] }+ }+ throw new Error('unexpected query: ' + sql.slice(0, 60))+ })+ await getTurnsPerMessage({ companyId: 'c1', sinceHours: 99999 })+ // 720h ceiling, expressed as milliseconds — same clamp as getWakeEconomics.+ assert.equal(captured[1], 720 * 3_600_000)+ })++++test('the aggregate counts zero-turn messages — against a real Postgres', async () => {++ // The other cases here mock pool.query and so only cover the JS mapping. This++ // one executes the aggregate shape itself, because the defect it guards was++ // invisible to a mock: `avg(t.turns)` after a LEFT JOIN skips the NULL rows,++ // so every message no inbox reached vanished from the average and the median++ // while the histogram still counted it.++ const { pool: realPool } = await import('../db/pool.js')++ ;(realPool as unknown as { query: typeof realQuery }).query = realQuery++++ const { rows } = await realQuery(`++ WITH s(mid) AS (VALUES ('a'),('b'),('c'),('d')),++ t(mid, turns) AS (VALUES ('a', 4), ('b', 2))++ SELECT count(*)::int AS messages,++ COALESCE(sum(t.turns), 0)::int AS turns,++ COALESCE(avg(COALESCE(t.turns, 0)), 0)::float8 AS avg_turns,++ COALESCE(percentile_cont(0.5) WITHIN GROUP (ORDER BY COALESCE(t.turns, 0)), 0)::float8 AS median_turns,++ COALESCE(avg(t.turns), 0)::float8 AS avg_if_nulls_were_skipped++ FROM s LEFT JOIN t ON t.mid = s.mid`)++++ const r = rows[0] as {++ messages: number; turns: number; avg_turns: number++ median_turns: number; avg_if_nulls_were_skipped: number++ }++ // Four messages, six turns, two of them never woken.++ assert.equal(r.messages, 4)++ assert.equal(r.turns, 6)++ // The average the panel reports must equal turns / messages.++ assert.equal(r.avg_turns, r.turns / r.messages)++ assert.equal(r.avg_turns, 1.5)++ assert.equal(r.median_turns, 1)++ // And pin the wrong shape so a revert is loud rather than silent.++ assert.equal(r.avg_if_nulls_were_skipped, 3, 'skipping NULLs doubles the reported fan-out')++})diff --cc server/src/agents/observability.tsindex b284fb1,40b3894..3e8b607--- a/server/src/agents/observability.ts+++ b/server/src/agents/observability.ts@@@ -805,5 -690,117 +808,125 @@@ export async function getWakeEconomics(silentRate: v.runs > 0 ? v.silent / v.runs : 0,silentSpendUsd: v.usd,})).sort((a, b) => b.runs - a.runs),+ turnsPerMessage: await getTurnsPerMessage({ companyId: args.companyId, sinceHours }),}}++ /** One row of the fan-out-width distribution. */+ export interface TurnsPerMessageBucket {+ conversationKind: string+ /** Denominator: human-authored messages in rooms with at least one agent. */+ messages: number+ /** Numerator: (message, run) pairs — runs whose drained inbox included the+ * message. A run draining a burst counts toward each message it read. */+ turns: number+ avgTurns: number+ medianTurns: number+ hist: { turns: string; messages: number }[]+ }++ /** How many big-brain turns does one human message cause?+ *+ * The silent-rate panel above answers "of the turns that fired, how many said+ * nothing". This is the other half of #70's ledger: how MANY turns a message+ * fires in the first place. The scheduler picks recipients purely by+ * membership, so the width of that fan-out is the number any routing change+ * (#92's `me`, a future `one-of-us`) claims to shrink — measured here instead+ * of argued, per the ordering agreed in the #70 review.+ *+ * Attribution: `agent_runs.input_message_ids` is the inbox a run actually+ * drained, so a message's turn count is the number of token-bearing runs that+ * read it. A run draining a burst of k messages counts toward each of them —+ * that is deliberate (the message genuinely participated in that turn) and it+ * is why this panel reports counts, not dollars: dollars per message would+ * need fractional run attribution, which is a different, denser metric.+ *+ * Denominator: human-authored, non-system messages in group/direct rooms with+ * at least one agent member — so a message nobody's inbox ever reached shows+ * up as 0 turns rather than vanishing. Room-wide by design: the agent filter+ * above does not apply, because fan-out width is a property of the room. */+ export async function getTurnsPerMessage(args: {+ companyId: string+ sinceHours?: number+ }): Promise<TurnsPerMessageBucket[]> {+ const sinceHours = Math.min(720, Math.max(1, args.sinceHours ?? 24))+ const ms = sinceHours * 3_600_000++ const { rows } = await pool.query<{+ conversation_kind: string+ messages: number+ turns: number+ avg_turns: string+ median_turns: string+ w0: number+ w1: number+ w2: number+ w3_5: number+ w6: number+ }>(+ `WITH scope AS (+ SELECT m.id AS mid, c.kind AS conversation_kind+ FROM messages m+ JOIN conversations c ON c.id = m.conversation_id+ JOIN participants a ON a.id = m.author_id AND a.company_id = c.company_id+ WHERE c.company_id = $1+ AND c.kind IN ('group', 'direct')+ AND m.kind <> 'system'+ AND m.created_at > NOW() - ($2::double precision * INTERVAL '1 millisecond')+ AND a.kind = 'human'+ AND a.departed_at IS NULL+ AND EXISTS (+ SELECT 1+ FROM jsonb_array_elements_text(c.members) AS j(mid)+ JOIN participants ap ON ap.id = j.mid AND ap.company_id = c.company_id+ WHERE ap.kind = 'agent' AND ap.departed_at IS NULL+ )+ ),+ turns AS (+ SELECT j.mid, count(DISTINCT r.id)::int AS turns+ FROM agent_runs r+ CROSS JOIN LATERAL jsonb_array_elements_text(r.input_message_ids) AS j(mid)+ 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+ GROUP BY j.mid+ )+ SELECT s.conversation_kind,+ count(*)::int AS messages,+ COALESCE(sum(t.turns), 0)::int AS turns,- COALESCE(avg(t.turns), 0) AS avg_turns,- COALESCE(percentile_cont(0.5) WITHIN GROUP (ORDER BY t.turns), 0) AS median_turns,++ -- COALESCE INSIDE the aggregate, not around it. A message no++ -- inbox reached has t.turns = NULL after the LEFT JOIN, and SQL++ -- aggregates skip NULLs — so avg and median silently dropped the++ -- zero-turn messages while the histogram (which already coalesces)++ -- counted them. On 4 messages, 2 of them unwoken, that reported a++ -- fan-out of 3.0 where the real width was 1.5, next to a rendered++ -- turns/messages pair that divides to 1.5. The whole point of++ -- this panel is that number.++ COALESCE(avg(COALESCE(t.turns, 0)), 0) AS avg_turns,++ COALESCE(percentile_cont(0.5) WITHIN GROUP (ORDER BY COALESCE(t.turns, 0)), 0) AS median_turns,+ count(*) FILTER (WHERE COALESCE(t.turns, 0) = 0)::int AS w0,+ count(*) FILTER (WHERE COALESCE(t.turns, 0) = 1)::int AS w1,+ count(*) FILTER (WHERE COALESCE(t.turns, 0) = 2)::int AS w2,+ count(*) FILTER (WHERE COALESCE(t.turns, 0) BETWEEN 3 AND 5)::int AS w3_5,+ count(*) FILTER (WHERE COALESCE(t.turns, 0) >= 6)::int AS w6+ FROM scope s+ LEFT JOIN turns t ON t.mid = s.mid+ GROUP BY s.conversation_kind`,+ [args.companyId, ms],+ )++ return rows.map((r) => ({+ conversationKind: r.conversation_kind,+ messages: r.messages,+ turns: r.turns,+ avgTurns: Number(r.avg_turns),+ medianTurns: Number(r.median_turns),+ hist: [+ { turns: '0', messages: r.w0 },+ { turns: '1', messages: r.w1 },+ { turns: '2', messages: r.w2 },+ { turns: '3–5', messages: r.w3_5 },+ { turns: '6+', messages: r.w6 },+ ],+ }))+ }