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

The agent holds a reminder until tomorrow with one tap, so a message they are not ready to approve waits instead of being declined or lost #103

Merged opened this

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

Merged

mason/deal-clock:mason/100-the-agent-holds-a-reminder-until-tomorro → main 2 commits fork 1 thread · 1 unresolved

  • Merged. mason/100-the-agent-holds-a-reminder-until-tomorro was merged into main as c2378cc.

Review

Sign in to review this change.
20 files changed +478 −26
README.md +1
@@ -75,6 +75,7 @@ Signed out, `/` shows what deal-clock does, three short points, a still picture
7575 Decided against a message? Beside Send, **Don't send** asks why (up to 200
7676 characters). The reminder stops counting as "to send" and reads "Not sent:
7777 <reason> · <who>"; the reason is kept, and **Undo** makes it a draft again.
78 Not ready to approve one? **Tomorrow** holds it: it leaves today's list and the count, and returns at the top tomorrow as "Held from <weekday>" with your edited words (hold it again to push it another day). In the terminal, press h on the reminders list.
7879 To keep a client informed about the whole deal, a deal's page also has a
7980 **Status update** card for each buyer and seller with an email or phone: a
8081 draft of what is done, what is next and who owes it, and when it closes,
contract/openapi.json +89
@@ -1441,6 +1441,95 @@
14411441 }
14421442 }
14431443 },
1444 "/api/deals/{id}/reminders/hold": {
1445 "post": {
1446 "summary": "Hold a reminder until tomorrow: it leaves today's list and /tick, and comes back the next morning with its words. Held again, it waits one more day. A status update is not held.",
1447 "operationId": "postApiDealsIdRemindersHold",
1448 "parameters": [
1449 {
1450 "name": "id",
1451 "in": "path",
1452 "required": true,
1453 "schema": {
1454 "type": "integer"
1455 }
1456 }
1457 ],
1458 "requestBody": {
1459 "required": true,
1460 "content": {
1461 "application/json": {
1462 "schema": {
1463 "type": "object",
1464 "properties": {
1465 "deadline_id": {
1466 "type": "integer"
1467 },
1468 "party_id": {
1469 "type": "integer"
1470 },
1471 "moment": {
1472 "enum": [
1473 "before",
1474 "day_of",
1475 "late",
1476 "moved"
1477 ]
1478 }
1479 },
1480 "required": [
1481 "deadline_id",
1482 "party_id",
1483 "moment"
1484 ]
1485 }
1486 }
1487 }
1488 },
1489 "responses": {
1490 "201": {
1491 "description": "Hold a reminder until tomorrow: it leaves today's list and /tick, and comes back the next morning with its words. Held again, it waits one more day. A status update is not held.",
1492 "content": {
1493 "application/json": {
1494 "schema": {
1495 "type": "object",
1496 "properties": {
1497 "id": {
1498 "type": "integer"
1499 },
1500 "until": {
1501 "type": "string"
1502 },
1503 "by_name": {
1504 "type": "string"
1505 }
1506 },
1507 "required": [
1508 "id",
1509 "until"
1510 ]
1511 }
1512 }
1513 }
1514 },
1515 "default": {
1516 "description": "{ error, message }: why not",
1517 "content": {
1518 "application/json": {
1519 "schema": {
1520 "$ref": "#/components/schemas/Error"
1521 }
1522 }
1523 }
1524 }
1525 },
1526 "x-contract": {
1527 "resource": "deal",
1528 "verb": "update",
1529 "least": "user"
1530 }
1531 }
1532 },
14441533 "/api/deals/{id}/reminders/undo": {
14451534 "post": {
14461535 "summary": "Take back a decline: the reminder is a draft again.",
docs/TECHNICAL.md +7
@@ -102,6 +102,13 @@ sent until undone. Over the API: `POST /api/deals/:id/reminders/decline` and
102102 `decline_reminder` and `undo_decline_reminder`; in the terminal, `n` then the
103103 reason on the reminders list, and `u` to undo. Each is an update of the deal.
104104
105 A hold (`holdReminder`) is a row of `reminder_hold`, keyed like a sent or declined
106 reminder (`deadline_id`, `party_id`, `moment`, `due`, `move_id`) with the morning it
107 returns (`until`). It leaves `todaysDrafts`, the waiting count and `/tick` until then,
108 returns at the top as "Held from <weekday>", and holding again pushes `until` one more
109 day. Posts: `/reminders/hold`, `/reminders/today/hold`, `POST /api/deals/:id/reminders/hold`;
110 MCP `hold_reminder`; in the terminal, `h` on the reminders list. A reminder can be held only from its send morning on. Audited as `reminder.hold:<until>`. Same `deal` update cell as Send.
111
105112 `GET /deals/:id/sheets` is an HTML fragment: every date's sheet for one deal. The clock carries
106113 no sheets (they were most of its size); `sheets.js` fetches a deal's the first time one of its dates is tapped,
107114 and without script the date is a link to `/deals/:id#sheet-N`; the deal page has its sheets inline,
src/actions.ts +2 −2
@@ -7,7 +7,7 @@
77 */
88
99 import type { Database } from "bun:sqlite";
10 import { MESSAGE_WHATS, type AuditRow } from "./audit.ts";
10 import { HOLD_WHAT, MESSAGE_WHATS, type AuditRow } from "./audit.ts";
1111 import { permit } from "./contract.ts";
1212 import { emit } from "./live.ts";
1313 import { audited, fail, ok, refuse, type Result } from "./result.ts";
@@ -43,7 +43,7 @@ export function listAudit(
4343 : Number.MAX_SAFE_INTEGER;
4444 const kept =
4545 input.only === "messages"
46 ? ` AND what IN (${MESSAGE_WHATS.map((w) => `'${w}'`).join(", ")})`
46 ? ` AND (what IN (${MESSAGE_WHATS.map((w) => `'${w}'`).join(", ")}) OR what LIKE '${HOLD_WHAT}:%')`
4747 : "";
4848 return ok(
4949 db
src/activity.ts +10 −1
@@ -5,7 +5,8 @@
55 */
66
77 import type { Database } from "bun:sqlite";
8 import type { AuditRow } from "./audit.ts";
8 import { HOLD_WHAT, type AuditRow } from "./audit.ts";
9 import { isDate, spoken } from "./dates.ts";
910
1011 /** Rows to a page; a door asks for one more to know whether there is an older page. */
1112 export const ACTIVITY_PAGE = 100;
@@ -14,6 +15,7 @@ export const ACTIVITY_PAGE = 100;
1415 const WORDS: Readonly<Record<string, string>> = {
1516 "reminder.send": "sent a reminder",
1617 "reminder.decline": "declined a reminder",
18 "reminder.hold": "held a reminder",
1719 "reminder.undo": "undid a declined reminder",
1820 "date.move": "moved a date",
1921 "date.done": "marked a date done",
@@ -50,7 +52,14 @@ const AT = new Intl.DateTimeFormat("en-US", {
5052 timeZoneName: "short",
5153 });
5254
55 /** "held a reminder until Wed, Nov 4": a hold's audit name carries the day it comes back. */
56 const heldWords = (what: string | null): string | undefined => {
57 const until = what?.startsWith(`${HOLD_WHAT}:`) ? what.slice(HOLD_WHAT.length + 1) : "";
58 return isDate(until) ? `held a reminder until ${spoken(until)}` : undefined;
59 };
60
5361 export const wording = (row: Pick<AuditRow, "resource" | "verb" | "what">): string =>
62 heldWords(row.what) ||
5463 (row.what !== null && WORDS[row.what]) || WORDS[`${row.resource} ${row.verb}`] || `${row.resource} ${row.verb}`;
5564
5665 /** "Fri, Oct 16, 3:04 PM UTC" from the stored ISO time; the text itself if it does not read. */
src/audit.ts +3 −1
@@ -41,8 +41,10 @@ export interface Attempt {
4141 readonly what?: string | undefined;
4242 }
4343
44 /** The changes that are a message's life: sent, declined, undone. The Activity page's `only=messages`. */
44 /** The changes that are a message's life: sent, declined, held, undone. The Activity page's `only=messages`. */
4545 export const MESSAGE_WHATS = ["reminder.send", "reminder.decline", "reminder.undo"] as const;
46 /** A hold is audited as `reminder.hold:<the day it comes back>`. */
47 export const HOLD_WHAT = "reminder.hold";
4648
4749 /** The newest rows kept; older ones go as new ones come. */
4850 export const KEEP = 50_000;
src/contract.test.ts +18
@@ -14,6 +14,7 @@ import {
1414 createDeal,
1515 deleteDeal,
1616 getDeal,
17 holdReminder,
1718 listDeals,
1819 sendStatusUpdate,
1920 statusUpdates,
@@ -179,6 +180,23 @@ test("the status update, at GET /api/deals/:id/status, its send and the two MCP
179180 expect(sendStatusUpdate(db, { role: "anon" }, { dealId: dealBy("u1"), partyId: 1 }).ok).toBe(false);
180181 });
181182
183 test("holding a reminder answers as deal update says, as every identity", () => {
184 for (const identity of identities(contract)) {
185 const who = whoIs(identity);
186 const { mine, theirs } = actingAs(contract, identity);
187 for (const row of [mine, theirs]) {
188 const id = dealBy(String(row["author_id"]));
189 const said = `hold as ${identity} on ${String(row["author_id"])}`;
190 const allowed = permit(who, "deal", "update", row) === "yes";
191 const deadline = db.query<{ id: number }, [number]>("INSERT INTO deadline (deal_id, kind, label, due, owes) VALUES (?1, 'closing', 'Closing', '2026-11-01', 'buyer') RETURNING id").get(id)!.id;
192 const party = db.query<{ id: number }, [number]>("INSERT INTO party (deal_id, role, name, contact) VALUES (?1, 'buyer', 'B', '[email protected]') RETURNING id").get(id)!.id;
193 const held = holdReminder(db, who, { dealId: id, deadlineId: deadline, partyId: party, moment: "day_of", on: "2026-11-01" });
194 expect([said, held.ok]).toEqual([said, allowed]);
195 }
196 }
197 expect(holdReminder(db, { role: "anon" }, { dealId: dealBy("u1"), deadlineId: 1, partyId: 1, moment: "day_of" }).ok).toBe(false);
198 });
199
182200 test("the spreadsheet, at GET /deals/csv and GET /api/deals.csv, answers as deal list says, as every identity", async () => {
183201 for (const path of ["/deals/csv", "/api/deals.csv"]) {
184202 const route = routes.find((r) => r.method === "GET" && r.path === path)!;
src/dates.ts +5
@@ -138,6 +138,11 @@ const SHORT = new Intl.DateTimeFormat("en-US", {
138138 /** "Fri, Oct 16" — how a person reads a date in a sentence. */
139139 export const spoken = (date: string): string => SPOKEN.format(toMs(date));
140140
141 const WEEKDAY = new Intl.DateTimeFormat("en-US", { weekday: "long", timeZone: "UTC" });
142
143 /** "Friday" — the day of the week a date falls on. */
144 export const weekday = (date: string): string => WEEKDAY.format(toMs(date));
145
141146 /** "Oct 16" — for tight places. */
142147 export const short = (date: string): string => SHORT.format(toMs(date));
143148
src/db.ts +17
@@ -374,6 +374,23 @@ export const migrations: string[] = [
374374 // A date the buyer gave up on purpose: neither done nor gone. Who waived it is kept with the day.
375375 `ALTER TABLE deadline ADD COLUMN waived_at TEXT`,
376376 `ALTER TABLE deadline ADD COLUMN waived_by TEXT`,
377 // A reminder the agent holds until a later morning. It is keyed like a
378 // sent or declined one, so a moved date's notice is held once, not twice.
379 `CREATE TABLE IF NOT EXISTS reminder_hold (
380 id INTEGER PRIMARY KEY,
381 deal_id INTEGER NOT NULL REFERENCES deal (id) ON DELETE CASCADE,
382 deadline_id INTEGER NOT NULL,
383 party_id INTEGER NOT NULL,
384 moment TEXT NOT NULL CHECK (moment IN ('before', 'day_of', 'late', 'moved')),
385 due TEXT NOT NULL,
386 move_id INTEGER NOT NULL DEFAULT 0,
387 until TEXT NOT NULL,
388 held_on TEXT NOT NULL,
389 by_name TEXT NOT NULL,
390 at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),
391 UNIQUE (deadline_id, party_id, moment, due, move_id)
392 );
393 CREATE INDEX IF NOT EXISTS reminder_hold_deal ON reminder_hold (deal_id)`,
377394 ];
378395
379396 export function openDb(dir = dataDir): Database {
src/deals.ts +57 −1
@@ -8,7 +8,7 @@
88
99 import type { Database } from "bun:sqlite";
1010 import { permit } from "./contract.ts";
11 import { isBusinessDay, isDate, nextBusinessDay, today } from "./dates.ts";
11 import { addDays, isBusinessDay, isDate, nextBusinessDay, spoken, today } from "./dates.ts";
1212 import {
1313 DEFAULT_LENGTHS,
1414 isClosed,
@@ -78,6 +78,21 @@ export interface Move {
7878 /** The addendum that made this move together with others; 0 for a move made on its own. */
7979 readonly amendment: number;
8080 }
81 /** A reminder held until a later morning; keyed like a sent or declined one. */
82 export interface Held {
83 readonly id: number;
84 readonly deal_id: number;
85 readonly deadline_id: number;
86 readonly party_id: number;
87 readonly moment: Moment;
88 readonly due: string;
89 readonly move_id: number;
90 /** The morning it comes back. */
91 readonly until: string;
92 /** The day it was held. */
93 readonly held_on: string;
94 readonly by_name: string;
95 }
8196 export interface Sent {
8297 readonly id: number;
8398 readonly deal_id: number;
@@ -137,6 +152,7 @@ export interface DealView extends Deal {
137152 readonly deadlines: readonly DeadlineView[];
138153 readonly sent: readonly Sent[];
139154 readonly declined: readonly Declined[];
155 readonly held: readonly Held[];
140156 /** Open dates due on or after the open closing date (`order.ts`). */
141157 readonly conflicts: readonly Conflict[];
142158 }
@@ -197,6 +213,7 @@ interface Children {
197213 parties: Party[];
198214 sent: SentRow[];
199215 declined: Declined[];
216 held: Held[];
200217 }
201218
202219 /** A sent reminder with the link for the party's contact as it stands now; none once the party is gone. */
@@ -221,6 +238,7 @@ function assemble(deal: Deal, rows: Children): DealView {
221238 })),
222239 sent: rows.sent.map((m) => withHref(m, rows.parties)),
223240 declined: rows.declined,
241 held: rows.held,
224242 conflicts: conflicts(rows.deadlines),
225243 };
226244 }
@@ -252,6 +270,7 @@ function view(db: Database, deal: Deal): DealView {
252270 "SELECT * FROM reminder_declined WHERE deal_id = ?1 ORDER BY id",
253271 )
254272 .all(deal.id),
273 held: db.query<Held, [number]>("SELECT * FROM reminder_hold WHERE deal_id = ?1 ORDER BY id").all(deal.id),
255274 });
256275 }
257276
@@ -306,6 +325,10 @@ function viewMany(db: Database, where: string, params: string[]): DealView[] {
306325 db.query<Declined, string[]>(`SELECT * FROM reminder_declined WHERE ${of} ORDER BY id`).all(...params),
307326 (r) => r.deal_id,
308327 );
328 const held = byDeal(
329 db.query<Held, string[]>(`SELECT * FROM reminder_hold WHERE ${of} ORDER BY id`).all(...params),
330 (r) => r.deal_id,
331 );
309332 return deals.map((deal) =>
310333 assemble(deal, {
311334 deadlines: deadlines.get(deal.id) ?? [],
@@ -313,6 +336,7 @@ function viewMany(db: Database, where: string, params: string[]): DealView[] {
313336 parties: parties.get(deal.id) ?? [],
314337 sent: sent.get(deal.id) ?? [],
315338 declined: declined.get(deal.id) ?? [],
339 held: held.get(deal.id) ?? [],
316340 }),
317341 );
318342 }
@@ -1047,6 +1071,38 @@ export function declineReminder(
10471071 return within(db, who, "reminder.decline", dealId, ok(declined));
10481072 }
10491073
1074 /**
1075 * Hold a reminder until tomorrow: it leaves today's list and comes back the
1076 * next morning with the words as edited. Held again, it waits one more day.
1077 * A status update is not a morning reminder and is not held.
1078 */
1079 export function holdReminder(
1080 db: Database,
1081 who: Who,
1082 input: { deadlineId: number; dealId?: number; partyId: number; moment: unknown; agent?: Agent; on?: string },
1083 ): Result<Held> {
1084 const { dealId, found } = draftOf(db, who, input);
1085 if (!found.ok) return within(db, who, "reminder.hold", dealId, found);
1086 const { draft, deal } = found.value;
1087 if (draft.moment === "status")
1088 return within(db, who, "reminder.hold", dealId, fail("invalid", "A status update is not held; send it or decline it."));
1089 if (draft.sent_at !== null)
1090 return within(db, who, "reminder.hold", dealId, fail("invalid", "This reminder was already sent."));
1091 if (draft.declined !== null)
1092 return within(db, who, "reminder.hold", dealId, fail("invalid", "This reminder was declined; undo that first to hold it."));
1093 const day = input.on ?? today();
1094 if (draft.on > day)
1095 return within(db, who, "reminder.hold", dealId, fail("invalid", `This reminder goes out on ${spoken(draft.on)}; it can be held from that morning.`));
1096 const until = addDays(draft.held !== null && draft.held.until > day ? draft.held.until : day, 1);
1097 const held = db
1098 .query<Held, [number, number, number, string, string, number, string, string, string]>(
1099 `INSERT INTO reminder_hold (deal_id, deadline_id, party_id, moment, due, move_id, until, held_on, by_name) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
1100 ON CONFLICT (deadline_id, party_id, moment, due, move_id) DO UPDATE SET until = excluded.until, held_on = excluded.held_on, by_name = excluded.by_name, at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now') RETURNING *`,
outdated

Nothing stops holding a reminder whose send day is still in the future. It then returns on until, before it is due (see dueOn). Refuse that, or return it no earlier than d.on.

1101 )
1102 .get(deal.id, draft.deadline_id, draft.party_id, draft.moment, draft.due, draft.move_id, until, day, authorOf(who).name)!;
1103 return within(db, who, `reminder.hold:${until}`, dealId, ok(held));
1104 }
1105
10501106 /** Take back a decline: the reminder is a draft again. */
10511107 export function undoDecline(
10521108 db: Database,
src/hold.test.ts added +135
@@ -0,0 +1,135 @@
1 /** Holding a reminder until tomorrow: it leaves today, comes back with its words, and is sent like any other. */
2 import { afterAll, beforeEach, expect, test } from "bun:test";
3 import { mkdtempSync } from "node:fs";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { listAudit, restoreSamples } from "./actions.ts";
7 import { addDays, today } from "./dates.ts";
8 import { openDb } from "./db.ts";
9 import { createDeal, getDeal, holdReminder, sendReminder, declineReminder, type DealView } from "./deals.ts";
10 import { drafts, dueOn, todaysDrafts, waitingCount, type Draft } from "./reminders.ts";
11 import { wording } from "./activity.ts";
12 import { forgetRationing } from "./security.ts";
13 import { serve } from "./server.ts";
14 import type { Who } from "./who.ts";
15 import { sign } from "./who.ts";
16
17 const db = openDb(mkdtempSync(join(tmpdir(), "app-hold-")));
18 const alice: Who = { role: "user", id: "u1", name: "alice" };
19 const admin: Who = { role: "admin", id: "a1", name: "root" };
20 const anon: Who = { role: "anon" };
21 const agent = { name: "Dana Whitfield", brokerage: "Harbor & Pine Realty", phone: "(555) 010-0142", email: "[email protected]" };
22
23 const now = today();
24 const deal = ((): DealView => {
25 const made = createDeal(db, alice, { openAnyway: true, address: "7 Hold Ln", buyer: "Ann Buyer", seller: "Sam Seller", contractDate: addDays(now, -5), closingDate: addDays(now, 40), lengths: { inspection: "8" } });
26 if (!made.ok) throw new Error(made.message);
27 return made.value;
28 })();
29 const fresh = (): DealView => {
30 const got = getDeal(db, alice, { id: deal.id });
31 if (!got.ok) throw new Error(got.message);
32 return got.value;
33 };
34 const inspection = deal.deadlines.find((d) => d.kind === "inspection")!;
35 const mine = (list: readonly Draft[]) => list.filter((d) => d.deadline_id === inspection.id);
36 // The inspection is due in 3 days: its "before" reminder goes out today.
37 const first = mine(todaysDrafts([fresh()], now, agent)).find((d) => d.moment === "before")!;
38 const ask = { dealId: deal.id, deadlineId: first.deadline_id, partyId: first.party_id, moment: first.moment };
39 const tomorrow = addDays(now, 1);
40 const listed = (day: string) => mine(todaysDrafts([fresh()], day, agent)).filter((d) => d.party_id === first.party_id && d.moment === "before");
41
42 test("a held reminder is missing from today, back tomorrow with its words, sent the day after", () => {
43 expect(listed(now).length).toBe(1);
44 const before = waitingCount([fresh()], now, agent);
45 const held = holdReminder(db, alice, ask);
46 expect(held.ok && held.value.until).toBe(tomorrow);
47 expect(listed(now)).toEqual([]);
48 expect(waitingCount([fresh()], now, agent)).toBe(before - 1);
49 expect(mine(dueOn([fresh()], now, agent)).some((d) => d.party_id === first.party_id && d.moment === "before")).toBe(false);
50 // Tomorrow: back, at the top, labelled, and on /tick.
51 const back = listed(tomorrow);
52 expect(back.length).toBe(1);
53 expect(back[0]!.held).toEqual({ until: tomorrow, from: now, by_name: "alice" });
54 expect(back[0]!.subject).toBe(first.subject);
55 expect(todaysDrafts([fresh()], tomorrow, agent)[0]!.held).not.toBeNull();
56 expect(mine(dueOn([fresh()], tomorrow, agent)).some((d) => d.party_id === first.party_id && d.moment === "before")).toBe(true);
57 // Sent the day after: recorded like any other.
58 const sent = sendReminder(db, alice, { ...ask, subject: "Edited", body: "Edited words" });
59 expect(sent.ok).toBe(true);
60 const after = drafts(fresh(), agent).find((d) => d.deadline_id === first.deadline_id && d.party_id === first.party_id && d.moment === "before")!;
61 expect(after.sent_at).not.toBeNull();
62 expect(after.held).toBeNull();
63 expect(fresh().sent.length).toBe(1);
64 });
65
66 test("holding a held reminder pushes it one more day, and a sent one cannot be held", () => {
67 const second = mine(drafts(fresh(), agent)).find((d) => d.moment === "late")!;
68 const k = { dealId: deal.id, deadlineId: second.deadline_id, partyId: second.party_id, moment: second.moment };
69 // Not before its send morning.
70 expect(holdReminder(db, alice, k).ok).toBe(false);
71 const morning = second.on;
72 const hold = holdReminder(db, alice, { ...k, on: morning });
73 expect(hold.ok && hold.value.until).toBe(addDays(morning, 1));
74 const again = holdReminder(db, alice, { ...k, on: addDays(morning, 1) });
75 expect(again.ok && again.value.until).toBe(addDays(morning, 2));
76 const twice = holdReminder(db, alice, { ...k, on: addDays(morning, 1) });
77 expect(twice.ok && twice.value.until).toBe(addDays(morning, 3));
78 expect(holdReminder(db, alice, ask).ok).toBe(false);
79 });
80
81 test("a held reminder can be declined, and the hold is audited with its day", () => {
82 const late = mine(drafts(fresh(), agent)).find((d) => d.moment === "day_of" && d.party_id === first.party_id)!;
83 const k = { dealId: deal.id, deadlineId: late.deadline_id, partyId: late.party_id, moment: late.moment };
84 expect(holdReminder(db, alice, { ...k, on: late.on }).ok).toBe(true);
85 expect(declineReminder(db, alice, { ...k, reason: "Spoke by phone" }).ok).toBe(true);
86 const row = listAudit(db, admin, { only: "messages" });
87 expect(row.ok && row.value.some((r) => wording(r).startsWith("held a reminder until"))).toBe(true);
88 expect(holdReminder(db, alice, k).ok).toBe(false);
89 });
90
91 test("a status update is not held, an anonymous visitor is refused, and restore clears holds on samples only", () => {
92 expect(holdReminder(db, anon, ask).ok).toBe(false);
93 const status = holdReminder(db, alice, { ...ask, moment: "status" });
94 expect(status.ok).toBe(false);
95 const sample = db.query<{ id: number }, []>("SELECT id FROM deal WHERE author_id = 'sample' LIMIT 1").get()!;
96 const sdeal = getDeal(db, alice, { id: sample.id });
97 if (!sdeal.ok) throw new Error(sdeal.message);
98 const todo = drafts(sdeal.value, agent).find((d) => d.sent_at === null)!;
99 expect(holdReminder(db, alice, { dealId: sample.id, deadlineId: todo.deadline_id, partyId: todo.party_id, moment: todo.moment, on: todo.on > now ? todo.on : now }).ok).toBe(true);
100 const holds = (): number => db.query<{ n: number }, []>("SELECT count(*) AS n FROM reminder_hold").get()!.n;
101 const mineHeld = db.query<{ n: number }, [number]>("SELECT count(*) AS n FROM reminder_hold WHERE deal_id = ?1").get(deal.id)!.n;
102 expect(holds()).toBeGreaterThan(mineHeld);
103 expect(restoreSamples(db, admin).ok).toBe(true);
104 expect(holds()).toBe(mineHeld);
105 });
106
107 // ---- through the door ----
108
109 const KEY = "a-key-only-the-forge-holds";
110 const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-hold-web-")), identityKey: KEY });
111 const base = `http://${server.hostname}:${server.port}`;
112 afterAll(() => server.stop(true));
113 beforeEach(forgetRationing);
114 const identity = `u1|alice|user|${Date.now() + 600_000}`;
115 const signed = { "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) };
116 const post = (path: string, fields: Record<string, string>, headers: Record<string, string> = signed) =>
117 fetch(base + path, { method: "POST", body: new URLSearchParams(fields), headers: { ...headers, "content-type": "application/x-www-form-urlencoded" }, redirect: "manual" });
118
119 test("Tomorrow is a form on the review page and posts; another origin and an anonymous visitor are refused", async () => {
120 const page = await (await fetch(`${base}/reminders/today`, { headers: signed })).text();
121 expect(page).toContain('action="/reminders/today/hold"');
122 expect(page).toContain(">Tomorrow<");
123 const hidden = (name: string) => new RegExp(`name="${name}" value="([^"]*)"`).exec(page)![1]!;
124 const keys = { deadline: hidden("deadline"), party: hidden("party"), moment: hidden("moment"), at: "0", done: "0", q: "" };
125 const cross = await post("/reminders/today/hold", keys, { ...signed, origin: "https://evil.example" });
126 expect(cross.status).toBeGreaterThanOrEqual(400);
127 expect((await post("/reminders/today/hold", keys, {})).status).toBe(401);
128 const total = (p: string): number => Number(/(\d+) of (\d+)/.exec(p)?.[2] ?? 0);
129 const res = await post("/reminders/today/hold", keys);
130 expect(res.status).toBe(303);
131 const after = await (await fetch(`${base}/reminders/today`, { headers: signed })).text();
132 expect(total(after)).toBe(total(page) - 1);
133 // The deal's sheet offers it too, and the API documents the route.
134 expect(await (await fetch(`${base}/openapi.json`, { headers: signed })).text()).toContain("/api/deals/{id}/reminders/hold");
135 });
src/mcp.ts +14 −1
@@ -32,6 +32,7 @@ import {
3232 statusUpdates,
3333 setReminderLead,
3434 declineReminder,
35 holdReminder,
3536 undoDecline,
3637 } from "./deals.ts";
3738 import { LENGTH_MAX, standard, title } from "./env.ts";
@@ -86,7 +87,7 @@ export const tools: readonly Tool[] = [
8687 },
8788 {
8889 name: "reminders_today",
89 description: "The reminder drafts that go out today and have not been sent.",
90 description: "The reminder drafts that go out today and have not been sent, including ones held from an earlier day that come back today.",
9091 inputSchema: { type: "object", properties: {} },
9192 run: (db, who) => {
9293 const deals = listDeals(db, who);
@@ -245,6 +246,18 @@ export const tools: readonly Tool[] = [
245246 run: (db, who, args) =>
246247 declineReminder(db, who, { deadlineId: Number(args.deadline_id), partyId: Number(args.party_id), moment: args.moment, reason: args.reason }),
247248 },
249 {
250 name: "hold_reminder",
251 description:
252 "Hold a reminder until tomorrow, for a message the agent is not ready to approve: it leaves reminders_today and comes back the next morning with its words, labelled held. Held again, it waits one more day. A status update is not held.",
253 inputSchema: {
254 type: "object",
255 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late", "moved"] } },
256 required: ["deadline_id", "party_id", "moment"],
257 },
258 run: (db, who, args) =>
259 holdReminder(db, who, { deadlineId: Number(args.deadline_id), partyId: Number(args.party_id), moment: args.moment }),
260 },
248261 {
249262 name: "undo_decline_reminder",
250263 description: "Take back a decline: the reminder is a draft again, to send or decline.",
src/pages/deal.ts +11 −5
@@ -9,7 +9,7 @@ import { canChange, canRemove, closedOn, type DealView, type Party, type Plan, t
99 import { agent as defaults, standard } from "../env.ts";
1010 import { DEFAULT_LENGTHS, PARTY_LABEL, PARTY_ROLES } from "../deadlines.ts";
1111 import { escape } from "../http.ts";
12 import { sentLabel, statusDrafts, type Agent } from "../reminders.ts";
12 import { drafts, sentLabel, statusDrafts, type Agent } from "../reminders.ts";
1313 import type { Who } from "../who.ts";
1414 import { amendForm, type AmendState } from "./amend.ts";
1515 import { partyContact } from "./contact.ts";
@@ -62,8 +62,14 @@ function statusCard(deal: DealView, agent: Agent, on: string, may: boolean, to:
6262 }
6363
6464 /** The record of what went out: each sent reminder with the words approved, newest first. */
65 function messages(deal: DealView, may: boolean): string {
66 if (deal.sent.length === 0) return `<p class="muted">Nothing sent yet</p>`;
65 function messages(deal: DealView, may: boolean, agent: Agent): string {
66 const holding = drafts(deal, agent).flatMap((d) => (d.held === null ? [] : [{ d, held: d.held }]));
67 const waiting = holding.length === 0
68 ? ""
69 : `<ul class="drafts">${holding
70 .map(({ d, held }) => `<li class="draft"><span><b>${escape(d.party_name)}</b> <span class="muted">· ${escape(d.label)}, ${escape(short(d.due))} · ${escape(sentLabel(d.moment))}</span></span><span class="state">Held until ${escape(spoken(held.until))} by ${escape(held.by_name || "someone")}</span></li>`)
71 .join("")}</ul>`;
72 if (deal.sent.length === 0) return `${waiting}<p class="muted">Nothing sent yet</p>`;
6773 const live = new Set(deal.deadlines.map((d) => d.id));
6874 const item = (m: Sent): string => {
6975 const role = m.party_role === "" ? "" : ` · ${escape(PARTY_LABEL[m.party_role])}`;
@@ -74,7 +80,7 @@ function messages(deal: DealView, may: boolean): string {
7480 : `<div class="draft-text"><p><b>${escape(m.subject)}</b></p><p class="draft-body">${escape(m.body)}</p></div>${outboxLine(m.href, may)}`;
7581 return `<li class="draft"><details><summary><span><b>${escape(m.party_name)}</b> <span class="muted">${role} · ${escape(m.label)}${removed}, ${escape(short(m.due))} · ${escape(sentLabel(m.moment))}</span><br>${escape(m.subject === "" ? "(no subject kept)" : m.subject)}</span><span class="state" data-sent>Sent ${escape(short(m.sent_at.slice(0, 10)))}</span></summary>${words}</details></li>`;
7682 };
77 return `<ul class="drafts">${deal.sent.map(item).join("")}</ul>`;
83 return `${waiting}<ul class="drafts">${deal.sent.map(item).join("")}</ul>`;
7884 }
7985
8086 export function dealPage(input: {
@@ -176,7 +182,7 @@ export function dealPage(input: {
176182 ${statusCard(deal, agent ?? defaults, on, may, path)}
177183 <section class="card" id="messages">
178184 <h2>Messages</h2>
179 ${messages(deal, may)}
185 ${messages(deal, may, agent ?? defaults)}
180186 </section>
181187 ${deal.deadlines.map((d) => sheet(deal, d, who, on, path, agent)).join("")}
182188 </div>
src/pages/review.ts +4 −3
@@ -11,10 +11,10 @@ import { BODY_MAX, REASON_MAX, SUBJECT_MAX } from "../deals.ts";
1111 import { spoken } from "../dates.ts";
1212 import { PARTY_LABEL } from "../deadlines.ts";
1313 import { escape } from "../http.ts";
14 import { momentLabel, type Draft } from "../reminders.ts";
14 import { heldFrom, momentLabel, type Draft } from "../reminders.ts";
1515 import type { Who } from "../who.ts";
1616 import { layout } from "./layout.ts";
17 import { hidden } from "./sheet.ts";
17 import { hidden, holdForm } from "./sheet.ts";
1818
1919 export const REVIEW_PATH = "/reminders/today";
2020
@@ -89,7 +89,7 @@ function form(
8989 <p class="eyebrow">${s.position} of ${s.total}</p>
9090 <h1>Review today's reminders</h1>
9191 <p><a href="/deals/${draft.deal_id}">${escape(draft.address)}</a></p>
92 <p><b>${escape(draft.label)}</b> <span class="muted">· ${escape(spoken(draft.due))} · ${escape(momentLabel(draft.moment, draft.lead_days))}</span></p>
92 <p><b>${escape(draft.label)}</b> <span class="muted">· ${escape(spoken(draft.due))} · ${escape(momentLabel(draft.moment, draft.lead_days))}${draft.held === null ? "" : ` · ${escape(heldFrom(draft.held))}`}</span></p>
9393 <p>To <b>${escape(draft.party_name)}</b> <span class="muted">· ${escape(PARTY_LABEL[draft.party_role])} · ${escape(draft.contact === "" ? "no contact on file" : draft.contact)}</span></p>
9494 <form class="move" method="post" action="${REVIEW_PATH}/send">${hidden(keys)}
9595 ${problem("subject")}
@@ -98,6 +98,7 @@ function form(
9898 <label>Message<textarea class="input" name="body" rows="9" maxlength="${BODY_MAX}" required${invalid("body")}>${escape(typed.body)}</textarea></label>
9999 <button class="button">Send</button>
100100 </form>
101 ${holdForm(draft, "", `${REVIEW_PATH}/hold`, keys)}
101102 <form class="move" method="post" action="${REVIEW_PATH}/decline">${hidden(keys)}
102103 ${problem("reason")}
103104 <label>Why not<input class="input" name="reason" value="${escape(typed.reason)}" maxlength="${REASON_MAX}" required placeholder="e.g. Buyer already confirmed by phone"${invalid("reason")}></label>
src/pages/sheet.ts +14 −2
@@ -14,7 +14,7 @@ import { memoizer, print } from "../memo.ts";
1414 import { labelOf, NO_CONTACT, outbox } from "../outbox.ts";
1515 import { conflictLine } from "../order.ts";
1616 import { agent as defaults } from "../env.ts";
17 import { draftsFor, momentLabel, MOMENTS, remindsLine, type Agent, type Draft } from "../reminders.ts";
17 import { draftsFor, heldFrom, momentLabel, MOMENTS, remindsLine, type Agent, type Draft } from "../reminders.ts";
1818 import type { Who } from "../who.ts";
1919 import { owner } from "../week.ts";
2020
@@ -110,6 +110,14 @@ const declineForm = (draft: Draft, to: string): string =>
110110 <button class="button button-quiet">Don't send</button>
111111 </form>`;
112112
113 /** Beside *Send* and *Don't send*: hold it until tomorrow. A plain POST, no reason asked. */
114 export const holdForm = (draft: Draft, to: string, action = "/reminders/hold", keys?: Record<string, string | number>): string =>
115 draft.moment === "status"
116 ? ""
117 : `<form class="move" method="post" action="${action}">${hidden(keys ?? { deadline: draft.deadline_id, party: draft.party_id, moment: draft.moment, to })}
118 <button class="button button-quiet">Tomorrow</button>
119 </form>`;
120
113121 /** A declined reminder: the reason on record, and — for whoever may change the deal — the way back. */
114122 const undoForm = (draft: Draft, to: string): string =>
115123 `<form method="post" action="/reminders/undo">${hidden({ deadline: draft.deadline_id, party: draft.party_id, moment: draft.moment, to })}
@@ -123,6 +131,10 @@ function draftLine(draft: Draft, on: string, withDeal: boolean): string {
123131 ? `<span class="state" data-sent>Sent ${escape(short(draft.sent_at.slice(0, 10)))}</span>`
124132 : draft.declined !== null
125133 ? `<span class="state" data-declined>Not sent: ${escape(draft.declined.reason)} · ${escape(draft.declined.by_name || "someone")}</span>`
134 : draft.held !== null && draft.held.until > on
135 ? `<span class="state">Held until ${escape(short(draft.held.until))}</span>`
136 : draft.held !== null
137 ? `<span class="state" data-late>${escape(heldFrom(draft.held))}</span>`
126138 : draft.moment === "status"
127139 ? `<span class="state">Ready to send</span>`
128140 : draft.on < on
@@ -144,7 +156,7 @@ export function draftItem(draft: Draft, on: string, may: boolean, to: string): s
144156 : draft.declined !== null
145157 ? `${draftText(draft)}${may ? undoForm(draft, to) : ""}`
146158 : may
147 ? `${sendForm(draft, to)}${declineForm(draft, to)}`
159 ? `${sendForm(draft, to)}${holdForm(draft, to)}${declineForm(draft, to)}`
148160 : draftText(draft);
149161 return `<li class="draft"><details><summary>${draftLine(draft, on, false)}</summary>${inside}</details></li>`;
150162 }
src/reminders.ts +21 −5
@@ -8,7 +8,7 @@
88 * sent one, with the words approved; a sent draft reads back those words.
99 */
1010
11 import { addDays, relative, spoken, today } from "./dates.ts";
11 import { addDays, relative, spoken, today, weekday } from "./dates.ts";
1212 import { memoizer, print } from "./memo.ts";
1313 import { DEFAULT_LEAD, isOpen, KIND, PARTY_LABEL, type PartyRole } from "./deadlines.ts";
1414 import type { DealView, DeadlineView, Move, Moment, Party } from "./deals.ts";
@@ -47,6 +47,8 @@ export interface Draft {
4747 readonly sent_at: string | null;
4848 /** Why the agent chose not to send it, and who; null while it stands. */
4949 readonly declined: { readonly reason: string; readonly by_name: string } | null;
50 /** Held by the agent until a later morning, and who held it; null while it is not (and once sent or declined). */
51 readonly held: { readonly until: string; readonly from: string; readonly by_name: string } | null;
5052 }
5153
5254 export const MOMENTS: readonly Moment[] = ["before", "day_of", "late", "moved"];
@@ -198,6 +200,7 @@ export function draftsFor(deal: DealView, deadline: DeadlineView, agent: Agent):
198200 (amended || (s.deadline_id === deadline.id && s.due === deadline.due));
199201 const sent = deal.sent.find(mine);
200202 const declined = deal.declined.find(mine);
203 const held = sent === undefined && declined === undefined ? deal.held.find(mine) : undefined;
201204 const drafted = words(deal, deadline, party, moment, agent, notice);
202205 return [{
203206 deal_id: deal.id,
@@ -218,6 +221,7 @@ export function draftsFor(deal: DealView, deadline: DeadlineView, agent: Agent):
218221 body: sent !== undefined && sent.subject !== "" ? sent.body : drafted.body,
219222 sent_at: sent?.sent_at ?? null,
220223 declined: declined === undefined ? null : { reason: declined.reason, by_name: declined.by_name },
224 held: held === undefined ? null : { until: held.until, from: held.held_on, by_name: held.by_name },
221225 }];
222226 }),
223227 );
@@ -302,6 +306,7 @@ export function statusDrafts(deal: DealView, agent: Agent): Draft[] {
302306 body: sent !== undefined && sent.subject !== "" ? sent.body : drafted.body,
303307 sent_at: sent?.sent_at ?? null,
304308 declined: declined === undefined ? null : { reason: declined.reason, by_name: declined.by_name },
309 held: null,
305310 };
306311 });
307312 }
@@ -318,7 +323,7 @@ export const unsent = (d: Draft): boolean => d.sent_at === null && d.declined ==
318323
319324 /** What goes out on `day` and has not gone yet: `POST /tick`'s answer. */
320325 export const dueOn = (deals: readonly DealView[], day: string, agent: Agent): Draft[] =>
321 deals.flatMap((deal) => drafts(deal, agent)).filter((d) => d.on === day && d.sent_at === null && d.declined === null);
326 deals.flatMap((deal) => drafts(deal, agent)).filter((d) => unsent(d) && (d.held === null ? d.on === day : d.held.until === day));
322327
323328 /**
324329 * Waiting on `day`: goes out that morning, or was missed and still matters —
@@ -326,15 +331,26 @@ export const dueOn = (deals: readonly DealView[], day: string, agent: Agent): Dr
326331 * long as the date stays open.
327332 */
328333 export const pending = (d: Draft, day: string): boolean =>
329 d.on === day || (d.on < day && unsent(d) && (d.due >= day || d.moment === "late"));
334 d.held !== null
335 ? d.held.until <= day && (d.on === day || d.due >= day || d.moment === "late")
336 : d.on === day || (d.on < day && unsent(d) && (d.due >= day || d.moment === "late"));
330337
331338 /**
332339 * The drafts waiting on `day` across these deals, in the order the clock lists
333340 * them: deal by deal, date by date. The clock's "Reminders for today" and the
334341 * review page both read it, so they never disagree.
335342 */
336 export const todaysDrafts = (deals: readonly DealView[], day: string, agent: Agent): Draft[] =>
337 deals.flatMap((deal) => drafts(deal, agent).filter((d) => pending(d, day)));
343 export const todaysDrafts = (deals: readonly DealView[], day: string, agent: Agent): Draft[] => {
344 const these = deals.flatMap((deal) => drafts(deal, agent).filter((d) => pending(d, day)));
345 // A reminder held from an earlier day comes back at the top.
346 return [...these.filter(returned), ...these.filter((d) => !returned(d))];
347 };
348
349 /** Held earlier and back: unsent, with its hold run out. */
350 const returned = (d: Draft): boolean => d.held !== null;
351
352 /** "Held from Monday": what a reminder that came back says it was. */
353 export const heldFrom = (held: NonNullable<Draft["held"]>): string => `Held from ${weekday(held.from)}`;
338354
339355 const waitingIn = memoizer<number>(400);
340356
src/routes.ts +37
@@ -67,6 +67,7 @@ import {
6767 statusUpdates,
6868 setReminderLead,
6969 declineReminder,
70 holdReminder,
7071 undoDecline,
7172 updateDeal,
7273 type NewDeal,
@@ -505,6 +506,7 @@ async function reviewed(c: Context, act: (f: Record<string, string>) => Result<{
505506 }
506507
507508 const SENT = "Reminder sent.";
509 const HELD = "Held until tomorrow.";
508510
509511 /** An unticked box is absent from a form: that says no, not "the agent's default". */
510512 const fromForm = (f: Record<string, unknown>): Record<string, unknown> => ({
@@ -984,6 +986,15 @@ export const routes: readonly Route[] = [
984986 );
985987 },
986988 },
989 {
990 method: "POST",
991 path: "/reminders/hold",
992 handle: async (c) => {
993 const f = await form(c);
994 if (f instanceof Response) return f;
995 return done(holdReminder(c.db, c.who, { deadlineId: Number(f.deadline), partyId: Number(f.party), moment: f.moment }), backTo(f.to), HELD);
996 },
997 },
987998 {
988999 method: "GET",
9891000 path: "/reminders/today",
@@ -1020,6 +1031,11 @@ export const routes: readonly Route[] = [
10201031 handle: (c) =>
10211032 reviewed(c, (f) => declineReminder(c.db, c.who, { deadlineId: Number(f.deadline), partyId: Number(f.party), moment: f.moment, reason: f.reason }), "Reminder declined; the reason is kept."),
10221033 },
1034 {
1035 method: "POST",
1036 path: "/reminders/today/hold",
1037 handle: (c) => reviewed(c, (f) => holdReminder(c.db, c.who, { deadlineId: Number(f.deadline), partyId: Number(f.party), moment: f.moment }), HELD),
1038 },
10231039 {
10241040 method: "POST",
10251041 path: "/reminders/undo",
@@ -1224,6 +1240,27 @@ export const routes: readonly Route[] = [
12241240 status: 201,
12251241 },
12261242 },
1243 {
1244 method: "POST",
1245 path: "/api/deals/:id/reminders/hold",
1246 handle: async (c) => {
1247 const body = await readJson(c.request);
1248 if (body === undefined) return json({ error: "too_large" }, 413);
1249 const f = fields(body);
1250 return answer(holdReminder(c.db, c.who, { dealId: Number(c.params.id), deadlineId: Number(f.deadline_id), partyId: Number(f.party_id), moment: f.moment }), 201);
1251 },
1252 api: {
1253 summary:
1254 "Hold a reminder until tomorrow: it leaves today's list and /tick, and comes back the next morning with its words. Held again, it waits one more day. A status update is not held.",
1255 body: {
1256 type: "object",
1257 properties: { deadline_id: { type: "integer" }, party_id: { type: "integer" }, moment: { enum: ["before", "day_of", "late", "moved"] } },
1258 required: ["deadline_id", "party_id", "moment"],
1259 },
1260 answer: { type: "object", properties: { id: { type: "integer" }, until: { type: "string" }, by_name: { type: "string" } }, required: ["id", "until"] },
1261 status: 201,
1262 },
1263 },
12271264 {
12281265 method: "POST",
12291266 path: "/api/deals/:id/reminders/undo",
src/server.test.ts +1
@@ -186,6 +186,7 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
186186 "draft_status_update",
187187 "send_status_update",
188188 "decline_reminder",
189 "hold_reminder",
189190 "undo_decline_reminder",
190191 "open_deal",
191192 "add_date",
src/terminal.test.ts +16
@@ -269,6 +269,22 @@ test("n declines a reminder with a reason, u undoes it; anon is not asked to typ
269269 expect(db.query<{ n: number }, []>("SELECT count(*) AS n FROM reminder_declined").get()!.n).toBe(before);
270270 });
271271
272 test("h holds a reminder until tomorrow: it leaves the list, is written, and anon cannot", () => {
273 const t = terminal(db, alice, context);
274 t.press("r");
275 const row = under(t);
276 const holds = () => db.query<{ n: number }, []>("SELECT count(*) AS n FROM reminder_hold").get()!.n;
277 const before = holds();
278 t.press("h");
279 expect(lines(t).join("\n")).toContain("Held until");
280 expect(holds()).toBe(before + 1);
281 expect(lines(t).join("\n")).not.toContain(row);
282 const guest = terminal(db, { role: "anon" }, context);
283 guest.press("r");
284 guest.press("h");
285 expect(holds()).toBe(before + 1);
286 });
287
272288 test("a closed deal's dates leave the date list and reminders, it is listed under Closed, and u reopens it", () => {
273289 // The inspection ends in three days, so its "3 days before" reminder goes out today.
274290 const other = createDeal(db, alice, {
src/terminal.ts +16 −5
@@ -50,6 +50,7 @@ import {
5050 sendStatusUpdate,
5151 statusUpdates,
5252 declineReminder,
53 holdReminder,
5354 undoDecline,
5455 REASON_MAX,
5556 ROLL_REASON,
@@ -62,7 +63,7 @@ import { conflictLine } from "./order.ts";
6263 import { isOpen, PARTY_LABEL, PARTY_ROLES, type PartyRole } from "./deadlines.ts";
6364 import { agentOf, getProfile, setProfile, useDefaults } from "./profile.ts";
6465 import { permit } from "./contract.ts";
65 import { drafts, momentLabel, pending, remindsLine, sentLabel, unsent, type Agent, type Draft } from "./reminders.ts";
66 import { drafts, heldFrom, momentLabel, pending, remindsLine, sentLabel, unsent, type Agent, type Draft } from "./reminders.ts";
6667 import type { AuditRow } from "./audit.ts";
6768 import type { Result } from "./result.ts";
6869 import type { Who } from "./who.ts";
@@ -149,11 +150,13 @@ export function terminal(
149150 /** Today's reminders: what goes out today, and what should have and has not, for dates still ahead. */
150151 const reminderRows = (): { deal: DealView; draft: Draft }[] => {
151152 const day = on();
152 return deals().flatMap((deal) =>
153 const rows = deals().flatMap((deal) =>
153154 drafts(deal, agentNow())
154155 .filter((r) => pending(r, day))
155156 .map((draft) => ({ deal, draft })),
156157 );
158 // A reminder held from an earlier day comes back at the top, as on the page.
159 return [...rows.filter((r) => r.draft.held !== null), ...rows.filter((r) => r.draft.held === null)];
157160 };
158161 const editKey = (d: Draft): string => `${d.deadline_id}:${d.party_id}:${d.moment}`;
159162 /** The draft with any words typed for it; a sent one is as it went. */
@@ -304,7 +307,7 @@ export function terminal(
304307 }
305308
306309 function onReminder(key: string): boolean {
307 if (key !== "\r" && key !== "s" && key !== "e" && key !== "n" && key !== "u") return false;
310 if (key !== "\r" && key !== "s" && key !== "e" && key !== "n" && key !== "u" && key !== "h") return false;
308311 const row = reminderRows()[cursor];
309312 if (row === undefined) {
310313 said = "No reminder here.";
@@ -345,6 +348,14 @@ export function terminal(
345348 return report(declined, `Not sent to ${draft.party_name}: ${reason}`);
346349 }, REASON_MAX);
347350 }
351 if (key === "h") {
352 if (drafted.sent_at !== null) said = "Already sent; it cannot be held.";
353 else if (drafted.declined !== null) said = "Already declined; u undoes it.";
354 else {
355 const held = holdReminder(db, me, { deadlineId: draft.deadline_id, partyId: draft.party_id, moment: draft.moment });
356 said = report(held, () => `Held until ${held.ok ? spoken(held.value.until) : ""}: ${draft.party_name}'s reminder returns then.`);
357 }
358 }
348359 if (key === "u") {
349360 if (drafted.declined === null) said = "Not declined, nothing to undo.";
350361 else
@@ -730,7 +741,7 @@ export function terminal(
730741 const rows = reminderRows();
731742 if (rows.length === 0) lines.push(dim("Nothing goes out today."));
732743 rows.forEach(({ draft }, i) => {
733 const state = draft.sent_at !== null ? dim("sent") : draft.declined !== null ? dim("not sent") : draft.on < day ? tint("overdue", "late") : tint("soon", "to send");
744 const state = draft.sent_at !== null ? dim("sent") : draft.declined !== null ? dim("not sent") : draft.held !== null ? tint("overdue", heldFrom(draft.held).toLowerCase()) : draft.on < day ? tint("overdue", "late") : tint("soon", "to send");
734745 const text = `${draft.party_name} (${PARTY_LABEL[draft.party_role].toLowerCase()}) · ${draft.label}, ${draft.address} · ${momentLabel(draft.moment, draft.lead_days).toLowerCase()}`;
735746 lines.push(`${i === cursor ? "▸" : " "} ${state.padEnd(16)} ${i === cursor ? bold(text) : text}`);
736747 if (reading === i) {
@@ -754,7 +765,7 @@ export function terminal(
754765 : view === "people"
755766 ? "P people · d dates · w this week · r reminders · q quit"
756767 : view === "reminders"
757 ? "j/k move · enter read · e edit · s send · n don't send · u undo · / find · d dates · q quit"
768 ? "j/k move · enter read · e edit · s send · n don't send · h tomorrow · u undo · / find · d dates · q quit"
758769 : view === "messages"
759770 ? "j/k move · enter read · b back to the deal · d dates · q quit"
760771 : view === "timeline"

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs