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

A tell that is refused for length or emptiness keeps what was typed and names the limit #13610

Merged opened this

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

Merged

scout/forge:scout/13587-a-tell-that-is-refused-for-length-or-emp → main 4 commits fork 3 threads · 3 unresolved

  • Merged. scout/13587-a-tell-that-is-refused-for-length-or-emp was merged into main as 88a2c85.

Review

Sign in to review this change.
10 files changed +245 −35
docs/features/share-tell.md +4
@@ -17,3 +17,7 @@ is first), and confirm with `y` or Enter on Send. `n` or Esc files nothing.
1717
1818 Code: `src/web/share_target.ts` (contract and refusal), `src/web/studio/share_tell.ts`
1919 (page), `src/tui/screens/share_tell.ts` (terminal), `src/core/last_told.ts` (last told).
20
21 ## A tell refused for length or emptiness (#13587)
22
23 An empty tell, or one over 2,000 characters (`TELL_MAX`), answers 422 with the form again, the words still in the box and one sentence naming the limit; nothing is filed and a share token is not used up. The share sheet's `GET /tell` does the same. The terminal's share screen reads the same sentence from `refuseTell` (`src/web/share_target.ts`).
src/web/share_target.ts +15 −3
@@ -18,6 +18,18 @@ export const SHARE_TARGET = { action: "/tell", method: "GET", params: SHARE_PARA
1818 /** The longest tell the composer takes (its textarea's `maxlength`). */
1919 export const TELL_MAX = 2000;
2020
21 /**
22 * Why these words cannot be a tell, in one sentence naming the limit, or undefined when they can:
23 * nothing but whitespace, or longer than TELL_MAX. Every door that takes a tell asks this first.
24 */
25 export function refuseTell(text: string): string | undefined {
26 const max = TELL_MAX.toLocaleString("en-US");
27 if (text.trim() === "") return `Nothing to tell yet: write something, up to ${max} characters.`;
28 if (text.length > TELL_MAX)
29 return `That is too long: a tell takes at most ${max} characters and this one has ${text.length.toLocaleString("en-US")}, so none of it was sent.`;
30 return undefined;
31 }
32
2133 const NOT_WEB = "That share's link is not a web address (http or https), so it was not kept.";
2234
2335 /**
@@ -27,14 +39,14 @@ const NOT_WEB = "That share's link is not a web address (http or https), so it w
2739 export function refuseShare(params: URLSearchParams | Params): string | undefined {
2840 const get = (k: string) => (params.get(k) ?? "").trim();
2941 const title = get(SHARE_PARAMS.title), text = get(SHARE_PARAMS.text), url = get(SHARE_PARAMS.url);
30 if (title === "" && text === "" && url === "") return "Nothing came through with that share: no title, text or link.";
42 if (title === "" && text === "" && url === "") return refuseTell("");
3143 if (url !== "" && !URL.canParse(url)) return NOT_WEB;
3244 if (url !== "") {
3345 const protocol = new URL(url).protocol;
3446 if (protocol !== "http:" && protocol !== "https:") return NOT_WEB;
3547 }
36 if (sharedDraft(params).length > TELL_MAX)
37 return `That share is too long: a tell takes at most ${TELL_MAX.toLocaleString("en-US")} characters, and this one is longer, so none of it was kept.`;
48 const long = refuseTell(sharedDraft(params));
49 if (long !== undefined) return long;
3850 return undefined;
3951 }
4052
src/web/studio/actions.ts +9 −2
@@ -9,7 +9,7 @@
99 */
1010
1111 import type { Routed } from "../../crew/route.ts";
12 import { COMPOSER_FIELDS, claimShare, releaseShare } from "../share_target.ts";
12 import { COMPOSER_FIELDS, claimShare, refuseTell, releaseShare } from "../share_target.ts";
1313 import { mayView } from "../../core/sealed.ts";
1414 import { holdPull, releasePull } from "../../actions/holds.ts";
1515 import { addComment } from "../../actions/issues.ts";
@@ -30,10 +30,11 @@ import { crumbsFor, loadRepo, notFoundPage, pageHead, repoBase, signInFirst } fr
3030 import { teamHoldRefusal } from "../../core/teams_words.ts";
3131 import { guardedRefusal } from "../../crew/stranger.ts";
3232 import type { Guarded } from "../../core/pulls.ts";
33 import { backTo, field, readForm, type Form } from "../form.ts";
33 import { backTo, field, prefersJson, readForm, type Form } from "../form.ts";
3434 import { isLocalPath } from "../flash.ts";
3535 import { html } from "../html.ts";
3636 import { flashOrJson, flashTo, page } from "../layout.ts";
37 import { tellRefusedPage } from "./tell_refused.ts";
3738 import { crewCanRun, NO_CREDIT_WORDS } from "./crew_key.ts";
3839 import { FORGE_TARGET, NEW_APP_TARGET } from "./feed.ts";
3940 import { AUTONOMY_FAILED_WORDS, firstAsk } from "../../actions/first_ask.ts";
@@ -232,6 +233,12 @@ export async function composerSubmit(ctx: Ctx): Promise<Response> {
232233 // given back unless the tell was made (so a failed post can be retried).
233234 const once = field(form, COMPOSER_FIELDS.once);
234235 const userId = ctx.auth.user.id;
236 // Empty or over the limit: said before anything is claimed or made, the words kept in the box.
237 const words = refuseTell(field(form, COMPOSER_FIELDS.text));
238 if (words !== undefined) {
239 if (prefersJson(ctx)) return flashOrJson(ctx, home, { tone: "danger", message: words });
240 return tellRefusedPage(ctx, { text: field(form, COMPOSER_FIELDS.text), app: target, back: home, once, from: field(form, "from") }, words);
241 }
235242 if (once !== "") {
236243 const claim = claimShare(userId, once);
237244 if (claim === "bad") return flashOrJson(ctx, home, { tone: "danger", message: "That share could not be sent." }, { href: home });
src/web/studio/share_tell.ts +17 −12
@@ -13,7 +13,8 @@ import { signInFirst } from "../chrome.ts";
1313 import { html, type Html } from "../html.ts";
1414 import { page } from "../layout.ts";
1515 import { btn } from "../ui.ts";
16 import { COMPOSER_FIELDS, TELL_MAX, refuseShare, sharedDraft, shareToken } from "../share_target.ts";
16 import { tellForm } from "./tell_form.ts";
17 import { COMPOSER_FIELDS, refuseShare, refuseTell, sharedDraft, shareToken } from "../share_target.ts";
1718 import { writableAppsOf } from "./asks.ts";
1819 import { FORGE_TARGET, NEW_APP_TARGET } from "./feed.ts";
1920 import { lastTold, TOLD_FORGE } from "../../core/last_told.ts";
@@ -29,7 +30,11 @@ export function shareTellPage(ctx: Ctx): Response {
2930 const user = ctx.auth.user;
3031 const params = ctx.url.searchParams;
3132 const refusal = refuseShare(params);
32 if (refusal !== undefined) {
33 const draft = sharedDraft(params);
34 // Empty or too long: the form again, the words kept, 422. Any other refusal (a bad link) is a
35 // dead end.
36 const tellRefusal = refuseTell(draft);
37 if (refusal !== undefined && refusal !== tellRefusal) {
3338 return done(page(
3439 {
3540 ctx,
@@ -39,7 +44,6 @@ export function shareTellPage(ctx: Ctx): Response {
3944 400,
4045 ));
4146 }
42 const draft = sharedDraft(params);
4347 const { repos } = writableAppsOf(ctx, user);
4448 const { ordered, onlyForgeCopy } = appsFirst(ctx.app, repos);
4549 const slug = (r: { ownerName: string; name: string }) => `${r.ownerName}/${r.name}`;
@@ -57,15 +61,16 @@ export function shareTellPage(ctx: Ctx): Response {
5761 </select>`;
5862 return done(page({
5963 ctx,
60 title: "Tell the crew",
64 title: tellRefusal === undefined ? "Tell the crew" : "Tell not sent",
6165 scriptJs: keepJs,
6266 body: html`<h1>Tell the crew</h1>
63 <p class="muted small">Shared from your phone. Nothing is sent until you tap Send.</p>
64 <form class="stack" method="post" action="/tell">
65 <input type="hidden" name="${COMPOSER_FIELDS.back}" value="/feed" />
66 <input type="hidden" name="${COMPOSER_FIELDS.once}" value="${shareToken(user.id, draft)}" />
67 <textarea class="input" name="${COMPOSER_FIELDS.text}" rows="6" maxlength="${String(TELL_MAX)}" required aria-label="Tell the crew" data-keep>${draft}</textarea>
68 <div class="bar">${target}<span class="spacer"></span>${btn("Send", { variant: "primary" })}</div>
69 </form>`,
70 }));
67 ${tellRefusal === undefined ? html`<p class="muted small">Shared from your phone. Nothing is sent until you tap Send.</p>` : html``}
68 ${tellForm({
69 text: draft,
70 refusal: tellRefusal,
71 aside: target,
72 hidden: html`<input type="hidden" name="${COMPOSER_FIELDS.back}" value="/feed" />
73 <input type="hidden" name="${COMPOSER_FIELDS.once}" value="${shareToken(user.id, draft)}" />`,
74 })}`,
75 }, tellRefusal === undefined ? 200 : 422));
7176 }
src/web/studio/tell_form.ts added +22
@@ -0,0 +1,22 @@
1 /**
2 * The tell form, written once: the words in the box, the hidden fields and the target the caller
3 * brings, and, when the tell was refused (#13587), the one sentence naming the limit. That sentence
4 * has an id the box points at (aria-describedby, aria-invalid) and the box takes focus, because a
5 * role=alert present on load is not reliably announced.
6 */
7 import { html, type Html } from "../html.ts";
8 import { btn } from "../ui.ts";
9 import { COMPOSER_FIELDS, TELL_MAX } from "../share_target.ts";
10
11 export function tellForm(opts: { text: string; hidden: Html; aside?: Html; refusal?: string | undefined }): Html {
12 const refused = opts.refusal !== undefined;
13 const limits = refused ? html`` : html`maxlength="${String(TELL_MAX)}" required`;
14 const flags = refused ? html`autofocus aria-invalid="true" aria-describedby="tell-refusal"` : html``;
15 const sentence = refused ? html`<p id="tell-refusal" role="alert" data-tell-refused>${opts.refusal ?? ""}</p>` : html``;
16 return html`${sentence}
17 <form class="stack" method="post" action="/tell">
18 ${opts.hidden}
19 <textarea class="input" name="${COMPOSER_FIELDS.text}" rows="6" ${limits} ${flags} aria-label="Tell the crew" data-keep>${opts.text}</textarea>
20 <div class="bar">${opts.aside ?? html``}<span class="spacer"></span>${btn("Send", { variant: "primary" })}</div>
21 </form>`;
22 }
src/web/studio/tell_refused.ts added +32
@@ -0,0 +1,32 @@
1 /**
2 * A tell refused for being empty or over TELL_MAX (#13587): the form again, what was typed still in
3 * the box, and one sentence naming the limit, with status 422. The words are output, so they are
4 * escaped by `html`; the target, back path and share token are carried as hidden fields.
5 */
6 import type { Ctx } from "../../http/context.ts";
7 import { html } from "../html.ts";
8 import { page } from "../layout.ts";
9 import { keepJs } from "../keep.ts";
10 import { COMPOSER_FIELDS } from "../share_target.ts";
11 import { tellForm } from "./tell_form.ts";
12 import { isLocalPath } from "../flash.ts";
13
14 export function tellRefusedPage(ctx: Ctx, kept: { text: string; app: string; back: string; once: string; from: string }, words: string): Response {
15 const back = isLocalPath(kept.back) ? kept.back : "/";
16 return page(
17 {
18 ctx,
19 title: "Tell not sent",
20 scriptJs: keepJs,
21 body: html`<h1>Tell the crew</h1>${tellForm({
22 text: kept.text,
outdated

Give this an id and point the textarea at it with aria-describedby and aria-invalid; role=alert on load is not reliably read.

23 refusal: words,
24 hidden: html`<input type="hidden" name="${COMPOSER_FIELDS.back}" value="${back}" />
25 ${kept.app === "" ? "" : html`<input type="hidden" name="${COMPOSER_FIELDS.app}" value="${kept.app}" />`}
26 ${kept.once === "" ? "" : html`<input type="hidden" name="${COMPOSER_FIELDS.once}" value="${kept.once}" />`}
27 ${kept.from === "" ? "" : html`<input type="hidden" name="from" value="${kept.from}" />`}`,
28 })}`,
outdated

Add autofocus so the keyboard lands in the kept words, plus aria-describedby/aria-invalid.

29 },
outdated

Principle 1: this repeats the limit the alert already names. Remove it.

30 422,
31 );
32 }
test/first-ask-new-app.test.ts +7 −7
@@ -6,8 +6,7 @@
66
77 import { afterAll, beforeAll, expect, test } from "bun:test";
88 import { listIssues, MAX_BODY } from "../src/core/issues.ts";
9 import { TOO_LONG_WORDS } from "../src/actions/tell.ts";
10 import { FORGE_REPO_WORDS, SAY_SOMETHING_WORDS } from "../src/actions/tell_words.ts";
9 import { FORGE_REPO_WORDS } from "../src/actions/tell_words.ts";
1110 import { listReposOwnedBy } from "../src/core/repos.ts";
1211 import { autonomyStatus } from "../src/crew/autonomy.ts";
1312 import { listCrewRoles } from "../src/core/agents.ts";
@@ -52,7 +51,8 @@ test("the first tell makes one app, files one open issue on it, keeps no thought
5251 // The forge's included credit lets the crew run: the new app starts autonomous (box 2).
5352 expect(crewCanRun(forge.child)).toBe(true);
5453 expect(repo.autonomy).toBe("autonomous");
55 // Autonomy is on as the asker and a builder and reviewer are seated: the tick does not pause (#11508).
54 // Autonomy is on as the asker and a builder and reviewer are seated: the tick does not pause
55 // (#11508).
5656 expect(repo.autonomyBy).toBe(maria.id);
5757 expect(autonomyStatus(forge.child, repo).paused).toBeNull();
5858 expect(listCrewRoles(db, repo.id).map((c) => c.role).sort()).toEqual(["builder", "reviewer"]);
@@ -89,8 +89,8 @@ test("an empty ask makes no app and says so", async () => {
8989 const db = forge.child.db;
9090 const before = listReposOwnedBy(db, getUserByName(db, "maria")!.id).length;
9191 const res = await forge.post(forge.owner, "/tell", { app: "new-app", text: " " });
92 expect(res.status).toBe(303);
93 expect(flashOf(res)).toContain(SAY_SOMETHING_WORDS);
92 expect(res.status).toBe(422);
93 expect(decodeURIComponent(await res.text()).replace(/&#39;|&apos;/g, "'")).toContain("Nothing to tell yet");
9494 expect(listReposOwnedBy(db, getUserByName(db, "maria")!.id).length).toBe(before);
9595 });
9696
@@ -98,8 +98,8 @@ test("an over-long ask makes no app and says so", async () => {
9898 const db = forge.child.db;
9999 const before = listReposOwnedBy(db, getUserByName(db, "maria")!.id).length;
100100 const res = await forge.post(forge.owner, "/tell", { app: "new-app", text: "zebra ".repeat(MAX_BODY) });
101 expect(res.status).toBe(303);
102 expect(flashOf(res)).toContain(TOO_LONG_WORDS);
101 expect(res.status).toBe(422);
102 expect(decodeURIComponent(await res.text()).replace(/&#39;|&apos;/g, "'")).toContain("That is too long: a tell takes at most");
103103 expect(listReposOwnedBy(db, getUserByName(db, "maria")!.id).length).toBe(before);
104104 });
105105
test/share-target-tell.test.ts +11 −10
@@ -87,16 +87,17 @@ test("the last repository told is the one chosen", async () => {
8787 });
8888
8989 test("a share that cannot be a tell is refused with a sentence", async () => {
90 const cases: [Record<string, string>, RegExp][] = [
91 [{ title: " " }, /Nothing came through/],
92 [{ text: "x".repeat(2001) }, /too long/],
93 [{ title: "t", url: "javascript:alert(1)" }, /not a web address/],
94 [{ title: "t", url: "ftp://example.com/" }, /not a web address/],
95 [{ title: "t", url: "not a url" }, /not a web address/],
90 const cases: [Record<string, string>, RegExp, number][] = [
91 [{ title: " " }, /Nothing to tell yet/, 422],
92 [{ text: "x".repeat(2001) }, /too long/, 422],
93 [{ title: "t", url: "javascript:alert(1)" }, /not a web address/, 400],
94 [{ title: "t", url: "ftp://example.com/" }, /not a web address/, 400],
95 [{ title: "t", url: "not a url" }, /not a web address/, 400],
9696 ];
97 for (const [fields, words] of cases) {
97 for (const [fields, words, status] of cases) {
9898 const res = await share(fields);
99 expect(res.status).toBe(400);
99 // Empty and too long keep the form (422, #13587); a bad link is a dead end (400).
100 expect(res.status).toBe(status);
100101 const out = await res.text();
101102 expect(out).toMatch(words);
102103 expect(out).not.toContain("at /");
@@ -136,8 +137,8 @@ test("where the last tell went decides: a tell to the forge after an issue choos
136137
137138 test("a share the composer cannot hold whole is refused, not cut", async () => {
138139 const res = await share({ text: "y".repeat(2001) });
139 expect(res.status).toBe(400);
140 expect(await res.text()).toContain("none of it was kept");
140 expect(res.status).toBe(422);
141 expect(await res.text()).toContain("none of it was sent");
141142 const ok = await (await share({ text: "y".repeat(2000) })).text();
142143 expect(ok).toContain("y".repeat(2000));
143144 });
test/share-tell-tui.test.ts +1 −1
@@ -17,7 +17,7 @@ test("a typed share: a trailing link is the link, the rest the text", () => {
1717 const p = parseShare("look at this https://example.com/a");
1818 expect(p.get("url")).toBe("https://example.com/a");
1919 expect(p.get("text")).toBe("look at this");
20 expect(refuseShare(parseShare(" "))).toMatch(/Nothing came through/);
20 expect(refuseShare(parseShare(" "))).toMatch(/Nothing to tell yet/);
2121 expect(refuseShare(parseShare("go javascript:alert(1)"))).toMatch(/not a web address/);
2222 expect(refuseShare(parseShare("x ".repeat(1500)))).toMatch(/too long/);
2323 });
test/tell-refused.test.ts added +127
@@ -0,0 +1,127 @@
1 /** A tell refused for emptiness or length keeps what was typed and names the limit (#13587). */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { createUser } from "../src/core/users.ts";
8 import { serve, type Servers } from "../src/http/server.ts";
9 import { TELL_MAX, forgetShares } from "../src/web/share_target.ts";
10 import { quietLogs } from "./helpers/globals.ts";
11
12 quietLogs();
13
14 let dataDir: string;
15 let app: App;
16 let servers: Servers;
17 let cookie = "";
18
19 beforeAll(async () => {
20 dataDir = await mkdtemp(join(tmpdir(), "forge-tell-refused-"));
21 app = createApp({ dataDir, port: 0, host: "forge.test" });
22 servers = await serve(app);
23 const made = await createUser(app.db, {
24 origin: "seed", trusted: true, username: "alice", email: "[email protected]",
25 password: "a-good-passphrase", adminIfFirst: true,
26 });
27 if (!made.ok) throw new Error(made.error);
28 const res = await fetch(`${servers.url}/signin`, {
29 method: "POST",
30 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
31 redirect: "manual",
32 });
33 cookie = (res.headers.get("set-cookie") ?? "").split(";")[0]!;
34 }, 120_000);
35
36 afterAll(async () => {
37 servers.stop();
38 app.close();
39 await rm(dataDir, { recursive: true, force: true });
40 });
41
42 const thoughts = () => app.db.query<{ n: number }, []>("SELECT count(*) AS n FROM thought").get()!.n;
43
44 const post = (fields: Record<string, string>) =>
45 fetch(`${servers.url}/tell`, {
46 method: "POST",
47 headers: { cookie, origin: servers.url },
48 body: new URLSearchParams({ app: "forge", back: "/feed", ...fields }),
49 redirect: "manual",
50 });
51
52 test("an empty tell answers 422, names the limit and files nothing", async () => {
53 const before = thoughts();
54 for (const text of ["", " \n "]) {
55 const res = await post({ text });
56 expect(res.status).toBe(422);
57 const out = await res.text();
58 expect(out).toContain("Nothing to tell yet");
59 expect(out).toContain("2,000 characters");
60 expect(out).toContain('<textarea');
61 }
62 expect(thoughts()).toBe(before);
63 });
64
65 test("a tell over the limit keeps the words, escaped, and names the limit", async () => {
66 const before = thoughts();
67 const text = `<script>alert(1)</script>${"x".repeat(TELL_MAX)}`;
68 const res = await post({ text, once: "0123456789abcdef01234567" });
69 expect(res.status).toBe(422);
70 const out = await res.text();
71 expect(out).toContain("at most 2,000 characters");
72 expect(out).toContain("&lt;script&gt;alert(1)&lt;/script&gt;" + "x".repeat(TELL_MAX));
73 expect(out).not.toContain("<script>alert(1)");
74 expect(out).toContain('name="app" value="forge"');
75 expect(out).toContain('name="once" value="0123456789abcdef01234567"');
76 expect(thoughts()).toBe(before);
77 });
78
79 test("exactly the limit is told", async () => {
80 const before = thoughts();
81 const res = await post({ text: "y".repeat(TELL_MAX) });
82 expect(res.status).toBe(303);
83 expect(thoughts()).toBe(before + 1);
84 });
85
86 test("a refused post does not use up its share token", async () => {
87 forgetShares();
88 const once = "abcdef0123456789abcdef01";
89 expect((await post({ text: "", once })).status).toBe(422);
90 expect((await post({ text: "", once })).status).toBe(422);
91 const before = thoughts();
92 const retry = await post({ text: "now with words", once });
93 expect(retry.status).toBe(303);
94 expect(thoughts()).toBe(before + 1);
95 });
96
97 test("the refusal is announced and the box is pointed at it", async () => {
98 const out = await (await post({ text: "" })).text();
99 expect(out).toContain('id="tell-refusal"');
100 expect(out).toContain('aria-describedby="tell-refusal"');
101 expect(out).toContain('aria-invalid="true"');
102 expect(out).toContain("autofocus");
103 expect(out).not.toContain("At most 2,000 characters.");
104 });
105
106 test("the share-sheet path does the same: 422, the draft kept, the limit named", async () => {
107 const long = await fetch(`${servers.url}/tell?text=${encodeURIComponent("<b>" + "z".repeat(TELL_MAX))}`, { headers: { cookie } });
108 expect(long.status).toBe(422);
109 const out = await long.text();
110 expect(out).toContain("at most 2,000 characters");
111 expect(out).toContain("&lt;b&gt;" + "z".repeat(TELL_MAX));
112 const empty = await fetch(`${servers.url}/tell?title=%20`, { headers: { cookie } });
113 expect(empty.status).toBe(422);
114 expect(await empty.text()).toContain("Nothing to tell yet");
115 const exact = await fetch(`${servers.url}/tell?text=${"z".repeat(TELL_MAX)}`, { headers: { cookie } });
116 expect(exact.status).toBe(200);
117 });
118
119 test("a JSON asker still gets a 422 with the sentence", async () => {
120 const res = await fetch(`${servers.url}/tell`, {
121 method: "POST",
122 headers: { cookie, origin: servers.url, accept: "application/json" },
123 body: new URLSearchParams({ app: "forge", text: "" }),
124 });
125 expect(res.status).toBe(422);
126 expect(((await res.json()) as { error: string }).error).toContain("2,000");
127 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs