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

The agent rewrites how their first reply opens for each lead source, and sees a new draft in their words before saving #45

Merged opened this

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

Merged

mason/speed-to-lead:mason/43-the-agent-rewrites-how-their-first-reply → main 4 commits fork

  • Merged. mason/43-the-agent-rewrites-how-their-first-reply was merged into main as 82f6c8b.

Review

Sign in to review this change.
19 files changed +672 −61
AGENTS.md +2 −1
@@ -126,7 +126,8 @@ Speed to Lead is one realtor's desk. The concepts, one module each:
126126 answer, not a second mechanism.
127127 - `src/drafts.ts` — the words: templates filled from the inquiry and the
128128 agent's profile (`src/profile.ts`: the saved one, else the `AGENT_*`
129 defaults of `agent` in `src/env.ts`), the signature every message
129 defaults of `agent` in `src/env.ts`; its `openers` are the agent's own
130 first-reply opening per source, else `BUILT_IN_OPENER`), the signature every message
130131 carries, and the consent rule (`channelFor`: text only with written
131132 consent and a phone number). A trigger in `src/db.ts` holds that rule
132133 in the file as well.
README.md +9 −2
@@ -285,6 +285,8 @@ signed in can read it. The license number is required, because every
285285 message shows it. Drafts you have not sent take the new profile at once;
286286 messages already sent keep the signature they went out with.
287287
288 Under **How your first reply opens**, an admin can write the opening line for each source (Zillow, website, open house, referral), up to 160 characters on one line; leave one empty to keep the built-in wording. **Preview** shows the first reply to a sample lead in your words without saving; new first replies use them, drafts already on the desk keep theirs, and an opener too long to leave a text under its limit falls back to the built-in line for that text.
289
288290 Until you save one, the app uses these environment variables (forge
289291 Settings → App → Environment) or, failing those, a sample agent, Jordan
290292 Avery of Harbor & Pine Realty. Once a profile is saved it wins.
@@ -298,8 +300,13 @@ Avery of Harbor & Pine Realty. Once a profile is saved it wins.
298300 | `AGENT_EMAIL` | the email address in your emails |
299301 | `AGENT_TIMEZONE` | your time zone, for quiet hours (falls back to `TZ`) |
300302
301 In the terminal, press `p` on the desk to read it; an admin presses `e`
302 and types each field in turn (enter moves on, the last one saves).
303 In the terminal, press `p` on the desk to read it, openers included; an admin
304 presses `e` and types each field in turn, the five above and then one opening
305 line per source (enter moves on, empty means the built-in wording, the last
306 one saves). A save from the terminal reaches web viewers live.
307
308 A browser form that posts openers as a non-admin gets a redirect (303) with a
309 notice on the page, where JSON and MCP get a 403; either way nothing is saved.
303310
304311 A script reads it with `GET /profile` and an admin changes it with
305312 `POST /profile` (JSON, the five fields and optionally `timeZone`); MCP has `get_profile` and
contract/openapi.json +73 −2
@@ -1267,6 +1267,29 @@
12671267 "type": "string",
12681268 "maxLength": 60,
12691269 "description": "An IANA time zone name, e.g. America/Chicago. Texts go out only between 8:00 a.m. and 9:00 p.m. there. Left out, it stays as it is."
1270 },
1271 "openers": {
1272 "type": "object",
1273 "description": "How a first reply opens, by source. A source left out keeps its wording; an empty one goes back to the built-in line. Drafts already on the desk are not rewritten.",
1274 "properties": {
1275 "zillow": {
1276 "type": "string",
1277 "maxLength": 160
1278 },
1279 "website": {
1280 "type": "string",
1281 "maxLength": 160
1282 },
1283 "open_house": {
1284 "type": "string",
1285 "maxLength": 160
1286 },
1287 "referral": {
1288 "type": "string",
1289 "maxLength": 160
1290 }
1291 },
1292 "additionalProperties": false
12701293 }
12711294 },
12721295 "required": [
@@ -1276,7 +1299,8 @@
12761299 "license",
12771300 "phone",
12781301 "email",
1279 "timeZone"
1302 "timeZone",
1303 "openers"
12801304 ]
12811305 }
12821306 }
@@ -1332,6 +1356,29 @@
13321356 "type": "string",
13331357 "maxLength": 60,
13341358 "description": "An IANA time zone name, e.g. America/Chicago. Texts go out only between 8:00 a.m. and 9:00 p.m. there. Left out, it stays as it is."
1359 },
1360 "openers": {
1361 "type": "object",
1362 "description": "How a first reply opens, by source. A source left out keeps its wording; an empty one goes back to the built-in line. Drafts already on the desk are not rewritten.",
1363 "properties": {
1364 "zillow": {
1365 "type": "string",
1366 "maxLength": 160
1367 },
1368 "website": {
1369 "type": "string",
1370 "maxLength": 160
1371 },
1372 "open_house": {
1373 "type": "string",
1374 "maxLength": 160
1375 },
1376 "referral": {
1377 "type": "string",
1378 "maxLength": 160
1379 }
1380 },
1381 "additionalProperties": false
13351382 }
13361383 },
13371384 "required": [
@@ -1384,6 +1431,29 @@
13841431 "type": "string",
13851432 "maxLength": 60,
13861433 "description": "An IANA time zone name, e.g. America/Chicago. Texts go out only between 8:00 a.m. and 9:00 p.m. there. Left out, it stays as it is."
1434 },
1435 "openers": {
1436 "type": "object",
1437 "description": "How a first reply opens, by source. A source left out keeps its wording; an empty one goes back to the built-in line. Drafts already on the desk are not rewritten.",
1438 "properties": {
1439 "zillow": {
1440 "type": "string",
1441 "maxLength": 160
1442 },
1443 "website": {
1444 "type": "string",
1445 "maxLength": 160
1446 },
1447 "open_house": {
1448 "type": "string",
1449 "maxLength": 160
1450 },
1451 "referral": {
1452 "type": "string",
1453 "maxLength": 160
1454 }
1455 },
1456 "additionalProperties": false
13871457 }
13881458 },
13891459 "required": [
@@ -1393,7 +1463,8 @@
13931463 "license",
13941464 "phone",
13951465 "email",
1396 "timeZone"
1466 "timeZone",
1467 "openers"
13971468 ]
13981469 }
13991470 }
src/actions.ts +98 −10
@@ -11,7 +11,16 @@ import { csvName, leadsCsv } from "./export.ts";
1111 import { record, type Act, type AuditRow } from "./audit.ts";
1212 import { MAX_NOTE, outcomeOf } from "./calls.ts";
1313 import { permit } from "./contract.ts";
14 import { channelFor, MAX_BODY, SOURCES, type Channel, type Source } from "./drafts.ts";
14 import {
15 BUILT_IN_OPENER,
16 channelFor,
17 MAX_BODY,
18 OPENER_MAX,
19 SOURCES,
20 type Channel,
21 type Openers,
22 type Source,
23 } from "./drafts.ts";
1524 import type { Agent } from "./env.ts";
1625 import {
1726 advance,
@@ -841,8 +850,26 @@ export function resetSample(
841850 return result;
842851 }
843852
844 /** The agent whose desk this is, as a row of one: what every message is signed with. */
845 export type Profile = Agent & { readonly id: 1 };
853 /**
854 * The agent whose desk this is, as a row of one: what every message is signed
855 * with, and the words each source's first reply opens with (the built-in line
856 * where they have not written their own).
857 */
858 export type Profile = Agent & {
859 readonly id: 1;
860 readonly openers: Readonly<Record<Source, string>>;
861 };
862
863 /** Every source's opening words: the agent's own, else the built-in line. */
864 const wording = (own: Openers | undefined): Record<Source, string> =>
865 Object.fromEntries(
866 SOURCES.map((s) => [s, own?.[s] || BUILT_IN_OPENER[s]]),
867 ) as Record<Source, string>;
868
869 const profileOf = (db: Database): Profile => {
870 const now = currentAgent(db);
871 return { id: 1, ...now, openers: wording(now.openers) };
872 };
846873
847874 export function getProfile(db: Database, who: Who): Result<Profile> {
848875 if (permit(who, "profile", "read", { id: 1 }) !== "yes")
@@ -851,7 +878,40 @@ export function getProfile(db: Database, who: Who): Result<Profile> {
851878 "Sign in to read the profile.",
852879 "You may not read the profile.",
853880 );
854 return ok({ id: 1, ...currentAgent(db) });
881 return ok(profileOf(db));
882 }
883
884 /**
885 * The openers that arrived, checked: the agent's own words to keep. A source
886 * left out keeps what it had; an empty one, or the built-in line itself,
887 * goes back to the built-in wording.
888 */
889 export function readOpeners(
890 input: unknown,
891 kept: Openers,
892 ): Result<Openers> {
893 if (input === undefined) return ok(kept);
894 if (typeof input !== "object" || input === null || Array.isArray(input))
895 return fail("invalid", "Openers are an object keyed by source.");
896 const given = input as Record<string, unknown>;
897 const stray = Object.keys(given).find((k) => !(SOURCES as readonly string[]).includes(k));
898 if (stray !== undefined)
899 return fail("invalid", `Not a source: ${stray.slice(0, 40)}.`);
900 const own: Record<string, string> = { ...kept };
901 for (const source of SOURCES) {
902 const v = given[source];
903 if (v === undefined) continue;
904 if (typeof v !== "string")
905 return fail("invalid", `The opening for ${source} is text.`);
906 const words = v.trim();
907 if (hasControl(words, false))
908 return fail("invalid", "An opening is one line of plain text: no line breaks.");
909 if (words.length > OPENER_MAX)
910 return fail("invalid", `An opening is at most ${OPENER_MAX} characters.`);
911 if (words === "" || words === BUILT_IN_OPENER[source]) delete own[source];
912 else own[source] = words;
913 }
914 return ok(own);
855915 }
856916
857917 /** What arrived for the profile, checked field by field: the agent to keep, or what is wrong. */
@@ -889,18 +949,32 @@ export function readAgent(
889949 return ok({ name, brokerage, license, phone, email, timeZone });
890950 }
891951
892 export const saveProfile = (
952 export function saveProfile(
893953 db: Database,
894954 who: Who,
895955 input: Record<string, unknown>,
896956 at?: Date,
897 ): Result<Profile> =>
898 audited(db, who, "profile", "update", 1, change(db, who, input, at));
957 ): Result<Profile> {
958 const changes: Record<string, { from: string; to: string }> = {};
959 const result = change(db, who, input, changes, at);
960 const changed = result.ok && Object.keys(changes).length > 0;
961 return audited(
962 db,
963 who,
964 "profile",
965 "update",
966 1,
967 result,
968 changed ? "openers" : undefined,
969 changed ? JSON.stringify(changes) : undefined,
970 );
971 }
899972
900973 function change(
901974 db: Database,
902975 who: Who,
903976 input: Record<string, unknown>,
977 changes: Record<string, { from: string; to: string }>,
904978 at?: Date,
905979 ): Result<Profile> {
906980 if (permit(who, "profile", "update", { id: 1 }) !== "yes")
@@ -911,12 +985,26 @@ function change(
911985 );
912986 const read = readAgent(input, currentAgent(db).timeZone);
913987 if (!read.ok) return read;
988 const before = currentAgent(db).openers ?? {};
989 const openers = readOpeners(input.openers, before);
990 if (!openers.ok) return openers;
991 const was = wording(before);
992 const now = wording(openers.value);
993 for (const source of SOURCES)
994 if (was[source] !== now[source])
995 changes[`${source} opening`] = { from: was[source], to: now[source] };
914996 db.transaction(() => {
915 storeAgent(db, read.value, who.role === "anon" ? "" : who.name, stamp(at));
916 redraftUnsent(db, read.value);
997 storeAgent(
998 db,
999 { ...read.value, openers: openers.value },
1000 who.role === "anon" ? "" : who.name,
1001 stamp(at),
1002 );
1003 // Drafts on the desk keep the opening they were written with.
1004 redraftUnsent(db, { ...read.value, openers: before });
9171005 })();
9181006 emit("lead.changed", {});
919 return ok({ id: 1, ...read.value });
1007 return ok(profileOf(db));
9201008 }
9211009
9221010 /**
src/audit.ts +2 −2
@@ -34,8 +34,8 @@ export interface AuditRow {
3434 readonly detail: string | null;
3535 }
3636
37 /** 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. */
38 export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off", "edited", "held", "unhold"] as const;
37 /** 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; `openers` is a change to how first replies open (the profile). */
38 export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off", "edited", "held", "unhold", "openers"] as const;
3939 export type Act = (typeof ACTS)[number];
4040
4141 export interface Attempt {
src/db.test.ts +2 −1
@@ -26,6 +26,7 @@ test("the inbound migrations tolerate a file that already has them (a preview th
2626 const db = openDb(mkdtempSync(join(tmpdir(), "app-db-")));
2727 const at = migrations.findIndex((m) => m.includes("TABLE IF NOT EXISTS inbound"));
2828 db.exec("DELETE FROM schema_version WHERE version > " + at);
29 db.exec("ALTER TABLE audit DROP COLUMN detail"); // the one migration after them that is not safe to run twice
29 db.exec("ALTER TABLE audit DROP COLUMN detail"); // migrations after them that are not safe to run twice
30 db.exec("ALTER TABLE profile DROP COLUMN openers");
3031 expect(() => migrate(db)).not.toThrow();
3132 });
src/db.ts +3
@@ -214,6 +214,9 @@ export const migrations: string[] = [
214214 `CREATE TRIGGER IF NOT EXISTS message_text_needs_consent_update BEFORE UPDATE OF channel ON message
215215 WHEN NEW.channel = 'text' AND (SELECT consent FROM lead WHERE id = NEW.lead_id) = 0
216216 BEGIN SELECT RAISE(ABORT, 'no consent to text'); END`,
217 // The agent's own opening words for a first reply, by source, as JSON.
218 // `{}` means every source opens with the built-in line.
219 `ALTER TABLE profile ADD COLUMN openers TEXT NOT NULL DEFAULT '{}'`,
217220 ];
218221
219222 export function openDb(dir = dataDir): Database {
src/details.test.ts +1
@@ -139,6 +139,7 @@ test("the lead table rebuild keeps every message, inbound reply and call", () =>
139139 const id = arrive(before);
140140 const edit = migrations.findIndex((m) => m.includes("DROP TABLE IF EXISTS lead_new"));
141141 before.exec(`DELETE FROM schema_version WHERE version > ${edit}`);
142 before.exec("ALTER TABLE profile DROP COLUMN openers"); // a later migration, not safe to run twice
142143 before.close();
143144 const after = openDb(dir);
144145 expect(after.query("SELECT count(*) AS n FROM message WHERE lead_id = ?1").get(id)).toEqual({ n: 1 });
src/drafts.ts +26 −5
@@ -89,13 +89,26 @@ export const addressIn = (message: string): string | undefined =>
8989 export const firstName = (name: string): string =>
9090 name.trim().split(/\s+/)[0] ?? name;
9191
92 const OPENER: Readonly<Record<Source, string>> = {
92 /** The opening line of a first reply for each source, until the agent words it themselves. */
93 export const BUILT_IN_OPENER: Readonly<Record<Source, string>> = {
9394 zillow: "Thanks for reaching out on Zillow",
9495 website: "Thanks for your note through my website",
9596 open_house: "It was great to have you at the open house",
9697 referral: "Thank you for reaching out — referrals mean the world to me",
9798 };
9899
100 /** The longest opening the agent may write for a source. */
101 export const OPENER_MAX = 160;
102
103 /** The agent's own opening words, by source; a source left out opens with the built-in line. */
104 export type Openers = Partial<Record<Source, string>>;
105
106 /** Who a message is from: the agent, and the opening words they chose. */
107 export type Writer = Agent & { readonly openers?: Openers };
108
109 /** Closing punctuation is added by the template, so the agent's own is dropped. */
110 const bare = (opener: string): string => opener.replace(/[.!?…\s]+$/, "");
111
99112 function ask(topic: Topic, address: string | undefined, short: boolean): string {
100113 switch (topic) {
101114 case "showing":
@@ -226,15 +239,23 @@ const TOUCH: Readonly<Record<number, Readonly<Record<Topic, Touch>>>> = {
226239 * day a touch of the cadence. The signature is not in here; it is added,
227240 * unchangeable, when the message goes out.
228241 */
229 export function draft(lead: Asker, day: number, agent: Agent): string {
242 export function draft(lead: Asker, day: number, agent: Writer): string {
230243 const channel = channelFor(lead);
231244 const first = firstName(lead.name);
232245 const topic = topicOf(lead.message);
233246 if (day === 0) {
234247 const address = addressIn(lead.message);
235 if (channel === "text")
236 return `Hi ${first}, it's ${firstName(agent.name)} with ${agent.brokerage}. ${OPENER[lead.source]}! ${ask(topic, address, true)}`;
237 return `Hi ${first},\n\n${OPENER[lead.source]}. ${ask(topic, address, false)}\n\nTalk soon,`;
248 const own = bare(agent.openers?.[lead.source] ?? "");
249 if (channel === "text") {
250 const text = (opener: string): string =>
251 `Hi ${first}, it's ${firstName(agent.name)} with ${agent.brokerage}. ${opener}! ${ask(topic, address, true)}`;
252 // A long opener must still leave a text that can be sent.
253 const chosen = own === "" ? "" : text(own);
254 return chosen !== "" && chosen.length <= MAX_BODY.text
255 ? chosen
256 : text(BUILT_IN_OPENER[lead.source]);
257 }
258 return `Hi ${first},\n\n${own === "" ? BUILT_IN_OPENER[lead.source] : own}. ${ask(topic, address, false)}\n\nTalk soon,`;
238259 }
239260 const words = TOUCH[day] ?? TOUCH[30]!;
240261 const touch = words[topic](first, addressIn(lead.message));
src/mcp.ts +10 −2
@@ -30,7 +30,7 @@ import {
3030 import { MAX_NOTE, OUTCOMES } from "./calls.ts";
3131 import { MAX_EMAIL_TEXT } from "./intake.ts";
3232 import { MAX_ADDRESS } from "./showings.ts";
33 import { SOURCES } from "./drafts.ts";
33 import { OPENER_MAX, SOURCES } from "./drafts.ts";
3434 import { title } from "./env.ts";
3535 import { MAX_INBOUND, Q_HELP, VIEW_HELP, VIEWS } from "./leads.ts";
3636 import { fields } from "./http.ts";
@@ -260,7 +260,7 @@ export const tools: readonly Tool[] = [
260260 {
261261 name: "set_profile",
262262 description:
263 "Change the agent's name, brokerage, license, phone, email and time zone (admin only). Unsent drafts take it at once; sent messages keep theirs.",
263 "Change the agent's name, brokerage, license, phone, email and time zone, and optionally how first replies open (admin only). Unsent drafts take it at once; sent messages keep theirs.",
264264 inputSchema: {
265265 type: "object",
266266 properties: {
@@ -269,6 +269,14 @@ export const tools: readonly Tool[] = [
269269 license: { type: "string" },
270270 phone: { type: "string" },
271271 email: { type: "string" },
272 openers: {
273 type: "object",
274 description:
275 "How a first reply opens, by source (zillow, website, open_house, referral): one line of at most 160 characters. A source left out keeps its wording; an empty one goes back to the built-in line. Drafts already on the desk are not rewritten.",
276 properties: Object.fromEntries(
277 SOURCES.map((s) => [s, { type: "string", maxLength: OPENER_MAX }]),
278 ),
279 },
272280 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." },
273281 },
274282 required: ["name", "brokerage", "license", "phone", "email"],
src/openers.test.ts added +214
@@ -0,0 +1,214 @@
1 /**
2 * How the first reply opens, for each source: the agent's own words, kept
3 * with the profile, used by the next first reply and no draft already written.
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 {
10 addLead,
11 getLead,
12 getProfile,
13 listAudit,
14 saveProfile,
15 type Result,
16 } from "./actions.ts";
17 import { openDb } from "./db.ts";
18 import { BUILT_IN_OPENER, draft, MAX_BODY, OPENER_MAX, SOURCES } from "./drafts.ts";
19 import { agent } from "./env.ts";
20 import { rpc } from "./mcp.ts";
21 import { serve } from "./server.ts";
22 import { sign } from "./who.ts";
23 import type { Who } from "./who.ts";
24
25 const fresh = () => openDb(mkdtempSync(join(tmpdir(), "app-openers-")));
26 const alice: Who = { role: "user", id: "u1", name: "alice" };
27 const root: Who = { role: "admin", id: "u0", name: "root" };
28 const must = <T>(r: Result<T>): T => {
29 if (!r.ok) throw new Error(`${r.error}: ${r.message}`);
30 return r.value;
31 };
32 const lead = (source: string, n = 1) => ({
33 name: "Maria Gonzalez",
34 email: `maria${n}@example.com`,
35 phone: "(206) 555-0101",
36 source,
37 message: "Could we see 418 Juniper Ln?",
38 consent: false,
39 });
40 const mine = { name: "Sam Realtor", brokerage: "Sam & Co", license: "WA 99887", phone: "(555) 010-0000", email: "[email protected]" };
41 const firstBody = (db: ReturnType<typeof fresh>, source: string, n = 1) =>
42 must(addLead(db, alice, lead(source, n))).messages[0]!.body;
43
44 test("a saved opener opens the next first reply for that source and no other", () => {
45 const db = fresh();
46 must(saveProfile(db, root, { ...mine, openers: { zillow: "Glad you found me on Zillow." } }));
47 expect(firstBody(db, "zillow")).toContain("Glad you found me on Zillow. ");
48 expect(firstBody(db, "zillow", 2)).not.toContain("Zillow.. ");
49 expect(firstBody(db, "website", 3)).toContain(BUILT_IN_OPENER.website);
50 expect(firstBody(db, "referral", 4)).toContain(BUILT_IN_OPENER.referral);
51 });
52
53 test("an empty field, or the built-in line itself, is the built-in wording", () => {
54 const db = fresh();
55 must(saveProfile(db, root, { ...mine, openers: { zillow: "Custom hello" } }));
56 const saved = must(saveProfile(db, root, { ...mine, openers: { zillow: " " } }));
57 expect(saved.openers).toEqual(BUILT_IN_OPENER);
58 expect(firstBody(db, "zillow")).toContain(BUILT_IN_OPENER.zillow);
59 // A save that names no openers leaves them alone.
60 must(saveProfile(db, root, { ...mine, openers: { website: "Hello from my site" } }));
61 const again = must(saveProfile(db, root, { ...mine, name: "Sam R." }));
62 expect(again.openers.website).toBe("Hello from my site");
63 });
64
65 test("161 characters or a line break is refused and saves nothing", () => {
66 const db = fresh();
67 for (const bad of ["x".repeat(OPENER_MAX + 1), "two\nlines", 5, "bell\x07"]) {
68 const r = saveProfile(db, root, { ...mine, name: "Changed", openers: { zillow: bad } });
69 expect(r.ok).toBe(false);
70 if (!r.ok) expect(r.error).toBe("invalid");
71 }
72 expect(saveProfile(db, root, { ...mine, openers: { nowhere: "x" } }).ok).toBe(false);
73 expect(must(getProfile(db, root)).name).toBe(agent.name);
74 expect(must(saveProfile(db, root, { ...mine, openers: { zillow: "x".repeat(OPENER_MAX) } })).openers.zillow).toHaveLength(OPENER_MAX);
75 });
76
77 test("a user may not save openers", () => {
78 const db = fresh();
79 const r = saveProfile(db, alice, { ...mine, openers: { zillow: "Mine" } });
80 expect(r.ok).toBe(false);
81 if (!r.ok) expect(r.error).toBe("forbidden");
82 expect(must(getProfile(db, alice)).openers.zillow).toBe(BUILT_IN_OPENER.zillow);
83 });
84
85 test("drafts already on the desk are not rewritten by a new opener", () => {
86 const db = fresh();
87 const id = must(addLead(db, alice, lead("zillow"))).id;
88 const before = must(getLead(db, alice, { id })).messages.map((m) => m.body);
89 must(saveProfile(db, root, { ...mine, openers: { zillow: "A brand new opening" } }));
90 expect(must(getLead(db, alice, { id })).messages.map((m) => m.body)).toEqual(before);
91 });
92
93 test("the longest opener with the longest text still leaves a draft that can be sent", () => {
94 const long = "w".repeat(OPENER_MAX);
95 const big = { ...agent, name: `${"A".repeat(30)} ${"B".repeat(80)}`, brokerage: "R".repeat(120) };
96 const asker = { name: "N".repeat(120), phone: "(206) 555-0101", source: "zillow" as const, message: "Could we see 418 Juniper Ln?", consent: true };
97 const text = draft(asker, 0, { ...big, openers: { zillow: long } });
98 expect(text.length).toBeLessThanOrEqual(MAX_BODY.text);
99 // A modest sender keeps the long opener in a text.
100 const ok = draft({ ...asker, name: "Maria" }, 0, { ...agent, openers: { zillow: long } });
101 expect(ok).toContain(long);
102 expect(ok.length).toBeLessThanOrEqual(MAX_BODY.text);
103 expect(draft({ ...asker, consent: false }, 0, { ...agent, openers: { zillow: long } })).toContain(long);
104 });
105
106 test("the save writes one audit row with the old and new wording", () => {
107 const db = fresh();
108 must(saveProfile(db, root, { ...mine, openers: { zillow: "Hi from Zillow" } }));
109 const rows = must(listAudit(db, root)).filter((r) => r.resource === "profile");
110 expect(rows).toHaveLength(1);
111 expect(JSON.parse(rows[0]!.detail!)).toEqual({
112 "zillow opening": { from: BUILT_IN_OPENER.zillow, to: "Hi from Zillow" },
113 });
114 // A save that changes no opening adds a row with no opener detail.
115 must(saveProfile(db, root, { ...mine, openers: { zillow: "Hi from Zillow" } }));
116 expect(must(listAudit(db, root)).filter((r) => r.act === "openers")).toHaveLength(1);
117 });
118
119 test("the MCP tool saves openers, and a user is refused", async () => {
120 const db = fresh();
121 const call = (who: Who, args: object) =>
122 rpc(db, who, { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "set_profile", arguments: args } });
123 const done = await call(root, { ...mine, openers: { open_house: "Lovely to meet you" } });
124 expect(JSON.stringify(done)).toContain("Lovely to meet you");
125 expect(firstBody(db, "open_house")).toContain("Lovely to meet you");
126 expect(JSON.stringify(await call(alice, { ...mine, openers: { open_house: "No" } }))).toContain("forbidden");
127 });
128
129 // --- the doors ---
130
131 const KEY = "a-key-only-the-forge-holds";
132 const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-")), identityKey: KEY });
133 const base = `http://${server.hostname}:${server.port}`;
134 afterAll(() => server.stop(true));
135 const as = (id: string, name: string, role: "user" | "admin"): Record<string, string> => {
136 const identity = `${id}|${name}|${role}|${Date.now() + 60_000}`;
137 return { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
138 };
139 const form = (fields: Record<string, string>) => {
140 const f = new FormData();
141 for (const [k, v] of Object.entries(fields)) f.set(k, v);
142 return f;
143 };
144 const post = (path: string, who: Record<string, string>, body: FormData, extra: Record<string, string> = {}) =>
145 fetch(base + path, { method: "POST", body, headers: { ...who, ...extra }, redirect: "manual" });
146 const page = (path: string, who: Record<string, string>) => fetch(base + path, { headers: who }).then((r) => r.text());
147
148 test("the profile page: a form with a preview for an admin, read-only words for a user", async () => {
149 const admin = as("openers-admin", "openers-root", "admin");
150 const user = as("openers-user", "openers-alice", "user");
151 const html = await page("/profile", admin);
152 expect(html).toContain("How your first reply opens");
153 for (const s of SOURCES) expect(html).toContain(`name="opener_${s}"`);
154 expect(html).toContain(`value="${BUILT_IN_OPENER.zillow}"`);
155 expect(html).toContain("Preview");
156 const seen = await page("/profile", user);
157 expect(seen).toContain("How your first reply opens");
158 expect(seen).toContain(BUILT_IN_OPENER.zillow);
159 expect(seen).not.toContain('name="opener_zillow"');
160 expect(seen).not.toContain("<form class=\"card stack\"");
161 });
162
163 test("a form saves openers, HTML is escaped on the page and the preview, a preview saves nothing", async () => {
164 const admin = as("openers-admin", "openers-root", "admin");
165 const fields = { ...mine, opener_zillow: "<script>alert(1)</script> hello", opener_website: "", opener_open_house: "", opener_referral: "" };
166 const previewed = await post("/profile/preview", admin, form(fields));
167 const shown = await previewed.text();
168 expect(previewed.status).toBe(200);
169 expect(shown).toContain("&lt;script&gt;alert(1)&lt;/script&gt; hello");
170 expect(shown).not.toContain("<script>alert(1)");
171 expect(await page("/profile", admin)).not.toContain("alert(1)");
172 const saved = await post("/profile", admin, form(fields));
173 expect(saved.status).toBe(303);
174 const after = await page("/profile", admin);
175 expect(after).toContain("&lt;script&gt;alert(1)&lt;/script&gt; hello");
176 expect(after).not.toContain("<script>alert(1)");
177 const activity = await page("/activity", admin);
178 expect(activity).toContain("zillow opening");
179 expect(activity).not.toContain("<script>alert(1)");
180 });
181
182 test("over the limit is a 422 on the form, the preview and JSON; saves nothing", async () => {
183 const admin = as("openers-admin", "openers-root", "admin");
184 const long = "y".repeat(OPENER_MAX + 1);
185 expect((await post("/profile/preview", admin, form({ ...mine, opener_zillow: long }))).status).toBe(422);
186 const json = (openers: unknown) =>
187 fetch(base + "/profile", { method: "POST", headers: { ...admin, "content-type": "application/json" }, body: JSON.stringify({ ...mine, openers }) });
188 expect((await json({ zillow: long })).status).toBe(422);
189 expect((await json({ zillow: "a\nb" })).status).toBe(422);
190 expect(await page("/profile", admin)).not.toContain("yyyy");
191 const ok = await json({ referral: "Thanks for the introduction" });
192 expect(ok.status).toBe(200);
193 expect(((await ok.json()) as { openers: Record<string, string> }).openers.referral).toBe("Thanks for the introduction");
194 const spec = JSON.stringify(await (await fetch(base + "/openapi.json", { headers: admin })).json());
195 expect(spec).toContain('"openers"');
196 });
197
198 test("a user gets 403 from the save and the preview; a cross-origin POST is refused", async () => {
199 const user = as("openers-user", "openers-alice", "user");
200 const admin = as("openers-admin", "openers-root", "admin");
201 const fields = { ...mine, opener_zillow: "Sneaky" };
202 const jsonSave = await fetch(base + "/profile", {
203 method: "POST",
204 headers: { ...user, "content-type": "application/json" },
205 body: JSON.stringify({ ...mine, openers: { zillow: "Sneaky" } }),
206 });
207 expect(jsonSave.status).toBe(403);
208 // A form from a user goes back to the page, refused, with nothing saved.
209 expect((await post("/profile", user, form(fields))).status).toBe(303);
210 expect((await post("/profile/preview", user, form(fields))).status).toBe(403);
211 expect((await post("/profile", admin, form(fields), { "sec-fetch-site": "cross-site" })).status).toBe(403);
212 expect((await post("/profile/preview", admin, form(fields), { "sec-fetch-site": "cross-site" })).status).toBe(403);
213 expect(await page("/profile", admin)).not.toContain("Sneaky");
214 });
src/pages/profile.ts +54 −3
@@ -4,6 +4,14 @@
44 */
55
66 import type { Profile } from "../actions.ts";
7 import {
8 draft,
9 OPENER_MAX,
10 SOURCE_LABEL,
11 SOURCES,
12 type Asker,
13 type Source,
14 } from "../drafts.ts";
715 import { escape } from "../http.ts";
816 import type { Who } from "../who.ts";
917 import { layout } from "./layout.ts";
@@ -17,25 +25,68 @@ const FIELDS = [
1725 { name: "timeZone", label: "Time zone (texts wait for 8:00 a.m. there, e.g. America/Chicago)", type: "text", max: 60, auto: "off" },
1826 ] as const;
1927
28 /** The inquiry each source's preview answers: the same person, asking about a showing. */
29 const sample = (source: Source, consent: boolean): Asker => ({
30 name: "Maria Gonzalez",
31 phone: consent ? "(206) 555-0101" : "",
32 source,
33 message: "Could we see 418 Juniper Ln?",
34 consent,
35 });
36
37 /** The day-0 draft for a sample lead from each source, in the words `openers` give. */
38 function previews(profile: Profile, openers: Readonly<Record<Source, string>>): string {
39 const writer = { ...profile, openers };
40 return `<section class="card stack" aria-label="Preview of the first reply">
41 <h2>Preview</h2>
42 <p class="muted">The first reply to a sample lead from each source, as it would be drafted.</p>
43 ${SOURCES.map(
44 (s) =>
45 `<div><p><strong>${escape(SOURCE_LABEL[s])}</strong> <span class="muted">· email</span></p><p class="body">${escape(draft(sample(s, false), 0, writer))}</p><p><span class="muted">Text</span></p><p class="body">${escape(draft(sample(s, true), 0, writer))}</p></div>`,
46 ).join("\n ")}
47 </section>`;
48 }
49
2050 export function profilePage(input: {
2151 who: Who;
2252 profile: Profile;
2353 mayUpdate: boolean;
2454 notice?: string | undefined;
55 /** What the opener inputs hold, when not what is saved (a preview, or a refused save). */
56 fields?: Readonly<Record<Source, string>> | undefined;
57 /** Whether to preview `fields` rather than what is saved. */
58 preview?: boolean | undefined;
2559 }): string {
2660 const { who, profile, mayUpdate, notice } = input;
61 const fields = input.fields ?? profile.openers;
62 const opening = mayUpdate
63 ? `${SOURCES.map(
64 (s) =>
65 `<label>${escape(SOURCE_LABEL[s])} <input class="input" name="opener_${s}" type="text" value="${escape(fields[s])}" maxlength="${OPENER_MAX}" autocomplete="off"></label>`,
66 ).join("\n ")}
67 <p class="muted">One line each, at most ${OPENER_MAX} characters. Leave one empty for the built-in wording. Drafts already on the desk keep their words.</p>
68 <div class="row"><button class="button">Save profile</button> <button class="button" formaction="/profile/preview">Preview</button></div>`
69 : SOURCES.map(
70 (s) => `<p><span class="muted">${escape(SOURCE_LABEL[s])}</span><br>${escape(profile.openers[s])}</p>`,
71 ).join("\n ");
72 const shown = mayUpdate && input.preview === true ? fields : profile.openers;
2773 const body = mayUpdate
2874 ? `<form class="card stack" method="post" action="/profile">
2975 ${FIELDS.map(
3076 (f) =>
3177 `<label>${f.label} <input class="input" name="${f.name}" type="${f.type}" value="${escape(profile[f.name])}" required maxlength="${f.max}" autocomplete="${f.auto}"></label>`,
3278 ).join("\n ")}
33 <button class="button">Save profile</button>
34 </form>`
79 <h2>How your first reply opens</h2>
80 ${opening}
81 </form>
82 ${previews(profile, shown)}`
3583 : `<div class="card stack">
3684 ${FIELDS.map((f) => `<p><span class="muted">${f.label}</span><br>${escape(profile[f.name])}</p>`).join("\n ")}
85 <h2>How your first reply opens</h2>
86 ${opening}
3787 <p class="muted">Only an admin can change this.</p>
38 </div>`;
88 </div>
89 ${previews(profile, shown)}`;
3990 return layout({
4091 who,
4192 agent: profile,
src/profile.test.ts +6 −6
@@ -48,8 +48,8 @@ const sam = {
4848
4949 test("before any save, the environment is the profile", () => {
5050 const db = fresh();
51 expect(currentAgent(db)).toEqual(agent);
52 expect(must(getProfile(db, alice))).toEqual({ id: 1, ...agent });
51 expect(currentAgent(db)).toMatchObject(agent);
52 expect(must(getProfile(db, alice))).toMatchObject({ id: 1, ...agent });
5353 const first = must(addLead(db, alice, lead)).messages[0]!;
5454 expect(first.signature).toContain(agent.license);
5555 });
@@ -62,8 +62,8 @@ test("saving changes the next draft's signature and the unsent ones, never a sen
6262 expect(oldSignature).toContain(agent.license);
6363 const b = must(addLead(db, alice, { ...lead, email: "[email protected]" }));
6464
65 expect(must(saveProfile(db, root, sam))).toEqual({ id: 1, ...sam, timeZone: agent.timeZone });
66 expect(currentAgent(db)).toEqual({ ...sam, timeZone: agent.timeZone });
65 expect(must(saveProfile(db, root, sam))).toMatchObject({ id: 1, ...sam, timeZone: agent.timeZone });
66 expect(currentAgent(db)).toMatchObject({ ...sam, timeZone: agent.timeZone });
6767
6868 const next = must(addLead(db, alice, { ...lead, email: "[email protected]" }));
6969 expect(next.messages[0]!.signature).toContain("WA 99887");
@@ -107,7 +107,7 @@ test("a user may read the profile, not change it; a stranger may do neither", ()
107107 const read = getProfile(db, anon);
108108 if (!read.ok) expect(read.error).toBe("signin_required");
109109 expect(read.ok).toBe(false);
110 expect(currentAgent(db)).toEqual(agent);
110 expect(currentAgent(db)).toMatchObject(agent);
111111 });
112112
113113 test("the license may not be blank, and every field is checked", () => {
@@ -130,7 +130,7 @@ test("the license may not be blank, and every field is checked", () => {
130130 expect([JSON.stringify(bad), r.ok]).toEqual([JSON.stringify(bad), false]);
131131 if (!r.ok) expect(r.error).toBe("invalid");
132132 }
133 expect(currentAgent(db)).toEqual(agent);
133 expect(currentAgent(db)).toMatchObject(agent);
134134 });
135135
136136 test("changes are audited, refusals too", () => {
src/profile.ts +39 −11
@@ -6,31 +6,59 @@
66 */
77
88 import type { Database } from "bun:sqlite";
9 import { agent as fromEnvironment, type Agent } from "./env.ts";
9 import { SOURCES, type Openers, type Writer } from "./drafts.ts";
10 import { agent as fromEnvironment } from "./env.ts";
11
12 /** The openers kept as JSON: only the strings, only for known sources. */
13 function readOpeners(json: string): Openers {
14 let kept: unknown;
15 try {
16 kept = JSON.parse(json);
17 } catch {
18 return {};
19 }
20 if (typeof kept !== "object" || kept === null) return {};
21 const found = kept as Record<string, unknown>;
22 return Object.fromEntries(
23 SOURCES.flatMap((s) =>
24 typeof found[s] === "string" && found[s] !== "" ? [[s, found[s]]] : [],
25 ),
26 );
27 }
1028
1129 /** The saved profile, or the environment's until there is one. */
12 export function currentAgent(db: Database): Agent {
30 export function currentAgent(db: Database): Writer {
1331 const saved = db
14 .query<Omit<Agent, "timeZone"> & { time_zone: string | null }, []>(
15 "SELECT name, brokerage, license, phone, email, time_zone FROM profile WHERE id = 1",
32 .query<Omit<Writer, "timeZone" | "openers"> & { time_zone: string | null; openers: string }, []>(
33 "SELECT name, brokerage, license, phone, email, time_zone, openers FROM profile WHERE id = 1",
1634 )
1735 .get();
1836 if (saved === null) return fromEnvironment;
19 const { time_zone, ...rest } = saved;
20 return { ...rest, timeZone: time_zone ?? fromEnvironment.timeZone };
37 const { time_zone, openers, ...rest } = saved;
38 return { ...rest, timeZone: time_zone ?? fromEnvironment.timeZone, openers: readOpeners(openers) };
2139 }
2240
2341 /** Save `agent` as the profile, whoever it replaces. */
2442 export function storeAgent(
2543 db: Database,
26 agent: Agent,
44 agent: Writer,
2745 by: string,
2846 at: string,
2947 ): void {
3048 db.query(
31 `INSERT INTO profile (id, name, brokerage, license, phone, email, time_zone, updated_at, updated_by)
32 VALUES (1, ?1, ?2, ?3, ?4, ?5, ?8, ?6, ?7)
49 `INSERT INTO profile (id, name, brokerage, license, phone, email, time_zone, openers, updated_at, updated_by)
50 VALUES (1, ?1, ?2, ?3, ?4, ?5, ?8, ?9, ?6, ?7)
3351 ON CONFLICT (id) DO UPDATE SET name = ?1, brokerage = ?2, license = ?3,
34 phone = ?4, email = ?5, time_zone = ?8, updated_at = ?6, updated_by = ?7`,
35 ).run(agent.name, agent.brokerage, agent.license, agent.phone, agent.email, at, by, agent.timeZone);
52 phone = ?4, email = ?5, time_zone = ?8, openers = ?9, updated_at = ?6, updated_by = ?7`,
53 ).run(
54 agent.name,
55 agent.brokerage,
56 agent.license,
57 agent.phone,
58 agent.email,
59 at,
60 by,
61 agent.timeZone,
62 JSON.stringify(agent.openers ?? {}),
63 );
3664 }
src/routes.ts +71 −5
@@ -22,6 +22,7 @@ import {
2222 getAudit,
2323 getLead,
2424 getProfile,
25 readOpeners,
2526 listAudit,
2627 exportLeads,
2728 listLeads,
@@ -42,7 +43,7 @@ import {
4243 type Result,
4344 } from "./actions.ts";
4445 import { permit } from "./contract.ts";
45 import { CADENCE, MAX_BODY, SOURCES } from "./drafts.ts";
46 import { CADENCE, MAX_BODY, OPENER_MAX, SOURCES, type Source } from "./drafts.ts";
4647 import { commit, env, forgeUrl, startedAt, version } from "./env.ts";
4748 import {
4849 asset,
@@ -347,10 +348,19 @@ const PROFILE_FIELDS = {
347348 description: "An IANA time zone name, e.g. America/Chicago. Texts go out only between 8:00 a.m. and 9:00 p.m. there. Left out, it stays as it is.",
348349 },
349350 } as const;
351 const OPENERS: Schema = {
352 type: "object",
353 description:
354 "How a first reply opens, by source. A source left out keeps its wording; an empty one goes back to the built-in line. Drafts already on the desk are not rewritten.",
355 properties: Object.fromEntries(
356 SOURCES.map((s) => [s, { type: "string", maxLength: OPENER_MAX }]),
357 ),
358 additionalProperties: false,
359 };
350360 export const PROFILE: Schema = {
351361 type: "object",
352 properties: { id: { const: 1 }, ...PROFILE_FIELDS },
353 required: ["id", ...Object.keys(PROFILE_FIELDS)],
362 properties: { id: { const: 1 }, ...PROFILE_FIELDS, openers: OPENERS },
363 required: ["id", ...Object.keys(PROFILE_FIELDS), "openers"],
354364 };
355365 export const ERROR: Schema = {
356366 type: "object",
@@ -418,6 +428,15 @@ async function readFields(
418428 );
419429 }
420430
431 /** A form posts one field per source (`opener_zillow`); the action reads an `openers` object, as JSON sends it. */
432 const withOpeners = (input: Record<string, unknown>): Record<string, unknown> => {
433 if (input.openers !== undefined) return input;
434 const own = Object.fromEntries(
435 SOURCES.filter((s) => input[`opener_${s}`] !== undefined).map((s) => [s, input[`opener_${s}`]]),
436 );
437 return Object.keys(own).length === 0 ? input : { ...input, openers: own };
438 };
439
421440 /** The details an edit may carry, and the fields of them that a body names. */
422441 const CONTACT = ["name", "email", "phone"] as const;
423442 const contactOf = (input: Record<string, unknown>): Record<string, unknown> =>
@@ -971,7 +990,7 @@ export const routes: readonly Route[] = [
971990 handle: (c) =>
972991 posted(
973992 c,
974 (input) => saveProfile(c.db, c.who, input),
993 (input) => saveProfile(c.db, c.who, withOpeners(input)),
975994 () => ({ to: "/profile", said: "Saved. Drafts now carry this profile." }),
976995 ),
977996 api: {
@@ -979,12 +998,59 @@ export const routes: readonly Route[] = [
979998 "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.",
980999 body: {
9811000 type: "object",
982 properties: PROFILE_FIELDS,
1001 properties: { ...PROFILE_FIELDS, openers: OPENERS },
9831002 required: Object.keys(PROFILE_FIELDS).filter((f) => f !== "timeZone"),
9841003 },
9851004 answer: PROFILE,
9861005 },
9871006 },
1007 // The profile form's Preview button: the first replies as they would read, nothing saved.
1008 {
1009 method: "POST",
1010 path: "/profile/preview",
1011 handle: async (c) => {
1012 const found = getProfile(c.db, c.who);
1013 if (!found.ok)
1014 return html(
1015 layout({
1016 who: c.who,
1017 agent: currentAgent(c.db),
1018 path: c.url.pathname,
1019 body: `<p class="empty">${escape(found.message)} <a href="/">Back to the desk</a></p>`,
1020 }),
1021 STATUS[found.error],
1022 );
1023 if (permit(c.who, "profile", "update", { id: 1 }) !== "yes")
1024 return html(
1025 layout({
1026 who: c.who,
1027 agent: currentAgent(c.db),
1028 path: c.url.pathname,
1029 body: `<p class="empty">Only an admin can change the profile. <a href="/profile">Back to the profile</a></p>`,
1030 }),
1031 403,
1032 );
1033 const input = await readFields(c.request);
1034 if (input === undefined) return text("too large", 413);
1035 const typed = withOpeners(input).openers;
1036 const read = readOpeners(typed, {});
1037 const given = (typed ?? {}) as Record<string, unknown>;
1038 const fields = Object.fromEntries(
1039 SOURCES.map((s) => [s, typeof given[s] === "string" ? given[s].trim() : found.value.openers[s]]),
1040 ) as Record<Source, string>;
1041 return html(
1042 profilePage({
1043 who: c.who,
1044 profile: found.value,
1045 mayUpdate: true,
1046 fields,
1047 preview: read.ok,
1048 ...(read.ok ? {} : { notice: read.message }),
1049 }),
1050 read.ok ? 200 : 422,
1051 );
1052 },
1053 },
9881054
9891055 // The audit trail in words, for whoever the table lets read it.
9901056 {
src/sentences.ts +5
@@ -29,6 +29,11 @@ export function deed(
2929 lead: string,
3030 esc: (text: string) => string,
3131 ): { done: string; tried: string } {
32 if (row.resource === "profile" && row.act === "openers")
33 return {
34 done: `changed how first replies open${changeWords(row.detail, esc)}`,
35 tried: "change how first replies open",
36 };
3237 if (row.resource === "profile")
3338 return {
3439 done: "changed the agent profile",
src/server.test.ts +3 −3
@@ -319,7 +319,7 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
319319 expect(userSet.result.content[0].text).toContain("forbidden");
320320 expect((await call("set_profile", { ...mine, license: "" }, root)).result.isError).toBe(true);
321321 expect((await call("set_profile", mine, root)).result.isError).toBeUndefined();
322 expect(JSON.parse((await call("get_profile", {}, bob)).result.content[0].text)).toEqual({ id: 1, ...mine, timeZone: "America/New_York" });
322 expect(JSON.parse((await call("get_profile", {}, bob)).result.content[0].text)).toMatchObject({ id: 1, ...mine, timeZone: "America/New_York" });
323323 // The desk over MCP carries the response record beside the leads.
324324 const deskText = (await call("list_leads", {}, bob)).result.content[0].text;
325325 const mcpDesk = JSON.parse(deskText) as { record: { days: number; leads: number }; leads: unknown[] };
@@ -531,7 +531,7 @@ test("what the web expects: robots.txt, and security.txt from the forge that run
531531
532532 test("the profile is a page and a JSON twin: everyone in reads, only an admin saves", async () => {
533533 const seen = await (await api("/profile", { headers: asJson }, alice)).json();
534 expect(Object.keys(seen as object).sort()).toEqual(["brokerage", "email", "id", "license", "name", "phone", "timeZone"]);
534 expect(Object.keys(seen as object).sort()).toEqual(["brokerage", "email", "id", "license", "name", "openers", "phone", "timeZone"]);
535535 const page = await (await api("/profile", {}, alice)).text();
536536 expect(page).toContain("Your profile");
537537 expect(page).not.toContain('action="/profile"');
@@ -544,7 +544,7 @@ test("the profile is a page and a JSON twin: everyone in reads, only an admin sa
544544 expect(blank.status).toBe(422);
545545 const saved = await api("/profile", { method: "POST", ...jsonBody(sam) }, root);
546546 expect(saved.status).toBe(200);
547 expect(await (await api("/profile", { headers: asJson }, bob)).json()).toEqual({ id: 1, ...sam, timeZone: "America/New_York" });
547 expect(await (await api("/profile", { headers: asJson }, bob)).json()).toMatchObject({ id: 1, ...sam, timeZone: "America/New_York" });
548548 const form_ = await api("/profile", {}, root);
549549 expect(await form_.text()).toContain('action="/profile"');
550550 const home = await (await api("/", {}, bob)).text();
src/terminal.test.ts +26 −1
@@ -244,6 +244,7 @@ test("an admin edits the profile one field at a time; it is saved, audited and r
244244 next(agent.phone, "(555) 010-0000");
245245 next(agent.email, "[email protected]");
246246 next(agent.timeZone, "America/Chicago");
247 for (let i = 0; i < 4; i++) t.key("\r"); // the openers stay built-in
247248 expect(read(t)).toContain("Saved.");
248249 expect(db.query<{ time_zone: string }, []>("SELECT time_zone FROM profile").get()?.time_zone).toBe("America/Chicago");
249250 expect(read(t)).toContain("WA 99887");
@@ -258,6 +259,30 @@ test("an admin edits the profile one field at a time; it is saved, audited and r
258259 expect(audit.map((a) => a.outcome)).toEqual(["ok"]);
259260 });
260261
262 test("the profile shows each source's opening; an admin words them in the terminal and a user cannot", () => {
263 const db = fresh();
264 const user = terminal(db, alice);
265 user.key("p");
266 expect(read(user)).toContain("How your first reply opens");
267 expect(read(user)).toContain("Zillow");
268 const t = terminal(db, root);
269 t.key("p");
270 t.key("e");
271 for (let i = 0; i < 6; i++) t.key("\r"); // keep name … time zone as they are
272 expect(read(t)).toContain("Opening for Zillow");
273 const current = (db.query("SELECT openers FROM profile").get() as { openers: string } | null)?.openers;
274 expect(current).toBeUndefined();
275 for (let i = 0; i < 3; i++) t.key("\r"); // Zillow, website and the next stay
276 clear(t, "x".repeat(300));
277 type(t, "Hi from the open house!");
278 t.key("\r");
279 expect(read(t)).toContain("Saved.");
280 expect(read(t)).toContain("Hi from the open house!");
281 const saved = db.query<{ openers: string }, []>("SELECT openers FROM profile").get();
282 expect(Object.values(JSON.parse(saved!.openers))).toEqual(["Hi from the open house!"]);
283 expect(read(user)).toContain("Hi from the open house!");
284 });
285
261286 test("a blank license typed in the terminal is refused and nothing is saved", () => {
262287 const db = fresh();
263288 const t = terminal(db, root);
@@ -266,7 +291,7 @@ test("a blank license typed in the terminal is refused and nothing is saved", ()
266291 for (const current of [agent.name, agent.brokerage]) t.key("\r"), void current;
267292 clear(t, agent.license);
268293 t.key("\r");
269 for (let i = 0; i < 3; i++) t.key("\r");
294 for (let i = 0; i < 7; i++) t.key("\r");
270295 expect(read(t)).toContain("license number is required");
271296 expect(db.query("SELECT * FROM profile").all()).toHaveLength(0);
272297 });
src/terminal.ts +28 −7
@@ -31,6 +31,7 @@ import {
3131 editLead,
3232 getLead,
3333 getProfile,
34 type Profile,
3435 exportLeads,
3536 listLeads,
3637 optOutTexts,
@@ -53,7 +54,7 @@ import { between, elapsed, recordLine, tone } from "./clock.ts";
5354 import { permit } from "./contract.ts";
5455 import { goesLabel, isQuiet, nextOpening, RECORD_NOTE } from "./quiet.ts";
5556 import { said as saidOf } from "./sentences.ts";
56 import { SOURCE_LABEL, SOURCES, channelFor, isAnswer, type Channel } from "./drafts.ts";
57 import { SOURCE_LABEL, SOURCES, channelFor, isAnswer, type Channel, type Source } from "./drafts.ts";
5758 import { ssh, title, where } from "./env.ts";
5859 import { answerSince, CLOSED, MAX_QUERY, VIEWS, queryOf, type DeskLead, type LeadDetail, type Message, type View as DeskView } from "./leads.ts";
5960 import { currentAgent } from "./profile.ts";
@@ -119,6 +120,20 @@ const PROFILE_FIELDS = [
119120 { key: "timeZone", label: "Time zone (e.g. America/Chicago: texts go 8:00 a.m. to 9:00 p.m. there)" },
120121 ] as const;
121122
123 /** Each source's opening line, edited after the five fields above. */
124 const OPENER_FIELDS = SOURCES.map((s) => ({
125 key: `opener_${s}`,
126 source: s,
127 label: `Opening for ${SOURCE_LABEL[s]} (empty: built-in)`,
128 }));
129 const EDIT_FIELDS = [...PROFILE_FIELDS, ...OPENER_FIELDS];
130
131 /** What a field holds now, in the profile the editor starts from. */
132 const held = (p: Profile, key: string): string =>
133 key.startsWith("opener_")
134 ? (p.openers[key.slice("opener_".length) as Source] ?? "")
135 : p[key as (typeof PROFILE_FIELDS)[number]["key"]];
136
122137 type View =
123138 | { name: "desk" }
124139 | { name: "profile" }
@@ -408,6 +423,9 @@ export function terminal(
408423 "",
409424 ...PROFILE_FIELDS.map((f) => `${f.label.split(" (")[0]!.padEnd(15)} ${clean(found.value[f.key])}`),
410425 "",
426 bold("How your first reply opens"),
427 ...OPENER_FIELDS.map((f) => `${SOURCE_LABEL[f.source].padEnd(15)} ${clean(found.value.openers[f.source])}`),
428 "",
411429 dim(`Every message is signed with this.${mayEditProfile() ? " e edit ·" : " Only an admin can change it ·"} esc back`),
412430 ];
413431 }
@@ -448,7 +466,7 @@ export function terminal(
448466
449467 function profileEditScreen(v: Extract<View, { name: "profile-edit" }>): string[] {
450468 const lines = [bold("Your profile — editing"), ""];
451 PROFILE_FIELDS.forEach((field, i) => {
469 EDIT_FIELDS.forEach((field, i) => {
452470 if (i < v.step) lines.push(`${field.label}: ${clean(v.fields[field.key] ?? "")}`);
453471 if (i === v.step) lines.push(`${field.label}: ${clean(v.typed)}█`);
454472 });
@@ -670,7 +688,7 @@ export function terminal(
670688 view = {
671689 name: "profile-edit",
672690 step: 0,
673 typed: found.value[PROFILE_FIELDS[0].key],
691 typed: held(found.value, EDIT_FIELDS[0]!.key),
674692 fields: {},
675693 };
676694 }
@@ -681,19 +699,22 @@ export function terminal(
681699 said = "Nothing changed.";
682700 view = { name: "profile" };
683701 } else if (input === "\r") {
684 const field = PROFILE_FIELDS[view.step]!;
702 const field = EDIT_FIELDS[view.step]!;
685703 const fields = { ...view.fields, [field.key]: view.typed.trim() };
686 const following = PROFILE_FIELDS[view.step + 1];
704 const following = EDIT_FIELDS[view.step + 1];
687705 if (following !== undefined) {
688706 const current = getProfile(db, me);
689707 view = {
690708 name: "profile-edit",
691709 step: view.step + 1,
692 typed: current.ok ? current.value[following.key] : "",
710 typed: current.ok ? held(current.value, following.key) : "",
693711 fields,
694712 };
695713 } else {
696 const saved = saveProfile(db, me, fields);
714 const openers = Object.fromEntries(
715 OPENER_FIELDS.map((f) => [f.source, fields[f.key] ?? ""]),
716 );
717 const saved = saveProfile(db, me, { ...fields, openers });
697718 said = saved.ok ? "Saved. Drafts now carry this profile." : saved.message;
698719 view = { name: "profile" };
699720 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs