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

The client list can be searched by name or email with a plain GET box that survives a reload #14656

Merged opened this

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

Merged

scout/forge:scout/14641-the-client-list-can-be-searched-by-name → main 5 commits fork 2 threads · 2 unresolved

  • Merged. scout/14641-the-client-list-can-be-searched-by-name was merged into main as 5826e87.

Review

Sign in to review this change.
6 files changed +214 −16
docs/features/client-search.md added +13
@@ -0,0 +1,13 @@
1 ---
2 topic: Hosting forges for others, and getting paid
3 row: The forges you sent are searched by name or email
4 ---
5 # The forges you sent are searched by name or email (#14641)
6
7 An owner with many clients finds one at once. `/forges?q=maria` keeps the forges whose name, the person it was sent for, or the claimant's email contains the text, ignoring case (`searchClients`, `src/spawn/client_search.ts`).
8
9 - **On the page.** A plain GET search box above the list; the text stays in the box and survives a reload. It combines with the state and sort links, which carry `q`. No match says `No forges match "…"` with a link to clear. An empty `q` shows all.
10 - **In the terminal.** On *Forges you sent* (palette, `ctrl+k`, admins, as the page is) press `/`, type a name or email and Enter; the first line names the search and its count, and no match says so. `/` then an empty box shows all again. It combines with `f` (state) and uses the same `parseClientQuery` and `searchClients` (`stateLines`, `src/tui/screens/forges.ts`).
11 - **Counts.** The state counts and All (N) are over the searched rows, so they agree with the list.
12 - **Input.** `q` is trimmed, control characters dropped, capped at 80 characters, and escaped on output. The rows are in memory, so it is a substring match: no SQL, and `%`, `_` are ordinary characters.
13 - **Tests.** `bun test test/client-search.test.ts test/tui-forges.test.ts`.
src/spawn/client_search.ts added +26
@@ -0,0 +1,26 @@
1 /**
2 * The client list is searched by name or contact (#14641): `/forges?q=maria`. The rows are
3 * already in memory, so this is a plain case-insensitive substring match: no SQL, no pattern, so
4 * `%`, `_` and `\` are ordinary characters. A name is the forge's name, the person it was sent
5 * for, or the address that claimed it.
6 */
7

Both doors: no terminal screen in src/tui/ uses this. Add the search to the terminal client list, with a test, and name both doors in the how-to.

8 import type { ClientRow } from "./clients.ts";
9
10 export const CLIENT_QUERY_MAX = 80;
11
12 /** The query asked for: trimmed, control characters dropped, capped; empty means show all. */
13 export function parseClientQuery(raw: string | null): string {
14 // eslint-disable-next-line no-control-regex
15 return (raw ?? "").replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, CLIENT_QUERY_MAX).trim();
16 }
17
18 export function matchesClientQuery(r: ClientRow, q: string): boolean {
19 if (q === "") return true;
20 const needle = q.toLowerCase();
21 return [r.name, r.for, r.claimedBy].some((s) => (s ?? "").toLowerCase().includes(needle));
22 }
23
24 export function searchClients<T extends ClientRow>(rows: readonly T[], q: string): T[] {
25 return rows.filter((r) => matchesClientQuery(r, q));
26 }
src/tui/screens/forges.ts +32 −9
@@ -13,6 +13,7 @@ import { card } from "../ui/widgets.ts";
1313 import { drawFacts, runAsync } from "./common.ts";
1414 import type { PaletteEntry } from "./entries.ts";
1515 import { clientRows } from "../../spawn/clients.ts";
16 import { parseClientQuery, searchClients } from "../../spawn/client_search.ts";
1617 import { CLIENT_STATE_EMPTY, CLIENT_STATE_WORDS, narrowByState, nextClientState, type ClientState } from "../../spawn/client_state.ts";
1718 import { diskWords } from "../../spawn/disk_mount.ts";
1819 import { archiveForge, archivedForges, destinationWords, restoreForge } from "../../spawn/archive.ts";
@@ -22,7 +23,7 @@ import { moveToCell } from "../../spawn/move_cell.ts";
2223 import { readOwnCode } from "../../spawn/own_code.ts";
2324 import type { App } from "../../app.ts";
2425 import { undoable, type LinkInfo } from "../../spawn/claim.ts";
25 import { confirmScreen, pickerScreen } from "./common.ts";
26 import { confirmScreen, pickerScreen, promptScreen } from "./common.ts";
2627 import type { Session } from "../session.ts";
2728 import { offerNewLink } from "./claim_link.ts";
2829 import { appLinkSummary, appLinkWords } from "../../spawn/app_links.ts";
@@ -106,15 +107,23 @@ export function ownCodePicks(app: App, rows: readonly ClientRow[]): { id: string
106107 * The lines for one state (#14538), as /forges?state= narrows them: a heading with the count, then
107108 * the rows, or the page's empty words with the way back. Null shows all, unheaded.
108109 */
109 export function stateLines(rows: readonly ClientRow[], state: ClientState | null, sender = false, now = Date.now()): [string, string][] {
110 if (state === null) return forgeLines(rows, sender, now);
111 const shown = narrowByState(rows, state, now);
112 const head: [string, string] = ["Showing", `${CLIENT_STATE_WORDS[state]} (${String(shown.length)} of ${String(rows.length)}) · f for the next view`];
113 return shown.length === 0 ? [head, ["", `${CLIENT_STATE_EMPTY[state]} · f shows all`]] : [head, ...forgeLines(shown, sender, now)];
110 export function stateLines(rows: readonly ClientRow[], state: ClientState | null, sender = false, now = Date.now(), q = ""): [string, string][] {
111 if (state === null && q === "") return forgeLines(rows, sender, now);
112 const found = searchClients(rows, q);
113 const shown = narrowByState(found, state, now);
114 const what = [state === null ? null : CLIENT_STATE_WORDS[state], q === "" ? null : `matching "${q}"`].filter((m) => m !== null).join(" ");
115 const head: [string, string] = ["Showing", `${what} (${String(shown.length)} of ${String(rows.length)}) · f for the next view · / to search`];
116 if (shown.length > 0) return [head, ...forgeLines(shown, sender, now)];
117 const none = q !== "" ? `No forges match "${q}" · / to change the search` : CLIENT_STATE_EMPTY[state!];
118 return [head, ["", state === null ? none : `${none} · f shows all`]];
114119 }
115120
116121 export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Session, from: ClientState | null = null): Screen {
117122 let state = from;
123 let q = "";
124 const redraw = (): void => {
125 lines = stateLines(rows, state, session?.user?.isAdmin === true, Date.now(), q);
126 };
118127 let lines = stateLines(rows, state, session?.user?.isAdmin === true);
119128 // Stop and Remove are the page's buttons, through the same actions (`spawn/manage.ts`).
120129 const choose = (title: string, act: (name: string) => void): void => {
@@ -221,7 +230,7 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses
221230 };
222231 const screen: Screen = {
223232 title: "Forges you sent",
224 keys: [binding(["s"], "stop"), binding(["a"], "archive"), binding(["r"], "restore"), binding(["x"], "remove"), binding(["n"], "new link"), binding(["l"], "end a link"), binding(["u"], "undo an ended link"), binding(["o"], "own code or this forge's"), binding(["m"], "move"), binding(["w"], "raise to xlarge"), binding(["f"], "state"), binding(["esc"], "close")],
233 keys: [binding(["s"], "stop"), binding(["a"], "archive"), binding(["r"], "restore"), binding(["x"], "remove"), binding(["n"], "new link"), binding(["l"], "end a link"), binding(["u"], "undo an ended link"), binding(["o"], "own code or this forge's"), binding(["m"], "move"), binding(["w"], "raise to xlarge"), binding(["f"], "state"), binding(["/"], "search"), binding(["esc"], "close")],
225234 render(area, s) {
226235 const c = ctx.theme.c;
227236 const w = Math.min(100, Math.max(30, area.w - 6));
@@ -235,8 +244,22 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses
235244 if (e.key === "esc" || e.key === "q") ctx.pop();
236245 else if (e.key === "f") {
237246 state = nextClientState(state);
238 lines = stateLines(rows, state, session?.user?.isAdmin === true);
239 } else if (e.key === "s" && session !== undefined)
247 redraw();
248 } else if (e.key === "/")
249 ctx.push(
250 promptScreen(ctx, screen, {
251 title: "Search forges",
252 label: "name or email; empty shows all",
253 value: q,
254 onSubmit: (value) => {
255 q = parseClientQuery(value);
256 redraw();
257 ctx.invalidate();
258 return undefined;
259 },
260 }),
261 );
262 else if (e.key === "s" && session !== undefined)
240263 choose("Stop which forge?", (name) => void stopForge(session.app, name).then((done) => ctx.toast(done.says, done.ok ? "success" : "danger")));
241264 else if (e.key === "n") newLink();
242265 else if (e.key === "l") changeOne("revoke");
src/web/pages/forges.ts +17 −6
@@ -36,6 +36,7 @@ import { forgeReachRows } from "./hosted-forges.ts";
3636 import { keptWords, readHosted } from "../../snapshot/hosted.ts";
3737 import { archiveForge, archivedForges, restoreForge, type ArchiveRecord } from "../../spawn/archive.ts";
3838 import { CLIENT_STATES, CLIENT_STATE_EMPTY, CLIENT_STATE_WORDS, narrowByState, parseClientState, stateCounts } from "../../spawn/client_state.ts";
39 import { parseClientQuery, searchClients } from "../../spawn/client_search.ts";
3940 import { claimedWords, isForgeSort, keepWords, SORT_WORDS, sortForges, type ForgeSort } from "../../spawn/keep_words.ts";
4041 import { CHILD_NAME } from "../../spawn/placement.ts";
4142 import { forgesMemory, memoryOverLine } from "../../spawn/memory_fit.ts";
@@ -245,8 +246,10 @@ export async function forgesPage(ctx: Ctx): Promise<Response> {
245246 const everyone = sortForges(await timePhaseAsync(ctx.request, "clients", () => servedRows(ctx.app)), sort);
246247 const state = parseClientState(ctx.url.searchParams.get("state"));
247248 const now = Date.now();
248 const counts = stateCounts(everyone, now);
249 const rows = narrowByState(everyone, state, now);
249 const q = parseClientQuery(ctx.url.searchParams.get("q"));
250 const searched = searchClients(everyone, q);
251 const counts = stateCounts(searched, now);
252 const rows = narrowByState(searched, state, now);
250253 const archived = archivedForges(ctx.app);
251254 const full = timePhase(ctx.request, "room", () => noRoom(ctx.app));
252255 // Two small tables, by name: the rows themselves come from memory, and this reads no ledger.
@@ -282,15 +285,23 @@ export async function forgesPage(ctx: Ctx): Promise<Response> {
282285 </section>
283286 <section class="settings-block">
284287 <h2>Forges</h2>
285 <nav class="muted small" aria-label="Sort forges" data-sorts>Sort: ${(Object.keys(SORT_WORDS) as ForgeSort[]).map((k, i) => html`${i > 0 ? " · " : ""}${k === sort ? html`<strong aria-current="true">${SORT_WORDS[k]}</strong>` : html`<a href="/forges?sort=${k}${state === null ? null : html`&amp;state=${state}`}">${SORT_WORDS[k]}</a>`}`)}</nav>
288 <nav class="muted small" aria-label="Sort forges" data-sorts>Sort: ${(Object.keys(SORT_WORDS) as ForgeSort[]).map((k, i) => html`${i > 0 ? " · " : ""}${k === sort ? html`<strong aria-current="true">${SORT_WORDS[k]}</strong>` : html`<a href="/forges?sort=${k}${state === null ? null : html`&amp;state=${state}`}${q === "" ? null : html`&amp;q=${encodeURIComponent(q)}`}">${SORT_WORDS[k]}</a>`}`)}</nav>
286289 <ul class="list setting-list" aria-label="Narrow forges by state" data-states>
outdated

counts and the All (N) total are computed from the unsearched rows (stateCounts(everyone)), so with q set they no longer match the rows listed. Compute them over searchClients(everyone, q).

287 <li>${state === null ? html`<strong aria-current="true">All (${everyone.length})</strong>` : html`<a href="/forges?sort=${sort}">All (${everyone.length})</a>`}</li>
288 ${CLIENT_STATES.map((k) => html`<li>${k === state ? html`<strong aria-current="true">${CLIENT_STATE_WORDS[k]} (${counts[k]})</strong>` : html`<a href="/forges?state=${k}&amp;sort=${sort}">${CLIENT_STATE_WORDS[k]} (${counts[k]})</a>`}</li>`)}
290 <li>${state === null ? html`<strong aria-current="true">All (${searched.length})</strong>` : html`<a href="/forges?sort=${sort}${q === "" ? null : html`&amp;q=${encodeURIComponent(q)}`}">All (${searched.length})</a>`}</li>
291 ${CLIENT_STATES.map((k) => html`<li>${k === state ? html`<strong aria-current="true">${CLIENT_STATE_WORDS[k]} (${counts[k]})</strong>` : html`<a href="/forges?state=${k}&amp;sort=${sort}${q === "" ? null : html`&amp;q=${encodeURIComponent(q)}`}">${CLIENT_STATE_WORDS[k]} (${counts[k]})</a>`}</li>`)}
289292 </ul>
293 <form method="get" action="/forges" role="search" class="mt" data-search>
294 <input type="hidden" name="sort" value="${sort}" />
295 ${state === null ? null : html`<input type="hidden" name="state" value="${state}" />`}
296 <input type="search" name="q" value="${q}" maxlength="80" placeholder="Search by name or email" aria-label="Search forges by name or email" />
297 ${btn("Search", { size: "sm" })}
298 </form>
290299 <form id="forges-archive-form" method="get" action="/forges/archive" class="mt">
291300 ${btn("Archive selected", { size: "sm", title: "Pick forges with the boxes; the next page says what happens before anything does" })}
292301 </form>
293 ${state !== null && rows.length === 0
302 ${q !== "" && rows.length === 0
303 ? html`<p data-empty>No forges match "${q}". <a href="/forges?sort=${sort}" data-clear>Clear the search</a></p>`
304 : state !== null && rows.length === 0
294305 ? html`<p data-empty>${CLIENT_STATE_EMPTY[state]}. <a href="/forges?sort=${sort}">All forges</a></p>`
295306 : html`<ul class="list setting-list">
296307 ${rows.map((r) => forgeRow(r, now, reachOf.get(r.name), claimsBill(user, r.billTo), keptWords(hostedKept, r.name, now)))}
test/client-search.test.ts added +101
@@ -0,0 +1,101 @@
1 /** The client list is searched by name or contact (#14641): `/forges?q=`. */
2
3 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
4 import { mkdtemp, rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createRepo } from "../src/actions/repos.ts";
8 import { createApp, type App } from "../src/app.ts";
9 import { createToken } from "../src/core/tokens.ts";
10 import { createUser } from "../src/core/users.ts";
11 import { commitFiles } from "../src/git/write.ts";
12 import { repoDir } from "../src/git/repos.ts";
13 import { serve, type Servers } from "../src/http/server.ts";
14 import { useChildFetch, type ClientRow } from "../src/spawn/clients.ts";
15 import { CLIENT_QUERY_MAX, matchesClientQuery, parseClientQuery, searchClients } from "../src/spawn/client_search.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17
18 quietLogs();
19
20 const row = (name: string, over: Record<string, unknown> = {}) => ({ name, for: null, claimedBy: null, ...over }) as unknown as ClientRow;
21 const rows = [row("maria", { for: "Maria Lopez" }), row("bob", { claimedBy: "[email protected]" }), row("100%")];
22
23 describe("client search", () => {
24 test("matches name, person and contact, any case", () => {
25 expect(searchClients(rows, "MARI").map((r) => r.name)).toEqual(["maria"]);
26 expect(searchClients(rows, "lopez").map((r) => r.name)).toEqual(["maria"]);
27 expect(searchClients(rows, "bob@example").map((r) => r.name)).toEqual(["bob"]);
28 });
29 test("empty shows all; wildcards are ordinary characters", () => {
30 expect(searchClients(rows, "")).toHaveLength(3);
31 expect(searchClients(rows, "%").map((r) => r.name)).toEqual(["100%"]);
32 expect(searchClients(rows, "_")).toHaveLength(0);
33 expect(matchesClientQuery(rows[0]!, "' OR 1=1 --")).toBe(false);
34 });
35 test("the query is trimmed and capped", () => {
36 expect(parseClientQuery(" a\u0000b ")).toBe("a b");
37 expect(parseClientQuery(null)).toBe("");
38 expect(parseClientQuery("x".repeat(500))).toHaveLength(CLIENT_QUERY_MAX);
39 });
40 });
41
42 describe("the client list page", () => {
43 let dir = "";
44 let app: App;
45 let servers: Servers;
46 let cookie = "";
47 const get = async (q: string) => (await fetch(`${servers.url}/forges${q}`, { headers: { cookie } })).text();
48
49 beforeAll(async () => {
50 dir = await mkdtemp(join(tmpdir(), "forge-client-search-"));
51 app = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
52 const pw = "a-long-client-search-passphrase";
53 const alice = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: pw, isAdmin: true });
54 if (!alice.ok) throw new Error("user");
55 const rw = createToken(app.db, alice.value.id, "rw", "rw").token;
56 const repo = await createRepo(app, alice.value, { name: "bakery" });
57 if (!repo.ok) throw new Error("repo");
58 const c = await commitFiles(repoDir(app.reposRoot, "alice", "bakery"), {
59 branch: "main", message: "bakery", files: [{ path: "README.md", content: "# bakery\n" }], author: { name: "a", email: "[email protected]" },
60 });
61 if (!c.ok) throw new Error("commit");
62 servers = await serve(app);
63 useChildFetch(app, () => Promise.reject(new Error("unreachable")));
64 const made = await fetch(`${servers.url}/api/v1/forges`, {
65 method: "POST",
66 headers: { authorization: `Bearer ${rw}`, "content-type": "application/json" },
67 body: JSON.stringify({ name: "maria", for: "Maria", apps: ["alice/bakery"], dryRun: false }),
68 });
69 if (made.status !== 201) throw new Error(`spawn ${made.status}`);
70 const res = await fetch(`${servers.url}/signin`, { method: "POST", body: new URLSearchParams({ username: "alice", password: pw }), redirect: "manual" });
71 cookie = (res.headers.get("set-cookie") ?? "").split(";")[0]!;
72 });
73 afterAll(async () => {
74 await servers.stop();
75 await rm(dir, { recursive: true, force: true });
76 });
77
78 test("a match shows the row and keeps the box filled; empty q shows all", async () => {
79 const body = await get("?q=MAR");
80 expect(body).toContain('data-forge="maria"');
81 expect(body).toMatch(/<input[^>]*name="q"[^>]*value="MAR"/);
82 expect(await get("?q=")).toContain('data-forge="maria"');
83 });
84 test("no match says so with a link to clear", async () => {
85 const body = await get("?q=zzz");
86 expect(body).not.toContain('data-forge="maria"');
87 expect(body).toContain('No forges match "zzz"');
88 expect(body).toMatch(/<a href="\/forges\?sort=attention" data-clear>Clear the search<\/a>/);
89 });
90 test("the state counts are over the searched rows", async () => {
91 const hit = await get("?q=maria");
92 expect(hit).toMatch(/data-states[\s\S]*?All \(1\)/);
93 const miss = await get("?q=zzz");
94 expect(miss).toMatch(/data-states[\s\S]*?All \(0\)/);
95 });
96 test("a hostile q is escaped, never raw", async () => {
97 const body = await get("?q=" + encodeURIComponent('"><script>alert(1)</script>'));
98 expect(body).not.toContain("<script>alert(1)");
99 expect(body).toContain("&lt;script&gt;");
100 });
101 });
test/tui-forges.test.ts +25 −1
@@ -48,11 +48,20 @@ describe("forges narrowed by state in the terminal (#14538)", () => {
4848 const claimed = row({ name: "c", claimed: true, stage: { key: "signedin" } as ClientRow["stage"] });
4949 test("a state keeps its own forges and heads the list with the count", () => {
5050 const lines = stateLines([sent, claimed], "waiting", false, NOW);
51 expect(lines[0]).toEqual(["Showing", "Waiting (1 of 2) · f for the next view"]);
51 expect(lines[0]).toEqual(["Showing", "Waiting (1 of 2) · f for the next view · / to search"]);
5252 expect(lines.map((l) => l[0])).toContain("w");
5353 expect(lines.map((l) => l[0])).not.toContain("c");
5454 expect(stateLines([sent, claimed], "in", false, NOW)[0]![1]).toContain("Signed in (1 of 2)");
5555 });
56 test("a search keeps the matching forges, counts over them, and says when none match", () => {
57 const named = row({ name: "maria", for: "Maria Lopez" });
58 const lines = stateLines([named, claimed], null, false, NOW, "LOPEZ");
59 expect(lines[0]).toEqual(["Showing", 'matching "LOPEZ" (1 of 2) · f for the next view · / to search']);
60 expect(lines.map((l) => l[0])).toContain("maria");
61 expect(lines.map((l) => l[0])).not.toContain("c");
62 expect(stateLines([named, claimed], "in", false, NOW, "lopez")[1]).toEqual(["", 'No forges match "lopez" · / to change the search · f shows all']);
63 expect(stateLines([named], null, false, NOW, "%").at(-1)![1]).toContain('No forges match "%"');
64 });
5665 test("a state with none says so and how to get back", () => {
5766 const lines = stateLines([claimed], "waiting", false, NOW);
5867 expect(lines[1]).toEqual(["", "No forges are waiting · f shows all"]);
@@ -136,6 +145,21 @@ describe("forges you sent in the terminal", () => {
136145 h.stop();
137146 });
138147
148 test("/ opens a search box; a query with no match says so, and an empty one shows all", async () => {
149 const h = boot("alice");
150 await h.palette();
151 await h.enter();
152 await h.press("/");
153 for (const ch of "zz") await h.press(ch);
154 await h.enter();
155 expect(h.text()).toContain('No forges match "zz"');
156 await h.press("/");
157 for (let i = 0; i < 2; i++) await h.press("backspace");
158 await h.enter();
159 expect(h.text()).toContain("You have not sent a forge yet");
160 h.stop();
161 });
162
139163 test("the screen lists the keys for a link: end it, undo it; with none to change it says so", async () => {
140164 const h = boot("alice");
141165 await h.palette();

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs