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

When a lead writes back, the agent pastes it in: the lead's follow-ups pause and a drafted answer waits on the desk #31

Merged opened this

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

Merged

mason/speed-to-lead:mason/29-when-a-lead-writes-back-the-agent-pastes → main 4 commits fork

  • Merged. mason/29-when-a-lead-writes-back-the-agent-pastes was merged into main as f9fd252.

Review

Sign in to review this change.
20 files changed +974 −64
AGENTS.md +4
@@ -109,6 +109,10 @@ Speed to Lead is one realtor's desk. The concepts, one module each:
109109 a lead arrives with its first reply drafted (day 0); sending that reply
110110 drafts and schedules the cadence (days in `CADENCE`); `advance` makes a
111111 touch due on its day; `close` (qualified or lost) skips what is left.
112 - Replies: what a lead wrote back is pasted in (`logLeadReply`), kept in
113 the `inbound` table, and answered by a message numbered `ANSWER_DAY` + its
114 id (`isAnswer` in `src/drafts.ts`) that pauses unsent follow-ups until
115 sent; `respace` in `src/leads.ts` restarts them, as `reopen` does.
112116 - `src/drafts.ts` — the words: templates filled from the inquiry and the
113117 agent's profile (`src/profile.ts`: the saved one, else the `AGENT_*`
114118 defaults of `agent` in `src/env.ts`), the signature every message
README.md +19
@@ -48,6 +48,9 @@ what you see right after a restart. Do step 1 first.
4848 the ones already gone, and the ones still to come. When a day arrives,
4949 the follow-up shows on the desk, ready for you to approve. Then open
5050 **Ethan Brooks** and press "Mark qualified": he leaves the follow-up plan.
51 Back on **Marcus Lee**, open "They wrote back", paste "Yes, Saturday
52 works" and record it: he is in "Needs you" with a fresh green clock and an
53 answer drafted, and his upcoming follow-ups wait until you send it.
5154 7. Set your profile (admin to save). Press "Your profile" at the top, fill
5255 in your name, brokerage, license number, phone and email, and save. Every
5356 draft not yet sent takes it at once.
@@ -136,6 +139,22 @@ was ever sent), and the follow-ups not yet sent are drafted again and
136139 scheduled from that moment at day 1, 3, 7, 14 and 30, skipping those already
137140 sent.
138141
142 **When a lead answers.** The app sends nothing, so it never sees their
143 reply: you paste it in. On the lead's page open **They wrote back**, paste
144 what they wrote (up to 2000 characters) and choose email or text (text only
145 for a lead who gave written consent). It appears in the history on the other
146 side from your messages, with the time; the lead is back in **Needs you** with
147 a fresh response clock from that moment, and a short answer is drafted (same
148 signature and consent rule as every draft) to edit and approve like any
149 reply. While that answer is owed the follow-ups not yet sent are paused;
150 when you send it they are scheduled again from that day at day 1, 3, 7, 14
151 and 30, the same rule as putting a closed lead back. Sent touches are never
152 changed, and the response record still measures first replies only. A lead
153 that is closed, or has had no first reply yet, must first be put back or
154 answered. The same is `POST /leads/:id/inbound` (`body`, `channel`; form or
155 JSON), the MCP `log_lead_reply` tool, and `w` on a lead's terminal screen
156 (ctrl-t switches text and email, ctrl-d records).
157
139158 **Sample leads.** The app starts with twelve sample leads so you can see it
140159 work: two just in, two waiting a while, three gone red, and five already
141160 answered and partway through their follow-ups. An admin can restart them
contract/openapi.json +152 −10
@@ -416,6 +416,43 @@
416416 "$ref": "#/components/schemas/Message"
417417 }
418418 },
419 "replies": {
420 "type": "array",
421 "description": "What the lead wrote back, oldest first.",
422 "items": {
423 "type": "object",
424 "properties": {
425 "id": {
426 "type": "integer"
427 },
428 "lead_id": {
429 "type": "integer"
430 },
431 "channel": {
432 "enum": [
433 "text",
434 "email"
435 ]
436 },
437 "body": {
438 "type": "string",
439 "minLength": 1,
440 "maxLength": 2000
441 },
442 "at": {
443 "type": "string",
444 "format": "date-time"
445 }
446 },
447 "required": [
448 "id",
449 "lead_id",
450 "channel",
451 "body",
452 "at"
453 ]
454 }
455 },
419456 "next": {
420457 "type": [
421458 "object",
@@ -450,6 +487,7 @@
450487 "replied_at",
451488 "updated_at",
452489 "messages",
490 "replies",
453491 "next"
454492 ]
455493 }
@@ -469,6 +507,73 @@
469507 }
470508 }
471509 },
510 "/leads/{id}/inbound": {
511 "post": {
512 "summary": "The lead wrote back and you paste it in: their words join the history, the lead is back in Needs you with a fresh response clock and a drafted answer, and follow-ups not yet sent pause until it goes. Nothing is sent.",
513 "operationId": "postLeadsIdInbound",
514 "parameters": [
515 {
516 "name": "id",
517 "in": "path",
518 "required": true,
519 "schema": {
520 "type": "integer"
521 }
522 }
523 ],
524 "requestBody": {
525 "required": true,
526 "content": {
527 "application/json": {
528 "schema": {
529 "type": "object",
530 "properties": {
531 "body": {
532 "type": "string",
533 "minLength": 1,
534 "maxLength": 2000,
535 "description": "What they wrote."
536 },
537 "channel": {
538 "enum": [
539 "text",
540 "email"
541 ],
542 "description": "How they wrote; text only for a lead who gave written consent."
543 }
544 },
545 "required": [
546 "body",
547 "channel"
548 ]
549 }
550 }
551 }
552 },
553 "responses": {
554 "200": {
555 "description": "The lead wrote back and you paste it in: their words join the history, the lead is back in Needs you with a fresh response clock and a drafted answer, and follow-ups not yet sent pause until it goes. Nothing is sent.",
556 "content": {
557 "application/json": {
558 "schema": {
559 "$ref": "#/components/schemas/Lead"
560 }
561 }
562 }
563 },
564 "default": {
565 "description": "{ error, message }: why not",
566 "content": {
567 "application/json": {
568 "schema": {
569 "$ref": "#/components/schemas/Error"
570 }
571 }
572 }
573 }
574 }
575 }
576 },
472577 "/leads/{id}/state": {
473578 "post": {
474579 "summary": "Mark a lead qualified or lost: it leaves the follow-up plan. 'open' puts a closed lead back in it.",
@@ -1081,6 +1186,43 @@
10811186 "items": {
10821187 "$ref": "#/components/schemas/Message"
10831188 }
1189 },
1190 "replies": {
1191 "type": "array",
1192 "description": "What the lead wrote back, oldest first.",
1193 "items": {
1194 "type": "object",
1195 "properties": {
1196 "id": {
1197 "type": "integer"
1198 },
1199 "lead_id": {
1200 "type": "integer"
1201 },
1202 "channel": {
1203 "enum": [
1204 "text",
1205 "email"
1206 ]
1207 },
1208 "body": {
1209 "type": "string",
1210 "minLength": 1,
1211 "maxLength": 2000
1212 },
1213 "at": {
1214 "type": "string",
1215 "format": "date-time"
1216 }
1217 },
1218 "required": [
1219 "id",
1220 "lead_id",
1221 "channel",
1222 "body",
1223 "at"
1224 ]
1225 }
10841226 }
10851227 },
10861228 "required": [
@@ -1096,7 +1238,8 @@
10961238 "created_at",
10971239 "replied_at",
10981240 "updated_at",
1099 "messages"
1241 "messages",
1242 "replies"
11001243 ]
11011244 },
11021245 "Desk": {
@@ -1270,6 +1413,11 @@
12701413 },
12711414 "day": {
12721415 "type": "integer"
1416 },
1417 "since": {
1418 "type": "string",
1419 "format": "date-time",
1420 "description": "When it began to wait on you."
12731421 }
12741422 }
12751423 },
@@ -1308,15 +1456,9 @@
13081456 "type": "integer"
13091457 },
13101458 "day": {
1311 "enum": [
1312 0,
1313 1,
1314 3,
1315 7,
1316 14,
1317 30
1318 ],
1319 "description": "0 is the first reply."
1459 "type": "integer",
1460 "minimum": 0,
1461 "description": "0 is the first reply, 1, 3, 7, 14, 30 a follow-up's day; 1000 and up answers something the lead wrote back."
13201462 },
13211463 "channel": {
13221464 "enum": [
src/actions.ts +49 −1
@@ -9,7 +9,7 @@
99 import type { Database } from "bun:sqlite";
1010 import { record, type Act, type AuditRow } from "./audit.ts";
1111 import { permit } from "./contract.ts";
12 import { MAX_BODY, SOURCES, type Source } from "./drafts.ts";
12 import { channelFor, MAX_BODY, SOURCES, type Channel, type Source } from "./drafts.ts";
1313 import type { Agent } from "./env.ts";
1414 import {
1515 advance,
@@ -23,11 +23,13 @@ import {
2323 inView,
2424 queryOf,
2525 reopen,
26 MAX_INBOUND,
2627 MAX_QUERY,
2728 insertLead,
2829 optOut,
2930 nextNeeding,
3031 readyFor,
32 recordInbound,
3133 redraftUnsent,
3234 removeLead,
3335 responseRecord,
@@ -335,6 +337,52 @@ function reply(
335337 return ok(detail(db, found.value.id)!);
336338 }
337339
340 /**
341 * The lead wrote back and the agent pastes it in: their words go into the
342 * history, the lead is waiting on the agent again with a drafted answer,
343 * and follow-ups not yet sent pause until it goes. Nothing is sent.
344 */
345 export const logLeadReply = (
346 db: Database,
347 who: Who,
348 input: { id: number; body?: unknown; channel?: unknown },
349 at?: Date,
350 ): Result<LeadDetail> =>
351 audited(db, who, "lead", "update", input.id, inbound(db, who, input, at), "inbound");
352
353 function inbound(
354 db: Database,
355 who: Who,
356 input: { id: number; body?: unknown; channel?: unknown },
357 at?: Date,
358 ): Result<LeadDetail> {
359 const found = leadFor(db, who, "update", input.id, {
360 signIn: "Sign in to log a reply.",
361 no: "You may not log a reply for this lead.",
362 });
363 if (!found.ok) return found;
364 const lead = found.value;
365 if (typeof input.body !== "string")
366 return fail("invalid", "What they wrote is text.");
367 const body = lines(input.body).trim();
368 if (body.length === 0 || body.length > MAX_INBOUND)
369 return fail("invalid", `What they wrote is 1 to ${MAX_INBOUND} characters.`);
370 if (hasControl(body, true))
371 return fail("invalid", "What they wrote is plain text: no control characters.");
372 if (input.channel !== "text" && input.channel !== "email")
373 return fail("invalid", "The channel is text or email.");
374 const channel: Channel = input.channel;
375 if (channel === "text" && channelFor(lead) !== "text")
376 return fail("invalid", "They have not given written consent to be texted, so a text from them cannot be logged.");
377 if (CLOSED.includes(lead.state))
378 return fail("invalid", "This lead is marked qualified or lost: put it back in follow-ups first.");
379 if (lead.replied_at === null)
380 return fail("invalid", "Send the first reply before logging what they wrote back.");
381 recordInbound(db, lead, channel, body, stamp(at), currentAgent(db));
382 emit("lead.changed", { id: lead.id });
383 return ok(detail(db, lead.id)!);
384 }
385
338386 /** Qualified or lost: the lead leaves the cadence; open: it returns to it. */
339387 export const setState = (
340388 db: Database,
src/audit.ts +2 −2
@@ -32,8 +32,8 @@ export interface AuditRow {
3232 readonly act: string | null;
3333 }
3434
35 /** Messages sent are `reply` and `first_reply`; a close is `qualified` or `lost`; `reopened` puts it back; `opted_out` is a lead who asked to stop texts. */
36 export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out"] as const;
35 /** Messages sent are `reply` and `first_reply`; a close is `qualified` or `lost`; `reopened` puts it back; `opted_out` is a lead who asked to stop texts; `inbound` is what the lead wrote back, pasted in. */
36 export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound"] as const;
3737 export type Act = (typeof ACTS)[number];
3838
3939 export interface Attempt {
src/contract.test.ts +19 −2
@@ -17,6 +17,7 @@ import {
1717 getProfile,
1818 listAudit,
1919 listLeads,
20 logLeadReply,
2021 saveProfile,
2122 setState,
2223 } from "./actions.ts";
@@ -94,8 +95,24 @@ const doors: Record<
9495 },
9596 list: (who) => listLeads(db, who).ok,
9697 read: (who, authorId) => getLead(db, who, { id: aLead(authorId) }).ok,
97 update: (who, authorId) =>
98 setState(db, who, { id: aLead(authorId), state: "lost" }).ok,
98 update: (who, authorId) => {
99 // Logging what a lead wrote back is the same cell, through its own door
100 // (POST /leads/:id/inbound and the MCP tool log_lead_reply): a lead
101 // already answered, so only the policy can refuse it.
102 const replied = aLead(authorId);
103 db.query("UPDATE lead SET replied_at = ?1 WHERE id = ?2").run(
104 new Date().toISOString(),
105 replied,
106 );
107 const logged = logLeadReply(db, who, {
108 id: replied,
109 body: "Yes please",
110 channel: "email",
111 }).ok;
112 const changed = setState(db, who, { id: aLead(authorId), state: "lost" }).ok;
113 expect(logged).toBe(changed);
114 return changed;
115 },
99116 delete: (who, authorId) => deleteLead(db, who, { id: aLead(authorId) }).ok,
100117 },
101118 // One profile, never created, listed or deleted: read it, and an admin changes it.
src/db.test.ts +7
@@ -21,3 +21,10 @@ test("migrations apply once, in order, and the file checks out", () => {
2121 ?.foreign_keys,
2222 ).toBe(1);
2323 });
24
25 test("the inbound migrations tolerate a file that already has them (a preview that ran them before main's opt-out column)", () => {
26 const db = openDb(mkdtempSync(join(tmpdir(), "app-db-")));
27 const at = migrations.findIndex((m) => m.includes("TABLE IF NOT EXISTS inbound"));
28 db.exec("DELETE FROM schema_version WHERE version > " + at);
29 expect(() => migrate(db)).not.toThrow();
30 });
src/db.ts +14
@@ -102,6 +102,20 @@ export const migrations: string[] = [
102102 // `consent` too, so the consent rule and its triggers hold with no change;
103103 // nothing in the app sets it back.
104104 `ALTER TABLE lead ADD COLUMN opted_out_at TEXT`,
105 // What a lead wrote back, in their words, pasted in by the agent. Our
106 // messages stay in `message`; theirs are here, append-only.
107 `CREATE TABLE IF NOT EXISTS inbound (
108 id INTEGER PRIMARY KEY,
109 lead_id INTEGER NOT NULL REFERENCES lead (id) ON DELETE CASCADE,
110 channel TEXT NOT NULL CHECK (channel IN ('text', 'email')),
111 body TEXT NOT NULL CHECK (length(body) BETWEEN 1 AND 2000),
112 at TEXT NOT NULL
113 )`,
114 `CREATE INDEX IF NOT EXISTS inbound_lead ON inbound (lead_id, at)`,
115 // A text from a lead who never agreed to texts is no text we can answer.
116 `CREATE TRIGGER IF NOT EXISTS inbound_text_needs_consent BEFORE INSERT ON inbound
117 WHEN NEW.channel = 'text' AND (SELECT consent FROM lead WHERE id = NEW.lead_id) = 0
118 BEGIN SELECT RAISE(ABORT, 'no consent to text'); END`,
105119 ];
106120
107121 export function openDb(dir = dataDir): Database {
src/drafts.ts +25
@@ -34,6 +34,13 @@ export const MAX_BODY: Readonly<Record<Channel, number>> = {
3434 email: 4000,
3535 };
3636
37 /**
38 * A message that answers what a lead wrote back is numbered from here, so it
39 * never meets a cadence day: the lead's reply number is added to it.
40 */
41 export const ANSWER_DAY = 1000;
42 export const isAnswer = (day: number): boolean => day >= ANSWER_DAY;
43
3744 export interface Asker {
3845 readonly name: string;
3946 readonly phone: string;
@@ -155,3 +162,21 @@ export function draft(lead: Asker, day: number, agent: Agent): string {
155162 const touch = (TOUCH[day] ?? TOUCH[30]!)(first, topic);
156163 return channel === "text" ? touch : `${touch}\n\nBest,`;
157164 }
165
166 const AGREES = /\b(yes|yeah|yep|sure|sounds good|works for me|that works|perfect|great)\b/i;
167
168 /**
169 * A short answer to what the lead wrote back, for the agent to edit and
170 * approve. Same channel rule as every draft; the signature is added when it goes.
171 */
172 export function answerDraft(lead: Asker, wrote: string): string {
173 const first = firstName(lead.name);
174 const address = addressIn(wrote) ?? addressIn(lead.message);
175 const topic = topicOf(wrote);
176 const next = AGREES.test(wrote)
177 ? "Wonderful — I'll lock that in and send you the details shortly. Anything you'd like me to prepare before then?"
178 : ask(topic, address, true);
179 if (channelFor(lead) === "text")
180 return `Hi ${first}, thanks for getting back to me! ${next}`;
181 return `Hi ${first},\n\nThanks for getting back to me. ${next}\n\nTalk soon,`;
182 }
src/inbound.test.ts added +327
@@ -0,0 +1,327 @@
1 /**
2 * When a lead writes back: the agent pastes it in, the lead waits on them
3 * again with a fresh clock and a drafted answer, follow-ups pause, and
4 * sending the answer starts them again. At every door.
5 */
6 import { afterAll, 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 {
11 addLead,
12 getLead,
13 listLeads,
14 logLeadReply,
15 sendReply,
16 setState,
17 tick,
18 turn,
19 } from "./actions.ts";
20 import { openDb } from "./db.ts";
21 import { ANSWER_DAY } from "./drafts.ts";
22 import { serve } from "./server.ts";
23 import { plain, terminal } from "./terminal.ts";
24 import { sign } from "./who.ts";
25 import type { Who } from "./who.ts";
26
27 const alice: Who = { role: "user", id: "u1", name: "alice" };
28 const anon: Who = { role: "anon" };
29 const T0 = new Date("2026-03-01T10:00:00Z");
30 const at = (ms: number) => new Date(T0.getTime() + ms);
31 const MIN = 60_000;
32 const DAY = 86_400_000;
33
34 const fresh = () => openDb(mkdtempSync(join(tmpdir(), "app-inbound-")));
35 const arrive = (db: ReturnType<typeof fresh>, consent: boolean) => {
36 const made = addLead(db, alice, {
37 name: "Dana Reyes",
38 email: "[email protected]",
39 phone: "(206) 555-0199",
40 source: "zillow",
41 message: "Can I see 12 Oak Street this week?",
42 consent,
43 });
44 if (!made.ok) throw new Error(made.message);
45 return made.value.id;
46 };
47 const value = <T>(r: { ok: boolean; value?: T; message?: string }): T => {
48 if (!r.ok) throw new Error(r.message);
49 return r.value as T;
50 };
51 /** A lead already answered at T0 + 1 min, its follow-ups scheduled. */
52 const answered = (consent = true) => {
53 const db = fresh();
54 const id = arrive(db, consent);
55 value(sendReply(db, alice, { id }, at(MIN)));
56 return { db, id };
57 };
58
59 test("logging a reply puts the lead in Needs you, clock fresh, answer drafted", () => {
60 const { db, id } = answered();
61 const before = value(listLeads(db, alice)).record;
62 const logged = value(
63 logLeadReply(db, alice, { id, body: "Yes, Saturday works!", channel: "text" }, at(2 * DAY)),
64 );
65 expect(logged.replies.map((r) => [r.body, r.channel, r.at])).toEqual([
66 ["Yes, Saturday works!", "text", at(2 * DAY).toISOString()],
67 ]);
68 const draft = logged.messages.find((m) => m.day >= ANSWER_DAY)!;
69 expect(draft.status).toBe("draft");
70 expect(draft.due_at).toBe(at(2 * DAY).toISOString());
71 expect(draft.body).toContain("Hi Dana");
72 expect(draft.channel).toBe("text");
73 expect(draft.signature).toContain("Reply STOP");
74
75 const desk = value(listLeads(db, alice, { show: "needs", now: at(5 * DAY).getTime() }));
76 expect(desk.leads.map((l) => l.id)).toEqual([id]);
77 expect(desk.leads[0]!.ready?.since).toBe(at(2 * DAY).toISOString());
78 // The record measures first replies only: logging one changes nothing in it.
79 expect(value(listLeads(db, alice)).record).toEqual(before);
80 expect(before.replied).toBe(1);
81 });
82
83 test("follow-ups wait while the answer is owed, then start again from the day it goes", () => {
84 const { db, id } = answered();
85 // Day 1's follow-up is due before they write.
86 turn(db, at(2 * DAY));
87 expect(value(getLead(db, alice, { id })).messages.find((m) => m.day === 1)!.status).toBe("due");
88
89 logLeadReply(db, alice, { id, body: "Sounds good", channel: "email" }, at(2 * DAY));
90 const paused = value(getLead(db, alice, { id }));
91 expect(paused.messages.find((m) => m.day === 1)!.status).toBe("scheduled");
92 tick(db, alice);
93 turn(db, at(10 * DAY));
94 const desk = value(listLeads(db, alice, { show: "needs" }));
95 // Nothing but the answer is ready, however late the days run.
96 expect(desk.leads[0]!.ready!.day).toBeGreaterThanOrEqual(ANSWER_DAY);
97 expect(value(getLead(db, alice, { id })).messages.filter((m) => m.status === "due")).toEqual([]);
98
99 const sentAt = at(10 * DAY);
100 const after = value(sendReply(db, alice, { id }, sentAt));
101 const sentDay1 = after.messages.find((m) => m.day === 1)!;
102 expect(sentDay1.status).toBe("scheduled");
103 for (const day of [1, 3, 7, 14, 30])
104 expect(after.messages.find((m) => m.day === day)!.due_at).toBe(
105 new Date(sentAt.getTime() + day * DAY).toISOString(),
106 );
107 expect(after.messages.find((m) => m.day >= ANSWER_DAY)!.status).toBe("sent");
108 // The answer stops the clock: no longer in Needs you.
109 expect(value(listLeads(db, alice, { show: "needs" })).leads).toEqual([]);
110 });
111
112 test("sent touches are left as they were when the answer goes", () => {
113 const { db, id } = answered();
114 turn(db, at(2 * DAY));
115 value(sendReply(db, alice, { id }, at(2 * DAY))); // day 1 sent
116 logLeadReply(db, alice, { id, body: "Thanks!", channel: "email" }, at(3 * DAY));
117 value(sendReply(db, alice, { id }, at(3 * DAY)));
118 const lead = value(getLead(db, alice, { id }));
119 const d1 = lead.messages.find((m) => m.day === 1)!;
120 expect(d1.status).toBe("sent");
121 expect(d1.sent_at).toBe(at(2 * DAY).toISOString());
122 expect(d1.due_at).toBe(new Date(at(MIN).getTime() + DAY).toISOString());
123 });
124
125 test("a text reply for a lead without consent is refused; email is not", () => {
126 const { db, id } = answered(false);
127 const refused = logLeadReply(db, alice, { id, body: "text me", channel: "text" }, at(DAY));
128 expect(refused.ok).toBe(false);
129 expect(value(getLead(db, alice, { id })).replies).toEqual([]);
130 expect(logLeadReply(db, alice, { id, body: "email me", channel: "email" }, at(DAY)).ok).toBe(true);
131 // The drafted answer to a lead who may not be texted is an email.
132 expect(value(getLead(db, alice, { id })).messages.find((m) => m.day >= ANSWER_DAY)!.channel).toBe("email");
133 });
134
135 test("an empty, over-long, odd or channel-less body is refused", () => {
136 const { db, id } = answered();
137 const bad = (body: unknown, channel: unknown = "email") =>
138 logLeadReply(db, alice, { id, body, channel }, at(DAY));
139 for (const body of ["", " \n ", "x".repeat(2001), "bell\x07", "esc\x1b[2J", 5, undefined])
140 expect(bad(body).ok).toBe(false);
141 expect(bad("fine", "fax").ok).toBe(false);
142 expect(bad("fine", null).ok).toBe(false);
143 expect(bad("x".repeat(2000)).ok).toBe(true);
144 });
145
146 test("who may update a lead may log; nobody else; closed and unanswered leads are told why", () => {
147 const { db, id } = answered();
148 const r = logLeadReply(db, anon, { id, body: "hi", channel: "email" });
149 expect(!r.ok && r.error).toBe("signin_required");
150 expect(logLeadReply(db, alice, { id: 999, body: "hi", channel: "email" }).ok).toBe(false);
151 const fresher = arrive(db, true);
152 const early = logLeadReply(db, alice, { id: fresher, body: "hi", channel: "email" });
153 expect(!early.ok && early.message).toContain("first reply");
154 setState(db, alice, { id, state: "lost" });
155 const closed = logLeadReply(db, alice, { id, body: "hi", channel: "email" });
156 expect(!closed.ok && closed.message).toContain("put it back");
157 // Every attempt is in the audit trail.
158 const rows = db.query("SELECT act, outcome FROM audit WHERE act = 'inbound'").all();
159 expect(rows.length).toBe(4);
160 });
161
162 test("a second reply before the answer keeps one draft and the first clock", () => {
163 const { db, id } = answered();
164 logLeadReply(db, alice, { id, body: "one", channel: "email" }, at(DAY));
165 logLeadReply(db, alice, { id, body: "two", channel: "email" }, at(DAY + 5 * MIN));
166 const lead = value(getLead(db, alice, { id }));
167 expect(lead.replies.length).toBe(2);
168 const drafts = lead.messages.filter((m) => m.day >= ANSWER_DAY);
169 expect(drafts.length).toBe(1);
170 expect(drafts[0]!.due_at).toBe(at(DAY).toISOString());
171 });
172
173 test("marking lost skips the answer; putting it back does not revive it", () => {
174 const { db, id } = answered();
175 logLeadReply(db, alice, { id, body: "one", channel: "email" }, at(DAY));
176 setState(db, alice, { id, state: "lost" });
177 setState(db, alice, { id, state: "open" }, at(2 * DAY));
178 const lead = value(getLead(db, alice, { id }));
179 expect(lead.messages.find((m) => m.day >= ANSWER_DAY)!.status).toBe("skipped");
180 expect(lead.messages.find((m) => m.day === 1)!.status).toBe("scheduled");
181 });
182
183 // The doors.
184 const KEY = "a-key-only-the-forge-holds";
185 const server = serve({
186 port: 0,
187 dataDir: mkdtempSync(join(tmpdir(), "app-inbound-srv-")),
188 identityKey: KEY,
189 sample: false,
190 });
191 const base = `http://${server.hostname}:${server.port}`;
192 afterAll(() => server.stop(true));
193 let grants = 0;
194 const api = (path: string, init: RequestInit = {}, headers: Record<string, string> = {}) => {
195 const identity = `inbound-${++grants}|alice|user|${Date.now() + 60_000}`;
196 return fetch(base + path, {
197 redirect: "manual",
198 ...init,
199 headers: {
200 ...(init.headers as Record<string, string>),
201 ...headers,
202 "x-forge-identity": identity,
203 "x-forge-signature": sign(identity, KEY),
204 },
205 });
206 };
207 const json = (path: string, body: unknown) =>
208 api(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
209 const served = async (consent = true): Promise<number> => {
210 const made = await json("/leads", {
211 name: "Pat <i>Lee</i>",
212 email: "[email protected]",
213 phone: "206 555 0111",
214 source: "website",
215 message: "Do you have time to talk this week?",
216 consent,
217 });
218 if (made.status !== 201) throw new Error(`${made.status} ${await made.text()}`);
219 const { id } = (await made.json()) as { id: number };
220 await json(`/leads/${id}/reply`, {});
221 return id;
222 };
223
224 test("the API logs a reply; the page shows it escaped, on their side, and a form does too", async () => {
225 const id = await served();
226 const done = await json(`/leads/${id}/inbound`, { body: "<script>alert(1)</script> yes", channel: "text" });
227 expect(done.status).toBe(200);
228 expect(((await done.json()) as { replies: unknown[] }).replies.length).toBe(1);
229
230 const form = await api(`/leads/${id}/inbound`, {
231 method: "POST",
232 body: (() => {
233 const f = new FormData();
234 f.set("body", "Also Sunday <b>works</b>");
235 f.set("channel", "email");
236 return f;
237 })(),
238 });
239 expect(form.status).toBe(303);
240
241 const page = await (await api(`/leads/${id}`)).text();
242 expect(page).toContain("&lt;script&gt;alert(1)&lt;/script&gt; yes");
243 expect(page).not.toContain("<script>alert(1)");
244 expect(page).toContain("Also Sunday &lt;b&gt;works&lt;/b&gt;");
245 expect(page).toContain('data-from="lead"');
246 expect(page).toContain("wrote back");
247 expect(page).toContain("Answer to their reply");
248 expect(page).toContain(`action="/leads/${id}/inbound"`);
249
250 const desk = await (await api("/")).text();
251 expect(desk).toContain("They wrote back — answer drafted");
252
253 const bad = await json(`/leads/${id}/inbound`, { body: "", channel: "email" });
254 expect(bad.status).toBe(422);
255 const crossed = await api(
256 `/leads/${id}/inbound`,
257 { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: "body=x&channel=email" },
258 { origin: "https://evil.example", "sec-fetch-site": "cross-site" },
259 );
260 expect(crossed.status).toBe(403);
261 const noText = await served(false);
262 expect((await json(`/leads/${noText}/inbound`, { body: "hi", channel: "text" })).status).toBe(422);
263 // The page offers text only to a lead who may be texted.
264 expect(await (await api(`/leads/${noText}`)).text()).not.toContain('<option value="text">');
265 expect(page).toContain('<option value="text">');
266 });
267
268 test("/openapi.json describes the route", async () => {
269 const spec = (await (await api("/openapi.json")).json()) as {
270 paths: Record<string, Record<string, { requestBody?: unknown }>>;
271 };
272 expect(spec.paths["/leads/{id}/inbound"]!.post!.requestBody).toBeDefined();
273 });
274
275 test("MCP log_lead_reply logs one", async () => {
276 const id = await served();
277 const res = await api("/mcp", {
278 method: "POST",
279 headers: { "content-type": "application/json" },
280 body: JSON.stringify({
281 jsonrpc: "2.0",
282 id: 1,
283 method: "tools/call",
284 params: { name: "log_lead_reply", arguments: { id, body: "Call me", channel: "email" } },
285 }),
286 });
287 const out = (await res.json()) as { result: { isError?: boolean; content: { text: string }[] } };
288 expect(out.result.isError).toBeUndefined();
289 expect(JSON.parse(out.result.content[0]!.text).replies[0].body).toBe("Call me");
290 });
291
292 test("the terminal logs one with w, and offers text only with consent", () => {
293 const { db, id } = answered();
294 const t = terminal(db, alice);
295 const read = () => t.screen(100).map(plain).join("\n");
296 t.key("\r");
297 expect(read()).toContain("w they wrote back");
298 t.key("w");
299 for (const ch of "Yes, Saturday works") t.key(ch);
300 t.key("\x14");
301 expect(read()).toContain("by text");
302 t.key("\x04");
303 const screen = read();
304 expect(screen).toContain("They wrote back");
305 expect(screen).toContain("Yes, Saturday works");
306 expect(screen).toContain("Answer to their reply");
307 expect(value(getLead(db, alice, { id })).replies[0]!.channel).toBe("text");
308
309 const other = answered(false);
310 const u = terminal(other.db, alice);
311 u.key("\r");
312 u.key("w");
313 u.key("x");
314 u.key("\x14");
315 expect(u.screen(100).map(plain).join("\n")).toContain("by email");
316 });
317
318 test("a lead who opts out while their answer is unsent gets that answer as an email", async () => {
319 const { optOutTexts: optOutLead } = await import("./actions.ts");
320 const { db, id } = answered();
321 logLeadReply(db, alice, { id, body: "Yes, Saturday works", channel: "text" }, at(DAY));
322 value(optOutLead(db, alice, { id }));
323 const draft = value(getLead(db, alice, { id })).messages.find((m) => m.day >= ANSWER_DAY)!;
324 expect(draft.channel).toBe("email");
325 expect(draft.body).toContain("Thanks for getting back to me");
326 expect(draft.body).not.toContain("Day");
327 });
src/leads.ts +130 −16
@@ -13,9 +13,12 @@
1313
1414 import type { Database } from "bun:sqlite";
1515 import {
16 ANSWER_DAY,
17 answerDraft,
1618 CADENCE,
1719 channelFor,
1820 draft,
21 isAnswer,
1922 signature,
2023 type Channel,
2124 type Source,
@@ -58,14 +61,32 @@ export interface Message {
5861 readonly sent_by: string | null;
5962 }
6063
64 /** The most a lead's reply may hold. */
65 export const MAX_INBOUND = 2000;
66
67 /** What a lead wrote back, in their words, as the agent pasted it in. */
68 export interface Inbound {
69 readonly id: number;
70 readonly lead_id: number;
71 readonly channel: Channel;
72 readonly body: string;
73 readonly at: string;
74 }
75
6176 export interface LeadDetail extends Lead {
6277 readonly messages: readonly Message[];
78 /** What they wrote back, oldest first. */
79 readonly replies: readonly Inbound[];
6380 }
6481
82 /** When the lead began to wait on our answer to what they wrote back; null when no answer is owed. */
83 export const answerSince = (messages: readonly Message[]): string | null =>
84 messages.find((m) => isAnswer(m.day) && m.status === "draft")?.due_at ?? null;
85
6586 /** A row of the desk: the lead, what is waiting on us, and when the next touch comes. */
6687 export interface DeskLead extends Lead {
6788 /** The message ready to approve now — the first reply or a due touch — if any. */
68 readonly ready: { readonly id: number; readonly day: number } | null;
89 readonly ready: { readonly id: number; readonly day: number; readonly since: string } | null;
6990 /** When the next scheduled touch comes due, if one is. */
7091 readonly next_at: string | null;
7192 }
@@ -150,9 +171,19 @@ export const messagesOf = (db: Database, id: number): Message[] =>
150171 >("SELECT * FROM message WHERE lead_id = ?1 ORDER BY day")
151172 .all(id);
152173
174 export const repliesOf = (db: Database, id: number): Inbound[] =>
175 db
176 .query<
177 Inbound,
178 [number]
179 >("SELECT * FROM inbound WHERE lead_id = ?1 ORDER BY at, id")
180 .all(id);
181
153182 export function detail(db: Database, id: number): LeadDetail | null {
154183 const found = findLead(db, id);
155 return found === null ? null : { ...found, messages: messagesOf(db, id) };
184 return found === null
185 ? null
186 : { ...found, messages: messagesOf(db, id), replies: repliesOf(db, id) };
156187 }
157188
158189 export const MAX_QUERY = 80;
@@ -193,6 +224,7 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] {
193224 LeadRecord & {
194225 ready_id: number | null;
195226 ready_day: number | null;
227 ready_since: string | null;
196228 next_at: string | null;
197229 },
198230 [number, string, string]
@@ -200,6 +232,7 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] {
200232 `SELECT lead.*,
201233 (SELECT id FROM message WHERE lead_id = lead.id AND status IN ('draft', 'due') ORDER BY day LIMIT 1) AS ready_id,
202234 (SELECT day FROM message WHERE lead_id = lead.id AND status IN ('draft', 'due') ORDER BY day LIMIT 1) AS ready_day,
235 (SELECT due_at FROM message WHERE lead_id = lead.id AND status IN ('draft', 'due') ORDER BY day LIMIT 1) AS ready_since,
203236 (SELECT min(due_at) FROM message WHERE lead_id = lead.id AND status = 'scheduled') AS next_at
204237 FROM lead
205238 WHERE ?2 = '' OR lead.name LIKE ?2 ESCAPE '\\' OR lead.email LIKE ?2 ESCAPE '\\'
@@ -207,12 +240,12 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] {
207240 ORDER BY created_at DESC, id DESC LIMIT ?1`,
208241 )
209242 .all(limit, q === "" ? "" : likeOf(q), digits === "" ? "" : `%${digits}%`)
210 .map(({ ready_id, ready_day, next_at, ...row }) => ({
243 .map(({ ready_id, ready_day, ready_since, next_at, ...row }) => ({
211244 ...lead(row),
212245 ready:
213 ready_id === null || ready_day === null
246 ready_id === null || ready_day === null || ready_since === null
214247 ? null
215 : { id: ready_id, day: ready_day },
248 : { id: ready_id, day: ready_day, since: ready_since },
216249 next_at,
217250 }));
218251 }
@@ -373,11 +406,70 @@ export function send(
373406 open ? "scheduled" : "skipped",
374407 later(at, day),
375408 );
376 } else
409 } else {
377410 db.query("UPDATE lead SET updated_at = ?1 WHERE id = ?2").run(
378411 at,
379412 found.id,
380413 );
414 // Their answer is out: the follow-ups paused for it start again from today.
415 if (isAnswer(message.day)) respace(db, found.id, at);
416 }
417 })();
418 }
419
420 /** Touches not yet sent come due on the cadence's days counted from `at`. */
421 function respace(db: Database, id: number, at: string): void {
422 const waiting = db
423 .query<{ id: number; day: number }, [number]>(
424 "SELECT id, day FROM message WHERE lead_id = ?1 AND status = 'scheduled'",
425 )
426 .all(id);
427 for (const m of waiting)
428 db.query("UPDATE message SET due_at = ?1 WHERE id = ?2").run(
429 later(at, m.day),
430 m.id,
431 );
432 }
433
434 /**
435 * The lead wrote back, and the agent pasted it in at `at`: their words are
436 * kept, a short answer is drafted for the agent to edit and approve (its
437 * clock starts now), and follow-ups not yet sent wait until it goes. A
438 * second reply before the first is answered adds to the history and leaves
439 * the draft, and the clock, where they are. Returns the reply's id.
440 */
441 export function recordInbound(
442 db: Database,
443 found: Lead,
444 channel: Channel,
445 body: string,
446 at: string,
447 agent: Agent,
448 ): number {
449 return db.transaction(() => {
450 const { id } = db
451 .query<{ id: number }, [number, Channel, string, string]>(
452 "INSERT INTO inbound (lead_id, channel, body, at) VALUES (?1, ?2, ?3, ?4) RETURNING id",
453 )
454 .get(found.id, channel, body, at)!;
455 if (answerSince(messagesOf(db, found.id)) === null) {
456 db.query(
457 "UPDATE message SET status = 'scheduled' WHERE lead_id = ?1 AND status = 'due'",
458 ).run(found.id);
459 const reply = channelFor(found);
460 db.query(
461 "INSERT INTO message (lead_id, day, channel, body, signature, status, due_at) VALUES (?1, ?2, ?3, ?4, ?5, 'draft', ?6)",
462 ).run(
463 found.id,
464 ANSWER_DAY + id,
465 reply,
466 answerDraft(found, body),
467 signature(reply, agent),
468 at,
469 );
470 }
471 db.query("UPDATE lead SET updated_at = ?1 WHERE id = ?2").run(at, found.id);
472 return id;
381473 })();
382474 }
383475
@@ -395,15 +487,30 @@ export function redraftUnsent(db: Database, agent: Agent): void {
395487 db.transaction(() => {
396488 for (const m of unsent) {
397489 const found = findLead(db, m.lead_id)!;
398 db.query("UPDATE message SET body = ?1, signature = ?2 WHERE id = ?3").run(
399 draft(found, m.day, agent),
400 signature(m.channel, agent),
401 m.id,
402 );
490 if (isAnswer(m.day))
491 db.query("UPDATE message SET signature = ?1 WHERE id = ?2").run(
492 signature(m.channel, agent),
493 m.id,
494 );
495 else
496 db.query("UPDATE message SET body = ?1, signature = ?2 WHERE id = ?3").run(
497 draft(found, m.day, agent),
498 signature(m.channel, agent),
499 m.id,
500 );
403501 }
404502 })();
405503 }
406504
505 /** The answer to the reply it was drafted for, drafted again for the lead as they are now. */
506 const answerAgain = (db: Database, found: Lead, day: number): string =>
507 answerDraft(
508 found,
509 db
510 .query<{ body: string }, [number]>("SELECT body FROM inbound WHERE id = ?1")
511 .get(day - ANSWER_DAY)?.body ?? "",
512 );
513
407514 /**
408515 * They replied STOP: consent ends, and every message not yet sent is
409516 * drafted again as an email (the edit of an unsent text is replaced).
@@ -425,7 +532,12 @@ export function optOut(db: Database, found: Lead, at: string, agent: Agent): voi
425532 for (const m of unsent)
426533 db.query(
427534 "UPDATE message SET channel = ?1, body = ?2, signature = ?3 WHERE id = ?4",
428 ).run(channel, draft(now, m.day, agent), signature(channel, agent), m.id);
535 ).run(
536 channel,
537 isAnswer(m.day) ? answerAgain(db, now, m.day) : draft(now, m.day, agent),
538 signature(channel, agent),
539 m.id,
540 );
429541 })();
430542 }
431543
@@ -464,10 +576,10 @@ export function reopen(db: Database, found: Lead, at: string, agent: Agent): voi
464576 );
465577 const channel = channelFor(found);
466578 const skipped = db
467 .query<{ id: number; day: number }, [number]>(
468 "SELECT id, day FROM message WHERE lead_id = ?1 AND status = 'skipped'",
579 .query<{ id: number; day: number; due_at: string }, [number, number]>(
580 "SELECT id, day, due_at FROM message WHERE lead_id = ?1 AND status = 'skipped' AND day < ?2",
469581 )
470 .all(found.id);
582 .all(found.id, ANSWER_DAY);
471583 for (const m of skipped)
472584 db.query(
473585 "UPDATE message SET status = ?1, channel = ?2, body = ?3, signature = ?4, due_at = ?5 WHERE id = ?6",
@@ -476,9 +588,10 @@ export function reopen(db: Database, found: Lead, at: string, agent: Agent): voi
476588 channel,
477589 draft(found, m.day, agent),
478590 signature(channel, agent),
479 m.day === 0 ? found.created_at : later(at, m.day),
591 m.day === 0 ? found.created_at : m.due_at,
480592 m.id,
481593 );
594 respace(db, found.id, at);
482595 })();
483596 }
484597
@@ -489,6 +602,7 @@ export function advance(db: Database, at: string): number[] {
489602 `UPDATE message SET status = 'due'
490603 WHERE status = 'scheduled' AND due_at <= ?1
491604 AND lead_id IN (SELECT id FROM lead WHERE state = 'contacted')
605 AND lead_id NOT IN (SELECT lead_id FROM message WHERE day >= ${ANSWER_DAY} AND status = 'draft')
492606 RETURNING lead_id`,
493607 )
494608 .all(at)
src/mcp.ts +18 −1
@@ -17,11 +17,12 @@ import {
1717 optOutTexts,
1818 approveReply,
1919 setState,
20 logLeadReply,
2021 type Result,
2122 } from "./actions.ts";
2223 import { SOURCES } from "./drafts.ts";
2324 import { title } from "./env.ts";
24 import { Q_HELP, VIEW_HELP, VIEWS } from "./leads.ts";
25 import { MAX_INBOUND, Q_HELP, VIEW_HELP, VIEWS } from "./leads.ts";
2526 import { fields } from "./http.ts";
2627 import type { Who } from "./who.ts";
2728
@@ -111,6 +112,22 @@ export const tools: readonly Tool[] = [
111112 body: typeof args.body === "string" ? args.body : undefined,
112113 }),
113114 },
115 {
116 name: "log_lead_reply",
117 description:
118 "The lead wrote back: record their words (and the channel they used) in the history. The lead returns to Needs you with a fresh response clock and a drafted answer to edit and approve with send_reply; follow-ups not yet sent pause until then. Nothing is sent. Text only for a lead who gave written consent.",
119 inputSchema: {
120 type: "object",
121 properties: {
122 id: { type: "integer" },
123 body: { type: "string", minLength: 1, maxLength: MAX_INBOUND },
124 channel: { enum: ["text", "email"] },
125 },
126 required: ["id", "body", "channel"],
127 },
128 run: (db, who, args) =>
129 logLeadReply(db, who, { id: Number(args.id), body: args.body, channel: args.channel }),
130 },
114131 {
115132 name: "mark_lead",
116133 description: "Mark a lead qualified or lost; it leaves the follow-up plan; 'open' puts a closed lead back in it.",
src/pages/desk.ts +7 −3
@@ -7,6 +7,7 @@ import { day, clock, consent, source, STATE_LABEL } from "./parts.ts";
77 import { layout } from "./layout.ts";
88 import { escape } from "../http.ts";
99 import { recordLine } from "../clock.ts";
10 import { isAnswer } from "../drafts.ts";
1011 import type { DeskLead, ResponseRecord, View } from "../leads.ts";
1112 import type { Agent } from "../env.ts";
1213 import type { Who } from "../who.ts";
@@ -46,8 +47,9 @@ export function deskPage(input: {
4647 const show = input.show ?? "all";
4748 const counts = input.counts;
4849 const waiting = leads.filter((l) => l.ready?.day === 0).length;
49 const due = leads.filter((l) => l.ready !== null && l.ready.day > 0).length;
50 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>`;
50 const answers = leads.filter((l) => l.ready !== null && isAnswer(l.ready.day)).length;
51 const due = leads.filter((l) => l.ready !== null && l.ready.day > 0 && !isAnswer(l.ready.day)).length;
52 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>`;
5153 const record = input.record === undefined ? "" : `<p class="record">${escape(recordLine(input.record))}</p>`;
5254 const q = input.q ?? "";
5355 const views =
@@ -138,6 +140,8 @@ function status(lead: DeskLead): string {
138140 return `<span class="status" data-state="${lead.state}">${STATE_LABEL[lead.state]}</span>`;
139141 if (lead.ready?.day === 0)
140142 return `<span class="status" data-ready>Reply drafted — approve and send</span>`;
143 if (lead.ready !== null && isAnswer(lead.ready.day))
144 return `<span class="status" data-ready>They wrote back — answer drafted</span>`;
141145 if (lead.ready !== null)
142146 return `<span class="status" data-ready>Day ${lead.ready.day} follow-up ready</span>`;
143147 if (lead.next_at !== null)
@@ -153,7 +157,7 @@ const row = (lead: DeskLead, now: number): string => `<li>
153157 <span class="ask">${escape(lead.message)}</span>
154158 ${status(lead)}
155159 </span>
156 ${clock(lead, now)}
160 ${clock(lead, now, lead.ready !== null && isAnswer(lead.ready.day) ? lead.ready.since : null)}
157161 </a>
158162 </li>`;
159163
src/pages/lead.ts +47 −11
@@ -4,19 +4,28 @@
44 * follow-ups to come.
55 */
66
7 import { channelFor, MAX_BODY } from "../drafts.ts";
7 import { channelFor, isAnswer, MAX_BODY } from "../drafts.ts";
88 import { escape } from "../http.ts";
99 import { elapsed, between } from "../clock.ts";
10 import type { LeadDetail, Message, NextLead } from "../leads.ts";
10 import { answerSince, MAX_INBOUND, type LeadDetail, type Message, type NextLead } from "../leads.ts";
1111 import type { Agent } from "../env.ts";
1212 import type { Who } from "../who.ts";
1313 import { layout } from "./layout.ts";
1414 import { clock, consent, day, source, STATE_LABEL, when } from "./parts.ts";
1515
16 /** One line of the thread: something we sent, or something they wrote back. */
17 type HistoryEntry =
18 | { at: string; ours: Message; theirs?: undefined }
19 | { at: string; theirs: LeadDetail["replies"][number]; ours?: undefined };
20
1621 const CHANNEL = { text: "text", email: "email" } as const;
1722
1823 const titleOf = (m: Message): string =>
19 m.day === 0 ? "First reply" : `Day ${m.day} follow-up`;
24 m.day === 0
25 ? "First reply"
26 : isAnswer(m.day)
27 ? "Answer to their reply"
28 : `Day ${m.day} follow-up`;
2029
2130 /** A message's words, line breaks kept, and the signature under them. */
2231 const words = (m: Pick<Message, "body" | "signature">): string =>
@@ -37,7 +46,8 @@ export function leadPage(input: {
3746 (m) => m.status === "draft" || m.status === "due",
3847 );
3948 const sent = lead.messages.filter((m) => m.status === "sent");
40 const cadence = lead.messages.filter((m) => m.day > 0);
49 const cadence = lead.messages.filter((m) => m.day > 0 && !isAnswer(m.day));
50 const owed = answerSince(lead.messages);
4151 const closed = lead.state === "qualified" || lead.state === "lost";
4252 const path = `/leads/${lead.id}`;
4353 const contact = [
@@ -82,14 +92,23 @@ export function leadPage(input: {
8292 }
8393 </div>`;
8494
95 const history: HistoryEntry[] = [
96 ...sent.map((m) => ({ at: m.sent_at ?? m.due_at, ours: m })),
97 ...lead.replies.map((r) => ({ at: r.at, theirs: r })),
98 ].sort((a, b) => Date.parse(a.at) - Date.parse(b.at));
8599 const thread =
86 sent.length === 0
100 history.length === 0
87101 ? ""
88 : `<section class="card"><h2>Sent</h2><ol class="thread">${sent
89 .map(
90 (m) => `<li>
91 <p class="meta">${titleOf(m)} · ${CHANNEL[m.channel]} · <time datetime="${escape(m.sent_at ?? "")}">${escape(when(m.sent_at ?? m.due_at))}</time>${m.sent_by ? ` · approved by ${escape(m.sent_by)}` : ""}</p>
92 ${words(m)}
102 : `<section class="card"><h2>History</h2><ol class="thread">${history
103 .map(({ ours: m, theirs: r }) =>
104 r !== undefined
105 ? `<li data-from="lead">
106 <p class="meta">${escape(lead.name)} wrote back · ${CHANNEL[r.channel]} · <time datetime="${escape(r.at)}">${escape(when(r.at))}</time></p>
107 <p class="body">${escape(r.body)}</p>
108 </li>`
109 : `<li>
110 <p class="meta">${titleOf(m!)} · ${CHANNEL[m!.channel]} · <time datetime="${escape(m!.sent_at ?? "")}">${escape(when(m!.sent_at ?? m!.due_at))}</time>${m!.sent_by ? ` · approved by ${escape(m!.sent_by)}` : ""}</p>
111 ${words(m!)}
93112 </li>`,
94113 )
95114 .join("")}</ol></section>`;
@@ -120,6 +139,22 @@ export function leadPage(input: {
120139 </section>`
121140 : "";
122141
142 const record =
143 mayUpdate && !closed && lead.replied_at !== null
144 ? `<details class="card add record">
145 <summary>They wrote back</summary>
146 <form class="stack" method="post" action="${path}/inbound">
147 <label>What they wrote <textarea class="input" name="body" required maxlength="${MAX_INBOUND}" rows="4"></textarea></label>
148 <label>How they wrote
149 <select class="input" name="channel">
150 <option value="email">Email</option>${channelFor(lead) === "text" ? '\n <option value="text">Text</option>' : ""}
151 </select>
152 </label>
153 <button class="button">Record it and draft my answer</button>
154 </form>
155 </details>`
156 : "";
157
123158 const stop =
124159 mayUpdate && lead.consent
125160 ? `<section class="states">
@@ -153,7 +188,7 @@ export function leadPage(input: {
153188 <p class="tags">${source(lead)}${consent(lead)}<span class="chip" data-state="${lead.state}">${STATE_LABEL[lead.state]}</span></p>
154189 <p class="contact">${contact}</p>
155190 </div>
156 ${clock(lead)}
191 ${clock(lead, now, owed)}
157192 </header>
158193 <div class="split">
159194 <div class="pane theirs">
@@ -163,6 +198,7 @@ export function leadPage(input: {
163198 ${draft}
164199 </div>
165200 ${thread}
201 ${record}
166202 ${plan}
167203 ${states}
168204 ${stop}
src/pages/parts.ts +8 −2
@@ -8,9 +8,15 @@ import type { Lead } from "../leads.ts";
88 /**
99 * The response clock. Waiting, it counts up from the inquiry
1010 * (`static/clock.js` keeps it ticking); answered, it holds how long the
11 * first reply took.
11 * first reply took. Once they write back, it counts from that moment again
12 * (`owedSince`) until the answer goes out.
1213 */
13 export function clock(lead: Lead, now = Date.now()): string {
14 export function clock(lead: Lead, now = Date.now(), owedSince: string | null = null): string {
15 // They wrote back: the clock starts again from the moment it was logged.
16 if (owedSince !== null) {
17 const waited = between(owedSince, now);
18 return `<span class="clock" data-tone="${tone(waited)}" data-since="${escape(owedSince)}" role="timer" aria-label="Waiting since they wrote back"><small>waiting</small> <span class="clock-time">${elapsed(waited)}</span></span>`;
19 }
1420 if (lead.replied_at !== null) {
1521 const took = between(lead.created_at, lead.replied_at);
1622 return `<span class="clock clock-done" data-tone="${tone(took)}"><small>answered in</small> <span class="clock-time">${elapsed(took)}</span></span>`;
src/routes.ts +64 −5
@@ -29,6 +29,7 @@ import {
2929 approveReply,
3030 nextLead,
3131 setState,
32 logLeadReply,
3233 tick,
3334 type Failure,
3435 type Result,
@@ -50,7 +51,7 @@ import {
5051 staticFile,
5152 text,
5253 } from "./http.ts";
53 import { MAX_QUERY, Q_HELP, VIEW_HELP, VIEWS } from "./leads.ts";
54 import { MAX_INBOUND, MAX_QUERY, Q_HELP, VIEW_HELP, VIEWS } from "./leads.ts";
5455 import { events } from "./live.ts";
5556 import { rpc } from "./mcp.ts";
5657 import { deskPage } from "./pages/desk.ts";
@@ -99,7 +100,11 @@ export const MESSAGE: Schema = {
99100 properties: {
100101 id: { type: "integer" },
101102 lead_id: { type: "integer" },
102 day: { enum: [0, ...CADENCE], description: "0 is the first reply." },
103 day: {
104 type: "integer",
105 minimum: 0,
106 description: `0 is the first reply, ${CADENCE.join(", ")} a follow-up's day; 1000 and up answers something the lead wrote back.`,
107 },
103108 channel: { enum: ["text", "email"] },
104109 body: { type: "string", minLength: 1, maxLength: MAX_BODY.email },
105110 signature: { type: "string" },
@@ -132,10 +137,29 @@ const LEAD_FIELDS = {
132137 updated_at: STAMP,
133138 } as const;
134139 const LEAD_REQUIRED = Object.keys(LEAD_FIELDS);
140 const INBOUND: Schema = {
141 type: "object",
142 properties: {
143 id: { type: "integer" },
144 lead_id: { type: "integer" },
145 channel: { enum: ["text", "email"] },
146 body: { type: "string", minLength: 1, maxLength: MAX_INBOUND },
147 at: STAMP,
148 },
149 required: ["id", "lead_id", "channel", "body", "at"],
150 };
135151 export const LEAD: Schema = {
136152 type: "object",
137 properties: { ...LEAD_FIELDS, messages: { type: "array", items: MESSAGE } },
138 required: [...LEAD_REQUIRED, "messages"],
153 properties: {
154 ...LEAD_FIELDS,
155 messages: { type: "array", items: MESSAGE },
156 replies: {
157 type: "array",
158 description: "What the lead wrote back, oldest first.",
159 items: INBOUND,
160 },
161 },
162 required: [...LEAD_REQUIRED, "messages", "replies"],
139163 };
140164 export const APPROVED: Schema = {
141165 type: "object",
@@ -158,7 +182,11 @@ export const DESK_LEAD: Schema = {
158182 ready: {
159183 type: ["object", "null"],
160184 description: "The message ready to approve now, if any.",
161 properties: { id: { type: "integer" }, day: { type: "integer" } },
185 properties: {
186 id: { type: "integer" },
187 day: { type: "integer" },
188 since: { ...STAMP, description: "When it began to wait on you." },
189 },
162190 },
163191 next_at: { type: ["string", "null"], format: "date-time" },
164192 },
@@ -519,6 +547,37 @@ export const routes: readonly Route[] = [
519547 answer: APPROVED,
520548 },
521549 },
550 {
551 method: "POST",
552 path: "/leads/:id/inbound",
553 handle: (c) =>
554 posted(
555 c,
556 (input) =>
557 logLeadReply(c.db, c.who, {
558 id: ID(c),
559 body: input.body,
560 channel: input.channel,
561 }),
562 () => ({
563 to: `/leads/${ID(c)}`,
564 said: "Logged. Their answer is drafted for you to approve.",
565 }),
566 ),
567 api: {
568 summary:
569 "The lead wrote back and you paste it in: their words join the history, the lead is back in Needs you with a fresh response clock and a drafted answer, and follow-ups not yet sent pause until it goes. Nothing is sent.",
570 body: {
571 type: "object",
572 properties: {
573 body: { type: "string", minLength: 1, maxLength: MAX_INBOUND, description: "What they wrote." },
574 channel: { enum: ["text", "email"], description: "How they wrote; text only for a lead who gave written consent." },
575 },
576 required: ["body", "channel"],
577 },
578 answer: LEAD,
579 },
580 },
522581 {
523582 method: "POST",
524583 path: "/leads/:id/state",
src/sentences.ts +5
@@ -30,6 +30,11 @@ export function deed(
3030 done: `marked ${lead} ${row.act}`,
3131 tried: `mark ${lead} ${row.act}`,
3232 };
33 if (row.act === "inbound")
34 return {
35 done: `logged what ${lead} wrote back`,
36 tried: `log what ${lead} wrote back`,
37 };
3338 if (row.act === "reopened")
3439 return {
3540 done: `put ${lead} back in follow-ups`,
src/server.test.ts +1
@@ -287,6 +287,7 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
287287 "add_lead",
288288 "new_sample_inquiry",
289289 "send_reply",
290 "log_lead_reply",
290291 "mark_lead",
291292 "opt_out_texts",
292293 "get_profile",
src/terminal.ts +69 −11
@@ -6,9 +6,10 @@
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 · ] next lead that needs you ·
9 * lead s approve and send · e edit, then send · w they wrote back · ] next lead that needs you ·
1010 * q qualified · x lost · t asked to stop texts · D remove (admin) · esc back
1111 * edit type; enter is a new line · ctrl-d approve and send · esc cancel
12 * wrote type what they wrote · ctrl-t text/email (text only with consent) · ctrl-d record it and draft the answer · esc cancel
1213 * add one field at a time; enter next · esc cancel
1314 * profile the name, brokerage and license every message carries ·
1415 * e edit (admin): one field at a time, enter next, the last saves · esc back
@@ -33,15 +34,16 @@ import {
3334 resetSample,
3435 saveProfile,
3536 approveReply,
37 logLeadReply,
3638 nextLead,
3739 setState,
3840 } from "./actions.ts";
3941 import { between, elapsed, recordLine, tone } from "./clock.ts";
4042 import { permit } from "./contract.ts";
4143 import { said as saidOf } from "./sentences.ts";
42 import { SOURCE_LABEL, SOURCES, channelFor } from "./drafts.ts";
44 import { SOURCE_LABEL, SOURCES, channelFor, isAnswer, type Channel } from "./drafts.ts";
4345 import { ssh, title, where } from "./env.ts";
44 import { CLOSED, MAX_QUERY, VIEWS, queryOf, type DeskLead, type LeadDetail, type Message, type View as DeskView } from "./leads.ts";
46 import { answerSince, CLOSED, MAX_QUERY, VIEWS, queryOf, type DeskLead, type LeadDetail, type Message, type View as DeskView } from "./leads.ts";
4547 import { currentAgent } from "./profile.ts";
4648 import type { Who } from "./who.ts";
4749
@@ -112,11 +114,16 @@ type View =
112114 | { name: "profile-edit"; step: number; typed: string; fields: Record<string, string> }
113115 | { name: "lead"; id: number }
114116 | { name: "edit"; id: number; text: string }
117 | { name: "wrote"; id: number; text: string; channel: Channel }
115118 | { name: "add"; step: number; typed: string; fields: Record<string, string> }
116119 | { name: "confirm"; what: "remove" | "reset" | "opt-out"; id?: number; back: View };
117120
118121 const titleOf = (m: Message): string =>
119 m.day === 0 ? "First reply" : `Day ${m.day} follow-up`;
122 m.day === 0
123 ? "First reply"
124 : isAnswer(m.day)
125 ? "Answer to their reply"
126 : `Day ${m.day} follow-up`;
120127
121128 export interface Terminal {
122129 /** The screen as lines, for the width given. */
@@ -165,10 +172,19 @@ export function terminal(
165172 l.messages.find((m) => m.status === "draft" || m.status === "due");
166173
167174 function clockOf(l: DeskLead | LeadDetail): string {
168 const waiting = l.replied_at === null;
169 const ms = waiting
170 ? between(l.created_at, now())
171 : between(l.created_at, l.replied_at!);
175 // They wrote back: the clock runs again from the moment it was logged.
176 const owed =
177 "messages" in l
178 ? answerSince(l.messages)
179 : l.ready !== null && isAnswer(l.ready.day)
180 ? l.ready.since
181 : null;
182 const waiting = l.replied_at === null || owed !== null;
183 const ms = owed !== null
184 ? between(owed, now())
185 : waiting
186 ? between(l.created_at, now())
187 : between(l.created_at, l.replied_at!);
172188 return `${paint(COLOUR[tone(ms)], elapsed(ms).padStart(7))} ${waiting ? "waiting " : "answered"}`;
173189 }
174190
@@ -205,7 +221,9 @@ export function terminal(
205221 ? dim(l.state === "qualified" || l.state === "lost" ? l.state : "")
206222 : l.ready.day === 0
207223 ? "reply drafted"
208 : `day ${l.ready.day} follow-up ready`;
224 : isAnswer(l.ready.day)
225 ? "wrote back · answer drafted"
226 : `day ${l.ready.day} follow-up ready`;
209227 const name = clean(l.name).padEnd(18).slice(0, 18);
210228 lines.push(
211229 `${i === cursor ? "▸" : " "} ${clockOf(l)} ${i === cursor ? bold(name) : name} ${dim(SOURCE_LABEL[l.source].padEnd(12))} ${next}`,
@@ -235,6 +253,11 @@ export function terminal(
235253 bold("They asked"),
236254 ...wrap(l.message, width).map((s) => ` ${s}`),
237255 "",
256 ...l.replies.flatMap((x) => [
257 bold(`They wrote back — ${x.channel}, ${x.at.slice(0, 16).replace("T", " ")}`),
258 ...wrap(x.body, width).map((s) => ` ${s}`),
259 "",
260 ]),
238261 ];
239262 if (r === undefined) {
240263 const next = l.messages.find((m) => m.status === "scheduled");
@@ -274,7 +297,7 @@ export function terminal(
274297 "",
275298 dim(
276299 `${sent} sent · plan: ${l.messages
277 .filter((m) => m.day > 0)
300 .filter((m) => m.day > 0 && !isAnswer(m.day))
278301 .map((m) => `day ${m.day} ${m.status}`)
279302 .join(", ") || "starts with the first reply"}`,
280303 ),
@@ -284,6 +307,7 @@ export function terminal(
284307 : dim(
285308 [
286309 ...(r === undefined ? [] : ["s approve and send", "e edit"]),
310 ...(l.replied_at !== null && !CLOSED.includes(l.state) ? ["w they wrote back"] : []),
287311 ...(l.state === "qualified" || l.state === "lost"
288312 ? ["o put back in follow-ups"]
289313 : ["q qualified", "x lost"]),
@@ -419,6 +443,14 @@ export function terminal(
419443 ? leadScreen(view.id, w)
420444 : view.name === "edit"
421445 ? leadScreen(view.id, w, view.text)
446 : view.name === "wrote"
447 ? [
448 bold(`What ${clean(lead(view.id)?.name ?? "the lead")} wrote back — by ${view.channel}`),
449 "",
450 ...wrap(`${view.text}█`, w).map((s) => ` ${s}`),
451 "",
452 dim("type or paste · enter new line · ctrl-t text/email · ctrl-d record it and draft my answer · esc cancel"),
453 ]
422454 : view.name === "add"
423455 ? addScreen(view)
424456 : [
@@ -548,7 +580,9 @@ export function terminal(
548580 state: input === "q" ? "qualified" : "lost",
549581 });
550582 said = marked.ok ? `${l.name}: ${marked.value.state}.` : marked.message;
551 } else if (input === "o" && CLOSED.includes(l.state)) {
583 } else if (input === "w")
584 view = { name: "wrote", id, text: "", channel: "email" };
585 else if (input === "o" && CLOSED.includes(l.state)) {
552586 const back = setState(db, me, { id, state: "open" });
553587 said = back.ok ? `${l.name}: back in follow-ups.` : back.message;
554588 } else if (input === "t" && l.consent)
@@ -569,6 +603,30 @@ export function terminal(
569603 }
570604 return;
571605 }
606 case "wrote": {
607 if (input === "\x1b") {
608 said = "Nothing recorded.";
609 view = { name: "lead", id: view.id };
610 } else if (input === "\x14") {
611 // Text is offered only to a lead who may be texted; the action refuses the rest.
612 const l = lead(view.id);
613 view = {
614 ...view,
615 channel: view.channel === "email" && l !== undefined && channelFor(l) === "text" ? "text" : "email",
616 };
617 } else if (input === "\x04") {
618 const logged = logLeadReply(db, me, { id: view.id, body: view.text, channel: view.channel });
619 said = logged.ok
620 ? `Recorded. ${logged.value.name} is waiting on you; the answer is drafted.`
621 : logged.message;
622 if (logged.ok) view = { name: "lead", id: view.id };
623 } else if (input === "\r") view = { ...view, text: `${view.text}\n` };
624 else {
625 const next = typing(view.text, input.replace(/\r\n?/g, "\n"));
626 if (next !== undefined) view = { ...view, text: next };
627 }
628 return;
629 }
572630 case "search": {
573631 if (input === "\x1b") view = { name: "desk" };
574632 else if (input === "\r") {
static/app.css +7
@@ -620,3 +620,10 @@ label.check input {
620620 list-style: none;
621621 padding-left: var(--space-4);
622622 }
623
624 /* What the lead wrote back sits on the other side of the thread from our words. */
625 .thread li[data-from="lead"] {
626 margin-left: var(--space-5);
627 padding-left: var(--space-3);
628 border-left: 3px solid var(--color-brass);
629 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs