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

Show the agent's own response record at the top of the desk #11

Merged opened this

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

Merged

mason/speed-to-lead:mason/4-show-the-agent-s-own-response-record-at → main 2 commits fork 2 threads · 2 unresolved

  • Merged. mason/4-show-the-agent-s-own-response-record-at was merged into main as 4ec5d8a.

Review

Sign in to review this change.
15 files changed +344 −105
README.md +8
@@ -21,6 +21,14 @@ counting since they asked:
2121 - **amber** — under an hour.
2222 - **red** — over an hour. Answer this one now.
2323
24 Above the list sits your **response record** for the last 30 days, e.g.
25 "Median first reply: 3 min · 71% answered within 5 minutes": the middle
26 time from a lead asking to your first reply, and the share of leads
27 answered inside 5 minutes. A lead still waiting counts with the time it has
28 waited so far, so a red clock pulls both numbers down until you answer it.
29 With no replies yet it says so. The same figures are in `GET /leads`
30 (`record`) and on the terminal desk.
31
2432 Once you've replied, the clock stops and shows how long it took.
2533
2634 **Tap a lead** to see what they wrote beside the reply drafted for them.
contract/openapi.json +57 −76
@@ -8,7 +8,7 @@
88 "paths": {
99 "/leads": {
1010 "get": {
11 "summary": "The desk: every lead, newest inquiry first.",
11 "summary": "The desk: your response record, and every lead, newest inquiry first.",
1212 "operationId": "getLeads",
1313 "parameters": [
1414 {
@@ -24,14 +24,11 @@
2424 ],
2525 "responses": {
2626 "200": {
27 "description": "The desk: every lead, newest inquiry first.",
27 "description": "The desk: your response record, and every lead, newest inquiry first.",
2828 "content": {
2929 "application/json": {
3030 "schema": {
31 "type": "array",
32 "items": {
33 "$ref": "#/components/schemas/DeskLead"
34 }
31 "$ref": "#/components/schemas/Desk"
3532 }
3633 }
3734 }
@@ -878,76 +875,7 @@
878875 "messages": {
879876 "type": "array",
880877 "items": {
881 "type": "object",
882 "properties": {
883 "id": {
884 "type": "integer"
885 },
886 "lead_id": {
887 "type": "integer"
888 },
889 "day": {
890 "enum": [
891 0,
892 1,
893 3,
894 7,
895 14,
896 30
897 ],
898 "description": "0 is the first reply."
899 },
900 "channel": {
901 "enum": [
902 "text",
903 "email"
904 ]
905 },
906 "body": {
907 "type": "string",
908 "minLength": 1,
909 "maxLength": 4000
910 },
911 "signature": {
912 "type": "string"
913 },
914 "status": {
915 "enum": [
916 "draft",
917 "scheduled",
918 "due",
919 "sent",
920 "skipped"
921 ]
922 },
923 "due_at": {
924 "type": "string",
925 "format": "date-time"
926 },
927 "sent_at": {
928 "type": [
929 "string",
930 "null"
931 ],
932 "format": "date-time"
933 },
934 "sent_by": {
935 "type": [
936 "string",
937 "null"
938 ]
939 }
940 },
941 "required": [
942 "id",
943 "lead_id",
944 "day",
945 "channel",
946 "body",
947 "signature",
948 "status",
949 "due_at"
950 ]
878 "$ref": "#/components/schemas/Message"
951879 }
952880 }
953881 },
@@ -966,6 +894,59 @@
966894 "messages"
967895 ]
968896 },
897 "Desk": {
898 "type": "object",
899 "properties": {
900 "record": {
901 "type": "object",
902 "description": "How fast you answer, over the last 30 days. A lead still waiting counts its time so far.",
903 "properties": {
904 "days": {
905 "type": "integer"
906 },
907 "leads": {
908 "type": "integer",
909 "description": "Leads that arrived in the window."
910 },
911 "replied": {
912 "type": "integer",
913 "description": "Of those, how many have had a first reply."
914 },
915 "median_ms": {
916 "type": [
917 "integer",
918 "null"
919 ],
920 "description": "Median time to first reply, in milliseconds; null with no leads."
921 },
922 "within_5_min_pct": {
923 "type": [
924 "integer",
925 "null"
926 ],
927 "description": "Whole percent of leads answered (or waiting) under five minutes; null with no leads."
928 }
929 },
930 "required": [
931 "days",
932 "leads",
933 "replied",
934 "median_ms",
935 "within_5_min_pct"
936 ]
937 },
938 "leads": {
939 "type": "array",
940 "items": {
941 "$ref": "#/components/schemas/DeskLead"
942 }
943 }
944 },
945 "required": [
946 "record",
947 "leads"
948 ]
949 },
969950 "DeskLead": {
970951 "type": "object",
971952 "properties": {
src/actions.test.ts +8 −4
@@ -77,7 +77,7 @@ test("a stranger may not see or add leads; a signed-in person may", () => {
7777 expect(r.ok).toBe(false);
7878 if (!r.ok) expect(r.error).toBe("signin_required");
7979 expect(listLeads(db, anon).ok).toBe(false);
80 expect(listLeads(db, alice)).toEqual({ ok: true, value: [] });
80 expect(must(listLeads(db, alice)).leads).toEqual([]);
8181 });
8282
8383 test("control characters are refused at the boundary; a textarea's line breaks are kept", () => {
@@ -186,12 +186,12 @@ test("the day turns: a touch comes due on its day, once, and is sent when approv
186186 expect(must(tick(db, alice, at(0, 30))).leads).not.toContain(lead.id);
187187 expect(must(tick(db, alice, at(1, 1))).leads).toContain(lead.id);
188188 expect(must(tick(db, alice, at(1, 2))).leads).not.toContain(lead.id);
189 const desk = must(listLeads(db, alice)).find((l) => l.id === lead.id)!;
189 const desk = must(listLeads(db, alice)).leads.find((l) => l.id === lead.id)!;
190190 expect(desk.ready?.day).toBe(1);
191191 const sent = must(sendReply(db, alice, { id: lead.id }, at(1, 5)));
192192 expect(sent.messages.find((m) => m.day === 1)!.status).toBe("sent");
193193 expect(sent.messages.find((m) => m.day === 3)!.status).toBe("scheduled");
194 const after = must(listLeads(db, alice)).find((l) => l.id === lead.id)!;
194 const after = must(listLeads(db, alice)).leads.find((l) => l.id === lead.id)!;
195195 expect(after.ready).toBeNull();
196196 expect(after.next_at).toBe(at(3).toISOString());
197197 expect(tick(db, anon, at(2)).ok).toBe(false);
@@ -221,7 +221,11 @@ test("the sample desk: twelve leads, some red, some mid-cadence; only an admin r
221221 const sampleDb = openDb(mkdtempSync(join(tmpdir(), "app-sample-")));
222222 expect(resetSample(sampleDb, alice).ok).toBe(false);
223223 expect(must(resetSample(sampleDb, root, T0)).leads).toBe(12);
224 const desk = must(listLeads(sampleDb, alice));
224 const listed = must(listLeads(sampleDb, alice, { now: T0.getTime() }));
225 // A believable first record: 11 leads in 30 days, 6 answered or waiting under 5 minutes.
226 expect(listed.record).toMatchObject({ leads: 11, replied: 4, within_5_min_pct: 55 });
227 expect(listed.record.median_ms).toBe(200_000);
228 const desk = listed.leads;
225229 expect(desk).toHaveLength(SAMPLES.length);
226230 expect(desk[0]!.name).toBe("Maria Gonzalez");
227231 const waited = desk
src/actions.ts +8 −4
@@ -22,7 +22,8 @@ import {
2222 redraftUnsent,
2323 removeLead,
2424 send,
25 type DeskLead,
25 type Desk,
26 responseRecord,
2627 type LeadDetail,
2728 type NewLead,
2829 } from "./leads.ts";
@@ -75,8 +76,8 @@ const stamp = (at?: Date): string => (at ?? new Date()).toISOString();
7576 export function listLeads(
7677 db: Database,
7778 who: Who,
78 input: { limit?: number } = {},
79 ): Result<DeskLead[]> {
79 input: { limit?: number; now?: number } = {},
80 ): Result<Desk> {
8081 // Leads are a team's desk, not anyone's own: anything but "yes" is a no.
8182 if (permit(who, "lead", "list") !== "yes")
8283 return refuse(who, "Sign in to open the desk.", "You may not see the desk.");
@@ -84,7 +85,10 @@ export function listLeads(
8485 Math.max(Math.trunc(input.limit ?? 200) || 200, 1),
8586 500,
8687 );
87 return ok(desk(db, limit));
88 return ok({
89 record: responseRecord(db, input.now ?? Date.now()),
90 leads: desk(db, limit),
91 });
8892 }
8993
9094 /**
src/clock.ts +25
@@ -27,3 +27,28 @@ export function elapsed(ms: number): string {
2727 /** Milliseconds between two ISO stamps (or a stamp and now). */
2828 export const between = (from: string, to: string | number = Date.now()): number =>
2929 (typeof to === "number" ? to : Date.parse(to)) - Date.parse(from);
30
31 /** 40 sec, 3 min, 2 h 10 min: a median said plainly. */
32 export function span(ms: number): string {
33 const min = Math.round(ms / 60_000);
34 if (ms < 60_000) return `${Math.round(ms / 1000)} sec`;
35 if (min < 60) return `${min} min`;
36 const rest = min % 60;
37 return rest === 0 ? `${Math.floor(min / 60)} h` : `${Math.floor(min / 60)} h ${rest} min`;
38 }
39
40 /** The record in a line: the same words on the page and in the terminal. */
41 export function recordLine(record: {
42 days: number;
43 replied: number;
44 median_ms: number | null;
45 within_5_min_pct: number | null;
46 }): string {
47 if (
48 record.replied === 0 ||
49 record.median_ms === null ||
50 record.within_5_min_pct === null
51 )
52 return `No replies yet in the last ${record.days} days.`;
53 return `Median first reply: ${span(record.median_ms)} · ${record.within_5_min_pct}% answered within 5 minutes`;
54 }
src/leads.test.ts added +85
@@ -0,0 +1,85 @@
1 /**
2 * The response record: the median time to first reply and the share
3 * answered within five minutes, over the last 30 days, a waiting lead
4 * counted by its time so far.
5 */
6 import { expect, test } from "bun:test";
7 import { mkdtempSync } from "node:fs";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { openDb } from "./db.ts";
11 import { agent } from "./env.ts";
12 import { findLead, insertLead, readyFor, responseRecord, send } from "./leads.ts";
13 import { recordLine } from "./clock.ts";
14
15 const NOW = Date.parse("2026-10-30T12:00:00.000Z");
16 const M = 60_000;
17 const D = 86_400_000;
18 const fresh = () => openDb(mkdtempSync(join(tmpdir(), "app-leads-")));
19
20 /** A lead that asked `ago` ago, answered after `took` (or still waiting). */
21 function lead(db: ReturnType<typeof fresh>, ago: number, took?: number): void {
22 const id = insertLead(
23 db,
24 { name: "X", email: "[email protected]", phone: "", source: "website", message: "hi", consent: false },
25 new Date(NOW - ago).toISOString(),
26 agent,
27 );
28 if (took !== undefined) {
29 const ready = readyFor(db, id)!;
30 send(db, findLead(db, id)!, ready, ready.body, "alice", new Date(NOW - ago + took).toISOString(), agent);
31 }
32 }
33
34 test("no leads: nothing to average, and the line says so in words", () => {
35 const record = responseRecord(fresh(), NOW);
36 expect(record).toMatchObject({ leads: 0, replied: 0, median_ms: null, within_5_min_pct: null });
37 expect(recordLine(record)).toBe("No replies yet in the last 30 days.");
38 });
39
40 test("only waiting leads: still no replies, said in words", () => {
41 const db = fresh();
42 lead(db, 10 * M);
43 const record = responseRecord(db, NOW);
44 expect(record.replied).toBe(0);
45 expect(recordLine(record)).not.toMatch(/NaN|0%/);
46 });
47
48 test("median and the five-minute share, over replied leads", () => {
49 const db = fresh();
50 lead(db, 2 * D, 1 * M);
51 lead(db, 2 * D, 3 * M);
52 lead(db, 2 * D, 20 * M);
53 const record = responseRecord(db, NOW);
54 expect(record).toMatchObject({ leads: 3, replied: 3, median_ms: 3 * M, within_5_min_pct: 67 });
55 expect(recordLine(record)).toBe("Median first reply: 3 min · 67% answered within 5 minutes");
56 });
57
58 test("an even count takes the middle two", () => {
59 const db = fresh();
60 lead(db, D, 2 * M);
61 lead(db, D, 4 * M);
62 expect(responseRecord(db, NOW).median_ms).toBe(3 * M);
63 });
64
65 test("a waiting lead counts its time so far, against the record", () => {
66 const db = fresh();
67 lead(db, D, 1 * M);
68 lead(db, D, 2 * M);
69 const before = responseRecord(db, NOW);
70 lead(db, 3 * 60 * M); // waiting three hours
71 const after = responseRecord(db, NOW);
72 expect(before.within_5_min_pct).toBe(100);
73 expect(after.within_5_min_pct).toBe(67);
74 expect(after).toMatchObject({ leads: 3, replied: 2, median_ms: 2 * M });
75 lead(db, 5 * 60 * M);
76 // Waiting leads move the median too: 1, 2, 180 and 300 minutes.
77 expect(responseRecord(db, NOW).median_ms).toBe(91 * M);
78 });
79
80 test("leads older than 30 days are not in the record", () => {
81 const db = fresh();
82 lead(db, 31 * D, 40 * M);
83 lead(db, 1 * D, 1 * M);
84 expect(responseRecord(db, NOW)).toMatchObject({ leads: 1, median_ms: 1 * M, within_5_min_pct: 100 });
85 });
src/leads.ts +64
@@ -20,6 +20,7 @@ import {
2020 type Channel,
2121 type Source,
2222 } from "./drafts.ts";
23 import { GREEN_MS } from "./clock.ts";
2324 import type { Agent } from "./env.ts";
2425
2526 export type State = "new" | "contacted" | "qualified" | "lost";
@@ -67,6 +68,12 @@ export interface DeskLead extends Lead {
6768 readonly next_at: string | null;
6869 }
6970
71 /** The desk as the doors see it: the leads, and the record above them. */
72 export interface Desk {
73 readonly record: ResponseRecord;
74 readonly leads: DeskLead[];
75 }
76
7077 export interface NewLead {
7178 readonly name: string;
7279 readonly email: string;
@@ -80,6 +87,7 @@ type LeadRecord = Omit<Lead, "consent"> & { consent: number };
8087 const lead = (row: LeadRecord): Lead => ({ ...row, consent: row.consent === 1 });
8188
8289 const DAY_MS = 86_400_000;
90 const FIVE_MIN_MS = GREEN_MS;
8391 const later = (at: string, days: number): string =>
8492 new Date(Date.parse(at) + days * DAY_MS).toISOString();
8593
@@ -131,6 +139,62 @@ export function desk(db: Database, limit: number): DeskLead[] {
131139 }));
132140 }
133141
142 /** How fast the agent answers, over the last `days` days. */
143 export interface ResponseRecord {
144 readonly days: number;
145 /** Leads that arrived in the window. */
146 readonly leads: number;
147 /** Of those, how many have had their first reply. */
148 readonly replied: number;
149 /** Median time to first reply in ms; a waiting lead counts its time so far. Null with no leads. */
150 readonly median_ms: number | null;
151 /** Whole percent of those leads answered within five minutes (waiting ones too long already count against). Null with no leads. */
152 readonly within_5_min_pct: number | null;
153 }
154
155 export const RECORD_DAYS = 30;
156
157 /**
158 * The record over the last 30 days. A lead still waiting is measured by
159 * its time so far, so the numbers cannot improve by ignoring red clocks.
160 */
161 export function responseRecord(db: Database, now: number): ResponseRecord {
162 const since = new Date(now - RECORD_DAYS * DAY_MS).toISOString();
163 const waits = db
164 .query<{ created_at: string; replied_at: string | null }, [string]>(
165 "SELECT created_at, replied_at FROM lead WHERE created_at >= ?1",
166 )
167 .all(since)
168 .map((row) => ({
169 ms: Math.max(
170 0,
171 (row.replied_at === null ? now : Date.parse(row.replied_at)) -
172 Date.parse(row.created_at),
173 ),
174 replied: row.replied_at !== null,
175 }))
176 .sort((a, b) => a.ms - b.ms);
177 const n = waits.length;
178 const mid = Math.floor(n / 2);
179 return {
180 days: RECORD_DAYS,
181 leads: n,
182 replied: waits.filter((w) => w.replied).length,
183 median_ms:
184 n === 0
185 ? null
186 : n % 2 === 1
187 ? waits[mid]!.ms
188 : Math.round((waits[mid - 1]!.ms + waits[mid]!.ms) / 2),
189 within_5_min_pct:
190 n === 0
191 ? null
192 : Math.round(
193 (100 * waits.filter((w) => w.ms < FIVE_MIN_MS).length) / n,
194 ),
195 };
196 }
197
134198 /** A lead arrives at `at`, with its first reply drafted. Returns its id. */
135199 export function insertLead(
136200 db: Database,
src/mcp.ts +1 −1
@@ -43,7 +43,7 @@ export const tools: readonly Tool[] = [
4343 {
4444 name: "list_leads",
4545 description:
46 "The desk: every lead, newest first, with what is ready to approve.",
46 "The desk: your response record (median first reply, share answered within 5 minutes, last 30 days) and every lead, newest first, with what is ready to approve.",

The description changed, but no test covers the MCP result shape. Add one asserting that list_leads carries record.

4747 inputSchema: {
4848 type: "object",
4949 properties: { limit: { type: "integer", minimum: 1, maximum: 500 } },
src/openapi.ts +8 −3
@@ -14,6 +14,7 @@ import { contract } from "./contract.ts";
1414 import { description, title, version } from "./env.ts";
1515 import {
1616 AUDIT_ROW,
17 DESK,
1718 DESK_LEAD,
1819 ERROR,
1920 LEAD,
@@ -26,6 +27,7 @@ import { doorOf } from "./security.ts";
2627 // The shapes said once, under components, and referred to wherever they appear.
2728 const NAMED = new Map<Schema, string>([
2829 [LEAD, "Lead"],
30 [DESK, "Desk"],
2931 [DESK_LEAD, "DeskLead"],
3032 [MESSAGE, "Message"],
3133 [AUDIT_ROW, "AuditRow"],
@@ -34,7 +36,11 @@ const NAMED = new Map<Schema, string>([
3436 const named = (schema: Schema): Schema => {
3537 const name = NAMED.get(schema);
3638 if (name !== undefined) return { $ref: `#/components/schemas/${name}` };
37 return Object.fromEntries(
39 return within(schema);
40 };
41 /** A schema with the named shapes inside it referred to, itself written out. */
42 const within = (schema: Schema): Schema =>
43 Object.fromEntries(
3844 Object.entries(schema).map(([key, value]) => [
3945 key,
4046 typeof value === "object" && value !== null && !Array.isArray(value)
@@ -42,7 +48,6 @@ const named = (schema: Schema): Schema => {
4248 : value,
4349 ]),
4450 );
45 };
4651 const content = (schema: Schema) => ({
4752 "application/json": { schema: named(schema) },
4853 });
@@ -102,7 +107,7 @@ export function openapi(): Record<string, unknown> {
102107 paths,
103108 components: {
104109 schemas: Object.fromEntries(
105 [...NAMED].map(([schema, name]) => [name, schema]),
110 [...NAMED].map(([schema, name]) => [name, within(schema)]),
106111 ),
107112 },
108113 };
src/pages/desk.ts +5 −1
@@ -6,7 +6,8 @@
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 type { DeskLead } from "../leads.ts";
9 import { recordLine } from "../clock.ts";
10 import type { DeskLead, ResponseRecord } from "../leads.ts";
1011 import type { Agent } from "../env.ts";
1112 import type { Who } from "../who.ts";
1213
@@ -14,6 +15,7 @@ export function deskPage(input: {
1415 who: Who;
1516 agent: Agent;
1617 leads: readonly DeskLead[] | undefined;
18 record?: ResponseRecord | undefined;
1719 mayAdd: boolean;
1820 mayReset: boolean;
1921 notice?: string | undefined;
@@ -35,6 +37,7 @@ export function deskPage(input: {
3537 const waiting = leads.filter((l) => l.ready?.day === 0).length;
3638 const due = leads.filter((l) => l.ready !== null && l.ready.day > 0).length;
3739 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</p>`;
40 const record = input.record === undefined ? "" : `<p class="record">${escape(recordLine(input.record))}</p>`;
3841 const list =
3942 leads.length === 0
4043 ? `<p class="empty">No leads yet. New inquiries appear here the moment they arrive.</p>`
@@ -47,6 +50,7 @@ export function deskPage(input: {
4750 heading: "Desk",
4851 body: `<div id="desk" data-live="lead.added lead.changed">
4952 <div class="desk-head"><h1>Leads</h1>${summary}</div>
53 ${record}
5054 ${list}
5155 </div>
5256 ${input.mayAdd ? addForm : ""}
src/routes.ts +30 −3
@@ -138,6 +138,32 @@ export const DESK_LEAD: Schema = {
138138 },
139139 required: [...LEAD_REQUIRED, "ready", "next_at"],
140140 };
141 export const DESK: Schema = {
142 type: "object",
143 properties: {
144 record: {
145 type: "object",
146 description:
147 "How fast you answer, over the last 30 days. A lead still waiting counts its time so far.",
148 properties: {
149 days: { type: "integer" },
150 leads: { type: "integer", description: "Leads that arrived in the window." },
151 replied: { type: "integer", description: "Of those, how many have had a first reply." },
152 median_ms: {
153 type: ["integer", "null"],
154 description: "Median time to first reply, in milliseconds; null with no leads.",
155 },
156 within_5_min_pct: {
157 type: ["integer", "null"],
158 description: "Whole percent of leads answered (or waiting) under five minutes; null with no leads.",
159 },
160 },
161 required: ["days", "leads", "replied", "median_ms", "within_5_min_pct"],
162 },
163 leads: { type: "array", items: DESK_LEAD },

leads: { type: "array", items: DESK_LEAD } should render as a $ref to DeskLead. The generated contract inlines the object instead, so check the NAMED lookup in src/openapi.ts.

164 },
165 required: ["record", "leads"],
166 };
141167 const NEW_LEAD: Schema = {
142168 type: "object",
143169 properties: {
@@ -281,7 +307,8 @@ export const routes: readonly Route[] = [
281307 deskPage({
282308 who: c.who,
283309 agent: currentAgent(c.db),
284 leads: leads.ok ? leads.value : undefined,
310 leads: leads.ok ? leads.value.leads : undefined,
311 record: leads.ok ? leads.value.record : undefined,
285312 mayAdd: permit(c.who, "lead", "create") === "yes",
286313 mayReset: permit(c.who, "lead", "delete") === "yes",
287314 notice,
@@ -303,9 +330,9 @@ export const routes: readonly Route[] = [
303330 }),
304331 ),
305332 api: {
306 summary: "The desk: every lead, newest inquiry first.",
333 summary: "The desk: your response record, and every lead, newest inquiry first.",
307334 query: { limit: LIMIT },
308 answer: list(DESK_LEAD),
335 answer: DESK,
309336 },
310337 },
311338 {
src/server.test.ts +25 −4
@@ -162,7 +162,7 @@ test("GET /leads/:id: the page, or JSON for a script", async () => {
162162 const missing = await api("/leads/999999", {}, alice);
163163 expect(missing.status).toBe(404);
164164 expect(missing.headers.get("content-type")).toContain("text/html");
165 const list = (await (await api("/leads", {}, alice)).json()) as { id: number }[];
165 const list = ((await (await api("/leads", {}, alice)).json()) as { leads: { id: number }[] }).leads;
166166 expect(list.map((l) => l.id)).toContain(made.id);
167167 });
168168
@@ -240,9 +240,9 @@ test("POST /tick: the day turns for whoever may update leads; a stranger may not
240240 expect(Array.isArray(((await ticked.json()) as { leads: number[] }).leads)).toBe(true);
241241 expect((await api("/tick", { method: "POST" })).status).toBe(401);
242242 // The sample desk shows follow-ups already due.
243 const desk = (await (await api("/leads", {}, alice)).json()) as {
244 ready: { day: number } | null;
245 }[];
243 const desk = ((await (await api("/leads", {}, alice)).json()) as {
244 leads: { ready: { day: number } | null }[];
245 }).leads;
246246 expect(desk.some((l) => l.ready !== null && l.ready.day > 0)).toBe(true);
247247 });
248248
@@ -294,6 +294,12 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
294294 expect((await call("set_profile", { ...mine, license: "" }, root)).result.isError).toBe(true);
295295 expect((await call("set_profile", mine, root)).result.isError).toBeUndefined();
296296 expect(JSON.parse((await call("get_profile", {}, bob)).result.content[0].text)).toEqual({ id: 1, ...mine });
297 // The desk over MCP carries the response record beside the leads.
298 const deskText = (await call("list_leads", {}, bob)).result.content[0].text;
299 const mcpDesk = JSON.parse(deskText) as { record: { days: number; leads: number }; leads: unknown[] };
300 expect(mcpDesk.record.days).toBe(30);
301 expect(mcpDesk.record.leads).toBeGreaterThan(0);
302 expect(mcpDesk.leads.length).toBeGreaterThan(0);
297303 const refused = await call("add_lead", NEW);
298304 expect(refused.result.isError).toBe(true);
299305 const added = await call("add_lead", { ...NEW, name: "Over MCP" }, root);
@@ -522,3 +528,18 @@ test("/profile answers each identity as the contract table says", async () => {
522528 for (const method of ["PATCH", "DELETE", "PUT"])
523529 expect((await api("/profile", { method, ...jsonBody(body) }, root)).status).toBeGreaterThanOrEqual(400);
524530 });
531
532 test("the desk carries the response record: in the page, in JSON, and in the API's description", async () => {
533 const page = await (await api("/", {}, alice)).text();
534 expect(page).toMatch(/class="record">Median first reply: [^<]+ · \d+% answered within 5 minutes</);
535 const desk = (await (await api("/leads", {}, alice)).json()) as {
536 record: { days: number; leads: number; median_ms: number; within_5_min_pct: number };
537 };
538 expect(desk.record).toMatchObject({ days: 30 });
539 expect(desk.record.leads).toBeGreaterThanOrEqual(11);
540 expect(desk.record.within_5_min_pct).toBeGreaterThan(0);
541 const spec = (await (await api("/openapi.json", {}, root)).json()) as {
542 components: { schemas: { Desk: { properties: Record<string, unknown> } } };
543 };
544 expect(Object.keys(spec.components.schemas.Desk.properties)).toContain("record");
545 });
src/terminal.test.ts +11 −5
@@ -30,7 +30,7 @@ const type = (t: ReturnType<typeof terminal>, text: string): void => {
3030 test("enter opens the lead; it never sends", () => {
3131 const db = fresh();
3232 const t = terminal(db, alice);
33 const first = (listLeads(db, alice) as { ok: true; value: { id: number; name: string; message: string }[] }).value[0]!;
33 const first = (listLeads(db, alice) as { ok: true; value: { leads: { id: number; name: string; message: string }[] } }).value.leads[0]!;
3434 expect(read(t)).toContain("Maria Gonzalez");
3535 t.key("\r");
3636 const screen = read(t);
@@ -50,7 +50,7 @@ test("s sends what was shown, from the lead screen", () => {
5050 const t = terminal(db, alice);
5151 t.key("s"); // On the desk, s is nothing.
5252 t.key("\r");
53 const id = (listLeads(db, alice) as { ok: true; value: { id: number }[] }).value[0]!.id;
53 const id = (listLeads(db, alice) as { ok: true; value: { leads: { id: number }[] } }).value.leads[0]!.id;
5454 const shown = (getLead(db, alice, { id }) as { ok: true; value: { messages: { body: string }[] } }).value.messages[0]!.body;
5555 t.key("s");
5656 expect(read(t)).toContain("Sent to Maria Gonzalez.");
@@ -78,7 +78,7 @@ test("e edits the draft in place; ctrl-d sends the edit, esc sends nothing", ()
7878 t.key("\r");
7979 type(t, "Thursday?");
8080 t.key("\x04");
81 const id = (listLeads(db, alice) as { ok: true; value: { id: number }[] }).value[1]!.id;
81 const id = (listLeads(db, alice) as { ok: true; value: { leads: { id: number }[] } }).value.leads[1]!.id;
8282 const after = getLead(db, alice, { id });
8383 if (!after.ok) throw new Error(after.message);
8484 expect(after.value.messages[0]!.status).toBe("sent");
@@ -108,7 +108,7 @@ test("n logs a lead by hand, field by field, and opens it with its reply drafted
108108 expect(screen).toContain("Open house");
109109 expect(screen).toContain("by email");
110110 const listed = listLeads(db, alice);
111 expect(listed.ok && listed.value.some((l) => l.name === "Zoe Park" && l.source === "open_house" && !l.consent)).toBe(true);
111 expect(listed.ok && listed.value.leads.some((l) => l.name === "Zoe Park" && l.source === "open_house" && !l.consent)).toBe(true);
112112 // A bad field is said, and nothing is logged.
113113 t.key("\x1b");
114114 t.key("n");
@@ -247,7 +247,7 @@ test("an admin edits the profile one field at a time; it is saved, audited and r
247247 expect(read(t)).toContain("WA 99887");
248248 const saved = db.query<{ license: string }, []>("SELECT license FROM profile").get();
249249 expect(saved?.license).toBe("WA 99887");
250 const id = (listLeads(db, root) as { ok: true; value: { id: number; state: string }[] }).value.find((l) => l.state === "new")!.id;
250 const id = (listLeads(db, root) as { ok: true; value: { leads: { id: number; state: string }[] } }).value.leads.find((l) => l.state === "new")!.id;
251251 const lead = getLead(db, root, { id });
252252 expect(lead.ok && lead.value.messages[0]!.signature).toContain("WA 99887");
253253 const audit = db
@@ -268,3 +268,9 @@ test("a blank license typed in the terminal is refused and nothing is saved", ()
268268 expect(read(t)).toContain("license number is required");
269269 expect(db.query("SELECT * FROM profile").all()).toHaveLength(0);
270270 });
271
272 test("the desk header carries the response record", () => {
273 const t = terminal(fresh(), alice);
274 expect(read(t)).toContain("Median first reply:");
275 expect(read(t)).toContain("answered within 5 minutes");
276 });
src/terminal.ts +4 −4
@@ -30,7 +30,7 @@ import {
3030 sendReply,
3131 setState,
3232 } from "./actions.ts";
33 import { between, elapsed, tone } from "./clock.ts";
33 import { between, elapsed, recordLine, tone } from "./clock.ts";
3434 import { permit } from "./contract.ts";
3535 import { SOURCE_LABEL, SOURCES, channelFor } from "./drafts.ts";
3636 import { ssh, title, where } from "./env.ts";
@@ -131,7 +131,7 @@ export function terminal(
131131
132132 const leads = (): DeskLead[] => {
133133 const listed = listLeads(db, me);
134 return listed.ok ? listed.value : [];
134 return listed.ok ? listed.value.leads : [];
135135 };
136136 const lead = (id: number): LeadDetail | undefined => {
137137 const found = getLead(db, me, { id });
@@ -161,9 +161,9 @@ export function terminal(
161161 const listed = listLeads(db, me);
162162 if (!listed.ok)
163163 return [listed.message, "", dim("esc quit")];
164 const rows = listed.value;
164 const rows = listed.value.leads;
165165 cursor = Math.min(cursor, Math.max(0, rows.length - 1));
166 const lines: string[] = [];
166 const lines: string[] = [dim(recordLine(listed.value.record)), ""];
167167 if (rows.length === 0) lines.push(dim("No leads yet. Press n to log one."));
168168 rows.forEach((l, i) => {
169169 const next =
static/app.css +5
@@ -143,6 +143,11 @@ footer {
143143 .summary b {
144144 color: var(--color-fg);
145145 }
146 .record {
147 margin: 0 0 var(--space-3);
148 color: var(--color-muted);
149 min-height: 1.5em;
150 }
146151 .desk {
147152 list-style: none;
148153 margin: 0;

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs