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

The home shows the desk as one quiet live strip; a hold shows on the pull it names #12566

Merged opened this

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

Merged

scout/forge:scout/12536-the-home-shows-the-desk-as-one-quiet-liv → main 9 commits fork 2 threads · 2 unresolved

  • Merged. scout/12536-the-home-shows-the-desk-as-one-quiet-liv was merged into main as d6cdd3f.

Review

Sign in to review this change.
21 files changed +433 −5
docs/design/areas/desk.md added +5
@@ -0,0 +1,5 @@
1 # Desk
2
3 `.desk-line`: the desk as one quiet line (`src/web/desk_strip.ts`). A fixed-height block that holds a single
4 `p.small.muted` truncated to one line, so a note arriving or leaving moves nothing. On a pull, a hold that links it is
5 a plain `p.small` in a `.stack-tight` section: no new class.
docs/features/desk.md +9
@@ -13,3 +13,12 @@ Each repository has its own desk: a note belongs to the repository it was left t
1313 In the terminal: the palette's `<owner>/<name> — Desk` (anyone who may read the repository). `n` leaves a note (its kind, then its words; a writer or a crew member), `x` clears the one under the cursor (its author or an admin); the screen follows `desk.noted` and `desk.cleared`, so a note an agent leaves appears at once. Code: `src/tui/screens/desk.ts`.
1414
1515 The repository in the path decides who may read and write it. Code: `src/core/desk.ts` (rules), `src/actions/desk.ts` (gate, events), `src/http/api/desk.ts`.
16
17 ## On the page
18
19 The desk is per repository (above); the page reads across them, for people who are signed in (a guest sees none of it).
20
21 - **Home.** One quiet line under the strip (`src/web/desk_strip.ts`): the newest live note of any repository the viewer may read, and a count of the rest; empty when the desk is. Its height is fixed, so a note arriving moves nothing.
22 - **A hold on a pull.** A hold that links `/owner/repo/pulls/N` (bare, or on this forge's host) shows as "On hold" under the head of that pull, on every tab. A hold naming two pulls shows on both.
23 - **Live.** The strip follows `desk.*` and fetches `/live/desk` (404 to a guest). `sweepDesk` (`src/actions/desk.ts`, every 30 seconds) says `desk.expired` (a count, no words) to the readers of each repository that lost a note when notes lapse.
24 - **Writing.** `POST /desk` (`repo` as `owner/name`, `kind`, `body`, optional `hours`) and `POST /desk/clear` (`repo`, `note`): signed in, same-origin, the same gate as the API (`src/web/studio/desk_post.ts`). No form on the home yet: the line stays one line.
src/actions/desk.ts +25 −2
@@ -8,9 +8,9 @@
88 */
99 import type { App } from "../app.ts";
1010 import { err, ok, type Result } from "../kernel/result.ts";
11 import { canRead, canWrite, onCrew, type Repo } from "../core/repos.ts";
11 import { canRead, canWrite, getRepoById, onCrew, type Repo } from "../core/repos.ts";
1212 import type { User } from "../core/users.ts";
13 import { addNote, clearNote, listNotes, type DeskError, type DeskNote } from "../core/desk.ts";
13 import { addNote, clearNote, expireNotes, lapsedRepos, listAllNotes, listNotes, type DeskError, type DeskNote } from "../core/desk.ts";
1414 import type { AccessError } from "./access.ts";
1515
1616 /** Who may leave or clear a note: the repository's writers and its crew. */
@@ -85,3 +85,26 @@ export function removeNote(app: App, actor: User | undefined, repo: Repo, noteId
8585 app.bus.append({ kind: "desk.cleared", repoId: repo.id, actorId: writer.value.id, payload: { note: noteId } });
8686 return cleared;
8787 }
88
89 /** The live notes of every repository this viewer may read (home line, holds on a pull). */
90 export function readableNotes(app: App, actor: User | undefined, now: Date = new Date()): DeskNote[] {
91 if (actor === undefined) return []; // the desk on the page is for people signed in
92 const may = new Map<string, boolean>();
93 return listAllNotes(app.db, now).filter((n) => {
94 let yes = may.get(n.repoId);
95 if (yes === undefined) {
96 const repo = getRepoById(app.db, n.repoId);
97 yes = repo !== undefined && canRead(app.db, repo, actor);
98 may.set(n.repoId, yes);
99 }
100 return yes;
101 });
102 }
103
104 /** Drop the notes whose time is up; each repository that lost one says so to its readers. */
105 export function sweepDesk(app: App, now: Date = new Date()): number {
106 const lapsed = lapsedRepos(app.db, now);
107 const gone = expireNotes(app.db, now);
108 for (const repoId of lapsed) app.bus.append({ kind: "desk.expired", repoId, payload: { count: gone } });
109 return gone;
110 }
src/core/desk.ts +16
@@ -98,6 +98,14 @@ export function hasOutsideLink(text: string, forgeHosts: readonly string[] = [])
9898 /** Whether `text` holds a string shaped like a credential (the code scanner's rules). */
9999 export const hasSecret = (text: string): boolean => secretFindings("desk", text).length > 0;
100100
101 /** The repositories that hold a note whose time is up. */
102 export function lapsedRepos(db: Database, now: Date = new Date()): string[] {
103 return db
104 .query<{ repo_id: string }, [string]>("SELECT DISTINCT repo_id FROM desk_note WHERE expires_at <= ?1")
105 .all(now.toISOString())
106 .map((r) => r.repo_id);
107 }
108
101109 /** Drop the notes whose time is up. */
102110 export function expireNotes(db: Database, now: Date = new Date()): number {
103111 return db.query("DELETE FROM desk_note WHERE expires_at <= ?1").run(now.toISOString()).changes;
@@ -145,6 +153,14 @@ export function listNotes(db: Database, repoId: string, now: Date = new Date()):
145153 .map(fromRow);
146154 }
147155
156 /** Every repository's live notes, newest first: the home's line filters them by who may read. */
157 export function listAllNotes(db: Database, now: Date = new Date()): DeskNote[] {
158 return db
159 .query<Row, [string]>("SELECT * FROM desk_note WHERE expires_at > ?1 ORDER BY created_at DESC, id DESC LIMIT 500")
160 .all(now.toISOString())
161 .map(fromRow);
162 }
163
148164 /**
149165 * Clear a note of this repository: its author or an admin only. Another repository's note is
150166 * not found.
src/core/event_audience.ts +1
@@ -181,6 +181,7 @@ const READER_KINDS: ReadonlySet<string> = new Set([
181181 // The desk's notes are short, secret-filtered, for readers (`actions/desk.ts`).
182182 "desk.noted",
183183 "desk.cleared",
184 "desk.expired",
184185 // A pin's screenshots are read by its repository's readers (`actions/build_shots.ts`).
185186 "build.shots",
186187 "invite.used",
src/core/reserved.ts +1
@@ -65,6 +65,7 @@ export const SYSTEM_NAMES: readonly string[] = [
6565 "audit.csv",
6666 "big",
6767 "board",
68 "desk",
6869 "boards",
6970 "broker",
7071 "contribute",
src/http/route_marks.ts +2
@@ -127,6 +127,7 @@ export const HEADS: Readonly<Record<string, Mark | "mixed">> = {
127127 "/flow": "mixed",
128128 "/forges": "mixed",
129129 "/front": "open",
130 "/desk": "open",
130131 "/go": "open",
131132 "/home": "open",
132133 "/hooks": "open",
@@ -229,6 +230,7 @@ export const ROUTES: Readonly<Record<string, Mark>> = {
229230 "/forges/start": "open",
230231 "/live/apps": "open",
231232 "/live/on-you": "open",
233 "/live/desk": "open",
232234 "/live/client-apps": "open",
233235 "/live/feed": "open",
234236 "/live/milestones": "open",
src/http/server.ts +5
@@ -348,10 +348,12 @@ import {
348348 feedPage,
349349 liveAppsFragment,
350350 liveClientAppsFragment,
351 liveDeskFragment,
351352 liveHomeFragment,
352353 liveOnYouFragment,
353354 studioDoor,
354355 } from "../web/studio/home.ts";
356 import { deskClear, deskLeave } from "../web/studio/desk_post.ts";
355357 import { appAnswersFragment } from "../web/studio/answers.ts";
356358 import { appNowFragment } from "../web/studio/now.ts";
357359 import { appStateFragment } from "../web/studio/previews.ts";
@@ -897,6 +899,8 @@ export function buildRouter(): Router<Handler> {
897899 router.add("GET", "/home", homeRedirect);
898900 // The new home's action bar: preview or apply one bulk action over the rows picked (web/pages/home_table.ts).
899901 router.add("POST", "/home/act", homeActPost);
902 router.add("POST", "/desk", deskLeave);
903 router.add("POST", "/desk/clear", deskClear);
900904 // A spawned child's claim link: GET shows, POST takes it (spawn/claim.ts).
901905 router.add("GET", "/claim", claimFragmentPage);
902906 router.add("POST", "/claim", claimSubmit);
@@ -1102,6 +1106,7 @@ export function buildRouter(): Router<Handler> {
11021106 // fetches a region and not the page. Literal, above /:owner.
11031107 router.add("GET", "/live/apps", liveAppsFragment);
11041108 router.add("GET", "/live/on-you", liveOnYouFragment);
1109 router.add("GET", "/live/desk", liveDeskFragment);
11051110 router.add("GET", "/live/client-apps", liveClientAppsFragment);
11061111 router.add("GET", "/live/feed", liveFeedFragment);
11071112 router.add("GET", "/live/milestones", liveMilestonesFragment);
src/http/sse.ts +1 −1
@@ -262,7 +262,7 @@ export function viewerStream(
262262 emit("run.log", { run: runId, ...frameOf(lines) });
263263 }, gone.signal);
264264 const unsubscribe = app.bus.subscribe((event: ForgeEvent) => {
265 if (event.repoId === null ? !event.kind.startsWith("backup.") : !visible(event.repoId)) return;
265 if (event.repoId === null ? !(event.kind.startsWith("backup.") || (viewer !== undefined && event.kind.startsWith("desk."))) : !visible(event.repoId)) return;
266266 if (!meant(event)) return;
267267 send(event);
268268 }, "ordered");
src/main.ts +4
@@ -6,6 +6,7 @@
66
77 import { join } from "node:path";
88 import { sweepEntitlements } from "./billing/sync.ts";
9 import { sweepDesk } from "./actions/desk.ts";
910 import { scanNightly } from "./checks/scan.ts";
1011 import { nightlyDue } from "./checks/scan_store.ts";
1112 import { checkLedger, setLedgerDir } from "./core/ledger.ts";
@@ -789,6 +790,8 @@ const landingsWatch = watchLandings(app);
789790 // A child born before its apps were linked is offered the link, and a child offered one takes it: at boot, then every tick.
790791 void followTick(app, true).catch((error) => app.log.error("could not link the apps", { error: String(error) }));
791792 const staleTimer = setInterval(() => void during("asks", tickAsks), 120_000);
793 // A desk note whose time is up goes off the home line at once, over the stream.
794 const deskTimer = setInterval(() => void during("desk", () => sweepDesk(app)), 30_000);
792795 // Every paid entitlement is re-read from Stripe once a day, so a missed webhook heals (#11247).
793796 const entitlementTimer = setInterval(() => void during("entitlements", () => sweepEntitlements(app)), 86_400_000);
794797 void during("entitlements", () => sweepEntitlements(app));
@@ -1021,6 +1024,7 @@ function drain(signal: NodeJS.Signals): Promise<unknown> {
10211024 clearInterval(reachTimer);
10221025 clearInterval(syncTimer);
10231026 clearInterval(staleTimer);
1027 clearInterval(deskTimer);
10241028 clearInterval(entitlementTimer);
10251029 if (ledgerTimer !== undefined) clearInterval(ledgerTimer);
10261030 clearInterval(followTimer);
src/web/desk_strip.ts added +89
@@ -0,0 +1,89 @@
1 /**
2 * The desk on the page (#12536): the home shows it as one quiet line, the
3 * newest live note with a count of the rest, empty when the desk is; a hold
4 * that links a pull shows on that pull. The strip is a live region
5 * (`desk.*` events, `/live/desk`), so it changes over the stream the page
6 * already holds and never by polling. Every word is escaped by `html`.
7 */
8 import type { Database } from "bun:sqlite";
9 import type { DeskNote } from "../core/desk.ts";
10 import { getUserById } from "../core/users.ts";
11 import { html, type Html } from "./html.ts";
12 import { time } from "./ui.ts";
13
14 /** The events that can change the desk. */
15 export const DESK_LIVE = "desk.*";
16
17 export interface PullRef {
18 readonly owner: string;
19 readonly name: string;
20 readonly number: number;
21 }
22
23 const KIND_WORD: Record<DeskNote["kind"], string> = {
24 doing: "Doing",
25 hold: "Hold",
26 found: "Found",
27 ask: "Ask",
28 };
29
30 /**
31 * Every pull a note links to: `/owner/name/pulls/N`, bare or on the forge's own
32 * host. A link to any other host names nothing (the desk refuses them anyway).
33 */
34 export function pullsLinked(body: string, forgeHost: string): PullRef[] {
35 const found: PullRef[] = [];
36 for (const m of body.matchAll(/(?<![\w/.-])(?:https?:\/\/([^/\s]+))?\/([\w.-]+)\/([\w.-]+)\/pulls\/(\d{1,9})(?!\d)/gi)) {
37 if (m[1] !== undefined && m[1].toLowerCase() !== forgeHost.toLowerCase()) continue;
38 found.push({ owner: m[2]!, name: m[3]!, number: Number(m[4]) });
39 }
40 return found;
41 }
42
43 const hostOf = (url: string): string => {
44 try {
45 return new URL(url).host;
46 } catch {
47 return "";
48 }
49 };
50
51 const who = (db: Database, id: string): string => getUserById(db, id)?.username ?? "someone";
52
53 /** The live holds that name this pull, newest first. */
54 export function holdsOnPull(notes: readonly DeskNote[], forgeUrl: string, ref: PullRef): DeskNote[] {
55 const host = hostOf(forgeUrl);
56 return notes.filter((n) => {
57 if (n.kind !== "hold") return false;
58 return pullsLinked(n.body, host).some((at) => at.number === ref.number && at.owner === ref.owner && at.name === ref.name);
59 });
60 }
61
62 /** The region: always present, so a note arriving moves nothing; empty when no note is live. */
63 export function deskStrip(db: Database, notes: readonly DeskNote[]): Html {
64 const [first] = notes;
65 const more = notes.length - 1;
66 return html`<div id="desk-strip" class="desk-line" data-live="${DESK_LIVE}" data-live-src="/live/desk">${
67 first === undefined
68 ? null
69 : html`<p class="small muted"
70 ><strong>${KIND_WORD[first.kind]}</strong> ${first.body}
71 <span class="sep" aria-hidden="true">·</span> ${who(db, first.authorId)} ${time(first.createdAt)}${
72 more > 0 ? html` <span class="sep" aria-hidden="true">·</span> ${more} more` : null
73 }</p
74 >`
75 }</div>`;
76 }
77
78 /** What a pull says of the holds that name it: one line each, nothing when none. */
79 export function holdLines(db: Database, notes: readonly DeskNote[], forgeUrl: string, ref: PullRef): Html | null {
80 const held = holdsOnPull(notes, forgeUrl, ref);
81 if (held.length === 0) return null;
82 return html`<section class="stack stack-tight" id="desk-holds" aria-label="Held on the desk">
83 ${held.map(
84 (n) =>
85 html`<p class="small"><strong>On hold</strong> ${n.body}
86 <span class="sep" aria-hidden="true">·</span> ${who(db, n.authorId)} ${time(n.createdAt)}</p>`,
87 )}
88 </section>`;
89 }
src/web/pages/home_flow.ts +3
@@ -54,6 +54,8 @@ import { secureFor } from "../../http/cookie_secure.ts";
5454 import { cookieValue } from "../../http/context.ts";
5555 import { parseTable, tableParams, tableRows, type TableQuery } from "../../flow/lanes_table.ts";
5656 import { TABLE_LIVE, tableRegion, tableTag, tableTools } from "./home_table.ts";
57 import { readableNotes } from "../../actions/desk.ts";
58 import { deskStrip } from "../desk_strip.ts";
5759 import { heldLine } from "../studio/held.ts";
5860 import { interruptedOutLine } from "../studio/interrupted_out.ts";
5961 import { listReposWritableTo } from "../../core/repos.ts";
@@ -559,6 +561,7 @@ export async function homeFlowPage(ctx: Ctx, known?: { readonly spawned: Awaited
559561 </header>
560562 ${before}
561563 ${strip}
outdated

Principle 1/2: the strip is always empty on the preview since nothing writes or emits desk events, so the live claim is unproven. Wire the events or drop data-live.

564 ${deskStrip(ctx.app.db, readableNotes(ctx.app, ctx.auth.user))}
562565 ${stopped}
563566 ${after}
564567 ${main}
src/web/studio/change.ts +8 −1
@@ -98,6 +98,8 @@ import { pullWord, servingHistory, stateDot, wordDot, type WordCtx } from "./wor
9898 import { getHold } from "../../core/holds.ts";
9999 import { backToWave } from "../../story/waves.ts";
100100 import { pullRoster } from "./pull_roster.ts";
101 import { readableNotes } from "../../actions/desk.ts";
102 import { holdLines } from "../desk_strip.ts";
101103
102104 /** The pull and its repo, or the response that refuses to say why not. */
103105 export function pullContext(ctx: Ctx): { repo: Repo; pull: Pull } | Response {
@@ -276,7 +278,12 @@ export function changeHead(
276278 )}${when(
277279 live === null ? null : landingLine(ctx.app.db, pull, repo.id),
278280 (eta) => html`<p class="muted small" data-landing-eta>${eta.says}</p>`,
279 )}
281 )}${
282 // The desk is the crew's: a guest sees no note, not even a hold on a public pull.
283 ctx.auth.user === undefined
284 ? null
285 : holdLines(ctx.app.db, readableNotes(ctx.app, ctx.auth.user), ctx.app.config.url ?? ctx.url.origin, { owner: repo.ownerName, name: repo.name, number: pull.number })
286 }
280287 </div>`;
281288 }
282289
src/web/studio/desk_post.ts added +61
@@ -0,0 +1,61 @@
1 /**
2 * Writing the desk from a form: `POST /desk` leaves a note, `POST /desk/clear`
3 * clears one (its author or an admin). Signed in and same-origin, like every
4 * mutation; the page goes back where it came from with one line saying what
5 * happened. The rules (length, kinds, secrets, links) are `core/desk.ts`'s.
6 */
7
8 import { DESK_WORDS, leaveNote, removeNote } from "../../actions/desk.ts";
9 import { getRepo } from "../../core/repos.ts";
10 import type { Ctx } from "../../http/context.ts";
11 import { signInFirst } from "../chrome.ts";
12 import { type Form, readForm } from "../form.ts";
13 import { redirect } from "../layout.ts";
14
15 const say = (error: string): string =>
16 error in DESK_WORDS
17 ? DESK_WORDS[error as keyof typeof DESK_WORDS]
18 : error === "forbidden"
19 ? "A writer or a crew member leaves a note."
20 : "No such desk.";
21
22 /** The repository a form names as `owner/name`. */
23 const repoOf = (ctx: Ctx, form: Form) => {
24 const [owner, name, extra] = field(form.get("repo"), 140).split("/");
25 return owner && name && extra === undefined ? getRepo(ctx.app.db, owner, name) : undefined;
26 };
27
28 const back = (ctx: Ctx, tone: "success" | "danger", message: string): Response =>
29 redirect("/", { url: ctx.url, forgeUrl: ctx.app.config.url, flash: { tone, message } });
30
31 const field = (v: unknown, max: number): string => (typeof v === "string" ? v.slice(0, max) : "");
32
33 // POST /desk — leave a note.
34 export async function deskLeave(ctx: Ctx): Promise<Response> {
35 const user = ctx.auth.user;
36 if (!user) return signInFirst(ctx);
37 const form = await readForm(ctx, "rw");
38 if (form instanceof Response) return form;
39 const repo = repoOf(ctx, form);
40 if (!repo) return back(ctx, "danger", say("not_found"));
41 const hours = field(form.get("hours"), 4);
42 const ttlHours = hours === "" ? undefined : /^\d{1,2}$/.test(hours) ? Number(hours) : -1;
43 const made = leaveNote(ctx.app, user, repo, {
44 kind: field(form.get("kind"), 16),
45 body: field(form.get("body"), 2_000),
46 ...(ttlHours === undefined ? {} : { ttlHours }),
47 });
48 return made.ok ? back(ctx, "success", "Left on the desk.") : back(ctx, "danger", say(made.error));
49 }
50
51 // POST /desk/clear — clear one note.
52 export async function deskClear(ctx: Ctx): Promise<Response> {
53 const user = ctx.auth.user;
54 if (!user) return signInFirst(ctx);
55 const form = await readForm(ctx, "rw");
56 if (form instanceof Response) return form;
57 const repo = repoOf(ctx, form);
58 if (!repo) return back(ctx, "danger", say("not_found"));
59 const cleared = removeNote(ctx.app, user, repo, field(form.get("note"), 64));
60 return cleared.ok ? back(ctx, "success", "Cleared.") : back(ctx, "danger", say(cleared.error));
61 }
src/web/studio/home.ts +12
@@ -80,6 +80,8 @@ import { homeFlowPage } from "../pages/home_flow.ts";
8080 import { crewKeyCard } from "./crew_key.ts";
8181 import { firstAskJs, nextStepsCard, nextStepsOf } from "../pages/next-steps.ts";
8282 import { spawnedForge } from "../../spawn/claim.ts";
83 import { readableNotes } from "../../actions/desk.ts";
84 import { deskStrip } from "../desk_strip.ts";
8385 import { clientApps } from "./client_home.ts";
8486
8587 /** The events that can change what is on you. */
@@ -202,6 +204,16 @@ export function liveAppsFragment(ctx: Ctx): Response {
202204 return body;
203205 }
204206
207 // GET /live/desk — the desk's one line alone.
208 export function liveDeskFragment(ctx: Ctx): Response {
209 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
210 if (!ctx.auth.user) return fragment(html``, { status: 404 });
211 const rendering = performance.now();
212 const body = fragment(deskStrip(ctx.app.db, readableNotes(ctx.app, ctx.auth.user)), { request: ctx.request });
213 notePhase(ctx.request, "render", performance.now() - rendering);
214 return body;
215 }
216
205217 // GET /live/client-apps — a client's apps card alone; 404 to anyone else.
206218 export async function liveClientAppsFragment(ctx: Ctx): Promise<Response> {
207219 const user = ctx.auth.user;
src/web/style/components.ts +4
@@ -973,6 +973,10 @@ html[data-overlay] { overflow: hidden; }
973973 /* The dot between facts on a line (a where strip, a row's meta); the crumbs
974974 keep their own for the flex rule. */
975975 .sep { color: var(--faint); }
976 /* The desk as one line (web/desk_strip.ts, docs/design/areas/desk.md): fixed height, so a
977 note arriving moves nothing. */
978 .desk-line { min-height: 24px; }
979 .desk-line p { margin: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
976980 .row-meta .sep { margin: 0 3px; }
977981 .crumbs .sep { color: var(--faint); flex: none; }
978982 .crumbs [aria-current="page"] { font-weight: 550; }
test/desk_page.test.ts added +121
@@ -0,0 +1,121 @@
1 /**
2 * The desk on its pages (#12536): a hold on every tab of the pull it names, for people signed in
3 * only; the home line; /live/desk; the desk.* events.
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { leaveNote, sweepDesk, removeNote } from "../src/actions/desk.ts";
10 import { openPull } from "../src/actions/pulls.ts";
11 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import { listEvents } from "../src/core/events.ts";
14 import type { Repo } from "../src/core/repos.ts";
15 import { createSession } from "../src/core/sessions.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
18 import { pullsLinked } from "../src/web/desk_strip.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20
21 quietLogs();
22
23 const url = "http://forge.test";
24
25 describe("pullsLinked", () => {
26 test("reads every pull a note names on this forge, nothing else", () => {
27 expect(pullsLinked("/a/b/pulls/1 and https://forge.test/a/b/pulls/2 and https://evil.test/a/b/pulls/3", "forge.test").map((r) => r.number)).toEqual([1, 2]);
28 });
29 });
30
31 describe("the desk on the pages", () => {
32 let dataDir = "";
33 let app: App;
34 let http: ForgeHttp;
35 let alice: User;
36 let lib: Repo;
37 const nums: number[] = [];
38 const get = (path: string, cookie?: string) =>
39 http.handle(new Request(`${url}${path}`, { headers: cookie ? { cookie } : {} }));
40
41 beforeAll(async () => {
42 dataDir = await mkdtemp(join(tmpdir(), "forge-deskpage-"));
43 app = createApp({ dataDir, port: 0, host: "forge.test" });
44 http = forgeHttp(app);
45 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
46 if (!made.ok) throw new Error(made.error);
47 alice = made.value;
48 const repo = await createRepo(app, alice, { name: "lib", visibility: "public" });
49 if (!repo.ok) throw new Error(String(repo.error));
50 lib = repo.value;
51 const seeded = await commitToBranch(app, alice, repo.value, { message: "Start", files: [{ path: "README.md", content: "lib\n" }] });
52 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
53 for (const b of ["one", "two"]) {
54 const c = await commitToBranch(app, alice, repo.value, { branch: b, message: b, files: [{ path: `${b}.md`, content: "x\n" }] });
55 if (!c.ok) throw new Error(JSON.stringify(c.error));
56 const o = await openPull(app, alice, repo.value, { title: b, baseBranch: "main", headBranch: b });
57 if (!o.ok) throw new Error(String(o.error));
58 nums.push(o.value.number);
59 }
60 }, 60_000);
61 afterAll(async () => {
62 http.close();
63 app.close();
64 await rm(dataDir, { recursive: true, force: true });
65 });
66 const cookie = () => `forge_session=${createSession(app.db, alice.id).token}`;
67
68 test("a hold naming two pulls shows on both, on the pull and its files tab, to a person; never to a guest", async () => {
69 const [a, b] = nums as [number, number];
70 const said = leaveNote(app, alice, lib, { kind: "hold", body: `park-for-rotation /alice/lib/pulls/${a} /alice/lib/pulls/${b}` });
71 expect(said.ok).toBe(true);
72 for (const n of [a, b]) {
73 for (const tab of ["", "/files"]) {
74 const page = await (await get(`/alice/lib/pulls/${n}${tab}`, cookie())).text();
75 expect(page).toContain("park-for-rotation");
76 }
77 const guest = await (await get(`/alice/lib/pulls/${n}`)).text();
78 expect(guest).not.toContain("park-for-rotation");
79 expect(await (await get(`/alice/lib/pulls/${n}/files`)).text()).not.toContain("park-for-rotation");
80 }
81 });
82
83 test("/live/desk is 404 to a guest and the strip to a person; the home carries the strip", async () => {
84 expect((await get("/live/desk")).status).toBe(404);
85 const live = await get("/live/desk", cookie());
86 expect(live.status).toBe(200);
87 expect(await live.text()).toContain("park-for-rotation");
88 const home = await (await get("/", cookie())).text();
89 expect(home).toContain('id="desk-strip"');
90 expect(home).toContain("park-for-rotation");
91 });
92
93 test("a note, a clear and an expiry each say so on the bus", () => {
94 const before = listEvents(app.db, { limit: 500 }).filter((e) => e.kind.startsWith("desk.")).length;
95 const made = leaveNote(app, alice, lib, { kind: "doing", body: "short note", ttlHours: 0.001 });
96 if (!made.ok) throw new Error(made.error);
97 expect(sweepDesk(app, new Date(Date.now() + 60_000))).toBe(1);
98 const again = leaveNote(app, alice, lib, { kind: "found", body: "another" });
99 if (!again.ok) throw new Error(again.error);
100 expect(removeNote(app, alice, lib, again.value.id).ok).toBe(true);
101 const events = listEvents(app.db, { limit: 500 }).filter((e) => e.kind.startsWith("desk."));
102 expect(events.length - before).toBe(4);
103 expect(events.map((e) => e.kind)).toEqual(expect.arrayContaining(["desk.noted", "desk.expired", "desk.cleared"]));
104 // A note rides its repository's stream (readers only); a clear and an expiry carry no words.
105 expect(JSON.stringify(events.filter((e) => e.kind !== "desk.noted"))).not.toContain("another");
106 });
107
108 test("POST /desk leaves a note for a person on this origin, refuses a stranger and a foreign origin, and clears only as author", async () => {
109 const post = (path: string, body: string, headers: Record<string, string> = {}) =>
110 http.handle(new Request(`${url}${path}`, { method: "POST", body, headers: { "content-type": "application/x-www-form-urlencoded", origin: url, ...headers } }));
111 const form = (o: Record<string, string>) => new URLSearchParams(o).toString();
112 await post("/desk", form({ repo: "alice/lib", kind: "doing", body: "no cookie" }));
113 expect(await (await get("/live/desk", cookie())).text()).not.toContain("no cookie");
114 expect((await post("/desk", form({ repo: "alice/lib", kind: "doing", body: "far away" }), { cookie: cookie(), origin: "http://evil.test" })).status).toBe(403);
115 expect((await post("/desk", form({ repo: "alice/lib", kind: "doing", body: "see https://evil.test/x" }), { cookie: cookie() })).headers.get("location") ?? "").toContain("/");
116 expect(await (await get("/live/desk", cookie())).text()).not.toContain("evil.test");
117 const ok = await post("/desk", form({ repo: "alice/lib", kind: "found", body: "posted by form" }), { cookie: cookie() });
118 expect(ok.status).toBe(303);
119 expect(await (await get("/live/desk", cookie())).text()).toContain("posted by form");
120 });
121 });
test/desk_strip.test.ts added +63
@@ -0,0 +1,63 @@
1 /** The desk on the page: the home line, the fragment it swaps, a hold on the pull it names. */
2 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { addNote, listAllNotes } from "../src/core/desk.ts";
8 import { createRepo } from "../src/actions/repos.ts";
9 import { createUser } from "../src/core/users.ts";
10 import { deskStrip, holdLines, holdsOnPull } from "../src/web/desk_strip.ts";
11 import { quietLogs } from "./helpers/globals.ts";
12
13 quietLogs();
14
15 describe("the desk strip", () => {
16 let dataDir = "";
17 let app: App;
18 let alice = "";
19 let repoId = "";
20 const T0 = new Date("2026-11-14T10:00:00Z");
21 beforeAll(async () => {
22 dataDir = await mkdtemp(join(tmpdir(), "forge-deskstrip-"));
23 app = createApp({ dataDir, port: 0 });
24 const u = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
25 if (!u.ok) throw new Error(u.error);
26 alice = u.value.id;
27 const r = await createRepo(app, u.value, { name: "app", visibility: "public" });
28 if (!r.ok) throw new Error(String(r.error));
29 repoId = r.value.id;
30 });
31 afterAll(async () => {
32 app.close();
33 await rm(dataDir, { recursive: true, force: true });
34 });
35
36 test("empty with no notes, yet the live region is there", () => {
37 const h = deskStrip(app.db, listAllNotes(app.db, T0)).text;
38 expect(h).toContain('id="desk-strip"');
39 expect(h).toContain('data-live="desk.*"');
40 expect(h).not.toContain("<p");
41 });
42
43 test("one line: the newest note, escaped, with a count of the rest", () => {
44 addNote(app.db, { repoId, authorId: alice, kind: "doing", body: "older", now: T0 });
45 addNote(app.db, { repoId, authorId: alice, kind: "found", body: "<b>x</b> newest", now: new Date(T0.getTime() + 1000) });
46 const h = deskStrip(app.db, listAllNotes(app.db, new Date(T0.getTime() + 2000))).text;
47 expect(h).toContain("&lt;b&gt;x&lt;/b&gt; newest");
48 expect(h).not.toContain("<b>");
49 expect(h).toContain("1 more");
50 expect(h.match(/<p\b/g)?.length).toBe(1);
51 });
52
53 test("a hold that links a pull shows on that pull and no other", () => {
54 addNote(app.db, { repoId, authorId: alice, kind: "hold", body: "hold /alice/app/pulls/7 until the key rotates", now: T0 });
55 addNote(app.db, { repoId, authorId: alice, kind: "doing", body: "working on /alice/app/pulls/8", now: T0 });
56 const ref = { owner: "alice", name: "app", number: 7 };
57 const later = new Date(T0.getTime() + 5000);
58 expect(holdsOnPull(listAllNotes(app.db, later), "https://f.test", ref).length).toBe(1);
59 expect(holdLines(app.db, listAllNotes(app.db, later), "https://f.test", ref)?.text).toContain("until the key rotates");
60 expect(holdLines(app.db, listAllNotes(app.db, later), "https://f.test", { ...ref, number: 8 })).toBeNull();
61 expect(holdLines(app.db, listAllNotes(app.db, new Date(T0.getTime() + 5 * 3_600_000)), "https://f.test", ref)).toBeNull();
62 });
63 });
test/forge-looks.test.ts +1
@@ -22,6 +22,7 @@ quietLogs();
2222 /** Top-level routes that are not pages, or are not worth a picture, and why. */
2323 const NOT_A_PAGE: Record<string, string> = {
2424 "/home": "the home's old address: a redirect to /, which is pictured",
25 "/desk": "a POST that leaves a note on the desk; the desk is read on the home (/), which is pictured; covered by test/desk.test.ts",
2526 "/pricing": "no picture: the cap of 24 looks is spent; the page is covered by test/pricing-order.test.ts",
2627 "/audit": "no picture: its slot went to /pinned; /audit.csv is its download, covered by test/audit.test.ts",
2728 "/deploy-to": "a form for a forge admin that fills from its link; covered by test/pinned-page.test.ts",
test/job-slices.test.ts +1
@@ -245,6 +245,7 @@ function jobs(): Record<string, () => unknown> {
245245 * The jobs not timed here, each with why. The release keeper's are off unless a cluster turns them on.
246246 */
247247 const UNTIMED: Record<string, string> = {
248 desk: "expires notes past their time: one indexed delete on the desk table every 30 s (actions/desk.ts); the fixture has no notes",
248249 ledger: "walks the cost ledger's hash chain at boot and once a day (#12273): file reads proportional to the ledger, off the request path; the fixture has no ledger",
249250 "full-disk-probe": "one 64 KiB write every 2 s, only while the disk is full; the full-disk test drives probeFull directly",
250251 "reach-asks": "a one-shot timer in actions/ask_host.ts, armed only while a hosted forge has an ask under an hour old: one signed call to its host over the network and a few rows; the fixture has no host",
test/pages-budget.test.ts +1 −1
@@ -51,7 +51,7 @@ const DEFAULT = { statements: 60, git: 8 };
5151 const HEAVIER: Record<string, { statements?: number; git?: number }> = {
5252 "/:owner/:name/issues/:number": { statements: 70 },
5353 "/:owner/:name/next": { statements: 65 }, // +1: the growth line, one read for the week and the planner pause (#12290)
54 "/:owner/:name/pulls/:number": { statements: 113 }, // +1: whether a repository is the forge's own copy, one read of the source setting for the tell box (#12037); +1: the paused sentence, one read of a queued paused run on the pull (#12010); +1: the header Talk count (#10327); +1: the landing line (#10860); +1: whether a reviewer is seated, read only when Require review is off and the pull would otherwise wait on one; the page loads no crew besides (#11666)
54 "/:owner/:name/pulls/:number": { statements: 114 }, // +1: the desk hold on the pull, one read of the notes that link it (#12536); +1: whether a repository is the forge's own copy, one read of the source setting for the tell box (#12037); +1: the paused sentence, one read of a queued paused run on the pull (#12010); +1: the header Talk count (#10327); +1: the landing line (#10860); +1: whether a reviewer is seated, read only when Require review is off and the pull would otherwise wait on one; the page loads no crew besides (#11666)
5555 "/api/v1/asks": { statements: 61 }, // +1: the stopped apps someone asked for, one read of the viewer's archived repositories (#12277)
5656 "/board": { statements: 72 }, // +1: the forge-copy read for the tell box (#12037); +1: the vitals read the database's growth (#12025); +6: the money line (#510) — one settings read, then the month's and the 30 days' meter, storage and ledger reads; constant in the number of apps
5757 "/settings/capacity": { statements: 71 },

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs