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

One tap brings a fresh sample inquiry onto the desk so the meeting sees a lead answered inside a minute #26

Merged opened this

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

Merged

mason/speed-to-lead:mason/22-one-tap-brings-a-fresh-sample-inquiry-on → main 2 commits fork 2 threads · 2 unresolved

  • Merged. mason/22-one-tap-brings-a-fresh-sample-inquiry-on was merged into main as 7ba1f08.

Review

Sign in to review this change.
12 files changed +244 −8
README.md +12
@@ -47,12 +47,24 @@ what you see right after a restart. Do step 1 first.
4747 in your name, brokerage, license number, phone and email, and save. Every
4848 draft not yet sent takes it at once.
4949
50 8. Watch a lead arrive live. Press "Bring in a new inquiry", beside "Log a
51 lead by hand". A new person is at the top of the desk with a green clock
52 at 0:00 and a reply already drafted. Open the lead, press "Approve and
53 send", and see the clock stop well under a minute. Press the button again
54 for someone else; the seven made-up inquiries come in turn (some "Text
55 OK", some "Email only"), and restarting the samples clears them.
56
5057 Nothing is really sent in this prototype: "send" records the message in the
5158 lead's history and goes no further. To run the tour again, restart the
5259 samples (step 1).
5360
5461 ## How it works
5562
63 **Sample inquiries** arrive on demand from the desk button, `POST
64 /sample/inquiry` (JSON, 201), the MCP `new_sample_inquiry` tool, or `i` in the
65 terminal desk. They go through the same path as `POST /leads`, for anyone who
66 may add a lead. The turn is read off the desk, so it needs no extra state.
67
5668 **The desk** (the first screen) lists your leads, newest first. Links above
5769 the list narrow it: **Needs you** (a first reply or follow-up waiting),
5870 **In follow-up** (open, nothing waiting), **Closed** and **All**, each with
contract/openapi.json +28
@@ -462,6 +462,34 @@
462462 }
463463 }
464464 },
465 "/sample/inquiry": {
466 "post": {
467 "summary": "A sample inquiry arrives now, for a demonstration: the next of a fixed set, with its first reply drafted. Same as POST /leads.",
468 "operationId": "postSampleInquiry",
469 "responses": {
470 "201": {
471 "description": "A sample inquiry arrives now, for a demonstration: the next of a fixed set, with its first reply drafted. Same as POST /leads.",
472 "content": {
473 "application/json": {
474 "schema": {
475 "$ref": "#/components/schemas/Lead"
476 }
477 }
478 }
479 },
480 "default": {
481 "description": "{ error, message }: why not",
482 "content": {
483 "application/json": {
484 "schema": {
485 "$ref": "#/components/schemas/Error"
486 }
487 }
488 }
489 }
490 }
491 }
492 },
465493 "/profile": {
466494 "get": {
467495 "summary": "The agent whose desk this is: name, brokerage, license, phone and email. The AGENT_* environment variables until a profile is saved.",
src/actions.ts +9 −1
@@ -37,7 +37,7 @@ import {
3737 } from "./leads.ts";
3838 import { emit } from "./live.ts";
3939 import { currentAgent, storeAgent } from "./profile.ts";
40 import { seed } from "./sample.ts";
40 import { nextInquiry, seed } from "./sample.ts";
4141 import type { Who } from "./who.ts";
4242
4343 export type Failure = "signin_required" | "forbidden" | "not_found" | "invalid";
@@ -238,6 +238,14 @@ function add(
238238 return ok(added);
239239 }
240240
241 /** The next sample inquiry arrives now, by the same path as any lead. */
242 export const addSampleInquiry = (
243 db: Database,
244 who: Who,
245 at?: Date,
246 ): Result<LeadDetail> =>
247 audited(db, who, "lead", "create", undefined, add(db, who, nextInquiry(db), at));
outdated

The new door is not in src/contract.test.ts. Add addSampleInquiry there, acting as each identity against the lead/create cell. Also drop the needless spread: pass nextInquiry(db) directly.

248
241249 /**
242250 * Approve and send what is ready for this lead — the first reply, or the
243251 * earliest touch that is due — as drafted, or as the agent edited it.
src/contract.test.ts +7 −1
@@ -10,6 +10,7 @@ import { tmpdir } from "node:os";
1010 import { join } from "node:path";
1111 import {
1212 addLead,
13 addSampleInquiry,
1314 deleteLead,
1415 getAudit,
1516 getLead,
@@ -85,7 +86,12 @@ const doors: Record<
8586 Partial<Record<Verb, (who: Who, authorId: string) => boolean>>
8687 > = {
8788 lead: {
88 create: (who) => addLead(db, who, NEW).ok,
89 create: (who) => {
90 const added = addLead(db, who, NEW).ok;
91 // The sample inquiry is the same cell, through its own door.
92 expect(addSampleInquiry(db, who).ok).toBe(added);
93 return added;
94 },
8995 list: (who) => listLeads(db, who).ok,
9096 read: (who, authorId) => getLead(db, who, { id: aLead(authorId) }).ok,
9197 update: (who, authorId) =>
src/leads.ts +2 −2
@@ -116,14 +116,14 @@ export interface Desk {
116116 readonly leads: DeskLead[];
117117 }
118118
119 export interface NewLead {
119 export type NewLead = {
120120 readonly name: string;
121121 readonly email: string;
122122 readonly phone: string;
123123 readonly source: Source;
124124 readonly message: string;
125125 readonly consent: boolean;
126 }
126 };
127127
128128 type LeadRecord = Omit<Lead, "consent"> & { consent: number };
129129 const lead = (row: LeadRecord): Lead => ({ ...row, consent: row.consent === 1 });
src/mcp.ts +8
@@ -9,6 +9,7 @@
99 import type { Database } from "bun:sqlite";
1010 import {
1111 addLead,
12 addSampleInquiry,
1213 getLead,
1314 getProfile,
1415 listLeads,
@@ -87,6 +88,13 @@ export const tools: readonly Tool[] = [
8788 },
8889 run: (db, who, args) => addLead(db, who, args),
8990 },
91 {
92 name: "new_sample_inquiry",
93 description:
94 "For a demonstration: the next of a fixed set of made-up inquiries arrives now, with its clock at 0:00 and its first reply drafted. Nothing is sent.",
95 inputSchema: { type: "object", properties: {} },
96 run: (db, who) => addSampleInquiry(db, who),
97 },
9098 {
9199 name: "send_reply",
92100 description:
src/pages/desk.ts +1 −1
@@ -80,7 +80,7 @@ export function deskPage(input: {
8080 ${views}
8181 ${list}
8282 </div>
83 ${input.mayAdd ? addForm : ""}
83 ${input.mayAdd ? `<form class="reset" method="post" action="/sample/inquiry"><button class="button button-quiet">Bring in a new inquiry</button></form>${addForm}` : ""}
8484 ${
8585 input.mayReset
8686 ? `<form class="reset" method="post" action="/sample/reset"><button class="button button-quiet">Restart the sample leads from now</button></form>`
src/routes.ts +18
@@ -15,6 +15,7 @@ import type { Database } from "bun:sqlite";
1515 import { existsSync, readFileSync } from "node:fs";
1616 import {
1717 addLead,
18 addSampleInquiry,
1819 deleteLead,
1920 activity,
2021 getAudit,
@@ -525,6 +526,23 @@ export const routes: readonly Route[] = [
525526 },
526527 },
527528 },
529 {
530 method: "POST",
531 path: "/sample/inquiry",
532 handle: (c) =>
533 posted(
534 c,
535 () => addSampleInquiry(c.db, c.who),
536 () => ({ to: "/", said: "A new inquiry is on the desk, its clock running." }),
537 201,
538 ),
539 api: {
540 summary:
541 "A sample inquiry arrives now, for a demonstration: the next of a fixed set, with its first reply drafted. Same as POST /leads.",
542 answer: LEAD,
543 status: 201,
544 },
545 },
528546 {
529547 method: "POST",
530548 path: "/sample/reset",
src/sample.test.ts added +86
@@ -0,0 +1,86 @@
1 import { expect, test } from "bun:test";
2 import { mkdtempSync } from "node:fs";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { addSampleInquiry, getLead, listLeads, resetSample } from "./actions.ts";
6 import { openDb } from "./db.ts";
7 import { INQUIRIES, SAMPLES } from "./sample.ts";
8 import { terminal, plain } from "./terminal.ts";
9 import type { Who } from "./who.ts";
10
11 const alice: Who = { role: "user", id: "u1", name: "alice" };
12 const root: Who = { role: "admin", id: "u0", name: "root" };
13 const anon: Who = { role: "anon" } as Who;
14 const fresh = () => openDb(mkdtempSync(join(tmpdir(), "app-inq-")));
15 const names = (db: ReturnType<typeof fresh>): string[] => {
16 const r = listLeads(db, alice);
17 return r.ok ? r.value.leads.map((l) => l.name) : [];
18 };
19
20 test("the set is large, fictitious, varied and apart from the seeded leads", () => {
21 expect(INQUIRIES.length).toBeGreaterThanOrEqual(6);
22 const taken = new Set(SAMPLES.map((s) => s.name));
23 for (const i of INQUIRIES) {
24 expect(taken.has(i.name)).toBe(false);
25 expect(i.email.endsWith("@example.com")).toBe(true);
26 expect(i.phone).toContain("555-02");
27 }
28 expect(INQUIRIES.some((i) => i.consent)).toBe(true);
29 expect(INQUIRIES.some((i) => !i.consent)).toBe(true);
30 expect(new Set(INQUIRIES.map((i) => i.source)).size).toBeGreaterThanOrEqual(3);
31 });
32
33 test("one press adds one lead with a fresh clock and a draft; presses differ until the set is used", () => {
34 const db = fresh();
35 const seen = new Set<string>();
36 for (let n = 1; n <= INQUIRIES.length; n++) {
37 const added = addSampleInquiry(db, alice);
38 expect(added.ok).toBe(true);
39 if (!added.ok) return;
40 expect(names(db)).toHaveLength(n);
41 expect(added.value.messages.some((m) => m.day === 0 && m.status === "draft")).toBe(true);
42 seen.add(added.value.name);
43 }
44 expect(seen.size).toBe(INQUIRIES.length);
45 // Used up: it comes round again, and still adds exactly one.
46 const again = addSampleInquiry(db, alice);
47 expect(again.ok).toBe(true);
48 expect(names(db)).toHaveLength(INQUIRIES.length + 1);
49 });
50
51 test("consent decides the channel of the drafted reply", () => {
52 const db = fresh();
53 for (const _ of INQUIRIES) {
54 const added = addSampleInquiry(db, alice);
55 if (!added.ok) throw new Error("refused");
56 const lead = getLead(db, alice, { id: added.value.id });
57 if (!lead.ok) throw new Error("missing");
58 const want = INQUIRIES.find((i) => i.name === lead.value.name)!.consent ? "text" : "email";
59 expect(lead.value.messages.find((m) => m.day === 0)!.channel).toBe(want);
60 }
61 });
62
63 test("anon is refused and nothing is added", () => {
64 const db = fresh();
65 const r = addSampleInquiry(db, anon);
66 expect(r.ok).toBe(false);
67 expect(names(db)).toHaveLength(0);
68 });
69
70 test("restarting the samples clears the inquiries and the turn starts over", () => {
71 const db = fresh();
72 const first = addSampleInquiry(db, alice);
73 addSampleInquiry(db, alice);
74 expect(resetSample(db, root).ok).toBe(true);
75 expect(names(db)).toHaveLength(SAMPLES.length);
76 const again = addSampleInquiry(db, alice);
77 expect(again.ok && first.ok && again.value.name === first.value.name).toBe(true);
78 });
79
80 test("the terminal key adds one", () => {
81 const db = fresh();
82 const t = terminal(db, alice);
83 t.key("i");
84 expect(names(db)).toHaveLength(1);
85 expect(t.screen(100).map(plain).join("\n")).toContain("clock is running");
86 });
src/sample.ts +48
@@ -112,3 +112,51 @@ export function seedOnce(db: Database, now = new Date()): void {
112112 );
113113 })();
114114 }
115
116 /**
117 * Inquiries that arrive on demand, for a meeting: distinct from the twelve
118 * above, every number a 555-02xx and every address example.com.
119 */
120 const inquiry = (
121 name: string,
122 phone: string,
123 source: Source,
124 consent: boolean,
125 message: string,
126 ): NewLead => ({
127 name,
128 email: `${name.toLowerCase().replace(/[^a-z]+/g, ".")}@example.com`,
129 phone,
130 source,
131 message,
132 consent,
133 });
134
135 export const INQUIRIES: readonly NewLead[] = [
136 inquiry("Nadia Farouk", "(206) 555-0201", "zillow", true, "Is 55 Cedar Way still on the market? We could see it tomorrow evening."),
137 inquiry("Oliver Grant", "(206) 555-0202", "website", false, "Thinking of selling our duplex on Pine St this summer. Could you tell us what it might fetch?"),
138 inquiry("Sofia Marin", "(206) 555-0203", "open_house", true, "We toured the Willow Ct open house today and loved it. What would an offer need to look like?"),
139 inquiry("Kenji Watanabe", "(206) 555-0204", "referral", false, "Our neighbour Priya recommended you. We're relocating for work in September and need a 4-bedroom."),
140 inquiry("Bridget Doyle", "(206) 555-0205", "zillow", true, "Does 310 Orchard Ln allow a home office addition? We're pre-approved to $620k."),
141 inquiry("Samuel Osei", "(206) 555-0206", "website", true, "First-time buyer here. Can we book a call this week to talk about the process?"),
142 inquiry("Ingrid Larsen", "(206) 555-0207", "open_house", false, "Signed in at the Elm St open house. Could you send the school zone and tax details?"),
143 ];
144
145 /**
146 * The next inquiry in turn, read off the desk and not remembered: the first
147 * that is not on it, or, when all are, the one that has been there longest.
148 * Restarting the samples clears the desk, so the turn starts over with it.
149 */
150 export function nextInquiry(db: Database): NewLead {
151 const placed = new Map(
152 db
153 .query<{ email: string; id: number }, []>(
154 "SELECT email, MIN(id) AS id FROM lead GROUP BY email",
155 )
156 .all()
157 .map((row) => [row.email, row.id] as const),
158 );
159 const fresh = INQUIRIES.find((i) => !placed.has(i.email));
160 if (fresh !== undefined) return fresh;
161 return [...INQUIRIES].sort((a, b) => placed.get(a.email)! - placed.get(b.email)!)[0]!;
162 }
src/server.test.ts +15
@@ -285,6 +285,7 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
285285 "list_leads",
286286 "get_lead",
287287 "add_lead",
288 "new_sample_inquiry",
288289 "send_reply",
289290 "mark_lead",
290291 "get_profile",
@@ -642,3 +643,17 @@ test("a closed lead is put back in follow-ups from its page and the API; other s
642643 (await api(`/leads/${one.id}/state`, { method: "POST", ...jsonBody({ state: "reopen" }) }, alice)).status,
643644 ).toBe(422);
644645 });
646
647 test("POST /sample/inquiry: the button and the JSON route make the same lead; anon is refused", async () => {
648 const page = await api("/sample/inquiry", { method: "POST", body: form({}) }, alice);
649 expect(page.status).toBe(200);
650 expect(await (await api("/", {}, alice)).text()).toContain('action="/sample/inquiry"');
651 const res = await api("/sample/inquiry", { method: "POST", ...jsonBody({}) }, alice);
652 expect(res.status).toBe(201);
653 const lead = (await res.json()) as Record<string, unknown>;
654 expect(Object.keys(lead).sort()).toEqual(
655 Object.keys(await (await api("/leads/" + lead.id, { headers: { accept: "application/json" } }, alice)).json() as object).sort(),
656 );
657 const refused = await api("/sample/inquiry", { method: "POST", ...jsonBody({}) }, {});
658 expect([401, 403]).toContain(refused.status);
659 });
src/terminal.ts +10 −3
@@ -5,7 +5,7 @@
55 * may — the hints only leave out keys the table would refuse.
66 *
77 * Screens:
8 * desk j/k move · enter open · f view (needs/open/closed/all) · / find by name, email or phone · n log a lead · p profile · a activity (admin) · R restart samples (admin) · esc quit
8 * desk j/k move · enter open · f view (needs/open/closed/all) · / find by name, email or phone · n log a lead · i new sample inquiry · p profile · a activity (admin) · R restart samples (admin) · esc quit
99 * lead s approve and send · e edit, then send · q qualified · x lost ·
1010 * D remove (admin) · esc back
1111 * edit type; enter is a new line · ctrl-d approve and send · esc cancel
@@ -24,6 +24,7 @@ import type { Database } from "bun:sqlite";
2424 import {
2525 activity,
2626 addLead,
27 addSampleInquiry,
2728 deleteLead,
2829 getLead,
2930 getProfile,
@@ -211,7 +212,7 @@ export function terminal(
211212 lines.push(
212213 "",
213214 dim(
214 `j/k move · enter open · f view · / find · n log a lead · p profile${admin() ? " · a activity" : ""}${admin() ? " · R restart the samples" : ""} · esc quit`,
215 `j/k move · enter open · f view · / find · n log a lead · i sample inquiry · p profile${admin() ? " · a activity" : ""}${admin() ? " · R restart the samples" : ""} · esc quit`,
215216 ),
216217 );
217218 return lines;
@@ -443,7 +444,13 @@ export function terminal(
443444 } else if (input === "/") view = { name: "search", typed: q };
444445 else if (input === "n")
445446 view = { name: "add", step: 0, typed: "", fields: {} };
446 else if (input === "p") view = { name: "profile" };
447 else if (input === "i") {
448 const added = addSampleInquiry(db, me);
449 said = added.ok
450 ? `${added.value.name} is on the desk; the clock is running.`
451 : added.message;
452 if (added.ok) cursor = 0;
453 } else if (input === "p") view = { name: "profile" };
447454 else if (input === "a")
448455 view = { name: "activity", sentOnly: false, before: [] };
449456 else if (input === "R")

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs