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

Skip one upcoming follow-up on a lead, or bring it back, from the lead's page #54

Merged opened this

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

Merged

mason/speed-to-lead:mason/47-skip-one-upcoming-follow-up-on-a-lead-or → main 5 commits fork

  • Merged. mason/47-skip-one-upcoming-follow-up-on-a-lead-or was merged into main as 6e5036e.

Review

Sign in to review this change.
16 files changed +602 −10
README.md +13
@@ -285,6 +285,19 @@ texts go at any hour (the test suite sets it). The 8:00 delivery is done by
285285 the clock, not by a person, so it is not audited: Activity shows the text as
286286 `held` (and the cancel), but never the send itself.
287287
288 **Skip one follow-up.** Each *Upcoming* (or ready) follow-up in a lead's plan
289 has **Skip this one**: it leaves the desk and never sends, and the rest of the
290 plan is untouched. It shows as *Skipped* with **Bring it back**, which returns
291 it to Upcoming at its original day, or to ready if that day has passed (a
292 showing's hold still applies). Only the lead's own day-1-or-later follow-ups
293 that are scheduled or ready can be skipped; the first reply, answers, and sent
294 or held messages are refused with 409. Closing and reopening a lead leaves a
295 follow-up you skipped skipped. Scripts use
296 `POST /leads/:id/messages/:mid/skip` and `.../restore`; MCP has
297 `skip_follow_up` and `restore_follow_up`. In the terminal, on the lead, `k`
298 skips the next follow-up in the plan (it says which day) and `K` brings back the
299 first one you skipped. Activity shows both.
300
288301 **Sample leads.** The app starts with twelve sample leads so you can see it
289302 work: two just in, two waiting a while, three gone red, and five already
290303 answered and partway through their follow-ups. An admin can restart them
contract/openapi.json +92
@@ -1139,6 +1139,98 @@
11391139 }
11401140 }
11411141 },
1142 "/leads/{id}/messages/{mid}/skip": {
1143 "post": {
1144 "summary": "Skip one upcoming follow-up (a scheduled or due message of day 1 or later on this lead): it leaves the desk, never sends, and closing then reopening the lead does not bring it back. The first reply, an answer, and sent or held messages are 409 with the reason; another lead's message is 404. No body needed.",
1145 "operationId": "postLeadsIdMessagesMidSkip",
1146 "parameters": [
1147 {
1148 "name": "id",
1149 "in": "path",
1150 "required": true,
1151 "schema": {
1152 "type": "integer"
1153 }
1154 },
1155 {
1156 "name": "mid",
1157 "in": "path",
1158 "required": true,
1159 "schema": {
1160 "type": "integer"
1161 }
1162 }
1163 ],
1164 "responses": {
1165 "200": {
1166 "description": "Skip one upcoming follow-up (a scheduled or due message of day 1 or later on this lead): it leaves the desk, never sends, and closing then reopening the lead does not bring it back. The first reply, an answer, and sent or held messages are 409 with the reason; another lead's message is 404. No body needed.",
1167 "content": {
1168 "application/json": {
1169 "schema": {
1170 "$ref": "#/components/schemas/Lead"
1171 }
1172 }
1173 }
1174 },
1175 "default": {
1176 "description": "{ error, message }: why not",
1177 "content": {
1178 "application/json": {
1179 "schema": {
1180 "$ref": "#/components/schemas/Error"
1181 }
1182 }
1183 }
1184 }
1185 }
1186 }
1187 },
1188 "/leads/{id}/messages/{mid}/restore": {
1189 "post": {
1190 "summary": "Bring back a follow-up you skipped: it is upcoming at its original day, or due on the desk if that day has passed (a showing's hold and quiet hours still apply). Only a follow-up skipped by hand can be; 409 otherwise. No body needed.",
1191 "operationId": "postLeadsIdMessagesMidRestore",
1192 "parameters": [
1193 {
1194 "name": "id",
1195 "in": "path",
1196 "required": true,
1197 "schema": {
1198 "type": "integer"
1199 }
1200 },
1201 {
1202 "name": "mid",
1203 "in": "path",
1204 "required": true,
1205 "schema": {
1206 "type": "integer"
1207 }
1208 }
1209 ],
1210 "responses": {
1211 "200": {
1212 "description": "Bring back a follow-up you skipped: it is upcoming at its original day, or due on the desk if that day has passed (a showing's hold and quiet hours still apply). Only a follow-up skipped by hand can be; 409 otherwise. No body needed.",
1213 "content": {
1214 "application/json": {
1215 "schema": {
1216 "$ref": "#/components/schemas/Lead"
1217 }
1218 }
1219 }
1220 },
1221 "default": {
1222 "description": "{ error, message }: why not",
1223 "content": {
1224 "application/json": {
1225 "schema": {
1226 "$ref": "#/components/schemas/Error"
1227 }
1228 }
1229 }
1230 }
1231 }
1232 }
1233 },
11421234 "/leads/{id}/note": {
11431235 "post": {
11441236 "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.",
src/actions.ts +69 −1
@@ -34,6 +34,10 @@ import {
3434 inView,
3535 queryOf,
3636 reopen,
37 messageOf,
38 restoreMessage,
39 skipMessage,
40 whyNotSkip,
3741 heldFor,
3842 hold,
3943 release,
@@ -74,7 +78,7 @@ import { MAX_EMAIL_TEXT, readLeadEmail } from "./intake.ts";
7478 import { MAX_ADDRESS, timeOf } from "./showings.ts";
7579 import type { Who } from "./who.ts";
7680
77 export type Failure = "signin_required" | "forbidden" | "not_found" | "invalid";
81 export type Failure = "signin_required" | "forbidden" | "not_found" | "invalid" | "conflict";
7882 export type Result<T> =
7983 | { ok: true; value: T }
8084 | { ok: false; error: Failure; message: string };
@@ -758,6 +762,70 @@ function cancelled(
758762 return ok(detail(db, found.value.id)!);
759763 }
760764
765 /**
766 * Set one upcoming follow-up aside: it never reaches the desk and never goes.
767 * Only this lead's own scheduled or due follow-ups (day 1 or later) can be;
768 * anything else is a conflict, with the reason in a sentence.
769 */
770 export const skipFollowUp = (
771 db: Database,
772 who: Who,
773 input: { id: number; messageId: number },
774 at?: Date,
775 ): Result<LeadDetail> =>
776 audited(db, who, "lead", "update", input.id, skipping(db, who, input, at), "skipped");
777
778 function skipping(
779 db: Database,
780 who: Who,
781 input: { id: number; messageId: number },
782 at?: Date,
783 ): Result<LeadDetail> {
784 const found = leadFor(db, who, "update", input.id, {
785 signIn: "Sign in to skip a follow-up.",
786 no: "You may not skip a follow-up for this lead.",
787 });
788 if (!found.ok) return found;
789 const message = Number.isInteger(input.messageId) ? messageOf(db, found.value.id, input.messageId) : null;
790 if (message === null) return fail("not_found", "No such follow-up on this lead.");
791 const why = whyNotSkip(message);
792 if (why !== null) return fail("conflict", why);
793 skipMessage(db, message, stamp(at));
794 emit("lead.changed", { id: found.value.id });
795 return ok(detail(db, found.value.id)!);
796 }
797
798 /** Bring back a follow-up the agent skipped: upcoming at its day, or due if that has passed. */
799 export const restoreFollowUp = (
800 db: Database,
801 who: Who,
802 input: { id: number; messageId: number },
803 at?: Date,
804 ): Result<LeadDetail> =>
805 audited(db, who, "lead", "update", input.id, restoring(db, who, input, at), "unskipped");
806
807 function restoring(
808 db: Database,
809 who: Who,
810 input: { id: number; messageId: number },
811 at?: Date,
812 ): Result<LeadDetail> {
813 const found = leadFor(db, who, "update", input.id, {
814 signIn: "Sign in to bring back a follow-up.",
815 no: "You may not bring back a follow-up for this lead.",
816 });
817 if (!found.ok) return found;
818 const message = Number.isInteger(input.messageId) ? messageOf(db, found.value.id, input.messageId) : null;
819 if (message === null) return fail("not_found", "No such follow-up on this lead.");
820 if (message.status !== "skipped" || message.skipped_by_hand !== 1)
821 return fail("conflict", "Only a follow-up you skipped yourself can be brought back.");
822 if (CLOSED.includes(found.value.state))
823 return fail("conflict", "This lead is closed: put it back in follow-ups first.");
824 restoreMessage(db, message, stamp(at));
825 emit("lead.changed", { id: found.value.id });
826 return ok(detail(db, found.value.id)!);
827 }
828
761829 /** Qualified or lost: the lead leaves the cadence; open: it returns to it. */
762830 export const setState = (
763831 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; `noted` is a change to the agent's private note on the lead; `merged` is a new arrival who was already a lead (the detail names the arrival's source and the lead): their message joined that lead; `openers` is a change to how first replies open (the profile). */
38 export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off", "edited", "held", "unhold", "openers", "noted", "merged"] 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; `merged` is a new arrival who was already a lead (the detail names the arrival's source and the lead): their message joined that lead; `openers` is a change to how first replies open (the profile); `skipped` sets one upcoming follow-up aside by hand, `unskipped` brings it back. */
38 export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off", "edited", "held", "unhold", "openers", "noted", "merged", "skipped", "unskipped"] as const;
3939 export type Act = (typeof ACTS)[number];
4040
4141 /** What a `merged` row's detail holds: where the new arrival came from, and the lead they already were. */
src/contract.test.ts +13
@@ -22,6 +22,8 @@ import {
2222 logCall,
2323 bookShowing,
2424 cancelHeld,
25 restoreFollowUp,
26 skipFollowUp,
2527 cancelShowing,
2628 logLeadReply,
2729 parseLeadEmail,
@@ -155,7 +157,18 @@ const doors: Record<
155157 const untold = cancelHeld(db, who, { id: heldLead(authorId) }).ok;
156158 const cancelTool = tools.find((t) => t.name === "cancel_held_text")!;
157159 const viaTool = (cancelTool.run(db, who, { id: heldLead(authorId) }) as { ok: boolean }).ok;
160 // And so is skipping a follow-up and bringing it back (POST /leads/:id/messages/:mid/skip|restore).
161 const skipId = aLead(authorId);
162 const upcoming = db
163 .query<{ id: number }, [number]>(
164 "INSERT INTO message (lead_id, day, channel, body, signature, status, due_at) VALUES (?1, 3, 'email', 'Hi', 'Me', 'scheduled', '2999-01-01T00:00:00.000Z') RETURNING id",
165 )
166 .get(skipId)!.id;
167 const skipped = skipFollowUp(db, who, { id: skipId, messageId: upcoming }).ok;
168 const restored = skipped && restoreFollowUp(db, who, { id: skipId, messageId: upcoming }).ok;
158169 const changed = setState(db, who, { id: aLead(authorId), state: "lost" }).ok;
170 expect(skipped).toBe(changed);
171 expect(restored).toBe(changed);
159172 expect(untold).toBe(changed);
160173 expect(viaTool).toBe(changed);
161174 expect(showing).toBe(changed);
src/db.test.ts +1 −2
@@ -38,8 +38,7 @@ test("a database that ran the note columns before the openers still gets the ope
3838 const db = openDb(dir);
3939 // As a preview left it: the openers column never added, the version past the notes.
4040 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);
41 db.exec("DELETE FROM schema_version WHERE version > " + (migrations.length - 2));
4342 expect(() => migrate(db)).not.toThrow();
4443 expect(db.query("SELECT openers FROM profile").all()).toBeDefined();
4544 // And the reverse: a column already there is not added again.
src/db.ts +3
@@ -224,6 +224,9 @@ export const migrations: string[] = [
224224 // its recorded version skipped `openers`. `migrate` leaves out an
225225 // ADD COLUMN whose column is already there, so this is a no-op everywhere else.
226226 `ALTER TABLE profile ADD COLUMN openers TEXT NOT NULL DEFAULT '{}'`,
227 // A follow-up the agent skipped by hand, so `reopen` leaves it skipped.
228 // Existing skipped rows were skipped by a close or a call: 0.
229 `ALTER TABLE message ADD COLUMN skipped_by_hand INTEGER NOT NULL DEFAULT 0 CHECK (skipped_by_hand IN (0, 1))`,
227230 ];
228231
229232 /** An `ALTER TABLE … ADD COLUMN` whose column the table already has: nothing to do. */
src/leads.ts +50 −5
@@ -70,6 +70,8 @@ export interface Message {
7070 readonly goes_at: string | null;
7171 /** For a held text: when the agent approved it, which is when the lead counts as answered. */
7272 readonly approved_at: string | null;
73 /** 1 when the agent set this follow-up aside by hand: closing and reopening the lead leave it skipped. */
74 readonly skipped_by_hand: 0 | 1;
7375 }
7476
7577 /** The most a lead's reply may hold. */
@@ -886,7 +888,7 @@ export function reopen(db: Database, found: Lead, at: string, agent: Agent): voi
886888 const channel = channelFor(found);
887889 const skipped = db
888890 .query<{ id: number; day: number; due_at: string }, [number, number, number]>(
889 "SELECT id, day, due_at FROM message WHERE lead_id = ?1 AND status = 'skipped' AND day < ?2 AND NOT (day = 0 AND ?3 = 1)",
891 "SELECT id, day, due_at FROM message WHERE lead_id = ?1 AND status = 'skipped' AND skipped_by_hand = 0 AND day < ?2 AND NOT (day = 0 AND ?3 = 1)",
890892 )
891893 .all(found.id, ANSWER_DAY, replied ? 1 : 0);
892894 for (const m of skipped)
@@ -904,18 +906,61 @@ export function reopen(db: Database, found: Lead, at: string, agent: Agent): voi
904906 })();
905907 }
906908
909 /** Why a follow-up cannot be skipped, or null when it can: only its lead's own scheduled or due cadence touches. */
910 export function whyNotSkip(message: Message): string | null {
911 if (message.day === 0) return "The first reply is not a follow-up: send it, or close the lead.";
912 if (message.day >= ANSWER_DAY) return "An answer to something the lead wrote is not a follow-up to skip.";
913 if (message.status === "sent") return "That follow-up has already been sent.";
914 if (message.status === "held") return "That text is approved and held for 8:00 a.m.: take it back first.";
915 if (message.status === "skipped") return "That follow-up is already skipped.";
916 return message.status === "scheduled" || message.status === "due"
917 ? null
918 : "That message is not an upcoming follow-up.";
919 }
920
921 /** One of `id`'s messages, or null when there is none or it belongs to another lead. */
922 export const messageOf = (db: Database, id: number, messageId: number): Message | null =>
923 db
924 .query<Message, [number, number]>("SELECT * FROM message WHERE id = ?1 AND lead_id = ?2")
925 .get(messageId, id);
926
927 /** The agent sets one upcoming follow-up aside; the rest of the plan is untouched. */
928 export function skipMessage(db: Database, message: Message, at: string): void {
929 db.transaction(() => {
930 db.query(
931 "UPDATE message SET status = 'skipped', skipped_by_hand = 1, goes_at = NULL WHERE id = ?1",
932 ).run(message.id);
933 db.query("UPDATE lead SET updated_at = ?1 WHERE id = ?2").run(at, message.lead_id);
934 })();
935 }
936
937 /**
938 * A follow-up skipped by hand returns to upcoming at its original day; the
939 * same rules as any scheduled touch then make it due (`advance`: a showing's
940 * hold and a pending answer still apply), this one alone.
941 */
942 export function restoreMessage(db: Database, message: Message, at: string): void {
943 db.transaction(() => {
944 db.query("UPDATE message SET status = 'scheduled', skipped_by_hand = 0 WHERE id = ?1").run(
945 message.id,
946 );
947 db.query("UPDATE lead SET updated_at = ?1 WHERE id = ?2").run(at, message.lead_id);
948 advance(db, at, message.id);
949 })();
950 }
951
907952 /** Every scheduled touch whose day has come is due now. Returns the ids of the leads it touched. */
908 export function advance(db: Database, at: string): number[] {
953 export function advance(db: Database, at: string, only?: number): number[] {
909954 return db
910 .query<{ lead_id: number }, [string]>(
955 .query<{ lead_id: number }, [string, number]>(
911956 `UPDATE message SET status = 'due'
912 WHERE status = 'scheduled' AND due_at <= ?1
957 WHERE status = 'scheduled' AND due_at <= ?1 AND (?2 = 0 OR id = ?2)
913958 AND lead_id IN (SELECT id FROM lead WHERE state = 'contacted')
914959 AND lead_id NOT IN (SELECT lead_id FROM showing WHERE hold_until > ?1)
915960 AND lead_id NOT IN (SELECT lead_id FROM message WHERE day >= ${ANSWER_DAY} AND status IN ('draft', 'held'))
916961 RETURNING lead_id`,
917962 )
918 .all(at)
963 .all(at, only ?? 0)
919964 .map((row) => row.lead_id)
920965 .filter((id, i, all) => all.indexOf(id) === i);
921966 }
src/mcp.ts +26
@@ -24,6 +24,8 @@ import {
2424 logCall,
2525 bookShowing,
2626 cancelShowing,
27 restoreFollowUp,
28 skipFollowUp,
2729 logLeadReply,
2830 parseLeadEmail,
2931 type Result,
@@ -244,6 +246,30 @@ export const tools: readonly Tool[] = [
244246 inputSchema: ONE,
245247 run: (db, who, args) => cancelHeld(db, who, { id: Number(args.id) }),
246248 },
249 {
250 name: "skip_follow_up",
251 description:
252 "Skip one upcoming follow-up on a lead (a scheduled or due message of day 1 or later; get its message id from get_lead). It never reaches the desk or sends; the rest of the plan is untouched and reopening the lead does not bring it back. The first reply, an answer, and sent or held messages are refused.",
253 inputSchema: {
254 type: "object",
255 properties: { id: { type: "integer" }, messageId: { type: "integer" } },
256 required: ["id", "messageId"],
257 },
258 run: (db, who, args) =>
259 skipFollowUp(db, who, { id: Number(args.id), messageId: Number(args.messageId) }),
260 },
261 {
262 name: "restore_follow_up",
263 description:
264 "Bring back a follow-up skipped by hand: upcoming at its original day, or due if that day has passed. A showing's hold and quiet hours still apply.",
265 inputSchema: {
266 type: "object",
267 properties: { id: { type: "integer" }, messageId: { type: "integer" } },
268 required: ["id", "messageId"],
269 },
270 run: (db, who, args) =>
271 restoreFollowUp(db, who, { id: Number(args.id), messageId: Number(args.messageId) }),
272 },
247273 {
248274 name: "set_note",
249275 description:
src/pages/lead.ts +7
@@ -171,6 +171,13 @@ export function leadPage(input: {
171171 <span class="plan-when">${escape(day(m.sent_at ?? m.due_at))}</span>
172172 <span class="plan-status">${waits(m) ? "Waits for the showing" : PLAN[m.status]}</span>
173173 ${m.status === "scheduled" ? `<details class="peek"><summary>Preview</summary>${words(m)}</details>` : ""}
174 ${
175 mayUpdate && (m.status === "scheduled" || m.status === "due") && m.day > 0
176 ? `<form method="post" action="${path}/messages/${m.id}/skip"><button class="button button-quiet">Skip this one</button></form>`
177 : mayUpdate && m.status === "skipped" && m.skipped_by_hand === 1 && !closed
178 ? `<form method="post" action="${path}/messages/${m.id}/restore"><button class="button button-quiet">Bring it back</button></form>`
179 : ""
180 }
174181 </li>`,
175182 )
176183 .join("")}</ol></section>`;
src/routes.ts +33
@@ -38,6 +38,8 @@ import {
3838 logCall,
3939 bookShowing,
4040 cancelShowing,
41 restoreFollowUp,
42 skipFollowUp,
4143 logLeadReply,
4244 tick,
4345 type Failure,
@@ -407,6 +409,7 @@ const STATUS: Record<Failure, number> = {
407409 forbidden: 403,
408410 not_found: 404,
409411 invalid: 422,
412 conflict: 409,
410413 };
411414
412415 /** A result as JSON: the value, or `{ error, message }` with the matching status. */
@@ -929,6 +932,36 @@ export const routes: readonly Route[] = [
929932 answer: LEAD,
930933 },
931934 },
935 {
936 method: "POST",
937 path: "/leads/:id/messages/:mid/skip",
938 handle: (c) =>
939 posted(
940 c,
941 () => skipFollowUp(c.db, c.who, { id: ID(c), messageId: Number(c.params.mid) }),
942 () => ({ to: `/leads/${ID(c)}`, said: "Skipped. The rest of the plan is as it was." }),
943 ),
944 api: {
945 summary:
946 "Skip one upcoming follow-up (a scheduled or due message of day 1 or later on this lead): it leaves the desk, never sends, and closing then reopening the lead does not bring it back. The first reply, an answer, and sent or held messages are 409 with the reason; another lead's message is 404. No body needed.",
947 answer: LEAD,
948 },
949 },
950 {
951 method: "POST",
952 path: "/leads/:id/messages/:mid/restore",
953 handle: (c) =>
954 posted(
955 c,
956 () => restoreFollowUp(c.db, c.who, { id: ID(c), messageId: Number(c.params.mid) }),
957 () => ({ to: `/leads/${ID(c)}`, said: "Brought back." }),
958 ),
959 api: {
960 summary:
961 "Bring back a follow-up you skipped: it is upcoming at its original day, or due on the desk if that day has passed (a showing's hold and quiet hours still apply). Only a follow-up skipped by hand can be; 409 otherwise. No body needed.",
962 answer: LEAD,
963 },
964 },
932965 {
933966 method: "POST",
934967 path: "/leads/:id/note",
src/sentences.ts +7
@@ -65,6 +65,13 @@ export function deed(
6565 done: `took back the held text to ${lead}`,
6666 tried: `take back the held text to ${lead}`,
6767 };
68 if (row.act === "skipped" || row.act === "unskipped") {
69 const skip = row.act === "skipped";
70 return {
71 done: skip ? `skipped a follow-up to ${lead}` : `brought back a skipped follow-up to ${lead}`,
72 tried: skip ? `skip a follow-up to ${lead}` : `bring back a skipped follow-up to ${lead}`,
73 };
74 }
6875 if (row.act === "qualified" || row.act === "lost")
6976 return {
7077 done: `marked ${lead} ${row.act}`,
src/server.test.ts +2
@@ -303,6 +303,8 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
303303 "mark_lead",
304304 "edit_lead",
305305 "cancel_held_text",
306 "skip_follow_up",
307 "restore_follow_up",
306308 "set_note",
307309 "opt_out_texts",
308310 "get_profile",
src/skip.test.ts added +221
@@ -0,0 +1,221 @@
1 /**
2 * Skipping one upcoming follow-up, and bringing it back: only the lead's own
3 * scheduled or due follow-ups; nothing else moves; reopening leaves a hand-
4 * skipped follow-up skipped; every door.
5 */
6 import { expect, test } from "bun:test";
7 import { mkdtempSync } from "node:fs";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import {
11 activity,
12 addLead,
13 bookShowing,
14 getLead,
15 listLeads,
16 restoreFollowUp,
17 sendReply,
18 setState,
19 skipFollowUp,
20 tick,
21 } from "./actions.ts";
22 import { openDb } from "./db.ts";
23 import { agent } from "./env.ts";
24 import { tools } from "./mcp.ts";
25 import { leadPage } from "./pages/lead.ts";
26 import { serve } from "./server.ts";
27 import { sign, type Who } from "./who.ts";
28
29 const db = openDb(mkdtempSync(join(tmpdir(), "app-skip-")));
30 const alice: Who = { role: "user", id: "u1", name: "alice" };
31 const anon: Who = { role: "anon" };
32 const T0 = new Date("2026-10-12T15:00:00.000Z");
33 const at = (days: number, minutes = 0): Date =>
34 new Date(T0.getTime() + days * 86_400_000 + minutes * 60_000);
35 const must = <T>(r: { ok: true; value: T } | { ok: false; message: string }): T => {
36 if (!r.ok) throw new Error(r.message);
37 return r.value;
38 };
39
40 let n = 0;
41 /** A lead whose first reply went out at day 0: five follow-ups scheduled. */
42 const answered = () => {
43 const lead = must(
44 addLead(db, alice, { name: `Skip ${++n}`, email: `s${n}@example.com`, phone: "", source: "zillow", message: "Is it still available?", consent: false }, at(0)),
45 );
46 must(sendReply(db, alice, { id: lead.id }, at(0)));
47 return lead.id;
48 };
49 const plan = (id: number) => must(getLead(db, alice, { id })).messages.filter((m) => m.day > 0);
50 const day = (id: number, d: number) => plan(id).find((m) => m.day === d)!;
51
52 test("skipping a due follow-up takes it off the desk, and it never sends", () => {
53 const id = answered();
54 must(tick(db, alice, at(1, 1)));
55 const due = day(id, 1);
56 expect(due.status).toBe("due");
57 expect(must(listLeads(db, alice)).leads.find((l) => l.id === id)!.ready?.day).toBe(1);
58 const after = must(skipFollowUp(db, alice, { id, messageId: due.id }, at(1, 2)));
59 const touches = after.messages.filter((m) => m.day > 0);
60 expect(touches.map((m) => m.status)).toEqual(["skipped", "scheduled", "scheduled", "scheduled", "scheduled"]);
61 expect(must(listLeads(db, alice)).leads.find((l) => l.id === id)!.ready).toBeNull();
62 expect(sendReply(db, alice, { id }, at(1, 3))).toMatchObject({ ok: false });
63 must(tick(db, alice, at(30)));
64 expect(day(id, 1).status).toBe("skipped");
65 });
66
67 test("an upcoming follow-up skipped and restored before its day is upcoming again, the others untouched", () => {
68 const id = answered();
69 const before = plan(id);
70 const seven = day(id, 7);
71 must(skipFollowUp(db, alice, { id, messageId: seven.id }, at(1)));
72 expect(plan(id).map((m) => m.status)).toEqual(["scheduled", "scheduled", "skipped", "scheduled", "scheduled"]);
73 must(restoreFollowUp(db, alice, { id, messageId: seven.id }, at(2)));
74 expect(plan(id)).toEqual(before);
75 });
76
77 test("restored after its day has passed, it is due on the desk", () => {
78 const id = answered();
79 const three = day(id, 3);
80 must(skipFollowUp(db, alice, { id, messageId: three.id }, at(1)));
81 must(tick(db, alice, at(4)));
82 expect(day(id, 3).status).toBe("skipped");
83 must(restoreFollowUp(db, alice, { id, messageId: three.id }, at(4)));
84 expect(day(id, 3).status).toBe("due");
85 expect(day(id, 3).due_at).toBe(three.due_at);
86 });
87
88 test("a restored follow-up still waits for a showing", () => {
89 const id = answered();
90 const three = day(id, 3);
91 must(skipFollowUp(db, alice, { id, messageId: three.id }, at(1)));
92 must(bookShowing(db, alice, { id, when: at(5).toISOString() }, at(1)));
93 must(restoreFollowUp(db, alice, { id, messageId: three.id }, at(4)));
94 expect(day(id, 3).status).toBe("scheduled");
95 });
96
97 test("another lead's message is 404; the first reply, a sent one and a skipped one are 409; nothing changes", () => {
98 const id = answered();
99 const other = answered();
100 must(tick(db, alice, at(1, 1)));
101 must(sendReply(db, alice, { id }, at(1, 1)));
102 const snapshot = JSON.stringify(must(getLead(db, alice, { id })).messages);
103 const otherSnapshot = JSON.stringify(must(getLead(db, alice, { id: other })).messages);
104 const first = must(getLead(db, alice, { id })).messages.find((m) => m.day === 0)!;
105 expect(skipFollowUp(db, alice, { id, messageId: other * 100 })).toMatchObject({ ok: false, error: "not_found" });
106 expect(skipFollowUp(db, alice, { id, messageId: day(other, 3).id })).toMatchObject({ ok: false, error: "not_found" });
107 expect(skipFollowUp(db, alice, { id, messageId: first.id })).toMatchObject({ ok: false, error: "conflict" });
108 const sent = skipFollowUp(db, alice, { id, messageId: day(id, 1).id });
109 expect(sent).toMatchObject({ ok: false, error: "conflict" });
110 expect(!sent.ok && sent.message).toContain("already been sent");
111 expect(restoreFollowUp(db, alice, { id, messageId: day(id, 3).id })).toMatchObject({ ok: false, error: "conflict" });
112 expect(JSON.stringify(must(getLead(db, alice, { id })).messages)).toBe(snapshot);
113 expect(JSON.stringify(must(getLead(db, alice, { id: other })).messages)).toBe(otherSnapshot);
114 });
115
116 test("someone without permission is refused and nothing changes", () => {
117 const id = answered();
118 const m = day(id, 3);
119 expect(skipFollowUp(db, anon, { id, messageId: m.id })).toMatchObject({ ok: false, error: "signin_required" });
120 expect(day(id, 3).status).toBe("scheduled");
121 must(skipFollowUp(db, alice, { id, messageId: m.id }));
122 expect(restoreFollowUp(db, anon, { id, messageId: m.id })).toMatchObject({ ok: false, error: "signin_required" });
123 expect(day(id, 3).status).toBe("skipped");
124 });
125
126 test("reopening a lead does not resurrect a follow-up skipped by hand, but does one skipped by closing", () => {
127 const id = answered();
128 const three = day(id, 3);
129 must(skipFollowUp(db, alice, { id, messageId: three.id }, at(1)));
130 must(setState(db, alice, { id, state: "lost" }, at(2)));
131 expect(restoreFollowUp(db, alice, { id, messageId: three.id }, at(2))).toMatchObject({ ok: false, error: "conflict" });
132 must(setState(db, alice, { id, state: "open" }, at(3)));
133 expect(plan(id).map((m) => m.status)).toEqual(["scheduled", "skipped", "scheduled", "scheduled", "scheduled"]);
134 // It can be brought back by hand once the lead is open again: its day (3) has come.
135 must(restoreFollowUp(db, alice, { id, messageId: three.id }, at(3)));
136 expect(day(id, 3).status).toBe("due");
137 });
138
139 test("skip and bring-back each write one audit row the Activity page reads", () => {
140 const id = answered();
141 const m = day(id, 7);
142 const rows = () => must(activity(db, { role: "admin", id: "u0", name: "root" }, {})).rows.filter((r) => r.target === String(id));
143 const was = rows().length;
144 must(skipFollowUp(db, alice, { id, messageId: m.id }));
145 expect(rows().length).toBe(was + 1);
146 expect(rows()[0]!.act).toBe("skipped");
147 must(restoreFollowUp(db, alice, { id, messageId: m.id }));
148 expect(rows().length).toBe(was + 2);
149 expect(rows()[0]!.act).toBe("unskipped");
150 });
151
152 test("the page offers Skip this one and Bring it back, to someone who may update", () => {
153 const id = answered();
154 const m = day(id, 7);
155 const html = (who: Who, mayUpdate: boolean) =>
156 leadPage({ lead: must(getLead(db, alice, { id })), who, agent, mayUpdate, next: null, now: at(1).getTime() });
157 expect(html(alice, true)).toContain(`action="/leads/${id}/messages/${m.id}/skip"`);
158 expect(html(alice, true)).toContain("Skip this one");
159 must(skipFollowUp(db, alice, { id, messageId: m.id }));
160 expect(html(alice, true)).toContain(`action="/leads/${id}/messages/${m.id}/restore"`);
161 expect(html(alice, true)).toContain("Bring it back");
162 expect(html(anon, false)).not.toContain("/skip");
163 });
164
165 test("the JSON door, the form door, the spec, the MCP tools, and a cross-origin POST", async () => {
166 const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-skip-doors-")), identityKey: "k", sample: false });
167 try {
168 const identity = `u-skip|skipper|user|${Date.now() + 60_000}`;
169 const auth = { "x-forge-identity": identity, "x-forge-signature": sign(identity, "k") };
170 const headers = { ...auth, "content-type": "application/json", accept: "application/json" };
171 const url = `http://${server.hostname}:${server.port}`;
172 const lead = (await (await fetch(`${url}/leads`, {
173 method: "POST",
174 headers,
175 body: JSON.stringify({ name: "Nina Park", email: "[email protected]", source: "website", message: "Could we see 12 Cedar Ln?" }),
176 })).json()) as { id: number };
177 await fetch(`${url}/leads/${lead.id}/reply`, { method: "POST", headers, body: "{}" });
178 const get = async () => (await (await fetch(`${url}/leads/${lead.id}`, { headers })).json()) as { messages: { id: number; day: number; status: string }[] };
179 const status = async (d: number) => (await get()).messages.find((m) => m.day === d)!;
180 const three = await status(3);
181 const seven = await status(7);
182
183 const cross = await fetch(`${url}/leads/${lead.id}/messages/${three.id}/skip`, { method: "POST", headers: { ...headers, origin: "https://evil.example" }, body: "{}" });
184 expect(cross.status).toBe(403);
185 expect((await status(3)).status).toBe("scheduled");
186
187 const skipped = await fetch(`${url}/leads/${lead.id}/messages/${three.id}/skip`, { method: "POST", headers, body: "{}" });
188 expect(skipped.status).toBe(200);
189 expect((await status(3)).status).toBe("skipped");
190 const first = (await get()).messages.find((m) => m.day === 0)!;
191 const refused = await fetch(`${url}/leads/${lead.id}/messages/${first.id}/skip`, { method: "POST", headers, body: "{}" });
192 expect(refused.status).toBe(409);
193 expect(((await refused.json()) as { message: string }).message.length).toBeGreaterThan(10);
194 const back = await fetch(`${url}/leads/${lead.id}/messages/${three.id}/restore`, { method: "POST", headers, body: "{}" });
195 expect(back.status).toBe(200);
196 expect((await status(3)).status).toBe("scheduled");
197
198 const form = await fetch(`${url}/leads/${lead.id}/messages/${seven.id}/skip`, {
199 method: "POST",
200 headers: { ...auth, "content-type": "application/x-www-form-urlencoded" },
201 body: "x=1",
202 redirect: "manual",
203 });
204 expect(form.status).toBe(303);
205 expect((await status(7)).status).toBe("skipped");
206
207 const spec = JSON.stringify(await (await fetch(`${url}/openapi.json`, { headers })).json());
208 expect(spec).toContain("/leads/{id}/messages/{mid}/skip");
209 expect(spec).toContain("/leads/{id}/messages/{mid}/restore");
210
211 const call = (name: string, args: unknown) =>
212 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());
213 await call("restore_follow_up", { id: lead.id, messageId: seven.id });
214 expect((await status(7)).status).toBe("scheduled");
215 await call("skip_follow_up", { id: lead.id, messageId: seven.id });
216 expect((await status(7)).status).toBe("skipped");
217 expect(tools.map((t) => t.name)).toContain("skip_follow_up");
218 } finally {
219 server.stop(true);
220 }
221 });
src/terminal.test.ts +39
@@ -11,6 +11,7 @@ import { sourceLine } from "./clock.ts";
1111 import { openDb } from "./db.ts";
1212 import { agent } from "./env.ts";
1313 import { seed } from "./sample.ts";
14 import { subscribe } from "./live.ts";
1415 import { insertLead } from "./leads.ts";
1516 import { clean, plain, terminal, wrap } from "./terminal.ts";
1617 import type { Who } from "./who.ts";
@@ -427,6 +428,44 @@ test("v reads a pasted email into the add screen, says what is missing, and adds
427428 expect(read(t)).toContain("Paste the text of the email");
428429 });
429430
431 test("k skips the next follow-up and K brings it back; the lead's viewers hear of both; a hint only for those who may", () => {
432 const db = fresh();
433 for (const who of [alice, root]) {
434 const t = terminal(db, who);
435 t.key("\r");
436 expect(read(t)).not.toContain("k skip the next follow-up");
437 t.key("s"); // the first reply goes: the plan is drafted
438 expect(read(t)).toContain("k skip the next follow-up");
439 expect(read(t)).not.toContain("K bring back");
440 const id = (listLeads(db, who) as { ok: true; value: { leads: { id: number }[] } }).value.leads[0]!.id;
441 const heard: string[] = [];
442 const stop = subscribe((e) => heard.push(e.type));
443 t.key("k");
444 expect(read(t)).toContain("Day 1 skipped.");
445 expect(read(t)).toContain("day 1 skipped, day 3 scheduled");
446 expect(read(t)).toContain("K bring back a skipped follow-up");
447 t.key("K");
448 expect(read(t)).toContain("Day 1 is back in the plan.");
449 expect(read(t)).toContain("day 1 scheduled");
450 stop();
451 expect(heard.filter((x) => x === "lead.changed").length).toBe(2);
452 const row = db.query<{ n: number }, [string]>("SELECT count(*) AS n FROM audit WHERE act = ?1").get("skipped")!;
453 expect(row.n).toBeGreaterThan(0);
454 expect(id).toBeGreaterThan(0);
455 db.query("DELETE FROM lead").run();
456 seed(db, new Date());
457 }
458 });
459
460 test("a guest cannot reach a lead, so k and K change nothing for them", () => {
461 const db = fresh();
462 const t = terminal(db, { role: "anon" });
463 t.key("\r");
464 t.key("k");
465 t.key("K");
466 expect(db.query("SELECT count(*) AS n FROM message WHERE skipped_by_hand = 1").get()).toEqual({ n: 0 });
467 });
468
430469 test("adding someone already on the desk says they wrote in again, and adds no lead", () => {
431470 const db = fresh();
432471 const t = terminal(db, alice);
src/terminal.ts +24
@@ -40,6 +40,8 @@ import {
4040 saveProfile,
4141 approveReply,
4242 cancelHeld,
43 restoreFollowUp,
44 skipFollowUp,
4345 logCall,
4446 bookShowing,
4547 cancelShowing,
@@ -309,6 +311,18 @@ export function terminal(
309311 /** Whether the private note can be changed here: the table says yes, in any state. */
310312 const mayNote = (l: LeadDetail): boolean => permit(me, "lead", "update", { ...l }) === "yes";
311313
314 /** The next follow-up that can be skipped (scheduled or due, day 1 on), if the table lets this person. */
315 const skippable = (l: LeadDetail): Message | undefined =>
316 mayNote(l)
317 ? l.messages.find((m) => m.day > 0 && !isAnswer(m.day) && (m.status === "scheduled" || m.status === "due"))
318 : undefined;
319
320 /** The first follow-up skipped by hand that can come back: the lead is open. */
321 const restorable = (l: LeadDetail): Message | undefined =>
322 mayNote(l) && !CLOSED.includes(l.state)
323 ? l.messages.find((m) => m.status === "skipped" && m.skipped_by_hand === 1)
324 : undefined;
325
312326 function leadScreen(id: number, width: number, editing?: string): string[] {
313327 const l = lead(id);
314328 if (l === undefined) {
@@ -402,6 +416,8 @@ export function terminal(
402416 [
403417 ...(r === undefined ? [] : ["s approve and send", "e edit"]),
404418 ...(held === undefined ? [] : ["h take back the held text"]),
419 ...(skippable(l) === undefined ? [] : ["k skip the next follow-up"]),
420 ...(restorable(l) === undefined ? [] : ["K bring back a skipped follow-up"]),
405421 ...(l.phone === "" ? [] : ["c log a call"]),
406422 ...(l.replied_at !== null && !CLOSED.includes(l.state) ? ["w they wrote back"] : []),
407423 ...(CLOSED.includes(l.state) ? [] : [l.showing === null ? "b book a showing" : "b move the showing"]),
@@ -758,6 +774,14 @@ export function terminal(
758774 else if (input === "h" && l.messages.some((m) => m.status === "held")) {
759775 const back = cancelHeld(db, me, { id });
760776 said = back.ok ? "Taken back. It is a draft again." : back.message;
777 } else if (input === "k" && skippable(l) !== undefined) {
778 const m = skippable(l)!;
779 const skipped = skipFollowUp(db, me, { id, messageId: m.id });
780 said = skipped.ok ? `Day ${m.day} skipped. The rest of the plan is as it was.` : skipped.message;
781 } else if (input === "K" && restorable(l) !== undefined) {
782 const m = restorable(l)!;
783 const back = restoreFollowUp(db, me, { id, messageId: m.id });
784 said = back.ok ? `Day ${m.day} is back in the plan.` : back.message;
761785 } else if (input === "e") {
762786 const r = ready(l);
763787 if (r === undefined) said = "Nothing is waiting to go to this lead right now.";

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs