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

A sent reminder opens in the agent's own Mail or Messages app with the approved words filled in, so Send really reaches the party #65

Merged opened this

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

Merged

mason/deal-clock:mason/62-a-sent-reminder-opens-in-the-agent-s-own → main 4 commits fork

  • Merged. mason/62-a-sent-reminder-opens-in-the-agent-s-own was merged into main as 30d746c.

Review

Sign in to review this change.
17 files changed +283 −42
README.md +9 −4
@@ -57,9 +57,13 @@ Signed out, `/` shows what deal-clock does, three short points, a still picture
5757 see the words it would send, in a subject field and a message field,
5858 already filled in. Change the message; the subject can run to 150
5959 characters and the message to 2000.
60 4. **Send it.** Tap Send. A short notice at the top of the page reads
61 "Reminder sent (simulated)." and the reminder now shows "Sent" with
62 today's date and your edited words, not the original draft. Under the
60 4. **Send it.** Tap Send. Send records your approval and opens your own
61 Mail or Messages with the words: nothing is sent by the app itself. A
62 short notice at the top of the page reads "Reminder sent." with one link,
63 **Open in Mail** (an email on file) or **Open in Messages** (a phone), that
64 you tap to send from your own app; with neither on file it says "No email
65 or phone on file". The reminder now shows "Sent" with
66 today's date, your edited words, not the original draft, and the same link. Under the
6367 clock, the heading "Reminders for today" counts what is left ("14 to send"
6468 becomes "13 to send"; when nothing is left it reads "all sent"). Each row
6569 there opens the sheet of the date it is for, where the reminder is edited,
@@ -69,7 +73,8 @@ Signed out, `/` shows what deal-clock does, three short points, a still picture
6973 <reason> · <who>"; the reason is kept, and **Undo** makes it a draft again.
7074 Every message you sent is kept: open 1418 Alder Lane's page and find
7175 **Messages**, newest first, each with who it went to, which date and
72 moment, the day it was sent, and (tap it open) the exact words you approved.
76 moment, the day it was sent, and (tap it open) the exact words you approved
77 with the link to open them again.
7378 In the terminal: open the deal with o, then press s.
7479 5. **Move a date, with a reason.** Open the same marker again and use Move
7580 this date: pick a new date and say why ("Inspector delayed"). The marker
contract/openapi.json +7
@@ -1265,6 +1265,13 @@
12651265 "body": {
12661266 "type": "string",
12671267 "description": "The message that was sent, as approved."
1268 },
1269 "href": {
1270 "type": [
1271 "string",
1272 "null"
1273 ],
1274 "description": "A mailto: or sms: link that opens the party's own Mail or Messages with these words; null when the party has no email or phone on file, or is gone."
12681275 }
12691276 }
12701277 }
docs/TECHNICAL.md +9 −2
@@ -31,8 +31,14 @@ an earlier notice stays sent and a date moved back and forth is told afresh.
3131 `deadline_move.notify` is 1 only for moves made after the moment existed.
3232 `send_reminder` and the decline and undo doors take `moment: "moved"`.
3333
34 Sending is simulated: *Send* records that a reminder went out and the
35 words approved with it; nothing leaves the app. The record is shown on the
34 *Send* records the agent's approval and the words approved with it; the app
35 itself sends nothing and has no mail server. `src/outbox.ts` turns a sent
36 reminder and its party's contact into one link: `mailto:` (subject and body
37 percent-encoded) for an email, `sms:` for a phone, none otherwise ("No email
38 or phone on file"). The page shows it as **Open in Mail** / **Open in Messages**
39 in the notice after Send, on the sheet and in **Messages**; it is never opened
40 by script. `sent[].href` (and `send_reminder`'s answer) carries it, `null` when
41 there is no link; the terminal shows the address and says to send from the phone. The record is shown on the
3642 page (the **Messages** section of `/deals/:id`, newest first, each entry
3743 opening to the approved words), in `/api/deals/:id` and the MCP `get_deal` as
3844 `sent`, and in the terminal (open a deal with `o`, then `s`: the sent reminders,
@@ -124,6 +130,7 @@ decide nothing themselves. `AGENTS.md` says how to add to it.
124130 | `src/deals.ts` | deals: open, read, move a date, mark done, parties, reminders sent |
125131 | `src/dates.ts`, `src/deadlines.ts` | calendar math; the standard contract dates and who owes them |
126132 | `src/reminders.ts`, `src/ics.ts` | reminder drafts and `/tick`; the calendar file |
133 | `src/outbox.ts` | a sent reminder's mailto:/sms: link |
127134 | `src/sample.ts` | the four sample deals a new database starts with |
128135 | `src/result.ts` | what an action answers, and the audit habit they share |
129136 | `src/actions.ts` | the audit trail, read |
src/deals.ts +18 −8
@@ -21,6 +21,7 @@ import {
2121 } from "./deadlines.ts";
2222 import { agent as defaultAgent, LENGTH_MAX, standard } from "./env.ts";
2323 import { emit } from "./live.ts";
24 import { outbox } from "./outbox.ts";
2425 import { conflictLine, conflicts, type Conflict } from "./order.ts";
2526 import { draftsFor, moveKey, type Agent, type Draft } from "./reminders.ts";
2627 import { audited, fail, ok, refuse, type Result } from "./result.ts";
@@ -88,7 +89,10 @@ export interface Sent {
8889 /** The words that went out, as approved; '' on a reminder sent before they were kept. */
8990 readonly subject: string;
9091 readonly body: string;
92 /** A link that opens the party's own Mail or Messages with these words (`outbox.ts`); null when there is none to offer. */
93 readonly href: string | null;
9194 }
95 type SentRow = Omit<Sent, "href">;
9296 export interface Deadline {
9397 readonly id: number;
9498 readonly deal_id: number;
@@ -162,10 +166,10 @@ const authorOf = (who: Who): { id: string; name: string } =>
162166 * work, so nothing is blanked; it holds the moment update narrows (to
163167 * `author`, say) without read narrowing with it.
164168 */
165 const shown = (who: Who, deal: DealView): DealView =>
169 export const shown = (who: Who, deal: DealView): DealView =>
166170 canChange(who, deal)
167171 ? deal
168 : { ...deal, parties: deal.parties.map((p) => ({ ...p, contact: "" })) };
172 : { ...deal, parties: deal.parties.map((p) => ({ ...p, contact: "" })), sent: deal.sent.map((m) => ({ ...m, href: null })) };
169173
170174 // ---- reading ----
171175
@@ -174,10 +178,16 @@ interface Children {
174178 deadlines: Deadline[];
175179 moves: Move[];
176180 parties: Party[];
177 sent: Sent[];
181 sent: SentRow[];
178182 declined: Declined[];
179183 }
180184
185 /** A sent reminder with the link for the party's contact as it stands now; none once the party is gone. */
186 function withHref(m: SentRow, parties: readonly Party[]): Sent {
187 const party = parties.find((p) => p.id === m.party_id);
188 return { ...m, href: party === undefined || m.subject === "" ? null : (outbox(party.contact, m.subject, m.body)?.href ?? null) };
189 }
190
181191 /** One deal assembled from its rows. */
182192 function assemble(deal: Deal, rows: Children): DealView {
183193 const moves = rows.moves;
@@ -191,7 +201,7 @@ function assemble(deal: Deal, rows: Children): DealView {
191201 ...d,
192202 moves: moves.filter((m) => m.deadline_id === d.id),
193203 })),
194 sent: rows.sent,
204 sent: rows.sent.map((m) => withHref(m, rows.parties)),
195205 declined: rows.declined,
196206 conflicts: conflicts(rows.deadlines),
197207 };
@@ -215,7 +225,7 @@ function view(db: Database, deal: Deal): DealView {
215225 )
216226 .all(deal.id),
217227 sent: db
218 .query<Sent, [number]>(
228 .query<SentRow, [number]>(
219229 "SELECT * FROM reminder WHERE deal_id = ?1 ORDER BY sent_at DESC, id DESC",
220230 )
221231 .all(deal.id),
@@ -270,7 +280,7 @@ function viewMany(db: Database, where: string, params: string[]): DealView[] {
270280 );
271281 const sent = byDeal(
272282 db
273 .query<Sent, string[]>(`SELECT * FROM reminder WHERE ${of} ORDER BY sent_at DESC, id DESC`)
283 .query<SentRow, string[]>(`SELECT * FROM reminder WHERE ${of} ORDER BY sent_at DESC, id DESC`)
274284 .all(...params),
275285 (r) => r.deal_id,
276286 );
@@ -783,12 +793,12 @@ export function sendReminder(
783793 if (body === undefined)
784794 return within(db, who, dealId, fail("invalid", `The message is 1 to ${BODY_MAX} characters.`));
785795 const sent = db
786 .query<Sent, [number, number, number, string, string, string, string, string, number, string, string, string]>(
796 .query<SentRow, [number, number, number, string, string, string, string, string, number, string, string, string]>(
787797 `INSERT INTO reminder (deal_id, deadline_id, party_id, label, party_name, party_role, moment, due, move_id, by_name, subject, body) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)
788798 ON CONFLICT (deadline_id, party_id, moment, due, move_id) DO UPDATE SET sent_at = sent_at RETURNING *`,
789799 )
790800 .get(found.value.deal.id, deadline.id, party.id, deadline.label, party.name, party.role, input.moment, deadline.due, moveKey(seen.deadlines.find((d) => d.id === deadline.id)!, input.moment), authorOf(who).name, subject, body)!;
791 return within(db, who, dealId, ok(sent));
801 return within(db, who, dealId, ok(withHref(sent, [party])));
792802 }
793803
794804 /** The draft one decline or undo names, on a date `who` may change. */
src/http.ts +7 −3
@@ -74,7 +74,7 @@ export const text = (body: string, status = 200): Response =>
7474 });
7575
7676 /** Back to a page (the clock, unless said), with a word for it to show once (`readNotice`). */
77 export const back = (notice?: string, to = "/"): Response =>
77 export const back = (notice?: string, to = "/", open?: number): Response =>
7878 new Response(null, {
7979 status: 303,
8080 headers: {
@@ -82,21 +82,25 @@ export const back = (notice?: string, to = "/"): Response =>
8282 ...SECURITY,
8383 ...(notice === undefined
8484 ? {}
85 : { "set-cookie": cookie("notice", encodeURIComponent(notice), 30) }),
85 : { "set-cookie": cookie("notice", `${open === undefined ? "" : `${open}~`}${encodeURIComponent(notice)}`, 30) }),
8686 },
8787 });
8888
8989 /** The notice a redirect left, and the header that clears it. */
9090 export function readNotice(request: Request): {
9191 notice?: string;
92 /** The sent reminder the notice offers to open in Mail or Messages. */
93 open?: number;
9294 clear: Record<string, string>;
9395 } {
9496 const raw = /(?:^|;\s*)notice=([^;]*)/.exec(
9597 request.headers.get("cookie") ?? "",
9698 )?.[1];
9799 if (raw === undefined) return { clear: {} };
100 const opened = /^(\d{1,12})~(.*)$/.exec(raw);
98101 return {
99 notice: decodeURIComponent(raw),
102 notice: decodeURIComponent(opened?.[2] ?? raw),
103 ...(opened === null ? {} : { open: Number(opened[1]) }),
100104 clear: { "set-cookie": cookie("notice", "", 0) },
101105 };
102106 }
src/mcp.ts +1 −1
@@ -145,7 +145,7 @@ export const tools: readonly Tool[] = [
145145 {
146146 name: "send_reminder",
147147 description:
148 "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.",
148 "Record a reminder as sent to one party. The app sends nothing itself: the answer's href is a mailto: or sms: link that opens the agent's own Mail or Messages with the approved words (null when the party has no email or phone on file). 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 and the href.",
149149 inputSchema: {
150150 type: "object",
151151 properties: {
src/notice.test.ts added +30
@@ -0,0 +1,30 @@
1 import { expect, test } from "bun:test";
2 import { back, readNotice } from "./http.ts";
3 import { outboxLine } from "./pages/sheet.ts";
4
5 const jar = (res: Response): Request =>
6 new Request("http://x/", { headers: { cookie: (res.headers.get("set-cookie") ?? "").split(";")[0]! } });
7
8 test("a notice carries the sent reminder it offers, and a plain notice carries none", () => {
9 const withId = readNotice(jar(back("Reminder sent. ~ ok & more", "/", 42)));
10 expect(withId.notice).toBe("Reminder sent. ~ ok & more");
11 expect(withId.open).toBe(42);
12 const plain = readNotice(jar(back("Date removed.")));
13 expect(plain.notice).toBe("Date removed.");
14 expect(plain.open).toBeUndefined();
15 expect(readNotice(new Request("http://x/")).notice).toBeUndefined();
16 });
17
18 test("a malformed notice cookie is shown as text and opens nothing", () => {
19 const read = (value: string) => readNotice(new Request("http://x/", { headers: { cookie: `notice=${value}` } }));
20 for (const bad of ["abc~hi", "~hi", "1234567890123~hi", "-5~hi", "7"]) expect(read(bad).open).toBeUndefined();
21 expect(read("abc~hi").notice).toBe("abc~hi");
22 });
23
24 test("the link and its absence are for whoever may change the deal alone", () => {
25 const href = "mailto:[email protected]?subject=s&body=b";
26 expect(outboxLine(href, true)).toContain('href="mailto:[email protected]?subject=s&amp;body=b"');
27 expect(outboxLine(null, true)).toContain("No email or phone on file");
28 expect(outboxLine(href, false)).toBe("");
29 expect(outboxLine(null, false)).toBe("");
30 });
src/outbox.test.ts added +37
@@ -0,0 +1,37 @@
1 import { expect, test } from "bun:test";
2 import { outbox } from "./outbox.ts";
3
4 const tricky = "Tom & Jerry #1\nline two — café ✓ 100%";
5
6 test("an email opens Mail with subject and body", () => {
7 const o = outbox("[email protected]", tricky, tricky)!;
8 expect(o.kind).toBe("mail");
9 expect(o.label).toBe("Open in Mail");
10 expect(o.href.startsWith("mailto:[email protected]?subject=")).toBe(true);
11 const q = new URLSearchParams(o.href.slice(o.href.indexOf("?") + 1));
12 expect(q.get("subject")).toBe(tricky);
13 expect(q.get("body")).toBe(tricky);
14 expect(decodeURIComponent(o.href.split("&body=")[1]!)).toBe(tricky);
15 });
16
17 test("a phone opens Messages with the body", () => {
18 const o = outbox("+1 (555) 010-0142", "s", tricky)!;
19 expect(o.kind).toBe("sms");
20 expect(o.label).toBe("Open in Messages");
21 expect(o.href.startsWith("sms:+15550100142?&body=")).toBe(true);
22 expect(decodeURIComponent(o.href.split("&body=")[1]!)).toBe(tricky);
23 expect(o.href).not.toMatch(/[\s"<>]/);
24 });
25
26 test("no contact, or one that is neither, gives no link", () => {
27 expect(outbox("", "s", "b")).toBeNull();
28 expect(outbox("call me", "s", "b")).toBeNull();
29 });
30
31 test("a contact with a quote or a scheme gives no link", () => {
32 expect(outbox('a"[email protected]', "s", "b")).toBeNull();
33 expect(outbox('"><script>@x.co', "s", "b")).toBeNull();
34 expect(outbox("javascript:alert(1)", "s", "b")).toBeNull();
35 expect(outbox("javascript:alert(1)//@x.co", "s", "b")).toBeNull();
36 expect(outbox('555 0100"', "s", "b")).toBeNull();
37 });
src/outbox.ts added +41
@@ -0,0 +1,41 @@
1 /**
2 * Where a sent reminder goes from here: a link that opens the agent's own
3 * Mail or Messages with the approved words filled in. The app sends nothing
4 * itself; a person taps the link. Plain data in, plain data out.
5 */
6
7 import { validEmail, validPhone } from "./env.ts";
8
9 export interface Outbox {
10 readonly kind: "mail" | "sms";
11 readonly href: string;
12 /** What the link says. */
13 readonly label: string;
14 }
15
16 /** What shows where there is no link to offer. */
17 export const NO_CONTACT = "No email or phone on file";
18
19 /**
20 * The link for these words to this contact: `mailto:` for an email, `sms:`
21 * for a phone, null for anything else. A contact is only used after it passes
22 * the same checks the settings do, so no quote or scheme can ride in it.
23 */
24 export function outbox(contact: string, subject: string, body: string): Outbox | null {
25 if (validEmail(contact))
26 return {
27 kind: "mail",
28 href: `mailto:${contact}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`,
29 label: "Open in Mail",
30 };
31 if (validPhone(contact))
32 return {
33 kind: "sms",
34 href: `sms:${contact.replace(/[^0-9+]/g, "")}?&body=${encodeURIComponent(body)}`,
35 label: "Open in Messages",
36 };
37 return null;
38 }
39
40 /** The words on a link `outbox` made, by its scheme. */
41 export const labelOf = (href: string): string => (href.startsWith("mailto:") ? "Open in Mail" : "Open in Messages");
src/pages/clock.ts +7 −3
@@ -143,10 +143,11 @@ export function clock(input: {
143143 deals: readonly DealView[];
144144 on: string;
145145 notice?: string | undefined;
146 open?: number | undefined;
146147 q?: string | undefined;
147148 }): string {
148149 const key = Bun.hash(
149 JSON.stringify([input.who, input.on, input.notice ?? null, input.q ?? "", agent]) +
150 JSON.stringify([input.who, input.on, input.notice ?? null, input.open ?? null, input.q ?? "", agent]) +
150151 input.deals.map(print).join(),
151152 );
152153 return pages(`${input.deals.length}:${key}`, () => render(input));
@@ -157,9 +158,12 @@ function render(input: {
157158 deals: readonly DealView[];
158159 on: string;
159160 notice?: string | undefined;
161 open?: number | undefined;
160162 q?: string | undefined;
161163 }): string {
162164 const { who, on, notice } = input;
165 const opened =
166 input.open === undefined ? undefined : input.deals.flatMap((d) => d.sent).find((m) => m.id === input.open);
163167 const q = input.q ?? "";
164168 const found = find(input.deals, q);
165169 const deals = found.filter((deal) => !deal.closed);
@@ -239,7 +243,7 @@ function render(input: {
239243 ? `<p class="muted">Nothing goes out today.</p>`
240244 : `<ul class="drafts">${today.map((t) => t.html).join("")}</ul>`
241245 }
242 <p class="muted small">Each date reminds its parties three days before and the morning of, and the one who owes a date is asked for an update the morning after it slips. Sending is simulated: the draft is shown and marked sent.</p>
246 <p class="muted small">Each date reminds its parties three days before and the morning of, and the one who owes a date is asked for an update the morning after it slips. Send records your approval and opens your own Mail or Messages with the words.</p>
243247 </section>`}`;
244 return layout({ body, who, path: "/", notice });
248 return layout({ body, who, path: "/", notice, open: opened?.href });
245249 }
src/pages/deal.ts +8 −5
@@ -12,7 +12,7 @@ import { escape } from "../http.ts";
1212 import { MOMENT_LABEL } from "../reminders.ts";
1313 import type { Who } from "../who.ts";
1414 import { layout } from "./layout.ts";
15 import { badge, conflictLines, dueLine, owedBy, sheet, sheetId } from "./sheet.ts";
15 import { badge, conflictLines, dueLine, outboxLine, owedBy, sheet, sheetId } from "./sheet.ts";
1616
1717 const roleOptions = (selected?: string): string =>
1818 PARTY_ROLES.map(
@@ -34,7 +34,7 @@ const partyControls = (p: Party, to: string): string => `<div class="party-contr
3434 </div>`;
3535
3636 /** The record of what went out: each sent reminder with the words approved, newest first. */
37 function messages(deal: DealView): string {
37 function messages(deal: DealView, may: boolean): string {
3838 if (deal.sent.length === 0) return `<p class="muted">Nothing sent yet</p>`;
3939 const live = new Set(deal.deadlines.map((d) => d.id));
4040 const item = (m: Sent): string => {
@@ -43,7 +43,7 @@ function messages(deal: DealView): string {
4343 const words =
4444 m.subject === ""
4545 ? `<p class="muted">The words were not kept for this one.</p>`
46 : `<div class="draft-text"><p><b>${escape(m.subject)}</b></p><p class="draft-body">${escape(m.body)}</p></div>`;
46 : `<div class="draft-text"><p><b>${escape(m.subject)}</b></p><p class="draft-body">${escape(m.body)}</p></div>${outboxLine(m.href, may)}`;
4747 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(MOMENT_LABEL[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>`;
4848 };
4949 return `<ul class="drafts">${deal.sent.map(item).join("")}</ul>`;
@@ -54,10 +54,13 @@ export function dealPage(input: {
5454 deal: DealView;
5555 on: string;
5656 notice?: string | undefined;
57 /** The sent reminder the notice offers to open. */
58 open?: number | undefined;
5759 /** An address that was refused: what was typed and why, to show beside the field. */
5860 problem?: { readonly value: string; readonly message: string } | undefined;
5961 }): string {
6062 const { who, deal, on, notice, problem } = input;
63 const opened = input.open === undefined ? undefined : deal.sent.find((m) => m.id === input.open);
6164 const path = `/deals/${deal.id}`;
6265 const may = canChange(who, deal);
6366 const editAddress = may
@@ -137,7 +140,7 @@ export function dealPage(input: {
137140 </section>
138141 <section class="card" id="messages">
139142 <h2>Messages</h2>
140 ${messages(deal)}
143 ${messages(deal, may)}
141144 </section>
142145 ${deal.deadlines.map((d) => sheet(deal, d, who, on, path)).join("")}
143146 </div>
@@ -147,7 +150,7 @@ export function dealPage(input: {
147150 ? `<form method="post" action="${path}/delete" class="remove"><button class="button button-quiet">Remove this deal</button></form>`
148151 : ""
149152 }`;
150 return layout({ body, who, path, heading: deal.address, notice });
153 return layout({ body, who, path, heading: deal.address, notice, open: opened?.href });
151154 }
152155
153156 /** What the form was last sent with, what was wrong with it, and the dates it would make. */
src/pages/layout.ts +6 −3
@@ -16,6 +16,7 @@ import {
1616 where,
1717 } from "../env.ts";
1818 import { asset, escape } from "../http.ts";
19 import { labelOf, NO_CONTACT } from "../outbox.ts";
1920 import { contactLinks } from "./contact.ts";
2021 import { token, tokensHref } from "../tokens.ts";
2122 import type { Who } from "../who.ts";
@@ -28,6 +29,8 @@ export function layout(input: {
2829 path: string;
2930 heading?: string;
3031 notice?: string | undefined;
32 /** The link a notice about a sent reminder offers: the href `outbox` made for it. */
33 open?: string | null | undefined;
3134 /** Whether the page keeps its regions live; false for a page with none. */
3235 live?: boolean;
3336 /** A page handed to someone outside the app: the brand only, no sign-in, footer or script. */
@@ -35,7 +38,7 @@ export function layout(input: {
3538 /** A class on <body>, for styles that belong to one page only. */
3639 bodyClass?: string;
3740 }): string {
38 const { body, who, path, notice, plain = false, bodyClass } = input;
41 const { body, who, path, notice, open, plain = false, bodyClass } = input;
3942 const pageTitle = input.heading === undefined ? title : `${input.heading} · ${title}`;
4043 const to = encodeURIComponent(path);
4144 const door =
@@ -85,13 +88,13 @@ ${plain || input.live === false ? "" : `<script type="module" src="${asset("live
8588 </header>
8689 <main>${body}</main>
8790 ${plain ? "" : `<footer class="muted">
88 <p>${escape(title)}${commit ? ` <span class="mono">${escape(commit)}</span>` : ""} — reminders here are drafted and marked sent; nothing is emailed or texted yet.</p>
91 <p>${escape(title)}${commit ? ` <span class="mono">${escape(commit)}</span>` : ""} — Send records your approval and opens your own Mail or Messages with the words. Nothing is sent by the app itself.</p>
8992 ${ssh === undefined ? "<p>The terminal is off.</p>" : `<p>Terminal: <code>${escape(ssh)}</code></p>`}
9093 <p>Also at <a href="/api/deals">/api/deals</a> (<a href="/openapi.json">described</a>), <code>POST /tick</code> and <code>POST /mcp</code>, with the same rules.</p>
9194 <p>Something wrong? <a href="/__forge/report">Report a problem</a>, no account needed.</p>
9295 </footer>`}
9396 </div>
94 ${notice === undefined ? "" : `<p class="toast" role="status">${escape(notice)}</p>`}
97 ${notice === undefined ? "" : `<p class="toast" role="status">${escape(notice)}${open === undefined ? "" : open === null ? ` ${NO_CONTACT}.` : ` <a href="${escape(open)}">${labelOf(open)}</a>`}</p>`}
9598 </body>
9699 </html>
97100 `;
src/pages/sheet.ts +6 −1
@@ -11,6 +11,7 @@ import { PARTY_LABEL } from "../deadlines.ts";
1111 import { agent } from "../env.ts";
1212 import { escape } from "../http.ts";
1313 import { memoizer, print } from "../memo.ts";
14 import { labelOf, NO_CONTACT, outbox } from "../outbox.ts";
1415 import { conflictLine } from "../order.ts";
1516 import { draftsFor, MOMENT_LABEL, MOMENTS, type Draft } from "../reminders.ts";
1617 import type { Who } from "../who.ts";
@@ -65,6 +66,10 @@ const hidden = (fields: Record<string, string | number>): string =>
6566 .map(([k, v]) => `<input type="hidden" name="${k}" value="${escape(String(v))}">`)
6667 .join("");
6768
69 /** The one link a sent reminder offers, or why there is none; nothing for a reader who may not see contacts. */
70 export const outboxLine = (href: string | null, may: boolean): string =>
71 !may ? "" : href === null ? `<p class="muted">${NO_CONTACT}</p>` : `<p><a class="button" href="${escape(href)}">${labelOf(href)}</a></p>`;
72
6873 /** The words of a draft, as the party will read them. */
6974 const draftText = (draft: Draft): string => `<div class="draft-text">
7075 <p class="muted">To ${escape(draft.contact || draft.party_name)}</p>
@@ -116,7 +121,7 @@ function draftLine(draft: Draft, on: string, withDeal: boolean): string {
116121 export function draftItem(draft: Draft, on: string, may: boolean, to: string): string {
117122 const inside =
118123 draft.sent_at !== null
119 ? draftText(draft)
124 ? `${draftText(draft)}${outboxLine(outbox(draft.contact, draft.subject, draft.body)?.href ?? null, may)}`
120125 : draft.declined !== null
121126 ? `${draftText(draft)}${may ? undoForm(draft, to) : ""}`
122127 : may
src/routes.ts +11 −9
@@ -235,6 +235,10 @@ export const DEAL: Schema = {
235235 sent_at: { type: "string" },
236236 subject: { type: "string", description: "The subject that was sent, as approved." },
237237 body: { type: "string", description: "The message that was sent, as approved." },
238 href: {
239 type: ["string", "null"],
240 description: "A mailto: or sms: link that opens the party's own Mail or Messages with these words; null when the party has no email or phone on file, or is gone.",
241 },
238242 },
239243 },
240244 },
@@ -372,7 +376,7 @@ export const routes: readonly Route[] = [
372376 method: "GET",
373377 path: "/",
374378 handle: (c) => {
375 const { notice, clear } = readNotice(c.request);
379 const { notice, open, clear } = readNotice(c.request);
376380 if (c.who.role === "anon") return html(welcomePage({ who: c.who, on: today() }), 200, clear);
377381 const deals = listDeals(c.db, c.who);
378382 if (!deals.ok)
@@ -394,7 +398,7 @@ export const routes: readonly Route[] = [
394398 400,
395399 clear,
396400 );
397 return html(clock({ who: c.who, deals: deals.value, on: today(), notice, q }), 200, clear);
401 return html(clock({ who: c.who, deals: deals.value, on: today(), notice, open, q }), 200, clear);
398402 },
399403 },
400404 {
@@ -450,8 +454,8 @@ export const routes: readonly Route[] = [
450454 }),
451455 STATUS[found.error],
452456 );
453 const { notice, clear } = readNotice(c.request);
454 return html(dealPage({ who: c.who, deal: found.value, on: today(), notice }), 200, clear);
457 const { notice, open, clear } = readNotice(c.request);
458 return html(dealPage({ who: c.who, deal: found.value, on: today(), notice, open }), 200, clear);
455459 },
456460 },
457461 {
@@ -631,11 +635,9 @@ export const routes: readonly Route[] = [
631635 handle: async (c) => {
632636 const f = await form(c);
633637 if (f instanceof Response) return f;
634 return done(
635 sendReminder(c.db, c.who, { deadlineId: Number(f.deadline), partyId: Number(f.party), moment: f.moment, subject: f.subject, body: f.body }),
636 backTo(f.to),
637 "Reminder sent (simulated).",
638 );
638 const sent = sendReminder(c.db, c.who, { deadlineId: Number(f.deadline), partyId: Number(f.party), moment: f.moment, subject: f.subject, body: f.body });
639 if (!sent.ok) return back(sent.message, backTo(f.to));
640 return back("Reminder sent.", backTo(f.to), sent.value.id);
639641 },
640642 },
641643 {
src/server.test.ts +38
@@ -748,6 +748,44 @@ test("the page offers an unsent draft as an edit form, and shows a sent one as i
748748 expect(after).not.toContain("<script>x</script>");
749749 });
750750
751 test("Send offers one link to the agent's own Mail or Messages, on the notice, the sheet and the Messages record, and the API carries href", async () => {
752 const made = await api("/api/deals", { method: "POST", ...jsonBody({ address: "7 Outbox Ct", buyer: "Bea Buyer", seller: "Sol Seller", contract_date: "2027-05-01", closing_date: "2027-06-05" }) }, editor);
753 const deal = (await made.json()) as { id: number; deadlines: { id: number; owes: string }[]; parties: { id: number; role: string }[] };
754 const [bea, sol] = [deal.parties.find((p) => p.role === "buyer")!, deal.parties.find((p) => p.role === "seller")!];
755 const edit = async (id: number, contact: string) =>
756 api(`/api/deals/${deal.id}/parties/${id}`, { method: "PATCH", ...jsonBody({ name: id === bea.id ? "Bea Buyer" : "Sol Seller", contact }) }, editor);
757 expect((await edit(bea.id, "[email protected]")).status).toBe(200);
758 const date = deal.deadlines.find((d) => d.owes === "buyer")!;
759 const send = (party: number, subject: string, body: string) => {
760 const f = new FormData();
761 for (const [k, v] of Object.entries({ deadline: String(date.id), party: String(party), moment: "before", subject, body, to: `/deals/${deal.id}` })) f.set(k, v);
762 return api("/reminders", { method: "POST", body: f, redirect: "manual" }, editor);
763 };
764 const sent = await send(bea.id, "Hello & <b>bye</b>", "Line one\nTom & Jerry #1 café");
765 const cookie = (sent.headers.get("set-cookie") ?? "").split(";")[0]!;
766 const page = await (await api(`/deals/${deal.id}`, { headers: { cookie } }, editor)).text();
767 expect(page).toContain("Reminder sent.");
768 expect(page).toContain('<a href="mailto:[email protected]?subject=Hello%20%26%20%3Cb%3Ebye%3C%2Fb%3E&amp;body=');
769 expect(page).toContain("Open in Mail");
770 const record = (await (await api(`/api/deals/${deal.id}`, {}, editor)).json()) as { sent: { party_id: number; href: string | null }[] };
771 const href = record.sent.find((m) => m.party_id === bea.id)!.href!;
772 expect(decodeURIComponent(href.split("&body=")[1]!)).toBe("Line one\nTom & Jerry #1 café");
773 expect(await (await api(`/deals/${deal.id}/sheets`, {}, editor)).text()).toContain("Open in Mail");
774 // A phone opens Messages; no contact says so.
775 expect((await edit(sol.id, "(555) 010-0199")).status).toBe(200);
776 expect(await (await api(`/deals/${deal.id}`, { headers: { cookie: (await send(sol.id, "S", "B")).headers.get("set-cookie")!.split(";")[0]! } }, editor)).text()).toContain("sms:5550100199?&amp;body=B");
777 // A stranger gets no deal at all: no href in the API, no link in the page.
778 const guestApi = await fetch(`${base}/api/deals/${deal.id}`);
779 expect(guestApi.status).toBe(401);
780 expect(await guestApi.text()).not.toMatch(/mailto:|sms:|href/);
781 const guestPage = await (await fetch(`${base}/deals/${deal.id}`)).text();
782 expect(guestPage).not.toMatch(/bea@example\.com|sms:|Open in Mail|Open in Messages|No email or phone on file/);
783 expect((await edit(sol.id, "")).status).toBe(200);
784 const none = await api(`/api/deals/${deal.id}`, {}, editor);
785 expect(((await none.json()) as { sent: { party_id: number; href: string | null }[] }).sent.find((m) => m.party_id === sol.id)!.href).toBeNull();
786 expect(await (await api(`/deals/${deal.id}`, {}, editor)).text()).toContain("No email or phone on file");
787 });
788
751789 // Last: it opens a deal that closes after every other, which the tests above take as the latest.
752790 const mia = as("u10", "mia");
753791 test("a party is corrected and removed from the page and the API; a custom date goes, a standard one is refused", async () => {
src/terminal.test.ts +43 −2
@@ -7,7 +7,7 @@ import { mkdtempSync } from "node:fs";
77 import { tmpdir } from "node:os";
88 import { join } from "node:path";
99 import { addDays, spoken, today } from "./dates.ts";
10 import { addDeadline, addParty, createDeal, getDeal, listDeals, markDone, moveDeadline, sendReminder, type DealView } from "./deals.ts";
10 import { canChange, shown, addDeadline, addParty, createDeal, editParty, getDeal, listDeals, markDone, moveDeadline, sendReminder, type DealView } from "./deals.ts";
1111 import { openDb } from "./db.ts";
1212 import { terminal, type Terminal } from "./terminal.ts";
1313 import type { Who } from "./who.ts";
@@ -40,6 +40,7 @@ const deal = (): DealView => {
4040 if (!got.ok) throw new Error(got.message);
4141 return got.value;
4242 };
43 const sentOf = () => deal().sent[0]!;
4344 const date = (kind: string) => deal().deadlines.find((d) => d.kind === kind)!;
4445
4546 test("x marks the date under the cursor done; h shows done dates; u reopens", () => {
@@ -110,7 +111,7 @@ test("r shows today's reminders; enter reads a draft; s sends it", () => {
110111 t.press("\r");
111112 expect(lines(t).join("\n")).toContain("Hi ");
112113 t.press("s");
113 expect(lines(t).join("\n")).toContain("(simulated)");
114 expect(lines(t).join("\n")).toMatch(/Recorded as sent to .*(Send it from your phone to|No email or phone on file)/s);
114115 // A late reminder, once sent, leaves today's list; one due today stays, marked sent.
115116 expect(under(t)).not.toBe(row);
116117 const sent = db.query<{ n: number }, []>("SELECT count(*) AS n FROM reminder WHERE sample = 0").get()!.n;
@@ -561,3 +562,43 @@ test("n declines a Date changed notice with a reason and u undoes it", () => {
561562 t.press("u");
562563 expect(n()).toBe(0);
563564 });
565
566 test("Send in the terminal names the exact address to send from the phone, or says there is none", () => {
567 /** Open the first reminder still to send on 12 Elm St; answer who it is for. */
568 const firstPending = () => {
569 const t = terminal(db, alice, context);
570 t.press("r");
571 for (let i = 0; i < 200 && !(under(t).includes("12 Elm St") && /to send|late/.test(under(t))); i++) t.press("j");
572 expect(under(t)).toContain("12 Elm St");
573 const name = /(?:to send|late)\s+(.+?) \(/.exec(under(t))![1]!;
574 return { t, party: deal().parties.find((p) => p.name === name)! };
575 };
576 const named = firstPending();
577 expect(editParty(db, alice, { id: named.party.id, name: named.party.name, contact: "[email protected]" }).ok).toBe(true);
578 press(named.t, "\r", "s");
579 expect(lines(named.t).join("\n")).toContain("Send it from your phone to [email protected].");
580 const bare = firstPending();
581 expect(editParty(db, alice, { id: bare.party.id, name: bare.party.name, contact: "" }).ok).toBe(true);
582 press(bare.t, "\r", "s");
583 const none = lines(bare.t).join("\n");
584 expect(none).toContain("No email or phone on file.");
585 expect(none).not.toContain("Send it from your phone");
586 });
587
588 test("the Messages view shows who a sent message goes to", () => {
589 const t = terminal(db, alice, context);
590 goTo(t, "12 Elm St");
591 press(t, "o", "s", "\r");
592 expect(lines(t).join("\n")).toMatch(/To \S+@\S+: send it from your phone|No email or phone on file/);
593 });
594
595 test("a reader who may not change a deal sees no contact and no link", () => {
596 const view = { ...deal(), parties: deal().parties.map((p) => ({ ...p, contact: "[email protected]" })), sent: [{ ...(sentOf()), href: "mailto:[email protected]?subject=s&body=b" }] };
597 const seen = shown({ role: "user", id: "u-reader", name: "reader" }, view);
598 expect(canChange({ role: "user", id: "u-reader", name: "reader" }, view)).toBe(true);
599 // With today's table every reader may work the deal; `shown` is what holds when update narrows.
600 expect(seen).toBe(view);
601 const narrowed = shown({ role: "anon" }, view);
602 expect(narrowed.parties.every((p) => p.contact === "")).toBe(true);
603 expect(narrowed.sent.every((m) => m.href === null)).toBe(true);
604 });
src/terminal.ts +5 −1
@@ -295,7 +295,7 @@ export function terminal(
295295 body: draft.body,
296296 });
297297 if (sent.ok) edits.delete(id);
298 said = report(sent, `Sent to ${draft.party_name} (simulated): ${draft.label}, ${draft.address}.`);
298 said = report(sent, `Recorded as sent to ${draft.party_name}: ${draft.label}, ${draft.address}. ${draft.contact === "" ? "No email or phone on file." : `Send it from your phone to ${draft.contact}.`}`);
299299 }
300300 return true;
301301 }
@@ -507,6 +507,10 @@ export function terminal(
507507 const role = m.party_role === "" ? "" : ` (${PARTY_LABEL[m.party_role].toLowerCase()})`;
508508 const text = `${m.party_name}${role} · ${m.label}, ${spoken(m.due)} · ${MOMENT_LABEL[m.moment].toLowerCase()}`;
509509 lines.push(`${i === cursor ? "▸" : " "} ${dim(`sent ${m.sent_at.slice(0, 10)}`.padEnd(16))} ${i === cursor ? bold(text) : text}`);
510 if (reading === i && canChange(me, deal)) {
511 const to = deal.parties.find((p) => p.id === m.party_id)?.contact ?? "";
512 lines.push("", ` ${dim(to === "" ? "No email or phone on file" : `To ${to}: send it from your phone`)}`);
513 }
510514 if (reading === i) lines.push("", ` ${bold(m.subject === "" ? "(words not kept)" : m.subject)}`, ...m.body.split("\n").map((l) => ` ${l}`), "");
511515 });
512516 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs