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

The agent can edit a reminder's words before sending, and the sent record keeps exactly what was approved #10

Merged opened this

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

Merged

mason/deal-clock:mason/5-the-agent-can-edit-a-reminder-s-words-be → main 5 commits fork 2 threads · 2 unresolved

  • Merged. mason/5-the-agent-can-edit-a-reminder-s-words-be was merged into main as fa34ea2.

Review

Sign in to review this change.
15 files changed +353 −74
README.md +11 −4
@@ -20,7 +20,10 @@ keeps the reason). Moving one date moves nothing else.
2020 Under the clock, **Reminders for today** lists what should go out this
2121 morning. Every open date reminds the parties it concerns — buyer, seller,
2222 lender, title company, the other agent — **three days before** and **the
23 morning of**. Open a draft to read it; tap **Send** to mark it sent.
23 morning of**. Open a draft to edit its subject (up to 150 characters) and message (up to
24 2000) in plain fields, then tap **Send**. What was approved is kept with the
25 send: a sent reminder shows those words, not the current draft, on the page,
26 in `/api/deals/:id`, in MCP and in the terminal.
2427
2528 **A deal's page** (tap its address) lists every date and party. Add a date
2629 the contract adds (an HOA review, a repair deadline), add the lender or the
@@ -67,7 +70,9 @@ stranger gets 401; it sends nothing and changes nothing). `GET /deals/:id/ics` i
6770 `/api/deals`, described at `/openapi.json`; the same operations are MCP
6871 tools at `POST /mcp` (`list_deals`, `get_deal`, `reminders_today`,
6972 `open_deal`, `add_date`, `add_party`, `mark_done` — with `done: false` to
70 reopen a date — `move_date`, `send_reminder`).
73 reopen a date — `move_date`, `send_reminder`). `send_reminder` takes an
74 optional `subject` and `body` to send edited words; without them the draft
75 goes as it is.
7176
7277 The terminal does the page's work too. It opens on every open date, soonest
7378 first: `n` opens a new deal (address, buyer, seller, contract date, closing
@@ -75,8 +80,10 @@ date; the standard lengths do the rest), `x` marks the date under the cursor
7580 done, `u` reopens it, `m` moves it (the new date, then the reason), `o` opens
7681 its deal — where `a` adds a date,
7782 `p` adds a party and `D` removes the deal after you type `yes` — and `h`
78 shows done dates. `r` lists today's reminders: enter reads a draft, `s`
79 sends it. `j`/`k` move, `b` goes back, `q` quits. What you change there
83 shows done dates. `r` lists today's reminders: enter reads a draft, `e`
84 types new words for it (a subject, then a message, where `\n` is a line
85 break and an empty answer keeps the draft's), and `s` sends what you read,
86 under the same limits as the page. `j`/`k` move, `b` goes back, `q` quits. What you change there
8087 shows on every open page within a second.
8188
8289 No runtime dependencies: Bun, `bun:sqlite`, and the browser's own popovers
contract/openapi.json +36 −1
@@ -666,7 +666,42 @@
666666 "sent": {
667667 "type": "array",
668668 "items": {
669 "type": "object"
669 "type": "object",
670 "properties": {
671 "id": {
672 "type": "integer"
673 },
674 "deadline_id": {
675 "type": "integer"
676 },
677 "party_id": {
678 "type": "integer"
679 },
680 "moment": {
681 "enum": [
682 "before",
683 "day_of"
684 ]
685 },
686 "due": {
687 "type": "string",
688 "format": "date"
689 },
690 "by_name": {
691 "type": "string"
692 },
693 "sent_at": {
694 "type": "string"
695 },
696 "subject": {
697 "type": "string",
698 "description": "The subject that was sent, as approved."
699 },
700 "body": {
701 "type": "string",
702 "description": "The message that was sent, as approved."
703 }
704 }
670705 }
671706 }
672707 },
src/db.test.ts +12
@@ -1,3 +1,4 @@
1 import { Database } from "bun:sqlite";
12 import { expect, test } from "bun:test";
23 import { mkdtempSync } from "node:fs";
34 import { addDays, today } from "./dates.ts";
@@ -62,3 +63,14 @@ test("sample deals boot looking like today, and a changed one is left alone", ()
6263 expect(move.to_due).toBe(addDays(today(), 2));
6364 expect(again.query("SELECT value FROM app_meta WHERE key = 'sample_anchor'").get()).toEqual({ value: today() });
6465 });
66
67 test("a database whose reminder columns came from another migration order still opens", () => {
68 const dir = mkdtempSync(join(tmpdir(), "app-db-order-"));
69 openDb(dir).close();
70 const raw = new Database(join(dir, "app.db"));
71 raw.exec("DELETE FROM schema_version WHERE version = (SELECT max(version) FROM schema_version)");
72 raw.close();
73 const db = openDb(dir);
74 expect(check(db).version).toBe(migrations.length);
75 expect(db.query("SELECT subject, body FROM reminder").all()).toEqual([]);
76 });
src/db.ts +12 −1
@@ -97,6 +97,10 @@ export const migrations: string[] = [
9797 // untouched ones forward from it on boot. A database seeded before this
9898 // anchored them to the day it was seeded.
9999 `INSERT OR IGNORE INTO app_meta (key, value) SELECT 'sample_anchor', value FROM app_meta WHERE key = 'seeded'`,
100 // The words a reminder went out with, exactly as approved. Rows sent
101 // before this carry '' and read as the draft they were sent from.
102 `ALTER TABLE reminder ADD COLUMN subject TEXT NOT NULL DEFAULT ''`,
103 `ALTER TABLE reminder ADD COLUMN body TEXT NOT NULL DEFAULT ''`,
100104 ];
101105
102106 export function openDb(dir = dataDir): Database {
@@ -124,7 +128,14 @@ export function migrate(db: Database): number {
124128 >("SELECT coalesce(max(version), 0) AS version FROM schema_version")
125129 .get()!.version;
126130 migrations.slice(current).forEach((sql, i) => {
127 db.exec(sql);
131 try {
132 db.exec(sql);
133 } catch (error) {
134 // A column added by a branch whose migrations ran in another order is
135 // already there; any other failure is real.
136 const again = /^ALTER TABLE \w+ ADD COLUMN/.test(sql) && String(error).includes("duplicate column name");
137 if (!again) throw error;
138 }
128139 db.query("INSERT INTO schema_version (version) VALUES (?1)").run(
129140 current + i + 1,
130141 );
src/deals.test.ts +30
@@ -220,6 +220,36 @@ test("reminders: three days before and the morning of, drafted in words, marked
220220 expect(moved.every((r) => r.sent_at === null)).toBe(true);
221221 });
222222
223 test("an edited send stores the edited words; an empty body is refused; a sent reminder keeps its words", () => {
224 const deal = open({ contractDate: addDays(today(), -5), closingDate: addDays(today(), 30), lengths: { inspection: "8" } });
225 const inspection = due(deal, "inspection");
226 const buyer = drafts(deal, agent).find((r) => r.deadline_id === inspection.id && r.moment === "before")!;
227 const ask = { deadlineId: inspection.id, partyId: buyer.party_id, moment: "before" };
228 const empty = sendReminder(db, alice, { ...ask, subject: "Hello", body: " \n " });
229 expect(empty.ok).toBe(false);
230 if (!empty.ok) expect(empty.error).toBe("invalid");
231 expect(sendReminder(db, alice, { ...ask, subject: "", body: "Hi" }).ok).toBe(false);
232 expect(sendReminder(db, alice, { ...ask, subject: "x".repeat(151), body: "Hi" }).ok).toBe(false);
233 expect(sendReminder(db, alice, { ...ask, subject: "Hello", body: "y".repeat(2001) }).ok).toBe(false);
234 expect(sendReminder(db, anon, { ...ask, subject: "Hello", body: "Hi" }).ok).toBe(false);
235 expect(fresh(deal.id).sent.length).toBe(0);
236 const sent = sendReminder(db, alice, { ...ask, subject: " Inspection <b>Friday</b> ", body: "Hi Ann,\r\nSee you there.\n\n\n\nDana" });
237 expect(sent.ok && [sent.value.subject, sent.value.body]).toEqual(["Inspection <b>Friday</b>", "Hi Ann,\nSee you there.\n\nDana"]);
238 // A second send keeps what was approved the first time.
239 sendReminder(db, alice, { ...ask, subject: "Other", body: "Other" });
240 expect(fresh(deal.id).sent.map((s) => s.subject)).toEqual(["Inspection <b>Friday</b>"]);
241 // Renaming the party leaves the record as it was sent.
242 db.query("UPDATE party SET name = 'Zed Renamed' WHERE id = ?1").run(buyer.party_id);
243 const again = drafts(fresh(deal.id), agent).find((r) => r.party_id === buyer.party_id && r.moment === "before")!;
244 expect(again.sent_at).not.toBeNull();
245 expect(again.subject).toBe("Inspection <b>Friday</b>");
246 expect(again.body).not.toContain("Zed");
247 // Sent with no words given, the draft as it stands is what is kept.
248 const plain = drafts(fresh(deal.id), agent).find((r) => r.moment === "before" && r.sent_at === null)!;
249 const kept = sendReminder(db, alice, { deadlineId: inspection.id, partyId: plain.party_id, moment: "before" });
250 expect(kept.ok && kept.value.body).toBe(plain.body);
251 });
252
223253 test("only the agent who opened a deal, or an admin, removes it", () => {
224254 const deal = open();
225255 expect(deleteDeal(db, bob, { id: deal.id }).ok).toBe(false);
src/deals.ts +39 −6
@@ -19,7 +19,9 @@ import {
1919 type Lengths,
2020 type PartyRole,
2121 } from "./deadlines.ts";
22 import { agent as defaultAgent } from "./env.ts";
2223 import { emit } from "./live.ts";
24 import { draftsFor, type Agent } from "./reminders.ts";
2325 import { audited, fail, ok, refuse, type Result } from "./result.ts";
2426 import type { Who } from "./who.ts";
2527
@@ -56,6 +58,9 @@ export interface Sent {
5658 readonly due: string;
5759 readonly by_name: string;
5860 readonly sent_at: string;
61 /** The words that went out, as approved; '' on a reminder sent before they were kept. */
62 readonly subject: string;
63 readonly body: string;
5964 }
6065 export interface Deadline {
6166 readonly id: number;
@@ -92,6 +97,21 @@ export function line(value: unknown, min: number, max: number): string | undefin
9297 return text.length >= min && text.length <= max ? text : undefined;
9398 }
9499
100 /** A message body from a person: line breaks kept, other control characters dropped, trimmed, within bounds. */
101 export function message(value: unknown, min: number, max: number): string | undefined {
102 if (typeof value !== "string") return undefined;
103 const text = value
104 .replace(/\r\n?/g, "\n")
105 .replace(/[\u0000-\u0009\u000b-\u001f\u007f-\u009f]+/g, " ")
106 .replace(/[ \t]+\n/g, "\n")
107 .replace(/\n{3,}/g, "\n\n")
108 .trim();
109 return text.length >= min && text.length <= max ? text : undefined;
110 }
111
112 export const SUBJECT_MAX = 150;
113 export const BODY_MAX = 2000;
114
95115 /** The name a row is written under: the person, as the forge signed them. */
96116 const authorOf = (who: Who): { id: string; name: string } =>
97117 who.role === "anon" ? { id: "", name: "" } : { id: who.id, name: who.name };
@@ -477,13 +497,14 @@ export function addParty(
477497 }
478498
479499 /**
480 * Mark a reminder sent. The prototype sends nothing: the draft is shown, and
481 * this records that the agent sent it, to that party, about that date.
500 * Mark a reminder sent, with the words the agent approved: the subject and
501 * body given, or — when neither is given — the draft as it stands. The words
502 * are stored with the send and are what the record shows from then on.
482503 */
483504 export function sendReminder(
484505 db: Database,
485506 who: Who,
486 input: { deadlineId: number; partyId: number; moment: unknown },
507 input: { deadlineId: number; partyId: number; moment: unknown; subject?: unknown; body?: unknown; agent?: Agent },
487508 ): Result<Sent> {
488509 const { dealId, found } = deadlineFor(db, who, input.deadlineId);
489510 if (!found.ok) return within(db, who, dealId, found);
@@ -497,11 +518,23 @@ export function sendReminder(
497518 if (party === null)
498519 return within(db, who, dealId, fail("not_found", "No such party on this deal."));
499520 const { deadline } = found.value;
521 const draft = draftsFor(
522 view(db, found.value.deal),
523 { ...deadline, moves: [] },
524 input.agent ?? defaultAgent,
525 ).find((r) => r.party_id === party.id && r.moment === input.moment);
526 const subject =
527 input.subject === undefined ? draft?.subject : line(input.subject, 1, SUBJECT_MAX);
528 if (subject === undefined)
529 return within(db, who, dealId, fail("invalid", `The subject is 1 to ${SUBJECT_MAX} characters.`));
530 const body = input.body === undefined ? draft?.body : message(input.body, 1, BODY_MAX);
531 if (body === undefined)
532 return within(db, who, dealId, fail("invalid", `The message is 1 to ${BODY_MAX} characters.`));
500533 const sent = db
501 .query<Sent, [number, number, string, string, string]>(
502 `INSERT INTO reminder (deadline_id, party_id, moment, due, by_name) VALUES (?1, ?2, ?3, ?4, ?5)
534 .query<Sent, [number, number, string, string, string, string, string]>(
535 `INSERT INTO reminder (deadline_id, party_id, moment, due, by_name, subject, body) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
503536 ON CONFLICT (deadline_id, party_id, moment, due) DO UPDATE SET sent_at = sent_at RETURNING *`,
504537 )
505 .get(deadline.id, party.id, input.moment, deadline.due, authorOf(who).name)!;
538 .get(deadline.id, party.id, input.moment, deadline.due, authorOf(who).name, subject, body)!;
506539 return within(db, who, dealId, ok(sent));
507540 }
src/mcp.ts +5 −2
@@ -84,18 +84,21 @@ export const tools: readonly Tool[] = [
8484 },
8585 {
8686 name: "send_reminder",
87 description: "Mark a reminder sent to one party (simulated: nothing is emailed).",
87 description:
88 "Mark a reminder sent to one party (simulated: nothing is emailed). Give subject and body to send your edited words (subject up to 150 characters, body up to 2000); leave them out to send the draft as it is. The answer holds the words that were sent.",
8889 inputSchema: {
8990 type: "object",
9091 properties: {
outdated

New subject/body arguments have no MCP test (edited words kept, invalid refused).

9192 deadline_id: { type: "integer" },
9293 party_id: { type: "integer" },
9394 moment: { enum: ["before", "day_of"] },
95 subject: { type: "string", minLength: 1, maxLength: 150 },
96 body: { type: "string", minLength: 1, maxLength: 2000 },
9497 },
9598 required: ["deadline_id", "party_id", "moment"],
9699 },
97100 run: (db, who, args) =>
98 sendReminder(db, who, { deadlineId: Number(args.deadline_id), partyId: Number(args.party_id), moment: args.moment }),
101 sendReminder(db, who, { deadlineId: Number(args.deadline_id), partyId: Number(args.party_id), moment: args.moment, subject: args.subject, body: args.body }),
99102 },
100103 {
101104 name: "open_deal",
src/pages/clock.ts +1 −1
@@ -124,7 +124,7 @@ export function clock(input: {
124124 ${
125125 today.length === 0
126126 ? `<p class="muted">Nothing goes out today.</p>`
127 : `<ul class="drafts">${today.map(({ r, may }) => draftItem(r, on, may, "/", true, true)).join("")}</ul>`
127 : `<ul class="drafts">${today.map(({ r, may }) => draftItem(r, on, may, "/", true)).join("")}</ul>`
128128 }
129129 <p class="muted small">Each date reminds its parties three days before and the morning of. Sending is simulated: the draft is shown and marked sent.</p>
130130 </section>`;
src/pages/sheet.ts +16 −13
@@ -5,7 +5,7 @@
55 * script; the forms post and come back.
66 */
77
8 import { canChange, type DealView, type DeadlineView } from "../deals.ts";
8 import { BODY_MAX, canChange, SUBJECT_MAX, type DealView, type DeadlineView } from "../deals.ts";
99 import { relative, short, spoken, urgency, type Urgency } from "../dates.ts";
1010 import { PARTY_LABEL } from "../deadlines.ts";
1111 import { agent } from "../env.ts";
@@ -54,11 +54,20 @@ const draftText = (draft: Draft): string => `<div class="draft-text">
5454 <p class="draft-body">${escape(draft.body)}</p>
5555 </div>`;
5656
57 /** Where a reminder is edited and sent: its words in plain fields, prefilled with the draft. */
58 const sendForm = (draft: Draft, to: string): string =>
59 `<form class="move" method="post" action="/reminders">${hidden({ deadline: draft.deadline_id, party: draft.party_id, moment: draft.moment, to })}
60 <p class="muted">To ${escape(draft.contact || draft.party_name)}</p>
61 <label>Subject<input class="input" name="subject" value="${escape(draft.subject)}" maxlength="${SUBJECT_MAX}" required></label>
62 <label>Message<textarea class="input" name="body" rows="9" maxlength="${BODY_MAX}" required>${escape(draft.body)}</textarea></label>
63 <button class="button">Send</button>
64 </form>`;
65
5766 /**
58 * One reminder: who, when, and the one tap that marks it sent. `withText`
59 * folds its words in beneath; a sheet shows the words once per moment instead.
67 * One reminder: who, when, and its words. Opened, an unsent draft is a form
68 * the agent may edit before *Send*; a sent one shows the words that went out.
6069 */
61 export function draftItem(draft: Draft, on: string, may: boolean, to: string, withText = true, withDeal = false): string {
70 export function draftItem(draft: Draft, on: string, may: boolean, to: string, withDeal = false): string {
6271 const state =
6372 draft.sent_at !== null
6473 ? `<span class="state" data-sent>Sent ${escape(short(draft.sent_at.slice(0, 10)))}</span>`
@@ -67,12 +76,9 @@ export function draftItem(draft: Draft, on: string, may: boolean, to: string, wi
6776 : draft.on === on
6877 ? `<span class="state" data-today>Goes out today</span>`
6978 : `<span class="state">Goes out ${escape(short(draft.on))}</span>`;
70 const send =
71 may && draft.sent_at === null
72 ? `<form method="post" action="/reminders">${hidden({ deadline: draft.deadline_id, party: draft.party_id, moment: draft.moment, to })}<button class="button button-small">Send</button></form>`
73 : "";
7479 const who = `<span><b>${escape(draft.party_name)}</b> <span class="muted">· ${escape(PARTY_LABEL[draft.party_role])}${withDeal ? ` · ${escape(draft.label)}, ${escape(draft.address)}` : ""}</span></span>${state}`;
75 return `<li class="draft">${withText ? `<details><summary>${who}</summary>${draftText(draft)}</details>` : `<div class="draft-who">${who}</div>`}${send}</li>`;
80 const inside = may && draft.sent_at === null ? sendForm(draft, to) : draftText(draft);
81 return `<li class="draft"><details><summary>${who}</summary>${inside}</details></li>`;
7682 }
7783
7884 export function sheet(deal: DealView, d: DeadlineView, who: Who, on: string, to: string): string {
@@ -87,10 +93,7 @@ export function sheet(deal: DealView, d: DeadlineView, who: Who, on: string, to:
8793 : MOMENTS.map((m) => {
8894 const these = drafts.filter((r) => r.moment === m);
8995 const head = `<h4>${MOMENT_LABEL[m]} <span class="muted">· ${escape(spoken(these[0]!.on))}</span></h4>`;
90 if (these.every((r) => r.sent_at !== null))
91 return `${head}<p class="muted small">Sent to all ${these.length}.</p>`;
92 return `${head}<details class="draft-preview"><summary>Read the draft</summary>${draftText(these[0]!)}<p class="muted small">Each party gets it addressed to them.</p></details>
93 <ul class="drafts">${these.map((r) => draftItem(r, on, may, to, false)).join("")}</ul>`;
96 return `${head}<ul class="drafts">${these.map((r) => draftItem(r, on, may, to)).join("")}</ul>`;
9497 }).join("");
9598 const moves =
9699 d.moves.length === 0
src/reminders.ts +29 −23
@@ -2,7 +2,8 @@
22 * Reminders, drafted. Every open date of a deal reminds each party it
33 * concerns twice: three days before, and the morning of. A draft is plain
44 * data — who, when, the words — computed from a deal; nothing is sent
5 * anywhere. `sendReminder` (`deals.ts`) records that the agent sent one.
5 * anywhere. `sendReminder` (`deals.ts`) records that the agent sent one, with
6 * the words approved; a sent draft reads back those words.
67 */
78
89 import { addDays, spoken } from "./dates.ts";
@@ -79,28 +80,33 @@ export function drafts(deal: DealView, agent: Agent): Draft[] {
7980 /** The reminders one date has, sent or not. */
8081 export function draftsFor(deal: DealView, deadline: DeadlineView, agent: Agent): Draft[] {
8182 return MOMENTS.flatMap((moment) =>
82 recipients(deal, deadline).map((party) => ({
83 deal_id: deal.id,
84 address: deal.address,
85 deadline_id: deadline.id,
86 label: deadline.label,
87 due: deadline.due,
88 party_id: party.id,
89 party_name: party.name,
90 party_role: party.role,
91 contact: party.contact,
92 moment,
93 on: sendOn(deadline.due, moment),
94 ...words(deal, deadline, party, moment, agent),
95 sent_at:
96 deal.sent.find(
97 (s) =>
98 s.deadline_id === deadline.id &&
99 s.party_id === party.id &&
100 s.moment === moment &&
101 s.due === deadline.due,
102 )?.sent_at ?? null,
103 })),
83 recipients(deal, deadline).map((party) => {
84 const sent = deal.sent.find(
85 (s) =>
86 s.deadline_id === deadline.id &&
87 s.party_id === party.id &&
88 s.moment === moment &&
89 s.due === deadline.due,
90 );
91 const drafted = words(deal, deadline, party, moment, agent);
92 return {
93 deal_id: deal.id,
94 address: deal.address,
95 deadline_id: deadline.id,
96 label: deadline.label,
97 due: deadline.due,
98 party_id: party.id,
99 party_name: party.name,
100 party_role: party.role,
101 contact: party.contact,
102 moment,
103 on: sendOn(deadline.due, moment),
104 // A sent reminder keeps the words it went with, whatever the deal says now.
105 subject: sent !== undefined && sent.subject !== "" ? sent.subject : drafted.subject,
106 body: sent !== undefined && sent.subject !== "" ? sent.body : drafted.body,
107 sent_at: sent?.sent_at ?? null,
108 };
109 }),
104110 );
105111 }
106112
src/routes.ts +18 −2
@@ -140,7 +140,23 @@ export const DEAL: Schema = {
140140 },
141141 },
142142 },
143 sent: { type: "array", items: { type: "object" } },
143 sent: {
144 type: "array",
145 items: {
146 type: "object",
147 properties: {
148 id: { type: "integer" },
149 deadline_id: { type: "integer" },
150 party_id: { type: "integer" },
151 moment: { enum: ["before", "day_of"] },
152 due: DATE,
153 by_name: { type: "string" },
154 sent_at: { type: "string" },
155 subject: { type: "string", description: "The subject that was sent, as approved." },
156 body: { type: "string", description: "The message that was sent, as approved." },
157 },
158 },
159 },
144160 },
145161 required: ["id", "address", "contract_date", "closing", "parties", "deadlines"],
146162 };
@@ -385,7 +401,7 @@ export const routes: readonly Route[] = [
385401 const f = await form(c);
386402 if (f instanceof Response) return f;
387403 return done(
388 sendReminder(c.db, c.who, { deadlineId: Number(f.deadline), partyId: Number(f.party), moment: f.moment }),
404 sendReminder(c.db, c.who, { deadlineId: Number(f.deadline), partyId: Number(f.party), moment: f.moment, subject: f.subject, body: f.body }),
389405 backTo(f.to),
390406 "Reminder sent (simulated).",
391407 );
src/server.test.ts +62 −1
@@ -467,10 +467,15 @@ test("the clock's forms: mark done, move with a reason, send a reminder, and com
467467 expect(decodeURIComponent(guest.headers.get("set-cookie") ?? "")).toContain("Sign in");
468468 const sent = await post("/reminders", { deadline: String(second!.id), party: String(deal.parties[0]!.id), moment: "before" });
469469 expect(sent.status).toBe(303);
470 const edited = await post("/reminders", { deadline: String(second!.id), party: String(deal.parties[1]!.id), moment: "day_of", subject: "Edited <i>subject</i>", body: "My own words" });
471 expect(edited.status).toBe(303);
472 const blank = await post("/reminders", { deadline: String(first!.id), party: String(deal.parties[0]!.id), moment: "day_of", subject: "Hi", body: " " });
473 expect(decodeURIComponent(blank.headers.get("set-cookie") ?? "")).toContain("1 to 2000");
470474 const after = (await (await api(`/api/deals/${deal.id}`, {}, alice)).json()) as {
471475 deadlines: { id: number; due: string; moves: { reason: string }[] }[];
472 sent: { deadline_id: number }[];
476 sent: { deadline_id: number; subject: string; body: string }[];
473477 };
478 expect(after.sent.some((s) => s.subject === "Edited <i>subject</i>" && s.body === "My own words")).toBe(true);
474479 const movedRow = after.deadlines.find((x) => x.id === second!.id)!;
475480 expect(movedRow.due).toBe("2027-01-04");
476481 expect(movedRow.moves.map((m) => m.reason)).toEqual(["Lender extension"]);
@@ -511,3 +516,59 @@ test("a form route answers 4xx, never 500, to a body that is not a form", async
511516 for (const path of ["/deals", "/reminders", "/deals/1/deadlines", "/deals/1/parties", "/deadlines/1/move"])
512517 expect([path, (await api(path, { method: "POST", redirect: "manual" }, formless)).status]).toEqual([path, 415]);
513518 });
519
520 const editor = as("u7", "editor");
521
522 test("MCP send_reminder takes edited words, refuses bad ones, and answers with what was sent", async () => {
523 const call = (args: unknown, who: Record<string, string> = editor) =>
524 rpc({ jsonrpc: "2.0", id: 9, method: "tools/call", params: { name: "send_reminder", arguments: args } }, who);
525 const deals = (await (await api("/api/deals", {}, editor)).json()) as {
526 id: number;
527 deadlines: { id: number; owes: string; done_at: string | null }[];
528 parties: { id: number; role: string }[];
529 }[];
530 const deal = deals.find((d) => d.deadlines.some((x) => x.done_at === null))!;
531 const deadline = deal.deadlines.find((x) => x.done_at === null)!;
532 const party = deal.parties.find((p) => p.role === deadline.owes)!;
533 const ask = { deadline_id: deadline.id, party_id: party.id, moment: "day_of" };
534 for (const bad of [{ body: " " }, { subject: "" }, { subject: "s".repeat(151) }, { body: "b".repeat(2001) }]) {
535 const refused = await call({ ...ask, subject: "Fine", body: "Fine", ...bad });
536 expect(refused.result.isError).toBe(true);
537 }
538 expect((await call({ ...ask, subject: "Hi", body: "Hi" }, {})).result.isError).toBe(true);
539 const sent = await call({ ...ask, subject: "Edited via MCP", body: "These are my words." });
540 expect(sent.result.isError).toBeUndefined();
541 expect(JSON.parse(sent.result.content[0].text)).toMatchObject({ subject: "Edited via MCP", body: "These are my words." });
542 const got = await call({ ...ask, subject: "Ignored", body: "Ignored" });
543 expect(JSON.parse(got.result.content[0].text).subject).toBe("Edited via MCP");
544 const read = await rpc(
545 { jsonrpc: "2.0", id: 10, method: "tools/call", params: { name: "get_deal", arguments: { id: deal.id } } },
546 editor,
547 );
548 expect(JSON.parse(read.result.content[0].text).sent.map((s: { subject: string }) => s.subject)).toContain("Edited via MCP");
549 });
550
551 test("the page offers an unsent draft as an edit form, and shows a sent one as it was sent, escaped", async () => {
552 const deals = (await (await api("/api/deals", {}, editor)).json()) as {
553 id: number;
554 deadlines: { id: number; owes: string; done_at: string | null }[];
555 parties: { id: number; role: string; name: string }[];
556 sent: { deadline_id: number }[];
557 }[];
558 const deal = deals[deals.length - 1]!;
559 const deadline = deal.deadlines.find((x) => x.done_at === null && !deal.sent.some((s) => s.deadline_id === x.id))!;
560 const party = deal.parties.find((p) => p.role === deadline.owes)!;
561 const before = await (await api("/", {}, editor)).text();
562 expect(before).toContain('name="subject" value="');
563 expect(before).toContain('<textarea class="input" name="body"');
564 const guest = await (await fetch(base + "/")).text();
565 expect(guest).not.toContain('name="subject"');
566 const form = new FormData();
567 for (const [k, v] of Object.entries({ deadline: String(deadline.id), party: String(party.id), moment: "before", subject: "Sent <u>words</u>", body: "Sent <script>x</script> body", to: "/" }))
568 form.set(k, v);
569 expect((await api("/reminders", { method: "POST", body: form, redirect: "manual" }, editor)).status).toBe(303);
570 const after = await (await api("/", {}, editor)).text();
571 expect(after).toContain("Sent &lt;u&gt;words&lt;/u&gt;");
572 expect(after).toContain("Sent &lt;script&gt;x&lt;/script&gt; body");
573 expect(after).not.toContain("<script>x</script>");
574 });
src/terminal.test.ts +29
@@ -115,6 +115,35 @@ test("r shows today's reminders; enter reads a draft; s sends it", () => {
115115 expect(under(t)).not.toBe(row);
116116 const sent = db.query<{ n: number }, []>("SELECT count(*) AS n FROM reminder").get()!.n;
117117 expect(sent).toBe(1);
118 // `s` sent the draft unchanged: its words are what the record keeps.
119 const kept = db.query<{ body: string }, []>("SELECT body FROM reminder").get()!.body;
120 expect(kept).toContain("Hi ");
121 });
122
123 test("e types new words for a reminder; s sends those words; anon is not asked to type", () => {
124 const guest = terminal(db, { role: "anon" }, context);
125 guest.press("r");
126 guest.press("e");
127 expect(lines(guest).join("\n")).not.toContain("Subject (enter keeps");
128 const before = db.query<{ n: number }, []>("SELECT count(*) AS n FROM reminder").get()!.n;
129 const t = terminal(db, alice, context);
130 t.press("r");
131 press(t, "e", "Edited subject\r", "My own words.\\nSecond line.\r");
132 expect(lines(t).join("\n")).toContain("Edited: read it here");
133 expect(lines(t).join("\n")).toContain("Edited subject");
134 expect(db.query<{ n: number }, []>("SELECT count(*) AS n FROM reminder").get()!.n).toBe(before);
135 t.press("s");
136 const row = db.query<{ subject: string; body: string }, []>("SELECT subject, body FROM reminder ORDER BY id DESC").get()!;
137 expect(row).toEqual({ subject: "Edited subject", body: "My own words.\nSecond line." });
138 });
139
140 test("e with an empty answer keeps that part of the draft; too long a message is refused at send", () => {
141 const t = terminal(db, alice, context);
142 t.press("r");
143 press(t, "e", "\r", "x".repeat(10) + "\r", "s");
144 const row = db.query<{ subject: string; body: string }, []>("SELECT subject, body FROM reminder ORDER BY id DESC").get()!;
145 expect(row.body).toBe("xxxxxxxxxx");
146 expect(row.subject).toContain(" — ");
118147 });
119148
120149 test("n opens a deal from five answers, and shows it", () => {
src/terminal.ts +49 −14
@@ -4,7 +4,7 @@
44 * a pty; a test presses keys and reads the screen. Three views:
55 *
66 * dates every open date of every deal, soonest first (h shows done ones)
7 * reminders what goes out today; enter reads a draft, s sends it
7 * reminders what goes out today; enter reads a draft, e edits its words, s sends it
88 * deal one deal's dates and parties; a adds a date, p a party, D removes it
99 *
1010 * On a date (dates or deal view): x marks it done, u reopens it, m moves it
@@ -18,6 +18,7 @@ import { isDate, relative, spoken, today, urgency, type Urgency } from "./dates.
1818 import {
1919 addDeadline,
2020 addParty,
21 BODY_MAX,
2122 canChange,
2223 createDeal,
2324 deleteDeal,
@@ -50,6 +51,8 @@ interface Prompt {
5051 readonly steps: readonly string[];
5152 readonly answers: string[];
5253 text: string;
54 /** Longest an answer may be; 200 unless the step asks for more. */
55 readonly max?: number;
5356 readonly finish: (answers: readonly string[]) => string;
5457 }
5558
@@ -72,6 +75,8 @@ export function terminal(
7275 let dealId: number | undefined;
7376 let showDone = false;
7477 let reading: number | undefined;
78 /** Words typed with `e` and not yet sent, by reminder; `s` sends them. */
79 const edits = new Map<string, { subject: string; body: string }>();
7580 let prompt: Prompt | undefined;
7681 let said = "";
7782 let done = false;
@@ -105,16 +110,19 @@ export function terminal(
105110 .map((draft) => ({ deal, draft })),
106111 );
107112 };
113 const editKey = (d: Draft): string => `${d.deadline_id}:${d.party_id}:${d.moment}`;
114 /** The draft with any words typed for it; a sent one is as it went. */
115 const edited = (d: Draft): Draft => (d.sent_at === null ? { ...d, ...edits.get(editKey(d)) } : d);
108116 const rowCount = (): number => (view === "reminders" ? reminderRows().length : dateRows().length);
109117
110118 const report = <T>(result: Result<T>, success: string): string => (result.ok ? success : result.message);
111119 /** Only someone who may work the deal is asked to type anything. */
112 const ask = (deal: DealView, steps: string[], finish: Prompt["finish"]): void => {
120 const ask = (deal: DealView, steps: string[], finish: Prompt["finish"], max?: number): void => {
113121 if (!canChange(me, deal)) {
114122 said = me.role === "anon" ? "Sign in to change a deal." : "You may not change this deal.";
115123 return;
116124 }
117 prompt = { steps, answers: [], text: "", finish };
125 prompt = { steps, answers: [], text: "", ...(max === undefined ? {} : { max }), finish };
118126 };
119127
120128 function onDate(key: string): boolean {
@@ -170,19 +178,44 @@ export function terminal(
170178 }
171179
172180 function onReminder(key: string): boolean {
173 if (key !== "\r" && key !== "s") return false;
181 if (key !== "\r" && key !== "s" && key !== "e") return false;
174182 const row = reminderRows()[cursor];
175183 if (row === undefined) {
outdated

Send always uses draft.subject/draft.body; there is no way to edit words here, unlike the page. Add an edit step and a test.

176184 said = "No reminder here.";
177185 return true;
178186 }
179 const { draft } = row;
187 const { deal, draft: drafted } = row;
188 const id = editKey(drafted);
189 const draft = edited(drafted);
180190 if (key === "\r") reading = reading === cursor ? undefined : cursor;
181 if (key === "s")
182 said = report(
183 sendReminder(db, me, { deadlineId: draft.deadline_id, partyId: draft.party_id, moment: draft.moment }),
184 `Sent to ${draft.party_name} (simulated): ${draft.label}, ${draft.address}.`,
185 );
191 if (key === "e") {
192 if (drafted.sent_at !== null) said = "Already sent; its words are kept as they went.";
193 else
194 ask(
195 deal,
196 [`Subject (enter keeps: ${draft.subject})`, "Message (\\n is a line break; enter keeps it)"],
197 ([subject, body]) => {
198 edits.set(id, {
199 subject: subject || draft.subject,
200 body: body ? body.replaceAll("\\n", "\n") : draft.body,
201 });
202 reading = cursor;
203 return "Edited: read it here, s sends it.";
204 },
205 BODY_MAX,
206 );
207 }
208 if (key === "s") {
209 const sent = sendReminder(db, me, {
210 deadlineId: draft.deadline_id,
211 partyId: draft.party_id,
212 moment: draft.moment,
213 subject: draft.subject,
214 body: draft.body,
215 });
216 if (sent.ok) edits.delete(id);
217 said = report(sent, `Sent to ${draft.party_name} (simulated): ${draft.label}, ${draft.address}.`);
218 }
186219 return true;
187220 }
188221
@@ -207,7 +240,7 @@ export function terminal(
207240 said = p.finish(p.answers);
208241 return;
209242 }
210 } else if (ch >= " " && p.text.length < 200) p.text += ch;
243 } else if (ch >= " " && p.text.length < (p.max ?? 200)) p.text += ch;
211244 }
212245 }
213246
@@ -300,8 +333,10 @@ export function terminal(
300333 const state = draft.sent_at !== null ? dim("sent") : draft.on < day ? tint("overdue", "late") : tint("soon", "to send");
301334 const text = `${draft.party_name} (${PARTY_LABEL[draft.party_role].toLowerCase()}) · ${draft.label}, ${draft.address} · ${MOMENT_LABEL[draft.moment].toLowerCase()}`;
302335 lines.push(`${i === cursor ? "▸" : " "} ${state.padEnd(16)} ${i === cursor ? bold(text) : text}`);
303 if (reading === i)
304 lines.push("", ` ${bold(draft.subject)}`, ...draft.body.split("\n").map((l) => ` ${l}`), "");
336 if (reading === i) {
337 const words = edited(draft);
338 lines.push("", ` ${bold(words.subject)}`, ...words.body.split("\n").map((l) => ` ${l}`), "");
339 }
305340 });
306341 }
307342 lines.push("");
@@ -311,7 +346,7 @@ export function terminal(
311346 if (said !== "") lines.push(said);
312347 const keys =
313348 view === "reminders"
314 ? "j/k move · enter read · s send · d dates · q quit"
349 ? "j/k move · enter read · e edit · s send · d dates · q quit"
315350 : view === "deal"
316351 ? "j/k move · x done · u reopen · m move · a add date · p add party · D remove · b back · q quit"
317352 : `j/k move · x done · u reopen · m move · o open deal · n new deal · h ${showDone ? "hide" : "show"} done · r reminders · q quit`;
static/app.css +4 −6
@@ -707,10 +707,8 @@ select.input {
707707 min-height: var(--size-tap);
708708 padding: var(--space-1) 0;
709709 }
710 .draft-preview summary {
711 display: flex;
712 align-items: center;
713 min-height: var(--size-tap);
714 color: var(--color-accent);
715 cursor: pointer;
710 textarea.input {
711 padding: var(--space-2) var(--space-3);
712 min-height: calc(var(--size-tap) * 2);
713 resize: vertical;
716714 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs