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

The agent keeps a few saved replies (lender intro, open-house details) and drops one into any draft before approving it #83

Merged opened this

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

Merged

mason/speed-to-lead:mason/78-the-agent-keeps-a-few-saved-replies-lend → main 1 commit fork

  • Merged. mason/78-the-agent-keeps-a-few-saved-replies-lend was merged into main as 25511d4.

Review

Sign in to review this change.
17 files changed +788 −40
README.md +4
@@ -409,6 +409,10 @@ A script reads it with `GET /profile` and an admin changes it with
409409 `POST /profile` (JSON, the five fields and optionally `timeZone`); MCP has `get_profile` and
410410 `set_profile`.
411411
412 ### Saved replies
413
414 The profile keeps up to 12 saved replies (a name of at most 40 characters, text of at most 1,000), edited with the profile by whoever may update it; two samples (a lender intro and an open-house invite) ship until you save your own. While editing a draft on a lead's page, **Insert saved reply** adds the chosen text at the end of the draft box (a small script does it in place; without JavaScript the same button posts to `/leads/{id}/insert` and returns the page with the text appended). Nothing is sent until **Approve and send**, and a text's usual length limit still applies. `{first_name}` becomes the lead's first name; nothing else is interpolated. JSON: `replies` in `GET`/`POST /profile`, `POST /leads/{id}/insert`; MCP: `insert_saved_reply` and `set_profile`'s `replies`.
415
412416 ## For whoever connects it to a website
413417
414418 Every page has a JSON twin. Send `content-type: application/json` (or
contract/openapi.json +161 −2
@@ -802,6 +802,85 @@
802802 }
803803 }
804804 },
805 "/leads/{id}/insert": {
806 "post": {
807 "summary": "Add one of the agent's saved replies to the end of the draft that is ready for this lead and answer with the words, unsent and unsaved. `{first_name}` becomes the lead's first name. A text or email that would be too long is refused with 422. Send the result with POST /leads/{id}/reply.",
808 "operationId": "postLeadsIdInsert",
809 "parameters": [
810 {
811 "name": "id",
812 "in": "path",
813 "required": true,
814 "schema": {
815 "type": "integer"
816 }
817 }
818 ],
819 "requestBody": {
820 "required": true,
821 "content": {
822 "application/json": {
823 "schema": {
824 "type": "object",
825 "properties": {
826 "reply": {
827 "type": "string",
828 "minLength": 1,
829 "maxLength": 40,
830 "description": "The name of a saved reply, as in GET /profile."
831 },
832 "body": {
833 "type": "string",
834 "maxLength": 4000,
835 "description": "The words in the edit box now; the draft when left out."
836 }
837 },
838 "required": [
839 "reply"
840 ]
841 }
842 }
843 }
844 },
845 "responses": {
846 "200": {
847 "description": "Add one of the agent's saved replies to the end of the draft that is ready for this lead and answer with the words, unsent and unsaved. `{first_name}` becomes the lead's first name. A text or email that would be too long is refused with 422. Send the result with POST /leads/{id}/reply.",
848 "content": {
849 "application/json": {
850 "schema": {
851 "type": "object",
852 "properties": {
853 "body": {
854 "type": "string"
855 },
856 "channel": {
857 "enum": [
858 "text",
859 "email"
860 ]
861 }
862 },
863 "required": [
864 "body",
865 "channel"
866 ]
867 }
868 }
869 }
870 },
871 "default": {
872 "description": "{ error, message }: why not",
873 "content": {
874 "application/json": {
875 "schema": {
876 "$ref": "#/components/schemas/Error"
877 }
878 }
879 }
880 }
881 }
882 }
883 },
805884 "/leads/{id}/inbound": {
806885 "post": {
807886 "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.",
@@ -1541,6 +1620,32 @@
15411620 "maximum": 90
15421621 },
15431622 "description": "The days after the first reply that each get a follow-up (default 1, 3, 7, 14, 30): 1 to 8 whole days, each 1 to 90, strictly increasing. A form may send it as text, \"1, 3, 7\". Applies to leads answered after the change; leads already in their follow-ups keep the touches scheduled. Left out, it stays as it is; anything else is refused with 422."
1623 },
1624 "replies": {
1625 "type": "array",
1626 "maxItems": 12,
1627 "items": {
1628 "type": "object",
1629 "properties": {
1630 "name": {
1631 "type": "string",
1632 "minLength": 1,
1633 "maxLength": 40
1634 },
1635 "text": {
1636 "type": "string",
1637 "minLength": 1,
1638 "maxLength": 1000,
1639 "description": "Plain text. {first_name} is filled with the lead's first name when it is inserted; nothing else is."
1640 }
1641 },
1642 "required": [
1643 "name",
1644 "text"
1645 ],
1646 "additionalProperties": false
1647 },
1648 "description": "Saved replies: up to 12, each a one-line name (at most 40 characters, no two alike) and text (at most 1000). The list replaces the one kept; left out, it stays as it is; [] takes them all away; anything else is refused with 422."
15441649 }
15451650 },
15461651 "required": [
@@ -1552,7 +1657,8 @@
15521657 "email",
15531658 "timeZone",
15541659 "openers",
1555 "cadence"
1660 "cadence",
1661 "replies"
15561662 ]
15571663 }
15581664 }
@@ -1646,6 +1752,32 @@
16461752 "maximum": 90
16471753 },
16481754 "description": "The days after the first reply that each get a follow-up (default 1, 3, 7, 14, 30): 1 to 8 whole days, each 1 to 90, strictly increasing. A form may send it as text, \"1, 3, 7\". Applies to leads answered after the change; leads already in their follow-ups keep the touches scheduled. Left out, it stays as it is; anything else is refused with 422."
1755 },
1756 "replies": {
1757 "type": "array",
1758 "maxItems": 12,
1759 "items": {
1760 "type": "object",
1761 "properties": {
1762 "name": {
1763 "type": "string",
1764 "minLength": 1,
1765 "maxLength": 40
1766 },
1767 "text": {
1768 "type": "string",
1769 "minLength": 1,
1770 "maxLength": 1000,
1771 "description": "Plain text. {first_name} is filled with the lead's first name when it is inserted; nothing else is."
1772 }
1773 },
1774 "required": [
1775 "name",
1776 "text"
1777 ],
1778 "additionalProperties": false
1779 },
1780 "description": "Saved replies: up to 12, each a one-line name (at most 40 characters, no two alike) and text (at most 1000). The list replaces the one kept; left out, it stays as it is; [] takes them all away; anything else is refused with 422."
16491781 }
16501782 },
16511783 "required": [
@@ -1736,6 +1868,32 @@
17361868 "maximum": 90
17371869 },
17381870 "description": "The days after the first reply that each get a follow-up (default 1, 3, 7, 14, 30): 1 to 8 whole days, each 1 to 90, strictly increasing. A form may send it as text, \"1, 3, 7\". Applies to leads answered after the change; leads already in their follow-ups keep the touches scheduled. Left out, it stays as it is; anything else is refused with 422."
1871 },
1872 "replies": {
1873 "type": "array",
1874 "maxItems": 12,
1875 "items": {
1876 "type": "object",
1877 "properties": {
1878 "name": {
1879 "type": "string",
1880 "minLength": 1,
1881 "maxLength": 40
1882 },
1883 "text": {
1884 "type": "string",
1885 "minLength": 1,
1886 "maxLength": 1000,
1887 "description": "Plain text. {first_name} is filled with the lead's first name when it is inserted; nothing else is."
1888 }
1889 },
1890 "required": [
1891 "name",
1892 "text"
1893 ],
1894 "additionalProperties": false
1895 },
1896 "description": "Saved replies: up to 12, each a one-line name (at most 40 characters, no two alike) and text (at most 1000). The list replaces the one kept; left out, it stays as it is; [] takes them all away; anything else is refused with 422."
17391897 }
17401898 },
17411899 "required": [
@@ -1747,7 +1905,8 @@
17471905 "email",
17481906 "timeZone",
17491907 "openers",
1750 "cadence"
1908 "cadence",
1909 "replies"
17511910 ]
17521911 }
17531912 }
src/actions.ts +84 −3
@@ -76,6 +76,7 @@ import {
7676 } from "./leads.ts";
7777 import { emit } from "./live.ts";
7878 import { currentAgent, storeAgent } from "./profile.ts";
79 import { append, fill, REPLIES_MAX, REPLY_NAME_MAX, REPLY_TEXT_MAX, SAMPLE_REPLIES, type SavedReply } from "./replies.ts";
7980 import { nextInquiry, seed } from "./sample.ts";
8081 import { goesAt, isZone } from "./quiet.ts";
8182 import { MAX_EMAIL_TEXT, readLeadEmail } from "./intake.ts";
@@ -524,6 +525,41 @@ export type Approved = LeadDetail & {
524525 readonly scheduledFor?: string;
525526 };
526527
528 /**
529 * The draft with a saved reply added at its end: what the edit box would hold
530 * after the tap, nothing sent and nothing kept. `body` is what the box holds
531 * now (the draft when left out); `{first_name}` is the lead's. Counted
532 * against the channel's length like any edit.
533 */
534 export function insertReply(
535 db: Database,
536 who: Who,
537 input: { id: number; reply: unknown; body?: string | undefined },
538 ): Result<{ body: string; channel: Channel }> {
539 const found = leadFor(db, who, "update", input.id, {
540 signIn: "Sign in to edit a draft.",
541 no: "You may not edit this lead's draft.",
542 });
543 if (!found.ok) return found;
544 const ready = readyFor(db, found.value.id);
545 if (ready === null)
546 return fail("invalid", "Nothing is waiting to go to this lead right now.");
547 const saved = (currentAgent(db).replies ?? SAMPLE_REPLIES).find((r) => r.name === input.reply);
548 if (typeof input.reply !== "string" || saved === undefined)
549 return fail("invalid", "Choose one of your saved replies.");
550 const current = lines(input.body ?? ready.body);
551 if (hasControl(current, true))
552 return fail("invalid", "A message is plain text: no control characters.");
553 const body = append(current, fill(saved, found.value.name), ready.channel);
554 const max = MAX_BODY[ready.channel];
555 if (body.length > max)
556 return fail(
557 "invalid",
558 `With "${saved.name}" added this ${ready.channel === "text" ? "text" : "email"} would be ${body.length} characters; the most is ${max}. Shorten the draft or choose a shorter reply.`,
559 );
560 return ok({ body, channel: ready.channel });
561 }
562
527563 /** `sendReply`, and which lead needs the agent after it. */
528564 export const approveReply = (
529565 db: Database,
@@ -1065,6 +1101,8 @@ export type Profile = Agent & {
10651101 readonly openers: Readonly<Record<Source, string>>;
10661102 /** The days after the first reply that each get a follow-up, for leads answered from now on. */
10671103 readonly cadence: readonly number[];
1104 /** Paragraphs saved once to drop into a draft (at most `REPLIES_MAX`). */
1105 readonly replies: readonly SavedReply[];
10681106 };
10691107
10701108 /** Every source's opening words: the agent's own, else the built-in line. */
@@ -1075,7 +1113,7 @@ const wording = (own: Openers | undefined): Record<Source, string> =>
10751113
10761114 const profileOf = (db: Database): Profile => {
10771115 const now = currentAgent(db);
1078 return { id: 1, ...now, openers: wording(now.openers), cadence: now.cadence ?? CADENCE };
1116 return { id: 1, ...now, openers: wording(now.openers), cadence: now.cadence ?? CADENCE, replies: now.replies ?? SAMPLE_REPLIES };
10791117 };
10801118
10811119 export function getProfile(db: Database, who: Who): Result<Profile> {
@@ -1121,6 +1159,42 @@ export function readOpeners(
11211159 return ok(own);
11221160 }
11231161
1162 /**
1163 * The saved replies that arrived, checked: at most 12, each a one-line name
1164 * of 1 to 40 characters (no two alike) and text of 1 to 1,000. Left out, the
1165 * list stays as it was; an empty list takes them all away.
1166 */
1167 export function readReplies(
1168 input: unknown,
1169 kept: readonly SavedReply[],
1170 ): Result<readonly SavedReply[]> {
1171 if (input === undefined) return ok(kept);
1172 if (!Array.isArray(input))
1173 return fail("invalid", "Saved replies are a list of {name, text}.");
1174 if (input.length > REPLIES_MAX)
1175 return fail("invalid", `Keep at most ${REPLIES_MAX} saved replies.`);
1176 const made: SavedReply[] = [];
1177 for (const item of input as unknown[]) {
1178 if (typeof item !== "object" || item === null || Array.isArray(item))
1179 return fail("invalid", "A saved reply is {name, text}.");
1180 const { name: n, text: t } = item as Record<string, unknown>;
1181 if (typeof n !== "string" || typeof t !== "string")
1182 return fail("invalid", "A saved reply has a name and text, both plain text.");
1183 const name = n.trim();
1184 const text = lines(t).trim();
1185 if (hasControl(name, false) || hasControl(text, true))
1186 return fail("invalid", "A saved reply is plain text: no control characters.");
1187 if (name.length === 0 || name.length > REPLY_NAME_MAX)
1188 return fail("invalid", `A saved reply's name is 1 to ${REPLY_NAME_MAX} characters.`);
1189 if (text.length === 0 || text.length > REPLY_TEXT_MAX)
1190 return fail("invalid", `A saved reply's text is 1 to ${REPLY_TEXT_MAX} characters.`);
1191 if (made.some((r) => r.name.toLowerCase() === name.toLowerCase()))
1192 return fail("invalid", `Two saved replies are named ${name.slice(0, REPLY_NAME_MAX)}: give each its own name.`);
1193 made.push({ name, text });
1194 }
1195 return ok(made);
1196 }
1197
11241198 /** The most follow-ups a cadence holds, and the furthest day any may fall on. */
11251199 export const CADENCE_MAX_TOUCHES = 8;
11261200 export const CADENCE_MAX_DAY = 90;
@@ -1204,7 +1278,8 @@ export function saveProfile(
12041278 // One audit row per kind of change, each under its own act.
12051279 const kinds = [
12061280 { act: "cadence" as const, on: (k: string) => k === "follow-up days" },
1207 { act: "openers" as const, on: (k: string) => k !== "follow-up days" },
1281 { act: "replies" as const, on: (k: string) => k === "saved replies" },
1282 { act: "openers" as const, on: (k: string) => k !== "follow-up days" && k !== "saved replies" },
12081283 ].map(({ act, on }) => ({
12091284 act,
12101285 detail: Object.fromEntries(Object.entries(changes).filter(([k]) => on(k))),
@@ -1257,6 +1332,12 @@ function change(
12571332 const days = currentAgent(db).cadence ?? CADENCE;
12581333 if (cadence.value.join(", ") !== days.join(", "))
12591334 changes["follow-up days"] = { from: days.join(", "), to: cadence.value.join(", ") };
1335 const replies = readReplies(input.replies, currentAgent(db).replies ?? SAMPLE_REPLIES);
1336 if (!replies.ok) return replies;
1337 const had = (currentAgent(db).replies ?? SAMPLE_REPLIES).map((r) => r.name).join(", ");
1338 const has = replies.value.map((r) => r.name).join(", ");
1339 const sameText = replies.value.every((r, i) => r.text === (currentAgent(db).replies ?? SAMPLE_REPLIES)[i]?.text);
1340 if (had !== has || !sameText) changes["saved replies"] = { from: had || "none", to: has || "none" };
12601341 const was = wording(before);
12611342 const now = wording(openers.value);
12621343 for (const source of SOURCES)
@@ -1265,7 +1346,7 @@ function change(
12651346 db.transaction(() => {
12661347 storeAgent(
12671348 db,
1268 { ...read.value, openers: openers.value, cadence: cadence.value },
1349 { ...read.value, openers: openers.value, cadence: cadence.value, replies: replies.value },
12691350 who.role === "anon" ? "" : who.name,
12701351 stamp(at),
12711352 );
src/audit.ts +1 −1
@@ -35,7 +35,7 @@ export interface AuditRow {
3535 }
3636
3737 /** 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; `call` is a phone call the agent logged; `showing` books or moves a showing, `showing_off` cancels it; `edited` is a correction of the lead's name, email or phone; `held` is a text approved outside quiet hours, to go at the next 8:00 a.m.; `unhold` takes back a text held for quiet hours; `noted` is a change to the agent's private note on the lead; `merged` is a new arrival who was already a lead (the detail names the arrival's source and the lead): their message joined that lead; `openers` is a change to how first replies open (the profile); `cadence` is a change to the follow-up days (the profile); `skipped` sets one upcoming follow-up aside by hand, `unskipped` brings it back; `put_away` parks a lead until a date (the detail holds `{"on":"YYYY-MM-DD"}`), `brought_back` clears that date. */
38 export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off", "edited", "held", "unhold", "openers", "cadence", "noted", "merged", "skipped", "unskipped", "put_away", "brought_back"] as const;
38 export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off", "edited", "held", "unhold", "openers", "cadence", "replies", "noted", "merged", "skipped", "unskipped", "put_away", "brought_back"] as const;
3939 export type Act = (typeof ACTS)[number];
4040
4141 /** What a `merged` row's detail holds: where the new arrival came from, and the lead they already were. */
src/db.ts +2
@@ -264,6 +264,8 @@ export const migrations: string[] = [
264264 `ALTER TABLE profile ADD COLUMN cadence TEXT`,
265265 // The day (YYYY-MM-DD, the agent's calendar) a lead put away is due back; null when it is not put away.
266266 `ALTER TABLE lead ADD COLUMN back_on TEXT`,
267 // The agent's saved replies as JSON, e.g. [{"name":"Lender intro","text":"…"}]. Null means the sample pair (SAMPLE_REPLIES).
268 `ALTER TABLE profile ADD COLUMN replies TEXT`,
267269 ];
268270
269271 /**
src/env.ts +2 −1
@@ -4,6 +4,7 @@
44 * variable — and running the app by hand needs none of them.
55 */
66
7 import type { SavedReply } from "./replies.ts";
78 import pkg from "../package.json";
89 import { isZone } from "./quiet.ts";
910
@@ -50,4 +51,4 @@ export const agent = {
5051 timeZone: [process.env.AGENT_TIMEZONE, process.env.TZ].find(isZone) ?? "America/New_York",
5152 } as const;
5253 /** The agent as the app uses them: the profile's fields, and the follow-up days they chose (the default when left out). */
53 export type Agent = typeof agent & { readonly cadence?: readonly number[] };
54 export type Agent = typeof agent & { readonly cadence?: readonly number[]; readonly replies?: readonly SavedReply[] };
src/mcp.ts +31
@@ -14,6 +14,7 @@ import {
1414 getLead,
1515 getProfile,
1616 listLeads,
17 insertReply,
1718 saveProfile,
1819 editLead,
1920 setNote,
@@ -311,6 +312,26 @@ export const tools: readonly Tool[] = [
311312 inputSchema: ONE,
312313 run: (db, who, args) => optOutTexts(db, who, { id: Number(args.id) }),
313314 },
315 {
316 name: "insert_saved_reply",
317 description:
318 "Add one of the agent's saved replies (names are in get_profile's replies) to the end of the draft ready for a lead, and get the words back. Nothing is sent or saved: show the person the words, and send them with approve_reply's body only once they approve. {first_name} becomes the lead's first name; too long for a text is refused.",
319 inputSchema: {
320 type: "object",
321 properties: {
322 id: { type: "integer" },
323 reply: { type: "string", description: "The saved reply's name." },
324 body: { type: "string", description: "The words so far; the draft when left out." },
325 },
326 required: ["id", "reply"],
327 },
328 run: (db, who, args) =>
329 insertReply(db, who, {
330 id: Number(args.id),
331 reply: args.reply,
332 body: typeof args.body === "string" ? args.body : undefined,
333 }),
334 },
314335 {
315336 name: "get_profile",
316337 description:
@@ -339,6 +360,16 @@ export const tools: readonly Tool[] = [
339360 ),
340361 },
341362 cadence: { type: "array", items: { type: "integer", minimum: 1, maximum: CADENCE_MAX_DAY }, minItems: 1, maxItems: CADENCE_MAX_TOUCHES, description: `The days after the first reply that each get a follow-up (default 1, 3, 7, 14, 30): 1 to ${CADENCE_MAX_TOUCHES} whole days, each 1 to ${CADENCE_MAX_DAY}, strictly increasing. Leads already in their follow-ups keep the days scheduled. Left out, unchanged.` },
363 replies: {
364 type: "array",
365 maxItems: 12,
366 description: "Saved replies, at most 12: the whole list replaces the one kept (left out, unchanged; [] removes all). Each has a name (1 to 40 characters, no two alike) and text (1 to 1,000). {first_name} is filled with the lead's first name when inserted.",
367 items: {
368 type: "object",
369 properties: { name: { type: "string", maxLength: 40 }, text: { type: "string", maxLength: 1000 } },
370 required: ["name", "text"],
371 },
372 },
342373 timeZone: { type: "string", description: "An IANA name like America/Chicago: texts go out only between 8:00 a.m. and 9:00 p.m. there. Left out, unchanged." },
343374 },
344375 required: ["name", "brokerage", "license", "phone", "email"],
src/pages/layout.ts +1
@@ -61,6 +61,7 @@ export function layout(input: {
6161 <link rel="stylesheet" href="${asset("app.css")}">
6262 <script type="module" src="${asset("live.js")}"></script>
6363 <script type="module" src="${asset("clock.js")}"></script>
64 <script type="module" src="${asset("replies.js")}"></script>
6465 <body>
6566 <div class="page">
6667 <header class="head">
src/pages/lead.ts +25 −3
@@ -6,6 +6,7 @@
66
77 import { callLine, MAX_NOTE, OUTCOME_LABEL, OUTCOMES } from "../calls.ts";
88 import { channelFor, dayLabel, isAnswer, planLabel, MAX_BODY } from "../drafts.ts";
9 import { fill, joiner, SAMPLE_REPLIES } from "../replies.ts";
910 import { escape } from "../http.ts";
1011 import { handoff } from "../handoff.ts";
1112 import { dateName, MAX_AWAY_DAYS, today } from "../putaway.ts";
@@ -43,8 +44,10 @@ export function leadPage(input: {
4344 next: NextLead | null;
4445 now: number;
4546 notice?: string | undefined;
47 /** What the draft box holds when it is not the draft: a reply was added, or an edit was refused. Opens the edit. */
48 editing?: string | undefined;
4649 }): string {
47 const { who, agent, lead, mayUpdate, next, now, notice } = input;
50 const { who, agent, lead, mayUpdate, next, now, notice, editing } = input;
4851 const ready = lead.messages.find(
4952 (m) => m.status === "draft" || m.status === "due",
5053 );
@@ -96,11 +99,12 @@ export function leadPage(input: {
9699 mayUpdate
97100 ? `<div class="actions">
98101 <form method="post" action="${path}/reply"><button class="button">Approve and send</button></form>
99 <details class="edit">
102 <details class="edit"${editing === undefined ? "" : " open"}>
100103 <summary class="button button-quiet">Edit</summary>
101104 <form class="stack" method="post" action="${path}/reply">
102105 <label class="sr" for="body">Your ${titleOf(ready).toLowerCase()}</label>
103 <textarea class="input" id="body" name="body" rows="${ready.channel === "text" ? 4 : 9}" maxlength="${MAX_BODY[ready.channel]}" required>${escape(ready.body)}</textarea>
106 <textarea class="input" id="body" name="body" rows="${ready.channel === "text" ? 4 : 9}" maxlength="${MAX_BODY[ready.channel]}" required>${escape(editing ?? ready.body)}</textarea>
107 ${insertSaved(agent, lead.name, ready.channel, path)}
104108 <p class="sig">${escape(ready.signature)}</p>
105109 <button class="button">Approve and send</button>
106110 </form>
@@ -356,6 +360,24 @@ function noteCard(lead: LeadDetail, path: string, may: boolean, zone: string): s
356360 </section>`;
357361 }
358362
363 /**
364 * "Insert saved reply": a list and a button inside the edit form. The button
365 * posts the form to the insert route, which answers with this page and the
366 * words added, so it works with no script; `static/replies.js` does the same
367 * in place from the data on each option. Nothing here sends.
368 */
369 function insertSaved(agent: Agent, leadName: string, channel: "text" | "email", path: string): string {
370 const replies = agent.replies ?? SAMPLE_REPLIES;
371 if (replies.length === 0) return "";
372 return `<div class="insert row" data-insert data-join="${escape(joiner(channel))}" data-max="${MAX_BODY[channel]}">
373 <label class="sr" for="saved-reply">Saved reply</label>
374 <select class="input" id="saved-reply" name="reply">
375 ${replies.map((r) => `<option value="${escape(r.name)}" data-text="${escape(fill(r, leadName))}">${escape(r.name)}</option>`).join("\n ")}
376 </select>
377 <button class="button button-quiet" formaction="${path}/insert" formnovalidate>Insert saved reply</button>
378 </div>`;
379 }
380
359381 /** "Edit details": the lead's name, email and phone, for whoever may update it. */
360382 function editDetails(lead: LeadDetail, path: string, may: boolean): string {
361383 if (!may) return "";
src/pages/profile.ts +21
@@ -13,6 +13,7 @@ import {
1313 type Source,
1414 } from "../drafts.ts";
1515 import { escape } from "../http.ts";
16 import { REPLIES_MAX, REPLY_NAME_MAX, REPLY_TEXT_MAX, type SavedReply } from "../replies.ts";
1617 import type { Who } from "../who.ts";
1718 import { layout } from "./layout.ts";
1819
@@ -58,6 +59,8 @@ export function profilePage(input: {
5859 preview?: boolean | undefined;
5960 /** What the form fields held when a save was refused, to show again instead of what is saved. */
6061 typed?: Readonly<Record<string, string>> | undefined;
62 /** The saved replies the form held when a save was refused, to show again. */
63 replies?: readonly SavedReply[] | undefined;
6164 }): string {
6265 const { who, profile, mayUpdate, notice } = input;
6366 const typed = input.typed ?? {};
@@ -72,6 +75,21 @@ export function profilePage(input: {
7275 : SOURCES.map(
7376 (s) => `<p><span class="muted">${escape(SOURCE_LABEL[s])}</span><br>${escape(profile.openers[s])}</p>`,
7477 ).join("\n ");
78 const kept = input.replies ?? profile.replies;
79 // The kept replies, then one empty pair to add another (until the limit).
80 const slots = [...kept, ...(kept.length < REPLIES_MAX ? [{ name: "", text: "" }] : [])];
81 const savedReplies = mayUpdate
82 ? `<h2>Saved replies</h2>
83 <p class="muted">Paragraphs you type every day, up to ${REPLIES_MAX}. While you edit a draft, <strong>Insert saved reply</strong> adds one at the end. <code>{first_name}</code> becomes the lead's first name; nothing else is filled in. Empty a reply's name and text to delete it.</p>
84 ${slots
85 .map(
86 (r, i) =>
87 `<div class="stack saved-reply"><label>Name <input class="input" name="reply_name_${i}" type="text" value="${escape(r.name)}" maxlength="${REPLY_NAME_MAX}" autocomplete="off"></label>
88 <label>Text <textarea class="input" name="reply_text_${i}" rows="3" maxlength="${REPLY_TEXT_MAX}">${escape(r.text)}</textarea></label></div>`,
89 )
90 .join("\n ")}`
91 : `<h2>Saved replies</h2>
92 ${kept.length === 0 ? `<p class="muted">None saved.</p>` : kept.map((r) => `<p><span class="muted">${escape(r.name)}</span><br>${escape(r.text)}</p>`).join("\n ")}`;
7593 const shown = mayUpdate && input.preview === true ? fields : profile.openers;
7694 const body = mayUpdate
7795 ? `<form class="card stack" method="post" action="/profile">
@@ -84,6 +102,8 @@ export function profilePage(input: {
84102 <p class="muted">1 to 8 whole days, each 1 to 90, each later than the one before (the default is 1, 3, 7, 14, 30). Leads you answer from now on get their follow-ups on these days; leads already in their follow-ups keep the days already scheduled.</p>
85103 <h2>How your first reply opens</h2>
86104 ${opening}
105 ${savedReplies}
106 <div class="row"><button class="button">Save profile</button></div>
87107 </form>
88108 ${previews(profile, shown)}`
89109 : `<div class="card stack">
@@ -92,6 +112,7 @@ export function profilePage(input: {
92112 <p>${escape(profile.cadence.join(", "))}</p>
93113 <h2>How your first reply opens</h2>
94114 ${opening}
115 ${savedReplies}
95116 <p class="muted">Only an admin can change this.</p>
96117 </div>
97118 ${previews(profile, shown)}`;
src/profile.ts +10 −8
@@ -8,6 +8,7 @@
88 import type { Database } from "bun:sqlite";
99 import { CADENCE, SOURCES, type Openers, type Writer } from "./drafts.ts";
1010 import { agent as fromEnvironment } from "./env.ts";
11 import { readStored, SAMPLE_REPLIES } from "./replies.ts";
1112
1213 /** The openers kept as JSON: only the strings, only for known sources. */
1314 function readOpeners(json: string): Openers {
@@ -39,13 +40,13 @@ function keptCadence(json: string | null): readonly number[] {
3940 /** The saved profile, or the environment's until there is one. */
4041 export function currentAgent(db: Database): Writer {
4142 const saved = db
42 .query<Omit<Writer, "timeZone" | "openers"> & { time_zone: string | null; openers: string; cadence: string | null }, []>(
43 "SELECT name, brokerage, license, phone, email, time_zone, openers, cadence FROM profile WHERE id = 1",
43 .query<Omit<Writer, "timeZone" | "openers"> & { time_zone: string | null; openers: string; cadence: string | null; replies: string | null }, []>(
44 "SELECT name, brokerage, license, phone, email, time_zone, openers, cadence, replies FROM profile WHERE id = 1",
4445 )
4546 .get();
46 if (saved === null) return fromEnvironment;
47 const { time_zone, openers, cadence, ...rest } = saved;
48 return { ...rest, timeZone: time_zone ?? fromEnvironment.timeZone, openers: readOpeners(openers), cadence: keptCadence(cadence) };
47 if (saved === null) return { ...fromEnvironment, replies: SAMPLE_REPLIES };
48 const { time_zone, openers, cadence, replies, ...rest } = saved;
49 return { ...rest, timeZone: time_zone ?? fromEnvironment.timeZone, openers: readOpeners(openers), cadence: keptCadence(cadence), replies: readStored(replies) };
4950 }
5051
5152 /** Save `agent` as the profile, whoever it replaces. */
@@ -56,10 +57,10 @@ export function storeAgent(
5657 at: string,
5758 ): void {
5859 db.query(
59 `INSERT INTO profile (id, name, brokerage, license, phone, email, time_zone, openers, cadence, updated_at, updated_by)
60 VALUES (1, ?1, ?2, ?3, ?4, ?5, ?8, ?9, ?10, ?6, ?7)
60 `INSERT INTO profile (id, name, brokerage, license, phone, email, time_zone, openers, cadence, replies, updated_at, updated_by)
61 VALUES (1, ?1, ?2, ?3, ?4, ?5, ?8, ?9, ?10, ?11, ?6, ?7)
6162 ON CONFLICT (id) DO UPDATE SET name = ?1, brokerage = ?2, license = ?3,
62 phone = ?4, email = ?5, time_zone = ?8, openers = ?9, cadence = ?10, updated_at = ?6, updated_by = ?7`,
63 phone = ?4, email = ?5, time_zone = ?8, openers = ?9, cadence = ?10, replies = ?11, updated_at = ?6, updated_by = ?7`,
6364 ).run(
6465 agent.name,
6566 agent.brokerage,
@@ -71,5 +72,6 @@ export function storeAgent(
7172 agent.timeZone,
7273 JSON.stringify(agent.openers ?? {}),
7374 JSON.stringify(agent.cadence ?? CADENCE),
75 JSON.stringify(agent.replies ?? SAMPLE_REPLIES),
7476 );
7577 }
src/replies.ts added +56
@@ -0,0 +1,56 @@
1 /**
2 * Saved replies: paragraphs the agent types every day (their lender's
3 * contact, this weekend's open house), kept once in the profile and dropped
4 * into a draft with a tap. Pure data and words; whether a person may keep or
5 * use them is `actions.ts`'s question.
6 */
7
8 import type { Channel } from "./drafts.ts";
9 import { firstName } from "./drafts.ts";
10
11 export type SavedReply = { readonly name: string; readonly text: string };
12
13 export const REPLIES_MAX = 12;
14 export const REPLY_NAME_MAX = 40;
15 export const REPLY_TEXT_MAX = 1000;
16
17 /** The two the sample profile ships with, kept until the agent saves a list of their own. */
18 export const SAMPLE_REPLIES: readonly SavedReply[] = [
19 {
20 name: "Lender intro",
21 text: "If you have not talked to a lender yet, I can introduce you to Dana Whitfield at Harbor Credit Union, (555) 214-0199. A pre-approval usually takes a day or two and tells us exactly what to shop for.",
22 },
23 {
24 name: "Open-house invite",
25 text: "{first_name}, I am hosting an open house this Saturday and Sunday from 1 to 4 p.m. at 418 Juniper Ln. Stop by any time; no need to RSVP.",
26 },
27 ];
28
29 /** The saved replies kept as JSON: only well-formed pairs, at most the limit. */
30 export function readStored(json: string | null): readonly SavedReply[] {
31 if (json === null) return SAMPLE_REPLIES;
32 try {
33 const kept: unknown = JSON.parse(json);
34 if (!Array.isArray(kept)) return SAMPLE_REPLIES;
35 return kept
36 .flatMap((r): SavedReply[] =>
37 typeof r === "object" && r !== null && typeof r.name === "string" && typeof r.text === "string"
38 ? [{ name: r.name, text: r.text }]
39 : [],
40 )
41 .slice(0, REPLIES_MAX);
42 } catch {
43 return SAMPLE_REPLIES;
44 }
45 }
46
47 /** A saved reply as it reads to this lead: `{first_name}` filled, nothing else interpolated (one pass, so a name that looks like a placeholder stays a name). */
48 export const fill = (reply: SavedReply, leadName: string): string =>
49 reply.text.replaceAll("{first_name}", firstName(leadName));
50
51 /** What joins a draft and a reply dropped at its end: a space in a text, a blank line in an email. */
52 export const joiner = (channel: Channel): string => (channel === "text" ? " " : "\n\n");
53
54 /** The draft with `added` at its end. An empty draft is just the addition. */
55 export const append = (body: string, added: string, channel: Channel): string =>
56 body.trim() === "" ? added : body.trimEnd() + joiner(channel) + added;
src/routes.ts +121 −21
@@ -32,6 +32,7 @@ import {
3232 saveProfile,
3333 optOutTexts,
3434 approveReply,
35 insertReply,
3536 cancelHeld,
3637 nextLead,
3738 setState,
@@ -49,6 +50,7 @@ import {
4950 CADENCE_MAX_TOUCHES,
5051 } from "./actions.ts";
5152 import { permit } from "./contract.ts";
53 import { REPLIES_MAX, REPLY_NAME_MAX, REPLY_TEXT_MAX } from "./replies.ts";
5254 import { CADENCE, MAX_BODY, OPENER_MAX, SOURCES, type Source } from "./drafts.ts";
5355 import { commit, env, forgeUrl, startedAt, version } from "./env.ts";
5456 import {
@@ -69,7 +71,7 @@ import { MAX_NOTE, OUTCOMES } from "./calls.ts";
6971 import { MAX_ADDRESS, MAX_AHEAD_DAYS } from "./showings.ts";
7072 import { MAX_EMAIL_TEXT } from "./intake.ts";
7173 import { LOST_REASONS, lostSaid } from "./lost.ts";
72 import { MAX_INBOUND, MAX_LEAD_NOTE, MAX_QUERY, Q_HELP, showingsAhead, VIEW_HELP, VIEWS, type NewLead } from "./leads.ts";
74 import { MAX_INBOUND, MAX_LEAD_NOTE, MAX_QUERY, Q_HELP, showingsAhead, VIEW_HELP, VIEWS, type LeadDetail, type NewLead } from "./leads.ts";
7375 import { events } from "./live.ts";
7476 import { rpc } from "./mcp.ts";
7577 import { deskPage } from "./pages/desk.ts";
@@ -411,10 +413,29 @@ const OPENERS: Schema = {
411413 ),
412414 additionalProperties: false,
413415 };
416 const REPLIES_FIELD: Schema = {
417 type: "array",
418 maxItems: REPLIES_MAX,
419 items: {
420 type: "object",
421 properties: {
422 name: { type: "string", minLength: 1, maxLength: REPLY_NAME_MAX },
423 text: {
424 type: "string",
425 minLength: 1,
426 maxLength: REPLY_TEXT_MAX,
427 description: "Plain text. {first_name} is filled with the lead's first name when it is inserted; nothing else is.",
428 },
429 },
430 required: ["name", "text"],
431 additionalProperties: false,
432 },
433 description: `Saved replies: up to ${REPLIES_MAX}, each a one-line name (at most ${REPLY_NAME_MAX} characters, no two alike) and text (at most ${REPLY_TEXT_MAX}). The list replaces the one kept; left out, it stays as it is; [] takes them all away; anything else is refused with 422.`,
434 };
414435 export const PROFILE: Schema = {
415436 type: "object",
416 properties: { id: { const: 1 }, ...PROFILE_FIELDS, openers: OPENERS, cadence: CADENCE_FIELD },
417 required: ["id", ...Object.keys(PROFILE_FIELDS), "openers", "cadence"],
437 properties: { id: { const: 1 }, ...PROFILE_FIELDS, openers: OPENERS, cadence: CADENCE_FIELD, replies: REPLIES_FIELD },
438 required: ["id", ...Object.keys(PROFILE_FIELDS), "openers", "cadence", "replies"],
418439 };
419440 export const ERROR: Schema = {
420441 type: "object",
@@ -492,6 +513,45 @@ const withOpeners = (input: Record<string, unknown>): Record<string, unknown> =>
492513 return Object.keys(own).length === 0 ? input : { ...input, openers: own };
493514 };
494515
516 /**
517 * A form posts a saved reply as a pair of fields (`reply_name_3`, `reply_text_3`);
518 * the action reads a `replies` list, as JSON sends it. A pair left blank is no
519 * reply, which is how the form deletes one. More pairs than the limit are kept
520 * so the action refuses them.
521 */
522 const withReplies = (input: Record<string, unknown>): Record<string, unknown> => {
523 if (input.replies !== undefined) return input;
524 const slots = Object.keys(input)
525 .flatMap((k) => (/^reply_(?:name|text)_(\d{1,3})$/.exec(k)?.[1] ?? []))
526 .map(Number);
527 if (slots.length === 0) return input;
528 const at = (k: string, i: number): string => {
529 const v = input[`reply_${k}_${i}`];
530 return typeof v === "string" ? v : "";
531 };
532 const replies = [...new Set(slots)]
533 .sort((a, b) => a - b)
534 .map((i) => ({ name: at("name", i), text: at("text", i) }))
535 .filter((r) => r.name.trim() !== "" || r.text.trim() !== "");
536 return { ...input, replies };
537 };
538
539 /** The lead's page for this person, with whatever the draft box holds when it is not the draft itself. */
540 const leadView = (
541 c: Context,
542 lead: LeadDetail,
543 extra: { notice?: string | undefined; editing?: string | undefined },
544 ): string =>
545 leadPage({
546 who: c.who,
547 agent: currentAgent(c.db),
548 lead,
549 mayUpdate: permit(c.who, "lead", "update", { ...lead }) === "yes",
550 next: nextLead(c.db, c.who, { except: lead.id }),
551 now: Date.now(),
552 ...extra,
553 });
554
495555 /** The details an edit may carry, and the fields of them that a body names. */
496556 const CONTACT = ["name", "email", "phone"] as const;
497557 const contactOf = (input: Record<string, unknown>): Record<string, unknown> =>
@@ -707,19 +767,7 @@ export const routes: readonly Route[] = [
707767 STATUS[found.error],
708768 );
709769 const { notice, clear } = readNotice(c.request);
710 return html(
711 leadPage({
712 who: c.who,
713 agent: currentAgent(c.db),
714 lead: found.value,
715 mayUpdate: permit(c.who, "lead", "update", { ...found.value }) === "yes",
716 next: nextLead(c.db, c.who, { except: found.value.id }),
717 now: Date.now(),
718 notice,
719 }),
720 200,
721 clear,
722 );
770 return html(leadView(c, found.value, { notice }), 200, clear);
723771 },
724772 api: {
725773 summary:
@@ -802,6 +850,56 @@ export const routes: readonly Route[] = [
802850 answer: APPROVED,
803851 },
804852 },
853 // Insert saved reply: the draft with the reply at its end, unsent. A script
854 // gets the words; a browser gets the lead's page with the edit box open.
855 {
856 method: "POST",
857 path: "/leads/:id/insert",
858 handle: async (c) => {
859 if (scripted(c.request))
860 return posted(
861 c,
862 (input) =>
863 insertReply(c.db, c.who, {
864 id: ID(c),
865 reply: input.reply,
866 body: typeof input.body === "string" ? input.body : undefined,
867 }),
868 () => ({ to: `/leads/${ID(c)}` }),
869 );
870 const input = await readFields(c.request);
871 if (input === undefined) return text("too large", 413);
872 const typed = typeof input.body === "string" ? input.body : undefined;
873 const made = insertReply(c.db, c.who, { id: ID(c), reply: input.reply, body: typed });
874 const found = getLead(c.db, c.who, { id: ID(c) });
875 if (!found.ok) return done(found, "/");
876 if (!made.ok && made.error !== "invalid") return done(made, `/leads/${ID(c)}`);
877 return html(
878 leadView(c, found.value, {
879 editing: made.ok ? made.value.body : typed,
880 ...(made.ok ? { notice: "Reply added below. Nothing is sent until you approve." } : { notice: made.message }),
881 }),
882 made.ok ? 200 : 422,
883 );
884 },
885 api: {
886 summary:
887 "Add one of the agent's saved replies to the end of the draft that is ready for this lead and answer with the words, unsent and unsaved. `{first_name}` becomes the lead's first name. A text or email that would be too long is refused with 422. Send the result with POST /leads/{id}/reply.",
888 body: {
889 type: "object",
890 properties: {
891 reply: { type: "string", minLength: 1, maxLength: REPLY_NAME_MAX, description: "The name of a saved reply, as in GET /profile." },
892 body: { type: "string", maxLength: MAX_BODY.email, description: "The words in the edit box now; the draft when left out." },
893 },
894 required: ["reply"],
895 },
896 answer: {
897 type: "object",
898 properties: { body: { type: "string" }, channel: { enum: ["text", "email"] } },
899 required: ["body", "channel"],
900 },
901 },
902 },
805903 {
806904 method: "POST",
807905 path: "/leads/:id/inbound",
@@ -1138,22 +1236,24 @@ export const routes: readonly Route[] = [
11381236 path: "/profile",
11391237 handle: async (c) => {
11401238 if (scripted(c.request))
1141 return posted(c, (input) => saveProfile(c.db, c.who, withOpeners(input)), () => ({ to: "/profile" }));
1239 return posted(c, (input) => saveProfile(c.db, c.who, withReplies(withOpeners(input))), () => ({ to: "/profile" }));
11421240 const input = await readFields(c.request);
11431241 if (input === undefined) return text("too large", 413);
1144 const saved = saveProfile(c.db, c.who, withOpeners(input));
1242 const saved = saveProfile(c.db, c.who, withReplies(withOpeners(input)));
11451243 if (saved.ok || saved.error !== "invalid")
11461244 return done(saved, "/profile", "Saved. Drafts now carry this profile.");
11471245 // A refused save shows the form again with what was typed and why.
11481246 const profile = getProfile(c.db, c.who);
11491247 if (!profile.ok) return done(saved, "/profile");
1150 const typed = withOpeners(input).openers as Record<string, unknown> | undefined;
1248 const typed = withReplies(withOpeners(input)).openers as Record<string, unknown> | undefined;
1249 const retyped = withReplies(input).replies;
11511250 return html(
11521251 profilePage({
11531252 who: c.who,
11541253 profile: profile.value,
11551254 mayUpdate: true,
11561255 notice: saved.message,
1256 ...(Array.isArray(retyped) ? { replies: retyped as { name: string; text: string }[] } : {}),
11571257 typed: Object.fromEntries(
11581258 Object.entries(input).map(([k, v]) => [k, typeof v === "string" ? v : ""]),
11591259 ),
@@ -1169,7 +1269,7 @@ export const routes: readonly Route[] = [
11691269 "Change the profile (admin only). Drafts not yet sent take it at once; messages already sent keep the signature they went out with. The license may not be blank.",
11701270 body: {
11711271 type: "object",
1172 properties: { ...PROFILE_FIELDS, openers: OPENERS, cadence: CADENCE_FIELD },
1272 properties: { ...PROFILE_FIELDS, openers: OPENERS, cadence: CADENCE_FIELD, replies: REPLIES_FIELD },
11731273 required: Object.keys(PROFILE_FIELDS).filter((f) => f !== "timeZone"),
11741274 },
11751275 answer: PROFILE,
@@ -1203,7 +1303,7 @@ export const routes: readonly Route[] = [
12031303 );
12041304 const input = await readFields(c.request);
12051305 if (input === undefined) return text("too large", 413);
1206 const typed = withOpeners(input).openers;
1306 const typed = withReplies(withOpeners(input)).openers;
12071307 const read = readOpeners(typed, {});
12081308 const given = (typed ?? {}) as Record<string, unknown>;
12091309 const fields = Object.fromEntries(
src/saved-replies.test.ts added +242
@@ -0,0 +1,242 @@
1 /**
2 * Saved replies: kept with the profile, dropped into a draft with a tap,
3 * filled with the lead's first name and nothing else, never sent by the drop.
4 */
5 import { afterAll, expect, test } from "bun:test";
6 import { mkdtempSync } from "node:fs";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { addLead, getLead, getProfile, insertReply, listAudit, saveProfile, type Result } from "./actions.ts";
10 import { openDb } from "./db.ts";
11 import { MAX_BODY } from "./drafts.ts";
12 import { rpc } from "./mcp.ts";
13 import { REPLIES_MAX, REPLY_NAME_MAX, REPLY_TEXT_MAX, SAMPLE_REPLIES } from "./replies.ts";
14 import { serve } from "./server.ts";
15 import { sign } from "./who.ts";
16 import type { Who } from "./who.ts";
17
18 const fresh = () => openDb(mkdtempSync(join(tmpdir(), "app-replies-")));
19 const alice: Who = { role: "user", id: "u1", name: "alice" };
20 const root: Who = { role: "admin", id: "u0", name: "root" };
21 const must = <T>(r: Result<T>): T => {
22 if (!r.ok) throw new Error(`${r.error}: ${r.message}`);
23 return r.value;
24 };
25 const mine = { name: "Sam Realtor", brokerage: "Sam & Co", license: "WA 99887", phone: "(555) 010-0000", email: "[email protected]" };
26 const asker = (consent: boolean, name = "Maria Gonzalez") => ({
27 name,
28 email: "[email protected]",
29 phone: "(206) 555-0101",
30 source: "zillow",
31 message: "Could we see 418 Juniper Ln?",
32 consent,
33 });
34 const withReplies = (replies: unknown) => saveProfile(fresh(), root, { ...mine, replies });
35
36 test("the sample profile ships a lender intro and an open-house invite", () => {
37 const db = fresh();
38 const kept = must(getProfile(db, alice)).replies;
39 expect(kept).toEqual(SAMPLE_REPLIES);
40 expect(kept.map((r) => r.name)).toEqual(["Lender intro", "Open-house invite"]);
41 // Saving the profile without naming replies keeps them.
42 expect(must(saveProfile(db, root, mine)).replies).toEqual(SAMPLE_REPLIES);
43 });
44
45 test("an admin adds, edits and deletes; the list is the whole list", () => {
46 const db = fresh();
47 const one = must(saveProfile(db, root, { ...mine, replies: [{ name: " Lender ", text: " Call Dana.\r\nThanks " }] }));
48 expect(one.replies).toEqual([{ name: "Lender", text: "Call Dana.\nThanks" }]);
49 const edited = must(saveProfile(db, root, { ...mine, replies: [{ name: "Lender", text: "Call Dan." }, { name: "Hours", text: "9 to 5." }] }));
50 expect(edited.replies.map((r) => r.text)).toEqual(["Call Dan.", "9 to 5."]);
51 expect(must(saveProfile(db, root, { ...mine, replies: [] })).replies).toEqual([]);
52 const rows = must(listAudit(db, root)).filter((r) => r.act === "replies");
53 expect(rows).toHaveLength(3);
54 });
55
56 test("a user may not save replies, and nothing changes", () => {
57 const db = fresh();
58 const r = saveProfile(db, alice, { ...mine, replies: [] });
59 expect(r.ok).toBe(false);
60 expect(must(getProfile(db, alice)).replies).toEqual(SAMPLE_REPLIES);
61 });
62
63 test("limits are refused as invalid, and nothing is saved", () => {
64 const ok = { name: "A", text: "B" };
65 const bads: unknown[] = [
66 Array.from({ length: REPLIES_MAX + 1 }, (_, i) => ({ name: `n${i}`, text: "t" })),
67 [{ name: "x".repeat(REPLY_NAME_MAX + 1), text: "t" }],
68 [{ name: "n", text: "x".repeat(REPLY_TEXT_MAX + 1) }],
69 [{ name: "", text: "t" }],
70 [{ name: "n", text: " " }],
71 [{ name: "two\nlines", text: "t" }],
72 [{ name: "n", text: "bell\x07" }],
73 [ok, { name: "a", text: "again" }],
74 [{ name: "n" }],
75 [5],
76 "nope",
77 ];
78 for (const bad of bads) {
79 const db = fresh();
80 const r = saveProfile(db, root, { ...mine, name: "Changed", replies: bad });
81 expect([JSON.stringify(bad).slice(0, 40), r.ok]).toEqual([JSON.stringify(bad).slice(0, 40), false]);
82 if (!r.ok) expect(r.error).toBe("invalid");
83 expect(must(getProfile(db, root)).name).not.toBe("Changed");
84 }
85 const edge = Array.from({ length: REPLIES_MAX }, (_, i) => ({ name: `${i}`.padEnd(REPLY_NAME_MAX, "x"), text: "y".repeat(REPLY_TEXT_MAX) }));
86 expect(must(withReplies(edge)).replies).toHaveLength(REPLIES_MAX);
87 });
88
89 test("inserting adds the reply at the end of the draft, fills {first_name}, and sends nothing", () => {
90 const db = fresh();
91 must(saveProfile(db, root, { ...mine, replies: [{ name: "Open", text: "{first_name}, come Saturday. {last_name} {{first_name}} {first_name}" }] }));
92 const lead = must(addLead(db, alice, asker(false, "Maria Gonzalez")));
93 const ready = lead.messages.find((m) => m.status === "draft")!;
94 const made = must(insertReply(db, alice, { id: lead.id, reply: "Open" }));
95 expect(made.channel).toBe("email");
96 expect(made.body).toBe(`${ready.body}\n\nMaria, come Saturday. {last_name} {Maria} Maria`);
97 // From what the box holds now, not the stored draft.
98 expect(must(insertReply(db, alice, { id: lead.id, reply: "Open", body: "Hi" })).body).toStartWith("Hi\n\nMaria, come");
99 expect(must(insertReply(db, alice, { id: lead.id, reply: "Open", body: "" })).body).toStartWith("Maria, come");
100 // Nothing sent, nothing stored.
101 const after = must(getLead(db, alice, { id: lead.id }));
102 expect(after.messages.find((m) => m.id === ready.id)).toMatchObject({ status: "draft", body: ready.body });
103 expect(after.messages.some((m) => m.status === "sent")).toBe(false);
104 });
105
106 test("a name that looks like the placeholder is not filled twice", () => {
107 const db = fresh();
108 const lead = must(addLead(db, alice, asker(false, "{first_name} Smith")));
109 const r = must(insertReply(db, alice, { id: lead.id, reply: "Open-house invite" }));
110 expect(r.body).toContain("{first_name}, I am hosting");
111 });
112
113 test("a reply that makes a text too long is refused; the same fits an email", () => {
114 const db = fresh();
115 const long = "y".repeat(MAX_BODY.text - 100);
116 must(saveProfile(db, root, { ...mine, replies: [{ name: "Long", text: long }] }));
117 const text = must(addLead(db, alice, asker(true)));
118 expect(text.messages.find((m) => m.status === "draft")!.channel).toBe("text");
119 const r = insertReply(db, alice, { id: text.id, reply: "Long" });
120 expect(r.ok).toBe(false);
121 if (!r.ok) {
122 expect(r.error).toBe("invalid");
123 expect(r.message).toContain(String(MAX_BODY.text));
124 }
125 const email = must(addLead(db, alice, { ...asker(false), email: "[email protected]", phone: "(206) 555-0199" }));
126 expect(insertReply(db, alice, { id: email.id, reply: "Long" }).ok).toBe(true);
127 });
128
129 test("an unknown reply, a closed lead and an anonymous caller are refused", () => {
130 const db = fresh();
131 const lead = must(addLead(db, alice, asker(false)));
132 for (const reply of ["Nope", 3, undefined]) {
133 const r = insertReply(db, alice, { id: lead.id, reply });
134 expect(r.ok).toBe(false);
135 }
136 const anon = insertReply(db, { role: "anon" }, { id: lead.id, reply: "Lender intro" });
137 expect(anon.ok).toBe(false);
138 if (!anon.ok) expect(anon.error).toBe("signin_required");
139 });
140
141 test("the MCP tool inserts, and set_profile saves the list", async () => {
142 const db = fresh();
143 const lead = must(addLead(db, alice, asker(false)));
144 const saved = await rpc(db, root, { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "set_profile", arguments: { ...mine, replies: [{ name: "Hi", text: "Hello {first_name}" }] } } });
145 expect(JSON.stringify(saved)).toContain("Hello {first_name}");
146 const made = await rpc(db, alice, { jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "insert_saved_reply", arguments: { id: lead.id, reply: "Hi", body: "Draft" } } });
147 expect(JSON.stringify(made)).toContain("Draft\\\\n\\\\nHello Maria");
148 });
149
150 // --- the doors ---
151
152 const KEY = "a-key-only-the-forge-holds";
153 const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-")), identityKey: KEY });
154 const base = `http://${server.hostname}:${server.port}`;
155 afterAll(() => server.stop(true));
156 const as = (id: string, name: string, role: "user" | "admin"): Record<string, string> => {
157 const identity = `${id}|${name}|${role}|${Date.now() + 60_000}`;
158 return { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
159 };
160 const admin = as("rep-admin", "rep-root", "admin");
161 const user = as("rep-user", "rep-alice", "user");
162 const form = (fields: Record<string, string>) => {
163 const f = new FormData();
164 for (const [k, v] of Object.entries(fields)) f.set(k, v);
165 return f;
166 };
167 const post = (path: string, who: Record<string, string>, body: FormData | string, extra: Record<string, string> = {}) =>
168 fetch(base + path, { method: "POST", body, headers: { ...who, ...extra }, redirect: "manual" });
169 const json = { "content-type": "application/json", accept: "application/json" };
170 const newLead = async (name: string): Promise<number> => {
171 const made = await fetch(base + "/leads", { method: "POST", headers: { ...user, ...json }, body: JSON.stringify({ ...asker(false, name), email: `${Math.random()}@example.com` }) });
172 return ((await made.json()) as { id: number }).id;
173 };
174
175 test("JSON: GET /profile lists them, a bad list is a 422, a user is a 403", async () => {
176 const seen = (await (await fetch(base + "/profile", { headers: { ...user, ...json } })).json()) as { replies: unknown[] };
177 expect(seen.replies).toEqual(SAMPLE_REPLIES as unknown as unknown[]);
178 const bad = await fetch(base + "/profile", { method: "POST", headers: { ...admin, ...json }, body: JSON.stringify({ ...mine, replies: [{ name: "x".repeat(41), text: "t" }] }) });
179 expect(bad.status).toBe(422);
180 const tooMany = await fetch(base + "/profile", { method: "POST", headers: { ...admin, ...json }, body: JSON.stringify({ ...mine, replies: Array.from({ length: 13 }, (_, i) => ({ name: `n${i}`, text: "t" })) }) });
181 expect(tooMany.status).toBe(422);
182 const long = await fetch(base + "/profile", { method: "POST", headers: { ...admin, ...json }, body: JSON.stringify({ ...mine, replies: [{ name: "n", text: "x".repeat(1001) }] }) });
183 expect(long.status).toBe(422);
184 const forbidden = await fetch(base + "/profile", { method: "POST", headers: { ...user, ...json }, body: JSON.stringify({ ...mine, replies: [] }) });
185 expect(forbidden.status).toBe(403);
186 });
187
188 test("the profile form saves, deletes and escapes a <script> in a saved reply", async () => {
189 const saved = await post(
190 "/profile",
191 admin,
192 form({ ...mine, timeZone: "America/Chicago", reply_name_0: "Evil <b>", reply_text_0: "<script>alert(1)</script> {first_name}", reply_name_1: "", reply_text_1: "" }),
193 );
194 expect(saved.status).toBe(303);
195 const html = await (await fetch(base + "/profile", { headers: admin })).text();
196 expect(html).toContain("&lt;script&gt;alert(1)&lt;/script&gt;");
197 expect(html).not.toContain("<script>alert(1)");
198 expect(html).toContain('name="reply_name_1"');
199 const seen = await (await fetch(base + "/profile", { headers: { ...user, ...json } })).json();
200 expect((seen as { replies: unknown[] }).replies).toHaveLength(1);
201 // A refused form shows what was typed, 422.
202 const refused = await post("/profile", admin, form({ ...mine, reply_name_0: "n".repeat(41), reply_text_0: "kept <i>" }));
203 expect(refused.status).toBe(422);
204 expect(await refused.text()).toContain("kept &lt;i&gt;");
205 // Clearing the pair deletes the reply.
206 await post("/profile", admin, form({ ...mine, reply_name_0: "", reply_text_0: "" }));
207 const gone = await (await fetch(base + "/profile", { headers: { ...user, ...json } })).json();
208 expect((gone as { replies: unknown[] }).replies).toEqual([]);
209 });
210
211 test("the lead page offers the list in the edit box; the form insert returns it filled, escaped and unsent; the API answers the words", async () => {
212 await post("/profile", admin, form({ ...mine, reply_name_0: "Evil", reply_text_0: "<script>alert(1)</script> hi {first_name}" }));
213 const id = await newLead("Maria Gonzalez");
214 const page = await (await fetch(`${base}/leads/${id}`, { headers: user })).text();
215 expect(page).toContain("Insert saved reply");
216 expect(page).toContain('data-text="&lt;script&gt;alert(1)&lt;/script&gt; hi Maria"');
217 expect(page).not.toContain("<script>alert(1)");
218 const inserted = await post(`/leads/${id}/insert`, user, form({ body: "Hello there", reply: "Evil" }));
219 expect(inserted.status).toBe(200);
220 const html = await inserted.text();
221 expect(html).toContain("Hello there &lt;script&gt;alert(1)&lt;/script&gt; hi Maria</textarea>");
222 expect(html).toContain("<details class=\"edit\" open>");
223 expect(html).not.toContain("<script>alert(1)");
224 // Unsent: still a draft.
225 const after = (await (await fetch(`${base}/leads/${id}`, { headers: { ...user, ...json } })).json()) as { messages: { status: string }[] };
226 expect(after.messages.some((m) => m.status === "sent")).toBe(false);
227 const api = await post(`/leads/${id}/insert`, user, JSON.stringify({ reply: "Evil", body: "Hi" }), json);
228 expect(await api.json()).toEqual({ body: "Hi <script>alert(1)</script> hi Maria", channel: "text" });
229 const missing = await post(`/leads/${id}/insert`, user, JSON.stringify({ reply: "Nope" }), json);
230 expect(missing.status).toBe(422);
231 const refused = await post(`/leads/${id}/insert`, user, form({ body: "kept <b>", reply: "Nope" }));
232 expect(refused.status).toBe(422);
233 expect(await refused.text()).toContain("kept &lt;b&gt;");
234 const cross = await post(`/leads/${id}/insert`, user, form({ reply: "Evil" }), { origin: "https://evil.example" });
235 expect(cross.status).toBe(403);
236 });
237
238 test("the OpenAPI document describes the list and the insert", async () => {
239 const spec = JSON.stringify(await (await fetch(base + "/openapi.json", { headers: admin })).json());
240 expect(spec).toContain("/leads/{id}/insert");
241 expect(spec).toContain("Saved replies");
242 });
src/sentences.ts +5
@@ -53,6 +53,11 @@ export function deed(
5353 done: `changed the follow-up days${changeWords(row.detail, esc)}`,
5454 tried: "change the follow-up days",
5555 };
56 if (row.resource === "profile" && row.act === "replies")
57 return {
58 done: `changed the saved replies${changeWords(row.detail, esc)}`,
59 tried: "change the saved replies",
60 };
5661 if (row.resource === "profile" && row.act === "openers")
5762 return {
5863 done: `changed how first replies open${changeWords(row.detail, esc)}`,
src/server.test.ts +2 −1
@@ -334,6 +334,7 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
334334 "restore_follow_up",
335335 "set_note",
336336 "opt_out_texts",
337 "insert_saved_reply",
337338 "get_profile",
338339 "set_profile",
339340 ]);
@@ -568,7 +569,7 @@ test("what the web expects: robots.txt, and security.txt from the forge that run
568569
569570 test("the profile is a page and a JSON twin: everyone in reads, only an admin saves", async () => {
570571 const seen = await (await api("/profile", { headers: asJson }, alice)).json();
571 expect(Object.keys(seen as object).sort()).toEqual(["brokerage", "cadence", "email", "id", "license", "name", "openers", "phone", "timeZone"]);
572 expect(Object.keys(seen as object).sort()).toEqual(["brokerage", "cadence", "email", "id", "license", "name", "openers", "phone", "replies", "timeZone"]);
572573 const page = await (await api("/profile", {}, alice)).text();
573574 expect(page).toContain("Your profile");
574575 expect(page).not.toContain('action="/profile"');
static/replies.js added +20
@@ -0,0 +1,20 @@
1 // "Insert saved reply" in place: add the chosen reply to the end of the draft
2 // box without leaving the page. The same words and the same joiner the server
3 // uses; when the result would be too long it lets the form post, and the
4 // server says why. Nothing is sent from here.
5
6 document.addEventListener("click", (event) => {
7 const button = event.target instanceof Element ? event.target.closest("[data-insert] button") : null;
8 if (button === null) return;
9 const box = button.closest("[data-insert]");
10 const form = button.closest("form");
11 const area = form?.querySelector("textarea[name=body]");
12 const option = box?.querySelector("select")?.selectedOptions[0];
13 if (!area || !option) return;
14 const body = area.value.trim() === "" ? option.dataset.text : area.value.trimEnd() + box.dataset.join + option.dataset.text;
15 if (body.length > Number(box.dataset.max)) return;
16 event.preventDefault();
17 area.value = body;
18 area.focus();
19 area.setSelectionRange(body.length, body.length);
20 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs