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

After approving a reply, one tap takes the agent to the next lead that needs them #27

Merged opened this

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

Merged

mason/speed-to-lead:mason/24-after-approving-a-reply-one-tap-takes-th → main 2 commits fork

  • Merged. mason/24-after-approving-a-reply-one-tap-takes-th was merged into main as ce481bc.

Review

Sign in to review this change.
10 files changed +385 −15
README.md +6 −1
@@ -32,7 +32,12 @@ what you see right after a restart. Do step 1 first.
3232 3. Answer a red lead. **Tom Becker** has waited hours, so his clock is
3333 red. Tap his name: his question is on one side, the reply already
3434 written for him on the other. Press "Approve and send". His clock stops
35 and shows how long he waited.
35 and shows how long he waited, and under "Sent." a "Next: <name>, waiting
36 <clock>" link takes you to the lead who has waited longest among those
37 that need you (the desk's "Needs you" view); when none is left it says
38 so and links back to the desk. Any page that needs nothing from you shows
39 the same link. In the terminal, `]` opens the next lead; `POST
40 /leads/:id/reply` and the `send_reply` tool return it as `next`.
3641 4. Change the words first. Open **Lena Novak**, another red lead. Press
3742 "Edit", change a sentence in the text box, then approve and send it.
3843 5. See who may be texted. **David Chen** carries an "Email only" badge: he
contract/openapi.json +98 −1
@@ -345,7 +345,104 @@
345345 "content": {
346346 "application/json": {
347347 "schema": {
348 "$ref": "#/components/schemas/Lead"
348 "type": "object",
349 "properties": {
350 "id": {
351 "type": "integer"
352 },
353 "name": {
354 "type": "string",
355 "minLength": 1,
356 "maxLength": 120
357 },
358 "email": {
359 "type": "string",
360 "format": "email"
361 },
362 "phone": {
363 "type": "string"
364 },
365 "source": {
366 "enum": [
367 "zillow",
368 "website",
369 "open_house",
370 "referral"
371 ]
372 },
373 "message": {
374 "type": "string",
375 "minLength": 1,
376 "maxLength": 2000
377 },
378 "consent": {
379 "type": "boolean",
380 "description": "Prior written consent to be texted. Without it, only email."
381 },
382 "state": {
383 "enum": [
384 "new",
385 "contacted",
386 "qualified",
387 "lost"
388 ]
389 },
390 "created_at": {
391 "type": "string",
392 "format": "date-time"
393 },
394 "replied_at": {
395 "type": [
396 "string",
397 "null"
398 ],
399 "format": "date-time"
400 },
401 "updated_at": {
402 "type": "string",
403 "format": "date-time"
404 },
405 "messages": {
406 "type": "array",
407 "items": {
408 "$ref": "#/components/schemas/Message"
409 }
410 },
411 "next": {
412 "type": [
413 "object",
414 "null"
415 ],
416 "description": "The lead that has waited longest among those that need you now (the desk's Needs you view); null when none is left.",
417 "properties": {
418 "id": {
419 "type": "integer"
420 },
421 "name": {
422 "type": "string"
423 }
424 },
425 "required": [
426 "id",
427 "name"
428 ]
429 }
430 },
431 "required": [
432 "id",
433 "name",
434 "email",
435 "phone",
436 "source",
437 "message",
438 "consent",
439 "state",
440 "created_at",
441 "replied_at",
442 "updated_at",
443 "messages",
444 "next"
445 ]
349446 }
350447 }
351448 }
src/actions.ts +35
@@ -25,6 +25,7 @@ import {
2525 reopen,
2626 MAX_QUERY,
2727 insertLead,
28 nextNeeding,
2829 readyFor,
2930 redraftUnsent,
3031 removeLead,
@@ -34,6 +35,7 @@ import {
3435 type Desk,
3536 type LeadDetail,
3637 type NewLead,
38 type NextLead,
3739 } from "./leads.ts";
3840 import { emit } from "./live.ts";
3941 import { currentAgent, storeAgent } from "./profile.ts";
@@ -270,6 +272,39 @@ export const sendReply = (
270272 );
271273 };
272274
275 /**
276 * The lead that has waited longest among those that need the agent, other
277 * than `except`. Reading it is `list lead`, as the desk is; whoever may not
278 * list gets null, never a refusal — there is just no next to offer.
279 */
280 export const nextLead = (
281 db: Database,
282 who: Who,
283 input: { except: number },
284 ): NextLead | null =>
285 permit(who, "lead", "list") === "yes" ? nextNeeding(db, input.except) : null;
286
287 /** A sent reply, and the lead to open next: the id and name, or null. */
288 export type Approved = LeadDetail & {
289 readonly next: { readonly id: number; readonly name: string } | null;
290 };
291
292 /** `sendReply`, and which lead needs the agent after it. */
293 export const approveReply = (
294 db: Database,
295 who: Who,
296 input: { id: number; body?: string | undefined },
297 at?: Date,
298 ): Result<Approved> => {
299 const sent = sendReply(db, who, input, at);
300 if (!sent.ok) return sent;
301 const next = nextLead(db, who, { except: input.id });
302 return ok({
303 ...sent.value,
304 next: next === null ? null : { id: next.id, name: next.name },
305 });
306 };
307
273308 function reply(
274309 db: Database,
275310 who: Who,
src/leads.ts +24
@@ -215,6 +215,30 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] {
215215 }));
216216 }
217217
218 /** The lead that needs the agent next, and since when it has. */
219 export interface NextLead {
220 readonly id: number;
221 readonly name: string;
222 /** When the reply began to wait: the inquiry, or the day the follow-up came due. */
223 readonly since: string;
224 }
225
226 /**
227 * Of the leads in the desk's "Needs you" view (`inView`), other than
228 * `exceptId`, the one that has waited longest; null when none.
229 */
230 export function nextNeeding(db: Database, exceptId: number): NextLead | null {
231 let best: NextLead | null = null;
232 for (const l of desk(db, -1)) {
233 if (l.id === exceptId || !inView(l, "needs")) continue;
234 const since = readyFor(db, l.id)?.due_at;
235 if (since === undefined) continue;
236 if (best === null || Date.parse(since) < Date.parse(best.since))
237 best = { id: l.id, name: l.name, since };
238 }
239 return best;
240 }
241
218242 /** How fast the agent answers, over the last `days` days. */
219243 export interface ResponseRecord {
220244 readonly days: number;
src/mcp.ts +3 −3
@@ -14,7 +14,7 @@ import {
1414 getProfile,
1515 listLeads,
1616 saveProfile,
17 sendReply,
17 approveReply,
1818 setState,
1919 type Result,
2020 } from "./actions.ts";
@@ -98,14 +98,14 @@ export const tools: readonly Tool[] = [
9898 {
9999 name: "send_reply",
100100 description:
101 "Approve and send what is ready for a lead (the first reply or a due follow-up), as drafted or with body as edited. Only call this when the person has approved the words.",
101 "Approve and send what is ready for a lead (the first reply or a due follow-up), as drafted or with body as edited. The answer says which lead is next (`next`: id and name, or null): the one that has waited longest among those that need the person now. Only call this when the person has approved the words.",
102102 inputSchema: {
103103 type: "object",
104104 properties: { id: { type: "integer" }, body: { type: "string" } },
105105 required: ["id"],
106106 },
107107 run: (db, who, args) =>
108 sendReply(db, who, {
108 approveReply(db, who, {
109109 id: Number(args.id),
110110 body: typeof args.body === "string" ? args.body : undefined,
111111 }),
src/next.test.ts added +161
@@ -0,0 +1,161 @@
1 /**
2 * After a send, the way on: the lead that has waited longest among those
3 * that need the agent, on the page, in the JSON, over MCP and in the terminal.
4 */
5 import { afterAll, expect, test } from "bun:test";
6 import { mkdtempSync } from "node:fs";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { approveReply, nextLead } from "./actions.ts";
10 import { openDb } from "./db.ts";
11 import { insertLead } from "./leads.ts";
12 import { agent } from "./env.ts";
13 import { serve } from "./server.ts";
14 import { plain, terminal } from "./terminal.ts";
15 import { sign } from "./who.ts";
16 import type { Who } from "./who.ts";
17
18 const KEY = "a-key-only-the-forge-holds";
19 const server = serve({
20 port: 0,
21 dataDir: mkdtempSync(join(tmpdir(), "app-next-")),
22 identityKey: KEY,
23 sample: false,
24 });
25 const base = `http://${server.hostname}:${server.port}`;
26 afterAll(() => server.stop(true));
27
28 let grants = 0;
29 const api = (path: string, init: RequestInit = {}) => {
30 const identity = `u${++grants}|alice|user|${Date.now() + 60_000}`;
31 return fetch(base + path, {
32 ...init,
33 headers: {
34 ...(init.headers as Record<string, string>),
35 "x-forge-identity": identity,
36 "x-forge-signature": sign(identity, KEY),
37 },
38 });
39 };
40 const post = (path: string, body: unknown = {}) =>
41 api(path, {
42 method: "POST",
43 headers: { "content-type": "application/json" },
44 body: JSON.stringify(body),
45 });
46 const arrive = async (name: string): Promise<number> => {
47 await Bun.sleep(3);
48 const made = await post("/leads", {
49 name,
50 email: "[email protected]",
51 source: "zillow",
52 message: "Is it still available?",
53 });
54 return ((await made.json()) as { id: number }).id;
55 };
56
57 test("the next lead is the longest-waiting one left; the last gives null, and the page says so", async () => {
58 const a = await arrive("Ada <b>First</b>");
59 const b = await arrive("Bea Second");
60 const c = await arrive("Cy Third");
61
62 const sentA = (await (await post(`/leads/${a}/reply`)).json()) as {
63 next: { id: number; name: string } | null;
64 };
65 expect(sentA.next).toEqual({ id: b, name: "Bea Second" });
66
67 // The page agrees with the JSON: Sent., then the link to the same lead.
68 const pageA = await (await api(`/leads/${a}`)).text();
69 expect(pageA).toMatch(new RegExp(`Next: <a href="/leads/${b}">Bea Second, waiting \\d`));
70 expect(pageA).not.toContain("Nothing else needs you");
71
72 const sentB = (await (await post(`/leads/${b}/reply`)).json()) as { next: { id: number } | null };
73 expect(sentB.next?.id).toBe(c);
74 // The name is escaped wherever it appears.
75 const pageB = await (await api(`/leads/${b}`)).text();
76 expect(pageB).toContain(`href="/leads/${c}">Cy Third, waiting`);
77
78 const sentC = (await (await post(`/leads/${c}/reply`)).json()) as { next: unknown };
79 expect(sentC.next).toBeNull();
80 const pageC = await (await api(`/leads/${c}`)).text();
81 expect(pageC).toContain("Nothing else needs you right now.");
82 expect(pageC).toContain('href="/?show=needs"');
83 });
84
85 test("a closed lead's page shows the link; a lead that needs you does not", async () => {
86 const a = await arrive("Dee <i>Closed</i>");
87 const b = await arrive("Eve Waiting");
88 await post(`/leads/${a}/state`, { state: "lost" });
89 const closed = await (await api(`/leads/${a}`)).text();
90 expect(closed).toContain(`Next: <a href="/leads/${b}">Eve Waiting, waiting`);
91 const waiting = await (await api(`/leads/${b}`)).text();
92 expect(waiting).not.toContain("Next: <a");
93 // The next lead's name is escaped.
94 await post(`/leads/${b}/state`, { state: "lost" });
95 const c = await arrive("<script>alert(1)</script>");
96 const page = await (await api(`/leads/${a}`)).text();
97 expect(page).toContain(`&lt;script&gt;alert(1)&lt;/script&gt;, waiting`);
98 expect(page).not.toContain("<script>alert(1)");
99 expect(c).toBeGreaterThan(b);
100 });
101
102 test("a stranger is offered no next", async () => {
103 const db = openDb(mkdtempSync(join(tmpdir(), "app-next-")));
104 insertLead(db, { name: "Fay", email: "[email protected]", phone: "", source: "zillow", message: "Hi", consent: false }, new Date().toISOString(), agent);
105 expect(nextLead(db, { role: "anon" } as Who, { except: 0 })).toBeNull();
106 expect(nextLead(db, { role: "user", id: "u1", name: "alice" }, { except: 0 })?.name).toBe("Fay");
107 });
108
109 test("a follow-up that has come due counts, by the day it came due", () => {
110 const db = openDb(mkdtempSync(join(tmpdir(), "app-next-")));
111 const alice: Who = { role: "user", id: "u1", name: "alice" };
112 const lead = (name: string, at: Date) =>
113 insertLead(db, { name, email: "[email protected]", phone: "", source: "zillow", message: "Hi", consent: false }, at.toISOString(), agent);
114 const old = lead("Old", new Date(Date.now() - 10 * 86_400_000));
115 const mid = lead("Mid", new Date(Date.now() - 2 * 3_600_000));
116 const cur = lead("Cur", new Date(Date.now() - 60_000));
117 // Old was answered a week ago; its day-1 touch has been due since.
118 const sentAt = new Date(Date.now() - 8 * 86_400_000);
119 expect(approveReply(db, alice, { id: old }, sentAt).ok).toBe(true);
120 db.query("UPDATE message SET status = 'due' WHERE lead_id = ?1 AND day = 1").run(old);
121 expect(nextLead(db, alice, { except: cur })?.id).toBe(old);
122 expect(nextLead(db, alice, { except: old })?.id).toBe(mid);
123 });
124
125 test("the MCP reply says which lead is next", async () => {
126 const a = await arrive("Gus Sent");
127 const b = await arrive("Hal Next");
128 const call = await post("/mcp", {
129 jsonrpc: "2.0",
130 id: 1,
131 method: "tools/call",
132 params: { name: "send_reply", arguments: { id: a } },
133 });
134 const text = ((await call.json()) as any).result.content[0].text as string;
135 expect(JSON.parse(text).next.id).toBeLessThanOrEqual(b);
136 const listed = await (await post("/mcp", { jsonrpc: "2.0", id: 2, method: "tools/list" })).json();
137 const tool = (listed as any).result.tools.find((t: any) => t.name === "send_reply");
138 expect(tool.description).toContain("next");
139 });
140
141 test("in the terminal, ] opens the next lead that needs you", () => {
142 const db = openDb(mkdtempSync(join(tmpdir(), "app-next-")));
143 const alice: Who = { role: "user", id: "u1", name: "alice" };
144 const first = insertLead(db, { name: "Ida First", email: "[email protected]", phone: "", source: "zillow", message: "Hi", consent: false }, new Date(Date.now() - 600_000).toISOString(), agent);
145 insertLead(db, { name: "Jo Second", email: "[email protected]", phone: "", source: "zillow", message: "Hi", consent: false }, new Date(Date.now() - 300_000).toISOString(), agent);
146 const t = terminal(db, alice);
147 const read = () => t.screen(100).map(plain).join("\n");
148 t.key("\r"); // newest first: opens Jo
149 expect(read()).toContain("Jo Second");
150 expect(read()).toContain("] next that needs you");
151 t.key("s");
152 expect(read()).toContain("Next: Ida First (])");
153 t.key("]");
154 expect(read()).toContain("Ida First");
155 t.key("s");
156 expect(read()).toContain("Nothing else needs you right now.");
157 t.key("]");
158 expect(read()).toContain("Nothing else needs you right now.");
159 expect(read()).not.toContain("] next that needs you");
160 expect(first).toBeGreaterThan(0);
161 });
src/pages/lead.ts +15 −2
@@ -6,7 +6,8 @@
66
77 import { channelFor, MAX_BODY } from "../drafts.ts";
88 import { escape } from "../http.ts";
9 import type { LeadDetail, Message } from "../leads.ts";
9 import { elapsed, between } from "../clock.ts";
10 import type { LeadDetail, Message, NextLead } from "../leads.ts";
1011 import type { Agent } from "../env.ts";
1112 import type { Who } from "../who.ts";
1213 import { layout } from "./layout.ts";
@@ -26,9 +27,12 @@ export function leadPage(input: {
2627 agent: Agent;
2728 lead: LeadDetail;
2829 mayUpdate: boolean;
30 /** The lead that has waited longest among those that need the agent; null when none. */
31 next: NextLead | null;
32 now: number;
2933 notice?: string | undefined;
3034 }): string {
31 const { who, agent, lead, mayUpdate, notice } = input;
35 const { who, agent, lead, mayUpdate, next, now, notice } = input;
3236 const ready = lead.messages.find(
3337 (m) => m.status === "draft" || m.status === "due",
3438 );
@@ -116,6 +120,14 @@ export function leadPage(input: {
116120 </section>`
117121 : "";
118122
123 // A page that needs nothing from the agent never leaves them stuck.
124 const onward =
125 ready !== undefined
126 ? ""
127 : next === null
128 ? `<p class="next">Nothing else needs you right now. <a href="/?show=needs">Back to the desk</a></p>`
129 : `<p class="next">Next: <a href="/leads/${next.id}">${escape(next.name)}, waiting ${elapsed(between(next.since, now))}</a></p>`;
130
119131 return layout({
120132 who,
121133 agent,
@@ -124,6 +136,7 @@ export function leadPage(input: {
124136 heading: lead.name,
125137 body: `<div id="lead" data-live="lead.changed">
126138 <p><a class="backlink" href="/">← All leads</a></p>
139 ${onward}
127140 <header class="lead-head">
128141 <div>
129142 <h1>${escape(lead.name)}</h1>
src/routes.ts +20 −3
@@ -25,7 +25,8 @@ import {
2525 listLeads,
2626 resetSample,
2727 saveProfile,
28 sendReply,
28 approveReply,
29 nextLead,
2930 setState,
3031 tick,
3132 type Failure,
@@ -130,6 +131,20 @@ export const LEAD: Schema = {
130131 properties: { ...LEAD_FIELDS, messages: { type: "array", items: MESSAGE } },
131132 required: [...LEAD_REQUIRED, "messages"],
132133 };
134 export const APPROVED: Schema = {
135 type: "object",
136 properties: {
137 ...LEAD.properties,
138 next: {
139 type: ["object", "null"],
140 description:
141 "The lead that has waited longest among those that need you now (the desk's Needs you view); null when none is left.",
142 properties: { id: { type: "integer" }, name: { type: "string" } },
143 required: ["id", "name"],
144 },
145 },
146 required: [...(LEAD.required ?? []), "next"],
147 };
133148 export const DESK_LEAD: Schema = {
134149 type: "object",
135150 properties: {
@@ -415,6 +430,8 @@ export const routes: readonly Route[] = [
415430 agent: currentAgent(c.db),
416431 lead: found.value,
417432 mayUpdate: permit(c.who, "lead", "update", { ...found.value }) === "yes",
433 next: nextLead(c.db, c.who, { except: found.value.id }),
434 now: Date.now(),
418435 notice,
419436 }),
420437 200,
@@ -467,7 +484,7 @@ export const routes: readonly Route[] = [
467484 posted(
468485 c,
469486 (input) =>
470 sendReply(c.db, c.who, {
487 approveReply(c.db, c.who, {
471488 id: ID(c),
472489 body: typeof input.body === "string" ? input.body : undefined,
473490 }),
@@ -487,7 +504,7 @@ export const routes: readonly Route[] = [
487504 },
488505 },
489506 },
490 answer: LEAD,
507 answer: APPROVED,
491508 },
492509 },
493510 {
src/terminal.ts +14 −5
@@ -6,8 +6,8 @@
66 *
77 * Screens:
88 * 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
9 * lead s approve and send · e edit, then send · q qualified · x lost ·
10 * D remove (admin) · esc back
9 * lead s approve and send · e edit, then send · ] next lead that needs you ·
10 * q qualified · x lost · D remove (admin) · esc back
1111 * edit type; enter is a new line · ctrl-d approve and send · esc cancel
1212 * add one field at a time; enter next · esc cancel
1313 * profile the name, brokerage and license every message carries ·
@@ -31,7 +31,8 @@ import {
3131 listLeads,
3232 resetSample,
3333 saveProfile,
34 sendReply,
34 approveReply,
35 nextLead,
3536 setState,
3637 } from "./actions.ts";
3738 import { between, elapsed, recordLine, tone } from "./clock.ts";
@@ -283,6 +284,7 @@ export function terminal(
283284 ...(l.state === "qualified" || l.state === "lost"
284285 ? ["o put back in follow-ups"]
285286 : ["q qualified", "x lost"]),
287 ...(nextLead(db, me, { except: l.id }) === null ? [] : ["] next that needs you"]),
286288 ...(admin() ? ["D remove"] : []),
287289 "esc back",
288290 ].join(" · "),
@@ -362,8 +364,10 @@ export function terminal(
362364 }
363365
364366 function send(id: number, body?: string): void {
365 const sent = sendReply(db, me, { id, body });
366 said = sent.ok ? `Sent to ${sent.value.name}.` : sent.message;
367 const sent = approveReply(db, me, { id, body });
368 said = sent.ok
369 ? `Sent to ${sent.value.name}.${sent.value.next === null ? " Nothing else needs you right now." : ` Next: ${sent.value.next.name} (])`}`
370 : sent.message;
367371 view = { name: "lead", id };
368372 }
369373
@@ -523,6 +527,11 @@ export function terminal(
523527 if (input === "\x1b" || input === "\x7f") view = { name: "desk" };
524528 else if (l === undefined) view = { name: "desk" };
525529 else if (input === "s") send(id);
530 else if (input === "]") {
531 const next = nextLead(db, me, { except: id });
532 if (next === null) said = "Nothing else needs you right now.";
533 else view = { name: "lead", id: next.id };
534 }
526535 else if (input === "e") {
527536 const r = ready(l);
528537 if (r === undefined) said = "Nothing is waiting to go to this lead right now.";
static/app.css +9
@@ -311,6 +311,15 @@ footer {
311311 }
312312
313313 /* A lead. */
314 .next {
315 margin: 0 0 var(--space-3);
316 font-weight: 600;
317 }
318 .next a {
319 display: inline-flex;
320 align-items: center;
321 min-height: var(--size-tap);
322 }
314323 .backlink {
315324 display: inline-flex;
316325 align-items: center;

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs