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

The agent stars the leads they want to keep close, and starred leads lead the desk #87

Merged opened this

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

Merged

mason/speed-to-lead:mason/82-the-agent-stars-the-leads-they-want-to-k → main 2 commits fork 2 threads · 2 unresolved

  • Merged. mason/82-the-agent-stars-the-leads-they-want-to-k was merged into main as 42ab7a5.

Review

Sign in to review this change.
24 files changed +516 −30
AGENTS.md +5
@@ -135,6 +135,11 @@ Speed to Lead is one realtor's desk. The concepts, one module each:
135135 check-in message numbered `CHECK_IN_DAY` + n (300…399) comes due at 8:00 on
136136 the date in the agent's zone. Writing back, closing and sending the check-in
137137 clear it. `inView` keeps a put-away lead out of `needs` and `open`.
138 - Starred: a lead the agent keeps close (`setStar`/`starredFirst` in
139 `src/leads.ts`, the `starred` column). It is a flag, not a state, and it does
140 not touch the cadence. `starredFirst` lifts starred open leads to the top of
141 any view but leaves a first reply past the green clock ahead of them, and does
142 nothing while nobody is starred. `show=starred` is a view of its own.
138143 - `src/drafts.ts` — the words: templates filled from the inquiry and the
139144 agent's profile (`src/profile.ts`: the saved one, else the `AGENT_*`
140145 defaults of `agent` in `src/env.ts`; its `openers` are the agent's own
README.md +12
@@ -79,6 +79,10 @@ what you see right after a restart. Do step 1 first.
7979 day; at 8:00 that morning in your time zone a check-in draft waits for you
8080 to approve. **Hannah Wright** is already put away for sixty days. "Bring
8181 back now" clears the day, and so does a lead writing back.
82 Keep your best leads close with the star: tap ☆ on a desk row or under a
83 lead's name (one tap, no JavaScript needed). Starred open leads sort first
84 under every filter, and *Starred* is a filter of its own. A first reply
85 that has waited past five minutes still comes before the stars.
8286 8. Set your profile (admin to save). Press "Your profile" at the top, fill
8387 in your name, brokerage, license number, phone and email, and save. Every
8488 draft not yet sent takes it at once.
@@ -333,6 +337,14 @@ for a bad date), the MCP tool `put_lead_away`, and `a` (put away) and `A`
333337 change to a lead, and the Activity page says "put … away until …" and "brought
334338 … back".
335339
340 Starring a lead keeps it close: `PATCH /leads/:id` with `{"starred": true}` (or
341 `false`; `422` for anything else), the page's `POST /leads/:id/star`, the MCP
342 tool `star_lead`, and `*` on the terminal's desk and lead screens. A lead's JSON
343 and the CSV export carry it (`starred`, the CSV's last column, `yes` or `no`),
344 `GET /leads?show=starred` lists the starred open leads, and the Activity page
345 says "starred …" and "took the star off …". It needs the same permission as any
346 change to a lead; the policy table is unchanged.
347
336348 **Quiet hours.** Texts go out only between 8:00 a.m. and 9:00 p.m. in your
337349 time zone, the window realtors are told to keep. Approve a text at 11 p.m.
338350 and the app does not send it: it is approved, held, and the lead's page and
contract/openapi.json +26 −4
@@ -29,9 +29,10 @@
2929 "needs",
3030 "open",
3131 "closed",
32 "starred",
3233 "all"
3334 ],
34 "description": "needs: a reply or follow-up waits on you; open: in follow-up, nothing waiting (not put away until a date); closed: qualified or lost; all (default, also for any other value)."
35 "description": "needs: a reply or follow-up waits on you; open: in follow-up, nothing waiting (not put away until a date); closed: qualified or lost; starred: open leads you starred; all (default, also for any other value)."
3536 }
3637 },
3738 {
@@ -166,9 +167,10 @@
166167 "needs",
167168 "open",
168169 "closed",
170 "starred",
169171 "all"
170172 ],
171 "description": "needs: a reply or follow-up waits on you; open: in follow-up, nothing waiting (not put away until a date); closed: qualified or lost; all (default, also for any other value)."
173 "description": "needs: a reply or follow-up waits on you; open: in follow-up, nothing waiting (not put away until a date); closed: qualified or lost; starred: open leads you starred; all (default, also for any other value)."
172174 }
173175 },
174176 {
@@ -526,7 +528,7 @@
526528 }
527529 },
528530 "patch": {
529 "summary": "Mark a lead qualified or lost (the same as POST /leads/{id}/state), correct its name, email or phone (the same as POST /leads/{id}/edit), keep a private note on it (the same as POST /leads/{id}/note), or put it away until a day with back_on (YYYY-MM-DD, from tomorrow to 365 days out in the profile's time zone; null brings it back now): send one of the four. Putting it away sets unsent follow-ups aside, and at 8:00 that morning a check-in draft waits on the desk; a bad date is a 422 naming back_on.",
531 "summary": "Mark a lead qualified or lost (the same as POST /leads/{id}/state), correct its name, email or phone (the same as POST /leads/{id}/edit), keep a private note on it (the same as POST /leads/{id}/note), star it or take the star off with starred (true or false), or put it away until a day with back_on (YYYY-MM-DD, from tomorrow to 365 days out in the profile's time zone; null brings it back now): send one of the five. Putting it away sets unsent follow-ups aside, and at 8:00 that morning a check-in draft waits on the desk; a bad date is a 422 naming back_on.",
530532 "operationId": "patchLeadsId",
531533 "parameters": [
532534 {
@@ -587,6 +589,10 @@
587589 "null"
588590 ],
589591 "description": "YYYY-MM-DD: put the lead away until then; null brings it back now."
592 },
593 "starred": {
594 "type": "boolean",
595 "description": "true stars the lead, false takes the star off."
590596 }
591597 }
592598 }
@@ -595,7 +601,7 @@
595601 },
596602 "responses": {
597603 "200": {
598 "description": "Mark a lead qualified or lost (the same as POST /leads/{id}/state), correct its name, email or phone (the same as POST /leads/{id}/edit), keep a private note on it (the same as POST /leads/{id}/note), or put it away until a day with back_on (YYYY-MM-DD, from tomorrow to 365 days out in the profile's time zone; null brings it back now): send one of the four. Putting it away sets unsent follow-ups aside, and at 8:00 that morning a check-in draft waits on the desk; a bad date is a 422 naming back_on.",
604 "description": "Mark a lead qualified or lost (the same as POST /leads/{id}/state), correct its name, email or phone (the same as POST /leads/{id}/edit), keep a private note on it (the same as POST /leads/{id}/note), star it or take the star off with starred (true or false), or put it away until a day with back_on (YYYY-MM-DD, from tomorrow to 365 days out in the profile's time zone; null brings it back now): send one of the five. Putting it away sets unsent follow-ups aside, and at 8:00 that morning a check-in draft waits on the desk; a bad date is a 422 naming back_on.",
599605 "content": {
600606 "application/json": {
601607 "schema": {
@@ -806,6 +812,10 @@
806812 "pattern": "^\\d{4}-\\d{2}-\\d{2}$",
807813 "description": "The day (YYYY-MM-DD, the profile's calendar) a lead put away comes back, with a check-in draft at 8:00; null when it is not put away."
808814 },
815 "starred": {
816 "type": "boolean",
817 "description": "The agent keeps this lead close: starred open leads lead the desk."
818 },
809819 "created_at": {
810820 "type": "string",
811821 "format": "date-time"
@@ -977,6 +987,7 @@
977987 "lostReason",
978988 "lostAt",
979989 "back_on",
990 "starred",
980991 "created_at",
981992 "replied_at",
982993 "updated_at",
@@ -2429,6 +2440,10 @@
24292440 "pattern": "^\\d{4}-\\d{2}-\\d{2}$",
24302441 "description": "The day (YYYY-MM-DD, the profile's calendar) a lead put away comes back, with a check-in draft at 8:00; null when it is not put away."
24312442 },
2443 "starred": {
2444 "type": "boolean",
2445 "description": "The agent keeps this lead close: starred open leads lead the desk."
2446 },
24322447 "created_at": {
24332448 "type": "string",
24342449 "format": "date-time"
@@ -2576,6 +2591,7 @@
25762591 "lostReason",
25772592 "lostAt",
25782593 "back_on",
2594 "starred",
25792595 "created_at",
25802596 "replied_at",
25812597 "updated_at",
@@ -2663,6 +2679,7 @@
26632679 "needs",
26642680 "open",
26652681 "closed",
2682 "starred",
26662683 "all"
26672684 ],
26682685 "description": "The view listed."
@@ -2808,6 +2825,10 @@
28082825 "pattern": "^\\d{4}-\\d{2}-\\d{2}$",
28092826 "description": "The day (YYYY-MM-DD, the profile's calendar) a lead put away comes back, with a check-in draft at 8:00; null when it is not put away."
28102827 },
2828 "starred": {
2829 "type": "boolean",
2830 "description": "The agent keeps this lead close: starred open leads lead the desk."
2831 },
28112832 "created_at": {
28122833 "type": "string",
28132834 "format": "date-time"
@@ -2896,6 +2917,7 @@
28962917 "lostReason",
28972918 "lostAt",
28982919 "back_on",
2920 "starred",
28992921 "created_at",
29002922 "replied_at",
29012923 "updated_at",
docs/design/areas/desk.md +10
@@ -19,3 +19,13 @@ Above the record and the leads, while a showing is ahead: `.showings`, a
1919 `section` holding an `h2`, a plain `ul` of `.showing-when` (the time, as the
2020 badge words it), the lead's name as a link, and the address in `.muted`.
2121 At most five, then "and N more". Absent, not empty, when none is ahead.
22
23 # Desk: the star
24
25 One `form.star` holding one `button.star-button` (★ starred, ☆ not; the state
26 is `aria-pressed`, the name says what a tap does). It is a sibling of the
27 `.lead-row` link inside `li.lead-item`, because a button cannot live inside a
28 link; `.lead-item` is a two-column grid (the row, then the star). On a lead's
29 page the same form sits under the name. The button is `--size-tap` (44px)
30 square on every screen, so it is a thumb-sized target on a phone, and it
31 works as a plain POST with no JavaScript.
src/actions.test.ts +1
@@ -274,6 +274,7 @@ test("the desk's views: each lists exactly its leads, counts add up, a bad value
274274 needs: needs.leads.length,
275275 open: open.leads.length,
276276 closed: closed.leads.length,
277 starred: 0,
277278 all: everyone.length,
278279 });
279280 const newestFirst = (d: { leads: { created_at: string }[] }) =>
src/actions.ts +33 −2
@@ -61,6 +61,8 @@ import {
6161 bookShowing as bookShowingFor,
6262 bringBack,
6363 putAway,
64 setStar,
65 starredFirst,
6466 cancelShowing as cancelShowingFor,
6567 recordInbound,
6668 redraftUnsent,
@@ -155,7 +157,7 @@ export function listLeads(
155157 show,
156158 q,
157159 counts: countViews(all),
158 leads: all.filter((l) => inView(l, show)).slice(0, limit),
160 leads: starredFirst(all.filter((l) => inView(l, show)), input.now ?? Date.now()).slice(0, limit),
159161 });
160162 }
161163
@@ -174,7 +176,7 @@ export function exportLeads(
174176 if (q === undefined)
175177 return fail("invalid", `A search is plain text, up to ${MAX_QUERY} characters.`);
176178 const show = viewOf(input.show);
177 const leads = desk(db, -1, q).filter((l) => inView(l, show));
179 const leads = starredFirst(desk(db, -1, q).filter((l) => inView(l, show)), (input.now ?? new Date()).getTime());
178180 return ok({
179181 name: csvName(input.now ?? new Date()),
180182 csv: leadsCsv(leads, lastMessages(db)),
@@ -943,6 +945,35 @@ function comeBack(
943945 return ok(detail(db, lead.id)!);
944946 }
945947
948 /**
949 * Star a lead, or take the star off (`starred` is true or false). Starred open
950 * leads lead the desk. Saying what is already so changes nothing and succeeds.
951 */
952 export const setStarred = (
953 db: Database,
954 who: Who,
955 input: { id: number; starred: unknown },
956 ): Result<LeadDetail> =>
957 audited(db, who, "lead", "update", input.id, starring(db, who, input), input.starred === true ? "starred" : "unstarred");

This new write door needs a row in src/contract.test.ts (setStarred, star_lead and POST /leads/:id/star per identity against lead update).

958
959 function starring(
960 db: Database,
961 who: Who,
962 input: { id: number; starred: unknown },
963 ): Result<LeadDetail> {
964 const found = leadFor(db, who, "update", input.id, {
965 signIn: "Sign in to star this lead.",
966 no: "You may not star this lead.",
967 });
968 if (!found.ok) return found;
969 if (typeof input.starred !== "boolean") return fail("invalid", "starred: true or false.");
970 if (found.value.starred !== input.starred) {
971 setStar(db, found.value, input.starred);
972 emit("lead.changed", { id: found.value.id });
973 }
974 return ok(detail(db, found.value.id)!);
975 }
976
946977 /** Take the showing off a lead; the follow-ups held for it return to their usual place. */
947978 export const cancelShowing = (
948979 db: Database,
src/audit.ts +2 −2
@@ -34,8 +34,8 @@ export interface AuditRow {
3434 readonly detail: string | null;
3535 }
3636
37 /** Messages sent are `reply` and `first_reply`; a close is `qualified` or `lost`; `reopened` puts it back; `opted_out` is a lead who asked to stop texts; `inbound` is what the lead wrote back, pasted in; `call` is a phone call the agent logged; `showing` books or moves a showing, `showing_off` cancels it; `edited` is a correction of the lead's name, email or phone; `held` is a text approved outside quiet hours, to go at the next 8:00 a.m.; `unhold` takes back a text held for quiet hours; `noted` is a change to the agent's private note on the lead; `merged` is a new arrival who was already a lead (the detail names the arrival's source and the lead): their message joined that lead; `openers` is a change to how first replies open (the profile); `cadence` is a change to the follow-up days (the profile); `skipped` sets one upcoming follow-up aside by hand, `unskipped` brings it back; `put_away` parks a lead until a date (the detail holds `{"on":"YYYY-MM-DD"}`), `brought_back` clears that date. */
38 export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off", "edited", "held", "unhold", "openers", "cadence", "replies", "noted", "merged", "skipped", "unskipped", "put_away", "brought_back"] as const;
37 /** Messages sent are `reply` and `first_reply`; a close is `qualified` or `lost`; `reopened` puts it back; `opted_out` is a lead who asked to stop texts; `inbound` is what the lead wrote back, pasted in; `call` is a phone call the agent logged; `showing` books or moves a showing, `showing_off` cancels it; `edited` is a correction of the lead's name, email or phone; `held` is a text approved outside quiet hours, to go at the next 8:00 a.m.; `unhold` takes back a text held for quiet hours; `noted` is a change to the agent's private note on the lead; `merged` is a new arrival who was already a lead (the detail names the arrival's source and the lead): their message joined that lead; `openers` is a change to how first replies open (the profile); `cadence` is a change to the follow-up days (the profile); `skipped` sets one upcoming follow-up aside by hand, `unskipped` brings it back; `put_away` parks a lead until a date (the detail holds `{"on":"YYYY-MM-DD"}`), `brought_back` clears that date; `starred` keeps a lead close, `unstarred` lets it go. */
38 export const ACTS = ["reply", "first_reply", "qualified", "lost", "reopened", "opted_out", "inbound", "call", "showing", "showing_off", "edited", "held", "unhold", "openers", "cadence", "replies", "noted", "merged", "skipped", "unskipped", "put_away", "brought_back", "starred", "unstarred"] as const;
3939 export type Act = (typeof ACTS)[number];
4040
4141 /** What a `merged` row's detail holds: where the new arrival came from, and the lead they already were. */
src/contract.test.ts +7
@@ -33,6 +33,7 @@ import {
3333 saveProfile,
3434 setNote,
3535 setState,
36 setStarred,
3637 } from "./actions.ts";
3738 import { record } from "./audit.ts";
3839 import { actingAs, identities, table, type Verb } from "./can.ts";
@@ -179,7 +180,13 @@ const doors: Record<
179180 .get(skipId)!.id;
180181 const skipped = skipFollowUp(db, who, { id: skipId, messageId: upcoming }).ok;
181182 const restored = skipped && restoreFollowUp(db, who, { id: skipId, messageId: upcoming }).ok;
183 // And so is starring and unstarring (PATCH /leads/:id with starred,
184 // POST /leads/:id/star, the MCP tool star_lead).
185 const starred = setStarred(db, who, { id: replied, starred: true }).ok;
186 const starredViaTool = (tools.find((t) => t.name === "star_lead")!.run(db, who, { id: replied, starred: false }) as { ok: boolean }).ok;
182187 const changed = setState(db, who, { id: aLead(authorId), state: "lost", reason: "other" }).ok;
188 expect(starred).toBe(changed);
189 expect(starredViaTool).toBe(changed);
183190 expect(skipped).toBe(changed);
184191 expect(restored).toBe(changed);
185192 expect(untold).toBe(changed);
src/db.ts +2
@@ -266,6 +266,8 @@ export const migrations: string[] = [
266266 `ALTER TABLE lead ADD COLUMN back_on TEXT`,
267267 // The agent's saved replies as JSON, e.g. [{"name":"Lender intro","text":"…"}]. Null means the sample pair (SAMPLE_REPLIES).
268268 `ALTER TABLE profile ADD COLUMN replies TEXT`,
269 // A lead the agent keeps close: 1 is starred. Starred open leads lead the desk. Existing leads are not starred.
270 `ALTER TABLE lead ADD COLUMN starred INTEGER NOT NULL DEFAULT 0 CHECK (starred IN (0, 1))`,
269271 ];
270272
271273 /**
src/export.test.ts +2 −1
@@ -170,9 +170,10 @@ test("minutes to first reply, texts allowed, and last message", () => {
170170 "2026-11-02T11:00:00.000Z",
171171 "yes",
172172 "",
173 "no",
173174 ]);
174175 const waiting = parse(leadsCsv([{ ...lead, replied_at: null, consent: false }], new Map()))[1]!;
175 expect(waiting.slice(6)).toEqual(["", "", "", "no", ""]);
176 expect(waiting.slice(6)).toEqual(["", "", "", "no", "", "no"]);
176177 expect(csvName(new Date("2026-11-02T08:00:00Z"))).toBe("leads-2026-11-02.csv");
177178 });
178179
src/export.ts +2
@@ -18,6 +18,7 @@ export const COLUMNS = [
1818 "last message at",
1919 "texts allowed",
2020 "lost_reason",
21 "starred",
2122 ] as const;
2223
2324 /** An international number, "+1 206-555-0101": a plus and then only digits and the marks people type. */
@@ -59,6 +60,7 @@ export function leadsCsv(
5960 lastMessageAt.get(lead.id) ?? "",
6061 lead.consent ? "yes" : "no",
6162 lead.state === "lost" ? (lead.lostReason ?? "no reason given") : "",
63 lead.starred ? "yes" : "no",
6264 ]);
6365 return [COLUMNS, ...rows].map((row) => row.map((v, i) => field(v, COLUMNS[i] === "phone")).join(",")).join("\r\n") + "\r\n";
6466 }
src/leads.ts +35 −5
@@ -34,7 +34,7 @@ import {
3434 type Source,
3535 } from "./drafts.ts";
3636 import { answers, type Call, type Outcome } from "./calls.ts";
37 import { GREEN_MS } from "./clock.ts";
37 import { between, GREEN_MS } from "./clock.ts";
3838 import type { Agent } from "./env.ts";
3939 import { isQuiet, nextOpening } from "./quiet.ts";
4040 import { type LostReason } from "./lost.ts";
@@ -70,6 +70,8 @@ export interface Lead {
7070 readonly lostAt: string | null;
7171 /** The day (`YYYY-MM-DD`, the agent's calendar) a lead put away comes back; null when it is not put away. */
7272 readonly back_on: string | null;
73 /** The agent keeps this lead close: starred open leads lead the desk. */
74 readonly starred: boolean;
7375 }
7476
7577 export interface Message {
@@ -133,15 +135,16 @@ export interface DeskLead extends Lead {
133135 /**
134136 * Ways to look at the desk. `needs`: a first reply or a follow-up is waiting
135137 * on the agent. `open`: still in the cadence, nothing waiting. `closed`:
136 * qualified or lost. `all`: everyone. The first three never overlap, and a
138 * qualified or lost. `starred`: open leads the agent starred (it overlaps the
139 * others). `all`: everyone. `needs`, `open` and `closed` never overlap, and a
137140 * lead put away until a date is in none of them until its check-in is ready.
138141 */
139 export const VIEWS = ["needs", "open", "closed", "all"] as const;
142 export const VIEWS = ["needs", "open", "closed", "starred", "all"] as const;
140143 export type View = (typeof VIEWS)[number];
141144
142145 /** What a door says about the views, in one place. */
143146 export const VIEW_HELP =
144 "needs: a reply or follow-up waits on you; open: in follow-up, nothing waiting (not put away until a date); closed: qualified or lost; all (default, also for any other value).";
147 "needs: a reply or follow-up waits on you; open: in follow-up, nothing waiting (not put away until a date); closed: qualified or lost; starred: open leads you starred; all (default, also for any other value).";
145148
146149 /** A view from user text; anything unknown is `all`. */
147150 export const viewOf = (text: unknown): View =>
@@ -156,16 +159,36 @@ export const inView = (lead: DeskLead, view: View): boolean => {
156159 return !closed && lead.ready === null && lead.back_on === null;
157160 case "closed":
158161 return closed;
162 case "starred":
163 return !closed && lead.starred;
159164 case "all":
160165 return true;
161166 }
162167 };
163168
169 /**
170 * Starred open leads first, whatever view is chosen; each group keeps the
171 * order it came in (newest inquiry first). A first reply that has waited past
172 * the green clock stays ahead of the stars, so a star never hides a lead
173 * who is owed an answer. With nobody starred the order is left alone.
174 */
175 export const starredFirst = (leads: readonly DeskLead[], now: number): DeskLead[] => {
176 if (!leads.some((l) => l.starred)) return [...leads];
177 const rank = (l: DeskLead): number =>
178 l.replied_at === null && !CLOSED.includes(l.state) && between(l.created_at, now) >= GREEN_MS
179 ? 0
180 : l.starred && !CLOSED.includes(l.state)
181 ? 1
182 : 2;
183 return [...leads].sort((a, b) => rank(a) - rank(b));
184 };
185
164186 /** How many leads each view holds. */
165187 export const countViews = (leads: readonly DeskLead[]): Record<View, number> => ({
166188 needs: leads.filter((l) => inView(l, "needs")).length,
167189 open: leads.filter((l) => inView(l, "open")).length,
168190 closed: leads.filter((l) => inView(l, "closed")).length,
191 starred: leads.filter((l) => inView(l, "starred")).length,
169192 all: leads.length,
170193 });
171194
@@ -188,8 +211,9 @@ export type NewLead = {
188211 readonly consent: boolean;
189212 };
190213
191 type LeadRecord = Omit<Lead, "consent" | "noteUpdatedAt" | "lostReason" | "lostAt"> & {
214 type LeadRecord = Omit<Lead, "consent" | "noteUpdatedAt" | "lostReason" | "lostAt" | "starred"> & {
192215 consent: number;
216 starred: number;
193217 note_updated_at: string | null;
194218 lost_reason: LostReason | null;
195219 lost_at: string | null;
@@ -197,6 +221,7 @@ type LeadRecord = Omit<Lead, "consent" | "noteUpdatedAt" | "lostReason" | "lostA
197221 const lead = ({ note_updated_at, lost_reason, lost_at, ...row }: LeadRecord): Lead => ({
198222 ...row,
199223 consent: row.consent === 1,
224 starred: row.starred === 1,
200225 noteUpdatedAt: note_updated_at,
201226 lostReason: lost_reason,
202227 lostAt: lost_at,
@@ -1183,6 +1208,11 @@ function placeShowingMessage(
11831208 const reachable = (lead: Pick<Lead, "consent" | "phone" | "email">): boolean =>
11841209 channelFor(lead) === "text" || lead.email !== "";
11851210
1211 /** Star a lead or take the star off. It touches nothing else: not the cadence, not `updated_at`. */
1212 export function setStar(db: Database, found: Lead, starred: boolean): void {
1213 db.query("UPDATE lead SET starred = ?1 WHERE id = ?2").run(starred ? 1 : 0, found.id);
1214 }
1215
11861216 /**
11871217 * The lead is put away until `on` (a `YYYY-MM-DD` on the agent's calendar):
11881218 * every follow-up not yet sent is set aside, and at 8:00 that morning in the
src/lost.test.ts +3 −2
@@ -105,10 +105,11 @@ test("the CSV has a lost_reason column: the reason, 'no reason given', or empty"
105105 db.query("UPDATE lead SET state = 'lost' WHERE id = ?1").run(b!);
106106 const csv = must(exportLeads(db, alice)).csv.trimEnd().split("\r\n");
107107 const head = csv[0]!.split(",");
108 expect(head[head.length - 1]).toBe("lost_reason");
108 const column = head.indexOf("lost_reason");
109 expect(column).toBeGreaterThan(-1);
109110 const last = (id: number) => {
110111 const name = must(getLead(db, alice, { id })).name;
111 return csv.find((l) => l.startsWith(`${name},`))!.split(",").pop();
112 return csv.find((l) => l.startsWith(`${name},`))!.split(",")[column];
112113 };
113114 expect(last(a!)).toBe("never_answered");
114115 expect(last(b!)).toBe("no reason given");
src/mcp.ts +15
@@ -26,6 +26,7 @@ import {
2626 bookShowing,
2727 cancelShowing,
2828 setBackOn,
29 setStarred,
2930 restoreFollowUp,
3031 skipFollowUp,
3132 logLeadReply,
@@ -243,6 +244,20 @@ export const tools: readonly Tool[] = [
243244 run: (db, who, args) =>
244245 setBackOn(db, who, { id: Number(args.id), back_on: args.back_on === undefined ? "" : args.back_on }),
245246 },
247 {
248 name: "star_lead",
249 description:
250 "Star a lead the agent wants to keep close (starred true), or take the star off (starred false). Starred open leads lead the desk, and list_leads can show only them with show=starred. Nothing is sent.",
251 inputSchema: {
252 type: "object",
253 properties: {
254 id: { type: "integer" },
255 starred: { type: "boolean" },
256 },
257 required: ["id", "starred"],
258 },
259 run: (db, who, args) => setStarred(db, who, { id: Number(args.id), starred: args.starred }),
260 },
246261 {
247262 name: "cancel_showing",
248263 description:
src/pages/desk.ts +10 −4
@@ -3,7 +3,7 @@
33 * clock since they asked. One tap opens the lead with the reply drafted.
44 */
55
6 import { day, clock, consent, source, STATE_LABEL } from "./parts.ts";
6 import { day, clock, consent, source, starForm, STATE_LABEL } from "./parts.ts";
77 import { deskTitle, layout } from "./layout.ts";
88 import { escape } from "../http.ts";
99 import { recordLine, sourceLine } from "../clock.ts";
@@ -29,6 +29,8 @@ export function deskPage(input: {
2929 /** Every showing still ahead, soonest first; the desk lists the first few. */
3030 ahead?: readonly Ahead[] | undefined;
3131 mayAdd: boolean;
32 /** Whether a star shows on each row: the same word as `lead update`. */
33 mayStar: boolean;
3234 mayReset: boolean;
3335 notice?: string | undefined;
3436 /** What a pasted email was read into: the add form opens with it filled in. */
@@ -77,10 +79,11 @@ export function deskPage(input: {
7779 <button class="button button-quiet">Search</button>
7880 </form>
7981 ${q === "" ? "" : found(q, show, counts?.all ?? leads.length)}`;
82 const mayStar = input.mayStar;
8083 const list =
8184 leads.length === 0
8285 ? `<p class="empty">${q === "" ? EMPTY[show] : `No lead matches '${escape(q)}'${show === "all" ? "" : " in this view"}.`}</p>`
83 : `<ul class="desk">${leads.map((lead) => row(lead, now, agent.timeZone)).join("")}</ul>`;
86 : `<ul class="desk">${leads.map((lead) => row(lead, now, agent.timeZone, mayStar ? viewHref(show, q) : undefined)).join("")}</ul>`;
8487 const showings = showingsList(input.ahead ?? [], now, agent.timeZone);
8588 const tab = deskTitle(counts?.needs ?? leads.filter((l) => inView(l, "needs")).length);
8689 return layout({
@@ -144,6 +147,7 @@ const VIEW_LABEL: readonly (readonly [View, string])[] = [
144147 ["needs", "Needs you"],
145148 ["open", "In follow-up"],
146149 ["closed", "Closed"],
150 ["starred", "Starred"],
147151 ["all", "All"],
148152 ];
149153
@@ -151,6 +155,7 @@ const EMPTY: Record<View, string> = {
151155 needs: "Nobody is waiting on you.",
152156 open: "Nobody is in follow-up.",
153157 closed: "No closed leads yet.",
158 starred: "No starred leads. Tap the star on a lead to keep it close.",
154159 all: "No leads yet. New inquiries appear here the moment they arrive.",
155160 };
156161
@@ -206,7 +211,7 @@ function status(lead: DeskLead, now: number, zone: string): string {
206211 return `<span class="status">Follow-ups done</span>`;
207212 }
208213
209 const row = (lead: DeskLead, now: number, zone: string): string => `<li>
214 const row = (lead: DeskLead, now: number, zone: string, back?: string): string => `<li class="lead-item">
210215 <a class="lead-row" href="/leads/${lead.id}"${lead.state === "lost" ? " data-closed" : ""}>
211216 <span class="lead-main">
212217 <span class="lead-name">${escape(lead.name)}</span>${noteLine(lead.note) === "" ? "" : `
@@ -216,7 +221,8 @@ const row = (lead: DeskLead, now: number, zone: string): string => `<li>
216221 ${status(lead, now, zone)}
217222 </span>
218223 ${clock(lead, now, lead.ready !== null && isAnswer(lead.ready.day) ? lead.ready.since : null)}
219 </a>
224 </a>${back === undefined ? "" : `
225 ${starForm(lead, back)}`}
220226 </li>`;
221227
222228 const pasteForm = `<details class="card add">
src/pages/lead.ts +3 −2
@@ -18,7 +18,7 @@ import type { Agent } from "../env.ts";
1818 import type { Who } from "../who.ts";
1919 import { layout } from "./layout.ts";
2020 import { LOST_REASONS, REASON_LABEL, lostSaid } from "../lost.ts";
21 import { clock, consent, day, source, STATE_LABEL, when } from "./parts.ts";
21 import { clock, consent, day, source, starForm, STATE_LABEL, when } from "./parts.ts";
2222
2323 /** One line of the thread: something we sent, or something they wrote back. */
2424 type HistoryEntry =
@@ -307,7 +307,8 @@ export function leadPage(input: {
307307 ${onward}
308308 <header class="lead-head">
309309 <div>
310 <h1>${escape(lead.name)}</h1>
310 <h1>${escape(lead.name)}</h1>${mayUpdate ? `
311 ${starForm(lead, path)}` : ""}
311312 <p class="tags">${source(lead)}${consent(lead, agent.timeZone)}<span class="chip" data-state="${lead.state}">${STATE_LABEL[lead.state]}</span></p>
312313 <p class="contact">${contact}${
313314 mayUpdate && lead.phone !== ""
src/pages/parts.ts +14
@@ -59,3 +59,17 @@ export const when = (iso: string, zone: string): string =>
5959 minute: "2-digit",
6060 timeZone: zone,
6161 });
62
63 /**
64 * The star: one button in its own form, so one tap stars or unstars with no
65 * JavaScript. `back` is the page to return to (the desk keeps its view and
66 * search); the route checks it before it redirects.
67 */
68 export function starForm(lead: Pick<Lead, "id" | "name" | "starred">, back: string): string {
69 const label = `${lead.starred ? "Take the star off" : "Star"} ${lead.name}`;
70 return `<form class="star" method="post" action="/leads/${lead.id}/star">
71 <input type="hidden" name="starred" value="${lead.starred ? "no" : "yes"}">
72 <input type="hidden" name="back" value="${escape(back)}">
73 <button class="star-button" aria-pressed="${lead.starred}" aria-label="${escape(label)}" title="${escape(label)}">${lead.starred ? "★" : "☆"}</button>
74 </form>`;
75 }
src/routes.ts +35 −4
@@ -43,6 +43,7 @@ import {
4343 bookShowing,
4444 cancelShowing,
4545 setBackOn,
46 setStarred,
4647 restoreFollowUp,
4748 skipFollowUp,
4849 logLeadReply,
@@ -187,6 +188,7 @@ const LEAD_FIELDS = {
187188 pattern: "^\\d{4}-\\d{2}-\\d{2}$",
188189 description: "The day (YYYY-MM-DD, the profile's calendar) a lead put away comes back, with a check-in draft at 8:00; null when it is not put away.",
189190 },
191 starred: { type: "boolean", description: "The agent keeps this lead close: starred open leads lead the desk." },
190192 created_at: STAMP,
191193 replied_at: { type: ["string", "null"], format: "date-time" },
192194 updated_at: STAMP,
@@ -595,6 +597,15 @@ const BACK_ON_FIELD = {
595597 description: "YYYY-MM-DD: put the lead away until then; null brings it back now.",
596598 } as const;
597599
600 const STARRED_FIELD = {
601 type: "boolean",
602 description: "true stars the lead, false takes the star off.",
603 } as const;
604
605 /** Where a star's form returns to: the desk with its view and search, or a lead's page; anything else is nowhere. */
606 const backOf = (value: unknown): string | undefined =>
607 typeof value === "string" && /^\/(\?[\w=&%.+~-]{0,200}|leads\/\d+)?$/.test(value) ? value : undefined;
608
598609 const NOTE_FIELD = {
599610 type: "string",
600611 maxLength: MAX_LEAD_NOTE,
@@ -660,6 +671,7 @@ function desk(
660671 counts: leads.ok ? leads.value.counts : undefined,
661672 ahead: leads.ok ? showingsAhead(c.db, Date.now()) : undefined,
662673 mayAdd: permit(c.who, "lead", "create") === "yes",
674 mayStar: permit(c.who, "lead", "update") === "yes",
663675 mayReset: permit(c.who, "lead", "delete") === "yes",
664676 notice: pasted?.notice ?? refused ?? notice,
665677 prefill: pasted?.found,
@@ -880,11 +892,13 @@ export const routes: readonly Route[] = [
880892 const details = CONTACT.some((field) => input[field] !== undefined);
881893 const noted = input.note !== undefined;
882894 const away = input.back_on !== undefined;
883 if ([details, noted, away, input.state !== undefined].filter(Boolean).length > 1)
895 const star = input.starred !== undefined;
896 if ([details, noted, away, star, input.state !== undefined].filter(Boolean).length > 1)
884897 return json(
885 { error: "invalid", message: "Send one change at a time: a state, details to correct, a note, or a come-back date." },
898 { error: "invalid", message: "Send one change at a time: a state, details to correct, a note, a star, or a come-back date." },
886899 422,
887900 );
901 if (star) return answer(setStarred(c.db, c.who, { id: ID(c), starred: input.starred }));
888902 if (away) return answer(setBackOn(c.db, c.who, { id: ID(c), back_on: input.back_on }));
889903 if (noted) return answer(setNote(c.db, c.who, { id: ID(c), note: input.note }));
890904 if (details)
@@ -893,10 +907,10 @@ export const routes: readonly Route[] = [
893907 },
894908 api: {
895909 summary:
896 "Mark a lead qualified or lost (the same as POST /leads/{id}/state), correct its name, email or phone (the same as POST /leads/{id}/edit), keep a private note on it (the same as POST /leads/{id}/note), or put it away until a day with back_on (YYYY-MM-DD, from tomorrow to 365 days out in the profile's time zone; null brings it back now): send one of the four. Putting it away sets unsent follow-ups aside, and at 8:00 that morning a check-in draft waits on the desk; a bad date is a 422 naming back_on.",
910 "Mark a lead qualified or lost (the same as POST /leads/{id}/state), correct its name, email or phone (the same as POST /leads/{id}/edit), keep a private note on it (the same as POST /leads/{id}/note), star it or take the star off with starred (true or false), or put it away until a day with back_on (YYYY-MM-DD, from tomorrow to 365 days out in the profile's time zone; null brings it back now): send one of the five. Putting it away sets unsent follow-ups aside, and at 8:00 that morning a check-in draft waits on the desk; a bad date is a 422 naming back_on.",
897911 body: {
898912 type: "object",
899 properties: { state: { enum: ["qualified", "lost", "open"] }, reason: REASON_FIELD, ...EDIT_FIELDS, note: NOTE_FIELD, back_on: BACK_ON_FIELD },
913 properties: { state: { enum: ["qualified", "lost", "open"] }, reason: REASON_FIELD, ...EDIT_FIELDS, note: NOTE_FIELD, back_on: BACK_ON_FIELD, starred: STARRED_FIELD },
900914 },
901915 answer: LEAD,
902916 },
@@ -1103,6 +1117,23 @@ export const routes: readonly Route[] = [
11031117 }),
11041118 ),
11051119 },
1120 {
1121 // The star's form: `starred` is yes or no, `back` the page to return to.
1122 method: "POST",
1123 path: "/leads/:id/star",
1124 handle: (c) => {
1125 let to = `/leads/${ID(c)}`;
1126 return posted(
1127 c,
1128 (input) => {
1129 to = backOf(input.back) ?? to;
1130 const starred = input.starred === "yes" || input.starred === true ? true : input.starred === "no" || input.starred === false ? false : input.starred;
1131 return setStarred(c.db, c.who, { id: ID(c), starred });
1132 },
1133 (lead) => ({ to, said: lead === undefined ? undefined : lead.starred ? `Starred ${lead.name}.` : `Took the star off ${lead.name}.` }),
1134 );
1135 },
1136 },
11061137 {
11071138 method: "POST",
11081139 path: "/leads/:id/bring-back",
src/sentences.ts +7
@@ -100,6 +100,13 @@ export function deed(
100100 tried: `put ${lead} away`,
101101 };
102102 }
103 if (row.act === "starred" || row.act === "unstarred") {
104 const star = row.act === "starred";
105 return {
106 done: star ? `starred ${lead}` : `took the star off ${lead}`,
107 tried: star ? `star ${lead}` : `take the star off ${lead}`,
108 };
109 }
103110 if (row.act === "brought_back")
104111 return {
105112 done: `brought ${lead} back`,
src/server.test.ts +1
@@ -328,6 +328,7 @@ test("the MCP server lists the tools and calls them as the caller", async () =>
328328 "log_call",
329329 "book_showing",
330330 "put_lead_away",
331 "star_lead",
331332 "cancel_showing",
332333 "mark_lead",
333334 "edit_lead",
src/star.test.ts added +245
@@ -0,0 +1,245 @@
1 /**
2 * A star keeps a lead close: one tap on the desk row or the lead's page,
3 * starred open leads first (but never ahead of a first reply that is
4 * overdue), a Starred view, the CSV column, the Activity sentence, and the
5 * same at the API, MCP and the terminal.
6 */
7 import { afterAll, expect, test } from "bun:test";
8 import { Database } from "bun:sqlite";
9 import { mkdtempSync } from "node:fs";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { addLead, exportLeads, getLead, listLeads, sendReply, setStarred, setState } from "./actions.ts";
13 import { check, migrate, migrations, openDb } from "./db.ts";
14 import { activityPage } from "./pages/activity.ts";
15 import { currentAgent } from "./profile.ts";
16 import { serve } from "./server.ts";
17 import { plain, terminal } from "./terminal.ts";
18 import { sign } from "./who.ts";
19 import type { Who } from "./who.ts";
20
21 const alice: Who = { role: "user", id: "u1", name: "alice" };
22 const anon: Who = { role: "anon" };
23 const NOW = Date.now();
24 const mins = (n: number) => new Date(NOW - n * 60_000);
25
26 const value = <T>(r: { ok: boolean; value?: T; message?: string }): T => {
27 if (!r.ok) throw new Error(r.message);
28 return r.value as T;
29 };
30 const fresh = () => openDb(mkdtempSync(join(tmpdir(), "app-star-")));
31 let n = 0;
32 /** A lead who arrived `ago` minutes ago; `replied` sends the first reply at once. */
33 const arrive = (db: Database, name: string, ago: number, replied: boolean): number => {
34 const id = value(
35 addLead(db, alice, { name, email: `lead${++n}@example.com`, phone: "", source: "website", message: "Is it still for sale?", consent: false }, mins(ago)),
36 ).id;
37 if (replied) value(sendReply(db, alice, { id }, mins(ago - 1)));
38 return id;
39 };
40 const names = (db: Database, show?: string) => value(listLeads(db, alice, { show, now: NOW })).leads.map((l) => l.name);
41
42 test("star and unstar: stored, idempotent, and a lead starts unstarred", () => {
43 const db = fresh();
44 const id = arrive(db, "Ann", 600, true);
45 expect(value(getLead(db, alice, { id })).starred).toBe(false);
46 expect(value(setStarred(db, alice, { id, starred: true })).starred).toBe(true);
47 expect(value(setStarred(db, alice, { id, starred: true })).starred).toBe(true);
48 expect(value(getLead(db, alice, { id })).starred).toBe(true);
49 expect(value(setStarred(db, alice, { id, starred: false })).starred).toBe(false);
50 for (const bad of ["yes", 1, null, undefined]) {
51 const r = setStarred(db, alice, { id, starred: bad });
52 expect(!r.ok && r.error).toBe("invalid");
53 }
54 const missing = setStarred(db, alice, { id: 9999, starred: true });
55 expect(!missing.ok && missing.error).toBe("not_found");
56 });
57
58 test("anon is refused and nothing changes", () => {
59 const db = fresh();
60 const id = arrive(db, "Ann", 600, true);
61 const r = setStarred(db, anon, { id, starred: true });
62 expect(!r.ok && r.error).toBe("signin_required");
63 expect(value(getLead(db, alice, { id })).starred).toBe(false);
64 });
65
66 test("starred open leads sort first in every view, the rest keep their order", () => {
67 const db = fresh();
68 const a = arrive(db, "Old", 900, true);
69 arrive(db, "Mid", 600, true);
70 const c = arrive(db, "New", 300, true);
71 expect(names(db)).toEqual(["New", "Mid", "Old"]);
72 value(setStarred(db, alice, { id: a, starred: true }));
73 expect(names(db)).toEqual(["Old", "New", "Mid"]);
74 value(setStarred(db, alice, { id: c, starred: true }));
75 expect(names(db)).toEqual(["New", "Old", "Mid"]);
76 expect(names(db, "open")).toEqual(["New", "Old", "Mid"]);
77 expect(names(db, "starred")).toEqual(["New", "Old"]);
78 const desk = value(listLeads(db, alice, { now: NOW }));
79 expect(desk.counts.starred).toBe(2);
80 // A starred lead that is closed is not in the Starred view and no longer leads.
81 value(setState(db, alice, { id: a, state: "lost", reason: "never_answered" }));
82 expect(names(db, "starred")).toEqual(["New"]);
83 expect(names(db)).toEqual(["New", "Mid", "Old"]);
84 });
85
86 test("a star never hides a first reply that is overdue: those stay first", () => {
87 const db = fresh();
88 const starred = arrive(db, "Starry", 900, true);
89 const late = arrive(db, "Late", 120, false); // two hours without a reply
90 arrive(db, "Fresh", 1, false); // still green: not overdue
91 value(setStarred(db, alice, { id: starred, starred: true }));
92 expect(names(db)).toEqual(["Late", "Starry", "Fresh"]);
93 value(setStarred(db, alice, { id: late, starred: true }));
94 expect(names(db)).toEqual(["Late", "Starry", "Fresh"]);
95 expect(names(db, "needs")).toEqual(["Late", "Fresh"]);
96 });
97
98 test("the CSV has a starred column, and exports starred leads first", () => {
99 const db = fresh();
100 arrive(db, "Plain", 300, true);
101 const s = arrive(db, "Keeper", 600, true);
102 value(setStarred(db, alice, { id: s, starred: true }));
103 const rows = value(exportLeads(db, alice)).csv.trimEnd().split("\r\n").map((l) => l.split(","));
104 const col = rows[0]!.indexOf("starred");
105 expect(col).toBeGreaterThan(-1);
106 expect(rows.slice(1).map((r) => [r[0], r[col]])).toEqual([["Keeper", "yes"], ["Plain", "no"]]);
107 });
108
109 test("the Activity page says who starred whom, and the audit keeps the refused try", () => {
110 const db = fresh();
111 const id = arrive(db, "Ann", 600, true);
112 value(setStarred(db, alice, { id, starred: true }));
113 value(setStarred(db, alice, { id, starred: false }));
114 setStarred(db, anon, { id, starred: true });
115 const rows = db.query("SELECT * FROM audit ORDER BY id").all() as never[];
116 const html = activityPage({ who: { role: "admin", id: "a", name: "root" }, agent: currentAgent(db), rows, names: new Map([[id, "Ann"]]), older: undefined, lost: [], sentOnly: false });
117 expect(html).toContain(`starred <a href="/leads/${id}">Ann</a>`);
118 expect(html).toContain(`took the star off <a href="/leads/${id}">Ann</a>`);
119 expect(html).toContain("star");
120 expect(rows.filter((r: any) => r.act === "starred").length).toBe(2);
121 });
122
123 test("the migration adds the column to an existing database and keeps its leads", () => {
124 const db = new Database(":memory:");
125 const at = migrations.findIndex((m) => m.includes("ADD COLUMN starred"));
126 expect(at).toBe(migrations.length - 1);
127 db.exec("CREATE TABLE schema_version (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')))");
128 migrations.slice(0, at).forEach((sql, i) => {
129 try {
130 db.exec(sql);
131 } catch (e) {
132 if (!/duplicate column/.test(String(e))) throw e;
133 }
134 db.query("INSERT INTO schema_version (version) VALUES (?1)").run(i + 1);
135 });
136 db.exec("INSERT INTO lead (id, name, email, source, message, consent) VALUES (4, 'Old Lead', '[email protected]', 'zillow', 'Is it open?', 0)");
137 expect(() => db.query("SELECT starred FROM lead").all()).toThrow();
138 migrate(db);
139 expect(db.query("SELECT id, name, starred FROM lead").all()).toEqual([{ id: 4, name: "Old Lead", starred: 0 }]);
140 expect(() => db.exec("UPDATE lead SET starred = 2")).toThrow();
141 expect(check(db).integrity).toBe("ok");
142 });
143
144 test("the terminal stars from the desk and the lead screen with *", () => {
145 const db = fresh();
146 const id = arrive(db, "Ann", 600, true);
147 const t = terminal(db, alice);
148 t.key("*");
149 expect(value(getLead(db, alice, { id })).starred).toBe(true);
150 expect(t.screen(100).map(plain).join("\n")).toContain("★ Ann");
151 t.key("\r");
152 expect(t.screen(100).map(plain).join("\n")).toContain("* take the star off");
153 t.key("*");
154 expect(value(getLead(db, alice, { id })).starred).toBe(false);
155 const guest = terminal(db, anon);
156 guest.key("*");
157 expect(value(getLead(db, alice, { id })).starred).toBe(false);
158 });
159
160 // The doors.
161 const KEY = "a-key-only-the-forge-holds";
162 const server = serve({ port: 0, dataDir: mkdtempSync(join(tmpdir(), "app-star-srv-")), identityKey: KEY, sample: false });
163 const base = `http://${server.hostname}:${server.port}`;
164 afterAll(() => server.stop(true));
165 let grants = 0;
166 const api = (path: string, init: RequestInit = {}, headers: Record<string, string> = {}) => {
167 const identity = `star-${++grants}|alice|user|${Date.now() + 60_000}`;
168 return fetch(base + path, {
169 redirect: "manual",
170 ...init,
171 headers: { ...(init.headers as Record<string, string>), ...headers, "x-forge-identity": identity, "x-forge-signature": sign(identity, KEY) },
172 });
173 };
174 const send = (method: string, path: string, body?: unknown) =>
175 api(path, { method, headers: { "content-type": "application/json" }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
176 const served = async (name = "Pat"): Promise<number> => {
177 const made = await send("POST", "/leads", { name, email: `${name.toLowerCase()}@example.com`, phone: "", source: "website", message: "Can we see it?", consent: false });
178 if (made.status !== 201) throw new Error(`${made.status} ${await made.text()}`);
179 return ((await made.json()) as { id: number }).id;
180 };
181 const form = (path: string, fields: Record<string, string>, headers: Record<string, string> = {}) =>
182 api(path, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(fields).toString() }, headers);
183
184 test("the API stars with PATCH starred; a bad value is 422; one change at a time", async () => {
185 const id = await served();
186 const on = await send("PATCH", `/leads/${id}`, { starred: true });
187 expect(on.status).toBe(200);
188 expect(((await on.json()) as { starred: boolean }).starred).toBe(true);
189 expect(((await (await api(`/leads/${id}`, { headers: { accept: "application/json" } })).json()) as { starred: boolean }).starred).toBe(true);
190 expect((await send("PATCH", `/leads/${id}`, { starred: "yes" })).status).toBe(422);
191 expect((await send("PATCH", `/leads/${id}`, { starred: false, note: "x" })).status).toBe(422);
192 const off = await send("PATCH", `/leads/${id}`, { starred: false });
193 expect(((await off.json()) as { starred: boolean }).starred).toBe(false);
194 const guest = await fetch(`${base}/leads/${id}`, { method: "PATCH", headers: { "content-type": "application/json" }, body: JSON.stringify({ starred: true }) });
195 expect([401, 403]).toContain(guest.status);
196 });
197
198 test("the page stars with a plain form: no JavaScript, same-origin only, back to where it was", async () => {
199 const id = await served("Quinn");
200 const desk = await (await api("/")).text();
201 expect(desk).toContain(`action="/leads/${id}/star"`);
202 expect(desk).toContain('class="star-button"');
203 const page = await (await api(`/leads/${id}`)).text();
204 expect(page).toContain(`action="/leads/${id}/star"`);
205
206 const evil = { origin: "https://evil.example", "sec-fetch-site": "cross-site" };
207 expect((await form(`/leads/${id}/star`, { starred: "yes" }, evil)).status).toBe(403);
208 expect((await send("PATCH", `/leads/${id}`, { starred: true }).then((r) => r.json()) as { starred: boolean }).starred).toBe(true);
209 await send("PATCH", `/leads/${id}`, { starred: false });
210
211 const res = await form(`/leads/${id}/star`, { starred: "yes", back: "/?show=starred" });
212 expect(res.status).toBe(303);
213 expect(res.headers.get("location")).toBe("/?show=starred");
214 expect(((await (await api(`/leads/${id}`, { headers: { accept: "application/json" } })).json()) as { starred: boolean }).starred).toBe(true);
215 expect(await (await api("/?show=starred")).text()).toContain("Quinn");
216 expect(await (await api(`/leads/${id}`)).text()).toContain("Take the star off Quinn");
217
218 // A back that is not ours goes to the lead's page.
219 for (const back of ["https://evil.example/", "//evil.example", "/\\evil.example", "javascript:1"]) {
220 const r = await form(`/leads/${id}/star`, { starred: "no", back });
221 expect(r.headers.get("location")).toBe(`/leads/${id}`);
222 }
223 const garbled = await form(`/leads/${id}/star`, { starred: "maybe" });
224 expect(garbled.status).toBe(303);
225 const guest = await fetch(`${base}/leads/${id}/star`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: "starred=yes" });
226 expect([303, 401, 403]).toContain(guest.status);
227 expect(((await (await api(`/leads/${id}`, { headers: { accept: "application/json" } })).json()) as { starred: boolean }).starred).toBe(false);
228 });
229
230 test("/openapi.json, the CSV download and MCP carry the star", async () => {
231 const spec = (await (await api("/openapi.json")).json()) as any;
232 expect(spec.paths["/leads/{id}"].patch.requestBody.content["application/json"].schema.properties.starred.type).toBe("boolean");
233 expect(JSON.stringify(spec)).toContain('"starred"');
234 const id = await served("Rowan");
235 const call = async (name: string, args: unknown) =>
236 (await (await send("POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "tools/call", params: { name, arguments: args } })).json()) as { result: { isError?: boolean; content: { text: string }[] } };
237 const on = await call("star_lead", { id, starred: true });
238 expect(JSON.parse(on.result.content[0]!.text).starred).toBe(true);
239 expect((await call("star_lead", { id, starred: "yes" })).result.isError).toBe(true);
240 const csv = await (await api("/leads.csv")).text();
241 expect(csv.split("\r\n")[0]).toContain("starred");
242 expect(csv).toContain("Rowan");
243 const listed = await call("list_leads", { show: "starred" });
244 expect(JSON.parse(listed.result.content[0]!.text).leads.map((l: { name: string }) => l.name)).toContain("Rowan");
245 });
src/terminal.test.ts +2
@@ -334,6 +334,8 @@ test("f cycles the desk's views; each shows its count and only its leads", () =>
334334 t.key("f");
335335 expect(read(t)).toContain("[Closed ");
336336 t.key("f");
337 expect(read(t)).toContain("[Starred ");
338 t.key("f");
337339 expect(read(t)).toContain("[All ");
338340 });
339341
src/terminal.ts +17 −4
@@ -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) · / find by name, email, phone or note · n log a lead · v paste a lead email · o open house sign-ins · i new sample inquiry · p profile · a activity (admin) · R restart samples (admin) · esc quit
8 * desk j/k move · enter open · * star · f view (needs/open/closed/all) · / find by name, email, phone or note · n log a lead · v paste a lead email · o open house sign-ins · i new sample inquiry · p profile · a activity (admin) · R restart samples (admin) · esc quit
99 * lead s approve and send · e edit, then send · w they wrote back · ] next lead that needs you ·
1010 * q qualified · x lost · t asked to stop texts · D remove (admin) · esc back
1111 * edit type; enter is a new line · ctrl-d approve and send · esc cancel
@@ -49,6 +49,7 @@ import {
4949 bookShowing,
5050 cancelShowing,
5151 setBackOn,
52 setStarred,
5253 logLeadReply,
5354 nextLead,
5455 parseLeadEmail,
@@ -200,12 +201,14 @@ const VIEW_LABEL: Record<DeskView, string> = {
200201 needs: "Needs you",
201202 open: "In follow-up",
202203 closed: "Closed",
204 starred: "Starred",
203205 all: "All",
204206 };
205207 const EMPTY: Record<DeskView, string> = {
206208 needs: "Nobody is waiting on you.",
207209 open: "Nobody is in follow-up.",
208210 closed: "No closed leads yet.",
211 starred: "No starred leads. Press * on a lead to star it.",
209212 all: "No leads yet. Press n to log one.",
210213 };
211214
@@ -291,7 +294,7 @@ export function terminal(
291294 : isAnswer(l.ready.day)
292295 ? "wrote back · answer drafted"
293296 : isCheckIn(l.ready.day) ? "check-in ready" : isBeforeShowing(l.ready.day) ? "before the showing · confirmation ready" : isAfterShowing(l.ready.day) ? "after the showing · note ready" : `day ${l.ready.day} follow-up ready`;
294 const name = clean(l.name).padEnd(18).slice(0, 18);
297 const name = `${l.starred ? "★ " : ""}${clean(l.name)}`.padEnd(18).slice(0, 18);
295298 const showing =
296299 l.showing === null
297300 ? ""
@@ -328,6 +331,8 @@ export function terminal(
328331
329332 /** Whether the private note can be changed here: the table says yes, in any state. */
330333 const mayNote = (l: LeadDetail): boolean => permit(me, "lead", "update", { ...l }) === "yes";
outdated

mayStar splits the note's doc comment from mayNote. Move it above the comment, give it its own comment, and let one reuse the other since the two are identical.

334 /** Whether a lead can be starred here: the same cell as a note, `lead update`. */
335 const mayStar = mayNote;
331336
332337 /** The next follow-up that can be skipped (scheduled or due, day 1 on), if the table lets this person. */
333338 const skippable = (l: LeadDetail): Message | undefined =>
@@ -351,7 +356,7 @@ export function terminal(
351356 const zone = currentAgent(db).timeZone;
352357 const channel = channelFor(l);
353358 const lines = [
354 `${bold(clean(l.name))} ${SOURCE_LABEL[l.source]} · ${channel === "text" ? "Text OK" : "Email only"} · ${l.state} ${clockOf(l)}`,
359 `${l.starred ? "★ " : ""}${bold(clean(l.name))} ${SOURCE_LABEL[l.source]} · ${channel === "text" ? "Text OK" : "Email only"} · ${l.state} ${clockOf(l)}`,
355360 dim([l.email, l.phone].filter((s) => s !== "").map((s) => clean(s)).join(" · ")),
356361 ...(l.note === ""
357362 ? []
@@ -449,6 +454,7 @@ export function terminal(
449454 : ["q qualified", "x lost"]),
450455 ...(mayEdit(l) ? ["d fix details"] : []),
451456 ...(mayNote(l) ? [l.note === "" ? "n add a note" : "n edit your note"] : []),
457 ...(mayStar(l) ? [l.starred ? "* take the star off" : "* star"] : []),
452458 ...(l.consent ? ["t they asked to stop texts"] : []),
453459 ...(nextLead(db, me, { except: l.id }) === null ? [] : ["] next that needs you"]),
454460 ...(admin() ? ["D remove"] : []),
@@ -729,7 +735,11 @@ export function terminal(
729735 cursor = Math.max(cursor - 1, 0);
730736 else if (input === "\r" && rows[cursor] !== undefined)
731737 view = { name: "lead", id: rows[cursor]!.id };
732 else if (input === "f") {
738 else if (input === "*" && rows[cursor] !== undefined) {
739 const row = rows[cursor]!;
740 const starred = setStarred(db, me, { id: row.id, starred: !row.starred });
741 said = starred.ok ? `${row.name}: ${starred.value.starred ? "starred" : "star taken off"}.` : starred.message;
742 } else if (input === "f") {
733743 show = VIEWS[(VIEWS.indexOf(show) + 1) % VIEWS.length]!;
734744 cursor = 0;
735745 } else if (input === "/") view = { name: "search", typed: q };
@@ -861,6 +871,9 @@ export function terminal(
861871 else if (input === "A" && l.back_on !== null) {
862872 const back = setBackOn(db, me, { id, back_on: null });
863873 said = back.ok ? `${l.name}: brought back. Follow-ups are scheduled again.` : back.message;
874 } else if (input === "*" && mayStar(l)) {
875 const starred = setStarred(db, me, { id, starred: !l.starred });
876 said = starred.ok ? `${l.name}: ${starred.value.starred ? "starred" : "star taken off"}.` : starred.message;
864877 } else if (input === "u" && l.showing !== null) {
865878 const off = cancelShowing(db, me, { id });
866879 said = off.ok ? "Showing cancelled. Follow-ups are back in their usual place." : off.message;
static/app.css +27
@@ -190,6 +190,33 @@ footer {
190190 .desk li + li {
191191 border-top: 1px solid var(--color-line);
192192 }
193 .lead-item {
194 display: grid;
195 grid-template-columns: minmax(0, 1fr) auto;
196 align-items: center;
197 }
198 .star {
199 margin: 0;
200 padding-right: var(--space-2);
201 }
202 .star-button {
203 min-width: var(--size-tap);
204 min-height: var(--size-tap);
205 padding: 0;
206 font-size: var(--text-xl);
207 line-height: 1;
208 color: var(--color-muted);
209 background: transparent;
210 border: 0;
211 border-radius: var(--radius-md);
212 cursor: pointer;
213 }
214 .star-button[aria-pressed="true"] {
215 color: var(--color-fg);
216 }
217 .lead-head .star {
218 display: inline-block;
219 }
193220 .lead-row {
194221 display: grid;
195222 grid-template-columns: minmax(0, 1fr) auto;

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs