Public: anyone can read this; the crew can change it.

The response record says how fast each lead source was answered #52

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/speed-to-lead:mason/32-the-response-record-says-how-fast-each-l → main 3 commits fork 2 threads · 2 unresolved

  • Merged. mason/32-the-response-record-says-how-fast-each-l was merged into main as 8f8afee.

Review

Sign in to review this change.
12 files changed +170 −22
README.md +8 −2
@@ -28,7 +28,9 @@ what you see right after a restart. Do step 1 first.
2828 2. Read the desk. The newest leads are at the top. **Maria Gonzalez** and
2929 **David Chen** have just asked, so their clocks are green, under five
3030 minutes; they turn amber at five. Above the list, your response record
31 says how fast you have been lately.
31 says how fast you have been lately, and under it one short line for each
32 lead source, e.g. "Zillow · 4 leads · median 0:48 · 3 answered under 5
33 min", so you can see whether Zillow leads are slipping.
3234 3. Answer a red lead. **Tom Becker** has waited hours, so his clock is
3335 red. Tap his name: his question is on one side, the reply already
3436 written for him on the other. Press "Approve and send". His clock stops
@@ -160,7 +162,11 @@ time from a lead asking to your first reply, and the share of leads
160162 answered inside 5 minutes. A lead still waiting counts with the time it has
161163 waited so far, so a red clock pulls both numbers down until you answer it.
162164 With no replies yet it says so. The same figures are in `GET /leads`
163 (`record`) and on the terminal desk.
165 (`record`, with the per-source lines as `record.by_source`) and on the
166 terminal desk. Under the record, one line per lead source that had leads in
167 those 30 days says how many leads it sent, the median first reply and how
168 many were answered under 5 minutes, measured the same way; sources with no
169 leads are left out.
164170
165171 Admins can read the **Activity** page (`/activity`): every change and refused attempt in plain sentences, newest first, 50 to a page, with a "Messages sent only" filter. In the terminal an admin presses `a` on the desk (`o` older, `n` newer, `m` messages sent only).
166172
contract/openapi.json +33 −1
@@ -2014,6 +2014,37 @@
20142014 "null"
20152015 ],
20162016 "description": "Whole percent of leads answered (or waiting) under five minutes; null with no leads."
2017 },
2018 "by_source": {
2019 "type": "array",
2020 "description": "The same record per lead source that had leads in the window, most leads first; empty with no leads.",
2021 "items": {
2022 "type": "object",
2023 "properties": {
2024 "source": {
2025 "type": "string",
2026 "description": "Where the leads came from."
2027 },
2028 "count": {
2029 "type": "integer",
2030 "description": "Leads from this source in the window."
2031 },
2032 "median_ms": {
2033 "type": "integer",
2034 "description": "Median time to first reply, in milliseconds; waiting leads count their time so far."
2035 },
2036 "under_five": {
2037 "type": "integer",
2038 "description": "How many were answered (or are waiting) under five minutes."
2039 }
2040 },
2041 "required": [
2042 "source",
2043 "count",
2044 "median_ms",
2045 "under_five"
2046 ]
2047 }
20172048 }
20182049 },
20192050 "required": [
@@ -2021,7 +2052,8 @@
20212052 "leads",
20222053 "replied",
20232054 "median_ms",
2024 "within_5_min_pct"
2055 "within_5_min_pct",
2056 "by_source"
20252057 ]
20262058 },
20272059 "show": {
src/clock.ts +18
@@ -6,6 +6,8 @@
66 * in the browser; the page's first paint is this module's.
77 */
88
9 import { SOURCE_LABEL, type Source } from "./drafts.ts";
10
911 export const GREEN_MS = 5 * 60_000;
1012 export const AMBER_MS = 60 * 60_000;
1113
@@ -52,3 +54,19 @@ export function recordLine(record: {
5254 return `No replies yet in the last ${record.days} days.`;
5355 return `Median first reply: ${span(record.median_ms)} · ${record.within_5_min_pct}% answered within 5 minutes`;
5456 }
57
58 /** m:ss, so 48 seconds reads 0:48 and 2 h 5 min reads 125:00. */
59 function minSec(ms: number): string {
60 const total = Math.round(ms / 1000);
61 return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, "0")}`;
62 }
63
64 /** One line per source under the record: "Zillow · 4 leads · median 0:48 · 3 answered under 5 min". */
65 export function sourceLine(row: {
66 source: Source;
67 count: number;
68 median_ms: number;
69 under_five: number;
70 }): string {
71 return `${SOURCE_LABEL[row.source] ?? row.source} · ${row.count} ${row.count === 1 ? "lead" : "leads"} · median ${minSec(row.median_ms)} · ${row.under_five} answered under 5 min`;
72 }
src/leads.test.ts +23 −1
@@ -10,7 +10,7 @@ import { join } from "node:path";
1010 import { openDb } from "./db.ts";
1111 import { agent } from "./env.ts";
1212 import { findLead, insertLead, readyFor, responseRecord, send } from "./leads.ts";
13 import { recordLine } from "./clock.ts";
13 import { recordLine, sourceLine } from "./clock.ts";
1414
1515 const NOW = Date.parse("2026-10-30T12:00:00.000Z");
1616 const M = 60_000;
@@ -83,3 +83,25 @@ test("leads older than 30 days are not in the record", () => {
8383 lead(db, 1 * D, 1 * M);
8484 expect(responseRecord(db, NOW)).toMatchObject({ leads: 1, median_ms: 1 * M, within_5_min_pct: 100 });
8585 });
86
87 test("by source: counts, medians, under five, waiting leads by time so far, old ones out", () => {
88 const db = fresh();
89 const add = (source: string, ago: number, took?: number) => {
90 lead(db, ago, took);
91 db.run("UPDATE lead SET source = ?1 WHERE id = (SELECT max(id) FROM lead)", [source]);
92 };
93 add("zillow", 10 * M, 48_000);
94 add("zillow", 20 * M, 2 * M);
95 add("zillow", 30 * M, 9 * M);
96 add("zillow", 40 * M); // waiting 40 min
97 add("referral", 5 * M, M);
98 add("website", 40 * 86_400_000, M); // outside the window
99 const rows = responseRecord(db, NOW).by_source;
100 expect(rows).toEqual([
101 { source: "zillow", count: 4, median_ms: Math.round((2 * M + 9 * M) / 2), under_five: 2 },
102 { source: "referral", count: 1, median_ms: M, under_five: 1 },
103 ]);
104 expect(sourceLine(rows[0]!)).toBe("Zillow · 4 leads · median 5:30 · 2 answered under 5 min");
105 expect(sourceLine(rows[1]!)).toBe("Referral · 1 lead · median 1:00 · 1 answered under 5 min");
106 expect(responseRecord(fresh(), NOW).by_source).toEqual([]);
107 });
src/leads.ts +41 −13
@@ -354,8 +354,26 @@ export interface ResponseRecord {
354354 readonly median_ms: number | null;
355355 /** Whole percent of those leads answered within five minutes (waiting ones too long already count against). Null with no leads. */
356356 readonly within_5_min_pct: number | null;
357 /** The same, one entry per source that had leads in the window, most leads first. */
358 readonly by_source: readonly SourceRecord[];
357359 }
358360
361 /** How fast one lead source was answered over the same window. */
362 export interface SourceRecord {
363 readonly source: Source;
364 readonly count: number;
365 readonly median_ms: number;
366 /** Leads answered (or still waiting) under five minutes. */
367 readonly under_five: number;
368 }
369
370 const medianOf = (sorted: readonly number[]): number => {
371 const mid = Math.floor(sorted.length / 2);
372 return sorted.length % 2 === 1
373 ? sorted[mid]!
374 : Math.round((sorted[mid - 1]! + sorted[mid]!) / 2);
375 };
376
359377 export const RECORD_DAYS = 30;
360378
361379 /**
@@ -364,12 +382,13 @@ export const RECORD_DAYS = 30;
364382 */
365383 export function responseRecord(db: Database, now: number): ResponseRecord {
366384 const since = new Date(now - RECORD_DAYS * DAY_MS).toISOString();
367 const waits = db
368 .query<{ created_at: string; replied_at: string | null }, [string]>(
369 "SELECT created_at, replied_at FROM lead WHERE created_at >= ?1",
385 const all = db
386 .query<{ source: Source; created_at: string; replied_at: string | null }, [string]>(
387 "SELECT source, created_at, replied_at FROM lead WHERE created_at >= ?1",
370388 )
371389 .all(since)
372390 .map((row) => ({
391 source: row.source,
373392 ms: Math.max(
374393 0,
375394 (row.replied_at === null ? now : Date.parse(row.replied_at)) -
@@ -378,24 +397,33 @@ export function responseRecord(db: Database, now: number): ResponseRecord {
378397 replied: row.replied_at !== null,
379398 }))
380399 .sort((a, b) => a.ms - b.ms);
381 const n = waits.length;
382 const mid = Math.floor(n / 2);
400 const n = all.length;
401 const groups = new Map<Source, number[]>();
402 for (const w of all) {
outdated

Quadratic: this spreads the whole array for every lead. Fetch or create the array in the map and push into it.

403 const ms = groups.get(w.source);
404 if (ms === undefined) groups.set(w.source, [w.ms]);
405 else ms.push(w.ms);
406 }
407 const by_source = [...groups]
408 .map(([source, ms]) => ({
409 source,
410 count: ms.length,
411 median_ms: medianOf(ms),
412 under_five: ms.filter((m) => m < FIVE_MIN_MS).length,
413 }))
414 .sort((a, b) => b.count - a.count || a.source.localeCompare(b.source));
383415 return {
384416 days: RECORD_DAYS,
385417 leads: n,
386 replied: waits.filter((w) => w.replied).length,
387 median_ms:
388 n === 0
389 ? null
390 : n % 2 === 1
391 ? waits[mid]!.ms
392 : Math.round((waits[mid - 1]!.ms + waits[mid]!.ms) / 2),
418 replied: all.filter((w) => w.replied).length,
419 median_ms: n === 0 ? null : medianOf(all.map((w) => w.ms)),
393420 within_5_min_pct:
394421 n === 0
395422 ? null
396423 : Math.round(
397 (100 * waits.filter((w) => w.ms < FIVE_MIN_MS).length) / n,
424 (100 * all.filter((w) => w.ms < FIVE_MIN_MS).length) / n,
398425 ),
426 by_source,
399427 };
400428 }
401429
src/mcp.ts +1 −1
@@ -58,7 +58,7 @@ export const tools: readonly Tool[] = [
5858 {
5959 name: "list_leads",
6060 description:
61 "The desk: your response record (median first reply, share answered within 5 minutes, last 30 days) and the leads (optionally only those that need you, are in follow-up, or are closed), newest first, with what is ready to approve.",
61 "The desk: your response record (median first reply, share answered within 5 minutes, last 30 days, and the same per lead source as record.by_source) and the leads (optionally only those that need you, are in follow-up, or are closed), newest first, with what is ready to approve.",
6262 inputSchema: {
6363 type: "object",
6464 properties: {
src/pages/desk.ts +2 −2
@@ -6,7 +6,7 @@
66 import { day, clock, consent, source, STATE_LABEL } from "./parts.ts";
77 import { layout } from "./layout.ts";
88 import { escape } from "../http.ts";
9 import { recordLine } from "../clock.ts";
9 import { recordLine, sourceLine } from "../clock.ts";
1010 import { isAnswer } from "../drafts.ts";
1111 import { goesLabel, RECORD_NOTE } from "../quiet.ts";
1212 import { showingWhen } from "../showings.ts";
@@ -55,7 +55,7 @@ export function deskPage(input: {
5555 const answers = leads.filter((l) => l.ready !== null && isAnswer(l.ready.day)).length;
5656 const due = leads.filter((l) => l.ready !== null && l.ready.day > 0 && !isAnswer(l.ready.day)).length;
5757 const summary = `<p class="summary" aria-live="polite"><b>${waiting}</b> waiting for a first reply <span aria-hidden="true">·</span> <b>${due}</b> follow-up${due === 1 ? "" : "s"} due today${answers === 0 ? "" : ` <span aria-hidden="true">·</span> <b>${answers}</b> wrote back`}</p>`;
58 const record = input.record === undefined ? "" : `<p class="record">${escape(recordLine(input.record))}</p><p class="muted">${RECORD_NOTE}</p>`;
58 const record = input.record === undefined ? "" : `<p class="record">${escape(recordLine(input.record))}</p>${input.record.by_source.map((r) => `<p class="record-source muted">${escape(sourceLine(r))}</p>`).join("")}<p class="muted">${RECORD_NOTE}</p>`;
5959 const q = input.q ?? "";
6060 const views =
6161 counts === undefined
src/quiet.test.ts +11
@@ -20,6 +20,7 @@ import {
2020 tick,
2121 turn,
2222 } from "./actions.ts";
23 import type { Source } from "./drafts.ts";
2324 import { openDb } from "./db.ts";
2425 import { deskPage } from "./pages/desk.ts";
2526 import { leadPage } from "./pages/lead.ts";
@@ -314,3 +315,13 @@ test("an unsent text opened in quiet hours says approving will hold it", () => {
314315 const page = leadPage({ who: alice, agent: { ...agent, timeZone: ZONE }, lead: value(getLead(db, alice, { id })), mayUpdate: true, next: null, now: now.getTime() });
315316 expect(page).toContain("approving holds this text");
316317 });
318
319 test("the desk shows a line per source, escaped, and none with no leads", () => {
320 const listed = value(listLeads(fresh(), alice));
321 const base = { who: alice, agent: { ...agent, timeZone: ZONE }, leads: listed.leads, mayAdd: false, mayReset: false };
322 const row = { source: "<b>x</b>" as unknown as Source, count: 2, median_ms: 48_000, under_five: 1 };
323 const page = deskPage({ ...base, record: { ...listed.record, by_source: [row] } });
324 expect(page).toContain("&lt;b&gt;x&lt;/b&gt; · 2 leads · median 0:48 · 1 answered under 5 min");
325 expect(page).not.toContain("<b>x</b>");
326 expect(deskPage({ ...base, record: { ...listed.record, by_source: [] } })).not.toContain("record-source");
327 });
src/routes.ts +16 −1
@@ -289,8 +289,23 @@ export const DESK: Schema = {
289289 type: ["integer", "null"],
290290 description: "Whole percent of leads answered (or waiting) under five minutes; null with no leads.",
291291 },
292 by_source: {
293 type: "array",
294 description:
295 "The same record per lead source that had leads in the window, most leads first; empty with no leads.",
296 items: {
297 type: "object",
298 properties: {
299 source: { type: "string", description: "Where the leads came from." },
300 count: { type: "integer", description: "Leads from this source in the window." },
301 median_ms: { type: "integer", description: "Median time to first reply, in milliseconds; waiting leads count their time so far." },
302 under_five: { type: "integer", description: "How many were answered (or are waiting) under five minutes." },
303 },
304 required: ["source", "count", "median_ms", "under_five"],
305 },
306 },
292307 },
293 required: ["days", "leads", "replied", "median_ms", "within_5_min_pct"],
308 required: ["days", "leads", "replied", "median_ms", "within_5_min_pct", "by_source"],
294309 },
295310 show: { enum: [...VIEWS], description: "The view listed." },
296311 q: { type: "string", description: "The search that narrowed the desk; empty when none." },
src/server.test.ts +4
@@ -587,6 +587,10 @@ test("the desk carries the response record: in the page, in JSON, and in the API
587587 record: { days: number; leads: number; median_ms: number; within_5_min_pct: number };
588588 };
589589 expect(desk.record).toMatchObject({ days: 30 });
590 const rows = (desk.record as unknown as { by_source: { source: string; count: number; median_ms: number; under_five: number }[] }).by_source;
591 expect(rows.length).toBeGreaterThan(0);
592 expect(Object.keys(rows[0]!).sort()).toEqual(["count", "median_ms", "source", "under_five"]);
593 expect(page).toContain('class="record-source');
590594 expect(desk.record.leads).toBeGreaterThanOrEqual(11);
591595 expect(desk.record.within_5_min_pct).toBeGreaterThan(0);
592596 const spec = (await (await api("/openapi.json", {}, root)).json()) as {
src/terminal.test.ts +11
@@ -7,6 +7,7 @@ import { mkdtempSync } from "node:fs";
77 import { tmpdir } from "node:os";
88 import { join } from "node:path";
99 import { getLead, listLeads } from "./actions.ts";
10 import { sourceLine } from "./clock.ts";
1011 import { openDb } from "./db.ts";
1112 import { agent } from "./env.ts";
1213 import { seed } from "./sample.ts";
@@ -302,6 +303,16 @@ test("the desk header carries the response record", () => {
302303 expect(read(t)).toContain("answered within 5 minutes");
303304 });
304305
306 test("the desk header lists how fast each lead source was answered", () => {
307 const db = fresh();
308 const rows = listLeads(db, alice, { show: "all", q: "" });
309 if (!rows.ok) throw new Error(rows.message);
310 const by_source = rows.value.record.by_source;
311 expect(by_source.length).toBeGreaterThan(0);
312 const screen = read(terminal(db, alice));
313 for (const r of by_source) expect(screen).toContain(sourceLine(r));
314 });
315
305316 test("f cycles the desk's views; each shows its count and only its leads", () => {
306317 const db = fresh();
307318 const t = terminal(db, alice);
src/terminal.ts +2 −1
@@ -51,7 +51,7 @@ import {
5151 import { missingLine } from "./intake.ts";
5252 import { showingLine, showingWhen } from "./showings.ts";
5353 import { answers, callLine, OUTCOME_LABEL, OUTCOMES, type Outcome } from "./calls.ts";
54 import { between, elapsed, recordLine, tone } from "./clock.ts";
54 import { between, elapsed, recordLine, sourceLine, tone } from "./clock.ts";
5555 import { permit } from "./contract.ts";
5656 import { goesLabel, isQuiet, nextOpening, RECORD_NOTE } from "./quiet.ts";
5757 import { said as saidOf } from "./sentences.ts";
@@ -249,6 +249,7 @@ export function terminal(
249249 const zone = currentAgent(db).timeZone;
250250 const lines: string[] = [
251251 dim(recordLine(listed.value.record)),
252 ...listed.value.record.by_source.map((r) => dim(sourceLine(r))),

No test covers these terminal lines. Add one that renders the terminal desk and expects the source line, and that fails without this line.

252253 dim(RECORD_NOTE),
253254 VIEWS.map((v) => {
254255 const tab = `${VIEW_LABEL[v]} ${counts[v]}`;

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs