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

Refused feed replies and review-line comments keep the typed text #16810

Merged opened this

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

Merged

scout/forge:scout/16272-refused-feed-replies-and-review-line-com → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/16272-refused-feed-replies-and-review-line-com was merged into main as d51db8b.

Review

Sign in to review this change.
7 files changed +182 −104
docs/features/feed-reply.md +1 −1
@@ -8,7 +8,7 @@ On `/feed`, a reply under an issue post is written as a comment on that issue. T
88 `/<owner>/<repo>/issues/<n>/comments` with `back=feed`, so it works with JavaScript off: the page
99 returns to `/feed` saying "Reply posted." (one reload; live insertion without a reload is not done).
1010
11 A refused reply keeps its words (cut to what the flash cookie can carry) in the flash, to copy back.
11 A refused reply (empty, or too long) is drawn in place on the thread with the typed words in the box and the message beside it; an origin refusal still returns to the feed with its flash.
1212
1313 From the terminal: the API `POST /api/v1/repos/<owner>/<repo>/issues/<n>/comments` writes the same
1414 comment; there is no terminal screen for it yet.
src/web/diff-view.ts +28 −12
@@ -22,7 +22,19 @@ import { composeLine } from "./code.ts";
2222 import type { Token } from "./highlight.ts";
2323 import { escapeHtml, html, raw, when, type Html } from "./html.ts";
2424 import { urlPath } from "./pages/explorer.ts";
25 import { btn, card, disclosure, empty, icon, listCard, row, time, userLink } from "./ui.ts";
25 import {
26 btn,
27 card,
28 disclosure,
29 empty,
30 field as formField,
31 icon,
32 listCard,
33 row,
34 time,
35 userLink,
36 } from "./ui.ts";
37 import { kept, type Refused } from "./form.ts";
2638 import { renderMarkdown } from "./markdown.ts";
2739 import { permalink } from "./comments.ts";
2840 import { wordDiff, type Segment } from "./worddiff.ts";
@@ -63,6 +75,8 @@ export interface DiffViewOptions {
6375 marks?: ReadonlyMap<string, Mark>;
6476 /** Render an inline comment form at this anchor (from a `?rc=` link). */
6577 active?: { path: string; side: Side; line: number };
78 /** A refused submit of the active form: its typed words and the message. */
79 refused?: Refused;
6680 /** Base path for comment forms and "+" links, e.g. `/owner/repo/pulls/3`.
6781 * When set, lines become commentable. */
6882 reviewBase?: string;
@@ -340,17 +354,19 @@ function reviewRows(
340354 <input type="hidden" name="path" value="${path}" />
341355 <input type="hidden" name="side" value="${side}" />
342356 <input type="hidden" name="line" value="${line}" />
343 <label class="sr-only" for="rc-text">Comment on this line</label>
344 <textarea
345 class="input"
346 id="rc-text"
347 name="body"
348 rows="3"
349 data-grow
350 placeholder="Comment on this line"
351 required
352 autofocus
353 ></textarea>
357 ${formField(
358 kept(opts.refused, {
359 label: "Comment on this line",
360 labelHidden: true,
361 name: "body",
362 id: "rc-text",
363 type: "textarea",
364 rows: 3,
365 placeholder: "Comment on this line",
366 required: true,
367 autofocus: true,
368 }),
369 )}
354370 <div class="form-actions">
355371 <button
356372 class="btn"
src/web/pages/issues.ts +8 −18
@@ -344,12 +344,11 @@ export async function issuePrivateSubmit(ctx: Ctx): Promise<Response> {
344344
345345 /**
346346 * Where a comment returns to when the form names a fixed word: never a URL
347 * from the form. A refused reply from the feed returns there too, as the
348 * pull's does; one from the board keeps the issue page, where it always went.
347 * from the form. A refused reply is drawn in place on the thread.
349348 */
350 const BACK = new Map<string, { to: string; said: (n: number) => string; refusedTo?: string }>([
349 const BACK = new Map<string, { to: string; said: (n: number) => string }>([
351350 ["board", { to: "/board", said: (n) => `Answered on #${n}. The planner plans again.` }],
352 ["feed", { to: "/feed", said: () => "Reply posted.", refusedTo: "/feed" }],
351 ["feed", { to: "/feed", said: () => "Reply posted." }],
353352 ]);
354353
355354 // POST /:owner/:name/issues/:number/comments
@@ -364,24 +363,15 @@ export async function issueCommentSubmit(ctx: Ctx): Promise<Response> {
364363 // the board. A fixed word, never a URL from the form: no open redirect.
365364 const back = BACK.get(field(form, "back"));
366365 const dest = `${repoBase(found.repo)}/issues/${found.issue.number}`;
367 const refusedTo = back?.refusedTo ?? dest;
368366 const body = field(form, "body");
369 // From the thread's own page the refusal is drawn in place: the words typed
370 // stay in the box and the message sits beside it. A reply from the feed or
371 // the board has no such box here, so it goes back with its flash. The issue
367 // A refusal is drawn in place, from the thread, the feed or the board alike:
368 // the words typed stay in the box and the message sits beside it. The issue
372369 // page is drawn by `tellPage`: it is the one renderer of an issue thread.
373 const inPlace = back === undefined;
374370 const refuse = (why: string): Promise<Response> => {
375371 refuseHere(ctx, refused(form, { body: why }));
376372 return asRefusal(tellPage(ctx));
377373 };
378 if (body.trim() === "")
379 return inPlace
380 ? refuse(COMMENT_EMPTY)
381 : flashTo(ctx, refusedTo, {
382 tone: "danger",
383 message: COMMENT_EMPTY,
384 });
374 if (body.trim() === "") return refuse(COMMENT_EMPTY);
385375 const added = await addCommentThrough(
386376 ctx.app,
387377 ctx.auth.user,
@@ -389,12 +379,12 @@ export async function issueCommentSubmit(ctx: Ctx): Promise<Response> {
389379 found.issue,
390380 body,
391381 );
392 if (!added.ok && inPlace && !originError(added.error))
382 if (!added.ok && !originError(added.error))
393383 return refuse(COMMENT_NOT_POSTED);
394384 if (!added.ok)
395385 return flashTo(
396386 ctx,
397 refusedTo,
387 dest,
398388 // The words are kept, cut to what the cookie can carry, to copy back.
399389 flashKeeping(
400390 { tone: "danger", message: originError(added.error) ?? COMMENT_NOT_POSTED },
src/web/pages/pull.ts +47 −27
@@ -96,7 +96,7 @@ import {
9696 type DiffViewOptions,
9797 type ThreadView,
9898 } from "../diff-view.ts";
99 import { asRefusal, field, readForm, refused, refuseHere } from "../form.ts";
99 import { asRefusal, field, kept, readForm, refused, refuseHere, refusedHere } from "../form.ts";
100100 import { waitingOnTeams } from "../../core/teams_words.ts";
101101 import { teamsHolding, teamVerdicts, type TeamVerdict } from "../../core/issue_teams.ts";
102102 import { html, raw, when, type Html } from "../html.ts";
@@ -1078,8 +1078,14 @@ export async function pullFilesPage(ctx: Ctx): Promise<Response> {
10781078 const unresolved = threads.filter((t) => t.resolvedAt === null).length;
10791079
10801080 // A "?rc=path~side~line" link opens an inline comment form at that row.
1081 // A refused line comment reopens the form at its own line, the words kept.
1082 const refusal = refusedHere(ctx);
10811083 const active = ctx.auth.user
1082 ? parseAnchor(ctx.url.searchParams.get("rc"))
1084 ? parseAnchor(
1085 refusal !== undefined
1086 ? `${field(refusal.form, "path")}~${field(refusal.form, "side")}~${field(refusal.form, "line")}`
1087 : ctx.url.searchParams.get("rc"),
1088 )
10831089 : undefined;
10841090 const diffOptions: DiffViewOptions = {
10851091 syntax,
@@ -1094,6 +1100,7 @@ export async function pullFilesPage(ctx: Ctx): Promise<Response> {
10941100 ? { reviewBase: thread, reviewPage: `${thread}/files` }
10951101 : {}),
10961102 ...(active ? { active } : {}),
1103 ...(active && refusal ? { refused: refusal } : {}),
10971104 };
10981105
10991106 // Nothing viewer-specific is drawn when no comment, thread or form is; then
@@ -1103,6 +1110,24 @@ export async function pullFilesPage(ctx: Ctx): Promise<Response> {
11031110 ? `${diffKey(status.baseOid, status.headOid)}|${diffOptions.fileLinkBase}|${diffOptions.reviewBase ?? ""}|${diffOptions.reviewPage ?? ""}`
11041111 : undefined;
11051112
1113 const diffHtml = keptRender(renderKey, () => renderDiff(diff, diffOptions));
1114 // A refused line comment is drawn by the inline form at its row. When the
1115 // line has no row (no line, a stale anchor, a path not in the diff) nothing
1116 // does, so the message and the typed words are drawn here instead.
1117 const refusalFallback =
1118 refusal !== undefined && !diffHtml.text.includes('id="rc-text"')
1119 ? html`<form class="comment-form" id="rc-refused">${formField(

Non-blocking, first thing next: this form has no action, no hidden path/side/line and no button, so the kept words cannot be resubmitted by keyboard or thumb. Add the Comment button in a form-actions row, or turn it into a note with a link back.

1120 kept(refusal, {
1121 label: "Your review comment",
1122 name: "body",
1123 id: "rc-refused-text",
1124 type: "textarea",
1125 rows: 3,
1126 autofocus: true,
1127 }),
1128 )}</form>`
1129 : null;
1130
11061131 const headRepo = pull.crossRepo
11071132 ? getRepoById(ctx.app.db, pull.headRepoId)
11081133 : undefined;
@@ -1219,7 +1244,7 @@ export async function pullFilesPage(ctx: Ctx): Promise<Response> {
12191244 ${crewActivityCard(ctx, repo, pull)}
12201245 </aside>
12211246 </div>
1222 <div class="mt" id="diff">${keptRender(renderKey, () => renderDiff(diff, diffOptions))}</div>
1247 <div class="mt" id="diff">${refusalFallback}${diffHtml}</div>
12231248 ${liveMount({ repo: base })}`;
12241249
12251250 const response = page({
@@ -1288,16 +1313,13 @@ export async function pullCommentSubmit(ctx: Ctx): Promise<Response> {
12881313 // A reply from the feed returns there: a fixed word, never a URL from the form.
12891314 const fromFeed = field(form, "back") === "feed";
12901315 const bodyText = field(form, "body");
1291 // From the pull's own page the refusal is drawn in place, the typed words
1292 // kept and the message beside the box; from the feed it returns by flash.
1316 // A refusal is drawn in place on the pull, the typed words kept and the
1317 // message beside the box, whether it came from the pull or from the feed.
12931318 const refuse = (why: string): Promise<Response> => {
12941319 refuseHere(ctx, refused(form, { body: why }));
12951320 return asRefusal(pullPage(ctx));
12961321 };
1297 if (bodyText.trim() === "")
1298 return fromFeed
1299 ? flashTo(ctx, "/feed", { tone: "danger", message: COMMENT_EMPTY })
1300 : refuse(COMMENT_EMPTY);
1322 if (bodyText.trim() === "") return refuse(COMMENT_EMPTY);
13011323 const added = await addCommentThrough(
13021324 ctx.app,
13031325 ctx.auth.user,
@@ -1305,7 +1327,7 @@ export async function pullCommentSubmit(ctx: Ctx): Promise<Response> {
13051327 found.pull,
13061328 bodyText,
13071329 );
1308 if (!added.ok && !fromFeed && !originError(added.error))
1330 if (!added.ok && !originError(added.error))
13091331 return refuse(COMMENT_NOT_POSTED);
13101332 if (!added.ok)
13111333 return flashTo(ctx, "/feed", {
@@ -1331,12 +1353,12 @@ export async function pullReviewSubmit(ctx: Ctx): Promise<Response> {
13311353 `${field(form, "path")}~${field(form, "side")}~${field(form, "line")}`,
13321354 );
13331355 const bodyText = field(form, "body");
1334 if (!anchor || bodyText.trim() === "") {
1335 return flashTo(ctx, dest, {
1336 tone: "danger",
1337 message: "That review comment had no line or no text.",
1338 });
1339 }
1356 const refuse = (why: string): Promise<Response> => {
1357 refuseHere(ctx, refused(form, { body: why }));
1358 return asRefusal(pullFilesPage(ctx));
1359 };
1360 if (!anchor) return refuse("That review comment had no line.");
1361 if (bodyText.trim() === "") return refuse("A review comment needs some text.");
13401362 // The line's content hash is computed server-side from the blob the anchor
13411363 // names, so a stale form can never claim a line said something it did not.
13421364 const added = await addReview(
@@ -1352,17 +1374,15 @@ export async function pullReviewSubmit(ctx: Ctx): Promise<Response> {
13521374 },
13531375 );
13541376 if (!added.ok) {
1355 return flashTo(ctx, dest, {
1356 tone: "danger",
1357 message:
1358 added.error === "bad_anchor"
1359 ? "That line is no longer part of this diff."
1360 : added.error === "empty_body"
1361 ? "A review comment needs some text."
1362 : added.error === "body_too_long"
1363 ? "That review comment is too long (64 KB at most)."
1364 : "That review comment could not be saved.",
1365 });
1377 return refuse(
1378 added.error === "bad_anchor"
1379 ? "That line is no longer part of this diff."
1380 : added.error === "empty_body"
1381 ? "A review comment needs some text."
1382 : added.error === "body_too_long"
1383 ? "That review comment is too long (64 KB at most)."
1384 : "That review comment could not be saved.",
1385 );
13661386 }
13671387 // It lands on the comment itself (`diff-view.ts`: `rc-<id>`), the address it now has.
13681388 return flashTo(ctx, `${dest}#rc-${added.value.id}`, {
test/comment-forms-refused.test.ts +5 −4
@@ -156,10 +156,11 @@ test("an origin refusal still redirects with its flash, not an in-place page", a
156156 });
157157
158158 for (const kind of ["issues", "pulls"] as const) {
159 test(`${kind}: a blank reply from the feed still redirects to /feed with a flash`, async () => {
159 test(`${kind}: a blank reply from the feed is drawn in place, not redirected`, async () => {
160160 const res = await post(`${kind}/${kind === "issues" ? issueNumber : pullNumber}`, { body: " ", back: "feed" });
161 expect(res.status).toBe(303);
162 expect(new URL(res.headers.get("location")!, servers.url).pathname).toBe("/feed");
163 expect(decodeURIComponent(res.headers.getSetCookie().join(";"))).toContain(COMMENT_EMPTY);
161 expect(res.status).toBe(422);
162 const page = await res.text();
163 expect(page).toContain(COMMENT_EMPTY);
164 expect(page).toContain('aria-invalid="true"');
164165 });
165166 }
test/feed-reply-comment.test.ts +11 −19
@@ -91,30 +91,22 @@ test("a reply sent from another origin is refused and writes nothing", async ()
9191 expect(listComments(app.db, issueId)).toHaveLength(before);
9292 });
9393
94 test("a refused reply returns to the feed with its words kept to copy", async () => {
94 test("a refused reply is drawn in place with its words kept in the box", async () => {
9595 const long = "x".repeat(70_000);
9696 const res = await send({ body: long, back: "feed" });
97 expect(res.status).toBe(303);
98 expect(new URL(res.headers.get("location")!, servers.url).pathname).toBe("/feed");
99 const set = res.headers.getSetCookie().find((c) => c.startsWith("forge_flash=")) ?? "";
100 const flash = JSON.parse(decodeURIComponent(set.slice("forge_flash=".length).split(";")[0]!));
101 expect(flash.tone).toBe("danger");
102 expect(flash.code).toBe("x".repeat(512));
97 expect(res.status).toBe(422);
98 const page = await res.text();
99 expect(page).toContain('aria-invalid="true"');
100 expect(page).toContain("x".repeat(1000));
103101 });
104102
105 test("kept words with newlines, quotes and non-ASCII still leave a readable danger flash", async () => {
106 const long = '"é\n日本'.repeat(14_000);
103 test("kept words with newlines, quotes and non-ASCII come back whole, escaped", async () => {
104 const long = '"é\n日本<b>'.repeat(14_000);
107105 const res = await send({ body: long, back: "feed" });
108 expect(res.status).toBe(303);
109 const set = res.headers.getSetCookie().find((c) => c.startsWith("forge_flash=")) ?? "";
110 const raw = set.slice("forge_flash=".length).split(";")[0]!;
111 expect(raw.length).toBeLessThanOrEqual(2000);
112 const flash = JSON.parse(decodeURIComponent(raw));
113 expect(flash.tone).toBe("danger");
114 expect(flash.message).not.toBe("");
115 expect(long.startsWith(flash.code)).toBe(true);
116 const page = await fetch(`${servers.url}/feed`, { headers: { cookie: `${cookie}; forge_flash=${raw}` } });
117 expect(await page.text()).toContain(flash.message.slice(0, 20));
106 expect(res.status).toBe(422);
107 const page = await res.text();
108 expect(page).toContain("é\n日本&lt;b&gt;");
109 expect(page).not.toContain("日本<b>");
118110 });
119111
120112 test("a good reply from the feed returns to /feed and says Reply posted", async () => {
test/feed-reply.test.ts +82 −23
@@ -206,10 +206,10 @@ test("a post linking to a thread in another repository offers no Reply", () => {
206206 expect(cardOf({ app: "alice/secret" })).not.toContain("/comments");
207207 });
208208
209 test("an empty reply on an issue returns to the feed with a danger flash", async () => {
209 test("an empty reply on an issue is drawn in place with the field marked, not redirected", async () => {
210210 const res = await post(`/alice/open/issues/${publicIssue}/comments`, aliceCookie, { body: " ", back: "feed" });
211 expect(new URL(res.headers.get("location")!, servers.url).pathname).toBe("/feed");
212 expect(flashOf(res).tone).toBe("danger");
211 expect(res.status).toBe(422);
212 expect(await res.text()).toContain('aria-invalid="true"');
213213 });
214214
215215 test("an empty comment from the issue page is drawn again in place, the field marked", async () => {
@@ -237,10 +237,10 @@ test("a reply on a pull comments on it and returns to the feed with a flash", as
237237 expect(listComments(app.db, pullId).map((c) => c.body)).toContain("Looks good.");
238238 });
239239
240 test("an empty reply on a pull returns to the feed with a danger flash", async () => {
240 test("an empty reply on a pull is drawn in place with the field marked, not redirected", async () => {
241241 const res = await post(`/alice/open/pulls/${pullNumber}/comments`, aliceCookie, { body: " ", back: "feed" });
242 expect(new URL(res.headers.get("location")!, servers.url).pathname).toBe("/feed");
243 expect(flashOf(res).tone).toBe("danger");
242 expect(res.status).toBe(422);
243 expect(await res.text()).toContain('aria-invalid="true"');
244244 });
245245
246246 test("a pull comment with an unknown back returns to the pull page", async () => {
@@ -263,24 +263,83 @@ test("a back that is not the feed's word goes nowhere new", async () => {
263263 expect(new URL(res.headers.get("location")!, servers.url).pathname).toBe(`/alice/open/issues/${publicIssue}`);
264264 });
265265
266 test("an over-long reply is refused with a danger flash, keeps the feed as its place and posts nothing", async () => {
267 const before = listComments(app.db, publicId).length;
268 const res = await post(`/alice/open/issues/${publicIssue}/comments`, aliceCookie, {
269 body: "x".repeat(70_000),
270 back: "feed",
271 });
272 expect(new URL(res.headers.get("location")!, servers.url).pathname).toBe("/feed");
273 expect(flashOf(res).tone).toBe("danger");
274 expect(listComments(app.db, publicId)).toHaveLength(before);
275 });
266 /** A refused reply keeps the typed words, escaped, in the textarea. */
267 const typedIn = (page: string, typed: string, id = ""): void => {
268 const at = id === "" ? page.indexOf("<textarea") : page.indexOf(`id="${id}"`);
269 const box = page.slice(at, page.indexOf("</textarea>", at));
270 expect(box).toContain(typed.replace(/</g, "&lt;").replace(/>/g, "&gt;"));
271 expect(page).not.toContain(typed);
272 expect(page).toContain('aria-invalid="true"');
273 };
274 const hostile = `<script>alert(1)</script>${"x".repeat(70_000)}`;
276275
277 test("an over-long reply on a pull is refused and posts nothing", async () => {
278 const before = listComments(app.db, pullId).length;
279 const res = await post(`/alice/open/pulls/${pullNumber}/comments`, aliceCookie, {
280 body: "x".repeat(70_000),
281 back: "feed",
276 for (const back of ["feed", "board"]) {
277 test(`an over-long ${back} reply on an issue answers 422 with the typed text in the box, escaped`, async () => {
278 const before = listComments(app.db, publicId).length;
279 const res = await post(`/alice/open/issues/${publicIssue}/comments`, aliceCookie, { body: hostile, back });
280 expect(res.status).toBe(422);
281 typedIn(await res.text(), "<script>alert(1)</script>", "comment-body");
282 expect(listComments(app.db, publicId)).toHaveLength(before);
282283 });
283 expect(new URL(res.headers.get("location")!, servers.url).pathname).toBe("/feed");
284 expect(flashOf(res).tone).toBe("danger");
284 }
285
286 test("an over-long reply on a pull answers 422 with the typed text in the box, escaped", async () => {
287 const before = listComments(app.db, pullId).length;
288 const res = await post(`/alice/open/pulls/${pullNumber}/comments`, aliceCookie, { body: hostile, back: "feed" });
289 expect(res.status).toBe(422);
290 typedIn(await res.text(), "<script>alert(1)</script>", "comment-body");
285291 expect(listComments(app.db, pullId)).toHaveLength(before);
286292 });
293
294 test("a refused review-line comment reopens the form at its line with the typed text, escaped", async () => {
295 const res = await post(`/alice/open/pulls/${pullNumber}/review`, aliceCookie, {
296 path: "idea.md",
297 side: "new",
298 line: "1",
299 body: hostile,
300 });
301 expect(res.status).toBe(422);
302 const page = await res.text();
303 expect(page).toContain('id="rc-text"');
304 typedIn(page, "<script>alert(1)</script>", "rc-text");
305 });
306
307 /** Each refusal of a review-line comment shows its message and the typed words. */
308 const review = (over: Record<string, string>) =>
309 post(`/alice/open/pulls/${pullNumber}/review`, aliceCookie, {
310 path: "idea.md",
311 side: "new",
312 line: "1",
313 body: "my <b>words</b>",
314 ...over,
315 });
316
317 test("a review comment with a blank body answers 422 with its message", async () => {
318 const res = await review({ body: " " });
319 expect(res.status).toBe(422);
320 expect(await res.text()).toContain("A review comment needs some text.");
321 });
322
323 test("a review comment with no line answers 422 with the message and the words kept", async () => {
324 const res = await review({ line: "" });
325 expect(res.status).toBe(422);
326 const page = await res.text();
327 expect(page).toContain("That review comment had no line.");
328 typedIn(page, "my <b>words</b>", "rc-refused-text");
329 });
330
331 test("a review comment on a stale anchor answers 422 with the message and the words kept", async () => {
332 const res = await review({ line: "9999" });
333 expect(res.status).toBe(422);
334 const page = await res.text();
335 expect(page).toContain("That line is no longer part of this diff.");
336 typedIn(page, "my <b>words</b>", "rc-refused-text");
337 });
338
339 test("a review comment on a path not in the diff answers 422 with the message and the words kept", async () => {
340 const res = await review({ path: "nowhere.md" });
341 expect(res.status).toBe(422);
342 const page = await res.text();
343 expect(page).toContain("That line is no longer part of this diff.");
344 typedIn(page, "my <b>words</b>", "rc-refused-text");
345 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs