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

Pressed Send by mistake? For one minute after, one tap takes it back to a draft #91

Merged opened this

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

Merged

mason/speed-to-lead:mason/74-pressed-send-by-mistake-for-one-minute-a → main 3 commits fork

  • Merged. mason/74-pressed-send-by-mistake-for-one-minute-a was merged into main as 9cb19b9.

Review

Sign in to review this change.
14 files changed +500 −7
README.md +14
@@ -375,6 +375,20 @@ texts go at any hour (the test suite sets it). The 8:00 delivery is done by
375375 the clock, not by a person, so it is not audited: Activity shows the text as
376376 `held` (and the cancel), but never the send itself.
377377
378 **Undo send.** Pressed Send on the wrong lead? For 60 seconds after you
379 approve a message, its lead's page shows **Undo send** beside it. One tap
380 returns the message to a draft with the words it went with, and the lead is as
381 it was before: a first reply undone leaves the lead new with the clock running
382 again (and out of your response record), and the follow-ups that send
383 scheduled are taken back, so sending again makes them once. It works on a text
384 held for quiet hours too. The minute is the server's clock; after it the
385 button is gone and `POST /leads/:id/undo` answers 409 with a sentence, as it
386 does if anything else changed on the lead in the meantime. It is a same-origin
387 POST needing the same permission as any change to a lead (the policy table is
388 unchanged), and Activity records both the send and "took back the message …"
389 with who and when. It is on the page, the JSON door, MCP (`undo_send`) and the
390 terminal (`z` on the lead, offered while the minute lasts).
391
378392 **Skip one follow-up.** Each *Upcoming* (or ready) follow-up in a lead's plan
379393 has **Skip this one**: it leaves the desk and never sends, and the rest of the
380394 plan is untouched. It shows as *Skipped* with **Bring it back**, which returns
contract/openapi.json +38
@@ -1458,6 +1458,44 @@
14581458 }
14591459 }
14601460 },
1461 "/leads/{id}/undo": {
1462 "post": {
1463 "summary": "Take back a send within 60 seconds of it (server time), a text held for quiet hours included: the message returns to a draft with the words it went with, and the lead's clock, state and follow-ups are as they were. Refused with 409 after the minute. No body needed.",
1464 "operationId": "postLeadsIdUndo",
1465 "parameters": [
1466 {
1467 "name": "id",
1468 "in": "path",
1469 "required": true,
1470 "schema": {
1471 "type": "integer"
1472 }
1473 }
1474 ],
1475 "responses": {
1476 "200": {
1477 "description": "Take back a send within 60 seconds of it (server time), a text held for quiet hours included: the message returns to a draft with the words it went with, and the lead's clock, state and follow-ups are as they were. Refused with 409 after the minute. No body needed.",
1478 "content": {
1479 "application/json": {
1480 "schema": {
1481 "$ref": "#/components/schemas/Lead"
1482 }
1483 }
1484 }
1485 },
1486 "default": {
1487 "description": "{ error, message }: why not",
1488 "content": {
1489 "application/json": {
1490 "schema": {
1491 "$ref": "#/components/schemas/Error"
1492 }
1493 }
1494 }
1495 }
1496 }
1497 }
1498 },
14611499 "/leads/{id}/unhold": {
14621500 "post": {
14631501 "summary": "Take back a text held for quiet hours: it returns to an unsent draft you can edit and approve again. No body needed.",
src/actions.ts +41 −2
@@ -77,6 +77,7 @@ import {
7777 type NextLead,
7878 } from "./leads.ts";
7979 import { emit } from "./live.ts";
80 import { capture, keep, restore, whyNot } from "./undo.ts";
8081 import { currentAgent, storeAgent } from "./profile.ts";
8182 import { append, fill, REPLIES_MAX, REPLY_NAME_MAX, REPLY_TEXT_MAX, SAMPLE_REPLIES, type SavedReply } from "./replies.ts";
8283 import { nextInquiry, seed } from "./sample.ts";
@@ -726,8 +727,46 @@ function reply(
726727 const agent = currentAgent(db);
727728 // A text outside quiet hours is approved now and goes at the next 8:00.
728729 const goes = goesAt(ready.channel, now, agent.timeZone);
729 if (goes === null) send(db, found.value, ready, body, by, now, agent);
730 else hold(db, found.value, ready, body, by, now, goes);
730 // The way back is kept in the same transaction as the send, so neither can exist without the other.
731 db.transaction(() => {
732 const before = capture(db, found.value.id);
733 if (goes === null) send(db, found.value, ready, body, by, now, agent);
734 else hold(db, found.value, ready, body, by, now, goes);
735 // For a minute the agent can take it back (`undoSend`).
736 if (before !== null) keep(db, found.value.id, ready.id, before, now);
737 })();
738 emit("lead.changed", { id: found.value.id });
739 return ok(detail(db, found.value.id)!);
740 }
741
742 /**
743 * Take back a send within a minute of it (a text held for quiet hours
744 * included): the message is a draft again with the words it went with, and
745 * the lead's clock, state and follow-ups are as they were before. The minute
746 * is the server's. A conflict after it, with the reason in a sentence.
747 */
748 export const undoSend = (
749 db: Database,
750 who: Who,
751 input: { id: number },
752 at?: Date,
753 ): Result<LeadDetail> =>
754 audited(db, who, "lead", "update", input.id, unsend(db, who, input, at), "unsent");
755
756 function unsend(
757 db: Database,
758 who: Who,
759 input: { id: number },
760 at?: Date,
761 ): Result<LeadDetail> {
762 const found = leadFor(db, who, "update", input.id, {
763 signIn: "Sign in to take back a send.",
764 no: "You may not take back a send on this lead.",
765 });
766 if (!found.ok) return found;
767 const why = whyNot(db, found.value.id, (at ?? new Date()).getTime());
768 if (why !== null) return fail("conflict", why);
769 restore(db, found.value.id);
731770 emit("lead.changed", { id: found.value.id });
732771 return ok(detail(db, found.value.id)!);
733772 }
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); `cadence` is a change to the follow-up days (the profile); `skipped` sets one upcoming follow-up aside by hand, `unskipped` brings it back; `put_away` parks a lead until a date (the detail holds `{"on":"YYYY-MM-DD"}`), `brought_back` clears that date; `starred` keeps a lead close, `unstarred` lets it go. */
38 export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off", "edited", "held", "unhold", "openers", "cadence", "replies", "noted", "merged", "skipped", "unskipped", "put_away", "brought_back", "starred", "unstarred"] 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); `cadence` is a change to the follow-up days (the profile); `skipped` sets one upcoming follow-up aside by hand, `unskipped` brings it back; `put_away` parks a lead until a date (the detail holds `{"on":"YYYY-MM-DD"}`), `brought_back` clears that date; `starred` keeps a lead close, `unstarred` lets it go; `unsent` takes back a send within its minute. */
38 export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off", "edited", "held", "unhold", "openers", "cadence", "replies", "noted", "merged", "skipped", "unskipped", "put_away", "brought_back", "starred", "unstarred", "unsent"] as const;
3939 export type Act = (typeof ACTS)[number];
4040
4141 /** What a `merged` row's detail holds: where the new arrival came from, and the lead they already were. */
src/db.ts +8
@@ -268,6 +268,14 @@ export const migrations: string[] = [
268268 `ALTER TABLE profile ADD COLUMN replies TEXT`,
269269 // A lead the agent keeps close: 1 is starred. Starred open leads lead the desk. Existing leads are not starred.
270270 `ALTER TABLE lead ADD COLUMN starred INTEGER NOT NULL DEFAULT 0 CHECK (starred IN (0, 1))`,
271 // The way back from the latest send on a lead, kept for a minute (see undo.ts): the lead and its messages as they were, as JSON.
272 `CREATE TABLE IF NOT EXISTS undo_send (
273 lead_id INTEGER PRIMARY KEY REFERENCES lead (id) ON DELETE CASCADE,
274 message_id INTEGER NOT NULL,
275 taken_at TEXT NOT NULL,
276 after_updated_at TEXT NOT NULL,
277 snapshot TEXT NOT NULL
278 )`,
271279 ];
272280
273281 /**
src/mcp.ts +8
@@ -21,6 +21,7 @@ import {
2121 optOutTexts,
2222 approveReply,
2323 cancelHeld,
24 undoSend,
2425 setState,
2526 logCall,
2627 bookShowing,
@@ -301,6 +302,13 @@ export const tools: readonly Tool[] = [
301302 run: (db, who, args) =>
302303 editLead(db, who, { id: Number(args.id), name: args.name, email: args.email, phone: args.phone }),
303304 },
305 {
306 name: "undo_send",
307 description:
308 "Take back a send within 60 seconds of it (server time), a held text included: the message returns to a draft with the words it went with, and the lead's clock, state and follow-ups are as they were. Refused as a conflict after the minute.",
309 inputSchema: ONE,
310 run: (db, who, args) => undoSend(db, who, { id: Number(args.id) }),
311 },
304312 {
305313 name: "cancel_held_text",
306314 description:
src/pages/lead.ts +9 −1
@@ -44,11 +44,18 @@ export function leadPage(input: {
4444 /** The lead that has waited longest among those that need the agent; null when none. */
4545 next: NextLead | null;
4646 now: number;
47 /** The message that may still be taken back (sent in the last minute); null when none. */
48 undo?: number | null;
4749 notice?: string | undefined;
4850 /** What the draft box holds when it is not the draft: a reply was added, or an edit was refused. Opens the edit. */
4951 editing?: string | undefined;
5052 }): string {
5153 const { who, agent, lead, mayUpdate, next, now, notice, editing } = input;
54 const undo = mayUpdate ? (input.undo ?? null) : null;
55 const undoForm = (m: Message): string =>
56 m.id === undo
57 ? `<form method="post" action="/leads/${lead.id}/undo" data-undo><button class="button button-quiet">Undo send</button> <span class="hint">For a minute after sending.</span></form>`
58 : "";
5259 const ready = lead.messages.find(
5360 (m) => m.status === "draft" || m.status === "due",
5461 );
@@ -74,6 +81,7 @@ export function leadPage(input: {
7481 <h2>${titleOf(held)} <span class="muted">· by ${CHANNEL[held.channel]}</span></h2>
7582 <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>
7683 <div class="draft-view">${words({ body: held.body, signature: held.signature })}</div>
84 ${undoForm(held)}
7785 ${
7886 mayUpdate
7987 ? `<form method="post" action="${path}/unhold"><button class="button button-quiet">Cancel and keep as a draft</button></form>`
@@ -160,7 +168,7 @@ export function leadPage(input: {
160168 </li>`
161169 : `<li>
162170 <p class="meta">${titleOf(m!)} · ${CHANNEL[m!.channel]} · <time datetime="${escape(m!.sent_at ?? "")}">${escape(when(m!.sent_at ?? m!.due_at, agent.timeZone))}</time>${m!.sent_by ? ` · approved by ${escape(m!.sent_by)}` : ""}</p>
163 ${words(m!)}${link(m!)}
171 ${words(m!)}${link(m!)}${undoForm(m!)}
164172 </li>`,
165173 )
166174 .join("")}</ol></section>`;
src/routes.ts +18
@@ -37,6 +37,7 @@ import {
3737 approveReply,
3838 insertReply,
3939 cancelHeld,
40 undoSend,
4041 nextLead,
4142 setState,
4243 logCall,
@@ -77,6 +78,7 @@ import { MAX_EMAIL_TEXT } from "./intake.ts";
7778 import { MAX_SIGNIN_TEXT } from "./signins.ts";
7879 import { LOST_REASONS, lostSaid } from "./lost.ts";
7980 import { MAX_INBOUND, MAX_LEAD_NOTE, MAX_QUERY, Q_HELP, showingsAhead, VIEW_HELP, VIEWS, type LeadDetail, type NewLead } from "./leads.ts";
81 import { undoable } from "./undo.ts";
8082 import { events } from "./live.ts";
8183 import { rpc } from "./mcp.ts";
8284 import { deskPage } from "./pages/desk.ts";
@@ -574,6 +576,7 @@ const leadView = (
574576 mayUpdate: permit(c.who, "lead", "update", { ...lead }) === "yes",
575577 next: nextLead(c.db, c.who, { except: lead.id }),
576578 now: Date.now(),
579 undo: undoable(c.db, lead.id, Date.now()),
577580 ...extra,
578581 });
579582
@@ -1203,6 +1206,21 @@ export const routes: readonly Route[] = [
12031206 answer: LEAD,
12041207 },
12051208 },
1209 {
1210 method: "POST",
1211 path: "/leads/:id/undo",
1212 handle: (c) =>
1213 posted(
1214 c,
1215 () => undoSend(c.db, c.who, { id: ID(c) }),
1216 () => ({ to: `/leads/${ID(c)}`, said: "Taken back. It is a draft again, and the lead is as it was before." }),
1217 ),
1218 api: {
1219 summary:
1220 "Take back a send within 60 seconds of it (server time), a text held for quiet hours included: the message returns to a draft with the words it went with, and the lead's clock, state and follow-ups are as they were. Refused with 409 after the minute. No body needed.",
1221 answer: LEAD,
1222 },
1223 },
12061224 {
12071225 method: "POST",
12081226 path: "/leads/:id/unhold",
src/sentences.ts +5
@@ -86,6 +86,11 @@ export function deed(
8686 done: `took back the held text to ${lead}`,
8787 tried: `take back the held text to ${lead}`,
8888 };
89 if (row.act === "unsent")
90 return {
91 done: `took back the message to ${lead} (undo send)`,
92 tried: `take back the message to ${lead}`,
93 };
8994 if (row.act === "skipped" || row.act === "unskipped") {
9095 const skip = row.act === "skipped";
9196 return {
src/server.test.ts +1
@@ -332,6 +332,7 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
332332 "cancel_showing",
333333 "mark_lead",
334334 "edit_lead",
335 "undo_send",
335336 "cancel_held_text",
336337 "skip_follow_up",
337338 "restore_follow_up",
src/star.test.ts +2 −1
@@ -123,7 +123,8 @@ test("the Activity page says who starred whom, and the audit keeps the refused t
123123 test("the migration adds the column to an existing database and keeps its leads", () => {
124124 const db = new Database(":memory:");
125125 const at = migrations.findIndex((m) => m.includes("ADD COLUMN starred"));
126 expect(at).toBe(migrations.length - 1);
126 expect(at).toBeGreaterThan(0);
127 expect(migrations.findIndex((m) => m.includes("undo_send"))).toBeGreaterThan(at);
127128 db.exec("CREATE TABLE schema_version (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')))");
128129 migrations.slice(0, at).forEach((sql, i) => {
129130 try {
src/terminal.ts +7 −1
@@ -23,6 +23,7 @@
2323 * and whether it goes by text or email.
2424 */
2525
26 import { undoable } from "./undo.ts";
2627 import type { Database } from "bun:sqlite";
2728 import {
2829 activity,
@@ -43,6 +44,7 @@ import {
4344 saveProfile,
4445 approveReply,
4546 cancelHeld,
47 undoSend,
4648 restoreFollowUp,
4749 skipFollowUp,
4850 logCall,
@@ -443,6 +445,7 @@ export function terminal(
443445 : dim(
444446 [
445447 ...(r === undefined ? [] : ["s approve and send", "e edit"]),
448 ...(undoable(db, l.id, now()) === null ? [] : ["z undo send (for a minute)"]),
446449 ...(held === undefined ? [] : ["h take back the held text"]),
447450 ...(skippable(l) === undefined ? [] : ["k skip the next follow-up"]),
448451 ...(restorable(l) === undefined ? [] : ["K bring back a skipped follow-up"]),
@@ -846,7 +849,10 @@ export function terminal(
846849 if (next === null) said = "Nothing else needs you right now.";
847850 else view = { name: "lead", id: next.id };
848851 }
849 else if (input === "h" && l.messages.some((m) => m.status === "held")) {
852 else if (input === "z" && undoable(db, id, now()) !== null) {
853 const back = undoSend(db, me, { id }, new Date(now()));
854 said = back.ok ? "Taken back. It is a draft again, and the lead is as it was before." : back.message;
855 } else if (input === "h" && l.messages.some((m) => m.status === "held")) {
850856 const back = cancelHeld(db, me, { id });
851857 said = back.ok ? "Taken back. It is a draft again." : back.message;
852858 } else if (input === "k" && skippable(l) !== undefined) {
src/undo.test.ts added +236
@@ -0,0 +1,236 @@
1 /**
2 * Undo send: for one minute after approving, one POST takes the message back
3 * to a draft with its words, and the lead is as it was — state, clock,
4 * response record, follow-ups. After the minute it is a 409; anon is refused;
5 * the audit trail has the send and the undo; sending again makes the
6 * follow-ups once.
7 */
8 import { afterAll, beforeAll, expect, test } from "bun:test";
9 import { mkdtempSync } from "node:fs";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { addLead, approveReply, getLead, listAudit, listLeads, saveProfile, undoSend } from "./actions.ts";
13 import { openDb } from "./db.ts";
14 import { agent } from "./env.ts";
15 import { leadPage } from "./pages/lead.ts";
16 import { serve } from "./server.ts";
17 import { undoable, UNDO_MS } from "./undo.ts";
18 import { plain, terminal } from "./terminal.ts";
19 import { sign } from "./who.ts";
20 import type { Who } from "./who.ts";
21
22 let was: string | undefined;
23 beforeAll(() => {
24 was = process.env.QUIET_HOURS;
25 delete process.env.QUIET_HOURS;
26 });
27 afterAll(() => {
28 if (was !== undefined) process.env.QUIET_HOURS = was;
29 });
30
31 const alice: Who = { role: "user", id: "u1", name: "alice" };
32 const root: Who = { role: "admin", id: "u0", name: "root" };
33 const anon: Who = { role: "anon" };
34 const noon = new Date("2026-06-10T12:00:00-05:00");
35 const after = (ms: number, from = noon) => new Date(from.getTime() + ms);
36
37 const value = <T>(r: { ok: boolean; value?: T; message?: string }): T => {
38 if (!r.ok) throw new Error(r.message);
39 return r.value as T;
40 };
41
42 const fresh = (consent = false) => {
43 const db = openDb(mkdtempSync(join(tmpdir(), "app-undo-")));
44 value(saveProfile(db, root, { ...agent, timeZone: "America/Chicago" }));
45 const id = value(
46 addLead(
47 db,
48 alice,
49 { name: "Dana Reyes", email: "[email protected]", phone: "(206) 555-0199", source: "zillow", message: "Can I see 12 Oak Street?", consent },
50 new Date(noon.getTime() - 3_600_000),
51 ),
52 ).id;
53 return { db, id };
54 };
55
56 const rowsOf = (db: ReturnType<typeof fresh>["db"], id: number) =>
57 db.query("SELECT * FROM message WHERE lead_id = ?1 ORDER BY day").all(id);
58
59 test("undone within the minute, a first reply is a draft with its words and the lead is new again", () => {
60 const { db, id } = fresh();
61 const was = value(getLead(db, alice, { id }));
62 const sentRows = rowsOf(db, id).length;
63 value(approveReply(db, alice, { id, body: "Hi Dana, my own words." }, noon));
64 const sent = value(getLead(db, alice, { id }));
65 expect(sent.state).toBe("contacted");
66 expect(sent.replied_at).not.toBeNull();
67 expect(sent.messages.length).toBeGreaterThan(sentRows);
68
69 const back = value(undoSend(db, alice, { id }, after(59_000)));
70 expect(back.state).toBe("new");
71 expect(back.replied_at).toBeNull();
72 expect(back.updated_at).toBe(was.updated_at);
73 expect(back.messages).toHaveLength(sentRows);
74 const first = back.messages.find((m) => m.day === 0)!;
75 expect(first.status).toBe("draft");
76 expect(first.body).toBe("Hi Dana, my own words.");
77 expect(first.sent_at).toBeNull();
78 expect(first.sent_by).toBeNull();
79 // The desk's speed numbers no longer count a reply.
80 expect(value(listLeads(db, alice, { now: noon.getTime() + 61_000 })).record.replied).toBe(0);
81 });
82
83 test("sent again after an undo, the follow-ups exist once", () => {
84 const { db, id } = fresh();
85 value(approveReply(db, alice, { id }, noon));
86 const once = rowsOf(db, id).length;
87 value(undoSend(db, alice, { id }, after(1_000)));
88 value(approveReply(db, alice, { id }, after(5_000)));
89 expect(rowsOf(db, id)).toHaveLength(once);
90 const days = (rowsOf(db, id) as { day: number }[]).map((m) => m.day);
91 expect(new Set(days).size).toBe(days.length);
92 });
93
94 test("after the minute the route refuses with a sentence, by the server's clock", () => {
95 const { db, id } = fresh();
96 value(approveReply(db, alice, { id }, noon));
97 expect(undoable(db, id, noon.getTime() + UNDO_MS)).not.toBeNull();
98 expect(undoable(db, id, noon.getTime() + UNDO_MS + 1)).toBeNull();
99 const late = undoSend(db, alice, { id }, after(UNDO_MS + 1));
100 expect(late).toMatchObject({ ok: false, error: "conflict" });
101 expect(late.ok ? "" : late.message).toContain("more than a minute");
102 expect(value(getLead(db, alice, { id })).state).toBe("contacted");
103 });
104
105 test("anon is refused, and nothing changes", () => {
106 const { db, id } = fresh();
107 value(approveReply(db, alice, { id }, noon));
108 expect(undoSend(db, anon, { id }, after(1_000))).toMatchObject({ ok: false, error: "signin_required" });
109 expect(value(getLead(db, alice, { id })).state).toBe("contacted");
110 });
111
112 test("something else changing the lead in the minute makes the undo a conflict", () => {
113 const { db, id } = fresh();
114 value(approveReply(db, alice, { id }, noon));
115 db.query("UPDATE lead SET updated_at = ?1 WHERE id = ?2").run(after(2_000).toISOString(), id);
116 expect(undoSend(db, alice, { id }, after(3_000))).toMatchObject({ ok: false, error: "conflict" });
117 });
118
119 test("a second undo has nothing to take back", () => {
120 const { db, id } = fresh();
121 value(approveReply(db, alice, { id }, noon));
122 value(undoSend(db, alice, { id }, after(1_000)));
123 expect(undoSend(db, alice, { id }, after(2_000))).toMatchObject({ ok: false, error: "conflict" });
124 });
125
126 test("the audit trail has the send and the undo, with who and when", () => {
127 const { db, id } = fresh();
128 value(approveReply(db, alice, { id }, noon));
129 value(undoSend(db, alice, { id }, after(1_000)));
130 undoSend(db, anon, { id }, after(2_000));
131 const rows = value(listAudit(db, root, {}));
132 const acts = rows.filter((r) => r.target === String(id)).map((r) => [r.act, r.who_name, r.allowed]);
133 expect(acts).toContainEqual(["first_reply", "alice", 1]);
134 expect(acts).toContainEqual(["unsent", "alice", 1]);
135 expect(acts).toContainEqual(["unsent", null, 0]);
136 });
137
138 test("a text held for quiet hours is taken back the same way", () => {
139 const { db, id } = fresh(true);
140 const night = new Date("2026-06-10T22:00:00-05:00");
141 const held = value(approveReply(db, alice, { id }, night));
142 expect(held.scheduledFor).toBeDefined();
143 expect(value(getLead(db, alice, { id })).messages.find((m) => m.day === 0)!.status).toBe("held");
144 const back = value(undoSend(db, alice, { id }, after(30_000, night)));
145 expect(back.state).toBe("new");
146 expect(back.replied_at).toBeNull();
147 const first = back.messages.find((m) => m.day === 0)!;
148 expect(first.status).toBe("draft");
149 expect(first.goes_at).toBeNull();
150 expect(first.approved_at).toBeNull();
151 });
152
153 test("the lead page offers Undo send only while the minute lasts, and only to who may update", () => {
154 const { db, id } = fresh();
155 value(approveReply(db, alice, { id }, noon));
156 const lead = value(getLead(db, alice, { id }));
157 const msg = undoable(db, id, noon.getTime() + 1_000);
158 const page = (undo: number | null, mayUpdate = true) =>
159 leadPage({ who: alice, agent, lead, mayUpdate, next: null, now: noon.getTime(), undo });
160 expect(page(msg)).toContain("Undo send");
161 expect(page(msg)).toContain(`action="/leads/${id}/undo"`);
162 expect(page(null)).not.toContain("Undo send");
163 expect(page(msg, false)).not.toContain("Undo send");
164 });
165
166 test("the route: a same-origin POST undoes; a cross-site one is refused", async () => {
167 const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-undo-srv-")), identityKey: "k", sample: false });
168 try {
169 const identity = `u1|alice|user|${Date.now() + 60_000}`;
170 const url = `http://${server.hostname}:${server.port}`;
171 const headers = { "x-forge-identity": identity, "x-forge-signature": sign(identity, "k"), "content-type": "application/json", accept: "application/json" };
172 const made = await fetch(`${url}/leads`, {
173 method: "POST",
174 headers,
175 body: JSON.stringify({ name: "Sam Lee", email: "[email protected]", source: "zillow", message: "Is it still available?" }),
176 });
177 const id = ((await made.json()) as { id: number }).id;
178 expect((await fetch(`${url}/leads/${id}/reply`, { method: "POST", headers, body: "{}" })).status).toBe(200);
179 const cross = await fetch(`${url}/leads/${id}/undo`, { method: "POST", headers: { ...headers, origin: "https://evil.example" }, body: "{}" });
180 expect(cross.status).toBe(403);
181 const anonymous = await fetch(`${url}/leads/${id}/undo`, { method: "POST", headers: { "content-type": "application/json", accept: "application/json" }, body: "{}" });
182 expect(anonymous.status).toBe(401);
183 const ok = await fetch(`${url}/leads/${id}/undo`, { method: "POST", headers, body: "{}" });
184 expect(ok.status).toBe(200);
185 expect(((await ok.json()) as { state: string }).state).toBe("new");
186 expect((await fetch(`${url}/leads/${id}/undo`, { method: "POST", headers, body: "{}" })).status).toBe(409);
187 } finally {
188 server.stop(true);
189 }
190 });
191
192 test("the migration adds the undo table to an existing database", () => {
193 const db = openDb(mkdtempSync(join(tmpdir(), "app-undo-mig-")));
194 expect(db.query("SELECT count(*) AS n FROM undo_send").get()).toEqual({ n: 0 });
195 });
196
197 test("the terminal offers z while the minute lasts, undoes through undoSend, and audits it", () => {
198 const { db, id } = fresh();
199 let clock = noon.getTime();
200 value(approveReply(db, alice, { id }, noon));
201 const t = terminal(db, alice, () => clock);
202 const screen = () => t.screen(100).map(plain).join("\n");
203 t.key("\r");
204 expect(screen()).toContain("z undo send");
205 t.key("z");
206 const back = value(getLead(db, alice, { id }));
207 expect(back.state).toBe("new");
208 expect(back.messages.find((m) => m.day === 0)!.status).toBe("draft");
209 expect(screen()).not.toContain("z undo send");
210 expect(value(listAudit(db, root, {})).some((r) => r.act === "unsent" && r.who_name === "alice")).toBe(true);
211
212 // After the minute the key does nothing and the hint is gone.
213 value(approveReply(db, alice, { id }, new Date(clock)));
214 clock += UNDO_MS + 1_000;
215 expect(screen()).not.toContain("z undo send");
216 t.key("z");
217 expect(value(getLead(db, alice, { id })).state).toBe("contacted");
218 });
219
220 test("the MCP tool undo_send takes a send back", async () => {
221 const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-undo-mcp-")), identityKey: "k", sample: false });
222 try {
223 const identity = `u1|alice|user|${Date.now() + 60_000}`;
224 const url = `http://${server.hostname}:${server.port}`;
225 const headers = { "x-forge-identity": identity, "x-forge-signature": sign(identity, "k"), "content-type": "application/json", accept: "application/json" };
226 const made = await fetch(`${url}/leads`, { method: "POST", headers, body: JSON.stringify({ name: "Sam Lee", email: "[email protected]", source: "zillow", message: "Hello?" }) });
227 const id = ((await made.json()) as { id: number }).id;
228 const call = (name: string, args: unknown) =>
229 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>);
230 await call("send_reply", { id });
231 const back = await call("undo_send", { id });
232 expect(JSON.parse(back.result.content[0].text).state).toBe("new");
233 } finally {
234 server.stop(true);
235 }
236 });
src/undo.ts added +111
@@ -0,0 +1,111 @@
1 /**
2 * Undo send: for one minute after a message is approved, the lead goes back
3 * to what it was just before. The state of the lead (its clock, state and
4 * place in a put-away) and of its messages is kept at the moment of the tap
5 * and put back whole, so whatever the send did — stopped the clock, drafted
6 * the follow-ups, moved their days — is undone with it, and sending again
7 * makes the follow-ups once. Plain data in and out; the server's clock is
8 * the only clock.
9 */
10
11 import type { Database } from "bun:sqlite";
12 import type { Message } from "./leads.ts";
13
14 /** How long after a send it can be taken back. */
15 export const UNDO_MS = 60_000;
16
17 /** What the lead stood at before the tap. */
18 export interface Before {
19 readonly lead: {
20 readonly replied_at: string | null;
21 readonly state: string;
22 readonly updated_at: string;
23 readonly back_on: string | null;
24 };
25 readonly messages: readonly Message[];
26 }
27
28 /** Read how the lead stands, before a send changes it. */
29 export function capture(db: Database, leadId: number): Before | null {
30 const lead = db
31 .query<Before["lead"], [number]>("SELECT replied_at, state, updated_at, back_on FROM lead WHERE id = ?1")
32 .get(leadId);
33 if (lead === null) return null;
34 const messages = db.query<Message, [number]>("SELECT * FROM message WHERE lead_id = ?1").all(leadId);
35 return { lead, messages };
36 }
37
38 /** Keep `before` as the way back from sending `messageId` at `at`; the lead's latest send replaces an earlier one. */
39 export function keep(db: Database, leadId: number, messageId: number, before: Before, at: string): void {
40 const after = db.query<{ updated_at: string }, [number]>("SELECT updated_at FROM lead WHERE id = ?1").get(leadId);
41 if (after === null) return;
42 db.query(
43 "INSERT OR REPLACE INTO undo_send (lead_id, message_id, taken_at, after_updated_at, snapshot) VALUES (?1, ?2, ?3, ?4, ?5)",
44 ).run(leadId, messageId, at, after.updated_at, JSON.stringify(before));
45 }
46
47 interface Row {
48 readonly message_id: number;
49 readonly taken_at: string;
50 readonly after_updated_at: string;
51 readonly snapshot: string;
52 }
53
54 const rowOf = (db: Database, leadId: number): Row | null =>
55 db.query<Row, [number]>("SELECT message_id, taken_at, after_updated_at, snapshot FROM undo_send WHERE lead_id = ?1").get(leadId);
56
57 /** Why the send cannot be taken back, or null when it can. A sentence for the person. */
58 export function whyNot(db: Database, leadId: number, nowMs: number): string | null {
59 const row = rowOf(db, leadId);
60 if (row === null) return "There is no send to take back on this lead.";
61 if (nowMs - Date.parse(row.taken_at) > UNDO_MS)
62 return "That was sent more than a minute ago, so it can no longer be taken back.";
63 const lead = db.query<{ updated_at: string }, [number]>("SELECT updated_at FROM lead WHERE id = ?1").get(leadId);
64 const message = db
65 .query<{ status: string }, [number]>("SELECT status FROM message WHERE id = ?1")
66 .get(row.message_id);
67 if (lead === null || message === null || lead.updated_at !== row.after_updated_at || !["sent", "held"].includes(message.status))
68 return "This lead has changed since it was sent, so it can no longer be taken back.";
69 return null;
70 }
71
72 /** The message that can be taken back right now, or null: what the page asks to show the button. */
73 export const undoable = (db: Database, leadId: number, nowMs: number): number | null =>
74 whyNot(db, leadId, nowMs) === null ? rowOf(db, leadId)!.message_id : null;
75
76 /** Put the lead back as it was before the send. The message keeps its words as sent. Call only when `whyNot` is null. */
77 export function restore(db: Database, leadId: number): void {
78 const row = rowOf(db, leadId)!;
79 const before = JSON.parse(row.snapshot) as Before;
80 db.transaction(() => {
81 db.query("UPDATE lead SET replied_at = ?1, state = ?2, updated_at = ?3, back_on = ?4 WHERE id = ?5").run(
82 before.lead.replied_at,
83 before.lead.state,
84 before.lead.updated_at,
85 before.lead.back_on,
86 leadId,
87 );
88 const kept = new Set(before.messages.map((m) => m.id));
89 for (const { id } of db.query<{ id: number }, [number]>("SELECT id FROM message WHERE lead_id = ?1").all(leadId))
90 if (!kept.has(id)) db.query("DELETE FROM message WHERE id = ?1").run(id);
91 for (const m of before.messages) {
92 const asSent = m.id === row.message_id;
93 db.query(
94 "UPDATE message SET body = ?1, channel = ?2, signature = ?3, status = ?4, due_at = ?5, sent_at = ?6, sent_by = ?7, goes_at = ?8, approved_at = ?9, skipped_by_hand = ?10 WHERE id = ?11",
95 ).run(
96 asSent ? db.query<{ body: string }, [number]>("SELECT body FROM message WHERE id = ?1").get(m.id)!.body : m.body,
97 m.channel,
98 m.signature,
99 m.status,
100 m.due_at,
101 m.sent_at,
102 m.sent_by,
103 m.goes_at,
104 m.approved_at,
105 m.skipped_by_hand,
106 m.id,
107 );
108 }
109 db.query("DELETE FROM undo_send WHERE lead_id = ?1").run(leadId);
110 })();
111 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs