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

An admin can read every approved message and change on an Activity page #20

Merged opened this

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

Merged

mason/speed-to-lead:mason/17-an-admin-can-read-every-approved-message → main 2 commits fork 3 threads · 3 unresolved

  • Merged. mason/17-an-admin-can-read-every-approved-message was merged into main as cc26296.

Review

Sign in to review this change.
13 files changed +434 −15
README.md +2
@@ -74,6 +74,8 @@ waited so far, so a red clock pulls both numbers down until you answer it.
7474 With no replies yet it says so. The same figures are in `GET /leads`
7575 (`record`) and on the terminal desk.
7676
77 Admins can read the **Activity** page (`/activity`): every change and refused attempt in plain sentences, newest first, 50 to a page, with a "Messages sent only" filter. In the terminal an admin presses `a` on the desk (`o` older, `n` newer, `m` messages sent only).
78
7779 Once you've replied, the clock stops and shows how long it took.
7880
7981 **Tap a lead** to see what they wrote beside the reply drafted for them.
contract/openapi.json +6
@@ -1213,6 +1213,12 @@
12131213 },
12141214 "outcome": {
12151215 "type": "string"
1216 },
1217 "act": {
1218 "type": [
1219 "string",
1220 "null"
1221 ]
12161222 }
12171223 },
12181224 "required": [
src/actions.ts +77 −6
@@ -7,7 +7,7 @@
77 */
88
99 import type { Database } from "bun:sqlite";
10 import { record, type AuditRow } from "./audit.ts";
10 import { record, type Act, type AuditRow } from "./audit.ts";
1111 import { permit } from "./contract.ts";
1212 import { MAX_BODY, SOURCES, type Source } from "./drafts.ts";
1313 import type { Agent } from "./env.ts";
@@ -18,6 +18,7 @@ import {
1818 countViews,
1919 desk,
2020 detail,
21 findLead,
2122 inView,
2223 insertLead,
2324 readyFor,
@@ -62,8 +63,10 @@ const audited = <T extends { readonly id: number }>(
6263 verb: "create" | "update" | "delete",
6364 target: number | undefined,
6465 result: Result<T>,
66 act?: Act,
6567 ): Result<T> => {
6668 record(db, {
69 ...(act === undefined ? {} : { act }),
6770 who,
6871 resource,
6972 verb,
@@ -235,8 +238,18 @@ export const sendReply = (
235238 who: Who,
236239 input: { id: number; body?: string | undefined },
237240 at?: Date,
238 ): Result<LeadDetail> =>
239 audited(db, who, "lead", "update", input.id, reply(db, who, input, at));
241 ): Result<LeadDetail> => {
242 const first = findLead(db, input.id)?.replied_at === null;
243 return audited(
244 db,
245 who,
246 "lead",
247 "update",
248 input.id,
249 reply(db, who, input, at),
250 first ? "first_reply" : "reply",
251 );
252 };
240253
241254 function reply(
242255 db: Database,
@@ -274,7 +287,17 @@ export const setState = (
274287 input: { id: number; state: unknown },
275288 at?: Date,
276289 ): Result<LeadDetail> =>
277 audited(db, who, "lead", "update", input.id, mark(db, who, input, at));
290 audited(
291 db,
292 who,
293 "lead",
294 "update",
295 input.id,
296 mark(db, who, input, at),
297 input.state === "qualified" || input.state === "lost"
298 ? input.state
299 : undefined,
300 );
278301
279302 function mark(
280303 db: Database,
@@ -460,7 +483,7 @@ function change(
460483 export function listAudit(
461484 db: Database,
462485 who: Who,
463 input: { limit?: number; before?: number } = {},
486 input: { limit?: number; before?: number; sentOnly?: boolean } = {},
464487 ): Result<AuditRow[]> {
465488 if (permit(who, "audit", "list") !== "yes")
466489 return refuse(
@@ -480,11 +503,59 @@ export function listAudit(
480503 .query<
481504 AuditRow,
482505 [number, number]
483 >("SELECT * FROM audit WHERE id < ?1 ORDER BY id DESC LIMIT ?2")
506 >(
507 input.sentOnly === true
508 ? "SELECT * FROM audit WHERE act IN ('reply', 'first_reply') AND id < ?1 ORDER BY id DESC LIMIT ?2"
509 : "SELECT * FROM audit WHERE id < ?1 ORDER BY id DESC LIMIT ?2",
510 )
484511 .all(before, limit),
485512 );
486513 }
487514
515 /** Rows on one page of the Activity page. */
516 export const ACTIVITY_PAGE = 50;
517
518 export interface Activity {
519 readonly rows: AuditRow[];
520 /** Lead names by id; a lead since removed has none. */
521 readonly names: ReadonlyMap<number, string>;
522 /** The id to page back from, when older rows exist. */
523 readonly older: number | undefined;
524 }
525
526 /** One page of the audit trail with the leads' names looked up, for the Activity page. */
527 export function activity(
528 db: Database,
529 who: Who,
530 input: { before?: number; sentOnly?: boolean },
531 ): Result<Activity> {
532 const found = listAudit(db, who, { ...input, limit: ACTIVITY_PAGE + 1 });
533 if (!found.ok) return found;
534 const rows = found.value.slice(0, ACTIVITY_PAGE);
535 const ids = [
536 ...new Set(
537 rows
538 .filter((r) => r.resource === "lead" && r.target !== null)
539 .map((r) => Number(r.target))
540 .filter(Number.isSafeInteger),
541 ),
542 ];
543 const names = new Map<number, string>();
544 if (ids.length > 0)
545 for (const lead of db
546 .query<{ id: number; name: string }, number[]>(
547 `SELECT id, name FROM lead WHERE id IN (${ids.map(() => "?").join(",")})`,
548 )
549 .all(...ids))
550 names.set(lead.id, lead.name);
551 return ok({
552 rows,
553 names,
554 older:
555 found.value.length > ACTIVITY_PAGE ? rows[rows.length - 1]!.id : undefined,
556 });
557 }
558
488559 export function getAudit(
489560 db: Database,
490561 who: Who,
src/audit.test.ts +94 −3
@@ -7,16 +7,18 @@ import { afterAll, expect, spyOn, test } from "bun:test";
77 import { mkdtempSync } from "node:fs";
88 import { tmpdir } from "node:os";
99 import { join } from "node:path";
10 import { addLead } from "./actions.ts";
10 import { addLead, listAudit, sendReply, setState } from "./actions.ts";
1111 import type { AuditRow } from "./audit.ts";
12 import { record } from "./audit.ts";
1213 import { openDb } from "./db.ts";
1314 import { serve } from "./server.ts";
14 import { sign } from "./who.ts";
15 import { sign, type Who } from "./who.ts";
1516
1617 const KEY = "a-key-only-the-forge-holds";
18 const dir = mkdtempSync(join(tmpdir(), "app-audit-"));
1719 const server = serve({
1820 port: 0,
19 dataDir: mkdtempSync(join(tmpdir(), "app-audit-")),
21 dataDir: dir,
2022 identityKey: KEY,
2123 sample: false,
2224 });
@@ -195,3 +197,92 @@ test("a trail that cannot be written is a log line, and the change still happens
195197 said.mockRestore();
196198 }
197199 });
200
201 const page = (path: string, who: Record<string, string> = {}) =>
202 fetch(base + path, { headers: who });
203 const admin = { id: "u0", name: "Jordan <b>Avery", role: "admin" as const };
204
205 test("/activity: an admin reads a sent reply and a refused attempt in sentences; a user is refused; a visitor is asked to sign in", async () => {
206 const lead = (await (
207 await call("/leads", { method: "POST", body: JSON.stringify({ ...NEW, name: "Maria <script>x</script>" }) }, alice)
208 ).json()) as { id: number };
209 await call(`/leads/${lead.id}/reply`, { method: "POST", body: "{}" }, root);
210 await call(`/leads/${lead.id}/state`, { method: "POST", body: JSON.stringify({ state: "lost" }) }, root);
211 const refused = await call(`/leads/${lead.id}/reply`, { method: "POST", body: "{}" });
212 expect(refused.status).toBe(401);
213
214 const seen = await (await page("/activity", root)).text();
215 expect(seen).toContain("root approved and sent the first reply to");
216 expect(seen).toContain(`<a href="/leads/${lead.id}">Maria &lt;script&gt;x&lt;/script&gt;</a>`);
217 expect(seen).not.toContain("<script>x");
218 expect(seen).toContain("marked");
219 expect(seen).toContain(" lost");
220 expect(seen).toContain("A visitor tried to send a reply to");
221 expect(seen).toContain("refused");
222 expect(seen).toContain('href="/activity"');
223
224 const user = await page("/activity", alice);
225 expect(user.status).toBe(403);
226 expect(await user.text()).not.toContain("approved and sent");
227 expect((await page("/activity", alice).then((r) => r.text()))).not.toContain('href="/activity"');
228 const visitor = await page("/activity");
229 expect(visitor.status).toBe(401);
230 expect(await visitor.text()).toContain("Sign in");
231 });
232
233 test("/activity: the sent filter keeps replies only, a removed lead is named so, and pages hold 50 with an Older link", async () => {
234 const db = openDb(dir);
235 const root0 = { ...admin, name: "Jordan Avery" };
236 for (let i = 0; i < 55; i++)
237 record(db, { who: root0, resource: "lead", verb: "update", target: 987654, outcome: "ok", act: "reply" });
238 record(db, { who: root0, resource: "profile", verb: "update", target: 1, outcome: "ok" });
239 db.close();
240
241 const sent = await (await page("/activity?show=sent", root)).text();
242 expect(sent).not.toContain("changed the agent profile");
243 expect(sent).toContain("Jordan Avery approved and sent a reply to a removed lead");
244 const all = await (await page("/activity", root)).text();
245 expect(all).toContain("changed the agent profile");
246 expect(all.match(/class="activity-row"/g)!.length).toBe(50);
247 const older = all.match(/href="(\/activity\?before=\d+)"/)![1]!;
248 const next = await (await page(older, root)).text();
249 expect(next.match(/class="activity-row"/g)!.length).toBeGreaterThan(0);
250 expect(next).not.toContain("changed the agent profile");
251 const onSent = (await (await page("/activity?show=sent", root)).text()).match(/href="(\/activity\?before=\d+&amp;show=sent)"/);
252 expect(onSent).not.toBeNull();
253 });
254
255 const admin0: Who = { role: "admin", id: "u0", name: "root" };
256
257 test("act is recorded as first_reply, reply, qualified and lost", () => {
258 const db = openDb(mkdtempSync(join(tmpdir(), "app-audit-act-")));
259 const one = addLead(db, admin0, NEW);
260 const two = addLead(db, admin0, { ...NEW, name: "Second" });
261 const three = addLead(db, admin0, { ...NEW, name: "Third" });
262 if (!one.ok || !two.ok || !three.ok) throw new Error("setup");
263 sendReply(db, admin0, { id: one.value.id });
264 // Later touches are due days after; send the next one by moving time on.
265 const later = new Date(Date.now() + 2 * 86_400_000);
266 db.query("UPDATE message SET status = 'due' WHERE lead_id = ?1 AND status = 'scheduled'").run(one.value.id);
267 sendReply(db, admin0, { id: one.value.id }, later);
268 setState(db, admin0, { id: two.value.id, state: "qualified" });
269 setState(db, admin0, { id: three.value.id, state: "lost" });
270 const acts = db
271 .query<{ act: string | null }, []>("SELECT act FROM audit WHERE verb = 'update' ORDER BY id")
272 .all()
273 .map((r) => r.act);
274 expect(acts).toEqual(["first_reply", "reply", "qualified", "lost"]);
275 });
276
277 test("listAudit sentOnly keeps only sent replies; without it every row comes", () => {
278 const db = openDb(mkdtempSync(join(tmpdir(), "app-audit-sent-")));
279 const one = addLead(db, admin0, NEW);
280 if (!one.ok) throw new Error("setup");
281 sendReply(db, admin0, { id: one.value.id });
282 setState(db, admin0, { id: one.value.id, state: "lost" });
283 const sent = listAudit(db, admin0, { sentOnly: true });
284 expect(sent.ok && sent.value.map((r) => r.act)).toEqual(["first_reply"]);
285 const all = listAudit(db, admin0, {});
286 expect(all.ok && all.value.map((r) => r.act)).toEqual(["lost", "first_reply", null]);
287 expect(listAudit(db, { role: "user", id: "u1", name: "a" }, { sentOnly: true }).ok).toBe(false);
288 });
src/audit.ts +11 −2
@@ -28,14 +28,21 @@ export interface AuditRow {
2828 readonly allowed: 0 | 1;
2929 /** `ok`, or the failure: `signin_required`, `forbidden`, `invalid`, `not_found`, `cross_site`. */
3030 readonly outcome: string;
31 /** What a lead change was, when it is known: see `Act`. */
32 readonly act: string | null;
3133 }
3234
35 /** Messages sent are `reply` and `first_reply`; a close is `qualified` or `lost`. */
36 export const ACTS = ["reply", "first_reply", "qualified", "lost"] as const;

ACTS is unused anywhere. Use it or delete it.

37 export type Act = (typeof ACTS)[number];
38
3339 export interface Attempt {
3440 readonly who: Who;
3541 readonly resource: string;
3642 readonly verb: string;
3743 readonly target?: string | number | undefined;
3844 readonly outcome: string;
45 readonly act?: Act | undefined;
3946 }
4047
4148 /** The newest rows kept; older ones go as new ones come. */
@@ -48,7 +55,7 @@ export const allowed = (outcome: string): boolean =>
4855 outcome !== "cross_site";
4956
5057 export function record(db: Database, attempt: Attempt): void {
51 const { who, resource, verb, target, outcome } = attempt;
58 const { who, resource, verb, target, outcome, act } = attempt;
5259 const row = {
5360 who_id: who.role === "anon" ? null : who.id,
5461 who_name: who.role === "anon" ? null : who.name,
@@ -58,11 +65,12 @@ export function record(db: Database, attempt: Attempt): void {
5865 target: target === undefined ? null : String(target),
5966 allowed: allowed(outcome) ? 1 : 0,
6067 outcome,
68 act: act !== undefined && ACTS.includes(act) ? act : null,
6169 };
6270 try {
6371 const { lastInsertRowid } = db
6472 .query(
65 "INSERT INTO audit (who_id, who_name, role, resource, verb, target, allowed, outcome) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
73 "INSERT INTO audit (who_id, who_name, role, resource, verb, target, allowed, outcome, act) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
6674 )
6775 .run(
6876 row.who_id,
@@ -73,6 +81,7 @@ export function record(db: Database, attempt: Attempt): void {
7381 row.target,
7482 row.allowed,
7583 row.outcome,
84 row.act,
7685 );
7786 db.query("DELETE FROM audit WHERE id <= ?1").run(
7887 Number(lastInsertRowid) - KEEP,
src/db.ts +4
@@ -94,6 +94,10 @@ export const migrations: string[] = [
9494 updated_at TEXT NOT NULL,
9595 updated_by TEXT NOT NULL
9696 )`,
97 // What a lead change was (`reply`, `first_reply`, `qualified`, `lost`), so
98 // the Activity page can say it and filter to messages sent. Older rows have none.
99 `ALTER TABLE audit ADD COLUMN act TEXT`,
100 `CREATE INDEX audit_act ON audit (act, id)`,
97101 ];
98102
99103 export function openDb(dir = dataDir): Database {
src/pages/activity.ts added +62
@@ -0,0 +1,62 @@
1 /**
2 * Activity: the audit trail in plain sentences, newest first, for admins.
3 * Every name is escaped; a lead that has since been removed is "a removed lead".
4 */
5
6 import type { Activity } from "../actions.ts";
7 import type { AuditRow } from "../audit.ts";
8 import type { Agent } from "../env.ts";
9 import { escape } from "../http.ts";
10 import { said } from "../sentences.ts";
11 import type { Who } from "../who.ts";
12 import { layout } from "./layout.ts";
13 import { when } from "./parts.ts";
14
15 /** The lead a row is about, as a link, or as what it has become. */
16 const leadOf = (row: AuditRow, names: ReadonlyMap<number, string>): string => {
17 const name = names.get(Number(row.target));
18 return name === undefined
19 ? "a removed lead"
20 : `<a href="/leads/${Number(row.target)}">${escape(name)}</a>`;
21 };
22
23 function sentence(row: AuditRow, names: ReadonlyMap<number, string>): string {
24 const text = said(row, leadOf(row, names), escape);
25 const refused =
26 row.allowed === 1
27 ? ""
28 : ` <span class="chip" data-state="lost">refused</span>`;
29 return `<li class="activity-row">${text}${refused} <span class="muted">· ${escape(when(row.at))}</span></li>`;
30 }
outdated

'your profile' is wrong when the reader is not the actor. Use 'the agent profile'.

31
32 export function activityPage(input: {
33 who: Who;
34 agent: Agent;
35 rows: readonly AuditRow[];
36 names: ReadonlyMap<number, string>;
37 older: number | undefined;
38 sentOnly: boolean;
39 }): string {
40 const { who, agent, rows, names, older, sentOnly } = input;
41 const filter = sentOnly ? "&amp;show=sent" : "";
42 const links = `<nav class="row" aria-label="Filter">
43 <a class="button button-quiet" href="/activity"${sentOnly ? "" : ' aria-current="page"'}>Everything</a>
44 <a class="button button-quiet" href="/activity?show=sent"${sentOnly ? ' aria-current="page"' : ""}>Messages sent only</a>
45 </nav>`;
46 const list =
47 rows.length === 0
48 ? `<p class="empty">Nothing here yet.</p>`
49 : `<ul class="card stack activity">${rows.map((r) => sentence(r, names)).join("\n")}</ul>`;
50 return layout({
51 who,
52 agent,
53 path: "/activity",
54 heading: "Activity",
55 body: `<p><a class="backlink" href="/">← All leads</a></p>
56 <h1>Activity</h1>
57 <p class="muted">Every change, newest first, and who made it. Refused attempts are shown too.</p>
58 ${links}
59 ${list}
60 ${older === undefined ? "" : `<p><a class="button button-quiet" href="/activity?before=${older}${filter}">Older</a></p>`}`,
61 });
62 }
src/pages/layout.ts +1 −1
@@ -28,7 +28,7 @@ export function layout(input: {
2828 const door =
2929 who.role === "anon"
3030 ? `<a class="button button-quiet" href="/__forge/signin?to=${escape(encodeURIComponent(path))}">Sign in</a>`
31 : `<a class="button button-quiet" href="/profile">Your profile</a>
31 : `${who.role === "admin" ? '<a class="button button-quiet" href="/activity">Activity</a>\n ' : ""}<a class="button button-quiet" href="/profile">Your profile</a>
3232 <span class="you">${escape(who.name)}</span>
3333 <a class="button button-quiet" href="/__forge/signout">Sign out</a>`;
3434 return `<!doctype html>
src/routes.ts +33
@@ -16,6 +16,7 @@ import { existsSync, readFileSync } from "node:fs";
1616 import {
1717 addLead,
1818 deleteLead,
19 activity,
1920 getAudit,
2021 getLead,
2122 getProfile,
@@ -52,6 +53,7 @@ import { rpc } from "./mcp.ts";
5253 import { deskPage } from "./pages/desk.ts";
5354 import { layout } from "./pages/layout.ts";
5455 import { leadPage } from "./pages/lead.ts";
56 import { activityPage } from "./pages/activity.ts";
5557 import { profilePage } from "./pages/profile.ts";
5658 import { currentAgent } from "./profile.ts";
5759 import { tokensCss } from "./tokens.ts";
@@ -207,6 +209,7 @@ export const AUDIT_ROW: Schema = {
207209 target: { type: ["string", "null"] },
208210 allowed: { enum: [0, 1] },
209211 outcome: { type: "string" },
212 act: { type: ["string", "null"] },
210213 },
211214 required: ["id", "at", "role", "resource", "verb", "allowed", "outcome"],
212215 };
@@ -577,6 +580,36 @@ export const routes: readonly Route[] = [
577580 },
578581 },
579582
583 // The audit trail in words, for whoever the table lets read it.

This adds an admin read door to the page only. src/tty.ts has no equivalent. Add it there, calling activity(), with a test and a README line.

584 {
585 method: "GET",
586 path: "/activity",
587 handle: (c) => {
588 const sentOnly = c.url.searchParams.get("show") === "sent";
589 const found = activity(c.db, c.who, {
590 sentOnly,
591 ...(whole(c.url.searchParams.get("before")) === undefined
592 ? {}
593 : { before: whole(c.url.searchParams.get("before"))! }),
594 });
595 const agent = currentAgent(c.db);
596 if (!found.ok)
597 return html(
598 layout({
599 who: c.who,
600 agent,
601 path: c.url.pathname,
602 heading: "Activity",
603 body: `<p class="empty">${escape(found.message)} <a href="/">Back to the desk</a></p>`,
604 }),
605 STATUS[found.error],
606 );
607 return html(
608 activityPage({ who: c.who, agent, ...found.value, sentOnly }),
609 );
610 },
611 },
612
580613 // Who tried to change what: the audit trail, for whoever the table lets read it.
581614 {
582615 method: "GET",
src/sentences.ts added +52
@@ -0,0 +1,52 @@
1 /**
2 * An audit row in words, shared by the Activity page and the terminal: the
3 * clause for what was done, and for what was tried when the door said no.
4 * `lead` is the lead already drawn for its door (a link, or plain text) and
5 * `esc` makes the row's own words safe for that door.
6 */
7
8 import type { AuditRow } from "./audit.ts";
9
10 export function deed(
11 row: AuditRow,
12 lead: string,
13 esc: (text: string) => string,
14 ): { done: string; tried: string } {
15 if (row.resource === "profile")
16 return {
17 done: "changed the agent profile",
18 tried: "change the agent profile",
19 };
20 if (row.resource === "lead") {
21 if (row.act === "first_reply" || row.act === "reply") {
22 const kind = row.act === "first_reply" ? "the first reply" : "a reply";
23 return {
24 done: `approved and sent ${kind} to ${lead}`,
25 tried: `send ${kind} to ${lead}`,
26 };
27 }
28 if (row.act === "qualified" || row.act === "lost")
29 return {
30 done: `marked ${lead} ${row.act}`,
31 tried: `mark ${lead} ${row.act}`,
32 };
33 if (row.verb === "create")
34 return { done: "added a lead", tried: "add a lead" };
35 if (row.verb === "delete")
36 return { done: "removed a lead", tried: "remove a lead" };
37 return { done: `changed ${lead}`, tried: `change ${lead}` };
38 }
39 const other = `${esc(row.verb)} ${esc(row.resource)}`;
40 return { done: other, tried: other };
41 }
42
43 /** "Jordan Avery approved…" or "A visitor tried to …". */
44 export const said = (
45 row: AuditRow,
46 lead: string,
47 esc: (text: string) => string,
48 ): string => {
49 const who = esc(row.who_name ?? "A visitor");
50 const { done, tried } = deed(row, lead, esc);
51 return row.allowed === 1 ? `${who} ${done}` : `${who} tried to ${tried}`;
52 };
src/terminal.test.ts +23
@@ -294,3 +294,26 @@ test("f cycles the desk's views; each shows its count and only its leads", () =>
294294 t.key("f");
295295 expect(read(t)).toContain("[All ");
296296 });
297
298 test("a opens Activity: an admin reads sentences and filters to messages sent; a user and a guest see none", () => {
299 const db = fresh();
300 const one = (listLeads(db, root) as { ok: true; value: { leads: { id: number }[] } }).value.leads[0]!;
301 const t = terminal(db, root);
302 t.key("\r");
303 t.key("s");
304 t.key("\x1b");
305 t.key("a");
306 expect(read(t)).toContain(`root approved and sent the first reply to`);
307 expect(read(t)).toContain("Maria Gonzalez");
308 t.key("m");
309 expect(read(t)).toContain("messages sent");
310 expect(read(t)).not.toContain("changed the agent profile");
311 expect(one.id).toBeGreaterThan(0);
312
313 for (const who of [alice, guest]) {
314 const other = terminal(db, who);
315 other.key("a");
316 expect(read(other)).not.toContain("approved and sent");
317 expect(read(other)).toMatch(/Sign in|Only an admin/);
318 }
319 });
src/terminal.ts +63 −3
@@ -5,7 +5,7 @@
55 * may — the hints only leave out keys the table would refuse.
66 *
77 * Screens:
8 * desk j/k move · enter open · f view (needs/open/closed/all) · n log a lead · p profile · R restart samples (admin) · esc quit
8 * desk j/k move · enter open · f view (needs/open/closed/all) · n log a lead · p profile · a activity (admin) · R restart samples (admin) · esc quit
99 * lead s approve and send · e edit, then send · q qualified · x lost ·
1010 * D remove (admin) · esc back
1111 * edit type; enter is a new line · ctrl-d approve and send · esc cancel
@@ -13,6 +13,8 @@
1313 * profile the name, brokerage and license every message carries ·
1414 * e edit (admin): one field at a time, enter next, the last saves · esc back
1515 *
16 * activity every change in words, newest first (admin) · o older · n newer · m messages sent only · esc back
17 *
1618 * Nothing is sent from a screen that has not shown it: the lead screen
1719 * shows what they asked, the words going out, the signature under them,
1820 * and whether it goes by text or email.
@@ -20,6 +22,7 @@
2022
2123 import type { Database } from "bun:sqlite";
2224 import {
25 activity,
2326 addLead,
2427 deleteLead,
2528 getLead,
@@ -32,6 +35,7 @@ import {
3235 } from "./actions.ts";
3336 import { between, elapsed, recordLine, tone } from "./clock.ts";
3437 import { permit } from "./contract.ts";
38 import { said as saidOf } from "./sentences.ts";
3539 import { SOURCE_LABEL, SOURCES, channelFor } from "./drafts.ts";
3640 import { ssh, title, where } from "./env.ts";
3741 import { VIEWS, type DeskLead, type LeadDetail, type Message, type View as DeskView } from "./leads.ts";
@@ -100,6 +104,7 @@ const PROFILE_FIELDS = [
100104 type View =
101105 | { name: "desk" }
102106 | { name: "profile" }
107 | { name: "activity"; sentOnly: boolean; before: number[] }
103108 | { name: "profile-edit"; step: number; typed: string; fields: Record<string, string> }
104109 | { name: "lead"; id: number }
105110 | { name: "edit"; id: number; text: string }
@@ -202,7 +207,7 @@ export function terminal(
202207 lines.push(
203208 "",
204209 dim(
205 `j/k move · enter open · f view · n log a lead · p profile${admin() ? " · R restart the samples" : ""} · esc quit`,
210 `j/k move · enter open · f view · n log a lead · p profile${admin() ? " · a activity" : ""}${admin() ? " · R restart the samples" : ""} · esc quit`,
206211 ),
207212 );
208213 return lines;
@@ -297,6 +302,40 @@ export function terminal(
297302 ];
298303 }
299304
305 function activityScreen(v: Extract<View, { name: "activity" }>): string[] {
306 const before = v.before[v.before.length - 1];
307 const found = activity(db, me, {
308 sentOnly: v.sentOnly,
309 ...(before === undefined ? {} : { before }),
310 });
311 if (!found.ok) return [found.message, "", dim("esc back")];
312 const { rows, names, older } = found.value;
313 const lines = [bold(v.sentOnly ? "Activity — messages sent" : "Activity"), ""];
314 if (rows.length === 0) lines.push(dim("Nothing here yet."));
315 for (const row of rows) {
316 const name = names.get(Number(row.target));
317 const text = saidOf(
318 row,
319 name === undefined ? "a removed lead" : clean(name),
320 clean,
321 );
322 const at = new Date(row.at).toLocaleString("en-US", {
323 month: "short",
324 day: "numeric",
325 hour: "numeric",
326 minute: "2-digit",
327 });
328 lines.push(`${text}${row.allowed === 1 ? "" : " (refused)"} ${dim(`· ${at}`)}`);
329 }
330 lines.push(
331 "",
332 dim(
333 `${older === undefined ? "" : "o older · "}${v.before.length > 0 ? "n newer · " : ""}m ${v.sentOnly ? "everything" : "messages sent only"} · esc back`,
334 ),
335 );
336 return lines;
337 }
338
300339 function profileEditScreen(v: Extract<View, { name: "profile-edit" }>): string[] {
301340 const lines = [bold("Your profile — editing"), ""];
302341 PROFILE_FIELDS.forEach((field, i) => {
@@ -355,7 +394,9 @@ export function terminal(
355394 const body =
356395 view.name === "desk"
357396 ? deskScreen()
358 : view.name === "profile"
397 : view.name === "activity"
398 ? activityScreen(view)
399 : view.name === "profile"
359400 ? profileScreen()
360401 : view.name === "profile-edit"
361402 ? profileEditScreen(view)
@@ -396,10 +437,29 @@ export function terminal(
396437 } else if (input === "n")
397438 view = { name: "add", step: 0, typed: "", fields: {} };
398439 else if (input === "p") view = { name: "profile" };
440 else if (input === "a")
441 view = { name: "activity", sentOnly: false, before: [] };
399442 else if (input === "R")
400443 view = { name: "confirm", what: "reset", back: view };
401444 return;
402445 }
446 case "activity": {
447 if (input === "\x1b" || input === "\x7f") view = { name: "desk" };
448 else if (input === "m")
449 view = { name: "activity", sentOnly: !view.sentOnly, before: [] };
450 else if (input === "n" && view.before.length > 0)
451 view = { ...view, before: view.before.slice(0, -1) };
452 else if (input === "o") {
453 const before = view.before[view.before.length - 1];
454 const found = activity(db, me, {
455 sentOnly: view.sentOnly,
456 ...(before === undefined ? {} : { before }),
457 });
458 if (found.ok && found.value.older !== undefined)
459 view = { ...view, before: [...view.before, found.value.older] };
460 }
461 return;
462 }
403463 case "profile": {
404464 if (input === "\x1b" || input === "\x7f") view = { name: "desk" };
405465 else if (input === "e") {
static/app.css +6
@@ -590,3 +590,9 @@ label.check input {
590590 animation: none;
591591 }
592592 }
593
594 /* Activity. */
595 .activity {
596 list-style: none;
597 padding-left: var(--space-4);
598 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs