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

On a busy morning, the agent reads every follow-up due today on one page and sends the ones they leave ticked, in one press #100

Merged opened this

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

Merged

mason/speed-to-lead:mason/98-on-a-busy-morning-the-agent-reads-every → main 4 commits fork

  • Merged. mason/98-on-a-busy-morning-the-agent-reads-every was merged into main as 6e8de18.

Review

Sign in to review this change.
14 files changed +643 −7
README.md +16
@@ -53,6 +53,13 @@ what you see right after a restart. Do step 1 first.
5353 Back on **Marcus Lee**, open "They wrote back", paste "Yes, Saturday
5454 works" and record it: he is in "Needs you" with a fresh green clock and an
5555 answer drafted, and his upcoming follow-ups wait until you send it.
56 On a busy morning, press "read them together" beside "follow-ups due
57 today" on the desk: every due follow-up is on one page with its words, each
58 box unticked. Tick the ones you approve and press "Send the ticked ones";
59 nothing ticked sends nothing, and one that stopped being due is skipped
60 and named. It is the same send as "Approve and send" (quiet hours, the
61 one-minute Undo, the audit). In the terminal, press `d` on the desk: the
62 same list with each follow-up's words, space ticks, `s` sends the ticked.
5663 7. Book a showing. Open **Marcus Lee** again, press "Book a showing", pick
5764 a day and time later this week (in your time zone from the profile), type an address and book it. The
5865 history says "Showing booked", his row on the desk carries a *Showing*
@@ -460,6 +467,15 @@ from the bottom of the desk, so the clocks read fresh for a demonstration.
460467 - **Drafts are templates**, filled from what the lead wrote and your
461468 profile. There is no AI writing them and no outside service called.
462469
470 ## Sending due follow-ups together
471
472 `/due` lists every follow-up due today. A script does the same with
473 `POST /leads/send-due` and `{"ids": [...]}` (message ids, at most 100, each a
474 due follow-up; one that stopped being due is skipped and named in `skipped`),
475 and the MCP tool is `send_due_followups`. Each id goes through the same send
476 as `POST /leads/:id/reply`. In the terminal, `d` opens the same list and
477 `s` sends the ticked ones.
478
463479 ## Your profile
464480
465481 Open **Your profile** in the header (`/profile`) and fill in your name,
contract/openapi.json +108
@@ -511,6 +511,114 @@
511511 }
512512 }
513513 },
514 "/leads/send-due": {
515 "post": {
516 "summary": "Approve the follow-ups you name, in one call: `ids` is a list of message ids (whole numbers, at most 100), each a follow-up that is due (not a first reply, not an answer to a lead who wrote back; 422 otherwise, and nothing is sent). Each goes the way send on its lead does: a text outside 8:00 a.m. to 9:00 p.m. is held for 8:00 (`held`), each can be taken back for a minute, the audit names who approved each. A follow-up that stopped being due meanwhile is skipped and named in `skipped`, never sent. An empty list sends nothing.",
517 "operationId": "postLeadsSendDue",
518 "requestBody": {
519 "required": true,
520 "content": {
521 "application/json": {
522 "schema": {
523 "type": "object",
524 "properties": {
525 "ids": {
526 "type": "array",
527 "maxItems": 100,
528 "items": {
529 "type": "integer",
530 "minimum": 1
531 }
532 }
533 },
534 "required": [
535 "ids"
536 ]
537 }
538 }
539 }
540 },
541 "responses": {
542 "200": {
543 "description": "Approve the follow-ups you name, in one call: `ids` is a list of message ids (whole numbers, at most 100), each a follow-up that is due (not a first reply, not an answer to a lead who wrote back; 422 otherwise, and nothing is sent). Each goes the way send on its lead does: a text outside 8:00 a.m. to 9:00 p.m. is held for 8:00 (`held`), each can be taken back for a minute, the audit names who approved each. A follow-up that stopped being due meanwhile is skipped and named in `skipped`, never sent. An empty list sends nothing.",
544 "content": {
545 "application/json": {
546 "schema": {
547 "type": "object",
548 "properties": {
549 "sent": {
550 "type": "array",
551 "items": {
552 "type": "object",
553 "properties": {
554 "id": {
555 "type": "integer"
556 },
557 "lead_id": {
558 "type": "integer"
559 },
560 "name": {
561 "type": "string"
562 },
563 "held": {
564 "type": "boolean",
565 "description": "A text approved in quiet hours: it goes at scheduledFor."
566 },
567 "scheduledFor": {
568 "type": [
569 "string",
570 "null"
571 ],
572 "format": "date-time"
573 }
574 }
575 }
576 },
577 "skipped": {
578 "type": "array",
579 "items": {
580 "type": "object",
581 "properties": {
582 "id": {
583 "type": "integer"
584 },
585 "lead_id": {
586 "type": [
587 "integer",
588 "null"
589 ]
590 },
591 "name": {
592 "type": "string"
593 },
594 "reason": {
595 "type": "string"
596 }
597 }
598 }
599 }
600 },
601 "required": [
602 "sent",
603 "skipped"
604 ]
605 }
606 }
607 }
608 },
609 "default": {
610 "description": "{ error, message }: why not",
611 "content": {
612 "application/json": {
613 "schema": {
614 "$ref": "#/components/schemas/Error"
615 }
616 }
617 }
618 }
619 }
620 }
621 },
514622 "/leads/price-change": {
515623 "post": {
516624 "summary": "A listing's price dropped: every open lead who asked about the address (in their inquiry, or by a showing booked there) gets one drafted note naming it and the new price, waiting on the desk. Nothing is sent, and the same change twice drafts nothing new. Answers with how many drafts were made, zero included; a bad address or price is a 422 naming the field.",
docs/design/areas/desk.md +8
@@ -38,3 +38,11 @@ never answered"), padded to line up with the row; it sits beside the row's
3838 link inside `li.lead-item` (full width under the row, shown to whoever
3939 sees the star), never inside it. On the lead's page the same form leads
4040 `.states`, as a plain `.button`.
41
42 # Desk: due follow-ups
43
44 `/due` is one `ul.stack` of `li.card.stack`, one per due follow-up: a
45 `label.row` holding an unticked checkbox and the name, channel and day, a link
46 to the lead, then `.body` and `.sig` as the lead's page shows them. One
47 `.button` ("Send the ticked ones") ends the form. No new class; a plain POST,
48 no JavaScript. The desk's summary links to it only while a follow-up is due.
src/actions.ts +68
@@ -16,6 +16,7 @@ import {
1616 BUILT_IN_OPENER,
1717 CADENCE,
1818 channelFor,
19 isAnswer,
1920 MAX_BODY,
2021 OPENER_MAX,
2122 SOURCES,
@@ -57,6 +58,10 @@ import {
5758 optOut,
5859 nextNeeding,
5960 readyFor,
61 dueFollowUps,
62 isDueFollowUp,
63 type DueFollowUp,
64 type Message,
6065 recordCall,
6166 bookShowing as bookShowingFor,
6267 bringBack,
@@ -671,6 +676,69 @@ export const sendReply = (
671676 return audited(db, who, "lead", "update", input.id, result, held ? "held" : first ? "first_reply" : "reply");
672677 };
673678
679 /** The most follow-ups one press may send. */
680 export const MAX_DUE_BATCH = 100;
681
682 /** The due follow-ups the agent may read and tick: the same ones the desk counts as due today. */
683 export const listDue = (db: Database, who: Who): Result<{ due: DueFollowUp[] }> =>
684 permit(who, "lead", "update") === "yes"
685 ? ok({ due: dueFollowUps(db) })
686 : refuse(who, "Sign in to read the follow-ups due today.", "You may not approve follow-ups.");
687
688 /** What a batch did: what went (or was held for 8 a.m.), and what was skipped and why. */
689 export interface DueSent {
690 readonly sent: readonly { id: number; lead_id: number; name: string; held: boolean; scheduledFor: string | null }[];
691 readonly skipped: readonly { id: number; lead_id: number | null; name: string; reason: string }[];
692 }
693
694 /**
695 * Approve exactly the ticked follow-ups, each through `sendReply` — the one
696 * send path, so quiet hours, undo and the audit hold for each. An id that is
697 * not a follow-up at all (a first reply, an answer, no message) refuses the
698 * whole batch before anything goes; a follow-up that stopped being due meanwhile
699 * is skipped and named, never sent. Nothing ticked sends nothing.
700 */
701 export function sendDue(
702 db: Database,
703 who: Who,
704 input: { ids: unknown },
705 at?: Date,
706 ): Result<DueSent> {
707 if (permit(who, "lead", "update") !== "yes")
708 return refuse(who, "Sign in to approve follow-ups.", "You may not approve follow-ups.");
709 const ids = input.ids;
710 if (!Array.isArray(ids) || ids.length > MAX_DUE_BATCH)
711 return fail("invalid", `Give a list of at most ${MAX_DUE_BATCH} message ids.`);
712 if (!ids.every((i) => typeof i === "number" && Number.isInteger(i) && i > 0))
713 return fail("invalid", "A message id is a whole number.");
714 const wanted = [...new Set(ids as number[])];
715 const rows = wanted.map((id) => ({
716 id,
717 message: db.query<Message, [number]>("SELECT * FROM message WHERE id = ?1").get(id),
718 }));
719 const notFollowUp = rows.find((r) => r.message === null || r.message.day === 0 || isAnswer(r.message.day));
720 if (notFollowUp !== undefined)
721 return fail("invalid", `Message ${notFollowUp.id} is not a follow-up that can be approved here.`);
722 const sent: Array<DueSent["sent"][number]> = [];
723 const skipped: Array<DueSent["skipped"][number]> = [];
724 for (const { id, message } of rows) {
725 const m = message!;
726 const name = findLead(db, m.lead_id)?.name ?? "a removed lead";
727 if (!isDueFollowUp(db, m)) {
728 skipped.push({ id, lead_id: m.lead_id, name, reason: "It is no longer due." });
729 continue;
730 }
731 const result = sendReply(db, who, { id: m.lead_id }, at);
732 if (!result.ok) {
733 skipped.push({ id, lead_id: m.lead_id, name, reason: result.message });
734 continue;
735 }
736 const after = result.value.messages.find((x) => x.id === id);
737 sent.push({ id, lead_id: m.lead_id, name, held: after?.status === "held", scheduledFor: after?.goes_at ?? null });
738 }
739 return ok({ sent, skipped });
740 }
741
674742 /**
675743 * The lead that has waited longest among those that need the agent, other
676744 * than `except`. Reading it is `list lead`, as the desk is; whoever may not
src/due.test.ts added +174
@@ -0,0 +1,174 @@
1 /**
2 * Due follow-ups on one page: the agent ticks, and exactly the ticked ones
3 * go, each by the one send path. Nothing ticked sends nothing; a follow-up
4 * that stopped being due is skipped; a first reply or an answer is refused.
5 */
6 import { afterAll, beforeAll, 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 { addLead, getLead, listDue, saveProfile, sendDue, sendReply, setState, turn, undoSend } from "./actions.ts";
11 import { openDb } from "./db.ts";
12 import type { DueFollowUp } from "./leads.ts";
13 import { agent } from "./env.ts";
14 import { duePage } from "./pages/due.ts";
15 import { serve } from "./server.ts";
16 import { sign } from "./who.ts";
17 import type { Who } from "./who.ts";
18
19 let was: string | undefined;
20 beforeAll(() => {
21 was = process.env.QUIET_HOURS;
22 delete process.env.QUIET_HOURS;
23 });
24 afterAll(() => {
25 if (was !== undefined) process.env.QUIET_HOURS = was;
26 });
27
28 const alice: Who = { role: "user", id: "u1", name: "alice" };
29 const anon: Who = { role: "anon" };
30 const root: Who = { role: "admin", id: "u0", name: "root" };
31 const ZONE = "America/Chicago";
32 const at = (hhmm: string, date = "2026-06-10") => new Date(`${date}T${hhmm}:00-05:00`);
33 const value = <T>(r: { ok: boolean; value?: T; message?: string }): T => {
34 if (!r.ok) throw new Error(r.message);
35 return r.value as T;
36 };
37 let n = 0;
38
39 /** A desk where two leads were answered on June 10 and their next follow-up is due on June 12, midday. */
40 const setup = (channel: "email" | "text" = "email") => {
41 const db = openDb(mkdtempSync(join(tmpdir(), "app-due-")));
42 value(saveProfile(db, root, { ...agent, timeZone: ZONE }));
43 const ids: number[] = [];
44 for (const name of ["Ann", "Bo"]) {
45 const id = value(
46 addLead(db, alice, { name, email: `due${++n}@example.com`, phone: channel === "text" ? "(206) 555-0199" : "", source: "zillow", message: "Is it open?", consent: channel === "text" }, at("12:00")),
47 ).id;
48 value(sendReply(db, alice, { id }, at("12:05")));
49 ids.push(id);
50 }
51 turn(db, at("12:00", "2026-06-12"));
52 return { db, ids };
53 };
54 const dueIds = (db: ReturnType<typeof setup>["db"]) => value(listDue(db, alice)).due.map((d) => d.id);
55 const status = (db: ReturnType<typeof setup>["db"], id: number, mid: number) => value(getLead(db, alice, { id })).messages.find((m) => m.id === mid)!.status;
56
57 test("lists due follow-ups only, and sends exactly the ticked ones", () => {
58 const { db, ids } = setup();
59 const due = value(listDue(db, alice)).due;
60 expect(due.map((d) => d.lead_id).sort()).toEqual([...ids].sort());
61 expect(due.every((d) => d.day > 0)).toBe(true);
62 const [first, second] = due as [typeof due[0], typeof due[0]];
63 const out = value(sendDue(db, alice, { ids: [first.id] }, at("13:00", "2026-06-12")));
64 expect(out.sent.map((s) => s.id)).toEqual([first.id]);
65 expect(out.skipped).toEqual([]);
66 expect(status(db, first.lead_id, first.id)).toBe("sent");
67 expect(status(db, second.lead_id, second.id)).toBe("due");
68 expect(dueIds(db)).toEqual([second.id]);
69 // The audit says who approved it.
70 const row = db.query<{ who: string }, [number]>("SELECT * FROM audit WHERE target = ?1 ORDER BY id DESC LIMIT 1").get(first.lead_id);
71 expect(JSON.stringify(row)).toContain("alice");
72 });
73
74 test("each send can be taken back for a minute, as one by one", () => {
75 const { db } = setup();
76 const [d] = value(listDue(db, alice)).due;
77 value(sendDue(db, alice, { ids: [d!.id] }));
78 value(undoSend(db, alice, { id: d!.lead_id }));
79 expect(status(db, d!.lead_id, d!.id)).toBe("due");
80 });
81
82 test("a text approved in quiet hours is held until 8 a.m.", () => {
83 const { db } = setup("text");
84 const [d] = value(listDue(db, alice)).due;
85 const out = value(sendDue(db, alice, { ids: [d!.id] }, at("22:30", "2026-06-12")));
86 expect(out.sent[0]!.held).toBe(true);
87 expect(out.sent[0]!.scheduledFor).not.toBeNull();
88 expect(status(db, d!.lead_id, d!.id)).toBe("held");
89 });
90
91 test("nothing ticked sends nothing", () => {
92 const { db } = setup();
93 const before = dueIds(db);
94 expect(value(sendDue(db, alice, { ids: [] }))).toEqual({ sent: [], skipped: [] });
95 expect(dueIds(db)).toEqual(before);
96 });
97
98 test("a follow-up that stopped being due is skipped and named, never sent", () => {
99 const { db } = setup();
100 const [a, b] = value(listDue(db, alice)).due as [DueFollowUp, DueFollowUp];
101 value(sendReply(db, alice, { id: a.lead_id })); // sent meanwhile
102 value(setState(db, alice, { id: b.lead_id, state: "lost", reason: "other" } as never)); // closed meanwhile
103 const out = value(sendDue(db, alice, { ids: [a.id, b.id] }));
104 expect(out.sent).toEqual([]);
105 expect(out.skipped.map((s) => s.id).sort()).toEqual([a.id, b.id].sort());
106 expect(out.skipped.map((s) => s.name).sort()).toEqual(["Ann", "Bo"]);
107 });
108
109 test("an id that is not a due follow-up is refused and nothing goes", () => {
110 const { db } = setup();
111 const [d] = value(listDue(db, alice)).due;
112 const first = db.query<{ id: number }, []>("SELECT id FROM message WHERE day = 0 LIMIT 1").get()!;
113 for (const ids of [[d!.id, first.id], [d!.id, 999999], ["1"], [1.5], [0], "1", null, Array.from({ length: 101 }, (_, i) => i + 1)]) {
114 const r = sendDue(db, alice, { ids });
115 expect(!r.ok && r.error).toBe("invalid");
116 }
117 expect(dueIds(db)).toContain(d!.id);
118 });
119
120 test("signed out is refused", () => {
121 const { db } = setup();
122 const r = sendDue(db, anon, { ids: [dueIds(db)[0]!] });
123 expect(!r.ok && r.error).toBe("signin_required");
124 expect(!listDue(db, anon).ok).toBe(true);
125 expect(dueIds(db).length).toBe(2);
126 });
127
128 test("the page shows name link, channel, day and the words; the checkboxes start unticked", () => {
129 const { db } = setup();
130 const due = value(listDue(db, alice)).due;
131 const html = duePage({ who: alice, agent, due });
132 expect(html).toContain(`href="/leads/${due[0]!.lead_id}"`);
133 expect(html).toContain("Send the ticked ones");
134 expect(html).toContain(`name="m_${due[0]!.id}"`);
135 expect(html).not.toContain("checked");
136 expect(html).toContain(due[0]!.signature.split("\n")[0]!);
137 });
138
139 // The doors.
140 const KEY = "a-key-only-the-forge-holds";
141 const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-due-srv-")), identityKey: KEY, sample: false });
142 const base = `http://${server.hostname}:${server.port}`;
143 afterAll(() => server.stop(true));
144 let grants = 0;
145 const api = (path: string, init: RequestInit = {}, headers: Record<string, string> = {}) => {
146 const identity = `due-${++grants}|alice|user|${Date.now() + 60_000}`;
147 return fetch(base + path, {
148 redirect: "manual",
149 ...init,
150 headers: { ...(init.headers as Record<string, string>), ...headers, "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) },
151 });
152 };
153
154 test("the page and the API: signed out refused, same-origin only, form and JSON send the ticked", async () => {
155 const guest = await fetch(`${base}/due`);
156 expect([401, 403]).toContain(guest.status);
157 const post = await fetch(`${base}/leads/send-due`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ ids: [] }) });
158 expect([401, 403]).toContain(post.status);
159 const page = await api("/due");
160 expect(page.status).toBe(200);
161 expect(await page.text()).toContain("No follow-up is due");
162 const empty = await api("/leads/send-due", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ ids: [] }) });
163 expect(empty.status).toBe(200);
164 expect(await empty.json()).toEqual({ sent: [], skipped: [] });
165 const bad = await api("/leads/send-due", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ ids: [999999] }) });
166 expect(bad.status).toBe(422);
167 const other = await api("/leads/send-due", { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded", origin: "https://evil.example" }, body: "" });
168 expect(other.status).toBe(403);
169 const form = await api("/leads/send-due", { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: "" });
170 expect(form.status).toBe(303);
171 expect(form.headers.get("location")).toBe("/due");
172 const spec = await (await api("/openapi.json")).text();
173 expect(spec).toContain("/leads/send-due");
174 });
src/leads.ts +32
@@ -1395,3 +1395,35 @@ export function lastMessages(db: Database): Map<number, string> {
13951395 .all();
13961396 return new Map(rows.map((r) => [r.lead_id, r.at]));
13971397 }
1398
1399 /** A follow-up that is due now, with the lead it goes to: what the due page lists. */
1400 export interface DueFollowUp {
1401 readonly id: number;
1402 readonly lead_id: number;
1403 readonly name: string;
1404 readonly channel: Channel;
1405 readonly day: number;
1406 readonly body: string;
1407 readonly signature: string;
1408 readonly due_at: string;
1409 }
1410
1411 /**
1412 * Whether `message` is a follow-up the agent may approve now: due, not a
1413 * first reply and not an answer to something the lead wrote, and the very
1414 * message `readyFor` would send — so the single send path sends it.
1415 */
1416 export const isDueFollowUp = (db: Database, message: Message): boolean =>
1417 message.status === "due" && message.day > 0 && !isAnswer(message.day) && readyFor(db, message.lead_id)?.id === message.id;
1418
1419 /** Every due follow-up, the one that has waited longest first. */
1420 export const dueFollowUps = (db: Database): DueFollowUp[] =>
1421 db
1422 .query<DueFollowUp, [number]>(
1423 `SELECT m.id, m.lead_id, l.name, m.channel, m.day, m.body, m.signature, m.due_at
1424 FROM message m JOIN lead l ON l.id = m.lead_id
1425 WHERE m.status = 'due' AND m.day > 0 AND m.day < ?1
1426 ORDER BY m.due_at, m.id`,
1427 )
1428 .all(ANSWER_DAY)
1429 .filter((m) => readyFor(db, m.lead_id)?.id === m.id);
src/mcp.ts +12
@@ -10,6 +10,7 @@ import type { Database } from "bun:sqlite";
1010 import {
1111 addLead,
1212 sendThanks,
13 sendDue,
1314 skipThanksFor,
1415 addSampleInquiry,
1516 exportLeads,
@@ -209,6 +210,17 @@ export const tools: readonly Tool[] = [
209210 body: typeof args.body === "string" ? args.body : undefined,
210211 }),
211212 },
213 {
214 name: "send_due_followups",
215 description:
216 "Approve the follow-ups the person has chosen, by message id (ids: at most 100, each a follow-up that is due, as listed by the due follow-ups page; a first reply or an answer is refused and nothing is sent). Each goes exactly as send_reply does: a text outside 8:00 a.m. to 9:00 p.m. is held for 8:00, each can be taken back with undo_send for a minute. One that stopped being due is skipped and named, never sent. Only call this with ids the person ticked.",
217 inputSchema: {
218 type: "object",
219 properties: { ids: { type: "array", items: { type: "integer" }, maxItems: 100 } },
220 required: ["ids"],
221 },
222 run: (db, who, args) => sendDue(db, who, { ids: args.ids }),
223 },
212224 {
213225 name: "log_lead_reply",
214226 description:
src/pages/desk.ts +1 −1
@@ -71,7 +71,7 @@ export function deskPage(input: {
7171 const waiting = leads.filter((l) => l.ready?.day === 0).length;
7272 const answers = leads.filter((l) => l.ready !== null && isAnswer(l.ready.day)).length;
7373 const due = leads.filter((l) => l.ready !== null && l.ready.day > 0 && !isAnswer(l.ready.day)).length;
74 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>`;
74 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${due > 0 && input.mayStar ? ` (<a href="/due">read them together</a>)` : ""}${answers === 0 ? "" : ` <span aria-hidden="true">·</span> <b>${answers}</b> wrote back`}</p>`;
7575 const record = input.record === undefined ? "" : `<p class="record">${escape(recordLine(input.record))}</p>${trendHtml(input.record)}${input.record.by_source.map((r) => `<p class="record-source muted">${escape(sourceLine(r))}</p>`).join("")}<p class="muted">${RECORD_NOTE}</p>`;
7676 const q = input.q ?? "";
7777 const views =
src/pages/due.ts added +39
@@ -0,0 +1,39 @@
1 /**
2 * Due follow-ups: every follow-up due today on one page, each with its
3 * words in full and a checkbox, unticked. A plain form, no JavaScript;
4 * "Send the ticked ones" posts the ticked ids and sends only those.
5 */
6
7 import { escape } from "../http.ts";
8 import type { DueFollowUp } from "../leads.ts";
9 import type { Agent } from "../env.ts";
10 import type { Who } from "../who.ts";
11 import { layout } from "./layout.ts";
12
13 const item = (m: DueFollowUp): string => `<li class="card stack">
14 <label class="row">
15 <input type="checkbox" name="m_${m.id}" value="1">
16 <span><strong>${escape(m.name)}</strong> <span class="muted">· ${m.channel === "text" ? "Text" : "Email"} · day ${m.day}</span></span>
17 </label>
18 <p class="muted"><a href="/leads/${m.lead_id}">Open ${escape(m.name)}</a></p>
19 <p class="body">${escape(m.body)}</p>
20 <p class="sig">${escape(m.signature)}</p>
21 </li>`;
22
23 export function duePage(input: {
24 who: Who;
25 agent: Agent;
26 due: readonly DueFollowUp[];
27 notice?: string | undefined;
28 }): string {
29 const { who, agent, due, notice } = input;
30 const body =
31 due.length === 0
32 ? `<p class="empty">No follow-up is due. <a href="/">Back to the desk</a></p>`
33 : `<p class="muted">Nothing is sent until you tick it and press the button. A text approved outside 8:00 a.m. to 9:00 p.m. waits for 8:00 a.m.; for a minute after, each can be taken back from its lead's page.</p>
34 <form method="post" action="/leads/send-due" class="stack">
35 <ul class="stack">${due.map(item).join("")}</ul>
36 <button class="button">Send the ticked ones</button>
37 </form>`;
38 return layout({ who, agent, path: "/due", heading: "Due follow-ups", notice, body: `<h1>Due follow-ups</h1>${body}` });
39 }
src/routes.ts +76
@@ -36,6 +36,9 @@ import {
3636 saveProfile,
3737 optOutTexts,
3838 approveReply,
39 listDue,
40 sendDue,
41 MAX_DUE_BATCH,
3942 sendThanks,
4043 skipThanksFor,
4144 insertReply,
@@ -83,12 +86,14 @@ import { MAX_EMAIL_TEXT } from "./intake.ts";
8386 import { MAX_SIGNIN_TEXT } from "./signins.ts";
8487 import { LOST_REASONS, lostSaid } from "./lost.ts";
8588 import { MAX_INBOUND, MAX_LEAD_NOTE, MAX_QUERY, Q_HELP, showingsAhead, VIEW_HELP, VIEWS, type LeadDetail, type NewLead } from "./leads.ts";
89 import { dueSaid } from "./sentences.ts";
8690 import { undoable } from "./undo.ts";
8791 import { events } from "./live.ts";
8892 import { rpc } from "./mcp.ts";
8993 import { deskPage } from "./pages/desk.ts";
9094 import { layout } from "./pages/layout.ts";
9195 import { leadPage } from "./pages/lead.ts";
96 import { duePage } from "./pages/due.ts";
9297 import { activityPage } from "./pages/activity.ts";
9398 import { reportPage } from "./pages/report.ts";
9499 import { profilePage } from "./pages/profile.ts";
@@ -566,8 +571,39 @@ const SIGNIN_LINE: Schema = {
566571 problem: { type: "string", description: "Why the line could not be read; absent when it could." },
567572 },
568573 };
574 /** A form posts one checkbox per message (`m_12`); the action reads an `ids` list, as JSON sends it. */
575 const idsOf = (input: Record<string, unknown>): unknown =>
576 input.ids !== undefined
577 ? input.ids
578 : Object.keys(input).flatMap((k) => (/^m_(\d{1,12})$/.exec(k)?.[1] ?? [])).map(Number);
579
569580 const ID = (c: Context): number => Number(c.params.id);
570581 const list = (items: Schema): Schema => ({ type: "array", items });
582 const DUE_SENT: Schema = {
583 type: "object",
584 properties: {
585 sent: list({
586 type: "object",
587 properties: {
588 id: { type: "integer" },
589 lead_id: { type: "integer" },
590 name: { type: "string" },
591 held: { type: "boolean", description: "A text approved in quiet hours: it goes at scheduledFor." },
592 scheduledFor: { type: ["string", "null"], format: "date-time" },
593 },
594 }),
595 skipped: list({
596 type: "object",
597 properties: {
598 id: { type: "integer" },
599 lead_id: { type: ["integer", "null"] },
600 name: { type: "string" },
601 reason: { type: "string" },
602 },
603 }),
604 },
605 required: ["sent", "skipped"],
606 };
571607
572608 const STATUS: Record<Failure, number> = {
573609 signin_required: 401,
@@ -876,6 +912,46 @@ export const routes: readonly Route[] = [
876912 status: 201,
877913 },
878914 },
915 {
916 method: "GET",
917 path: "/due",
918 handle: (c) => {
919 const found = listDue(c.db, c.who);
920 const agent = currentAgent(c.db);
921 if (!found.ok)
922 return html(
923 layout({
924 who: c.who,
925 agent,
926 path: c.url.pathname,
927 heading: "Due follow-ups",
928 body: `<p class="empty">${escape(found.message)} <a href="/">Back to the desk</a></p>`,
929 }),
930 STATUS[found.error],
931 );
932 const { notice, clear } = readNotice(c.request);
933 return html(duePage({ who: c.who, agent, due: found.value.due, notice }), 200, clear);
934 },
935 },
936 {
937 method: "POST",
938 path: "/leads/send-due",
939 handle: (c) =>
940 posted(
941 c,
942 (input) => sendDue(c.db, c.who, { ids: idsOf(input) }),
943 (value) => ({ to: "/due", said: value === undefined ? "Nothing was sent." : dueSaid(value) }),
944 ),
945 api: {
946 summary: `Approve the follow-ups you name, in one call: \`ids\` is a list of message ids (whole numbers, at most ${MAX_DUE_BATCH}), each a follow-up that is due (not a first reply, not an answer to a lead who wrote back; 422 otherwise, and nothing is sent). Each goes the way send on its lead does: a text outside 8:00 a.m. to 9:00 p.m. is held for 8:00 (\`held\`), each can be taken back for a minute, the audit names who approved each. A follow-up that stopped being due meanwhile is skipped and named in \`skipped\`, never sent. An empty list sends nothing.`,
947 body: {
948 type: "object",
949 properties: { ids: { type: "array", maxItems: MAX_DUE_BATCH, items: { type: "integer", minimum: 1 } } },
950 required: ["ids"],
951 },
952 answer: DUE_SENT,
953 },
954 },
879955 {
880956 // A listing's new price: a note is drafted for each open lead who asked about
881957 // the address, and nothing is sent. Not under /leads/:id; the action asks the
src/sentences.ts +11
@@ -231,3 +231,14 @@ export const said = (
231231 const { done, tried } = deed(row, lead, esc);
232232 return row.allowed === 1 ? `${who} ${done}` : `${who} tried to ${tried}`;
233233 };
234
235 /** What a batch did, in a sentence for the page. */
236 export const dueSaid = (v: { sent: readonly { name: string; held: boolean }[]; skipped: readonly { name: string; reason: string }[] }): string => {
237 const sent = v.sent.length;
238 const held = v.sent.filter((m) => m.held).length;
239 const head =
240 sent === 0 && v.skipped.length === 0
241 ? "Nothing was ticked, so nothing was sent."
242 : `Sent ${sent}${held === 0 ? "" : ` (${held} text${held === 1 ? "" : "s"} held for 8:00 a.m.)`}.`;
243 return v.skipped.length === 0 ? head : `${head} Skipped, no longer due: ${v.skipped.map((m) => m.name).join(", ")}.`;
244 };
src/server.test.ts +1
@@ -327,6 +327,7 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
327327 "add_sign_ins",
328328 "new_sample_inquiry",
329329 "send_reply",
330 "send_due_followups",
330331 "log_lead_reply",
331332 "log_call",
332333 "book_showing",
src/terminal.test.ts +45 −1
@@ -6,7 +6,7 @@ import { expect, test } from "bun:test";
66 import { mkdtempSync } from "node:fs";
77 import { tmpdir } from "node:os";
88 import { join } from "node:path";
9 import { getLead, listLeads, saveProfile } from "./actions.ts";
9 import { getLead, listDue, listLeads, saveProfile } from "./actions.ts";
1010 import { sourceLine } from "./clock.ts";
1111 import { openDb } from "./db.ts";
1212 import { agent } from "./env.ts";
@@ -23,6 +23,10 @@ const fresh = () => {
2323 seed(db, new Date());
2424 return db;
2525 };
26 const value = <T>(r: { ok: boolean; value?: T; message?: string }): T => {
27 if (!r.ok) throw new Error(r.message);
28 return r.value as T;
29 };
2630 const read = (t: ReturnType<typeof terminal>): string =>
2731 t.screen(100).map(plain).join("\n");
2832 const type = (t: ReturnType<typeof terminal>, text: string): void => {
@@ -572,6 +576,46 @@ test("a lead whose follow-ups finished says so, and m marks it lost, never answe
572576 expect(read(guest)).not.toContain("Follow-ups finished");
573577 });
574578
579 test("d lists the due follow-ups with their words; space ticks; s sends only the ticked ones, live", () => {
580 const db = fresh();
581 const due = value(listDue(db, alice)).due;
582 expect(due.length).toBeGreaterThan(0);
583 const t = terminal(db, alice);
584 t.key("d");
585 const shown = read(t);
586 expect(shown).toContain("Due follow-ups");
587 expect(shown).toContain(due[0]!.name);
588 expect(shown).toContain(due[0]!.body.split("\n")[0]!.slice(0, 20));
589 expect(shown).not.toContain("[x]");
590 // Nothing ticked sends nothing.
591 t.key("s");
592 expect(read(t)).toContain("Nothing was ticked");
593 expect(value(listDue(db, alice)).due.length).toBe(due.length);
594 const heard: string[] = [];
595 const stop = subscribe((e) => heard.push(e.type));
596 t.key(" ");
597 expect(read(t)).toContain("[x]");
598 t.key("s");
599 stop();
600 expect(read(t)).toContain("Sent 1.");
601 expect(heard).toContain("lead.changed");
602 const left = value(listDue(db, alice)).due.map((m) => m.id);
603 expect(left).not.toContain(due[0]!.id);
604 for (const m of due.slice(1)) expect(left).toContain(m.id);
605 });
606
607 test("a guest sees no due follow-up and sends none", () => {
608 const db = fresh();
609 const before = value(listDue(db, alice)).due.length;
610 const t = terminal(db, { role: "anon" });
611 t.key("d");
612 const shown = read(t);
613 expect(shown).toContain("Sign in");
614 t.key(" ");
615 t.key("s");
616 expect(value(listDue(db, alice)).due.length).toBe(before);
617 });
618
575619 test("w on the desk shows the week report in the page's words; esc goes back; a guest sees nothing", () => {
576620 const db = fresh();
577621 const t = terminal(db, alice);
src/terminal.ts +52 −5
@@ -5,7 +5,9 @@
55 * may — the hints only leave out keys the table would refuse.
66 *
77 * Screens:
8 * desk j/k move · enter open · * star · f view (needs/open/closed/all) · / find by name, email, phone or note · n log a lead · v paste a lead email · $ price change · w this week's report · o open house sign-ins · i new sample inquiry · p profile · a activity (admin) · R restart samples (admin) · esc quit
8 * desk j/k move · enter open · * star · f view (needs/open/closed/all) · / find by name, email, phone or note · n log a lead · v paste a lead email · $ price change · w this week's report · d due follow-ups · o open house sign-ins · i new sample inquiry · p profile · a activity (admin) · R restart samples (admin) · esc quit
9 * due j/k move · space tick · s send the ticked ones (each shown in full) · esc back
10
911 * lead s approve and send · e edit, then send · w they wrote back · ] next lead that needs you ·
1012 * q qualified · x lost · m lost, never answered (follow-ups finished) · t asked to stop texts · D remove (admin) · esc back
1113 * edit type; enter is a new line · ctrl-d approve and send · esc cancel
@@ -46,6 +48,8 @@ import {
4648 resetSample,
4749 saveProfile,
4850 approveReply,
51 listDue,
52 sendDue,
4953 sendThanks,
5054 skipThanksFor,
5155 cancelHeld,
@@ -77,7 +81,7 @@ import { between, elapsed, recordLine, sourceLine, tone, trendLine } from "./clo
7781 import { permit } from "./contract.ts";
7882 import { REPORT_ROWS } from "./report-words.ts";
7983 import { goesLabel, isQuiet, nextOpening, RECORD_NOTE } from "./quiet.ts";
80 import { said as saidOf } from "./sentences.ts";
84 import { dueSaid, said as saidOf } from "./sentences.ts";
8185 import { SOURCE_LABEL, SOURCES, channelFor, dayLabel, isAfterShowing, isAnswer, isBeforeShowing, isCheckIn, isPriceChange, planLabel, type Channel, type Source } from "./drafts.ts";
8286 import { ssh, title, where } from "./env.ts";
8387 import { FINISHED_ACTION, FINISHED_LABEL } from "./finished.ts";
@@ -185,6 +189,7 @@ const daysOf = (p: Profile): string => p.cadence.join(", ");
185189 type View =
186190 | { name: "desk" }
187191 | { name: "profile" }
192 | { name: "due"; at: number; ticked: number[] }
188193 | { name: "export" }
189194 | { name: "report" }
190195 | { name: "search"; typed: string }
@@ -333,12 +338,31 @@ export function terminal(
333338 lines.push(
334339 "",
335340 dim(
336 `j/k move · enter open · f view · / find · n log a lead${permit(me, "lead", "update") === "yes" ? " · $ price change" : ""} ${permit(me, "lead", "list") === "yes" ? " · w week report" : ""} · o open house · i sample inquiry · x export CSV · p profile${admin() ? " · a activity" : ""}${admin() ? " · R restart the samples" : ""} · esc quit`,
341 `j/k move · enter open · f view · / find · n log a lead${permit(me, "lead", "update") === "yes" ? " · $ price change" : ""}${permit(me, "lead", "list") === "yes" ? " · w week report" : ""} · o open house · i sample inquiry · d due follow-ups · x export CSV · p profile${admin() ? " · a activity" : ""}${admin() ? " · R restart the samples" : ""} · esc quit`,
342
337343 ),
338344 );
339345 return lines;
340346 }
341347
348 function dueScreen(v: { at: number; ticked: number[] }, w: number): string[] {
349 const listed = listDue(db, me);
350 if (!listed.ok) return [clean(listed.message), "", dim("esc back")];
351 const rows = listed.value.due;
352 if (rows.length === 0) return [bold("Due follow-ups"), "", dim("No follow-up is due."), "", dim("esc back")];
353 const lines = [bold("Due follow-ups"), dim("Nothing goes until you tick it and press s."), ""];
354 rows.forEach((m, i) => {
355 lines.push(
356 `${i === v.at ? "▸" : " "} [${v.ticked.includes(m.id) ? "x" : " "}] ${bold(clean(m.name))} · ${m.channel === "text" ? "text" : "email"} · day ${m.day}`,
357 ...wrap(clean(m.body, false), w - 6).map((s) => ` ${s}`),
358 ...wrap(clean(m.signature, false), w - 6).map((s) => dim(` ${s}`)),
359 "",
360 );
361 });
362 lines.push(dim("j/k move · space tick · s send the ticked ones · esc back"));
363 return lines;
364 }
365
342366 function exportScreen(): string[] {
343367 const taken = exportLeads(db, me, { show, q });
344368 if (!taken.ok) return [taken.message, "", dim("esc back")];
@@ -715,7 +739,9 @@ export function terminal(
715739 ? reportScreen()
716740 : view.name === "activity"
717741 ? activityScreen(view)
718 : view.name === "export"
742 : view.name === "due"
743 ? dueScreen(view, w)
744 : view.name === "export"
719745 ? exportScreen()
720746 : view.name === "profile"
721747 ? profileScreen()
@@ -839,7 +865,9 @@ export function terminal(
839865 const taken = exportLeads(db, me, { show, q });
840866 if (taken.ok) view = { name: "export" };
841867 else said = taken.message;
842 } else if (input === "w") view = { name: "report" };
868 } else if (input === "d") view = { name: "due", at: 0, ticked: [] };
869 else if (input === "w") view = { name: "report" };
870
843871 else if (input === "p") view = { name: "profile" };
844872 else if (input === "a")
845873 view = { name: "activity", sentOnly: false, before: [] };
@@ -864,8 +892,27 @@ export function terminal(
864892 }
865893 return;
866894 }
895 case "due": {
896 const listed = listDue(db, me);
897 const rows = listed.ok ? listed.value.due : [];
898 if (input === "\x1b" || input === "\x7f") view = { name: "desk" };
899 else if (input === "j" || input === "\x1b[B") view = { ...view, at: Math.min(view.at + 1, Math.max(0, rows.length - 1)) };
900 else if (input === "k" || input === "\x1b[A") view = { ...view, at: Math.max(view.at - 1, 0) };
901 else if (input === " " && rows[view.at] !== undefined) {
902 const id = rows[view.at]!.id;
903 view = { ...view, ticked: view.ticked.includes(id) ? view.ticked.filter((x) => x !== id) : [...view.ticked, id] };
904 } else if (input === "s") {
905 // Only what is ticked, and only what is still on the screen.
906 const ids = view.ticked.filter((id) => rows.some((m) => m.id === id));
907 const sent = sendDue(db, me, { ids });
908 said = sent.ok ? dueSaid(sent.value) : sent.message;
909 view = { name: "due", at: 0, ticked: [] };
910 }
911 return;
912 }
867913 case "report": {
868914 if (input === "\x1b" || input === "\x7f" || input === "q") view = { name: "desk" };
915
869916 return;
870917 }
871918 case "export": {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs