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

Keep a private note on a lead (budget, timing, what they want) that shows at the top of their page and never goes to the lead #49

Merged opened this

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

Merged

mason/speed-to-lead:mason/39-keep-a-private-note-on-a-lead-budget-tim → main 4 commits fork 3 threads · 3 unresolved

  • Merged. mason/39-keep-a-private-note-on-a-lead-budget-tim was merged into main as a4075e8.

Review

Sign in to review this change.
18 files changed +681 −26
README.md +10 −1
@@ -127,12 +127,21 @@ otherwise they wait and the page says so (nothing can be sent to no address).
127127 Sent messages stay as they were. The Activity page tells which fields changed,
128128 with old and new values.
129129
130 **Your note on a lead.** What a message thread does not hold (budget, timing,
131 what they want) goes in **Your note**, a card at the top of the lead's page
132 (2,000 characters; empty clears it), for a lead in any state. It is private
133 to you: never put into a drafted message or follow-up, never sent to the lead.
134 Its first line shows under the lead's name on the desk and the desk search finds
135 its text; `PATCH /leads/{id}` with `{"note": …}` (or `POST /leads/{id}/note`),
136 the MCP `set_note` tool and `n` on the terminal's lead screen change it, and the
137 Activity page tells the old and new note.
138
130139 **The desk** (the first screen) lists your leads, newest first. Links above
131140 the list narrow it: **Needs you** (a first reply or follow-up waiting),
132141 **In follow-up** (open, nothing waiting), **Closed** and **All**, each with
133142 its count (`/?show=needs|open|closed|all`; `GET /leads?show=…` and the MCP
134143 `list_leads` tool take the same filter). The **search box** above the
135 links finds a lead by name, email or phone (`/?q=maria`; digits only for a
144 links finds a lead by name, email, private note or phone (`/?q=maria`; digits only for a
136145 phone, so `555 0101` finds `(206) 555-0101`), case-insensitive, up to 80
137146 characters, and combines with the view; "Clear" drops it. `GET /leads?q=…`
138147 and the MCP `list_leads` tool take `q` too, and the terminal desk searches
contract/openapi.json +112 −4
@@ -40,7 +40,7 @@
4040 "schema": {
4141 "type": "string",
4242 "maxLength": 80,
43 "description": "Narrow the desk to leads whose name or email holds this text, or whose phone holds these digits; case-insensitive, at most 80 characters."
43 "description": "Narrow the desk to leads whose name, email or private note holds this text, or whose phone holds these digits; case-insensitive, at most 80 characters."
4444 }
4545 }
4646 ],
@@ -176,7 +176,7 @@
176176 "schema": {
177177 "type": "string",
178178 "maxLength": 80,
179 "description": "Narrow the desk to leads whose name or email holds this text, or whose phone holds these digits; case-insensitive, at most 80 characters."
179 "description": "Narrow the desk to leads whose name, email or private note holds this text, or whose phone holds these digits; case-insensitive, at most 80 characters."
180180 }
181181 }
182182 ],
@@ -323,7 +323,7 @@
323323 }
324324 },
325325 "patch": {
326 "summary": "Mark a lead qualified or lost (the same as POST /leads/{id}/state), or correct its name, email or phone (the same as POST /leads/{id}/edit): send one or the other.",
326 "summary": "Mark a lead qualified or lost (the same as POST /leads/{id}/state), correct its name, email or phone (the same as POST /leads/{id}/edit), or keep a private note on it (the same as POST /leads/{id}/note): send one of the three.",
327327 "operationId": "patchLeadsId",
328328 "parameters": [
329329 {
@@ -362,6 +362,11 @@
362362 "phone": {
363363 "type": "string",
364364 "description": "7 to 20 digits; empty takes it away, if an email remains."
365 },
366 "note": {
367 "type": "string",
368 "maxLength": 2000,
369 "description": "Empty clears it."
365370 }
366371 }
367372 }
@@ -370,7 +375,7 @@
370375 },
371376 "responses": {
372377 "200": {
373 "description": "Mark a lead qualified or lost (the same as POST /leads/{id}/state), or correct its name, email or phone (the same as POST /leads/{id}/edit): send one or the other.",
378 "description": "Mark a lead qualified or lost (the same as POST /leads/{id}/state), correct its name, email or phone (the same as POST /leads/{id}/edit), or keep a private note on it (the same as POST /leads/{id}/note): send one of the three.",
374379 "content": {
375380 "application/json": {
376381 "schema": {
@@ -518,6 +523,19 @@
518523 "type": "boolean",
519524 "description": "Prior written consent to be texted. Without it, only email."
520525 },
526 "note": {
527 "type": "string",
528 "maxLength": 2000,
529 "description": "Your private note on the lead (budget, timing, what they want); empty when none. Never part of a message and never sent to the lead."
530 },
531 "noteUpdatedAt": {
532 "type": [
533 "string",
534 "null"
535 ],
536 "format": "date-time",
537 "description": "When the note was last written; null while there is none."
538 },
521539 "opted_out_at": {
522540 "type": [
523541 "string",
@@ -698,6 +716,8 @@
698716 "source",
699717 "message",
700718 "consent",
719 "note",
720 "noteUpdatedAt",
701721 "opted_out_at",
702722 "state",
703723 "created_at",
@@ -1119,6 +1139,64 @@
11191139 }
11201140 }
11211141 },
1142 "/leads/{id}/note": {
1143 "post": {
1144 "summary": "Keep a private note on a lead (budget, timing, what they want), at most 2,000 characters; empty clears it. It shows at the top of the lead's page and under its name on the desk, is found by the desk search, and is never put into a message or sent to the lead. The audit trail holds the old and new note.",
1145 "operationId": "postLeadsIdNote",
1146 "parameters": [
1147 {
1148 "name": "id",
1149 "in": "path",
1150 "required": true,
1151 "schema": {
1152 "type": "integer"
1153 }
1154 }
1155 ],
1156 "requestBody": {
1157 "required": true,
1158 "content": {
1159 "application/json": {
1160 "schema": {
1161 "type": "object",
1162 "properties": {
1163 "note": {
1164 "type": "string",
1165 "maxLength": 2000,
1166 "description": "Empty clears it."
1167 }
1168 },
1169 "required": [
1170 "note"
1171 ]
1172 }
1173 }
1174 }
1175 },
1176 "responses": {
1177 "200": {
1178 "description": "Keep a private note on a lead (budget, timing, what they want), at most 2,000 characters; empty clears it. It shows at the top of the lead's page and under its name on the desk, is found by the desk search, and is never put into a message or sent to the lead. The audit trail holds the old and new note.",
1179 "content": {
1180 "application/json": {
1181 "schema": {
1182 "$ref": "#/components/schemas/Lead"
1183 }
1184 }
1185 }
1186 },
1187 "default": {
1188 "description": "{ error, message }: why not",
1189 "content": {
1190 "application/json": {
1191 "schema": {
1192 "$ref": "#/components/schemas/Error"
1193 }
1194 }
1195 }
1196 }
1197 }
1198 }
1199 },
11221200 "/leads/{id}/opt-out": {
11231201 "post": {
11241202 "summary": "They replied STOP: no more texts to this lead, for good. Every unsent draft becomes an email; sent messages stay as they were. No body needed; asking twice changes nothing.",
@@ -1723,6 +1801,19 @@
17231801 "type": "boolean",
17241802 "description": "Prior written consent to be texted. Without it, only email."
17251803 },
1804 "note": {
1805 "type": "string",
1806 "maxLength": 2000,
1807 "description": "Your private note on the lead (budget, timing, what they want); empty when none. Never part of a message and never sent to the lead."
1808 },
1809 "noteUpdatedAt": {
1810 "type": [
1811 "string",
1812 "null"
1813 ],
1814 "format": "date-time",
1815 "description": "When the note was last written; null while there is none."
1816 },
17261817 "opted_out_at": {
17271818 "type": [
17281819 "string",
@@ -1879,6 +1970,8 @@
18791970 "source",
18801971 "message",
18811972 "consent",
1973 "note",
1974 "noteUpdatedAt",
18821975 "opted_out_at",
18831976 "state",
18841977 "created_at",
@@ -2018,6 +2111,19 @@
20182111 "type": "boolean",
20192112 "description": "Prior written consent to be texted. Without it, only email."
20202113 },
2114 "note": {
2115 "type": "string",
2116 "maxLength": 2000,
2117 "description": "Your private note on the lead (budget, timing, what they want); empty when none. Never part of a message and never sent to the lead."
2118 },
2119 "noteUpdatedAt": {
2120 "type": [
2121 "string",
2122 "null"
2123 ],
2124 "format": "date-time",
2125 "description": "When the note was last written; null while there is none."
2126 },
20212127 "opted_out_at": {
20222128 "type": [
20232129 "string",
@@ -2115,6 +2221,8 @@
21152221 "source",
21162222 "message",
21172223 "consent",
2224 "note",
2225 "noteUpdatedAt",
21182226 "opted_out_at",
21192227 "state",
21202228 "created_at",
src/actions.ts +53
@@ -40,10 +40,12 @@ import {
4040 sendHeld,
4141 messagesOf,
4242 MAX_INBOUND,
43 MAX_LEAD_NOTE,
4344 MAX_QUERY,
4445 insertLead,
4546 lastMessages,
4647 updateContact,
48 writeNote,
4749 optOut,
4850 nextNeeding,
4951 readyFor,
@@ -396,6 +398,57 @@ function correct(
396398 return ok({ lead: detail(db, lead.id)!, changes });
397399 }
398400
401 /**
402 * The agent's private note on a lead (budget, timing, what they want) is
403 * written; an empty note clears it. It works on a lead in any state, is
404 * never read by the drafts, and the audit row holds the old and new note.
405 */
406 export const setNote = (
407 db: Database,
408 who: Who,
409 input: { id: number; note: unknown },
410 at?: Date,
411 ): Result<LeadDetail> => {
412 const noted = writeNoteOf(db, who, input, at);
413 const changed = noted.ok && noted.value.changed;
414 const result: Result<LeadDetail> = noted.ok ? ok(noted.value.lead) : noted;
415 return audited(
416 db,
417 who,
418 "lead",
419 "update",
420 input.id,
421 result,
422 changed ? "noted" : undefined,
423 changed ? JSON.stringify({ note: noted.value.change }) : undefined,
424 );
425 };
426
427 function writeNoteOf(
428 db: Database,
429 who: Who,
430 input: { id: number; note: unknown },
431 at?: Date,
432 ): Result<{ lead: LeadDetail; changed: boolean; change: { from: string; to: string } }> {
433 const found = leadFor(db, who, "update", input.id, {
434 signIn: "Sign in to keep a note on this lead.",
435 no: "You may not keep a note on this lead.",
436 });
437 if (!found.ok) return found;
438 const lead = found.value;
439 if (typeof input.note !== "string") return fail("invalid", "A note is text.");
440 const note = lines(input.note).trim();
441 if (note.length > MAX_LEAD_NOTE)
442 return fail("invalid", `A note is at most ${MAX_LEAD_NOTE} characters.`);
443 if (hasControl(note, true))
444 return fail("invalid", "A note is plain text: no control characters.");
445 const change = { from: lead.note, to: note };
446 if (note === lead.note) return ok({ lead, changed: false, change });
447 writeNote(db, lead, note, stamp(at));
448 emit("lead.changed", { id: lead.id });
449 return ok({ lead: detail(db, lead.id)!, changed: true, change });
450 }
451
399452 /** The next sample inquiry arrives now, by the same path as any lead. */
400453 export const addSampleInquiry = (
401454 db: Database,
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; `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;
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; `noted` is a change to the agent's private note on the lead; `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", "noted"] as const;
3939 export type Act = (typeof ACTS)[number];
4040
4141 export interface Attempt {
src/contract.test.ts +9
@@ -26,6 +26,7 @@ import {
2626 logLeadReply,
2727 parseLeadEmail,
2828 saveProfile,
29 setNote,
2930 setState,
3031 } from "./actions.ts";
3132 import { record } from "./audit.ts";
@@ -145,6 +146,10 @@ const doors: Record<
145146 // And so is correcting its details (POST /leads/:id/edit, PATCH /leads/:id
146147 // with a name, email or phone, and the MCP tool edit_lead).
147148 const edited = editLead(db, who, { id: replied, name: "Corrected Name" }).ok;
149 // And so is keeping a private note (POST /leads/:id/note, PATCH /leads/:id
150 // with a note, the MCP tool set_note), on an open lead and on a closed one.
151 const noted = setNote(db, who, { id: replied, note: "Pre-approved to $650k" }).ok;
152 const notedViaTool = (tools.find((t) => t.name === "set_note")!.run(db, who, { id: replied, note: "Wants 3 bed" }) as { ok: boolean }).ok;
148153 // And so is taking back a text held for quiet hours (POST /leads/:id/unhold,
149154 // the MCP tool cancel_held_text).
150155 const untold = cancelHeld(db, who, { id: heldLead(authorId) }).ok;
@@ -156,6 +161,10 @@ const doors: Record<
156161 expect(showing).toBe(changed);
157162 expect(off).toBe(changed);
158163 expect(edited).toBe(changed);
164 expect(noted).toBe(changed);
165 expect(notedViaTool).toBe(changed);
166 db.query("UPDATE lead SET state = 'lost' WHERE id = ?1").run(replied);
167 expect(setNote(db, who, { id: replied, note: "Call in spring" }).ok).toBe(changed);
159168 expect(logged).toBe(changed);
160169 expect(called).toBe(changed);
161170 return changed;
src/db.test.ts +16
@@ -26,7 +26,23 @@ 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 lead DROP COLUMN note_updated_at");
30 db.exec("ALTER TABLE lead DROP COLUMN note");
2931 db.exec("ALTER TABLE audit DROP COLUMN detail"); // migrations after them that are not safe to run twice
3032 db.exec("ALTER TABLE profile DROP COLUMN openers");
3133 expect(() => migrate(db)).not.toThrow();
3234 });
35
36 test("a database that ran the note columns before the openers still gets the openers, and nothing runs twice", () => {
37 const dir = mkdtempSync(join(tmpdir(), "app-db-"));
38 const db = openDb(dir);
39 // As a preview left it: the openers column never added, the version past the notes.
40 db.exec("ALTER TABLE profile DROP COLUMN openers");
41 db.exec("DELETE FROM schema_version WHERE version > " + (migrations.length - 1));
42 db.exec("DELETE FROM schema_version WHERE version = " + migrations.length);
43 expect(() => migrate(db)).not.toThrow();
44 expect(db.query("SELECT openers FROM profile").all()).toBeDefined();
45 // And the reverse: a column already there is not added again.
46 db.exec("DELETE FROM schema_version WHERE version > " + (migrations.length - 3));
47 expect(() => migrate(db)).not.toThrow();
48 });
src/db.ts +20 −1
@@ -217,8 +217,27 @@ export const migrations: string[] = [
217217 // The agent's own opening words for a first reply, by source, as JSON.
218218 // `{}` means every source opens with the built-in line.
219219 `ALTER TABLE profile ADD COLUMN openers TEXT NOT NULL DEFAULT '{}'`,
220 // The agent's private note on a lead, and when it was last written.
221 `ALTER TABLE lead ADD COLUMN note TEXT NOT NULL DEFAULT ''`,
222 `ALTER TABLE lead ADD COLUMN note_updated_at TEXT`,
223 // A preview ran the note columns before the openers were merged in, so
224 // its recorded version skipped `openers`. `migrate` leaves out an
225 // ADD COLUMN whose column is already there, so this is a no-op everywhere else.
226 `ALTER TABLE profile ADD COLUMN openers TEXT NOT NULL DEFAULT '{}'`,
220227 ];
221228
229 /** An `ALTER TABLE … ADD COLUMN` whose column the table already has: nothing to do. */
230 function alreadyAdded(db: Database, sql: string): boolean {
231 const added = /^ALTER TABLE (\w+) ADD COLUMN (\w+)/.exec(sql);
232 return (
233 added !== null &&
234 db
235 .query<{ name: string }, []>(`PRAGMA table_info(${added[1]})`)
236 .all()
237 .some((column) => column.name === added[2])
238 );
239 }
240
222241 export function openDb(dir = dataDir): Database {
223242 mkdirSync(dir, { recursive: true });
224243 const db = new Database(join(dir, "app.db"));
@@ -245,7 +264,7 @@ export function migrate(db: Database): number {
245264 >("SELECT coalesce(max(version), 0) AS version FROM schema_version")
246265 .get()!.version;
247266 migrations.slice(current).forEach((sql, i) => {
248 db.exec(sql);
267 if (!alreadyAdded(db, sql)) db.exec(sql);
249268 db.query("INSERT INTO schema_version (version) VALUES (?1)").run(
250269 current + i + 1,
251270 );
src/leads.ts +36 −5
@@ -48,6 +48,10 @@ export interface Lead {
4848 /** When the first reply went out; null while they wait. */
4949 readonly replied_at: string | null;
5050 readonly updated_at: string;
51 /** The agent's private note on the lead; empty when none. Never part of a message. */
52 readonly note: string;
53 /** When the note was last written; null while there is none. */
54 readonly noteUpdatedAt: string | null;
5155 }
5256
5357 export interface Message {
@@ -163,8 +167,15 @@ export type NewLead = {
163167 readonly consent: boolean;
164168 };
165169
166 type LeadRecord = Omit<Lead, "consent"> & { consent: number };
167 const lead = (row: LeadRecord): Lead => ({ ...row, consent: row.consent === 1 });
170 type LeadRecord = Omit<Lead, "consent" | "noteUpdatedAt"> & {
171 consent: number;
172 note_updated_at: string | null;
173 };
174 const lead = ({ note_updated_at, ...row }: LeadRecord): Lead => ({
175 ...row,
176 consent: row.consent === 1,
177 noteUpdatedAt: note_updated_at,
178 });
168179
169180 const DAY_MS = 86_400_000;
170181 const FIVE_MIN_MS = GREEN_MS;
@@ -222,9 +233,19 @@ export function detail(db: Database, id: number): LeadDetail | null {
222233
223234 export const MAX_QUERY = 80;
224235
236 /** The longest private note on a lead, and how much of its first line the desk shows. */
237 export const MAX_LEAD_NOTE = 2000;
238 export const NOTE_PREVIEW = 80;
239
240 /** The first line of a note, cut to what the desk has room for; "" when there is none. */
241 export const noteLine = (note: string): string => {
242 const first = (note.split("\n").find((l) => l.trim() !== "") ?? "").trim();
243 return first.length > NOTE_PREVIEW ? `${first.slice(0, NOTE_PREVIEW - 1)}…` : first;
244 };
245
225246 /** What a door says about the search, in one place. */
226247 export const Q_HELP =
227 "Narrow the desk to leads whose name or email holds this text, or whose phone holds these digits; case-insensitive, at most 80 characters.";
248 "Narrow the desk to leads whose name, email or private note holds this text, or whose phone holds these digits; case-insensitive, at most 80 characters.";
228249
229250 /**
230251 * A search from user text: trimmed, at most 80 characters, no control
@@ -248,8 +269,8 @@ const DIGITS = ["(", ")", "-", " ", ".", "+"].reduce(
248269 );
249270
250271 /**
251 * The desk, newest inquiry first; with `q`, only leads whose name or email
252 * holds it, or whose phone holds its digits ("555 0101" finds "(206) 555-0101").
272 * The desk, newest inquiry first; with `q`, only leads whose name, email or
273 * note holds it, or whose phone holds its digits ("555 0101" finds "(206) 555-0101").
253274 */
254275 export function desk(db: Database, limit: number, q = ""): DeskLead[] {
255276 const digits = /^[\d\s()+.\-]+$/.test(q) ? q.replace(/\D/g, "") : "";
@@ -278,6 +299,7 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] {
278299 (SELECT hold_until FROM showing WHERE lead_id = lead.id) AS show_hold
279300 FROM lead
280301 WHERE ?2 = '' OR lead.name LIKE ?2 ESCAPE '\\' OR lead.email LIKE ?2 ESCAPE '\\'
302 OR lead.note LIKE ?2 ESCAPE '\\'
281303 OR (?3 <> '' AND ${DIGITS} LIKE ?3)
282304 ORDER BY created_at DESC, id DESC LIMIT ?1`,
283305 )
@@ -723,6 +745,15 @@ export function updateContact(db: Database, found: Lead, to: Contact, at: string
723745 })();
724746 }
725747
748 /** The lead's private note is written (empty clears it). Nothing else follows from it. */
749 export function writeNote(db: Database, found: Lead, note: string, at: string): void {
750 db.query("UPDATE lead SET note = ?1, note_updated_at = ?2 WHERE id = ?3").run(
751 note,
752 note === "" ? null : at,
753 found.id,
754 );
755 }
756
726757 /**
727758 * Every message of `lead` not yet sent, drafted again by the channel it now
728759 * allows. A message set aside (`skipped`) is included only when `aside` says so.
src/mcp.ts +15
@@ -16,6 +16,7 @@ import {
1616 listLeads,
1717 saveProfile,
1818 editLead,
19 setNote,
1920 optOutTexts,
2021 approveReply,
2122 cancelHeld,
@@ -243,6 +244,20 @@ export const tools: readonly Tool[] = [
243244 inputSchema: ONE,
244245 run: (db, who, args) => cancelHeld(db, who, { id: Number(args.id) }),
245246 },
247 {
248 name: "set_note",
249 description:
250 "Keep a private note on a lead (budget, timing, what they want), at most 2,000 characters; an empty note clears it. Works on a lead in any state. The note is for the person alone: it is never put into a message or sent to the lead. The desk search finds it; the audit trail records the old and new note.",
251 inputSchema: {
252 type: "object",
253 properties: {
254 id: { type: "integer" },
255 note: { type: "string", maxLength: 2000, description: "Empty clears it." },
256 },
257 required: ["id", "note"],
258 },
259 run: (db, who, args) => setNote(db, who, { id: Number(args.id), note: args.note }),
260 },
246261 {
247262 name: "opt_out_texts",
248263 description:
src/notes.test.ts added +283
@@ -0,0 +1,283 @@
1 /**
2 * The agent's private note on a lead: kept, changed and cleared through one
3 * action; checked at the boundary; found by the desk search; shown on the
4 * lead's page and the desk, escaped; audited with the old and new note; and
5 * never part of anything said to the lead.
6 */
7 import { afterAll, expect, test } from "bun:test";
8 import { mkdtempSync } from "node:fs";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { addLead, editLead, getLead, listLeads, sendReply, setNote, setState, type Result } from "./actions.ts";
12 import type { AuditRow } from "./audit.ts";
13 import { openDb } from "./db.ts";
14 import { currentAgent } from "./profile.ts";
15 import { MAX_LEAD_NOTE, noteLine } from "./leads.ts";
16 import { leadPage } from "./pages/lead.ts";
17 import { serve } from "./server.ts";
18 import { SAMPLES, seed } from "./sample.ts";
19 import { plain, terminal } from "./terminal.ts";
20 import type { Who } from "./who.ts";
21 import { sign } from "./who.ts";
22
23 const alice: Who = { role: "user", id: "u1", name: "alice" };
24 const anon: Who = { role: "anon" };
25 const NEW = {
26 name: "Dana Reys",
27 email: "[email protected]",
28 phone: "(206) 555-0199",
29 source: "website",
30 message: "Can I see 12 Oak Street this week?",
31 consent: true,
32 };
33 const T0 = new Date("2026-03-01T10:00:00Z");
34 const NOTE = "Pre-approved to $650k.\nWants 3 bed near Lincoln Elementary, moving by June.";
35
36 const fresh = () => openDb(mkdtempSync(join(tmpdir(), "app-notes-")));
37 const must = <T>(r: Result<T>): T => {
38 if (!r.ok) throw new Error(r.message);
39 return r.value;
40 };
41 const arrive = (db: ReturnType<typeof fresh>, over: Record<string, unknown> = {}) =>
42 must(addLead(db, alice, { ...NEW, ...over }, T0)).id;
43 const audits = (db: ReturnType<typeof fresh>) =>
44 db.query<AuditRow, []>("SELECT * FROM audit WHERE act = 'noted' ORDER BY id").all();
45
46 test("a note is set, changed and cleared, with its time, and each change writes one audit row", () => {
47 const db = fresh();
48 const id = arrive(db);
49 expect(must(getLead(db, alice, { id }))).toMatchObject({ note: "", noteUpdatedAt: null });
50
51 const set = must(setNote(db, alice, { id, note: ` ${NOTE}\r\n ` }, T0));
52 expect(set.note).toBe(NOTE);
53 expect(set.noteUpdatedAt).toBe(T0.toISOString());
54 let rows = audits(db);
55 expect(rows).toHaveLength(1);
56 expect(rows[0]!.who_name).toBe("alice");
57 expect(JSON.parse(rows[0]!.detail!)).toEqual({ note: { from: "", to: NOTE } });
58
59 const later = new Date(T0.getTime() + 3_600_000);
60 const changed = must(setNote(db, alice, { id, note: "Now wants a condo." }, later));
61 expect(changed.noteUpdatedAt).toBe(later.toISOString());
62 expect(JSON.parse(audits(db)[1]!.detail!)).toEqual({ note: { from: NOTE, to: "Now wants a condo." } });
63
64 // The same note again changes nothing and says nothing.
65 must(setNote(db, alice, { id, note: "Now wants a condo." }, new Date(later.getTime() + 1000)));
66 expect(audits(db)).toHaveLength(2);
67
68 const cleared = must(setNote(db, alice, { id, note: " " }));
69 expect(cleared).toMatchObject({ note: "", noteUpdatedAt: null });
70 rows = audits(db);
71 expect(rows).toHaveLength(3);
72 expect(JSON.parse(rows[2]!.detail!)).toEqual({ note: { from: "Now wants a condo.", to: "" } });
73 });
74
75 test("a note works on a qualified or lost lead", () => {
76 const db = fresh();
77 for (const state of ["qualified", "lost"] as const) {
78 const id = arrive(db);
79 must(setState(db, alice, { id, state }));
80 expect(must(setNote(db, alice, { id, note: "Call in spring." })).note).toBe("Call in spring.");
81 }
82 });
83
84 test("more than 2,000 characters, control characters and non-text are refused and change nothing", () => {
85 const db = fresh();
86 const id = arrive(db);
87 must(setNote(db, alice, { id, note: "Keep me." }));
88 for (const bad of ["x".repeat(MAX_LEAD_NOTE + 1), "bell\x07", "esc\x1b[2J", 7, null, undefined]) {
89 const r = setNote(db, alice, { id, note: bad });
90 expect(r.ok).toBe(false);
91 if (!r.ok) expect(r.error).toBe("invalid");
92 }
93 expect(must(getLead(db, alice, { id })).note).toBe("Keep me.");
94 expect(audits(db)).toHaveLength(1);
95 expect(setNote(db, alice, { id, note: "x".repeat(MAX_LEAD_NOTE) }).ok).toBe(true);
96 });
97
98 test("an anonymous visitor may not keep a note", () => {
99 const db = fresh();
100 const id = arrive(db);
101 const r = setNote(db, anon, { id, note: "Sneaky" });
102 expect(r.ok).toBe(false);
103 expect(must(getLead(db, alice, { id })).note).toBe("");
104 expect(setNote(db, alice, { id: 9999, note: "x" })).toMatchObject({ ok: false, error: "not_found" });
105 });
106
107 test("a lead with a note is drafted to exactly the same words as one without", () => {
108 const db = fresh();
109 const plainId = arrive(db, { email: "[email protected]" });
110 const notedId = arrive(db, { email: "[email protected]" });
111 const secret = "Pre-approved to $650k";
112 must(setNote(db, alice, { id: notedId, note: `${secret}. Hates the Oak Street house.` }));
113 const words = (id: number) => must(getLead(db, alice, { id })).messages.map((m) => [m.day, m.channel, m.body, m.signature]);
114 const strip = (rows: unknown[][]) => JSON.stringify(rows).replaceAll("[email protected]", "x");
115 expect(strip(words(notedId))).toBe(strip(words(plainId)));
116
117 // Through the cadence, an edit of the details and a sent reply: still nothing of the note.
118 must(editLead(db, alice, { id: notedId, phone: "" }));
119 must(sendReply(db, alice, { id: notedId }, new Date(T0.getTime() + 60_000)));
120 const after = must(getLead(db, alice, { id: notedId }));
121 expect(after.messages.length).toBeGreaterThan(1);
122 expect(JSON.stringify(after.messages)).not.toContain("650k");
123 expect(JSON.stringify(after.messages)).not.toContain("Oak Street house");
124 });
125
126 test("the desk search finds a lead by its note", () => {
127 const db = fresh();
128 const id = arrive(db);
129 arrive(db, { name: "Other Person", email: "[email protected]", phone: "" });
130 must(setNote(db, alice, { id, note: "Near Lincoln Elementary" }));
131 const found = must(listLeads(db, alice, { q: "lincoln elem" }));
132 expect(found.leads.map((l) => l.id)).toEqual([id]);
133 expect(found.leads[0]!.note).toBe("Near Lincoln Elementary");
134 expect(must(listLeads(db, alice, { q: "nowhere" })).leads).toHaveLength(0);
135 });
136
137 test("the desk line is the first line, at most 80 characters", () => {
138 expect(noteLine("")).toBe("");
139 expect(noteLine("\n first\nsecond")).toBe("first");
140 expect(noteLine("x".repeat(200))).toHaveLength(80);
141 expect(noteLine("x".repeat(80))).toBe("x".repeat(80));
142 });
143
144 test("the sample desk gives two leads a note", () => {
145 expect(SAMPLES.filter((s) => s.note !== undefined)).toHaveLength(2);
146 const db = fresh();
147 seed(db, new Date());
148 const noted = must(listLeads(db, alice, {})).leads.filter((l) => l.note !== "");
149 expect(noted).toHaveLength(2);
150 expect(noted.every((l) => l.noteUpdatedAt !== null)).toBe(true);
151 });
152
153 test("the lead page shows the note escaped with its time, and the form only to whoever may update", () => {
154 const db = fresh();
155 const id = arrive(db);
156 must(setNote(db, alice, { id, note: "<script>alert(1)</script> & more" }, T0));
157 const lead = must(getLead(db, alice, { id }));
158 const show = (mayUpdate: boolean, l = lead) =>
159 leadPage({ who: alice, agent: currentAgent(db), lead: l, mayUpdate, next: null, now: T0.getTime() + 1000 });
160 const page = show(true);
161 expect(page).toContain("Your note");
162 expect(page).toContain("&lt;script&gt;alert(1)&lt;/script&gt; &amp; more");
163 expect(page).not.toContain("<script>alert");
164 expect(page).toContain(`<time datetime="${T0.toISOString()}"`);
165 expect(page).toContain(`action="/leads/${id}/note"`);
166 const readOnly = show(false);
167 expect(readOnly).toContain("&lt;script&gt;");
168 expect(readOnly).not.toContain("/note");
169 expect(readOnly).not.toContain("<textarea class=\"input\" id=\"note-text\"");
170 // No note and no right to write one: no card at all.
171 expect(show(false, { ...lead, note: "", noteUpdatedAt: null })).not.toContain("Your note");
172 expect(show(true, { ...lead, note: "", noteUpdatedAt: null })).toContain("Save note");
173 });
174
175 // --- the doors ---
176
177 const KEY = "a-key-only-the-forge-holds";
178 const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-")), identityKey: KEY });
179 const base = `http://${server.hostname}:${server.port}`;
180 afterAll(() => server.stop(true));
181 let grants = 0;
182 const as = (id: string, name: string, role = "user") => {
183 const identity = `${id}|${name}|${role}|${Date.now() + 60_000}`;
184 return { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
185 };
186 const call = (path: string, init: RequestInit = {}, who: Record<string, string> = as(`u-${++grants}`, "alice")) =>
187 fetch(base + path, { ...init, headers: { ...(init.headers as object), ...who } });
188 const JSON_HEADERS = { "content-type": "application/json", accept: "application/json" };
189 const made = async () =>
190 (await (await call("/leads", { method: "POST", headers: JSON_HEADERS, body: JSON.stringify(NEW) })).json()) as { id: number };
191
192 test("PATCH /leads/:id keeps, clears and refuses a note; POST /leads/:id/note works from the form; cross-site is refused", async () => {
193 const { id } = await made();
194 const patch = (body: unknown, who?: Record<string, string>, headers: object = {}) =>
195 call(`/leads/${id}`, { method: "PATCH", headers: { ...JSON_HEADERS, ...headers }, body: JSON.stringify(body) }, who);
196
197 const ok = await patch({ note: "Budget 650k" });
198 expect(ok.status).toBe(200);
199 expect(await ok.json()).toMatchObject({ note: "Budget 650k", noteUpdatedAt: expect.any(String) });
200 const shown = (await (await call(`/leads/${id}`, { headers: { accept: "application/json" } })).json()) as { note: string };
201 expect(shown.note).toBe("Budget 650k");
202
203 const tooLong = await patch({ note: "x".repeat(MAX_LEAD_NOTE + 1) });
204 expect(tooLong.status).toBe(422);
205 expect(await patch({ note: "ok", state: "lost" })).toHaveProperty("status", 422);
206 expect(await patch({ note: 5 })).toHaveProperty("status", 422);
207 expect(await patch({ note: "x" }, {})).toHaveProperty("status", 401);
208 expect(await patch({ note: "x" }, undefined, { "sec-fetch-site": "cross-site" })).toHaveProperty("status", 403);
209 const still = (await (await call(`/leads/${id}`, { headers: { accept: "application/json" } })).json()) as { note: string };
210 expect(still.note).toBe("Budget 650k");
211
212 const f = new FormData();
213 f.set("note", "From the form <b>");
214 const alice2 = as("u-form", "alice");
215 expect((await call(`/leads/${id}/note`, { method: "POST", body: f, redirect: "manual" }, alice2)).status).toBe(303);
216 expect((await call(`/leads/${id}/note`, { method: "POST", body: f, headers: { "sec-fetch-site": "cross-site" } }, alice2)).status).toBe(403);
217 const page = await (await call(`/leads/${id}`, {}, alice2)).text();
218 expect(page).toContain("From the form &lt;b&gt;");
219 expect(page).toContain(`action="/leads/${id}/note"`);
220 expect(await (await call(`/leads/${id}`, {}, {})).text()).not.toContain('action="/leads/');
221
222 expect((await patch({ note: "" })).status).toBe(200);
223 const desk = await (await call("/", {}, alice2)).text();
224 expect(desk).not.toContain("From the form");
225
226 const spec = (await (await call("/openapi.json")).json()) as { paths: Record<string, unknown> };
227 expect(Object.keys(spec.paths)).toContain("/leads/{id}/note");
228 });
229
230 test("the desk shows the note's first line escaped, the search finds it, and Activity tells the change", async () => {
231 const { id } = await made();
232 const alice3 = as("u-desk", "alice");
233 const f = new FormData();
234 f.set("note", `<i>${"y".repeat(100)}</i>\nsecond line zebra`);
235 await call(`/leads/${id}/note`, { method: "POST", body: f, redirect: "manual" }, alice3);
236 const desk = await (await call("/", {}, alice3)).text();
237 expect(desk).toContain(`&lt;i&gt;${"y".repeat(76)}…`);
238 expect(desk).not.toContain("second line");
239 expect(desk).not.toContain("<i>yyy");
240 const searched = await (await call("/?q=zebra", {}, alice3)).text();
241 expect(searched).toContain(`href="/leads/${id}"`);
242 expect(await (await call("/?q=nonesuch-note", {}, alice3)).text()).not.toContain(`href="/leads/${id}"`);
243
244 const activity = await (await call("/activity", {}, as("u0", "root", "admin"))).text();
245 expect(activity).toContain("alice changed the private note");
246 expect(activity).toContain("note nothing → “&lt;i&gt;");
247 });
248
249 test("the MCP keeps a note, and refuses a stranger or a note too long", async () => {
250 const { id } = await made();
251 const rpc = (who: Record<string, string>, args: unknown) =>
252 call("/mcp", {
253 method: "POST",
254 headers: JSON_HEADERS,
255 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "set_note", arguments: args } }),
256 }, who).then((r) => r.json() as Promise<any>);
257 const done = await rpc(as("u-mcp", "alice"), { id, note: "Via the tool" });
258 expect(done.result.isError).toBeUndefined();
259 expect(JSON.stringify(done.result)).toContain("Via the tool");
260 expect((await rpc({}, { id, note: "Nope" })).result?.isError ?? true).toBe(true);
261 expect((await rpc(as("u-mcp", "alice"), { id, note: "x".repeat(2001) })).result.isError).toBe(true);
262 });
263
264 test("the terminal shows the note and keeps one with n", () => {
265 const db = fresh();
266 const id = arrive(db);
267 const t = terminal(db, alice);
268 const read = () => t.screen(100).map(plain).join("\n");
269 t.key("\r");
270 expect(read()).toContain("n add a note");
271 t.key("n");
272 for (const ch of "Cash buyer") t.key(ch);
273 t.key("\x04");
274 expect(read()).toContain("Note saved");
275 expect(read()).toContain("Your note (private)");
276 expect(read()).toContain("Cash buyer");
277 expect(must(getLead(db, alice, { id })).note).toBe("Cash buyer");
278 t.key("n");
279 for (let i = 0; i < 10; i++) t.key("\x7f");
280 t.key("\x04");
281 expect(read()).toContain("Note cleared");
282 expect(terminal(db, anon).screen(100).map(plain).join("\n")).not.toContain("add a note");
283 });
src/pages/desk.ts +4 −3
@@ -11,7 +11,7 @@ import { isAnswer } from "../drafts.ts";
1111 import { goesLabel, RECORD_NOTE } from "../quiet.ts";
1212 import { showingWhen } from "../showings.ts";
1313 import { MAX_EMAIL_TEXT, missingLine } from "../intake.ts";
outdated

ResponseRecord and View are types; import them with type.

14 import type { DeskLead, NewLead, ResponseRecord, View } from "../leads.ts";
14 import { noteLine, type DeskLead, type NewLead, type ResponseRecord, type View } from "../leads.ts";
1515 import type { Agent } from "../env.ts";
1616 import type { Who } from "../who.ts";
1717
@@ -66,7 +66,7 @@ export function deskPage(input: {
6666 ).join("")}</nav>`;
6767 const search = `<form class="search" role="search" method="get" action="/">
6868 ${show === "all" ? "" : `<input type="hidden" name="show" value="${show}">`}
69 <input class="input" type="search" name="q" value="${escape(q)}" maxlength="80" placeholder="Find by name, email or phone" aria-label="Find a lead by name, email or phone" autocomplete="off">
69 <input class="input" type="search" name="q" value="${escape(q)}" maxlength="80" placeholder="Find by name, email, phone or note" aria-label="Find a lead by name, email, phone or note" autocomplete="off">
7070 <button class="button button-quiet">Search</button>
7171 </form>
7272 ${q === "" ? "" : found(q, show, counts?.all ?? leads.length)}`;
@@ -174,7 +174,8 @@ function status(lead: DeskLead, now: number, zone: string): string {
174174 const row = (lead: DeskLead, now: number, zone: string): string => `<li>
175175 <a class="lead-row" href="/leads/${lead.id}"${lead.state === "lost" ? " data-closed" : ""}>
176176 <span class="lead-main">
177 <span class="lead-name">${escape(lead.name)}</span>
177 <span class="lead-name">${escape(lead.name)}</span>${noteLine(lead.note) === "" ? "" : `
178 <span class="note-line">${escape(noteLine(lead.note))}</span>`}
178179 <span class="tags">${source(lead)}${consent(lead)}${showingBadge(lead, now)}</span>
179180 <span class="ask">${escape(lead.message)}</span>
180181 ${status(lead, now, zone)}
src/pages/lead.ts +24 −1
@@ -10,7 +10,7 @@ import { escape } from "../http.ts";
1010 import { MAX_ADDRESS, MAX_AHEAD_DAYS, showingLine, showingWhen } from "../showings.ts";
1111 import { elapsed, between } from "../clock.ts";
1212 import { goesLabel, isQuiet, nextOpening } from "../quiet.ts";
13 import { answerSince, MAX_INBOUND, type LeadDetail, type Message, type NextLead } from "../leads.ts";
13 import { answerSince, MAX_INBOUND, MAX_LEAD_NOTE, type LeadDetail, type Message, type NextLead } from "../leads.ts";
1414 import type { Agent } from "../env.ts";
1515 import type { Who } from "../who.ts";
1616 import { layout } from "./layout.ts";
@@ -281,6 +281,7 @@ export function leadPage(input: {
281281 </div>
282282 ${clock(lead, now, owed)}
283283 </header>
284 ${noteCard(lead, path, mayUpdate)}
284285 <div class="split">
285286 <div class="pane theirs">
286287 <h2>They asked <span class="muted">· <time datetime="${escape(lead.created_at)}">${escape(when(lead.created_at))}</time></span></h2>
@@ -300,6 +301,28 @@ export function leadPage(input: {
300301 });
301302 }
302303
304 /** "Your note": the agent's own, private; the form only for whoever may update the lead. */
305 function noteCard(lead: LeadDetail, path: string, may: boolean): string {
306 if (lead.note === "" && !may) return "";
307 return `<section class="card note" id="note">
308 <h2>Your note <span class="muted">· private, never sent to the lead${
309 lead.noteUpdatedAt === null
310 ? ""
311 : ` · edited <time datetime="${escape(lead.noteUpdatedAt)}">${escape(when(lead.noteUpdatedAt))}</time>`
312 }</span></h2>${lead.note === "" ? "" : `
313 <p class="body">${escape(lead.note)}</p>`}${

The note's line breaks collapse here; keep them (white-space: pre-wrap).

314 may
315 ? `
316 <form class="stack" method="post" action="${path}/note">
317 <label class="sr" for="note-text">Your note on ${escape(lead.name)}</label>
318 <textarea class="input" id="note-text" name="note" rows="3" maxlength="${MAX_LEAD_NOTE}" placeholder="Budget, timing, what they want">${escape(lead.note)}</textarea>
319 <button class="button button-quiet">${lead.note === "" ? "Save note" : "Update note"}</button>
320 </form>`
321 : ""
322 }
323 </section>`;
324 }
325
303326 /** "Edit details": the lead's name, email and phone, for whoever may update it. */
304327 function editDetails(lead: LeadDetail, path: string, may: boolean): string {
305328 if (!may) return "";
src/routes.ts +40 −5
@@ -19,6 +19,7 @@ import {
1919 deleteLead,
2020 activity,
2121 editLead,
22 setNote,
2223 getAudit,
2324 getLead,
2425 getProfile,
@@ -62,7 +63,7 @@ import {
6263 import { MAX_NOTE, OUTCOMES } from "./calls.ts";
6364 import { MAX_ADDRESS, MAX_AHEAD_DAYS } from "./showings.ts";
6465 import { MAX_EMAIL_TEXT } from "./intake.ts";
65 import { MAX_INBOUND, MAX_QUERY, Q_HELP, VIEW_HELP, VIEWS, type NewLead } from "./leads.ts";
66 import { MAX_INBOUND, MAX_LEAD_NOTE, MAX_QUERY, Q_HELP, VIEW_HELP, VIEWS, type NewLead } from "./leads.ts";
6667 import { events } from "./live.ts";
6768 import { rpc } from "./mcp.ts";
6869 import { deskPage } from "./pages/desk.ts";
@@ -144,6 +145,16 @@ const LEAD_FIELDS = {
144145 type: "boolean",
145146 description: "Prior written consent to be texted. Without it, only email.",
146147 },
148 note: {
149 type: "string",
150 maxLength: MAX_LEAD_NOTE,
151 description: "Your private note on the lead (budget, timing, what they want); empty when none. Never part of a message and never sent to the lead.",
152 },
153 noteUpdatedAt: {
154 type: ["string", "null"],
155 format: "date-time",
156 description: "When the note was last written; null while there is none.",
157 },
147158 opted_out_at: {
148159 type: ["string", "null"],
149160 format: "date-time",
@@ -447,6 +458,12 @@ const EDIT_FIELDS = {
447458 phone: { type: "string", description: "7 to 20 digits; empty takes it away, if an email remains." },
448459 } as const;
449460
461 const NOTE_FIELD = {
462 type: "string",
463 maxLength: MAX_LEAD_NOTE,
464 description: "Empty clears it.",
465 } as const;
466
450467 /** One POST, answered for whoever sent it: JSON to a script, back to the page for a form. */
451468 const posted = async <T>(
452469 c: Context,
@@ -661,21 +678,23 @@ export const routes: readonly Route[] = [
661678 const input = fields(body);
662679 // One change at a time: a mark, or a correction of the details.
663680 const details = CONTACT.some((field) => input[field] !== undefined);
664 if (details && input.state !== undefined)
681 const noted = input.note !== undefined;
682 if ([details, noted, input.state !== undefined].filter(Boolean).length > 1)
665683 return json(
666 { error: "invalid", message: "Send a state, or details to correct, not both." },
684 { error: "invalid", message: "Send one change at a time: a state, details to correct, or a note." },
667685 422,
668686 );
687 if (noted) return answer(setNote(c.db, c.who, { id: ID(c), note: input.note }));
669688 if (details)
670689 return answer(editLead(c.db, c.who, { id: ID(c), ...contactOf(input) }));
671690 return answer(setState(c.db, c.who, { id: ID(c), state: input.state }));
672691 },
673692 api: {
674693 summary:
675 "Mark a lead qualified or lost (the same as POST /leads/{id}/state), or correct its name, email or phone (the same as POST /leads/{id}/edit): send one or the other.",
694 "Mark a lead qualified or lost (the same as POST /leads/{id}/state), correct its name, email or phone (the same as POST /leads/{id}/edit), or keep a private note on it (the same as POST /leads/{id}/note): send one of the three.",
676695 body: {
677696 type: "object",
678 properties: { state: { enum: ["qualified", "lost", "open"] }, ...EDIT_FIELDS },
697 properties: { state: { enum: ["qualified", "lost", "open"] }, ...EDIT_FIELDS, note: NOTE_FIELD },
679698 },
680699 answer: LEAD,
681700 },
@@ -892,6 +911,22 @@ export const routes: readonly Route[] = [
892911 answer: LEAD,
893912 },
894913 },
914 {
915 method: "POST",
916 path: "/leads/:id/note",
917 handle: (c) =>
918 posted(
919 c,
920 (input) => setNote(c.db, c.who, { id: ID(c), note: input.note }),
921 (lead) => ({ to: `/leads/${ID(c)}`, said: lead?.note === "" ? "Note cleared." : "Note saved." }),
922 ),
923 api: {
924 summary:
925 "Keep a private note on a lead (budget, timing, what they want), at most 2,000 characters; empty clears it. It shows at the top of the lead's page and under its name on the desk, is found by the desk search, and is never put into a message or sent to the lead. The audit trail holds the old and new note.",
926 body: { type: "object", properties: { note: NOTE_FIELD }, required: ["note"] },
927 answer: LEAD,
928 },
929 },
895930 {
896931 method: "POST",
897932 path: "/leads/:id/opt-out",
src/sample.ts +7 −2
@@ -17,6 +17,7 @@ import {
1717 insertLead,
1818 readyFor,
1919 send,
20 writeNote,
2021 type NewLead,
2122 } from "./leads.ts";
2223
@@ -28,6 +29,8 @@ interface Sample extends NewLead {
2829 /** The cadence days already sent. */
2930 readonly touched?: readonly number[];
3031 readonly closed?: "qualified" | "lost";
32 /** The agent's private note on the lead, as of the first reply or the inquiry. */
33 readonly note?: string;
3134 }
3235
3336 const S = 1000;
@@ -61,10 +64,10 @@ export const SAMPLES: readonly Sample[] = [
6164 person("David Chen", "website", false, "We're thinking about selling our townhouse in the spring. Any idea what it might be worth in today's market?", { ago: 3 * M + 10 * S }),
6265 person("Priya Raman", "open_house", true, "Loved the kitchen at Sunday's open house on Alder Ct. Are the sellers flexible on price at all?", { ago: 18 * M }),
6366 person("James O'Neill", "referral", false, "Sarah Patel said you helped her family relocate last year. We're moving from Denver in August and don't know the area.", { ago: 47 * M }),
64 person("Aisha Bello", "zillow", false, "Pre-approved up to $550k. Looking for 3 bedrooms with a yard, ideally near good schools.", { ago: 2 * H + 12 * M }),
67 person("Aisha Bello", "zillow", false, "Pre-approved up to $550k. Looking for 3 bedrooms with a yard, ideally near good schools.", { ago: 2 * H + 12 * M, note: "Pre-approved to $550k. Wants 3 bed with a yard near Lincoln Elementary. Lease ends in June, so moving by then." }),
6568 person("Tom Becker", "website", true, "Do you work with first-time buyers? We have no idea where to start.", { ago: 5 * H + 30 * M }),
6669 person("Lena Novak", "open_house", false, "Signed in at the open house on Birch St. Could you send me the disclosures and HOA details?", { ago: 26 * H }),
67 person("Marcus Lee", "zillow", true, "Can I tour 92 Harbor View Dr this week? Available most evenings after 6.", { ago: 2 * D + 3 * H, answeredIn: 48 * S, touched: [1] }),
70 person("Marcus Lee", "zillow", true, "Can I tour 92 Harbor View Dr this week? Available most evenings after 6.", { ago: 2 * D + 3 * H, answeredIn: 48 * S, touched: [1], note: "Works nights: call after 6. Cash buyer, relocating from Austin; wants a short closing." }),
6871 person("Rosa Alvarez", "referral", false, "My cousin Elena recommended you. We need a bigger place before the baby comes in March.", { ago: 4 * D + 2 * H, answeredIn: 3 * M + 20 * S, touched: [1] }),
6972 person("Ethan Brooks", "website", true, "What would my 2-bed condo on Seaview Ave sell for? Considering upsizing next year.", { ago: 8 * D + 5 * H, answeredIn: 2 * M + 5 * S, touched: [1, 3] }),
7073 person("Grace Kim", "zillow", false, "Is the price on 7 Larkspur Ct negotiable? We're pre-approved and ready to move.", { ago: 15 * D, answeredIn: 1 * M + 30 * S, touched: [1, 3, 7], closed: "qualified" }),
@@ -87,6 +90,8 @@ export function seed(db: Database, now: Date): number {
8790 sendReady(db, id, iso(replied + day * D + 55 * M));
8891 }
8992 }
93 if (sample.note !== undefined)
94 writeNote(db, findLead(db, id)!, sample.note, iso(asked + 30 * M));
9095 if (sample.closed !== undefined) close(db, id, sample.closed, iso(t - 2 * D));
9196 }
9297 advance(db, iso(t));
src/sentences.ts +5
@@ -79,6 +79,11 @@ export function deed(
7979 tried: `correct ${lead}'s details`,
8080 };
8181 }
82 if (row.act === "noted")
83 return {
84 done: `changed the private note on ${lead}${changeWords(row.detail, esc)}`,
85 tried: `change the private note on ${lead}`,
86 };
8287 if (row.act === "showing")
8388 return {
8489 done: `booked a showing with ${lead}`,
src/server.test.ts +1
@@ -296,6 +296,7 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
296296 "mark_lead",
297297 "edit_lead",
298298 "cancel_held_text",
299 "set_note",
299300 "opt_out_texts",
300301 "get_profile",
301302 "set_profile",
src/terminal.ts +36 −2
@@ -5,7 +5,7 @@
55 * may — the hints only leave out keys the table would refuse.
66 *
77 * Screens:
8 * desk j/k move · enter open · f view (needs/open/closed/all) · / find by name, email or phone · n log a lead · v paste a lead email · i new sample inquiry · p profile · a activity (admin) · R restart samples (admin) · esc quit
8 * desk j/k move · enter open · f view (needs/open/closed/all) · / find by name, email, phone or note · n log a lead · v paste a lead email · i new sample inquiry · p profile · a activity (admin) · R restart samples (admin) · esc quit
99 * lead s approve and send · e edit, then send · w they wrote back · ] next lead that needs you ·
1010 * q qualified · x lost · t asked to stop texts · D remove (admin) · esc back
1111 * edit type; enter is a new line · ctrl-d approve and send · esc cancel
@@ -29,6 +29,7 @@ import {
2929 addSampleInquiry,
3030 deleteLead,
3131 editLead,
32 setNote,
3233 getLead,
3334 getProfile,
3435 type Profile,
@@ -146,6 +147,7 @@ type View =
146147 | { name: "call"; id: number; outcome: Outcome; text: string }
147148 | { name: "showing"; id: number; step: 0 | 1; typed: string; when: string }
148149 | { name: "wrote"; id: number; text: string; channel: Channel }
150 | { name: "note"; id: number; text: string }
149151 | { name: "details"; id: number; step: number; typed: string; fields: Record<string, string> }
150152 | { name: "paste"; text: string }
151153 | { name: "add"; step: number; typed: string; fields: Record<string, string>; found?: Record<string, string>; note?: string }
@@ -303,6 +305,9 @@ export function terminal(
303305 const mayEdit = (l: LeadDetail): boolean =>
304306 permit(me, "lead", "update", { ...l }) === "yes" && !CLOSED.includes(l.state);
305307
308 /** Whether the private note can be changed here: the table says yes, in any state. */
309 const mayNote = (l: LeadDetail): boolean => permit(me, "lead", "update", { ...l }) === "yes";
310
306311 function leadScreen(id: number, width: number, editing?: string): string[] {
307312 const l = lead(id);
308313 if (l === undefined) {
@@ -315,6 +320,9 @@ export function terminal(
315320 const lines = [
316321 `${bold(clean(l.name))} ${SOURCE_LABEL[l.source]} · ${channel === "text" ? "Text OK" : "Email only"} · ${l.state} ${clockOf(l)}`,
317322 dim([l.email, l.phone].filter((s) => s !== "").map((s) => clean(s)).join(" · ")),
323 ...(l.note === ""
324 ? []
325 : ["", bold("Your note (private)"), ...wrap(l.note, width).map((s) => ` ${s}`)]),
318326 "",
319327 bold("They asked"),
320328 ...wrap(l.message, width).map((s) => ` ${s}`),
@@ -401,6 +409,7 @@ export function terminal(
401409 ? ["o put back in follow-ups"]
402410 : ["q qualified", "x lost"]),
403411 ...(mayEdit(l) ? ["d fix details"] : []),
412 ...(mayNote(l) ? [l.note === "" ? "n add a note" : "n edit your note"] : []),
404413 ...(l.consent ? ["t they asked to stop texts"] : []),
405414 ...(nextLead(db, me, { except: l.id }) === null ? [] : ["] next that needs you"]),
406415 ...(admin() ? ["D remove"] : []),
@@ -567,7 +576,7 @@ export function terminal(
567576 : view.name === "profile-edit"
568577 ? profileEditScreen(view)
569578 : view.name === "search"
570 ? ["Find a lead by name, email or phone", "", `/ ${view.typed}▏`, "", dim("enter search · empty clears · esc cancel")]
579 ? ["Find a lead by name, email, phone or note", "", `/ ${view.typed}▏`, "", dim("enter search · empty clears · esc cancel")]
571580 : view.name === "lead"
572581 ? leadScreen(view.id, w)
573582 : view.name === "edit"
@@ -600,6 +609,14 @@ export function terminal(
600609 "",
601610 dim("type a note · enter new line · ctrl-o outcome · ctrl-d log the call · esc cancel"),
602611 ]
612 : view.name === "note"
613 ? [
614 bold(`Your note on ${clean(lead(view.id)?.name ?? "the lead")} (private, never sent)`),
615 "",
616 ...wrap(`${view.text}█`, w).map((s) => ` ${s}`),
617 "",
618 dim("type · enter new line · ctrl-d save (empty clears) · esc cancel"),
619 ]
603620 : view.name === "details"
604621 ? detailsScreen(view)
605622 : view.name === "paste"
@@ -757,6 +774,8 @@ export function terminal(
757774 said = off.ok ? "Showing cancelled. Follow-ups are back in their usual place." : off.message;
758775 } else if (input === "w")
759776 view = { name: "wrote", id, text: "", channel: "email" };
777 else if (input === "n" && mayNote(l))
778 view = { name: "note", id, text: l.note };
760779 else if (input === "d" && mayEdit(l))
761780 view = { name: "details", id, step: 0, typed: l.name, fields: {} };
762781 else if (input === "o" && CLOSED.includes(l.state)) {
@@ -859,6 +878,21 @@ export function terminal(
859878 }
860879 return;
861880 }
881 case "note": {
882 if (input === "\x1b") {
883 said = "Note unchanged.";
884 view = { name: "lead", id: view.id };
885 } else if (input === "\x04") {
886 const saved = setNote(db, me, { id: view.id, note: view.text });
887 said = saved.ok ? (saved.value.note === "" ? "Note cleared." : "Note saved.") : saved.message;
888 if (saved.ok || saved.error !== "invalid") view = { name: "lead", id: view.id };
889 } else if (input === "\r") view = { ...view, text: `${view.text}\n` };
890 else {
891 const next = typing(view.text, input.replace(/\r\n?/g, "\n"));
892 if (next !== undefined) view = { ...view, text: next };
893 }
894 return;
895 }
862896 case "details": {
863897 if (input === "\x1b") {
864898 said = "Nothing changed.";
static/app.css +8
@@ -225,6 +225,11 @@ footer {
225225 overflow: hidden;
226226 overflow-wrap: anywhere;
227227 }
228 .note-line {
229 color: var(--color-muted);
230 font-style: italic;
231 overflow-wrap: anywhere;
232 }
228233 .status {
229234 font-size: var(--text-sm);
230235 color: var(--color-muted);
@@ -384,6 +389,9 @@ blockquote {
384389 font-size: var(--text-sm);
385390 white-space: pre-line;
386391 }
392 .note .body {
393 white-space: pre-wrap;
394 }
387395 .hint {
388396 margin-top: var(--space-3);
389397 color: var(--color-warn);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs