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

The command palette's last row is "Tell the crew: <what you typed>", and choosing it sends the tell from wherever you are #5892

Parked opened this
Closed without merging

scout/forge:scout/5885-the-command-palette-s-last-row-is-tell-t → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
6 files changed +276 −11
src/core/repos.ts +3 −1
@@ -652,6 +652,8 @@ export interface ListReposOptions {
652652 appsFirst?: boolean;
653653 /** Leave archived repositories out. @default false */
654654 withoutArchived?: boolean;
655 /** Skip the per-repository counts read, for a caller that shows none. @default false */
656 withoutCounts?: boolean;
655657 /** Only archived repositories. @default false */
656658 archivedOnly?: boolean;
657659 }
@@ -728,7 +730,7 @@ export function listReposWritableTo(
728730 )
729731 .all(...params)
730732 .map(toRepo);
731 return withCounts(db, rows);
733 return options.withoutCounts === true ? rows : withCounts(db, rows);
732734 }
733735
734736 /** Repos owned by one user or org, visible to the viewer. */
src/web/client.ts +56
@@ -1677,6 +1677,43 @@ export const shellJs = /* js */ `
16771677 }).catch(function () { location.href = href; });
16781678 }
16791679
1680 // The palette's tell: the feed composer's own POST (same action, same
1681 // same-origin check), with this page's path as where it was said. The
1682 // answer is one line at the top of the page, in the flash's own classes.
1683 function tellFromHere(app, text) {
1684 var main = doc.getElementById('main');
1685 function say(tone, message, href) {
1686 if (!main) return;
1687 var old = main.querySelector('.toast[data-palette-tell]');
1688 if (old) old.remove();
1689 var t = doc.createElement('div');
1690 t.className = 'toast';
1691 t.setAttribute('data-tone', tone);
1692 t.setAttribute('data-palette-tell', '');
1693 t.setAttribute('role', 'status');
1694 var b = doc.createElement('div');
1695 b.className = 'toast-body';
1696 b.appendChild(doc.createTextNode(message));
1697 if (href && href.charAt(0) === '/' && href.charAt(1) !== '/') {
1698 b.appendChild(doc.createTextNode(' \u00b7 '));
1699 var a = doc.createElement('a');
1700 a.setAttribute('href', href);
1701 a.textContent = 'See it';
1702 b.appendChild(a);
1703 }
1704 t.appendChild(b);
1705 main.insertBefore(t, main.firstChild);
1706 }
1707 fetch('/tell', {
1708 method: 'POST', credentials: 'same-origin',
1709 headers: { accept: 'application/json' },
1710 body: new URLSearchParams({ app: app, text: text, from: location.pathname })
1711 }).then(function (r) { return r.json(); }).then(function (d) {
1712 if (d.ok) say('success', d.flash, d.href);
1713 else say('danger', d.error || '${NOT_TOLD_WORDS}');
1714 }).catch(function () { say('danger', '${NOT_TOLD_WORDS}'); });
1715 }
1716
16801717 var closePalette = null;
16811718 function openPalette() {
16821719 var dlg = doc.getElementById('palette');
@@ -1687,6 +1724,7 @@ export const shellJs = /* js */ `
16871724 var items = (loadIndex().items || []).map(function (i) {
16881725 return { t: String(i.t), h: String(i.h), g: i.c ? String(i.c) : 'Go to' };
16891726 });
1727 var tellApp = (loadIndex().tell || {}).app;
16901728 var recent = readRecent().map(function (r) { return { t: r.t, h: r.h, g: 'Recent', d: r.g }; });
16911729 var recentHrefs = recent.map(function (r) { return r.h; });
16921730 var served = []; // rows the server found, for the query servedFor
@@ -1769,6 +1807,18 @@ export const shellJs = /* js */ `
17691807 });
17701808 frag.appendChild(box);
17711809 });
1810 // Tell from anywhere: once there are words, the last row says them to the crew.
1811 if (tellApp && q.length >= 3) {
1812 var tbox = doc.createElement('div');
1813 tbox.className = 'palette-group';
1814 tbox.setAttribute('role', 'group');
1815 var ta = row({ t: 'Tell the crew: ' + q, h: '/' }, 'palette-o' + nodes.length);
1816 ta.setAttribute('href', '#tell');
1817 ta.setAttribute('data-tell', q);
1818 nodes.push(ta); shown.push({ t: ta.textContent, h: '#tell', g: 'Tell' });
1819 tbox.appendChild(ta);
1820 frag.appendChild(tbox);
1821 }
17721822 if (nodes.length === 0) frag.appendChild(emptyLine(q));
17731823 list.textContent = '';
17741824 list.appendChild(frag);
@@ -1853,6 +1903,12 @@ export const shellJs = /* js */ `
18531903 var a = e.target && e.target.closest ? e.target.closest('.palette-item') : null;
18541904 var i = a ? nodes.indexOf(a) : -1;
18551905 if (i === -1) return;
1906 if (a.hasAttribute('data-tell')) {
1907 e.preventDefault();
1908 close();
1909 tellFromHere(tellApp, a.getAttribute('data-tell'));
1910 return;
1911 }
18561912 remember(shown[i]);
18571913 var h = a.getAttribute('href') || '';
18581914 if (/^\\/[^\\/?#]+\\/[^\\/?#]+\\/tell\\?from=/.test(h) && !e.metaKey && !e.ctrlKey && !e.shiftKey) {
src/web/layout.ts +27 −2
@@ -10,7 +10,8 @@
1010 import { OPENSEARCH_PATH, OPENSEARCH_TITLE, OPENSEARCH_TYPE } from "./opensearch.ts";
1111 import { protectionNotice } from "../kernel/protection.ts";
1212 import { appsForRepos } from "../core/apps.ts";
13 import { listReposVisibleTo } from "../core/repos.ts";
13 import { getRepo, listReposVisibleTo, listReposWritableTo } from "../core/repos.ts";
14 import { mayDirectCrew } from "../crew/direct.ts";
1415 import type { User } from "../core/users.ts";
1516 import type { Ctx } from "../http/context.ts";
1617 import { activeEdgeToken, edgeLoginUrl, edgeLogoutUrl, edgeStrangerLogin } from "../http/edge.ts";
@@ -288,6 +289,30 @@ const STATIC_PALETTE: PaletteItem[] = [
288289 { t: "Origins", h: "/settings/origins", c: "Settings" },
289290 ];
290291
292 /**
293 * Where the palette's "Tell the crew" row sends a sentence, as the feed
294 * composer's `app` field names it: the repository the page is on when the
295 * viewer may direct its crew, else the first app they can write to, else
296 * the forge itself. Absent for anyone who may not tell (signed out, or an
297 * organization), and then the row is not drawn.
298 */
299 function tellTarget(ctx: Ctx): { app: string } | undefined {
300 const user = ctx.auth.user;
301 if (user === undefined || user.kind === "org") return undefined;
302 const [owner, name] = ctx.url.pathname.split("/").filter((s) => s !== "");
303 const here =
304 owner !== undefined && name !== undefined ? getRepo(ctx.app.db, owner, name) : undefined;
305 if (here !== undefined && mayDirectCrew(ctx.app.db, here, user))
306 return { app: `${here.ownerName}/${here.name}` };
307 const [first] = listReposWritableTo(ctx.app.db, user, {
308 limit: 1,
309 appsFirst: true,
310 withoutArchived: true,
311 withoutCounts: true,
312 });
313 return { app: first === undefined ? "forge" : `${first.ownerName}/${first.name}` };
314 }
315
291316 /**
292317 * The palette index rides as a `<script type="application/json">` data block.
293318 * The HTML spec stops parsing such a block as script, so the CSP never
@@ -334,7 +359,7 @@ function paletteIndex(ctx: Ctx, extra: PaletteItem[]): Html {
334359 // API found, folded in the browser — build the same addresses the server
335360 // just rendered (`tellHref`/`changeHref`, `src/web/studio/nouns.ts`). The
336361 // palette can never hand out a noun the page behind it would not.
337 const json = JSON.stringify({ items, studio }).replaceAll("<", "\\u003c");
362 const json = JSON.stringify({ items, studio, tell: tellTarget(ctx) }).replaceAll("<", "\\u003c");
338363 return raw(
339364 `<script type="application/json" id="palette-index">${json}</script>`,
340365 );
src/web/studio/actions.ts +22 −7
@@ -81,14 +81,26 @@ async function tellFrom(
8181 // A client's "Ask for something" (named by the form, not guessed from `/`):
8282 // they asked for something and want nothing more than to know it went.
8383 if (from === "/" && field(form, "ask") === "1") return flashOrJson(ctx, back, { message: SENT_WORDS });
84 // The tell's own page, for a caller that asked for JSON (the palette's row).
85 const at = { href: `${repoBase(repo)}/issues/${told.value.issue.number}` };
8486 if (routed === undefined)
85 return flashOrJson(ctx, back, {
86 message: `Opened as an issue. Nobody is on the crew to take it yet — add someone under Settings → Crew.`,
87 });
87 return flashOrJson(
88 ctx,
89 back,
90 {
91 message: `Opened as an issue. Nobody is on the crew to take it yet — add someone under Settings → Crew.`,
92 },
93 at,
94 );
8895 const builder = routed.builder;
89 return flashOrJson(ctx, back, {
90 message: `${builder.user.username} is on it — ${routed.size} ${routed.kind}${routed.by === "rule" ? "" : `, ${routed.by} decided in ${routed.ms} ms`}.${from === null ? " Watch it work below." : ""}`,
91 });
96 return flashOrJson(
97 ctx,
98 back,
99 {
100 message: `${builder.user.username} is on it — ${routed.size} ${routed.kind}${routed.by === "rule" ? "" : `, ${routed.by} decided in ${routed.ms} ms`}.${from === null ? " Watch it work below." : ""}`,
101 },
102 at,
103 );
92104 }
93105
94106 /** POST /:owner/:name/tell { text } — a sentence becomes work. */
@@ -160,8 +172,10 @@ export async function composerSubmit(ctx: Ctx): Promise<Response> {
160172 const target = field(form, "app");
161173 // "the forge" is no app: the words are kept as a thought, exactly as typed.
162174 if (target === FORGE_TARGET) {
175 if (field(form, "text").trim() === "")
176 return flashOrJson(ctx, "/", { tone: "danger", message: SAY_SOMETHING_WORDS });
163177 const kept = keepThought(ctx.app, ctx.auth.user, field(form, "text"), "composer");
164 return flashTo(
178 return flashOrJson(
165179 ctx,
166180 "/",
167181 kept.ok
@@ -171,6 +185,7 @@ export async function composerSubmit(ctx: Ctx): Promise<Response> {
171185 message:
172186 kept.error === "too_long" ? "That is too long to keep." : "That could not be kept.",
173187 },
188 { href: "/" },
174189 );
175190 }
176191 const [owner = "", name = "", ...extra] = target.split("/");
test/helpers/chrome.ts +2 −1
@@ -107,7 +107,7 @@ async function readDebuggerUrl(
107107 * cookies and the given colour scheme, and return what `expression` (a JS
108108 * expression that yields a JSON string) says once the page has loaded.
109109 */
110 async function evaluateLoaded(
110 export async function evaluateLoaded(
111111 binary: string,
112112 url: string,
113113 viewport: { width: number; height: number },
@@ -187,6 +187,7 @@ async function evaluateLoaded(
187187 const { result } = await cdp.send("Runtime.evaluate", {
188188 expression,
189189 returnByValue: true,
190 awaitPromise: true,
190191 });
191192 return result.value as string;
192193 } finally {
test/palette-tell.test.ts added +166
@@ -0,0 +1,166 @@
1 /**
2 * The palette's last row, "Tell the crew: <what you typed>" (#5885): in a
3 * real headless Chromium on a repository page, type a sentence, pick the
4 * row, and the tell is in the forge with that page as where it was said.
5 * Signed out, the row is not drawn. The refusals are the action's own words.
6 */
7
8 import { afterAll, beforeAll, describe, 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 { commitToBranch, createRepo } from "../src/actions/repos.ts";
13 import { createApp, type App } from "../src/app.ts";
14 import { createSession } from "../src/core/sessions.ts";
15 import { createUser } from "../src/core/users.ts";
16 import { serve, type Servers } from "../src/http/server.ts";
17 import { findChromium } from "../src/looks/capture.ts";
18 import { chromiumRuns, evaluateLoaded } from "./helpers/chrome.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20 import { promote } from "./helpers/members.ts";
21
22 quietLogs();
23
24 const found = findChromium();
25 const chromium = found !== undefined && chromiumRuns(found) ? found : undefined;
26 if (chromium === undefined)
27 console.log("SKIPPING: no chromium that starts on this machine, so the palette tell browser tests cannot run");
28
29 /** Open the palette, type `text`, and report the rows; with `pick`, choose the tell row. */
30 const drive = (text: string, pick: boolean): string => `(async () => { try {
31 const wait = (ms) => new Promise((r) => setTimeout(r, ms));
32 const opener = document.querySelector("[data-palette]");
33 if (!opener) return JSON.stringify({ error: "no palette button on " + location.href + ": " + document.title });
34 opener.click();
35 await wait(100);
36 const dlg = document.getElementById("palette");
37 const input = dlg.querySelector(".palette-input");
38 input.value = ${JSON.stringify(text)};
39 input.dispatchEvent(new Event("input"));
40 await wait(100);
41 const rows = [...dlg.querySelectorAll(".palette-item")];
42 const last = rows[rows.length - 1];
43 const tellRow = last && last.hasAttribute("data-tell") ? last.textContent : null;
44 let toast = null;
45 if (pick && last) {
46 last.click();
47 await wait(800);
48 const t = document.querySelector(".toast[data-palette-tell]");
49 toast = t ? { text: t.textContent, link: t.querySelector("a")?.getAttribute("href") ?? null } : null;
50 }
51 return JSON.stringify({ tellRow, rows: rows.length, open: dlg.open, toast });
52 } catch (e) { return JSON.stringify({ error: String(e && e.stack || e) }); }
53 })()`;
54
55 describe.skipIf(chromium === undefined)("the palette's tell row", () => {
56 let dataDir: string;
57 let app: App;
58 let servers: Servers;
59 let cookies: { name: string; value: string }[] = [];
60
61 beforeAll(async () => {
62 dataDir = await mkdtemp(join(tmpdir(), "forge-palette-tell-"));
63 app = createApp({ dataDir, port: 0 });
64 servers = await serve(app);
65 const made = await createUser(app.db, {
66 origin: "seed",
67 trusted: true,
68 username: "keeper",
69 email: "[email protected]",
70 password: "a-good-passphrase",
71 adminIfFirst: true,
72 });
73 if (!made.ok) throw new Error(made.error);
74 promote(app.db, made.value);
75 cookies = [{ name: "forge_session", value: createSession(app.db, made.value.id).token }];
76 const repo = await createRepo(app, made.value, { name: "garden", visibility: "public" });
77 if (!repo.ok) throw new Error("repo");
78 const seeded = await commitToBranch(app, made.value, repo.value, {
79 message: "seed",
80 files: [{ path: "README.md", content: "# garden\n" }],
81 });
82 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
83 }, 30_000);
84
85 afterAll(async () => {
86 servers.stop();
87 app.close();
88 await rm(dataDir, { recursive: true, force: true });
89 });
90
91 test("on a repository page, typing a sentence and picking the last row tells the crew from that page", async () => {
92 const said = "make the garden gate green";
93 const out = JSON.parse(
94 await evaluateLoaded(
95 chromium!,
96 `${servers.url}/keeper/garden`,
97 { width: 1280, height: 800 },
98 cookies,
99 drive(said, true),
100 ),
101 );
102 expect(out.error).toBeUndefined();
103 expect(out.tellRow).toBe(`Tell the crew: ${said}`);
104 expect(out.open).toBe(false);
105 expect(out.toast.link).toMatch(/^\/keeper\/garden\/issues\/\d+$/);
106 const issue = app.db
107 .query("SELECT title, body FROM issue WHERE title LIKE ?1")
108 .get(`%${said}%`) as { title: string; body: string } | null;
109 expect(issue).not.toBeNull();
110 expect(issue!.body).toContain("Told from [/keeper/garden](/keeper/garden)");
111 }, 30_000);
112
113 test("under three characters there is no tell row", async () => {
114 const out = JSON.parse(
115 await evaluateLoaded(chromium!, `${servers.url}/keeper/garden`, { width: 1280, height: 800 }, cookies, drive("ga", false)),
116 );
117 expect(out.error).toBeUndefined();
118 expect(out.tellRow).toBeNull();
119 }, 30_000);
120
121 test("signed out, the row is not drawn and the page carries no tell target", async () => {
122 const out = JSON.parse(
123 await evaluateLoaded(chromium!, `${servers.url}/keeper/garden`, { width: 1280, height: 800 }, [], drive("make the garden gate green", false)),
124 );
125 expect(out.error).toBeUndefined();
126 expect(out.tellRow).toBeNull();
127 const html = await (await fetch(`${servers.url}/keeper/garden`)).text();
128 expect(html).not.toContain('"tell":');
129 }, 30_000);
130 });
131
132 describe("the tell the palette posts", () => {
133 test("an empty tell answers in the action's own words, as JSON", async () => {
134 const dataDir = await mkdtemp(join(tmpdir(), "forge-palette-tell-"));
135 const app = createApp({ dataDir, port: 0 });
136 const servers = await serve(app);
137 try {
138 const made = await createUser(app.db, {
139 origin: "seed",
140 trusted: true,
141 username: "keeper",
142 email: "[email protected]",
143 password: "a-good-passphrase",
144 adminIfFirst: true,
145 });
146 if (!made.ok) throw new Error(made.error);
147 promote(app.db, made.value);
148 const cookie = `forge_session=${createSession(app.db, made.value.id).token}`;
149 const res = await fetch(`${servers.url}/tell`, {
150 method: "POST",
151 headers: { cookie, accept: "application/json" },
152 body: new URLSearchParams({ app: "forge", text: " ", from: "/" }),
153 });
154 expect(res.status).toBe(422);
155 const body = (await res.json()) as { ok: boolean; error: string };
156 expect(body.ok).toBe(false);
157 expect(body.error.length).toBeGreaterThan(0);
158 const index = await (await fetch(`${servers.url}/`, { headers: { cookie } })).text();
159 expect(index).toContain('"tell":{"app":"forge"}');
160 } finally {
161 servers.stop();
162 app.close();
163 await rm(dataDir, { recursive: true, force: true });
164 }
165 }, 30_000);
166 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs