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

A text approved late at night waits until 8 a.m. and the desk says when it will go #44

Merged opened this

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

Merged

mason/speed-to-lead:mason/42-a-text-approved-late-at-night-waits-unti → main 3 commits fork

  • Merged. mason/42-a-text-approved-late-at-night-waits-unti was merged into main as 4648e3e.

Review

Sign in to review this change.
24 files changed +942 −76
README.md +21 −2
@@ -203,6 +203,24 @@ past, malformed or too distant time), `DELETE /leads/:id/showing`, and the MCP
203203 tools `book_showing` and `cancel_showing`. It needs the same permission as any
204204 change to a lead, and shows on the Activity page.
205205
206 **Quiet hours.** Texts go out only between 8:00 a.m. and 9:00 p.m. in your
207 time zone, the window realtors are told to keep. Approve a text at 11 p.m.
208 and the app does not send it: it is approved, held, and the lead's page and
209 the desk say "Goes at 8:00 a.m. tomorrow". It goes by itself soon after 8:00
210 (the app checks every five minutes), and until then **Cancel and keep as a
211 draft** takes it back. If the lead replies STOP before it goes, it never goes
212 as a text: it becomes an email draft. Emails are never held. A held text
213 counts as your reply from the moment you approve it, not from when it goes,
214 and the line under your response record says so. Set your time zone on
215 **Your profile** (an IANA name such as `America/Chicago`; until you do it is
216 `AGENT_TIMEZONE`, then `TZ`, then `America/New_York`). A script sees it as
217 `scheduledFor` in the answer to `POST /leads/:id/reply` and takes the text
218 back with `POST /leads/:id/unhold`; MCP has `send_reply` and
219 `cancel_held_text`; in the terminal, `h` on the lead. `QUIET_HOURS=off` lets
220 texts go at any hour (the test suite sets it). The 8:00 delivery is done by
221 the clock, not by a person, so it is not audited: Activity shows the text as
222 `held` (and the cancel), but never the send itself.
223
206224 **Sample leads.** The app starts with twelve sample leads so you can see it
207225 work: two just in, two waiting a while, three gone red, and five already
208226 answered and partway through their follow-ups. An admin can restart them
@@ -241,12 +259,13 @@ Avery of Harbor & Pine Realty. Once a profile is saved it wins.
241259 | `AGENT_LICENSE` | your license number, as shown |
242260 | `AGENT_PHONE` | the phone number in your emails |
243261 | `AGENT_EMAIL` | the email address in your emails |
262 | `AGENT_TIMEZONE` | your time zone, for quiet hours (falls back to `TZ`) |
244263
245264 In the terminal, press `p` on the desk to read it; an admin presses `e`
246265 and types each field in turn (enter moves on, the last one saves).
247266
248267 A script reads it with `GET /profile` and an admin changes it with
249 `POST /profile` (JSON, all five fields); MCP has `get_profile` and
268 `POST /profile` (JSON, the five fields and optionally `timeZone`); MCP has `get_profile` and
250269 `set_profile`.
251270
252271 ## For whoever connects it to a website
@@ -274,7 +293,7 @@ emails, phones and messages are plain text: anything carrying control
274293 characters is turned away. `POST /tick` is safe to call as often as you
275294 like, but only as someone the forge has signed in — an unsigned scheduled
276295 job gets "sign in first". Nothing depends on it: the app does the same
277 itself every hour. The whole API is described at `/openapi.json`, and the same
296 itself every five minutes. The whole API is described at `/openapi.json`, and the same
278297 actions are MCP tools at `POST /mcp` (`list_leads`, `get_lead`, `add_lead`,
279298 `send_reply`, `mark_lead`, `export_leads`).
280299
bunfig.toml added +2
@@ -0,0 +1,2 @@
1 [test]
2 preload = ["./src/test-setup.ts"]
contract/openapi.json +94 −7
@@ -373,7 +373,7 @@
373373 },
374374 "/leads/{id}/reply": {
375375 "post": {
376 "summary": "Approve and send what is ready for this lead — the first reply, or the follow-up that is due — as drafted, or with `body` as edited. The first reply starts the follow-up plan.",
376 "summary": "Approve and send what is ready for this lead — the first reply, or the follow-up that is due — as drafted, or with `body` as edited. The first reply starts the follow-up plan. A text approved outside 8:00 a.m. to 9:00 p.m. in the profile's time zone is held for the next 8:00 and the answer says `scheduledFor`; an email always goes now.",
377377 "operationId": "postLeadsIdReply",
378378 "parameters": [
379379 {
@@ -405,7 +405,7 @@
405405 },
406406 "responses": {
407407 "200": {
408 "description": "Approve and send what is ready for this lead — the first reply, or the follow-up that is due — as drafted, or with `body` as edited. The first reply starts the follow-up plan.",
408 "description": "Approve and send what is ready for this lead — the first reply, or the follow-up that is due — as drafted, or with `body` as edited. The first reply starts the follow-up plan. A text approved outside 8:00 a.m. to 9:00 p.m. in the profile's time zone is held for the next 8:00 and the answer says `scheduledFor`; an email always goes now.",
409409 "content": {
410410 "application/json": {
411411 "schema": {
@@ -608,6 +608,11 @@
608608 "id",
609609 "name"
610610 ]
611 },
612 "scheduledFor": {
613 "type": "string",
614 "format": "date-time",
615 "description": "Present only when the text was held for quiet hours: when it will go (the next 8:00 a.m. in your time zone). Absent when it went now."
611616 }
612617 },
613618 "required": [
@@ -1001,6 +1006,44 @@
10011006 }
10021007 }
10031008 },
1009 "/leads/{id}/unhold": {
1010 "post": {
1011 "summary": "Take back a text held for quiet hours: it returns to an unsent draft you can edit and approve again. No body needed.",
1012 "operationId": "postLeadsIdUnhold",
1013 "parameters": [
1014 {
1015 "name": "id",
1016 "in": "path",
1017 "required": true,
1018 "schema": {
1019 "type": "integer"
1020 }
1021 }
1022 ],
1023 "responses": {
1024 "200": {
1025 "description": "Take back a text held for quiet hours: it returns to an unsent draft you can edit and approve again. No body needed.",
1026 "content": {
1027 "application/json": {
1028 "schema": {
1029 "$ref": "#/components/schemas/Lead"
1030 }
1031 }
1032 }
1033 },
1034 "default": {
1035 "description": "{ error, message }: why not",
1036 "content": {
1037 "application/json": {
1038 "schema": {
1039 "$ref": "#/components/schemas/Error"
1040 }
1041 }
1042 }
1043 }
1044 }
1045 }
1046 },
10041047 "/leads/{id}/opt-out": {
10051048 "post": {
10061049 "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.",
@@ -1041,11 +1084,11 @@
10411084 },
10421085 "/tick": {
10431086 "post": {
1044 "summary": "The day turns: every follow-up whose day has come is ready to approve. Safe to call as often as you like; the app also does it hourly.",
1087 "summary": "The day turns: every follow-up whose day has come is ready to approve, and every text held for quiet hours whose 8:00 a.m. has come goes out. Safe to call as often as you like; the app also does it every five minutes.",
10451088 "operationId": "postTick",
10461089 "responses": {
10471090 "200": {
1048 "description": "The day turns: every follow-up whose day has come is ready to approve. Safe to call as often as you like; the app also does it hourly.",
1091 "description": "The day turns: every follow-up whose day has come is ready to approve, and every text held for quiet hours whose 8:00 a.m. has come goes out. Safe to call as often as you like; the app also does it every five minutes.",
10491092 "content": {
10501093 "application/json": {
10511094 "schema": {
@@ -1144,6 +1187,11 @@
11441187 "email": {
11451188 "type": "string",
11461189 "format": "email"
1190 },
1191 "timeZone": {
1192 "type": "string",
1193 "maxLength": 60,
1194 "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."
11471195 }
11481196 },
11491197 "required": [
@@ -1152,7 +1200,8 @@
11521200 "brokerage",
11531201 "license",
11541202 "phone",
1155 "email"
1203 "email",
1204 "timeZone"
11561205 ]
11571206 }
11581207 }
@@ -1203,6 +1252,11 @@
12031252 "email": {
12041253 "type": "string",
12051254 "format": "email"
1255 },
1256 "timeZone": {
1257 "type": "string",
1258 "maxLength": 60,
1259 "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."
12061260 }
12071261 },
12081262 "required": [
@@ -1250,6 +1304,11 @@
12501304 "email": {
12511305 "type": "string",
12521306 "format": "email"
1307 },
1308 "timeZone": {
1309 "type": "string",
1310 "maxLength": 60,
1311 "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."
12531312 }
12541313 },
12551314 "required": [
@@ -1258,7 +1317,8 @@
12581317 "brokerage",
12591318 "license",
12601319 "phone",
1261 "email"
1320 "email",
1321 "timeZone"
12621322 ]
12631323 }
12641324 }
@@ -1870,6 +1930,14 @@
18701930 ],
18711931 "format": "date-time"
18721932 },
1933 "goes_at": {
1934 "type": [
1935 "string",
1936 "null"
1937 ],
1938 "format": "date-time",
1939 "description": "When a text you approved goes, if one is held for quiet hours."
1940 },
18731941 "showing": {
18741942 "type": [
18751943 "object",
@@ -1908,6 +1976,7 @@
19081976 "updated_at",
19091977 "ready",
19101978 "next_at",
1979 "goes_at",
19111980 "showing"
19121981 ]
19131982 },
@@ -1944,9 +2013,11 @@
19442013 "draft",
19452014 "scheduled",
19462015 "due",
2016 "held",
19472017 "sent",
19482018 "skipped"
1949 ]
2019 ],
2020 "description": "held: a text you approved outside 8:00 a.m. to 9:00 p.m. in your time zone; it goes at goes_at."
19502021 },
19512022 "due_at": {
19522023 "type": "string",
@@ -1964,6 +2035,22 @@
19642035 "string",
19652036 "null"
19662037 ]
2038 },
2039 "goes_at": {
2040 "type": [
2041 "string",
2042 "null"
2043 ],
2044 "format": "date-time",
2045 "description": "For a held text, when it goes."
2046 },
2047 "approved_at": {
2048 "type": [
2049 "string",
2050 "null"
2051 ],
2052 "format": "date-time",
2053 "description": "For a held text, when you approved it: the moment that counts as the reply."
19672054 }
19682055 },
19692056 "required": [
src/actions.ts +65 −16
@@ -25,6 +25,11 @@ import {
2525 inView,
2626 queryOf,
2727 reopen,
28 heldFor,
29 hold,
30 release,
31 sendHeld,
32 messagesOf,
2833 MAX_INBOUND,
2934 MAX_QUERY,
3035 insertLead,
@@ -51,6 +56,7 @@ import {
5156 import { emit } from "./live.ts";
5257 import { currentAgent, storeAgent } from "./profile.ts";
5358 import { nextInquiry, seed } from "./sample.ts";
59 import { goesAt, isZone } from "./quiet.ts";
5460 import { MAX_ADDRESS, timeOf } from "./showings.ts";
5561 import type { Who } from "./who.ts";
5662
@@ -383,15 +389,10 @@ export const sendReply = (
383389 at?: Date,
384390 ): Result<LeadDetail> => {
385391 const first = findLead(db, input.id)?.replied_at === null;
386 return audited(
387 db,
388 who,
389 "lead",
390 "update",
391 input.id,
392 reply(db, who, input, at),
393 first ? "first_reply" : "reply",
394 );
392 const ready = readyFor(db, input.id)?.id;
393 const result = reply(db, who, input, at);
394 const held = result.ok && result.value.messages.some((m) => m.id === ready && m.status === "held");
395 return audited(db, who, "lead", "update", input.id, result, held ? "held" : first ? "first_reply" : "reply");
395396 };
396397
397398 /**
@@ -409,6 +410,8 @@ export const nextLead = (
409410 /** A sent reply, and the lead to open next: the id and name, or null. */
410411 export type Approved = LeadDetail & {
411412 readonly next: { readonly id: number; readonly name: string } | null;
413 /** When the text will go, if it was held for quiet hours; absent when it went now. */
414 readonly scheduledFor?: string;
412415 };
413416
414417 /** `sendReply`, and which lead needs the agent after it. */
@@ -418,12 +421,15 @@ export const approveReply = (
418421 input: { id: number; body?: string | undefined },
419422 at?: Date,
420423 ): Result<Approved> => {
424 const before = readyFor(db, input.id)?.id;
421425 const sent = sendReply(db, who, input, at);
422426 if (!sent.ok) return sent;
423427 const next = nextLead(db, who, { except: input.id });
428 const held = sent.value.messages.find((m) => m.id === before && m.status === "held");
424429 return ok({
425430 ...sent.value,
426431 next: next === null ? null : { id: next.id, name: next.name },
432 ...(held?.goes_at ? { scheduledFor: held.goes_at } : {}),
427433 });
428434 };
429435
@@ -453,7 +459,42 @@ function reply(
453459 if (ready.channel === "email" && found.value.email === "")
454460 return fail("invalid", "This lead has no email address and has not agreed to be texted: add one, or call them.");
455461 const by = who.role === "anon" ? "" : who.name;
456 send(db, found.value, ready, body, by, stamp(at), currentAgent(db));
462 const now = stamp(at);
463 const agent = currentAgent(db);
464 // A text outside quiet hours is approved now and goes at the next 8:00.
465 const goes = goesAt(ready.channel, now, agent.timeZone);
466 if (goes === null) send(db, found.value, ready, body, by, now, agent);
467 else hold(db, found.value, ready, body, by, now, goes);
468 emit("lead.changed", { id: found.value.id });
469 return ok(detail(db, found.value.id)!);
470 }
471
472 /**
473 * Take back a text held for quiet hours: it returns to an unsent draft the
474 * agent can edit and approve again, and the lead is as unanswered as before.
475 */
476 export const cancelHeld = (
477 db: Database,
478 who: Who,
479 input: { id: number },
480 at?: Date,
481 ): Result<LeadDetail> =>
482 audited(db, who, "lead", "update", input.id, unhold(db, who, input, at), "unhold");
483
484 function unhold(
485 db: Database,
486 who: Who,
487 input: { id: number },
488 at?: Date,
489 ): Result<LeadDetail> {
490 const found = leadFor(db, who, "update", input.id, {
491 signIn: "Sign in to cancel a text.",
492 no: "You may not cancel a text for this lead.",
493 });
494 if (!found.ok) return found;
495 const held = heldFor(db, found.value.id);
496 if (held === null) return fail("invalid", "No text is waiting for 8:00 a.m. on this lead.");
497 release(db, held, stamp(at));
457498 emit("lead.changed", { id: found.value.id });
458499 return ok(detail(db, found.value.id)!);
459500 }
@@ -718,9 +759,9 @@ function remove(
718759 }
719760
720761 /**
721 * The day turns: every touch whose day has come is due, ready to approve.
762 * The day turns: every touch whose day has come is due, ready to approve, and every text held for quiet hours whose time has come goes out.
722763 * The forge may call it daily (`POST /tick`); the server also runs it on
723 * its own every hour, so a missed call costs nothing. Running it twice
764 * its own every five minutes (a held text goes within minutes of 8:00), so a missed call costs nothing. Running it twice
724765 * changes nothing the second time.
725766 */
726767 export function tick(
@@ -744,7 +785,9 @@ export function tick(
744785
745786 /** The clock's own turn, asked of no one: time passing is not a person. */
746787 export function turn(db: Database, at?: Date): number[] {
747 const leads = advance(db, stamp(at));
788 const now = stamp(at);
789 const sent = sendHeld(db, now, currentAgent(db));
790 const leads = [...new Set([...advance(db, now), ...sent])];
748791 for (const id of leads) emit("lead.changed", { id });
749792 return leads;
750793 }
@@ -793,7 +836,10 @@ export function getProfile(db: Database, who: Who): Result<Profile> {
793836 }
794837
795838 /** What arrived for the profile, checked field by field: the agent to keep, or what is wrong. */
796 export function readAgent(input: Record<string, unknown>): Result<Agent> {
839 export function readAgent(
840 input: Record<string, unknown>,
841 keep: string,
842 ): Result<Agent> {
797843 const text = (v: unknown): string => (typeof v === "string" ? v.trim() : "");
798844 const name = text(input.name);
799845 const brokerage = text(input.brokerage);
@@ -818,7 +864,10 @@ export function readAgent(input: Record<string, unknown>): Result<Agent> {
818864 return fail("invalid", "A phone number is 7 to 20 digits.");
819865 if (email.length > 254 || !EMAIL.test(email))
820866 return fail("invalid", "An email address looks like [email protected].");
821 return ok({ name, brokerage, license, phone, email });
867 const timeZone = input.timeZone === undefined ? keep : text(input.timeZone);
868 if (!isZone(timeZone))
869 return fail("invalid", "A time zone is a name like America/Chicago or Europe/London.");
870 return ok({ name, brokerage, license, phone, email, timeZone });
822871 }
823872
824873 export const saveProfile = (
@@ -841,7 +890,7 @@ function change(
841890 "Sign in to change the profile.",
842891 "Only an admin can change the profile.",
843892 );
844 const read = readAgent(input);
893 const read = readAgent(input, currentAgent(db).timeZone);
845894 if (!read.ok) return read;
846895 db.transaction(() => {
847896 storeAgent(db, read.value, who.role === "anon" ? "" : who.name, stamp(at));
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. */
38 export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off", "edited"] 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. */
38 export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off", "edited", "held", "unhold"] as const;
3939 export type Act = (typeof ACTS)[number];
4040
4141 export interface Attempt {
src/contract.test.ts +20 −1
@@ -21,6 +21,7 @@ import {
2121 listLeads,
2222 logCall,
2323 bookShowing,
24 cancelHeld,
2425 cancelShowing,
2526 logLeadReply,
2627 saveProfile,
@@ -44,7 +45,8 @@ function whoIs(identity: string): Who {
4445 }
4546
4647 import { agent } from "./env.ts";
47 import { insertLead } from "./leads.ts";
48 import { findLead, hold, insertLead, type Message } from "./leads.ts";
49 import { tools } from "./mcp.ts";
4850
4951 // Leads name no one: they are the desk's, not a person's. `authorId` goes unused.
5052 const aLead = (_authorId: string): number =>
@@ -61,6 +63,16 @@ const aLead = (_authorId: string): number =>
6163 new Date().toISOString(),
6264 agent,
6365 );
66 /** A lead with a text held for 8:00, as quiet hours leave it. */
67 const heldLead = (authorId: string): number => {
68 const id = aLead(authorId);
69 const draft = db
70 .query<Message, [number]>("SELECT * FROM message WHERE lead_id = ?1 AND day = 0")
71 .get(id)!;
72 const now = new Date().toISOString();
73 hold(db, findLead(db, id)!, draft, "Hello", "alice", now, new Date(Date.now() + 3_600_000).toISOString());
74 return id;
75 };
6476 const PROFILE = {
6577 name: "Sam Realtor",
6678 brokerage: "Sam & Co",
@@ -130,7 +142,14 @@ const doors: Record<
130142 // And so is correcting its details (POST /leads/:id/edit, PATCH /leads/:id
131143 // with a name, email or phone, and the MCP tool edit_lead).
132144 const edited = editLead(db, who, { id: replied, name: "Corrected Name" }).ok;
145 // And so is taking back a text held for quiet hours (POST /leads/:id/unhold,
146 // the MCP tool cancel_held_text).
147 const untold = cancelHeld(db, who, { id: heldLead(authorId) }).ok;
148 const cancelTool = tools.find((t) => t.name === "cancel_held_text")!;
149 const viaTool = (cancelTool.run(db, who, { id: heldLead(authorId) }) as { ok: boolean }).ok;
133150 const changed = setState(db, who, { id: aLead(authorId), state: "lost" }).ok;
151 expect(untold).toBe(changed);
152 expect(viaTool).toBe(changed);
134153 expect(showing).toBe(changed);
135154 expect(off).toBe(changed);
136155 expect(edited).toBe(changed);
src/db.ts +49
@@ -165,6 +165,55 @@ export const migrations: string[] = [
165165 ALTER TABLE lead_new RENAME TO lead;
166166 PRAGMA legacy_alter_table = OFF`,
167167 `CREATE INDEX IF NOT EXISTS lead_created ON lead (created_at)`,
168 // Quiet hours. The agent's time zone (null until set: the environment's
169 // speaks), and a text the agent approved outside 8:00-21:00 there: it is
170 // `held` with the moment it goes (`goes_at`) and when it was approved
171 // (`approved_at`, the moment that counts as the reply). SQLite cannot widen
172 // a CHECK in place (nor add a column twice), so both tables are rebuilt with
173 // their rows, index and triggers; safe to run again.
174 `DROP TABLE IF EXISTS profile_new`,
175 `CREATE TABLE profile_new (
176 id INTEGER PRIMARY KEY CHECK (id = 1),
177 name TEXT NOT NULL CHECK (length(name) BETWEEN 1 AND 120),
178 brokerage TEXT NOT NULL CHECK (length(brokerage) BETWEEN 1 AND 120),
179 license TEXT NOT NULL CHECK (length(trim(license)) BETWEEN 1 AND 60),
180 phone TEXT NOT NULL CHECK (length(phone) BETWEEN 1 AND 40),
181 email TEXT NOT NULL CHECK (length(email) BETWEEN 3 AND 254),
182 updated_at TEXT NOT NULL,
183 updated_by TEXT NOT NULL,
184 time_zone TEXT
185 )`,
186 `INSERT INTO profile_new (id, name, brokerage, license, phone, email, updated_at, updated_by)
187 SELECT id, name, brokerage, license, phone, email, updated_at, updated_by FROM profile`,
188 `DROP TABLE profile`,
189 `ALTER TABLE profile_new RENAME TO profile`,
190 `DROP TABLE IF EXISTS message_new`,
191 `CREATE TABLE message_new (
192 id INTEGER PRIMARY KEY,
193 lead_id INTEGER NOT NULL REFERENCES lead (id) ON DELETE CASCADE,
194 day INTEGER NOT NULL CHECK (day >= 0),
195 channel TEXT NOT NULL CHECK (channel IN ('text', 'email')),
196 body TEXT NOT NULL CHECK (length(body) BETWEEN 1 AND 4000),
197 signature TEXT NOT NULL,
198 status TEXT NOT NULL CHECK (status IN ('draft', 'scheduled', 'due', 'held', 'sent', 'skipped')),
199 due_at TEXT NOT NULL,
200 sent_at TEXT,
201 sent_by TEXT,
202 goes_at TEXT,
203 approved_at TEXT,
204 UNIQUE (lead_id, day)
205 )`,
206 `INSERT INTO message_new (id, lead_id, day, channel, body, signature, status, due_at, sent_at, sent_by)
207 SELECT id, lead_id, day, channel, body, signature, status, due_at, sent_at, sent_by FROM message`,
208 `DROP TABLE message`,
209 `ALTER TABLE message_new RENAME TO message`,
210 `CREATE INDEX IF NOT EXISTS message_due ON message (status, due_at)`,
211 `CREATE TRIGGER IF NOT EXISTS message_text_needs_consent BEFORE INSERT ON message
212 WHEN NEW.channel = 'text' AND (SELECT consent FROM lead WHERE id = NEW.lead_id) = 0
213 BEGIN SELECT RAISE(ABORT, 'no consent to text'); END`,
214 `CREATE TRIGGER IF NOT EXISTS message_text_needs_consent_update BEFORE UPDATE OF channel ON message
215 WHEN NEW.channel = 'text' AND (SELECT consent FROM lead WHERE id = NEW.lead_id) = 0
216 BEGIN SELECT RAISE(ABORT, 'no consent to text'); END`,
168217 ];
169218
170219 export function openDb(dir = dataDir): Database {
src/env.ts +3
@@ -5,6 +5,7 @@
55 */
66
77 import pkg from "../package.json";
8 import { isZone } from "./quiet.ts";
89
910 /** What a person sees the app called. */
1011 export const title = "Speed to Lead";
@@ -45,5 +46,7 @@ export const agent = {
4546 license: process.env.AGENT_LICENSE || "CA DRE 02145789",
4647 phone: process.env.AGENT_PHONE || "(555) 214-0187",
4748 email: process.env.AGENT_EMAIL || "[email protected]",
49 /** Where the agent's clock is: quiet hours for texts are kept in it. */
50 timeZone: [process.env.AGENT_TIMEZONE, process.env.TZ].find(isZone) ?? "America/New_York",
4851 } as const;
4952 export type Agent = typeof agent;
src/leads.ts +119 −14
@@ -26,6 +26,7 @@ import {
2626 import { answers, type Call, type Outcome } from "./calls.ts";
2727 import { GREEN_MS } from "./clock.ts";
2828 import type { Agent } from "./env.ts";
29 import { isQuiet, nextOpening } from "./quiet.ts";
2930 import { holdUntil, type Showing } from "./showings.ts";
3031
3132 export type State = "new" | "contacted" | "qualified" | "lost";
@@ -57,10 +58,14 @@ export interface Message {
5758 readonly channel: Channel;
5859 readonly body: string;
5960 readonly signature: string;
60 readonly status: "draft" | "scheduled" | "due" | "sent" | "skipped";
61 readonly status: "draft" | "scheduled" | "due" | "held" | "sent" | "skipped";
6162 readonly due_at: string;
6263 readonly sent_at: string | null;
6364 readonly sent_by: string | null;
65 /** For a held text: the moment it goes (the next 8:00 a.m.); null otherwise. */
66 readonly goes_at: string | null;
67 /** For a held text: when the agent approved it, which is when the lead counts as answered. */
68 readonly approved_at: string | null;
6469 }
6570
6671 /** The most a lead's reply may hold. */
@@ -95,6 +100,8 @@ export interface DeskLead extends Lead {
95100 readonly ready: { readonly id: number; readonly day: number; readonly since: string } | null;
96101 /** When the next scheduled touch comes due, if one is. */
97102 readonly next_at: string | null;
103 /** When a text the agent approved goes, if one is held for quiet hours. */
104 readonly goes_at: string | null;
98105 /** The showing booked on this lead, if one is. */
99106 readonly showing: Pick<Showing, "at" | "address" | "hold_until"> | null;
100107 }
@@ -253,6 +260,7 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] {
253260 ready_day: number | null;
254261 ready_since: string | null;
255262 next_at: string | null;
263 goes_at: string | null;
256264 show_at: string | null;
257265 show_address: string | null;
258266 show_hold: string | null;
@@ -264,6 +272,7 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] {
264272 (SELECT day FROM message WHERE lead_id = lead.id AND status IN ('draft', 'due') ORDER BY day LIMIT 1) AS ready_day,
265273 (SELECT due_at FROM message WHERE lead_id = lead.id AND status IN ('draft', 'due') ORDER BY day LIMIT 1) AS ready_since,
266274 (SELECT min(due_at) FROM message WHERE lead_id = lead.id AND status = 'scheduled') AS next_at,
275 (SELECT min(goes_at) FROM message WHERE lead_id = lead.id AND status = 'held') AS goes_at,
267276 (SELECT at FROM showing WHERE lead_id = lead.id) AS show_at,
268277 (SELECT address FROM showing WHERE lead_id = lead.id) AS show_address,
269278 (SELECT hold_until FROM showing WHERE lead_id = lead.id) AS show_hold
@@ -273,13 +282,14 @@ export function desk(db: Database, limit: number, q = ""): DeskLead[] {
273282 ORDER BY created_at DESC, id DESC LIMIT ?1`,
274283 )
275284 .all(limit, q === "" ? "" : likeOf(q), digits === "" ? "" : `%${digits}%`)
276 .map(({ ready_id, ready_day, ready_since, next_at, show_at, show_address, show_hold, ...row }) => ({
285 .map(({ ready_id, ready_day, ready_since, next_at, goes_at, show_at, show_address, show_hold, ...row }) => ({
277286 ...lead(row),
278287 ready:
279288 ready_id === null || ready_day === null || ready_since === null
280289 ? null
281290 : { id: ready_id, day: ready_day, since: ready_since },
282291 next_at,
292 goes_at,
283293 showing:
284294 show_at === null || show_address === null || show_hold === null
285295 ? null
@@ -420,13 +430,14 @@ export function send(
420430 by: string,
421431 at: string,
422432 agent: Agent,
433 repliedAt = at,
423434 ): void {
424435 db.transaction(() => {
425436 db.query(
426 "UPDATE message SET body = ?1, signature = ?2, status = 'sent', sent_at = ?3, sent_by = ?4 WHERE id = ?5",
437 "UPDATE message SET body = ?1, signature = ?2, status = 'sent', sent_at = ?3, sent_by = ?4, goes_at = NULL WHERE id = ?5",
427438 ).run(body, signature(message.channel, agent), at, by, message.id);
428439 if (message.day === 0) {
429 startCadence(db, found, at, agent);
440 startCadence(db, found, at, agent, repliedAt);
430441 } else {
431442 db.query("UPDATE lead SET updated_at = ?1 WHERE id = ?2").run(
432443 at,
@@ -438,11 +449,99 @@ export function send(
438449 })();
439450 }
440451
441 /** The first answer is out at `at`: the clock stops and the follow-ups are drafted and scheduled from it. */
442 function startCadence(db: Database, found: Lead, at: string, agent: Agent): void {
452 /**
453 * The agent approved a text outside quiet hours: it is kept, signed when it
454 * goes, and goes at `goesAt`. The lead counts as answered now, at approval
455 * (the clock stops, the state is `contacted`), but the follow-ups start only
456 * when the text is out. Cancelling puts it all back (`release`).
457 */
458 export function hold(
459 db: Database,
460 found: Lead,
461 message: Message,
462 body: string,
463 by: string,
464 at: string,
465 goesAt: string,
466 ): void {
467 db.transaction(() => {
468 db.query(
469 "UPDATE message SET body = ?1, status = 'held', goes_at = ?2, approved_at = ?3, sent_by = ?4 WHERE id = ?5",
470 ).run(body, goesAt, at, by, message.id);
471 if (message.day === 0)
472 db.query(
473 "UPDATE lead SET replied_at = ?1, state = CASE state WHEN 'new' THEN 'contacted' ELSE state END, updated_at = ?1 WHERE id = ?2",
474 ).run(at, found.id);
475 else db.query("UPDATE lead SET updated_at = ?1 WHERE id = ?2").run(at, found.id);
476 })();
477 }
478
479 /** The held text of `lead`, if one is. */
480 export const heldFor = (db: Database, id: number): Message | null =>
481 db
482 .query<Message, [number]>("SELECT * FROM message WHERE lead_id = ?1 AND status = 'held' LIMIT 1")
483 .get(id);
484
485 /**
486 * A held text goes back to an unsent draft the agent can approve again: a
487 * draft for the first reply or an answer, due for a follow-up. A first reply
488 * un-answers the lead; they wait from when they asked.
489 */
490 export function release(db: Database, message: Message, at: string): void {
491 db.transaction(() => {
492 const first = message.day === 0;
493 db.query(
494 "UPDATE message SET status = ?1, goes_at = NULL, approved_at = NULL, sent_by = NULL WHERE id = ?2",
495 ).run(first || isAnswer(message.day) ? "draft" : "due", message.id);
496 if (first)
497 db.query(
498 "UPDATE lead SET replied_at = NULL, state = CASE state WHEN 'contacted' THEN 'new' ELSE state END, updated_at = ?1 WHERE id = ?2",
499 ).run(at, message.lead_id);
500 else db.query("UPDATE lead SET updated_at = ?1 WHERE id = ?2").run(at, message.lead_id);
501 })();
502 }
503
504 /**
505 * Held texts whose time has come go out as approved, signed as the agent is
506 * now. One whose lead has since stopped texts goes back as an email draft
507 * instead, never as a text; one that fell due after 9 p.m. (the clock was
508 * not turned) waits for the next 8:00. Returns the ids of the leads touched.
509 */
510 export function sendHeld(db: Database, at: string, agent: Agent): number[] {
511 const due = db
512 .query<Message, [string]>(
513 "SELECT * FROM message WHERE status = 'held' AND goes_at <= ?1 ORDER BY goes_at, id",
514 )
515 .all(at);
516 const touched: number[] = [];
517 for (const m of due) {
518 const found = findLead(db, m.lead_id)!;
519 if (channelFor(found) !== "text") {
520 release(db, m, at);
521 redraftFor(db, found, agent, false);
522 } else if (isQuiet(at, agent.timeZone)) {
523 db.query("UPDATE message SET goes_at = ?1 WHERE id = ?2").run(
524 nextOpening(at, agent.timeZone),
525 m.id,
526 );
527 continue;
528 } else send(db, found, m, m.body, m.sent_by ?? "", at, agent, m.approved_at ?? at);
529 touched.push(m.lead_id);
530 }
531 return touched.filter((id, i, all) => all.indexOf(id) === i);
532 }
533
534 /** The first answer is out at `at` (approved at `repliedAt`, when the clock stopped): the clock stops and the follow-ups are drafted and scheduled from it. */
535 function startCadence(
536 db: Database,
537 found: Lead,
538 at: string,
539 agent: Agent,
540 repliedAt = at,
541 ): void {
443542 db.query(
444 "UPDATE lead SET replied_at = ?1, state = CASE state WHEN 'new' THEN 'contacted' ELSE state END, updated_at = ?1 WHERE id = ?2",
445 ).run(at, found.id);
543 "UPDATE lead SET replied_at = ?1, state = CASE state WHEN 'new' THEN 'contacted' ELSE state END, updated_at = ?2 WHERE id = ?3",
544 ).run(repliedAt, at, found.id);
446545 const channel = channelFor(found);
447546 const open = !CLOSED.includes(found.state);
448547 for (const day of CADENCE)
@@ -631,13 +730,18 @@ export function updateContact(db: Database, found: Lead, to: Contact, at: string
631730 function redraftFor(db: Database, lead: Lead, agent: Agent, aside: boolean): void {
632731 const channel = channelFor(lead);
633732 const unsent = db
634 .query<{ id: number; day: number }, [number]>(
733 .query<Message, [number]>(
635734 aside
636 ? "SELECT id, day FROM message WHERE lead_id = ?1 AND status <> 'sent'"
637 : "SELECT id, day FROM message WHERE lead_id = ?1 AND status IN ('draft', 'scheduled', 'due')",
735 ? "SELECT * FROM message WHERE lead_id = ?1 AND status <> 'sent'"
736 : "SELECT * FROM message WHERE lead_id = ?1 AND status IN ('draft', 'scheduled', 'due', 'held')",
638737 )
639738 .all(lead.id);
640 for (const m of unsent)
739 for (const m of unsent) {
740 // A held text the lead can still be texted keeps the words the agent approved.
741 if (m.status === "held") {
742 if (channel === "text") continue;
743 release(db, m, m.approved_at ?? m.due_at);
744 }
641745 db.query(
642746 "UPDATE message SET channel = ?1, body = ?2, signature = ?3 WHERE id = ?4",
643747 ).run(
@@ -646,6 +750,7 @@ function redraftFor(db: Database, lead: Lead, agent: Agent, aside: boolean): voi
646750 signature(channel, agent),
647751 m.id,
648752 );
753 }
649754 }
650755
651756 /** Qualified or lost: the lead leaves the cadence, and nothing more is drafted to go. */
@@ -662,7 +767,7 @@ export function close(
662767 id,
663768 );
664769 db.query(
665 "UPDATE message SET status = 'skipped' WHERE lead_id = ?1 AND status IN ('draft', 'scheduled', 'due')",
770 "UPDATE message SET status = 'skipped', goes_at = NULL WHERE lead_id = ?1 AND status IN ('draft', 'scheduled', 'due', 'held')",
666771 ).run(id);
667772 })();
668773 }
@@ -710,7 +815,7 @@ export function advance(db: Database, at: string): number[] {
710815 WHERE status = 'scheduled' AND due_at <= ?1
711816 AND lead_id IN (SELECT id FROM lead WHERE state = 'contacted')
712817 AND lead_id NOT IN (SELECT lead_id FROM showing WHERE hold_until > ?1)
713 AND lead_id NOT IN (SELECT lead_id FROM message WHERE day >= ${ANSWER_DAY} AND status = 'draft')
818 AND lead_id NOT IN (SELECT lead_id FROM message WHERE day >= ${ANSWER_DAY} AND status IN ('draft', 'held'))
714819 RETURNING lead_id`,
715820 )
716821 .all(at)
src/mcp.ts +12 −3
@@ -18,6 +18,7 @@ import {
1818 editLead,
1919 optOutTexts,
2020 approveReply,
21 cancelHeld,
2122 setState,
2223 logCall,
2324 bookShowing,
@@ -120,7 +121,7 @@ export const tools: readonly Tool[] = [
120121 {
121122 name: "send_reply",
122123 description:
123 "Approve and send what is ready for a lead (the first reply or a due follow-up), as drafted or with body as edited. The answer says which lead is next (`next`: id and name, or null): the one that has waited longest among those that need the person now. Only call this when the person has approved the words.",
124 "Approve and send what is ready for a lead (the first reply or a due follow-up), as drafted or with body as edited. The answer says which lead is next (`next`: id and name, or null): the one that has waited longest among those that need the person now. A text approved outside 8:00 a.m. to 9:00 p.m. in the profile's time zone is held for the next 8:00 and the answer says `scheduledFor`; an email always goes now. Only call this when the person has approved the words.",
124125 inputSchema: {
125126 type: "object",
126127 properties: { id: { type: "integer" }, body: { type: "string" } },
@@ -222,6 +223,13 @@ export const tools: readonly Tool[] = [
222223 run: (db, who, args) =>
223224 editLead(db, who, { id: Number(args.id), name: args.name, email: args.email, phone: args.phone }),
224225 },
226 {
227 name: "cancel_held_text",
228 description:
229 "Take back a text held for quiet hours (send_reply answered `scheduledFor`): it returns to an unsent draft, to edit and approve again.",
230 inputSchema: ONE,
231 run: (db, who, args) => cancelHeld(db, who, { id: Number(args.id) }),
232 },
225233 {
226234 name: "opt_out_texts",
227235 description:
@@ -232,14 +240,14 @@ export const tools: readonly Tool[] = [
232240 {
233241 name: "get_profile",
234242 description:
235 "The agent whose desk this is: name, brokerage, license, phone and email, as every message is signed.",
243 "The agent whose desk this is: name, brokerage, license, phone, email and time zone, as every message is signed.",
236244 inputSchema: { type: "object", properties: {} },
237245 run: (db, who) => getProfile(db, who),
238246 },
239247 {
240248 name: "set_profile",
241249 description:
242 "Change the agent's name, brokerage, license, phone and email (admin only). Unsent drafts take it at once; sent messages keep theirs.",
250 "Change the agent's name, brokerage, license, phone, email and time zone (admin only). Unsent drafts take it at once; sent messages keep theirs.",
243251 inputSchema: {
244252 type: "object",
245253 properties: {
@@ -248,6 +256,7 @@ export const tools: readonly Tool[] = [
248256 license: { type: "string" },
249257 phone: { type: "string" },
250258 email: { type: "string" },
259 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." },
251260 },
252261 required: ["name", "brokerage", "license", "phone", "email"],
253262 },
src/pages/desk.ts +8 −5
@@ -8,6 +8,7 @@ import { layout } from "./layout.ts";
88 import { escape } from "../http.ts";
99 import { recordLine } from "../clock.ts";
1010 import { isAnswer } from "../drafts.ts";
11 import { goesLabel, RECORD_NOTE } from "../quiet.ts";
1112 import { showingWhen } from "../showings.ts";
1213 import type { DeskLead, ResponseRecord, View } from "../leads.ts";
1314 import type { Agent } from "../env.ts";
@@ -51,7 +52,7 @@ export function deskPage(input: {
5152 const answers = leads.filter((l) => l.ready !== null && isAnswer(l.ready.day)).length;
5253 const due = leads.filter((l) => l.ready !== null && l.ready.day > 0 && !isAnswer(l.ready.day)).length;
5354 const summary = `<p class="summary" aria-live="polite"><b>${waiting}</b> waiting for a first reply <span aria-hidden="true">·</span> <b>${due}</b> follow-up${due === 1 ? "" : "s"} due today${answers === 0 ? "" : ` <span aria-hidden="true">·</span> <b>${answers}</b> wrote back`}</p>`;
54 const record = input.record === undefined ? "" : `<p class="record">${escape(recordLine(input.record))}</p>`;
55 const record = input.record === undefined ? "" : `<p class="record">${escape(recordLine(input.record))}</p><p class="muted">${RECORD_NOTE}</p>`;
5556 const q = input.q ?? "";
5657 const views =
5758 counts === undefined
@@ -69,7 +70,7 @@ export function deskPage(input: {
6970 const list =
7071 leads.length === 0
7172 ? `<p class="empty">${q === "" ? EMPTY[show] : `No lead matches '${escape(q)}'${show === "all" ? "" : " in this view"}.`}</p>`
72 : `<ul class="desk">${leads.map((lead) => row(lead, now)).join("")}</ul>`;
73 : `<ul class="desk">${leads.map((lead) => row(lead, now, agent.timeZone)).join("")}</ul>`;
7374 return layout({
7475 who,
7576 agent,
@@ -151,9 +152,11 @@ const showingBadge = (lead: DeskLead, now: number): string =>
151152 ["Showing", showingWhen(lead.showing.at, now), ...(lead.showing.address === "" ? [] : [lead.showing.address])].join(" · "),
152153 )}</span>`;
153154
154 function status(lead: DeskLead): string {
155 function status(lead: DeskLead, now: number, zone: string): string {
155156 if (lead.state === "qualified" || lead.state === "lost")
156157 return `<span class="status" data-state="${lead.state}">${STATE_LABEL[lead.state]}</span>`;
158 if (lead.goes_at !== null)
159 return `<span class="status">${escape(goesLabel(lead.goes_at, now, zone))}</span>`;
157160 if (lead.ready?.day === 0)
158161 return `<span class="status" data-ready>Reply drafted — approve and send</span>`;
159162 if (lead.ready !== null && isAnswer(lead.ready.day))
@@ -165,13 +168,13 @@ function status(lead: DeskLead): string {
165168 return `<span class="status">Follow-ups done</span>`;
166169 }
167170
168 const row = (lead: DeskLead, now: number): string => `<li>
171 const row = (lead: DeskLead, now: number, zone: string): string => `<li>
169172 <a class="lead-row" href="/leads/${lead.id}"${lead.state === "lost" ? " data-closed" : ""}>
170173 <span class="lead-main">
171174 <span class="lead-name">${escape(lead.name)}</span>
172175 <span class="tags">${source(lead)}${consent(lead)}${showingBadge(lead, now)}</span>
173176 <span class="ask">${escape(lead.message)}</span>
174 ${status(lead)}
177 ${status(lead, now, zone)}
175178 </span>
176179 ${clock(lead, now, lead.ready !== null && isAnswer(lead.ready.day) ? lead.ready.since : null)}
177180 </a>
src/pages/lead.ts +25 −2
@@ -9,6 +9,7 @@ import { channelFor, isAnswer, MAX_BODY } from "../drafts.ts";
99 import { escape } from "../http.ts";
1010 import { MAX_ADDRESS, MAX_AHEAD_DAYS, showingLine, showingWhen } from "../showings.ts";
1111 import { elapsed, between } from "../clock.ts";
12 import { goesLabel, isQuiet, nextOpening } from "../quiet.ts";
1213 import { answerSince, MAX_INBOUND, type LeadDetail, type Message, type NextLead } from "../leads.ts";
1314 import type { Agent } from "../env.ts";
1415 import type { Who } from "../who.ts";
@@ -63,8 +64,24 @@ export function leadPage(input: {
6364 : [`<a href="tel:${escape(lead.phone.replace(/[^\d+]/g, ""))}">${escape(lead.phone)}</a>`]),
6465 ].join(" · ");
6566
67 const held = lead.messages.find((m) => m.status === "held");
68 const holdPane =
69 held === undefined || held.goes_at === null
70 ? ""
71 : `<div class="pane ours held">
72 <h2>${titleOf(held)} <span class="muted">· by ${CHANNEL[held.channel]}</span></h2>
73 <p class="hint" data-held>${escape(goesLabel(held.goes_at, now, agent.timeZone))}. Texts go out between 8:00 a.m. and 9:00 p.m. (${escape(agent.timeZone)}); you approved this one, and it waits.</p>
74 <div class="draft-view">${words({ body: held.body, signature: held.signature })}</div>
75 ${
76 mayUpdate
77 ? `<form method="post" action="${path}/unhold"><button class="button button-quiet">Cancel and keep as a draft</button></form>`
78 : ""
79 }
80 </div>`;
6681 const draft =
67 ready === undefined
82 ready === undefined && held !== undefined
83 ? holdPane
84 : ready === undefined
6885 ? `<div class="pane ours"><h2>Nothing to send right now</h2><p class="muted">${
6986 closed
7087 ? `Marked ${STATE_LABEL[lead.state].toLowerCase()}: out of the follow-up plan.`
@@ -91,6 +108,11 @@ export function leadPage(input: {
91108 </div>`
92109 : ""
93110 }
111 ${
112 ready.channel === "text" && isQuiet(now, agent.timeZone)
113 ? `<p class="hint">It is outside texting hours (8:00 a.m. to 9:00 p.m.): approving holds this text. ${escape(goesLabel(nextOpening(now, agent.timeZone), now, agent.timeZone))}.</p>`
114 : ""
115 }
94116 ${
95117 ready.channel === "email" && lead.email === ""
96118 ? `<p class="hint">No email address on file, and they have not agreed to be texted: this waits until you add an address or call them.</p>`
@@ -98,7 +120,7 @@ export function leadPage(input: {
98120 ? `<p class="hint">Email only: ${lead.consent ? "no phone number to text." : lead.opted_out_at !== null ? "they asked to stop texts." : "they have not given written consent to be texted."}</p>`
99121 : ""
100122 }
101 </div>`;
123 </div>${holdPane}`;
102124
103125 const history: HistoryEntry[] = [
104126 ...sent.map((m) => ({ at: m.sent_at ?? m.due_at, ours: m })),
@@ -297,6 +319,7 @@ const PLAN: Readonly<Record<Message["status"], string>> = {
297319 draft: "Drafted",
298320 scheduled: "Upcoming",
299321 due: "Ready to send",
322 held: "Held for 8:00 a.m.",
300323 sent: "Sent",
301324 skipped: "Skipped",
302325 };
src/pages/profile.ts +1
@@ -14,6 +14,7 @@ const FIELDS = [
1414 { name: "license", label: "License number", type: "text", max: 60, auto: "off" },
1515 { name: "phone", label: "Phone", type: "tel", max: 20, auto: "tel" },
1616 { name: "email", label: "Email", type: "email", max: 254, auto: "email" },
17 { name: "timeZone", label: "Time zone (texts wait for 8:00 a.m. there, e.g. America/Chicago)", type: "text", max: 60, auto: "off" },
1718 ] as const;
1819
1920 export function profilePage(input: {
src/profile.test.ts +2 −2
@@ -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 });
66 expect(currentAgent(db)).toEqual(sam);
65 expect(must(saveProfile(db, root, sam))).toEqual({ id: 1, ...sam, timeZone: agent.timeZone });
66 expect(currentAgent(db)).toEqual({ ...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");
src/profile.ts +9 −7
@@ -11,11 +11,13 @@ import { agent as fromEnvironment, type Agent } from "./env.ts";
1111 /** The saved profile, or the environment's until there is one. */
1212 export function currentAgent(db: Database): Agent {
1313 const saved = db
14 .query<Agent, []>(
15 "SELECT name, brokerage, license, phone, email FROM profile WHERE id = 1",
14 .query<Omit<Agent, "timeZone"> & { time_zone: string | null }, []>(
15 "SELECT name, brokerage, license, phone, email, time_zone FROM profile WHERE id = 1",
1616 )
1717 .get();
18 return saved ?? fromEnvironment;
18 if (saved === null) return fromEnvironment;
19 const { time_zone, ...rest } = saved;
20 return { ...rest, timeZone: time_zone ?? fromEnvironment.timeZone };
1921 }
2022
2123 /** Save `agent` as the profile, whoever it replaces. */
@@ -26,9 +28,9 @@ export function storeAgent(
2628 at: string,
2729 ): void {
2830 db.query(
29 `INSERT INTO profile (id, name, brokerage, license, phone, email, updated_at, updated_by)
30 VALUES (1, ?1, ?2, ?3, ?4, ?5, ?6, ?7)
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)
3133 ON CONFLICT (id) DO UPDATE SET name = ?1, brokerage = ?2, license = ?3,
32 phone = ?4, email = ?5, updated_at = ?6, updated_by = ?7`,
33 ).run(agent.name, agent.brokerage, agent.license, agent.phone, agent.email, at, by);
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);
3436 }
src/quiet.test.ts added +316
@@ -0,0 +1,316 @@
1 /**
2 * Quiet hours: a text approved outside 8:00 a.m. to 9:00 p.m. in the agent's
3 * time zone waits for the next 8:00 and goes with the tick; an email never
4 * waits; the agent can take a held text back; a lead who opts out before it
5 * goes is never texted. At every door.
6 */
7 import { afterAll, beforeAll, 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 {
12 addLead,
13 approveReply,
14 cancelHeld,
15 getLead,
16 listLeads,
17 optOutTexts,
18 saveProfile,
19 setState,
20 tick,
21 turn,
22 } from "./actions.ts";
23 import { openDb } from "./db.ts";
24 import { deskPage } from "./pages/desk.ts";
25 import { leadPage } from "./pages/lead.ts";
26 import { agent } from "./env.ts";
27 import { goesAt, goesLabel, isQuiet, isZone, nextOpening } from "./quiet.ts";
28 import { serve } from "./server.ts";
29 import { plain, terminal } from "./terminal.ts";
30 import { sign } from "./who.ts";
31 import type { Who } from "./who.ts";
32
33 // The suite turns quiet hours off for everyone else; these tests need them.
34 let was: string | undefined;
35 beforeAll(() => {
36 was = process.env.QUIET_HOURS;
37 delete process.env.QUIET_HOURS;
38 });
39 afterAll(() => {
40 if (was !== undefined) process.env.QUIET_HOURS = was;
41 });
42
43 const alice: Who = { role: "user", id: "u1", name: "alice" };
44 const root: Who = { role: "admin", id: "u0", name: "root" };
45 const ZONE = "America/Chicago";
46 // June: Chicago is on daylight time, five hours behind UTC.
47 const at = (hhmm: string, date = "2026-06-10") => new Date(`${date}T${hhmm}:00-05:00`);
48
49 const fresh = (zone = ZONE) => {
50 const db = openDb(mkdtempSync(join(tmpdir(), "app-quiet-")));
51 const saved = saveProfile(db, root, { ...agent, timeZone: zone });
52 if (!saved.ok) throw new Error(saved.message);
53 return db;
54 };
55 const value = <T>(r: { ok: boolean; value?: T; message?: string }): T => {
56 if (!r.ok) throw new Error(r.message);
57 return r.value as T;
58 };
59 const arrive = (db: ReturnType<typeof fresh>, consent = true, when = at("20:00")) =>
60 value(
61 addLead(
62 db,
63 alice,
64 {
65 name: "Dana Reyes",
66 email: "[email protected]",
67 phone: "(206) 555-0199",
68 source: "zillow",
69 message: "Can I see 12 Oak Street this week?",
70 consent,
71 },
72 when,
73 ),
74 ).id;
75
76 test("the window is 8:00 to 21:00 on the agent's wall clock", () => {
77 expect(isQuiet(at("07:59"), ZONE)).toBe(true);
78 expect(isQuiet(at("08:00"), ZONE)).toBe(false);
79 expect(isQuiet(at("20:59"), ZONE)).toBe(false);
80 expect(isQuiet(at("21:00"), ZONE)).toBe(true);
81 expect(isQuiet(at("22:30"), "UTC")).toBe(true); // 03:30 UTC, the same instant
82 expect(isQuiet("2026-06-10T12:00:00Z", "UTC")).toBe(false);
83 });
84
85 test("the next opening is the coming 8:00, today before it and tomorrow after it", () => {
86 expect(nextOpening(at("22:30"), ZONE)).toBe(at("08:00", "2026-06-11").toISOString());
87 expect(nextOpening(at("03:00"), ZONE)).toBe(at("08:00").toISOString());
88 expect(nextOpening(at("21:00"), ZONE)).toBe(at("08:00", "2026-06-11").toISOString());
89 });
90
91 test("the arithmetic holds across a daylight-saving change", () => {
92 // New York springs forward on 2026-03-08: 22:30 EST on the 7th, 8:00 EDT on the 8th.
93 const evening = new Date("2026-03-08T03:30:00Z");
94 expect(nextOpening(evening, "America/New_York")).toBe("2026-03-08T12:00:00.000Z");
95 // And falls back on 2026-11-01: 22:30 EDT on the 31st, 8:00 EST on the 1st.
96 expect(nextOpening(new Date("2026-11-01T02:30:00Z"), "America/New_York")).toBe("2026-11-01T13:00:00.000Z");
97 // 21:00 EST the night before a spring change still lands on 8:00 local.
98 expect(nextOpening(new Date("2026-03-08T02:00:00Z"), "America/New_York")).toBe("2026-03-08T12:00:00.000Z");
99 });
100
101 test("emails are never held; a text is held only in quiet hours", () => {
102 expect(goesAt("email", at("23:00"), ZONE)).toBeNull();
103 expect(goesAt("text", at("12:00"), ZONE)).toBeNull();
104 expect(goesAt("text", at("22:30"), ZONE)).toBe(at("08:00", "2026-06-11").toISOString());
105 });
106
107 test("zones are IANA names the runtime knows", () => {
108 expect(isZone("America/Chicago")).toBe(true);
109 expect(isZone("Mars/Olympus")).toBe(false);
110 expect(isZone("")).toBe(false);
111 expect(isZone(5)).toBe(false);
112 });
113
114 test("the label says today, tomorrow or the date", () => {
115 const goes = at("08:00", "2026-06-11").toISOString();
116 expect(goesLabel(goes, at("22:30"), ZONE)).toBe("Goes at 8:00 a.m. tomorrow");
117 expect(goesLabel(goes, at("05:00", "2026-06-11"), ZONE)).toBe("Goes at 8:00 a.m. today");
118 expect(goesLabel(goes, at("22:30", "2026-06-08"), ZONE)).toBe("Goes at 8:00 a.m. on Jun 11");
119 });
120
121 test("a text approved at 22:30 is held until 8:00 next day; the record counts the approval", () => {
122 const db = fresh();
123 const id = arrive(db);
124 const approved = value(approveReply(db, alice, { id }, at("22:30")));
125 expect(approved.scheduledFor).toBe(at("08:00", "2026-06-11").toISOString());
126 const first = approved.messages.find((m) => m.day === 0)!;
127 expect(first.status).toBe("held");
128 expect(first.sent_at).toBeNull();
129 expect(approved.replied_at).toBe(at("22:30").toISOString());
130 expect(approved.state).toBe("contacted");
131 expect(approved.messages.filter((m) => m.day > 0)).toHaveLength(0);
132 const desk = value(listLeads(db, alice)).leads[0]!;
133 expect(desk.goes_at).toBe(at("08:00", "2026-06-11").toISOString());
134 expect(desk.ready).toBeNull();
135 });
136
137 test("a text approved at 12:00 goes now", () => {
138 const db = fresh();
139 const id = arrive(db);
140 const approved = value(approveReply(db, alice, { id }, at("12:00")));
141 expect(approved.scheduledFor).toBeUndefined();
142 expect(approved.messages[0]!.status).toBe("sent");
143 });
144
145 test("an email at 23:00 goes now", () => {
146 const db = fresh();
147 const id = arrive(db, false);
148 const approved = value(approveReply(db, alice, { id }, at("23:00")));
149 expect(approved.scheduledFor).toBeUndefined();
150 expect(approved.messages[0]!.channel).toBe("email");
151 expect(approved.messages[0]!.status).toBe("sent");
152 });
153
154 test("the tick at 8:00 sends the held text and starts the follow-ups; before 8:00 it waits", () => {
155 const db = fresh();
156 const id = arrive(db);
157 value(approveReply(db, alice, { id }, at("22:30")));
158 turn(db, at("07:59", "2026-06-11"));
159 expect(value(getLead(db, alice, { id })).messages[0]!.status).toBe("held");
160 expect(value(tick(db, alice, at("08:00", "2026-06-11"))).leads).toEqual([id]);
161 const lead = value(getLead(db, alice, { id }));
162 expect(lead.messages[0]!.status).toBe("sent");
163 expect(lead.messages[0]!.sent_at).toBe(at("08:00", "2026-06-11").toISOString());
164 expect(lead.messages[0]!.sent_by).toBe("alice");
165 expect(lead.replied_at).toBe(at("22:30").toISOString());
166 expect(lead.messages.filter((m) => m.day > 0 && m.status === "scheduled")).toHaveLength(5);
167 });
168
169 test("a tick that comes late, after 21:00, waits for the next 8:00 instead", () => {
170 const db = fresh();
171 const id = arrive(db);
172 value(approveReply(db, alice, { id }, at("22:30")));
173 turn(db, at("22:00", "2026-06-11"));
174 const lead = value(getLead(db, alice, { id }));
175 expect(lead.messages[0]!.status).toBe("held");
176 expect(lead.messages[0]!.goes_at).toBe(at("08:00", "2026-06-12").toISOString());
177 });
178
179 test("cancelling returns a held text to an unsent draft, and the lead is unanswered again", () => {
180 const db = fresh();
181 const id = arrive(db);
182 value(approveReply(db, alice, { id }, at("22:30")));
183 const back = value(cancelHeld(db, alice, { id }, at("22:40")));
184 const first = back.messages[0]!;
185 expect(first.status).toBe("draft");
186 expect(first.goes_at).toBeNull();
187 expect(back.replied_at).toBeNull();
188 expect(back.state).toBe("new");
189 expect(value(listLeads(db, alice)).leads[0]!.ready?.day).toBe(0);
190 turn(db, at("09:00", "2026-06-11"));
191 expect(value(getLead(db, alice, { id })).messages[0]!.status).toBe("draft");
192 expect(cancelHeld(db, alice, { id })).toMatchObject({ ok: false, error: "invalid" });
193 });
194
195 test("a lead who opts out before 8:00 gets an email draft, never the text", () => {
196 const db = fresh();
197 const id = arrive(db);
198 value(approveReply(db, alice, { id }, at("22:30")));
199 value(optOutTexts(db, alice, { id }));
200 turn(db, at("08:00", "2026-06-11"));
201 const lead = value(getLead(db, alice, { id }));
202 expect(lead.messages.every((m) => m.status !== "sent")).toBe(true);
203 const first = lead.messages[0]!;
204 expect(first.channel).toBe("email");
205 expect(first.status).toBe("draft");
206 expect(lead.replied_at).toBeNull();
207 });
208
209 test("a held text of a lead since marked lost is set aside and never goes", () => {
210 const db = fresh();
211 const id = arrive(db);
212 value(approveReply(db, alice, { id }, at("22:30")));
213 value(setState(db, alice, { id, state: "lost" }));
214 turn(db, at("08:00", "2026-06-11"));
215 expect(value(getLead(db, alice, { id })).messages[0]!.status).toBe("skipped");
216 });
217
218 test("an invalid time zone on the profile is a 422 and nothing is saved", async () => {
219 const db = fresh();
220 const bad = saveProfile(db, root, { ...agent, timeZone: "Mars/Olympus" });
221 expect(bad).toMatchObject({ ok: false, error: "invalid" });
222 expect(value(listLeads(db, alice)).record).toBeDefined();
223 const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-quiet-srv-")), identityKey: "k", sample: false });
224 try {
225 const identity = `u0|root|admin|${Date.now() + 60_000}`;
226 const headers = { "x-forge-identity": identity, "x-forge-signature": sign(identity, "k"), "content-type": "application/json" };
227 const post = (body: unknown) =>
228 fetch(`http://${server.hostname}:${server.port}/profile`, { method: "POST", headers, body: JSON.stringify(body) });
229 expect((await post({ ...agent, timeZone: "Mars/Olympus" })).status).toBe(422);
230 expect((await post({ ...agent, timeZone: "Europe/London" })).status).toBe(200);
231 // Left out, it stays as it was.
232 const { timeZone: _, ...rest } = agent;
233 const kept = await post(rest);
234 expect(((await kept.json()) as { timeZone: string }).timeZone).toBe("Europe/London");
235 } finally {
236 server.stop(true);
237 }
238 });
239
240 test("the same hold at the JSON door, the MCP and the terminal", async () => {
241 const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-quiet-doors-")), identityKey: "k", sample: false });
242 try {
243 const identity = `u1|alice|user|${Date.now() + 60_000}`;
244 const headers = { "x-forge-identity": identity, "x-forge-signature": sign(identity, "k"), "content-type": "application/json", accept: "application/json" };
245 const admin = `u0|root|admin|${Date.now() + 60_000}`;
246 const adminHeaders = { ...headers, "x-forge-identity": admin, "x-forge-signature": sign(admin, "k") };
247 const url = `http://${server.hostname}:${server.port}`;
248 // The doors read the real clock, so choose a zone in which it is quiet right now.
249 const quietZone = Array.from({ length: 25 }, (_, i) => `Etc/GMT${i - 12 < 0 ? "" : "+"}${i - 12}`).find((z) =>
250 isQuiet(new Date(), z),
251 )!;
252 await fetch(`${url}/profile`, { method: "POST", headers: adminHeaders, body: JSON.stringify({ ...agent, timeZone: quietZone }) });
253 const made = async () =>
254 ((await (await fetch(`${url}/leads`, {
255 method: "POST",
256 headers,
257 body: JSON.stringify({ name: "Nina Park", email: "[email protected]", phone: "(206) 555-0177", source: "website", message: "Could we see 12 Cedar Ln?", consent: true }),
258 })).json()) as { id: number }).id;
259 const json = await made();
260 const answered = (await (await fetch(`${url}/leads/${json}/reply`, { method: "POST", headers, body: "{}" })).json()) as { scheduledFor?: string };
261 expect(answered.scheduledFor).toBeDefined();
262 const back = await fetch(`${url}/leads/${json}/unhold`, { method: "POST", headers, body: "{}" });
263 expect(back.status).toBe(200);
264 const spec = (await (await fetch(`${url}/openapi.json`, { headers })).json()) as { components?: unknown };
265 expect(JSON.stringify(spec)).toContain("scheduledFor");
266
267 const viaMcp = await made();
268 const call = (name: string, args: unknown) =>
269 fetch(`${url}/mcp`, { method: "POST", headers, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } }) }).then((r) => r.json() as Promise<any>);
270 const sent = await call("send_reply", { id: viaMcp });
271 expect(JSON.parse(sent.result.content[0].text).scheduledFor).toBeDefined();
272 const taken = await call("cancel_held_text", { id: viaMcp });
273 expect(JSON.parse(taken.result.content[0].text).messages[0].status).toBe("draft");
274 } finally {
275 server.stop(true);
276 }
277 });
278
279 test("the terminal says when a held text goes and lets the agent take it back", () => {
280 const db = fresh();
281 const id = arrive(db);
282 const clock = at("22:30").getTime();
283 const t = terminal(db, alice, () => clock);
284 const screen = () => t.screen(100).map(plain).join("\n");
285 expect(screen()).toContain("No replies yet");
286 expect(screen()).toContain("counts as answered when you approve it");
287 value(approveReply(db, alice, { id }, new Date(clock)));
288 expect(screen()).toContain("Goes at 8:00 a.m. tomorrow");
289 t.key("\r");
290 expect(screen()).toContain("Goes at 8:00 a.m. tomorrow");
291 t.key("h");
292 expect(value(getLead(db, alice, { id })).messages[0]!.status).toBe("draft");
293 });
294
295 test("the lead's page and the desk say when a held text goes, and offer to take it back", () => {
296 const db = fresh();
297 const id = arrive(db);
298 const now = at("22:30");
299 value(approveReply(db, alice, { id }, now));
300 const profile = { ...agent, timeZone: ZONE };
301 const page = leadPage({ who: alice, agent: profile, lead: value(getLead(db, alice, { id })), mayUpdate: true, next: null, now: now.getTime() });
302 expect(page).toContain("Goes at 8:00 a.m. tomorrow");
303 expect(page).toContain(`action="/leads/${id}/unhold"`);
304 const listed = value(listLeads(db, alice));
305 const desk = deskPage({ who: alice, agent: profile, leads: listed.leads, record: listed.record, mayAdd: false, mayReset: false });
306 expect(desk).toContain("counts as answered when you approve it");
307 expect(desk).toMatch(/Goes at 8:00 a\.m\. (today|tomorrow|on )/);
308 });
309
310 test("an unsent text opened in quiet hours says approving will hold it", () => {
311 const db = fresh();
312 const id = arrive(db);
313 const now = at("22:30");
314 const page = leadPage({ who: alice, agent: { ...agent, timeZone: ZONE }, lead: value(getLead(db, alice, { id })), mayUpdate: true, next: null, now: now.getTime() });
315 expect(page).toContain("approving holds this text");
316 });
src/quiet.ts added +104
@@ -0,0 +1,104 @@
1 /**
2 * Quiet hours: when a text may go. Texts leave between 8:00 a.m. and 9:00
3 * p.m. in the agent's time zone, the window realtors are told to keep; an
4 * email goes any time. Pure functions of an instant and a zone name — no
5 * database, no clock of their own.
6 */
7
8 export const OPENS = 8;
9 export const CLOSES = 21;
10
11 /** Whether `zone` is an IANA time zone name the runtime knows. */
12 export function isZone(zone: unknown): zone is string {
13 if (typeof zone !== "string" || zone === "" || zone.length > 60) return false;
14 try {
15 new Intl.DateTimeFormat("en-US", { timeZone: zone });
16 return true;
17 } catch {
18 return false;
19 }
20 }
21
22 interface Wall {
23 readonly y: number;
24 readonly m: number;
25 readonly d: number;
26 readonly h: number;
27 }
28
29 /** The clock on the wall in `zone` at the instant `ms`. */
30 function wall(ms: number, zone: string): Wall {
31 const parts = new Intl.DateTimeFormat("en-US", {
32 timeZone: zone,
33 year: "numeric",
34 month: "numeric",
35 day: "numeric",
36 hour: "numeric",
37 hourCycle: "h23",
38 }).formatToParts(ms);
39 const n = (type: string): number =>
40 Number(parts.find((p) => p.type === type)?.value);
41 return { y: n("year"), m: n("month"), d: n("day"), h: n("hour") };
42 }
43
44 /** The instant at which the wall in `zone` reads `h`:00 on that date (months from 1; days may overflow). */
45 function instant(y: number, m: number, d: number, h: number, zone: string): number {
46 const asUtc = Date.UTC(y, m - 1, d, h);
47 // The zone's offset at the answer, found by closing in from the guess: two
48 // passes settle it on either side of a daylight-saving change.
49 let guess = asUtc;
50 for (let i = 0; i < 2; i++) {
51 const w = wall(guess, zone);
52 guess += asUtc - Date.UTC(w.y, w.m - 1, w.d, w.h);
53 }
54 return guess;
55 }
56
57 /**
58 * Whether a text sent at `at` would land in quiet hours in `zone`. The one
59 * switch is the operator's: `QUIET_HOURS=off` lets texts go at any hour (the
60 * test suite sets it, so its fixed and real clocks do not matter).
61 */
62 export const isQuiet = (at: Date | string | number, zone: string): boolean => {
63 if (process.env.QUIET_HOURS === "off") return false;
64 const h = wall(new Date(at).getTime(), zone).h;
65 return h < OPENS || h >= CLOSES;
66 };
67
68 /** The next 8:00 a.m. in `zone` strictly after `at`, as an ISO stamp. */
69 export function nextOpening(at: Date | string | number, zone: string): string {
70 const ms = new Date(at).getTime();
71 const w = wall(ms, zone);
72 const today = instant(w.y, w.m, w.d, OPENS, zone);
73 const opens = today > ms ? today : instant(w.y, w.m, w.d + 1, OPENS, zone);
74 return new Date(opens).toISOString();
75 }
76
77 /**
78 * When a text approved at `at` goes: null when it may go now, else the next
79 * 8:00 a.m. Emails never wait.
80 */
81 export const goesAt = (
82 channel: "text" | "email",
83 at: Date | string | number,
84 zone: string,
85 ): string | null =>
86 channel === "text" && isQuiet(at, zone) ? nextOpening(at, zone) : null;
87
88 const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
89
90 /** "Goes at 8:00 a.m. tomorrow", or on its date when it is further off. */
91 export function goesLabel(goes: string, now: Date | string | number, zone: string): string {
92 const then = wall(Date.parse(goes), zone);
93 const here = wall(new Date(now).getTime(), zone);
94 const days =
95 (Date.UTC(then.y, then.m - 1, then.d) - Date.UTC(here.y, here.m - 1, here.d)) / 86_400_000;
96 const time = `${then.h % 12 === 0 ? 12 : then.h % 12}:00 ${then.h < 12 ? "a.m." : "p.m."}`;
97 const when =
98 days <= 0 ? "today" : days === 1 ? "tomorrow" : `on ${MONTHS[then.m - 1]} ${then.d}`;
99 return `Goes at ${time} ${when}`;
100 }
101
102 /** The sentence under the response record: what counts as the reply. */
103 export const RECORD_NOTE =
104 "A text held for quiet hours counts as answered when you approve it, not when it goes.";
src/routes.ts +37 −5
@@ -29,6 +29,7 @@ import {
2929 saveProfile,
3030 optOutTexts,
3131 approveReply,
32 cancelHeld,
3233 nextLead,
3334 setState,
3435 logCall,
@@ -117,10 +118,15 @@ export const MESSAGE: Schema = {
117118 channel: { enum: ["text", "email"] },
118119 body: { type: "string", minLength: 1, maxLength: MAX_BODY.email },
119120 signature: { type: "string" },
120 status: { enum: ["draft", "scheduled", "due", "sent", "skipped"] },
121 status: {
122 enum: ["draft", "scheduled", "due", "held", "sent", "skipped"],
123 description: "held: a text you approved outside 8:00 a.m. to 9:00 p.m. in your time zone; it goes at goes_at.",
124 },
121125 due_at: STAMP,
122126 sent_at: { type: ["string", "null"], format: "date-time" },
123127 sent_by: { type: ["string", "null"] },
128 goes_at: { type: ["string", "null"], format: "date-time", description: "For a held text, when it goes." },
129 approved_at: { type: ["string", "null"], format: "date-time", description: "For a held text, when you approved it: the moment that counts as the reply." },
124130 },
125131 required: ["id", "lead_id", "day", "channel", "body", "signature", "status", "due_at"],
126132 };
@@ -210,6 +216,11 @@ export const APPROVED: Schema = {
210216 properties: { id: { type: "integer" }, name: { type: "string" } },
211217 required: ["id", "name"],
212218 },
219 scheduledFor: {
220 ...STAMP,
221 description:
222 "Present only when the text was held for quiet hours: when it will go (the next 8:00 a.m. in your time zone). Absent when it went now.",
223 },
213224 },
214225 required: [...(LEAD.required ?? []), "next"],
215226 };
@@ -227,6 +238,7 @@ export const DESK_LEAD: Schema = {
227238 },
228239 },
229240 next_at: { type: ["string", "null"], format: "date-time" },
241 goes_at: { type: ["string", "null"], format: "date-time", description: "When a text you approved goes, if one is held for quiet hours." },
230242 showing: {
231243 type: ["object", "null"],
232244 description: "The showing booked on this lead, if one is.",
@@ -237,7 +249,7 @@ export const DESK_LEAD: Schema = {
237249 },
238250 },
239251 },
240 required: [...LEAD_REQUIRED, "ready", "next_at", "showing"],
252 required: [...LEAD_REQUIRED, "ready", "next_at", "goes_at", "showing"],
241253 };
242254 const SHOW: Schema = {
243255 enum: [...VIEWS],
@@ -327,6 +339,11 @@ const PROFILE_FIELDS = {
327339 },
328340 phone: { type: "string", description: "7 to 20 digits." },
329341 email: { type: "string", format: "email" },
342 timeZone: {
343 type: "string",
344 maxLength: 60,
345 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.",
346 },
330347 } as const;
331348 export const PROFILE: Schema = {
332349 type: "object",
@@ -626,7 +643,7 @@ export const routes: readonly Route[] = [
626643 ),
627644 api: {
628645 summary:
629 "Approve and send what is ready for this lead — the first reply, or the follow-up that is due — as drafted, or with `body` as edited. The first reply starts the follow-up plan.",
646 "Approve and send what is ready for this lead — the first reply, or the follow-up that is due — as drafted, or with `body` as edited. The first reply starts the follow-up plan. A text approved outside 8:00 a.m. to 9:00 p.m. in the profile's time zone is held for the next 8:00 and the answer says `scheduledFor`; an email always goes now.",
630647 body: {
631648 type: "object",
632649 properties: {
@@ -795,6 +812,21 @@ export const routes: readonly Route[] = [
795812 answer: LEAD,
796813 },
797814 },
815 {
816 method: "POST",
817 path: "/leads/:id/unhold",
818 handle: (c) =>
819 posted(
820 c,
821 () => cancelHeld(c.db, c.who, { id: ID(c) }),
822 () => ({ to: `/leads/${ID(c)}`, said: "Taken back. It is a draft again." }),
823 ),
824 api: {
825 summary:
826 "Take back a text held for quiet hours: it returns to an unsent draft you can edit and approve again. No body needed.",
827 answer: LEAD,
828 },
829 },
798830 {
799831 method: "POST",
800832 path: "/leads/:id/opt-out",
@@ -816,7 +848,7 @@ export const routes: readonly Route[] = [
816848 handle: (c) => answer(tick(c.db, c.who)),
817849 api: {
818850 summary:
819 "The day turns: every follow-up whose day has come is ready to approve. Safe to call as often as you like; the app also does it hourly.",
851 "The day turns: every follow-up whose day has come is ready to approve, and every text held for quiet hours whose 8:00 a.m. has come goes out. Safe to call as often as you like; the app also does it every five minutes.",
820852 answer: {
821853 type: "object",
822854 properties: { leads: list({ type: "integer" }) },
@@ -902,7 +934,7 @@ export const routes: readonly Route[] = [
902934 body: {
903935 type: "object",
904936 properties: PROFILE_FIELDS,
905 required: Object.keys(PROFILE_FIELDS),
937 required: Object.keys(PROFILE_FIELDS).filter((f) => f !== "timeZone"),
906938 },
907939 answer: PROFILE,
908940 },
src/sentences.ts +10
@@ -42,6 +42,16 @@ export function deed(
4242 tried: `send ${kind} to ${lead}`,
4343 };
4444 }
45 if (row.act === "held")
46 return {
47 done: `approved a text to ${lead}, held until 8:00 a.m.`,
48 tried: `approve a text to ${lead}`,
49 };
50 if (row.act === "unhold")
51 return {
52 done: `took back the held text to ${lead}`,
53 tried: `take back the held text to ${lead}`,
54 };
4555 if (row.act === "qualified" || row.act === "lost")
4656 return {
4757 done: `marked ${lead} ${row.act}`,
src/server.test.ts +6 −4
@@ -294,6 +294,7 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
294294 "cancel_showing",
295295 "mark_lead",
296296 "edit_lead",
297 "cancel_held_text",
297298 "opt_out_texts",
298299 "get_profile",
299300 "set_profile",
@@ -317,7 +318,7 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
317318 expect(userSet.result.content[0].text).toContain("forbidden");
318319 expect((await call("set_profile", { ...mine, license: "" }, root)).result.isError).toBe(true);
319320 expect((await call("set_profile", mine, root)).result.isError).toBeUndefined();
320 expect(JSON.parse((await call("get_profile", {}, bob)).result.content[0].text)).toEqual({ id: 1, ...mine });
321 expect(JSON.parse((await call("get_profile", {}, bob)).result.content[0].text)).toEqual({ id: 1, ...mine, timeZone: "America/New_York" });
321322 // The desk over MCP carries the response record beside the leads.
322323 const deskText = (await call("list_leads", {}, bob)).result.content[0].text;
323324 const mcpDesk = JSON.parse(deskText) as { record: { days: number; leads: number }; leads: unknown[] };
@@ -343,7 +344,8 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
343344 });
344345
345346 test("a change is on the event stream, and a late client hears what it missed", async () => {
346 const stream = await fetch(base + "/events");
347 // Start past every event any earlier test emitted: only live ones follow.
348 const stream = await fetch(base + "/events?since=999999999");
347349 expect(stream.headers.get("content-type")).toBe("text/event-stream");
348350 const reader = stream.body!.getReader();
349351 const next = async (): Promise<{ id: string; type: string }> => {
@@ -528,7 +530,7 @@ test("what the web expects: robots.txt, and security.txt from the forge that run
528530
529531 test("the profile is a page and a JSON twin: everyone in reads, only an admin saves", async () => {
530532 const seen = await (await api("/profile", { headers: asJson }, alice)).json();
531 expect(Object.keys(seen as object).sort()).toEqual(["brokerage", "email", "id", "license", "name", "phone"]);
533 expect(Object.keys(seen as object).sort()).toEqual(["brokerage", "email", "id", "license", "name", "phone", "timeZone"]);
532534 const page = await (await api("/profile", {}, alice)).text();
533535 expect(page).toContain("Your profile");
534536 expect(page).not.toContain('action="/profile"');
@@ -541,7 +543,7 @@ test("the profile is a page and a JSON twin: everyone in reads, only an admin sa
541543 expect(blank.status).toBe(422);
542544 const saved = await api("/profile", { method: "POST", ...jsonBody(sam) }, root);
543545 expect(saved.status).toBe(200);
544 expect(await (await api("/profile", { headers: asJson }, bob)).json()).toEqual({ id: 1, ...sam });
546 expect(await (await api("/profile", { headers: asJson }, bob)).json()).toEqual({ id: 1, ...sam, timeZone: "America/New_York" });
545547 const form_ = await api("/profile", {}, root);
546548 expect(await form_.text()).toContain('action="/profile"');
547549 const home = await (await api("/", {}, bob)).text();
src/server.ts +1 −1
@@ -27,7 +27,7 @@ export interface ServeOptions {
2727 }
2828
2929 /** How often the server turns the cadence on its own, whether or not anyone calls `POST /tick`. */
30 const TURN_MS = 60 * 60_000;
30 const TURN_MS = 5 * 60_000;
3131
3232 export function serve(options: ServeOptions) {
3333 const db = openDb(options.dataDir);
src/terminal.test.ts +3 −1
@@ -243,7 +243,9 @@ test("an admin edits the profile one field at a time; it is saved, audited and r
243243 next(agent.license, "WA 99887");
244244 next(agent.phone, "(555) 010-0000");
245245 next(agent.email, "[email protected]");
246 next(agent.timeZone, "America/Chicago");
246247 expect(read(t)).toContain("Saved.");
248 expect(db.query<{ time_zone: string }, []>("SELECT time_zone FROM profile").get()?.time_zone).toBe("America/Chicago");
247249 expect(read(t)).toContain("WA 99887");
248250 const saved = db.query<{ license: string }, []>("SELECT license FROM profile").get();
249251 expect(saved?.license).toBe("WA 99887");
@@ -264,7 +266,7 @@ test("a blank license typed in the terminal is refused and nothing is saved", ()
264266 for (const current of [agent.name, agent.brokerage]) t.key("\r"), void current;
265267 clear(t, agent.license);
266268 t.key("\r");
267 for (let i = 0; i < 2; i++) t.key("\r");
269 for (let i = 0; i < 3; i++) t.key("\r");
268270 expect(read(t)).toContain("license number is required");
269271 expect(db.query("SELECT * FROM profile").all()).toHaveLength(0);
270272 });
src/terminal.ts +27 −4
@@ -36,6 +36,7 @@ import {
3636 resetSample,
3737 saveProfile,
3838 approveReply,
39 cancelHeld,
3940 logCall,
4041 bookShowing,
4142 cancelShowing,
@@ -47,6 +48,7 @@ import { showingLine, showingWhen } from "./showings.ts";
4748 import { answers, callLine, OUTCOME_LABEL, OUTCOMES, type Outcome } from "./calls.ts";
4849 import { between, elapsed, recordLine, tone } from "./clock.ts";
4950 import { permit } from "./contract.ts";
51 import { goesLabel, isQuiet, nextOpening, RECORD_NOTE } from "./quiet.ts";
5052 import { said as saidOf } from "./sentences.ts";
5153 import { SOURCE_LABEL, SOURCES, channelFor, isAnswer, type Channel } from "./drafts.ts";
5254 import { ssh, title, where } from "./env.ts";
@@ -111,6 +113,7 @@ const PROFILE_FIELDS = [
111113 { key: "license", label: "License number (required: every message shows it)" },
112114 { key: "phone", label: "Phone" },
113115 { key: "email", label: "Email" },
116 { key: "timeZone", label: "Time zone (e.g. America/Chicago: texts go 8:00 a.m. to 9:00 p.m. there)" },
114117 ] as const;
115118
116119 type View =
@@ -222,8 +225,10 @@ export function terminal(
222225 const rows = listed.value.leads;
223226 cursor = Math.min(cursor, Math.max(0, rows.length - 1));
224227 const counts = listed.value.counts;
228 const zone = currentAgent(db).timeZone;
225229 const lines: string[] = [
226230 dim(recordLine(listed.value.record)),
231 dim(RECORD_NOTE),
227232 VIEWS.map((v) => {
228233 const tab = `${VIEW_LABEL[v]} ${counts[v]}`;
229234 return v === show ? bold(`[${tab}]`) : dim(tab);
@@ -235,7 +240,9 @@ export function terminal(
235240 lines.push(dim(q === "" ? EMPTY[show] : `No lead matches '${clean(q)}'.`));
236241 rows.forEach((l, i) => {
237242 const next =
238 l.ready === null
243 l.goes_at !== null
244 ? dim(goesLabel(l.goes_at, now(), zone))
245 : l.ready === null
239246 ? dim(l.state === "qualified" || l.state === "lost" ? l.state : "")
240247 : l.ready.day === 0
241248 ? "reply drafted"
@@ -284,6 +291,7 @@ export function terminal(
284291 return deskScreen();
285292 }
286293 const r = ready(l);
294 const zone = currentAgent(db).timeZone;
287295 const channel = channelFor(l);
288296 const lines = [
289297 `${bold(clean(l.name))} ${SOURCE_LABEL[l.source]} · ${channel === "text" ? "Text OK" : "Email only"} · ${l.state} ${clockOf(l)}`,
@@ -298,6 +306,14 @@ export function terminal(
298306 "",
299307 ]),
300308 ];
309 const held = l.messages.find((m) => m.status === "held");
310 if (held !== undefined && held.goes_at !== null)
311 lines.push(
312 bold(`${titleOf(held)} — by ${held.channel}, approved`),
313 dim(` ${goesLabel(held.goes_at, now(), zone)} (texts go 8:00 a.m. to 9:00 p.m., ${zone})`),
314 ...wrap(held.body, width).map((s) => ` ${s}`),
315 "",
316 );
301317 if (r === undefined) {
302318 const next = l.messages.find((m) => m.status === "scheduled");
303319 lines.push(
@@ -315,6 +331,8 @@ export function terminal(
315331 `${titleOf(r)} — by ${r.channel}${editing === undefined ? ", as it will go" : ", editing"}`,
316332 ),
317333 );
334 if (r.channel === "text" && isQuiet(now(), zone))
335 lines.push(dim(` Outside texting hours: approving holds it. ${goesLabel(nextOpening(now(), zone), now(), zone)}.`));
318336 if (r.channel === "email")
319337 lines.push(
320338 dim(
@@ -355,6 +373,7 @@ export function terminal(
355373 : dim(
356374 [
357375 ...(r === undefined ? [] : ["s approve and send", "e edit"]),
376 ...(held === undefined ? [] : ["h take back the held text"]),
358377 ...(l.phone === "" ? [] : ["c log a call"]),
359378 ...(l.replied_at !== null && !CLOSED.includes(l.state) ? ["w they wrote back"] : []),
360379 ...(CLOSED.includes(l.state) ? [] : [l.showing === null ? "b book a showing" : "b move the showing"]),
@@ -454,9 +473,10 @@ export function terminal(
454473 }
455474
456475 function send(id: number, body?: string): void {
457 const sent = approveReply(db, me, { id, body });
476 const zone = currentAgent(db).timeZone;
477 const sent = approveReply(db, me, { id, body }, new Date(now()));
458478 said = sent.ok
459 ? `Sent to ${sent.value.name}.${sent.value.next === null ? " Nothing else needs you right now." : ` Next: ${sent.value.next.name} (])`}`
479 ? `${sent.value.scheduledFor === undefined ? "Sent to" : `Held for quiet hours; ${goesLabel(sent.value.scheduledFor, now(), zone).toLowerCase()}:`} ${sent.value.name}.${sent.value.next === null ? " Nothing else needs you right now." : ` Next: ${sent.value.next.name} (])`}`
460480 : sent.message;
461481 view = { name: "lead", id };
462482 }
@@ -664,7 +684,10 @@ export function terminal(
664684 if (next === null) said = "Nothing else needs you right now.";
665685 else view = { name: "lead", id: next.id };
666686 }
667 else if (input === "e") {
687 else if (input === "h" && l.messages.some((m) => m.status === "held")) {
688 const back = cancelHeld(db, me, { id });
689 said = back.ok ? "Taken back. It is a draft again." : back.message;
690 } else if (input === "e") {
668691 const r = ready(l);
669692 if (r === undefined) said = "Nothing is waiting to go to this lead right now.";
670693 else view = { name: "edit", id, text: r.body };
src/test-setup.ts added +6
@@ -0,0 +1,6 @@
1 /**
2 * Runs before every test file. Most tests approve texts at whatever hour the
3 * machine's clock (or their fixed stamp) says, so quiet hours are off for
4 * them; the tests about quiet hours turn them back on (`quiet.test.ts`).
5 */
6 process.env.QUIET_HOURS = "off";

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs