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

A card for every #12: the forge's one peek, on every page #16700

Merged opened this

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

Merged

peek-cards → main 0 commits 3 threads · 3 unresolved

  • Merged. peek-cards was merged into main as 68934bd.

Review

Sign in to review this change.
22 files changed +767 −576
docs/design/areas/talk.md +1 −2
@@ -132,8 +132,7 @@ Prior art: Claude and ChatGPT (one centred column, the person's words in a quiet
132132 - `.talk-figures`: the spend and context lines inside the conversation menu.
133133 - `.talk-time`: a centred quiet time before the first turn and wherever the conversation paused 30 minutes or more; the time is said once a group, not under every message (a person's message keeps its time for a screen reader).
134134 - `.talk-display`: Display, at the end of the conversation menu: the person's Talk preferences (spacing, motion, Enter, steps) as one plain form of selects (`core/settings.ts`).
135 - `.talk-peek`: a peek at what a message links to on this forge (an issue, a pull, a repository), a small card placed under the link (above it near the foot of the screen) on hover, focus or a long press (`src/web/talk_peek.ts`); on touch the same card opens through the overlay host as a `.dialog` with `.talk-peek-sheet`.
136 - `.talk-peek-card`, `.talk-peek-kind`, `.talk-peek-title`, `.talk-peek-body`, `.talk-peek-acts`: the card's kind and number with its state, its title, three lines of its body as plain text, and at most two actions (Open; Talk about this for an issue or a repository).
135 - `.peek`, `.peek-card`, `.peek-kind`, `.peek-title`, `.peek-body`, `.peek-acts`, `.peek-sheet`: the forge's card for what a link names (`src/web/peek.ts`, `docs/features/peek.md`), on every page's sheet; in Talk's thread it takes every forge link.
137136 - `.talk-receipt`: a receipt, one calm line of what was done (a check, the verb, the link, the time), and under it Undo where it can be undone; a first-class part of the thread, never mistakable for a confirm or an error.
138137 - `.talk-receipt-line`, `.talk-receipt-acts`: its line and its quiet row of actions (Undo; Reply on the issue).
139138 - `.talk-work-line`: under a receipt that names an issue, what the crew is doing on it now (queued, working for how long, the pull it pushed and its checks, waiting for you, landed), a live region swapped from `/live/talk-work`.
docs/design/size-budget.json +36 −36
@@ -1,78 +1,78 @@
11 {
22 "/": {
3 "js": 23040,
4 "css": 49920
3 "js": 24320,
4 "css": 50432
55 },
66 "/explore": {
7 "js": 22784,
8 "css": 49920
7 "js": 24064,
8 "css": 50432
99 },
1010 "/map": {
11 "js": 30208,
12 "css": 51712
11 "js": 31744,
12 "css": 51968
1313 },
1414 "/:owner/:name": {
15 "js": 39936,
16 "css": 49920
15 "js": 41216,
16 "css": 50432
1717 },
1818 "/changelog": {
19 "js": 28416,
20 "css": 49920
19 "js": 29696,
20 "css": 50432
2121 },
2222 "/:owner/:name/next": {
23 "js": 24576,
24 "css": 50176
23 "js": 25856,
24 "css": 50688
2525 },
2626 "/:owner/:name/space": {
27 "js": 31744,
28 "css": 50944
27 "js": 33024,
28 "css": 51456
2929 },
3030 "/:owner/:name/space.json": {
3131 "js": 0,
3232 "css": 0
3333 },
3434 "/maintenance": {
35 "js": 22784,
36 "css": 49920
35 "js": 24064,
36 "css": 50432
3737 },
3838 "/pricing": {
39 "js": 22784,
40 "css": 49920
39 "js": 24064,
40 "css": 50432
4141 },
4242 "/forges/new": {
43 "js": 22784,
44 "css": 49920
43 "js": 24064,
44 "css": 50432
4545 },
4646 "/claim": {
47 "js": 25600,
48 "css": 49920
47 "js": 27136,
48 "css": 50432
4949 },
5050 "/templates": {
51 "js": 22784,
52 "css": 49920
51 "js": 24064,
52 "css": 50432
5353 },
5454 "/system": {
55 "js": 24576,
56 "css": 49920
55 "js": 25856,
56 "css": 50432
5757 },
5858 "/feed": {
59 "js": 37888,
60 "css": 49920
59 "js": 39168,
60 "css": 50432
6161 },
6262 "/board": {
63 "js": 27648,
64 "css": 49920
63 "js": 28928,
64 "css": 50432
6565 },
6666 "/fleet": {
67 "js": 22784,
68 "css": 49920
67 "js": 24064,
68 "css": 50432
6969 },
7070 "/talk": {
71 "js": 41984,
72 "css": 56064
71 "js": 42496,
72 "css": 56832
7373 },
7474 "/:owner/:name/pulls/:number": {
75 "js": 33280,
76 "css": 49920
75 "js": 34560,
76 "css": 50432
7777 }
7878 }
docs/features/peek.md added +15
@@ -0,0 +1,15 @@
1 ---
2 topic: Getting around: keys, the palette and search
3 row: A card for every #12
4 ---
5 # A card for every #12 (#15734)
6
7 A link that reads `#12` or `owner/name#12`, in a comment, a pull's body, a receipt, the home feed or anywhere else the forge draws one, shows a small card on intent: after the pointer rests on it for 400 ms, at once on keyboard focus, and on touch after a 500 ms long press, as a sheet through the overlay host. A tap or a click still follows the link, and the click that ends a long press is the press's own. In Talk's thread every link to an issue, a pull or a repository on this forge peeks, whatever its words. A row that already shows its title beside the link (an issue list, a board) gets no card.
8
9 The card says the reference and its state in a word (Open, Merged, Closed; Draft; how its checks went), the title, who opened it and when, and the first three lines of its body as plain text: fenced code, HTML, comments and scripts taken out, links and images down to their words, the marks of headings, lists, quotes, tables and emphasis dropped. A signed-in reader also gets Open and Talk about this. One card at a time; each link is asked once a page. Escape closes it and puts focus back on the link; while it is open the link is described by it (`aria-describedby`), and focus is never held inside it.
10
11 It is `GET /peek?href=<rooted path>` (`src/web/peek.ts`), read exactly as the link is: a repository the viewer cannot read (a signed-out visitor on a private one included), a sealed issue they may not see, a number that is not there, a pull asked as `/pulls/N` that is an issue, or any other path answers the same 404, byte for byte. Every answer is `Cache-Control: private, no-store` and `Vary: Cookie`, so no shared cache gives one viewer's card to another. A card is at most five statements. The page side is in the shell script, about 1.4 KB gzip on every page.
12
13 Not here: cards for commits, people, or code and diff text; a card that updates while open; references to other forges. **In the terminal** there is no hover: the issue and repository screens open what a reference names.
14
15 Proof: `test/peek.test.ts` (the card, the one 404, the statement count, the plain lines, and in Chromium the hover, focus, Escape, long press and a list row with none).
docs/features/talk.md +1 −3
@@ -258,9 +258,7 @@ Four preferences of the person's own, at the end of the conversation menu (⋯
258258
259259 ## Peek (#15734)
260260
261 A link in a message to an issue, a pull or a repository on this forge peeks: on a pointer device a small card after a 300 ms hover (it leaves 150 ms after the pointer does, and stays while the pointer is on it), on keyboard focus, and on touch after a 500 ms long press, as a dialog through the overlay host. A tap or a click still follows the link. Escape or a press outside closes it; the link is described by the card (`aria-describedby`), and focus is never trapped by the hover card.
262
263 The card is `GET /talk/peek?href=<rooted path>` (`src/web/talk_peek.ts`), signed in only: the kind and number with its state in a word and an icon (Open, Closed, Merged; for a pull its checks in words), the title, what the crew is doing on it now, in the same sentence as a receipt's work line ("marin has been working on it for 4 min."), the first lines of its body as escaped plain text (never Markdown, never a link), when it last changed, and at most two actions (Open, and Talk about this, which opens Talk with that subject). Read exactly as the link is: a repository the person cannot read, a sealed issue they may not see, a number that is not there, a pull asked as an issue, or any other path answers not found, and no card appears. Cached by the browser for 5 seconds. Proof: `test/talk-peek.test.ts`.
261 A link in a message to an issue, a pull or a repository on this forge peeks, whatever its words: the forge's own card (`docs/features/peek.md`, `GET /peek`), which elsewhere is for bare `#12` references only.
264262
265263 **In the terminal** there is no hover: a conversation names the same links as `owner/repo#12` and `owner/repo`, which the terminal's issue and repository screens open.
266264
src/core/reserved.ts +1
@@ -145,6 +145,7 @@ export const SYSTEM_NAMES: readonly string[] = [
145145 "offline",
146146 "tell",
147147 "talk",
148 "peek",
148149 "notes",
149150 "next",
150151 "templates",
src/http/marks/peek.json added +4
@@ -0,0 +1,4 @@
1 {
2 "head": "/peek",
3 "mark": "open"
4 }
src/http/server.ts +3 −2
@@ -181,7 +181,8 @@ import {
181181 import { talkBuild, talkPublish, talkRestore } from "../web/talk_build.ts";
182182 import { talkModel } from "../web/talk_model.ts";
183183 import { talkAct, talkAgainSend, talkArchive, talkConfirm, talkDisplaySave, talkDownload, talkNew, talkPin, talkQueueCancel, talkRename, talkSend, talkUndo, talkStream, talkView, talkWall } from "../web/pages/talk.ts";
184 import { liveTalkCrew, liveTalkWork, talkPeek } from "../web/talk_peek.ts";
184 import { liveTalkCrew, liveTalkWork } from "../web/talk_lines.ts";
185 import { peekRoute } from "../web/peek.ts";
185186 import {
186187 recoverFinish,
187188 recoverOptions,
@@ -1277,7 +1278,7 @@ export function buildRouter(): Router<Handler> {
12771278 router.add("POST", "/talk", talkSend);
12781279 router.add("POST", "/talk/wall", talkWall);
12791280 router.add("GET", "/talk/stream", talkStream);
1280 router.add("GET", "/talk/peek", talkPeek);
1281 router.add("GET", "/peek", peekRoute);
12811282 router.add("POST", "/talk/again/:how", talkAgainSend);
12821283 router.add("POST", "/talk/queue/:id/cancel", talkQueueCancel);
12831284 router.add("POST", "/talk/confirm/:id", talkConfirm);
src/web/client.ts +2 −1
@@ -23,6 +23,7 @@ import { overlayHostJs } from "./overlay_host.ts";
2323 import { paletteHelpersJs } from "./palette.ts";
2424 import { MEDIA_PLAY_JS } from "./render/player.ts";
2525 import { NOT_TOLD_WORDS } from "../actions/tell_words.ts";
26 import { peekJs } from "./peek_client.ts";
2627
2728 /**
2829 * The device-code page's only enhancement: listen on the page's own stream
@@ -2387,7 +2388,7 @@ const shellCore = /* js */ `
23872388 `;
23882389
23892390 /** The shell and the one script that makes actions answer at once (`act_now.ts`). */
2390 export const shellJs = `${shellCore}\n${actNowJs}\n${pickJs}\n${foldJs}\n${FORM_BUSY_JS}\n${liveTimeJs}`;
2391 export const shellJs = `${shellCore}\n${actNowJs}\n${pickJs}\n${foldJs}\n${FORM_BUSY_JS}\n${liveTimeJs}\n${peekJs}`;
23912392
23922393 /**
23932394 * Live regions. A page marks the parts of itself that change while it is
src/web/pages/talk.ts +2 −2
@@ -79,7 +79,7 @@ import { agentHtml, liveHtml, voiceCss, voiceOf, type Voice } from "../talk_part
7979 import { badge, btn, icon, iconBtn, menu, meter, row, time } from "../ui.ts";
8080 import { inlineIcons } from "../icons.ts";
8181 import { DISPLAY_NAMES, setTalkDisplay, TALK_DISPLAY, talkDisplay, type TalkDisplay } from "../../core/settings.ts";
82 import { peekCss, workLineHtml } from "../talk_peek.ts";
82 import { workLineHtml } from "../talk_lines.ts";
8383 import { conversationPulls, paneCrew, receiptLines, type WorkLine } from "../../core/talk_work.ts";
8484 import { paneAtOf, paneChoice, paneOffer, paneQuery, workspaceOf } from "../../actions/talk_workspace.ts";
8585 import { buildCss, chosenTemplate, panelFor, templateChips } from "../talk_build.ts";
@@ -695,7 +695,7 @@ async function talkPage(ctx: Ctx, conversation: Conversation, before0: string |
695695 </div>
696696 ${split ? html`<div class="talk-work">${panel}${pane.html}</div>` : null}
697697 </div>`;
698 return page({ ctx, title: conversation.title === "" ? "Talk" : `${conversation.title} · Talk`, body, styleCss: talkCss + peekCss + paneCss + codePaneCss + (panel === null ? "" : buildCss) + voiceCss, scriptJs: `${talkJs}\n${liveRegionsJs}\n${ownTokenJs}`, description: "Talk to the forge.", wide: true, ...(!split ? {} : { frameSrc: frames }) });
698 return page({ ctx, title: conversation.title === "" ? "Talk" : `${conversation.title} · Talk`, body, styleCss: talkCss + paneCss + codePaneCss + (panel === null ? "" : buildCss) + voiceCss, scriptJs: `${talkJs}\n${liveRegionsJs}\n${ownTokenJs}`, description: "Talk to the forge.", wide: true, ...(!split ? {} : { frameSrc: frames }) });
699699 }
700700
701701 /**
src/web/pages/talk_client.ts +2 −58
@@ -31,10 +31,8 @@
3131 * the stored reply that takes the live block's place); the live block's new blocks only fade.
3232 * None under prefers-reduced-motion, or when the person chose reduced (Display). Opacity and
3333 * transform only, so nothing on screen moves.
34 * - A link to an issue, a pull or a repository on this forge peeks (`web/talk_peek.ts`): a card after
35 * a 300 ms hover (150 ms to leave, kept while the pointer is on it), on keyboard focus, or on a
36 * 500 ms long press on touch, as a sheet at the foot of the screen; never on a tap or a click, which
37 * still follow the link. Escape or a press outside closes it; the link is described by the card.
34 * - A link to an issue, a pull or a repository on this forge peeks: the shell's card
35 * (`web/peek.ts`), which in the thread takes every such link, not only a bare `#12`.
3836 * - The conversation's head slides away while the reader scrolls down and comes back on the way up.
3937 * - Copy buttons are drawn by the script, not the server: without the script
4038 * they would do nothing.
@@ -1207,60 +1205,6 @@ ${dictateJs}
12071205 } catch (_) {}
12081206 };
12091207 document.addEventListener("click", (e) => { if (e.target.closest && e.target.closest(".talk-reload")) reframe(); });
1210 const PEEK = /^\\/[^/]+\\/[^/]+(\\/(issues|pulls)\\/\\d+)?\\/?$/;
1211 const peekOf = (t) => { const a = t && t.closest && t.closest(".talk-log a[href^='/']"); return a && !a.closest(".talk-peek, .talk-acts, .talk-meta") && PEEK.test(a.getAttribute("href")) ? a : null; };
1212 let peek = null, peekAt = null, peekIn = 0, peekOut = 0, pressT = 0, pressed = null;
1213 const unpeek = () => { clearTimeout(peekIn); if (peek) peek.remove(); if (peekAt) peekAt.removeAttribute("aria-describedby"); peek = peekAt = null; };
1214 const showPeek = async (a, sheet) => {
1215 peekAt = a;
1216 try {
1217 const res = await fetch("/talk/peek?href=" + encodeURIComponent(a.getAttribute("href")));
1218 const body = res.ok ? await res.text() : "";
1219 if (!body || peekAt !== a) return;
1220 if (peek) peek.remove();
1221 if (sheet && window.forgeOverlay) {
1222 const d = Object.assign(document.createElement("dialog"), { className: "dialog talk-peek-sheet", innerHTML: '<div class="dialog-body">' + body + "</div>" });
1223 d.setAttribute("aria-label", a.textContent);
1224 document.body.append(d);
1225 d.addEventListener("close", () => { d.remove(); pressed = null; });
1226 window.forgeOverlay.open(d, { opener: a, name: "peek" });
1227 peekAt = null;
1228 return;
1229 }
1230 peek = Object.assign(document.createElement("div"), { className: "talk-peek", id: "talk-peek", innerHTML: body });
1231 peek.setAttribute("role", "region");
1232 peek.setAttribute("aria-label", a.textContent);
1233 document.body.append(peek);
1234 {
1235 // Below the link while it fits on screen (over the composer at worst, never over what is
1236 // being read above it), else above; held inside the screen by the stylesheet, so no width is read.
1237 const r = a.getBoundingClientRect(), h = peek.offsetHeight, vh = window.innerHeight;
1238 const head = document.querySelector(".topbar"), top = (head ? head.getBoundingClientRect().bottom : 0) + 8;
1239 const y = r.bottom + 6 + h <= vh - 8 ? r.bottom + 6 : r.top - h - 6;
1240 peek.style.top = Math.max(top, Math.min(y, vh - h - 8)) + window.scrollY + "px";
1241 peek.style.left = "clamp(16px, " + (r.left + window.scrollX) + "px, calc(100% - min(22rem, 100vw - 32px) - 16px))";
1242 }
1243 a.setAttribute("aria-describedby", "talk-peek");
1244 peek.addEventListener("pointerenter", () => clearTimeout(peekOut));
1245 peek.addEventListener("pointerleave", () => { peekOut = setTimeout(unpeek, 150); });
1246 } catch (_) {}
1247 };
1248 log.addEventListener("pointerover", (e) => { const a = e.pointerType === "mouse" && peekOf(e.target); if (!a) return; clearTimeout(peekOut); if (a !== peekAt) { clearTimeout(peekIn); peekIn = setTimeout(() => showPeek(a), 300); } });
1249 log.addEventListener("pointerout", (e) => { if (peekOf(e.target)) { clearTimeout(peekIn); peekOut = setTimeout(unpeek, 150); } });
1250 log.addEventListener("focusin", (e) => { const a = peekOf(e.target); if (a && a.matches(":focus-visible")) showPeek(a); });
1251 log.addEventListener("focusout", (e) => { if (peekOf(e.target)) peekOut = setTimeout(unpeek, 150); });
1252 log.addEventListener("touchstart", (e) => { const a = peekOf(e.target); if (a) pressT = setTimeout(() => { pressed = a; showPeek(a, true); }, 500); }, { passive: true });
1253 // The click a long press swallows comes at once or never (a callout, a closed sheet): the flag
1254 // never outlives the touch, so the next plain tap on the link still follows it.
1255 const unpress = () => { clearTimeout(pressT); pressed = null; };
1256 log.addEventListener("touchend", () => { clearTimeout(pressT); if (pressed) setTimeout(unpress, 400); });
1257 log.addEventListener("touchmove", unpress, { passive: true });
1258 log.addEventListener("touchcancel", unpress);
1259 log.addEventListener("pointercancel", unpress);
1260 window.addEventListener("scroll", unpress, { passive: true });
1261 log.addEventListener("click", (e) => { if (pressed && e.target.closest("a") === pressed) { e.preventDefault(); pressed = null; } }, true);
1262 document.addEventListener("pointerdown", (e) => { if (peek && !peek.contains(e.target) && !peekOf(e.target)) unpeek(); });
1263 document.addEventListener("keydown", (e) => { if (e.key === "Escape" && peek) { e.preventDefault(); e.stopImmediatePropagation(); unpeek(); } }, true);
12641208 document.addEventListener("click", async (e) => {
12651209 const a = e.target.closest("[data-shell] :is(.talk-tabs, .talk-pane nav.seg) a:not(.talk-back)"), shell = a && a.closest("[data-shell]");
12661210 if (!a || e.metaKey || e.ctrlKey || e.shiftKey) return;
src/web/pages/talk_preview.ts +1 −1
@@ -22,7 +22,7 @@ import { mayReadRunLog, mayReadRuns } from "../../actions/runs.ts";
2222 import { getAppByRepo } from "../../core/apps.ts";
2323 import { appsRuntime } from "../../apps/runtime.ts";
2424 import { originOf } from "../../actions/talk_workspace.ts";
25 import { workLineHtml } from "../talk_peek.ts";
25 import { workLineHtml } from "../talk_lines.ts";
2626 import type { Ctx } from "../../http/context.ts";
2727 import { html, raw, type Html } from "../html.ts";
2828 import { emptyLine } from "../empty_words.ts";
src/web/peek.ts added +159
@@ -0,0 +1,159 @@
1 /**
2 * The peek (#15734, forge-wide since the owner's "hovers that are informative and not noise"): a
3 * small card for an issue or a pull a link names, shown on intent (about 400 ms of hover, keyboard
4 * focus, or a long press on touch). On any page it is for a bare reference, a link that reads `#12`
5 * or `owner/name#12`, so a row that already shows its title gets none; in Talk's thread every link
6 * to an issue, a pull or a repository on this forge peeks.
7 *
8 * `GET /peek?href=/owner/name/issues/12` answers the card: the reference and its state in a word
9 * (Open, Merged, Closed; Draft; how its checks went), the title, who opened it and when, and the
10 * first lines of its body as plain text (Markdown, HTML and code fences taken out). Anything the
11 * viewer may not read, a signed-out visitor on a private repository included, answers the same
12 * 404, byte for byte, as a number that does not exist. Every answer is private to the viewer and
13 * varies on the cookie, so no shared cache hands one person's card to another.
14 *
15 * The body is someone else's words: escaped plain text, never Markdown, never a link.
16 */
17
18 import type { Database } from "bun:sqlite";
19 import type { Ctx } from "../http/context.ts";
20 import { getIssue } from "../core/issues.ts";
21 import { canRead, getRepo } from "../core/repos.ts";
22 import { mayView } from "../core/sealed.ts";
23 import type { User } from "../core/users.ts";
24 import { notePhase, takeSessionTime } from "../core/route_timing.ts";
25 import { html, type Html } from "./html.ts";
26 import { icon, time } from "./ui.ts";
27 import { inlineIcons } from "./icons.ts";
28 import { PEEK } from "./peek_client.ts";
29
30 /** How many lines of a body the card shows, and how many characters at most. */
31 const LINES_SHOWN = 3;
32 const BODY_SHOWN = 240;
33
34 /** The card's words, in one place. */
35 const PEEK_WORDS = {
36 open: "Open",
37 talk: "Talk about this",
38 merged: "Merged",
39 closed: "Closed",
40 draft: "Draft",
41 repository: "Repository",
42 opened: "Opened by",
43 checksOk: "checks passed",
44 checksFailed: "checks failed",
45 checksRunning: "checks running",
46 } as const;
47
48 /**
49 * The first lines of a Markdown body as plain text: fenced code and HTML taken out, links and
50 * images down to their words, the marks of headings, lists, quotes, tables and emphasis dropped.
51 */
52 export function plainLines(body: string, lines = LINES_SHOWN, chars = BODY_SHOWN): string {
53 const kept: string[] = [];

High (denial of service): the comment and script strip runs over the whole body, and an unclosed <!-- repeated makes the lazy scan quadratic. /peek is open to signed-out readers of public repos. Cap the input first (body.slice(0, 4096)) and test a 64 KB <!-- body for speed.

54 let fence: string | null = null;
55 // A comment, a script or a style says nothing a reader sees: taken out whole, words and all.
56 const shown = body.replace(/<!--[\s\S]*?-->/g, "").replace(/<(script|style)\b[\s\S]*?(<\/\1\s*>|$)/gi, " ");
57 for (const raw of shown.split(/\r?\n/)) {
58 const opens = /^\s*(`{3,}|~{3,})/.exec(raw);
59 if (fence !== null) {
60 if (opens !== null && opens[1]!.startsWith(fence)) fence = null;
61 continue;
62 }
63 if (opens !== null) {
64 fence = opens[1]!;
65 continue;
66 }
67 const line = raw
68 .replace(/<[^>]*>/g, " ")
69 .replace(/!?\[([^\]]*)\]\((?:[^()]|\([^()]*\))*\)/g, "$1")
70 .replace(/`([^`]*)`/g, "$1")
71 .replace(/^\s{0,3}(#{1,6}\s+|>\s?|[-*+]\s+(\[[ xX]\]\s+)?|\d+[.)]\s+)/, "")
72 .replace(/^\s*\|?(\s*:?-{3,}:?\s*\|)+\s*:?-*:?\s*$/, "")
73 .replace(/\|/g, " ")
74 .replace(/(\*\*|__|~~|\*|_)(?=\S)([^*_~]*?\S)\1/g, "$2")
75 .replace(/\s+/g, " ")
76 .trim();
77 if (line !== "") kept.push(line);
78 if (kept.length === lines) break;
79 }
80 const text = kept.join("\n");
81 return text.length > chars ? `${text.slice(0, chars).trimEnd()}…` : text;
82 }
83
84 /**
85 * The card for `href` as `viewer` reads it, or undefined for anything they may not read and
86 * anything that is not there, alike. At most five statements.
87 */
88 export function peekCard(db: Database, viewer: User | undefined, href: string): Html | undefined {
89 const m = PEEK.exec(href);
90 if (m === null) return undefined;
91 const [, owner = "", name = "", kind, number] = m;
92 const repo = getRepo(db, owner, name);
93 if (repo === undefined || !canRead(db, repo, viewer)) return undefined;
94 const full = `${repo.ownerName}/${repo.name}`;
95 const acts = (path: string, about: string): Html | null =>
96 viewer === undefined
97 ? null
98 : html`<div class="peek-acts">
99 <a class="btn" data-size="sm" href="${path}">${PEEK_WORDS.open}</a
100 ><a class="btn" data-size="sm" href="/talk?about=${encodeURIComponent(about)}">${PEEK_WORDS.talk}</a>
101 </div>`;
102 if (kind === undefined)
103 return html`<p class="peek-kind small muted">${icon("repo")} ${PEEK_WORDS.repository}</p>
104 <p class="peek-title">${full}</p>
105 ${repo.description === "" ? null : html`<p class="peek-body small">${plainLines(repo.description)}</p>`} ${acts(`/${full}`, full)}`;
106 const issue = getIssue(db, repo.id, Number(number));
107 // `/issues/N` names a pull as well (the page answers both); `/pulls/N` names only a pull.
108 if (issue === undefined || !mayView(db, repo, issue, viewer) || (kind === "pulls" && issue.kind !== "pull")) return undefined;
109 const pull =
110 issue.kind === "pull"
111 ? db
112 .query<
113 { merged_at: string | null; draft_run: string | null; check: string | null },
114 [string]
115 >("SELECT merged_at, draft_run, (SELECT state FROM run WHERE issue_id = ?1 AND kind = 'check' ORDER BY id DESC LIMIT 1) AS \"check\" FROM pull WHERE issue_id = ?1")
116 .get(issue.id)
117 : null;
118 const state = pull?.merged_at
119 ? (["merge", PEEK_WORDS.merged] as const)
120 : issue.state === "open"
121 ? ([issue.kind === "pull" ? "pull" : "issue", PEEK_WORDS.open] as const)
122 : (["issueClosed", PEEK_WORDS.closed] as const);
123 const check = pull?.check ?? null;
124 const checks =
125 check === null ? null : check === "ok" ? PEEK_WORDS.checksOk : check === "failed" ? PEEK_WORDS.checksFailed : PEEK_WORDS.checksRunning;
126 const draft = pull !== null && pull !== undefined && pull.draft_run !== null && issue.state === "open";
127 const body = plainLines(issue.body);
128 const path = `/${full}/${issue.kind === "pull" ? "pulls" : "issues"}/${issue.number}`;
129 return html`<p class="peek-kind small muted">
130 ${icon(state[0])} ${full}#${String(issue.number)} ·
131 ${state[1]}${draft ? ` · ${PEEK_WORDS.draft}` : null}${checks === null ? null : ` · ${checks}`}
132 </p>
133 <p class="peek-title">${issue.title}</p>
134 <p class="small muted">${PEEK_WORDS.opened} ${issue.authorName} ${time(issue.createdAt)}</p>
135 ${body === "" ? null : html`<p class="peek-body small">${body}</p>`} ${acts(path, `${full}#${issue.number}`)}`;
136 }
137
138 /** Every answer is the viewer's own: never stored by a shared cache, and keyed on the cookie. */
139 const PRIVATE = { "cache-control": "private, no-store", vary: "Cookie" } as const;
140
141 /** The one not found: a missing number and one the viewer may not read are the same bytes. */
142 const notFound = (): Response =>
143 new Response("not found", { status: 404, headers: { "content-type": "text/plain; charset=utf-8", ...PRIVATE } });
144
145 // GET /peek?href=<a rooted path on this forge>
146 export function peekRoute(ctx: Ctx): Response {
147 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
148 const rendering = performance.now();
149 const card = peekCard(ctx.app.db, ctx.auth.user, ctx.url.searchParams.get("href") ?? "");
150 // A fragment lands in a page whose sprite it does not know: its icons are drawn inline.
151 const answer =
152 card === undefined
153 ? notFound()
154 : new Response(inlineIcons(html`<div class="peek-card">${card}</div>`.text), {
155 headers: { "content-type": "text/html; charset=utf-8", ...PRIVATE },
156 });
157 notePhase(ctx.request, "render", performance.now() - rendering);
158 return answer;
159 }
src/web/peek_client.ts added +109
@@ -0,0 +1,109 @@
1 /**
2 * The peek's page side (`web/peek.ts` answers the card): the paths a card is for, the card's styles
3 * on every page's sheet, and the script in the shell that asks for it. Static: nothing here reads
4 * the forge's data, so the stylesheet and the shell build without it.
5 */
6
7 /** The paths a peek reads: a repository, or one of its issues or pulls. */
8 export const PEEK = /^\/([A-Za-z0-9][A-Za-z0-9_.-]{0,63})\/([A-Za-z0-9][A-Za-z0-9_.-]{0,99})(?:\/(issues|pulls)\/([1-9]\d{0,8}))?\/?$/;
9
10 /** The card's styles, on every page's sheet. Spacing is the scale. */
11 export const peekCss = /* css */ `
12 .peek { position: absolute; width: min(22rem, calc(100vw - 32px)); padding: 12px; border: 1px solid var(--border); border-radius: var(--radius-lg); background: var(--card); box-shadow: var(--shadow-2); transform-origin: top left; transition: opacity var(--dur-2) var(--ease), transform var(--dur-2) var(--ease); }
13 .peek[data-side="above"] { transform-origin: bottom left; }
14 .peek[data-warm] { transition: none; }
15 @starting-style { .peek { opacity: 0; transform: scale(.95); } }
16 .peek-card { display: grid; gap: 4px; }
outdated

Design principle 7 and the Both-doors rule: the card is a pile of facts, and the pull ships no terminal screen. The doc only says that in the terminal there is no hover. Say plainly in docs/features/peek.md that the issue screen already shows these facts as rows, or use the existing dl row for state and opener rather than loose paragraphs.

17 .peek-card p { margin: 0; }
outdated

Design principle 6: .peek adds border: 1px solid var(--border), a box around a thing. The card it replaces had none, only the shadow. Drop the border and keep the shadow.

18 .peek-kind { display: flex; align-items: center; gap: 6px; }
19 .peek-title { font-weight: 600; overflow-wrap: anywhere; }
20 .peek-body { color: var(--fg); overflow-wrap: anywhere; white-space: pre-line; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }
21 .peek-acts { display: flex; gap: 8px; margin-top: 4px; }
22 .peek-acts .btn { position: relative; }
23 .peek-acts .btn::after { content: ""; position: absolute; inset: -6px -2px; }
24 .peek-sheet .dialog-body { padding: 16px; }
25 @media (prefers-reduced-motion: reduce) { .peek { transition-property: opacity; } }
26 `;
27
28 /**
29 * The page side, part of the shell. A card opens after the pointer rests on a link for 400 ms (at
30 * once while one is open or was within 600 ms, and then with no enter: the next of a row reads as
31 * one card moving), at
32 * once on keyboard focus, or as a sheet after a 500 ms press on touch (the tap that follows a long
33 * press is the press's own, so it does not also follow the link; a plain tap always does). One card
34 * at a time, each href asked once a page. Escape closes it and puts focus back on the link; the
35 * card is not a trap, and while it is open the link is described by it. Focus a press gave (a
36 * click) is not a keyboard asking, so it opens nothing; the card sits below the link while it fits,
37 * else above. No comment rides inside: these bytes are on every page.
38 */
39 export const peekJs = /* js */ `
40 (function () {
41 if (window.forgePeek) return;
42 window.forgePeek = true;
43 var PEEK = ${String(PEEK)};
44 var BARE = /^(?:[\\w.-]+\\/[\\w.-]+)?#\\d+$/;
45 var ISSUE = /\\/(issues|pulls)\\/\\d+\\/?$/;
46 var of = function (t) {
47 var a = t && t.closest && t.closest("a[href^='/']");
48 if (!a || a.closest(".peek, .talk-acts, .talk-meta")) return null;
49 var href = a.getAttribute("href");
50 if (!PEEK.test(href)) return null;
51 if (a.closest(".talk-log")) return a;
52 return ISSUE.test(href) && BARE.test(a.textContent.trim()) ? a : null;
53 };
54 var kept = new Map(), card = null, at = null, inT = 0, outT = 0, pressT = 0, pressed = null, shutAt = -1e9;
55 var warm = function () { return !!card || performance.now() - shutAt < 600; };
56 var close = function () { clearTimeout(inT); if (card) { card.remove(); shutAt = performance.now(); } if (at) at.removeAttribute("aria-describedby"); card = at = null; };
57 var ask = function (href) {
58 if (!kept.has(href)) kept.set(href, fetch("/peek?href=" + encodeURIComponent(href), { credentials: "same-origin" }).then(function (r) { return r.ok ? r.text() : ""; }).catch(function () { kept.delete(href); return ""; }));
59 return kept.get(href);
60 };
61 var show = function (a, sheet) {
62 at = a;
63 ask(a.getAttribute("href")).then(function (body) {
64 if (!body || at !== a) return;
65 var hot = warm();
66 if (card) card.remove();
67 if (sheet && window.forgeOverlay) {
68 var d = Object.assign(document.createElement("dialog"), { className: "dialog peek-sheet", innerHTML: '<div class="dialog-body">' + body + "</div>" });
69 d.setAttribute("aria-label", a.textContent);
70 document.body.append(d);
71 d.addEventListener("close", function () { d.remove(); pressed = null; });
72 window.forgeOverlay.open(d, { opener: a, name: "peek" });
73 at = null;
74 return;
75 }
76 card = Object.assign(document.createElement("div"), { className: "peek", id: "peek", innerHTML: body });
77 card.setAttribute("role", "region");
78 if (hot) card.setAttribute("data-warm", "");
79 card.setAttribute("aria-label", a.textContent);
80 document.body.append(card);
81 var r = a.getBoundingClientRect(), h = card.offsetHeight, vh = window.innerHeight;
82 var bar = document.querySelector(".topbar"), top = (bar ? bar.getBoundingClientRect().bottom : 0) + 8;
83 var below = r.bottom + 6 + h <= vh - 8, y = below ? r.bottom + 6 : r.top - h - 6;
84 if (!below) card.dataset.side = "above";
85 card.style.top = Math.max(top, Math.min(y, vh - h - 8)) + window.scrollY + "px";
86 card.style.left = "clamp(16px, " + (r.left + window.scrollX) + "px, calc(100% - min(22rem, 100vw - 32px) - 16px))";
87 a.setAttribute("aria-describedby", "peek");
88 card.addEventListener("pointerenter", function () { clearTimeout(outT); });
89 card.addEventListener("pointerleave", function () { outT = setTimeout(close, 150); });
90 });
91 };
92 document.addEventListener("pointerover", function (e) { var a = e.pointerType === "mouse" && of(e.target); if (!a) return; clearTimeout(outT); if (a !== at) { clearTimeout(inT); inT = setTimeout(function () { show(a); }, warm() ? 0 : 400); } });
93 document.addEventListener("pointerout", function (e) { if (of(e.target)) { clearTimeout(inT); outT = setTimeout(close, 150); } });
94 var downAt = -1e9;
95 document.addEventListener("pointerdown", function () { downAt = performance.now(); }, true);
96 document.addEventListener("focusin", function (e) { var a = of(e.target); if (a && performance.now() - downAt > 300) { clearTimeout(outT); show(a); } });
97 document.addEventListener("focusout", function (e) { if (of(e.target)) outT = setTimeout(close, 150); });
98 document.addEventListener("touchstart", function (e) { var a = of(e.target); if (a) pressT = setTimeout(function () { pressed = a; show(a, true); }, 500); }, { passive: true });
99 var unpress = function () { clearTimeout(pressT); pressed = null; };
100 document.addEventListener("touchend", function () { clearTimeout(pressT); if (pressed) setTimeout(unpress, 400); });
101 document.addEventListener("touchmove", unpress, { passive: true });
102 document.addEventListener("touchcancel", unpress);
103 document.addEventListener("pointercancel", unpress);
104 window.addEventListener("scroll", unpress, { passive: true });
105 document.addEventListener("click", function (e) { if (pressed && e.target.closest && e.target.closest("a") === pressed) { e.preventDefault(); pressed = null; } }, true);
106 document.addEventListener("pointerdown", function (e) { if (card && !card.contains(e.target) && !of(e.target)) close(); });
107 document.addEventListener("keydown", function (e) { if (e.key === "Escape" && card) { var a = at; e.preventDefault(); e.stopImmediatePropagation(); close(); if (a) a.focus(); } }, true);
108 })();
109 `;
src/web/style.ts +2
@@ -33,6 +33,7 @@ import { gcodeCss } from "./render/gcode-css.ts";
3333 import { pcdCss } from "./render/pcd-css.ts";
3434 import { model3dCss } from "./render/model3d-css.ts";
3535 import { pickCss } from "./pick.ts";
36 import { peekCss } from "./peek_client.ts";
3637 import { studioCss } from "./studio/style.ts";
3738
3839 export const css = [
@@ -52,4 +53,5 @@ export const css = [
5253 pcdCss,
5354 utilities,
5455 pickCss,
56 peekCss,
5557 ].join("\n");
src/web/talk_lines.ts added +66
@@ -0,0 +1,66 @@
1 /**
2 * Talk's live lines: a receipt's work line (`GET /live/talk-work`, swapped in place as the issue
3 * moves) and the crew's one line (`GET /live/talk-crew`), each read as the page it stands for is.
4 * The peek at what a message links to is the forge's own (`web/peek.ts`).
5 */
6
7 import type { Ctx } from "../http/context.ts";
8 import { getIssue } from "../core/issues.ts";
9 import { canRead, getRepo } from "../core/repos.ts";
10 import { mayView } from "../core/sealed.ts";
11 import { html, type Html } from "./html.ts";
12 import { btn, time } from "./ui.ts";
13 import { notePhase, takeSessionTime } from "../core/route_timing.ts";
14 import { fragment } from "./layout.ts";
15 import { liveCrewRows } from "../actions/crew_now.ts";
16 import { crewLine } from "./crew_now.ts";
17 import { FOR_MINUTES, workLineFor, type WorkLine } from "../core/talk_work.ts";
18 import { PEEK } from "./peek_client.ts";
19
20 // GET /live/talk-work?href=/owner/name/issues/N&id=w-<turn> — a receipt's work line alone, read as
21 // the issue's own page is; the live client swaps it in place.
22 export function liveTalkWork(ctx: Ctx): Response {
23 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
24 const rendering = performance.now();
25 const answer = workFragment(ctx);
26 notePhase(ctx.request, "render", performance.now() - rendering);
27 return answer;
28 }
29
30 function workFragment(ctx: Ctx): Response {
31 const m = PEEK.exec(ctx.url.searchParams.get("href") ?? "");
32 const id = ctx.url.searchParams.get("id") ?? "";
33 if (ctx.auth.user === undefined || m === null || m[3] !== "issues" || !/^w-[0-9a-z]{1,40}$/.test(id)) return fragment(html``, { status: 404 });
34 const repo = getRepo(ctx.app.db, m[1] ?? "", m[2] ?? "");
35 const issue = repo === undefined || !canRead(ctx.app.db, repo, ctx.auth.user) ? undefined : getIssue(ctx.app.db, repo.id, Number(m[4]));
36 if (repo === undefined || issue === undefined || !mayView(ctx.app.db, repo, issue, ctx.auth.user)) return fragment(html``, { status: 404 });
37 return fragment(html`<div class="talk-work-line small muted" id="${id}">${workLineHtml(workLineFor(ctx.app.db, ctx.app.config.dataDir, issue, Date.now(), ctx.auth.user))}</div>`, { request: ctx.request });
38 }
39
40 // GET /live/talk-crew — the crew's one line on Talk, empty when it is idle.
41 export function liveTalkCrew(ctx: Ctx): Response {
42 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
43 const rendering = performance.now();
44 const rows = ctx.auth.user === undefined ? undefined : liveCrewRows(ctx, ctx.auth.user);
45 const answer = rows === undefined ? fragment(html``, { status: 404 }) : fragment(html`<p class="talk-crew small muted" id="talk-crew">${rows.length === 0 ? null : crewLine(rows)}</p>`, { request: ctx.request });
46 notePhase(ctx.request, "render", performance.now() - rendering);
47 return answer;
48 }
49
50 /**
51 * A work line's words, and the control that changes what it waits on as a link; when the access
52 * wall holds its pull, the two answers as forms that post to Talk's own `/talk/wall`, which work
53 * without the script.
54 */
55 export const workLineHtml = (l: WorkLine): Html =>
56 html`${l.since === undefined ? l.says : html`${l.says.replace(FOR_MINUTES, "")} for ${time(l.since, { count: "elapsed" })}.`}${l.change === undefined ? null : html` <a href="${l.change.href}">${l.change.words}</a>`}${l.wall === undefined ? null : wallAnswers(l.wall)}`;
57
58 /** "Allow it" and "Send it back", each its own form: the answer is in the form, never a query. */
59 const wallAnswers = (w: { readonly repo: string; readonly number: number }): Html => {
60 const form = (answer: "allow" | "send_back", words: string, variant: "primary" | "ghost") =>
61 html`<form method="post" action="/talk/wall" class="inline-form">
62 <input type="hidden" name="repo" value="${w.repo}" /><input type="hidden" name="number" value="${String(w.number)}" /><input type="hidden" name="answer" value="${answer}" />
63 ${btn(words, { size: "sm", variant })}
64 </form>`;
65 return html`<span class="bar mt" data-wall-answers>${form("allow", "Allow it", "primary")}${form("send_back", "Send it back", "ghost")}</span>`;
66 };
src/web/talk_peek.ts deleted −225
@@ -1,225 +0,0 @@
1 /**
2 * A peek at a thing a Talk message links to (#15734): `GET /talk/peek?href=/owner/name/issues/3`
3 * answers a small card the page shows on hover, focus or a long press: the kind and number, the
4 * title, the state in a word, who it is assigned to and whether the crew works on it now, the first
5 * lines of its body as plain text, when it last changed, and at most two safe actions. An issue,
6 * a pull or a repository; anything else, and anything the viewer cannot read, answers not found
7 * exactly as the link itself would, so no card says what a page would not.
8 *
9 * The body is someone else's words: escaped plain text, never Markdown, never a link.
10 */
11
12 import type { Ctx } from "../http/context.ts";
13 import { getIssue } from "../core/issues.ts";
14 import { canRead, getRepo } from "../core/repos.ts";
15 import { mayView } from "../core/sealed.ts";
16 import { html, type Html } from "./html.ts";
17 import { btn, icon, time } from "./ui.ts";
18 import { inlineIcons } from "./icons.ts";
19 import { notePhase, takeSessionTime } from "../core/route_timing.ts";
20 import { fragment } from "./layout.ts";
21 import { liveCrewRows } from "../actions/crew_now.ts";
22 import { crewLine } from "./crew_now.ts";
23 import { FOR_MINUTES, workLine, workLineFor, type WorkLine } from "../core/talk_work.ts";
24
25 /** The paths a peek reads: a repository, or one of its issues or pulls. */
26 const PEEK =
27 /^\/([A-Za-z0-9][A-Za-z0-9_.-]{0,63})\/([A-Za-z0-9][A-Za-z0-9_.-]{0,99})(?:\/(issues|pulls)\/([1-9]\d{0,8}))?\/?$/;
28 /** How much of a body the card shows, in characters. */
29 const BODY_SHOWN = 240;
30
31 /** The card's words, in one place. */
32 const PEEK_WORDS = {
33 open: "Open",
34 talk: "Talk about this",
35 changed: "Changed",
36 merged: "Merged",
37 open_: "Open",
38 closed: "Closed",
39 checksOk: "checks passed",
40 checksFailed: "checks failed",
41 checksRunning: "checks running",
42 } as const;
43
44 const notFound = (): Response =>
45 new Response("not found", {
46 status: 404,
47 headers: { "cache-control": "private, no-store" },
48 });
49
50 // GET /talk/peek?href=<a rooted path on this forge>
51 export function talkPeek(ctx: Ctx): Response {
52 if (ctx.auth.user === undefined)
53 return new Response("sign in", { status: 401 });
54 const m = PEEK.exec(ctx.url.searchParams.get("href") ?? "");
55 if (m === null) return notFound();
56 const [, owner = "", name = "", kind, number] = m;
57 const repo = getRepo(ctx.app.db, owner, name);
58 if (repo === undefined || !canRead(ctx.app.db, repo, ctx.auth.user))
59 return notFound();
60 const db = ctx.app.db;
61 let card: Html;
62 if (kind === undefined) {
63 card = html`<p class="talk-peek-kind small muted">
64 ${icon("repo")} Repository
65 </p>
66 <p class="talk-peek-title">${repo.ownerName}/${repo.name}</p>
67 ${repo.description === ""
68 ? null
69 : html`<p class="talk-peek-body small">
70 ${repo.description.slice(0, BODY_SHOWN)}
71 </p>`}
72 <div class="talk-peek-acts">
73 <a class="btn" data-size="sm" href="/${repo.ownerName}/${repo.name}"
74 >${PEEK_WORDS.open}</a
75 ><a
76 class="btn"
77 data-size="sm"
78 href="/talk?about=${encodeURIComponent(
79 `${repo.ownerName}/${repo.name}`,
80 )}"
81 >${PEEK_WORDS.talk}</a
82 >
83 </div>`;
84 } else {
85 const issue = getIssue(db, repo.id, Number(number));
86 if (
87 issue === undefined ||
88 !mayView(db, repo, issue, ctx.auth.user) ||
89 (issue.kind === "pull") !== (kind === "pulls")
90 )
91 return notFound();
92 const pull =
93 issue.kind === "pull"
94 ? db
95 .query<
96 { merged_at: string | null },
97 [string]
98 >("SELECT merged_at FROM pull WHERE issue_id = ?1")
99 .get(issue.id)
100 : null;
101 const check =
102 issue.kind === "pull"
103 ? db
104 .query<
105 { state: string },
106 [string]
107 >("SELECT state FROM run WHERE issue_id = ?1 AND kind = 'check' ORDER BY id DESC LIMIT 1")
108 .get(issue.id)
109 : null;
110 // Who is on it now, as the receipt's work line says it: one plain sentence.
111 const doing = issue.state === "open" && kind === "issues" ? workLine(db, issue, Date.now()) : "";
112 const state = pull?.merged_at
113 ? (["merge", PEEK_WORDS.merged] as const)
114 : issue.state === "open"
115 ? ([
116 issue.kind === "pull" ? "pull" : "issue",
117 PEEK_WORDS.open_,
118 ] as const)
119 : (["issueClosed", PEEK_WORDS.closed] as const);
120 const checks =
121 check === null || check === undefined
122 ? null
123 : check.state === "ok"
124 ? PEEK_WORDS.checksOk
125 : check.state === "failed"
126 ? PEEK_WORDS.checksFailed
127 : PEEK_WORDS.checksRunning;
128 const body = issue.body.replace(/\s+/g, " ").trim();
129 const path = `/${repo.ownerName}/${repo.name}/${kind}/${issue.number}`;
130 card = html`<p class="talk-peek-kind small muted">
131 ${icon(state[0])} ${repo.ownerName}/${repo.name}#${String(issue.number)}
132 · ${state[1]}${checks === null ? null : html` · ${checks}`}
133 </p>
134 <p class="talk-peek-title">${issue.title}</p>
135 ${doing === "" ? null : html`<p class="small muted">${doing}</p>`}
136 ${body === ""
137 ? null
138 : html`<p class="talk-peek-body small">
139 ${body.length > BODY_SHOWN ? `${body.slice(0, BODY_SHOWN)}…` : body}
140 </p>`}
141 <p class="small muted">${PEEK_WORDS.changed} ${time(issue.updatedAt)}</p>
142 <div class="talk-peek-acts">
143 <a class="btn" data-size="sm" href="${path}">${PEEK_WORDS.open}</a
144 ><a
145 class="btn"
146 data-size="sm"
147 href="/talk?about=${encodeURIComponent(
148 `${repo.ownerName}/${repo.name}#${issue.number}`,
149 )}"
150 >${PEEK_WORDS.talk}</a
151 >
152 </div>`;
153 }
154 // A fragment lands in a page whose sprite it does not know: its icons are drawn inline.
155 return new Response(inlineIcons(html`<div class="talk-peek-card">${card}</div>`.text), {
156 headers: {
157 "content-type": "text/html; charset=utf-8",
158 "cache-control": "private, max-age=5",
159 },
160 });
161 }
162
163 // GET /live/talk-work?href=/owner/name/issues/N&id=w-<turn> — a receipt's work line alone, read as
164 // the issue's own page is; the live client swaps it in place.
165 export function liveTalkWork(ctx: Ctx): Response {
166 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
167 const rendering = performance.now();
168 const answer = workFragment(ctx);
169 notePhase(ctx.request, "render", performance.now() - rendering);
170 return answer;
171 }
172
173 function workFragment(ctx: Ctx): Response {
174 const m = PEEK.exec(ctx.url.searchParams.get("href") ?? "");
175 const id = ctx.url.searchParams.get("id") ?? "";
176 if (ctx.auth.user === undefined || m === null || m[3] !== "issues" || !/^w-[0-9a-z]{1,40}$/.test(id)) return fragment(html``, { status: 404 });
177 const repo = getRepo(ctx.app.db, m[1] ?? "", m[2] ?? "");
178 const issue = repo === undefined || !canRead(ctx.app.db, repo, ctx.auth.user) ? undefined : getIssue(ctx.app.db, repo.id, Number(m[4]));
179 if (repo === undefined || issue === undefined || !mayView(ctx.app.db, repo, issue, ctx.auth.user)) return fragment(html``, { status: 404 });
180 return fragment(html`<div class="talk-work-line small muted" id="${id}">${workLineHtml(workLineFor(ctx.app.db, ctx.app.config.dataDir, issue, Date.now(), ctx.auth.user))}</div>`, { request: ctx.request });
181 }
182
183 // GET /live/talk-crew — the crew's one line on Talk, empty when it is idle.
184 export function liveTalkCrew(ctx: Ctx): Response {
185 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
186 const rendering = performance.now();
187 const rows = ctx.auth.user === undefined ? undefined : liveCrewRows(ctx, ctx.auth.user);
188 const answer = rows === undefined ? fragment(html``, { status: 404 }) : fragment(html`<p class="talk-crew small muted" id="talk-crew">${rows.length === 0 ? null : crewLine(rows)}</p>`, { request: ctx.request });
189 notePhase(ctx.request, "render", performance.now() - rendering);
190 return answer;
191 }
192
193 /** The card's own styles, part of the page's sheet. Spacing is the scale. */
194 export const peekCss = /* css */ `
195 .talk-peek { position: absolute; width: min(22rem, calc(100vw - 32px)); padding: 12px; border-radius: var(--radius-lg); background: var(--card); box-shadow: var(--shadow-2); }
196 .talk-peek[hidden] { display: none; }
197 .talk-peek-card { display: grid; gap: 4px; }
198 .talk-peek-card p { margin: 0; }
199 .talk-peek-kind { display: flex; align-items: center; gap: 6px; }
200 .talk-peek-title { font-weight: 600; overflow-wrap: anywhere; }
201 .talk-peek-body { color: var(--fg); overflow-wrap: anywhere; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }
202 .talk-peek-acts { display: flex; gap: 8px; margin-top: 4px; }
203 .talk-peek-acts .btn { position: relative; }
204 .talk-peek-acts .btn::after { content: ""; position: absolute; inset: -6px -2px; }
205 .talk-peek-sheet .dialog-body { padding: 16px; }
206 @media (prefers-reduced-motion: no-preference) { .talk-peek:not([hidden]) { animation: talk-in var(--dur-2) var(--ease); } }
207 `;
208
209 /**
210 * A work line's words, and the control that changes what it waits on as a link; when the access
211 * wall holds its pull, the two answers as forms that post to Talk's own `/talk/wall`, which work
212 * without the script.
213 */
214 export const workLineHtml = (l: WorkLine): Html =>
215 html`${l.since === undefined ? l.says : html`${l.says.replace(FOR_MINUTES, "")} for ${time(l.since, { count: "elapsed" })}.`}${l.change === undefined ? null : html` <a href="${l.change.href}">${l.change.words}</a>`}${l.wall === undefined ? null : wallAnswers(l.wall)}`;
216
217 /** "Allow it" and "Send it back", each its own form: the answer is in the form, never a query. */
218 const wallAnswers = (w: { readonly repo: string; readonly number: number }): Html => {
219 const form = (answer: "allow" | "send_back", words: string, variant: "primary" | "ghost") =>
220 html`<form method="post" action="/talk/wall" class="inline-form">
221 <input type="hidden" name="repo" value="${w.repo}" /><input type="hidden" name="number" value="${String(w.number)}" /><input type="hidden" name="answer" value="${answer}" />
222 ${btn(words, { size: "sm", variant })}
223 </form>`;
224 return html`<span class="bar mt" data-wall-answers>${form("allow", "Allow it", "primary")}${form("send_back", "Send it back", "ghost")}</span>`;
225 };
test/design-audit.test.ts +1 −1
@@ -17,7 +17,7 @@ const doc = readFileSync("docs/design/audit.md", "utf8");
1717
1818 /** Routes that answer a file, a fragment, a redirect hop or a callback. */
1919 const NOT_PAGES =
20 /^\/(design\/theme\.css|design\/theme\/|assets\/|\.well-known\/|icons\/|og\/|live\/|__forge\/|go\/|new\/issue$|events$|system\/stream$|talk\/stream$|talk\/peek$|settings\/teams\/stream$|sw\.js$|offline$|robots\.txt$|favicon\.ico$|apple-touch-icon(-precomposed)?\.png$|sitemap\.xml$|edition$|oembed$|manifest\.webmanifest$|opensearch\.xml$|llms(-full)?\.txt$|openapi\.json$|releases\.json$|templates\.json$|maintenance\.json$|changelog\.atom$|explore\.(atom|json)$|feed\.json$|docs(\/[^/]*)?$|audit\.csv$|settings\/traffic\/scrapes\/export$|settings\/payments\.csv$|fleet\/graph\/live$|fleet\/graph\.csv$|forges\/export\.csv$|settings\/origins\/callback$|broker\/origins\/start$|home\/archived\/|settings\/backups\/live$|api\/v1(\/|$))/;
20 /^\/(design\/theme\.css|design\/theme\/|assets\/|\.well-known\/|icons\/|og\/|live\/|__forge\/|go\/|new\/issue$|events$|system\/stream$|talk\/stream$|peek$|settings\/teams\/stream$|sw\.js$|offline$|robots\.txt$|favicon\.ico$|apple-touch-icon(-precomposed)?\.png$|sitemap\.xml$|edition$|oembed$|manifest\.webmanifest$|opensearch\.xml$|llms(-full)?\.txt$|openapi\.json$|releases\.json$|templates\.json$|maintenance\.json$|changelog\.atom$|explore\.(atom|json)$|feed\.json$|docs(\/[^/]*)?$|audit\.csv$|settings\/traffic\/scrapes\/export$|settings\/payments\.csv$|fleet\/graph\/live$|fleet\/graph\.csv$|forges\/export\.csv$|settings\/origins\/callback$|broker\/origins\/start$|home\/archived\/|settings\/backups\/live$|api\/v1(\/|$))/;
2121
2222 const getRoutes = [
2323 ...server.matchAll(/router\.add\(\s*"GET",\s*"([^"]+)"/g),
test/forge-looks.test.ts +1
@@ -60,6 +60,7 @@ const NOT_A_PAGE: Record<string, string> = {
6060 "/feed.json": "JSON Feed of /feed",
6161 "/sitemap.xml": "XML for crawlers",
6262 "/oembed": "JSON for other sites to build a link card; covered by test/oembed.test.ts",
63 "/peek": "a fragment, the card a #12 shows on hover; 404 without a readable href; covered by test/peek.test.ts",
6364 "/manifest.webmanifest": "the install manifest, JSON",
6465 "/opensearch.xml": "the browser search description, XML",
6566 "/sw.js": "the service worker script",
test/peek.test.ts added +360
@@ -0,0 +1,360 @@
1 /**
2 * The peek (#15734, forge-wide): `GET /peek` answers a small card for an issue or a pull (and, for
3 * Talk's thread, a repository) the viewer may read: the reference and its state, the title, who
4 * opened it and when, and the first lines of its body as plain text. Anything the viewer may not
5 * read answers the very same 404 as a number that is not there, private and varying on the cookie.
6 * In a real Chromium (skipped, and says so, where none starts; failed, never skipped, in the
7 * forge's own check): a hover on a bare `#1` in a comment opens the card after its intent delay,
8 * focus opens it, Escape closes it and gives focus back to the link, a row that shows its title
9 * gets none, and Talk's thread peeks every forge link.
10 */
11 import { afterAll, beforeAll, expect, test } from "bun:test";
12 import { mkdtemp, rm } from "node:fs/promises";
13 import { tmpdir } from "node:os";
14 import { join } from "node:path";
15 import { createRepo } from "../src/actions/repos.ts";
16 import { createApp, type App } from "../src/app.ts";
17 import { appendTurn, openConversation } from "../src/core/conversations.ts";
18 import { addComment, createIssue, setIssueState } from "../src/core/issues.ts";
19 import { getRepo } from "../src/core/repos.ts";
20 import { createRun } from "../src/core/runs.ts";
21 import { createSession } from "../src/core/sessions.ts";
22 import { createUser, type User } from "../src/core/users.ts";
23 import { findChromium } from "../src/looks/capture.ts";
24 import { serve, type Servers } from "../src/http/server.ts";
25 import { peekCard, plainLines } from "../src/web/peek.ts";
26 import { chromiumRuns, evaluateLoaded } from "./helpers/chrome.ts";
27 import { quietLogs } from "./helpers/globals.ts";
28 import { promote } from "./helpers/members.ts";
29 import { once } from "./helpers/statements.ts";
30
31 quietLogs();
32
33 const found = findChromium();
34 const chromium = found !== undefined && chromiumRuns(found) ? found : undefined;
35 /** The forge's own check names its run: there a browser test runs or fails, it never skips. */
36 const skip = chromium === undefined && (process.env["FORGE_CHECK"] ?? "") === "";
37 if (skip) console.log("SKIPPING: no chromium that starts on this machine, so the hover is not driven");
38
39 let dir: string;
40 let app: App;
41 let servers: Servers;
42 let alice: User;
43 let bob: User;
44 const token = (u: User) => createSession(app.db, u.id).token;
45 const peek = (href: string, u: User | null = alice) =>
46 fetch(`${servers.url}/peek?href=${encodeURIComponent(href)}`, { headers: u === null ? {} : { cookie: `forge_session=${token(u)}` } });
47 const BODY = [
48 "<!-- a note to self -->",
49 "# The hero is a **6 MB** PNG",
50 "",
51 "```ts",
52 "const secret = 'from a fence';",
53 "```",
54 "<script>alert(1)</script> See [the spec](javascript:alert(1)) and ![chart](/c.png) for `webp`.",
55 "- [ ] needs WebP",
56 "| a | b |",
57 "| --- | --- |",
58 "a fourth line never shown",
59 ].join("\n");
60
61 beforeAll(async () => {
62 dir = await mkdtemp(join(tmpdir(), "forge-peek-"));
63 app = createApp({ dataDir: dir, port: 0 });
64 servers = await serve(app);
65 for (const name of ["alice", "bob"]) {
66 const made = await createUser(app.db, { origin: "seed", trusted: true, username: name, email: `${name}@forge.local`, password: "a-good-passphrase", adminIfFirst: name === "alice" });
67 if (!made.ok) throw new Error(made.error);
68 promote(app.db, made.value);
69 if (name === "alice") alice = made.value;
70 else bob = made.value;
71 }
72 const open = await createRepo(app, alice, { name: "harbor", visibility: "public", description: "The harbor site" });
73 const secret = await createRepo(app, alice, { name: "vault", visibility: "private" });
74 if (!open.ok || !secret.ok) throw new Error("repo");
75 const issue = createIssue(app.db, { repoId: open.value.id, authorId: alice.id, title: "Hero image is <b>6 MB</b>", body: BODY });
76 if (!issue.ok) throw new Error("issue");
77 const other = createIssue(app.db, { repoId: open.value.id, authorId: bob.id, title: "Footer links", body: "b" });
78 if (!other.ok) throw new Error("issue");
79 addComment(app.db, { issueId: other.value.id, authorId: bob.id, body: "Blocked on #1 for now; see also #3." });
80 createIssue(app.db, { repoId: secret.value.id, authorId: alice.id, title: "Private plan", body: "x" });
81 const c = openConversation(app.db, alice.id);
82 appendTurn(app.db, alice.id, c.id, { role: "person", text: "what about the hero?" });
83 appendTurn(app.db, alice.id, c.id, { role: "agent", text: "It is [the hero issue](/alice/harbor/issues/1): a 6 MB PNG." });
84 });
85 afterAll(async () => {
86 servers.stop();
87 app.close();
88 await rm(dir, { recursive: true, force: true });
89 });
90
91 test("the body preview is plain text from its first lines: no Markdown, no HTML, nothing from a code fence", () => {
92 const lines = plainLines(BODY);
93 expect(lines).toBe("The hero is a 6 MB PNG\nSee the spec and chart for webp.\nneeds WebP");
94 expect(lines).not.toContain("secret");
95 expect(lines).not.toContain("<");
96 expect(plainLines("x".repeat(300))).toHaveLength(241);
97 expect(plainLines("```\nonly code\n```")).toBe("");
98 });
99
100 test("an issue's card: reference, state, title, who opened it and when, plain lines, and two safe actions for a signed-in reader only", async () => {
101 const res = await peek("/alice/harbor/issues/1");
102 expect(res.status).toBe(200);
103 expect(res.headers.get("cache-control")).toBe("private, no-store");
104 expect(res.headers.get("vary")).toContain("Cookie");
105 const card = (await res.text()).replace(/\s+/g, " ");
106 expect(card).toContain("alice/harbor#1 · Open");
107 expect(card).toContain("Hero image is &lt;b&gt;6 MB&lt;/b&gt;");
108 expect(card).toContain("Opened by alice");
109 expect(card).toContain("The hero is a 6 MB PNG");
110 expect(card).not.toContain("<script");
111 expect(card).not.toContain("javascript:");
112 expect(card).not.toContain("from a fence");
113 expect(card).toMatch(/href="\/alice\/harbor\/issues\/1">Open<\/a\s*>/);
114 expect(card).toContain('href="/talk?about=alice%2Fharbor%231">Talk about this</a>');
115 const out = (await (await peek("/alice/harbor/issues/1", null)).text()).replace(/\s+/g, " ");
116 expect(out).toContain("alice/harbor#1 · Open");
117 expect(out).not.toContain("Talk about this");
118 expect(await (await peek("/alice/harbor")).text()).toContain("The harbor site");
119 });
120
121 test("a stranger, a signed-out visitor, a missing number and a missing repository get the same 404, byte for byte, headers too", async () => {
122 const answers = await Promise.all([
123 peek("/alice/vault/issues/1", bob),
124 peek("/alice/vault/issues/1", null),
125 peek("/alice/vault", bob),
126 peek("/alice/harbor/issues/999", bob),
127 peek("/alice/nowhere/issues/1", bob),
128 peek("/alice/harbor/pulls/1", bob),
129 peek("https://evil.example/alice/harbor", bob),
130 peek("//evil.example/x", null),
131 ]);
132 // The date and the measured phases are the clock's, not the answer's.
133 const shape = async (r: Response) => ({ status: r.status, body: await r.text(), headers: [...r.headers].filter(([k]) => k !== "date" && k !== "server-timing").sort() });
134 const [first, ...rest] = await Promise.all(answers.map(shape));
135 expect(first!.status).toBe(404);
136 expect(Object.fromEntries(first!.headers)["cache-control"]).toBe("private, no-store");
137 expect(Object.fromEntries(first!.headers)["vary"]).toContain("Cookie");
138 for (const r of rest) expect(r).toEqual(first!);
139 expect((await peek("/alice/vault/issues/1", alice)).status).toBe(200);
140 });
141
142 test("each state a card carries: merged, closed, draft, checks in words; a sealed issue is not found to whoever may not see it", async () => {
143 const repo = getRepo(app.db, "alice", "harbor")!;
144 const made = (title: string, more: { kind?: "pull"; sealed?: boolean } = {}) => {
145 const i = createIssue(app.db, { repoId: repo.id, authorId: alice.id, title, body: "b", ...more });
146 if (!i.ok) throw new Error("issue");
147 return i.value;
148 };
149 const pullOf = (title: string, merged: string | null, draft: string | null = null) => {
150 const p = made(title, { kind: "pull" });
151 app.db.run("INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, merged_at, draft_run) VALUES (?1, 'main', ?2, '', 'h', ?3, ?4)", [p.id, `b${String(p.number)}`, merged, draft]);
152 return p;
153 };
154 const checked = (p: { id: string }, state: string) => app.db.run("UPDATE run SET state = ?1 WHERE id = ?2", [state, createRun(app.db, { repoId: repo.id, kind: "check", issueId: p.id }).id]);
155 const text = async (href: string, u: User = alice) => (await (await peek(href, u)).text()).replace(/\s+/g, " ");
156
157 const merged = pullOf("Ship WebP", new Date().toISOString());
158 checked(merged, "ok");
159 const card = await text(`/alice/harbor/pulls/${String(merged.number)}`);
160 expect(card).toContain(`alice/harbor#${String(merged.number)} · Merged · checks passed`);
161 expect(card).toMatch(new RegExp(`href="/alice/harbor/pulls/${String(merged.number)}">Open</a\\s*>`));
162 // A pull named as an issue, as `#N` in a comment links it, is the pull's card.
163 expect(await text(`/alice/harbor/issues/${String(merged.number)}`)).toContain("· Merged");
164 const red = pullOf("Try AVIF", null);
165 checked(red, "failed");
166 expect(await text(`/alice/harbor/pulls/${String(red.number)}`)).toContain("· Open · checks failed");
167 const going = pullOf("Try JPEG XL", null, "run-1");
168 checked(going, "running");
169 expect(await text(`/alice/harbor/pulls/${String(going.number)}`)).toContain("· Open · Draft · checks running");
170 const done = made("Old banner");
171 setIssueState(app.db, done.id, "closed");
172 expect(await text(`/alice/harbor/issues/${String(done.number)}`)).toContain(`alice/harbor#${String(done.number)} · Closed`);
173 const sealed = made("A hole", { sealed: true });
174 expect((await peek(`/alice/harbor/issues/${String(sealed.number)}`, bob)).status).toBe(404);
175 expect((await peek(`/alice/harbor/issues/${String(sealed.number)}`, alice)).status).toBe(200);
176 });
177
178 test("a card is at most five statements, whatever it shows or refuses", async () => {
179 const repo = getRepo(app.db, "alice", "harbor")!;
180 const p = createIssue(app.db, { repoId: repo.id, authorId: alice.id, title: "Counted", body: "b", kind: "pull" });
181 if (!p.ok) throw new Error("pull");
182 app.db.run("INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid) VALUES (?1, 'main', 'counted', '', 'h')", [p.value.id]);
183 for (const [who, href] of [
184 [alice, "/alice/harbor/issues/1"],
185 [alice, `/alice/harbor/pulls/${String(p.value.number)}`],
186 [alice, "/alice/harbor"],
187 [bob, "/alice/vault/issues/1"],
188 [undefined, "/alice/harbor/issues/1"],
189 ] as const) {
190 const n = await once(app.db, () => void peekCard(app.db, who, href));
191 expect(n, `${href} as ${who?.username ?? "nobody"}`).toBeLessThanOrEqual(5);
192 }
193 });
194
195 const inPage = (path: string, as: User | null, expression: string, width = 1280) =>
196 evaluateLoaded(chromium!, `${servers.url}${path}`, { width, height: 800 }, as === null ? [] : [{ name: "forge_session", value: token(as) }], expression).then((v) => JSON.parse(v));
197 /** In the page: wait for `f` to hold, checking every 25 ms, at most `ms`. */
198 const WAIT = "const wait = (f, ms = 3000) => new Promise((ok) => { const t0 = performance.now(); const t = setInterval(() => { if (f() || performance.now() - t0 > ms) { clearInterval(t); ok(); } }, 25); });";
199
200 for (const who of ["signed in", "signed out"] as const) {
201 test.skipIf(skip)(`${who}: a bare #1 in a comment peeks on hover; Escape closes it and gives focus back; focus opens it too`, async () => {
202 if (chromium === undefined) throw new Error("no Chromium starts in this check, so the peek is not driven: the check's image must carry one (FORGE_CHROMIUM)");
203 const s = await inPage("/alice/harbor/issues/2", who === "signed in" ? bob : null, `(async () => {
204 ${WAIT}
205 const a = [...document.querySelectorAll("a[href='/alice/harbor/issues/1']")].find((x) => x.textContent.trim() === "#1");
206 if (!a) return JSON.stringify({ found: false });
207 a.dispatchEvent(new PointerEvent("pointerover", { bubbles: true, pointerType: "mouse" }));
208 await wait(() => document.querySelector(".peek"));
209 const card = document.querySelector(".peek");
210 const out = { found: true, text: card ? card.textContent.replace(/\\s+/g, " ").trim() : "", described: a.getAttribute("aria-describedby"), role: card && card.getAttribute("role"), cards: document.querySelectorAll(".peek").length };
211 document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
212 out.closed = !document.querySelector(".peek") && !a.hasAttribute("aria-describedby");
213 out.focused = document.activeElement === a;
214 // Keyboard: focus coming back onto the link (no press gave it) opens it at once. A headless page
215 // has no window focus, so the focus event is sent as the browser would.
216 a.blur();
217 a.focus();
218 a.dispatchEvent(new FocusEvent("focusin", { bubbles: true }));
219 await wait(() => document.querySelector(".peek"));
220 out.onFocus = !!document.querySelector(".peek") && a.getAttribute("aria-describedby") === "peek";
221 // The card is not a trap: focus moves on freely.
222 const away = document.querySelector("a[href='/']");
223 away?.focus();
224 a.dispatchEvent(new FocusEvent("focusout", { bubbles: true }));
225 await wait(() => !document.querySelector(".peek"));
226 out.leftClosed = !document.querySelector(".peek");
227 out.href = a.getAttribute("href");
228 return JSON.stringify(out);
229 })()`);
230 const seen = JSON.stringify(s);
231 expect(s.found, seen).toBe(true);
232 expect(s.text, seen).toContain("Hero image is <b>6 MB</b>");
233 expect(s.text, seen).toContain("Opened by alice");
234 expect(s.text.includes("Talk about this"), seen).toBe(who === "signed in");
235 expect(s.described, seen).toBe("peek");
236 expect(s.role, seen).toBe("region");
237 expect(s.cards, seen).toBe(1);
238 expect(s.closed, seen).toBe(true);
239 expect(s.focused, seen).toBe(true);
240 expect(s.onFocus, seen).toBe(true);
241 expect(s.leftClosed, seen).toBe(true);
242 expect(s.href, seen).toBe("/alice/harbor/issues/1");
243 }, 30_000);
244 }
245
246 test.skipIf(skip)("a list row that shows its title gets no card", async () => {
247 if (chromium === undefined) throw new Error("no Chromium starts in this check, so the peek is not driven: the check's image must carry one (FORGE_CHROMIUM)");
248 const list = await inPage("/alice/harbor/issues", alice, `(async () => {
249 ${WAIT}
250 const a = document.querySelector("a[href='/alice/harbor/issues/1']");
251 a.dispatchEvent(new PointerEvent("pointerover", { bubbles: true, pointerType: "mouse" }));
252 // Past the 400 ms intent: a card would be asked for by now.
253 await wait(() => document.querySelector(".peek"), 600);
254 return JSON.stringify({ text: a.textContent.trim(), card: !!document.querySelector(".peek") });
255 })()`);
256 expect(list.card, JSON.stringify(list)).toBe(false);
257 }, 30_000);
258
259 test.skipIf(skip)("Talk's thread peeks a worded link to an issue", async () => {
260 if (chromium === undefined) throw new Error("no Chromium starts in this check, so the peek is not driven: the check's image must carry one (FORGE_CHROMIUM)");
261 const c = openConversation(app.db, alice.id);
262 const talk = await inPage(`/talk/${c.id}`, alice, `(async () => {
263 ${WAIT}
264 const a = document.querySelector(".talk-body a[href='/alice/harbor/issues/1']");
265 a.dispatchEvent(new PointerEvent("pointerover", { bubbles: true, pointerType: "mouse" }));
266 await wait(() => document.querySelector(".peek"));
267 return JSON.stringify({ text: (document.querySelector(".peek")?.textContent ?? "").replace(/\\s+/g, " ") });
268 })()`);
269 expect(talk.text, JSON.stringify(talk)).toContain("alice/harbor#1 · Open");
270 }, 30_000);
271
272 test.skipIf(skip)("on touch a tap follows the link; a long press opens the card as a sheet and swallows only its own click", async () => {
273 if (chromium === undefined) throw new Error("no Chromium starts in this check, so the peek is not driven: the check's image must carry one (FORGE_CHROMIUM)");
274 const s = await inPage("/alice/harbor/issues/2", bob, `(async () => {
275 ${WAIT}
276 const a = [...document.querySelectorAll("a[href='/alice/harbor/issues/1']")].find((x) => x.textContent.trim() === "#1");
277 // Whether the page took the click, read last, after which the test keeps the page where it is.
278 let took = false;
279 window.addEventListener("click", (e) => { took = e.defaultPrevented; e.preventDefault(); });
280 const tap = () => { a.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); return took; };
281 const touch = (type) => a.dispatchEvent(new Event(type, { bubbles: true }));
282 const out = {};
283 // Every sheet the page opens, counted as it is added.
284 let sheets = 0;
285 new MutationObserver((m) => { for (const r of m) for (const n of r.addedNodes) if (n.matches && n.matches("dialog.peek-sheet")) sheets++; }).observe(document.body, { childList: true });
286 // A plain tap: no card, and the link is followed.
287 touch("touchstart"); touch("touchend");
288 out.plain = tap();
289 // A press that ends in a scroll, a cancel or a move never swallows the next tap.
290 out.ends = [];
291 for (const end of ["scroll", "touchcancel", "pointercancel", "touchmove"]) {
292 touch("touchstart");
293 (end === "scroll" ? window : a).dispatchEvent(new Event(end, { bubbles: true }));
294 out.ends.push([end, tap()]);
295 }
296 // A long press opens the sheet; the click that ends it is its own and does not follow the link.
297 touch("touchstart");
298 await wait(() => document.querySelector("dialog.peek-sheet[open]"));
299 out.sheet = !!document.querySelector("dialog.peek-sheet[open]");
300 touch("touchend");
301 out.swallowed = tap();
302 document.querySelector("dialog.peek-sheet[open]")?.close();
303 // The swallowed click ended the press: the very next tap follows the link.
304 out.after = tap();
305 // The ended presses' 500 ms passed while this one was held: none of them opened a sheet.
306 out.sheetAfter = sheets !== 1;
307 return JSON.stringify(out);
308 })()`, 390);
309 const seen = JSON.stringify(s);
310 expect(s.plain, seen).toBe(false);
311 expect(s.sheet, seen).toBe(true);
312 expect(s.swallowed, seen).toBe(true);
313 expect(s.after, seen).toBe(false);
314 expect(s.ends, seen).toEqual([["scroll", false], ["touchcancel", false], ["pointercancel", false], ["touchmove", false]]);
315 expect(s.sheetAfter, seen).toBe(false);
316 }, 30_000);
317
318 test("the card's enter is a transition from @starting-style: its end state never waits on the transition", async () => {
319 const { peekCss } = await import("../src/web/peek_client.ts");
320 // Where @starting-style is unknown the whole block is dropped and the card simply appears: no
321 // rule outside it may leave the card faded or shrunk.
322 const outside = peekCss.replace(/@starting-style\s*\{\s*\.peek\s*\{[^}]*\}\s*\}/g, "");
323 expect(peekCss).toMatch(/@starting-style\s*\{\s*\.peek\s*\{\s*opacity: 0; transform: scale\(\.95\);\s*\}\s*\}/);
324 expect(outside).not.toMatch(/opacity:\s*0[;\s]/);
325 expect(outside).not.toMatch(/scale\(\s*0?\.\d+\s*\)/);
326 expect(outside).not.toContain("@keyframes");
327 });
328
329 test.skipIf(skip)("after one card, the next opens at once and without an enter; a fresh one waits for its intent", async () => {
330 if (chromium === undefined) throw new Error("no Chromium starts in this check, so the peek is not driven: the check's image must carry one (FORGE_CHROMIUM)");
331 const s = await inPage("/alice/harbor/issues/2", bob, `(async () => {
332 ${WAIT}
333 const link = (n) => [...document.querySelectorAll("a[href='/alice/harbor/issues/" + n + "']")].find((x) => x.textContent.trim() === "#" + n);
334 const over = (a) => a.dispatchEvent(new PointerEvent("pointerover", { bubbles: true, pointerType: "mouse" }));
335 const out = (a) => a.dispatchEvent(new PointerEvent("pointerout", { bubbles: true, pointerType: "mouse" }));
336 const one = link(1), three = link(3);
337 over(one);
338 await wait(() => document.querySelector(".peek"));
339 const first = document.querySelector(".peek");
340 const r = { firstWarm: first.hasAttribute("data-warm") };
341 // Settled, the card is whole: the transition only ever led here.
342 await wait(() => getComputedStyle(first).opacity === "1" && getComputedStyle(first).transform === "none", 1000);
343 r.settled = [getComputedStyle(first).opacity, getComputedStyle(first).transform];
344 out(one);
345 over(three);
346 // Well inside the 400 ms intent, the next card is already there, and it does not enter again.
347 await wait(() => (document.querySelector(".peek")?.textContent ?? "").includes("#3"), 250);
348 const next = document.querySelector(".peek");
349 r.next = next ? next.textContent.includes("#3") : false;
350 r.nextWarm = !!next && next.hasAttribute("data-warm");
351 r.cards = document.querySelectorAll(".peek").length;
352 return JSON.stringify(r);
353 })()`);
354 const seen = JSON.stringify(s);
355 expect(s.firstWarm, seen).toBe(false);
356 expect(s.settled, seen).toEqual(["1", "none"]);
357 expect(s.next, seen).toBe(true);
358 expect(s.nextWarm, seen).toBe(true);
359 expect(s.cards, seen).toBe(1);
360 }, 30_000);
test/talk-page.test.ts −26
@@ -1071,32 +1071,6 @@ describe("the page", () => {
10711071 expect(t.copied).toEqual(["let a = 1;"]);
10721072 });
10731073
1074 test("a long press never swallows a later tap: the flag ends with the touch, a scroll or a cancel", async () => {
1075 // A hand-run clock: the long press and its short grace run when the test says.
1076 const due: (() => void)[] = [];
1077 const timers = { setTimeout: ((f: () => void) => due.push(f)) as unknown as typeof setTimeout, clearTimeout: (() => {}) as unknown as typeof clearTimeout };
1078 const run = () => { for (const f of due.splice(0)) f(); };
1079 const t = await boot("u1", {}, "c1", timers);
1080 t.doc.querySelector("#t-1 .talk-body").insertAdjacentHTML("beforeend", '<a href="/alice/harbor/issues/1">#1</a>');
1081 const a = t.doc.querySelector("#t-1 .talk-body a");
1082 const tap = () => { const e = new t.window.MouseEvent("click", { bubbles: true, cancelable: true }); a.dispatchEvent(e); return e.defaultPrevented; };
1083 const press = () => { a.dispatchEvent(new t.window.Event("touchstart", { bubbles: true })); run(); };
1084 // The click that ends a long press is swallowed; the grace then passes and a tap follows the link.
1085 press();
1086 a.dispatchEvent(new t.window.Event("touchend", { bubbles: true }));
1087 expect(tap()).toBe(true);
1088 press();
1089 a.dispatchEvent(new t.window.Event("touchend", { bubbles: true }));
1090 run();
1091 expect(tap()).toBe(false);
1092 // No click at all (the callout took it), then a scroll, a cancel or a move: the next tap follows.
1093 for (const end of ["scroll", "touchcancel", "pointercancel", "touchmove"]) {
1094 press();
1095 (end === "scroll" ? t.window : a).dispatchEvent(new t.window.Event(end, { bubbles: true }));
1096 expect([end, tap()]).toEqual([end, false]);
1097 }
1098 });
1099
11001074 test("with steps set to start open (Display), a step that streams in opens its fold as the first paint does", async () => {
11011075 const t = await boot();
11021076 t.doc.querySelector("[data-talk]").dataset.fold = "open";
test/talk-peek.test.ts deleted −218
@@ -1,218 +0,0 @@
1 /**
2 * A peek at what a Talk message links to (#15734): `GET /talk/peek` answers a small card for an
3 * issue, a pull or a repository the viewer can read, and not found for anything else, exactly as
4 * the link would; the body is escaped plain text; a live crew run shows as working now. In a real
5 * Chromium (skipped, and says so, where none starts): a hover on a link opens the card after its
6 * intent delay, Escape closes it, and a plain click still follows the link.
7 */
8 import { afterAll, beforeAll, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createRepo } from "../src/actions/repos.ts";
13 import { createApp, type App } from "../src/app.ts";
14 import { appendTurn, openConversation } from "../src/core/conversations.ts";
15 import { createIssue, setAssignee, setIssueState } from "../src/core/issues.ts";
16 import { getRepo } from "../src/core/repos.ts";
17 import { claimRun, createRun } from "../src/core/runs.ts";
18 import { createSession } from "../src/core/sessions.ts";
19 import { createUser, type User } from "../src/core/users.ts";
20 import { findChromium } from "../src/looks/capture.ts";
21 import { serve, type Servers } from "../src/http/server.ts";
22 import { chromiumRuns, evaluateLoaded } from "./helpers/chrome.ts";
23 import { quietLogs } from "./helpers/globals.ts";
24 import { promote } from "./helpers/members.ts";
25
26 quietLogs();
27
28 const found = findChromium();
29 const chromium = found !== undefined && chromiumRuns(found) ? found : undefined;
30 if (chromium === undefined)
31 console.log(
32 "SKIPPING: no chromium that starts on this machine, so the hover is not driven",
33 );
34
35 let dir: string;
36 let app: App;
37 let servers: Servers;
38 let alice: User;
39 let bob: User;
40 const token = (u: User) => createSession(app.db, u.id).token;
41 const peek = (href: string, u: User | null = alice) =>
42 fetch(`${servers.url}/talk/peek?href=${encodeURIComponent(href)}`, {
43 headers: u === null ? {} : { cookie: `forge_session=${token(u)}` },
44 });
45
46 beforeAll(async () => {
47 dir = await mkdtemp(join(tmpdir(), "forge-talk-peek-"));
48 app = createApp({ dataDir: dir, port: 0 });
49 servers = await serve(app);
50 for (const name of ["alice", "bob"]) {
51 const made = await createUser(app.db, {
52 origin: "seed",
53 trusted: true,
54 username: name,
55 email: `${name}@forge.local`,
56 password: "a-good-passphrase",
57 adminIfFirst: name === "alice",
58 });
59 if (!made.ok) throw new Error(made.error);
60 promote(app.db, made.value);
61 if (name === "alice") alice = made.value;
62 else bob = made.value;
63 }
64 const open = await createRepo(app, alice, {
65 name: "harbor",
66 visibility: "public",
67 description: "The harbor site",
68 });
69 const secret = await createRepo(app, alice, {
70 name: "vault",
71 visibility: "private",
72 });
73 if (!open.ok || !secret.ok) throw new Error("repo");
74 const issue = createIssue(app.db, {
75 repoId: open.value.id,
76 authorId: alice.id,
77 title: "Hero image is <b>6 MB</b>",
78 body: "The hero is a 6 MB PNG.\n\n<script>alert(1)</script> [x](javascript:alert(1)) needs WebP.",
79 });
80 if (!issue.ok) throw new Error("issue");
81 claimRun(
82 app.db,
83 createRun(app.db, {
84 repoId: open.value.id,
85 kind: "agent",
86 issueId: issue.value.id,
87 reason: "work",
88 }).id,
89 );
90 createIssue(app.db, {
91 repoId: secret.value.id,
92 authorId: alice.id,
93 title: "Private plan",
94 body: "x",
95 });
96 const c = openConversation(app.db, alice.id);
97 appendTurn(app.db, alice.id, c.id, {
98 role: "person",
99 text: "what about the hero?",
100 });
101 appendTurn(app.db, alice.id, c.id, {
102 role: "agent",
103 text: "It is [#1](/alice/harbor/issues/1): a 6 MB PNG.",
104 });
105 });
106 afterAll(async () => {
107 servers.stop();
108 app.close();
109 await rm(dir, { recursive: true, force: true });
110 });
111
112 test("an issue's card: kind, number, state, title, who works on it now, its body as plain text, two safe actions", async () => {
113 const res = await peek("/alice/harbor/issues/1");
114 expect(res.status).toBe(200);
115 expect(res.headers.get("cache-control")).toBe("private, max-age=5");
116 const card = (await res.text()).replace(/\s+/g, " ");
117 expect(card).toContain("alice/harbor#1 · Open");
118 expect(card).toContain("Hero image is &lt;b&gt;6 MB&lt;/b&gt;");
119 expect(card).toContain("working on it for 1 min");
120 expect(card).toContain("&lt;script&gt;alert(1)&lt;/script&gt;");
121 expect(card).not.toContain("<script>");
122 expect(card).not.toContain('href="javascript:');
123 expect(card).toContain(`href="/alice/harbor/issues/1">Open</a`);
124 expect(card).toContain(
125 'href="/talk?about=alice%2Fharbor%231" >Talk about this</a',
126 );
127 expect(await (await peek("/alice/harbor")).text()).toContain(
128 "The harbor site",
129 );
130 });
131
132 test("anything not readable, not a forge path, or of the wrong kind answers not found, as the link would; signed out is asked to sign in", async () => {
133 expect((await peek("/alice/vault/issues/1", bob)).status).toBe(404);
134 expect((await peek("/alice/vault", bob)).status).toBe(404);
135 expect((await peek("/alice/vault/issues/1", alice)).status).toBe(200);
136 expect((await peek("/alice/harbor/pulls/1")).status).toBe(404);
137 expect((await peek("/alice/harbor/issues/9")).status).toBe(404);
138 expect((await peek("https://evil.example/alice/harbor")).status).toBe(404);
139 expect((await peek("//evil.example/x")).status).toBe(404);
140 expect((await peek("/alice/harbor/issues/1", null)).status).toBe(401);
141 });
142
143 test("each state and line a card can carry: merged, closed, checks in words, assigned, queued; a pull is talked about too; a sealed issue is not found to whoever may not see it", async () => {
144 const repo = getRepo(app.db, "alice", "harbor")!;
145 const made = (title: string, more: { kind?: "pull"; sealed?: boolean } = {}) => {
146 const i = createIssue(app.db, { repoId: repo.id, authorId: alice.id, title, body: "b", ...more });
147 if (!i.ok) throw new Error("issue");
148 return i.value;
149 };
150 const pullOf = (title: string, merged: string | null) => {
151 const p = made(title, { kind: "pull" });
152 app.db.run("INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, merged_at) VALUES (?1, 'main', ?2, '', 'h', ?3)", [p.id, `b${String(p.number)}`, merged]);
153 return p;
154 };
155 const checked = (p: { id: string }, state: string) => app.db.run("UPDATE run SET state = ?1 WHERE id = ?2", [state, createRun(app.db, { repoId: repo.id, kind: "check", issueId: p.id }).id]);
156 const text = async (href: string, u: User = alice) => (await (await peek(href, u)).text()).replace(/\s+/g, " ");
157
158 const merged = pullOf("Ship WebP", new Date().toISOString());
159 checked(merged, "ok");
160 const card = await text(`/alice/harbor/pulls/${String(merged.number)}`);
161 expect(card).toContain(`alice/harbor#${String(merged.number)} · Merged · checks passed`);
162 expect(card).toContain(`href="/alice/harbor/pulls/${String(merged.number)}">Open</a`);
163 expect(card).toContain(`href="/talk?about=alice%2Fharbor%23${String(merged.number)}"`);
164 expect(card).toContain("Talk about this");
165
166 const red = pullOf("Try AVIF", null);
167 checked(red, "failed");
168 expect(await text(`/alice/harbor/pulls/${String(red.number)}`)).toContain("· Open · checks failed");
169 const going = pullOf("Try JPEG XL", null);
170 checked(going, "running");
171 expect(await text(`/alice/harbor/pulls/${String(going.number)}`)).toContain("· Open · checks running");
172
173 const done = made("Old banner");
174 setIssueState(app.db, done.id, "closed");
175 expect(await text(`/alice/harbor/issues/${String(done.number)}`)).toContain(`alice/harbor#${String(done.number)} · Closed`);
176
177 const owned = made("Footer links");
178 setAssignee(app.db, owned.id, bob.id);
179 createRun(app.db, { repoId: repo.id, kind: "agent", issueId: owned.id, reason: "work" });
180 expect(await text(`/alice/harbor/issues/${String(owned.number)}`)).toContain("Queued for bob.");
181
182 const sealed = made("A hole", { sealed: true });
183 expect((await peek(`/alice/harbor/issues/${String(sealed.number)}`, bob)).status).toBe(404);
184 expect((await peek(`/alice/harbor/issues/${String(sealed.number)}`, alice)).status).toBe(200);
185 });
186
187 test.skipIf(chromium === undefined)(
188 "a hover opens the card after its intent delay and Escape closes it; the link stays a link",
189 async () => {
190 const c = openConversation(app.db, alice.id);
191 const seen = JSON.parse(
192 await evaluateLoaded(
193 chromium!,
194 `${servers.url}/talk/${c.id}`,
195 { width: 1280, height: 800 },
196 [{ name: "forge_session", value: token(alice) }],
197 `(async () => {
198 const a = document.querySelector(".talk-body a[href='/alice/harbor/issues/1']");
199 const opened = new Promise((done) => new MutationObserver(() => document.querySelector(".talk-peek") && done()).observe(document.body, { childList: true }));
200 a.dispatchEvent(new PointerEvent("pointerover", { bubbles: true, pointerType: "mouse" }));
201 await opened;
202 const card = document.querySelector(".talk-peek");
203 const out = { text: card.textContent.replace(/\\s+/g, " ").trim(), described: a.getAttribute("aria-describedby"), role: card.getAttribute("role") };
204 document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
205 out.closed = !document.querySelector(".talk-peek") && !a.hasAttribute("aria-describedby");
206 out.href = a.getAttribute("href");
207 return JSON.stringify(out);
208 })()`,
209 ),
210 );
211 expect(seen.text).toContain("Hero image is <b>6 MB</b>");
212 expect(seen.described).toBe("talk-peek");
213 expect(seen.role).toBe("region");
214 expect(seen.closed).toBe(true);
215 expect(seen.href).toBe("/alice/harbor/issues/1");
216 },
217 30_000,
218 );
test/talk-wall-says.test.ts +1 −1
@@ -42,7 +42,7 @@ import { createForgeApp } from "../src/tui/forge.ts";
4242 import { talkChatsScreen } from "../src/tui/screens/talk_chats.ts";
4343 import { headlessTerminal } from "../src/tui/term/terminal.ts";
4444 import { wallCard } from "../src/web/studio/change.ts";
45 import { workLineHtml } from "../src/web/talk_peek.ts";
45 import { workLineHtml } from "../src/web/talk_lines.ts";
4646 import { promote } from "./helpers/members.ts";
4747 import { settleApp } from "./helpers/tui.ts";
4848 import { pollUntil } from "./helpers/poll.ts";

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs