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

Ship, decline and say stay on the page they were taken from #15096

Merged opened this

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

Merged

scout/forge:scout/15069-ship-decline-and-say-stay-on-the-page-th → main 3 commits fork 2 threads · 2 unresolved

  • Merged. scout/15069-ship-decline-and-say-stay-on-the-page-th was merged into main as df24793.

Review

Sign in to review this change.
8 files changed +237 −37
src/web/come_back.ts added +30
@@ -0,0 +1,30 @@
1 /**
2 * Where an action returns to: the page it began on. The form's `back` field
3 * when it is a path on this origin, else the Referer when its origin is this
4 * forge's own (`safeBack`; a foreign Referer is ignored), else `fallback`.
5 * The inbox (any query) lands focused on its first decision (`#next-ask`,
6 * a tabindex=-1 target, so no script is needed). It decides where a person lands, never what is
7 * done.
8 */
9 import { safeBack, type Ctx } from "../http/context.ts";
10 import { isLocalPath } from "./flash.ts";
11 import { NEXT_ASK } from "./studio/asks_page.ts";
12 import { field, type Form } from "./form.ts";
13
14 const INBOX = "/asks";
15
16 export function comeBack(ctx: Ctx, form: Form, fallback: string): string {
17 const named = field(form, "back");
18 const ref = safeBack(ctx);
19 const to = isLocalPath(named)
20 ? named
21 : ref !== undefined && isLocalPath(ref)
22 ? ref
outdated

Only the exact /asks gets #needs-you; /asks?x=1 does not (test pins it). Match on the path, keep the query, append the fragment. Also this only scrolls; it does not focus the next decision (box 1).

23 : fallback;
24 const at = to.search(/[?#]/);
25 const path = at < 0 ? to : to.slice(0, at);
26 if (path !== INBOX) return to;
27 // Keep the query; the fragment is ours, so any other is replaced.
28 const rest = at < 0 ? "" : to.slice(at).split("#")[0]!;
29 return `${path}${rest}#${NEXT_ASK}`;
30 }
src/web/pages/issues.ts +3 −1
@@ -5,6 +5,7 @@
55 * Mobile-first, no JavaScript required.
66 */
77
8 import { comeBack } from "../come_back.ts";
89 import { CEILING_REFUSAL, PAUSE_REFUSAL } from "../../core/planner_pause.ts";
910 import {
1011 addCommentThrough,
@@ -409,8 +410,9 @@ export async function issueCommentSubmit(ctx: Ctx): Promise<Response> {
409410 message: "Comment posted, but it could not be marked as a question.",
410411 });
411412 }
413 const returned = comeBack(ctx, form, `${dest}#conversation`);
412414 return back === undefined
413 ? flashTo(ctx, `${dest}#conversation`, { message: "Comment posted." })
415 ? flashTo(ctx, returned, { message: "Comment posted." })
414416 : flashTo(ctx, back.to, {
415417 message: back.said(found.issue.number),
416418 });
src/web/pages/thread.ts +3 −1
@@ -65,6 +65,7 @@ import {
6565 } from "../../core/users.ts";
6666 import type { Ctx } from "../../http/context.ts";
6767 import { commentCard } from "../comments.ts";
68 import { comeBack } from "../come_back.ts";
6869 import { backTo, field, kept, readForm, refusedHere } from "../form.ts";
6970 import { html, raw, when, type Html } from "../html.ts";
7071 import { planCard } from "./plan_card.ts";
@@ -991,7 +992,8 @@ export async function stateSubmit(
991992 if (form instanceof Response) return form;
992993
993994 const wanted = field(form, "state") === "closed" ? "closed" : "open";
994 const dest = backTo(
995 const dest = comeBack(
996 ctx,
995997 form,
996998 `${repoBase(found.repo)}/${kind === "pull" ? "pulls" : "issues"}/${found.issue.number}`,
997999 );
src/web/studio/actions.ts +5 −3
@@ -8,6 +8,7 @@
88 * page that sent them, or JSON when the asks panel asked in place.
99 */
1010
11 import { comeBack } from "../come_back.ts";
1112 import type { Routed } from "../../crew/route.ts";
1213 import { COMPOSER_FIELDS, claimShare, refuseTell, releaseShare } from "../share_target.ts";
1314 import { mayView } from "../../core/sealed.ts";
@@ -332,7 +333,7 @@ export async function shipSubmit(ctx: Ctx): Promise<Response> {
332333 if (!pull || !mayView(ctx.app.db, repo, pull, ctx.auth.user))
333334 return notFoundPage(ctx);
334335 // The inbox and the feed say where they were; the pull page does not.
335 const back = backTo(form, changeHref(base, pull.number));
336 const back = comeBack(ctx, form, changeHref(base, pull.number));
336337 const merged = await mergePull(
337338 ctx.app, ctx.auth.user, repo, pull, "squash", undefined,
338339 // The crew cannot answer a reviewer's changes without credit: an admin's press lands the
@@ -438,13 +439,14 @@ export async function saySubmit(ctx: Ctx): Promise<Response> {
438439 if (!pull || !mayView(ctx.app.db, repo, pull, ctx.auth.user))
439440 return notFoundPage(ctx);
440441 const text = field(form, "text").trim();
442 const back = comeBack(ctx, form, base);
441443 if (text === "")
442 return flashTo(ctx, base, {
444 return flashTo(ctx, back, {
443445 tone: "danger",
444446 message: SAY_SOMETHING_WORDS,
445447 });
446448 const said = addComment(ctx.app, ctx.auth.user, repo, pull, text);
447 return flashOrJson(ctx, base, {
449 return flashOrJson(ctx, back, {
448450 ...(said.ok
449451 ? { message: `Told ${pull.authorName}. It picks the pull request back up.` }
450452 : { tone: "danger" as const, message: "That could not be said." }),
src/web/studio/asks_page.ts +11 −1
@@ -365,6 +365,11 @@ function filterNote(ctx: Ctx, rows: readonly AskRow<Decision>[], hidden: number)
365365 return html`<div id="asks-filters" class="stack">${clear}${picks}</div>`;
366366 }
367367
368 /**
369 * The first decision's id: a fragment that lands focus on it, with no script (`web/come_back.ts`).
370 */
371 export const NEXT_ASK = "next-ask";
372
368373 /** A row and, under it, the chip that mutes its repository (`asksMute`). */
369374 function mutableRow(ctx: Ctx, r: AskRow<Decision>, picked: ReadonlySet<string>): Html {
370375 return html`${rowCard(ctx, r, picked)}
@@ -625,7 +630,12 @@ export function needsYouSection(
625630 const body = html`<section id="needs-you" class="stack">
626631 <h2 id="asks-sentence">${askSentence(count)}</h2>
627632 ${top?.banner ?? null}
628 ${needs.map(forgeCard)} ${asleep.map(asleepCard)} ${first.map((r) => mutableRow(ctx, r, picked))}
633 ${needs.map(forgeCard)} ${asleep.map(asleepCard)}
634 ${first.map((r, i) =>
635 i === 0
636 ? html`<div id="${NEXT_ASK}" class="stack" tabindex="-1">${mutableRow(ctx, r, picked)}</div>`
637 : mutableRow(ctx, r, picked),
638 )}
629639 ${middle.length === 0
630640 ? null
631641 : more(
test/asks-one-pull.test.ts +2 −31
@@ -3,6 +3,7 @@
33 * `only` says exactly what the full read says of that pull, and nothing of
44 * the other pulls or of the repository's own asks (a parked issue).
55 */
6 import { openTopicPull } from "./helpers/open-pull.ts";
67 import { afterAll, beforeAll, expect, test } from "bun:test";
78 import { mkdtemp, rm } from "node:fs/promises";
89 import { tmpdir } from "node:os";
@@ -10,11 +11,9 @@ import { join } from "node:path";
1011 import { createApp, type App } from "../src/app.ts";
1112 import { holdPull } from "../src/actions/holds.ts";
1213 import { addComment, assignIssue, openIssue } from "../src/actions/issues.ts";
13 import { openPull } from "../src/actions/pulls.ts";
1414 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
1515 import type { Pull } from "../src/core/pulls.ts";
1616 import type { Repo } from "../src/core/repos.ts";
17 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
1817 import { createUser, type User } from "../src/core/users.ts";
1918 import { BREAKER_NOTE } from "../src/crew/breaker.ts";
2019 import { scoredFor } from "../src/web/studio/asks.ts";
@@ -28,35 +27,7 @@ let alice: User;
2827 let repo: Repo;
2928 const pulls: Record<"green" | "other" | "assigned" | "held", Pull> = {} as never;
3029
31 async function pull(n: number, green: boolean): Promise<Pull> {
32 const done = await commitToBranch(app, alice, repo, {
33 branch: `topic/${n}`,
34 base: "main",
35 message: `change ${n}`,
36 files: [{ path: `F${n}.md`, content: `${n}\n` }],
37 });
38 if (!done.ok) throw new Error(JSON.stringify(done.error));
39 const opened = await openPull(app, alice, repo, {
40 title: `change ${n}`,
41 body: "",
42 baseBranch: "main",
43 headBranch: `topic/${n}`,
44 });
45 if (!opened.ok) throw new Error(JSON.stringify(opened.error));
46 if (green) {
47 const run = createRun(app.db, {
48 repoId: repo.id,
49 kind: "check",
50 issueId: opened.value.id,
51 env: `pull-${opened.value.number}`,
52 commitOid: opened.value.headOid,
53 reason: "pull",
54 });
55 claimRun(app.db, run.id);
56 finishRun(app.db, run.id, { state: "ok", summary: "check passed" });
57 }
58 return opened.value;
59 }
30 const pull = (n: number, green: boolean): Promise<Pull> => openTopicPull(app, alice, repo, n, green);
6031
6132 beforeAll(async () => {
6233 dataDir = await mkdtemp(join(tmpdir(), "forge-asks-one-pull-"));
test/come-back.test.ts added +145
@@ -0,0 +1,145 @@
1 /**
2 * Ship, decline, say and decide return to the page they began on (#15069):
3 * the inbox lands on its decisions, an issue page stays on its page, and a
4 * Referer from another origin is never followed.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { openIssue } from "../src/actions/issues.ts";
12 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
13 import { getPull } from "../src/core/pulls.ts";
14 import type { Repo } from "../src/core/repos.ts";
15 import { createUser, type User } from "../src/core/users.ts";
16 import { serve, type Servers } from "../src/http/server.ts";
17 import { openTopicPull } from "./helpers/open-pull.ts";
18 import { giveHistory } from "./helpers/history.ts";
19
20 describe("actions return to where they began", () => {
21 let dataDir: string;
22 let app: App;
23 let servers: Servers;
24 let base: string;
25 let alice: User;
26 let repo: Repo;
27 let cookie: string;
28 let n = 0;
29
30 const post = (path: string, body: Record<string, string>, referer?: string) =>
31 fetch(`${base}${path}`, {
32 method: "POST",
33 headers: { cookie, origin: base, ...(referer === undefined ? {} : { referer }) },
34 body: new URLSearchParams(body),
35 redirect: "manual",
36 });
37
38 const newPull = (green = false) => openTopicPull(app, alice, repo, (n += 1), green);
39
40 beforeAll(async () => {
41 dataDir = await mkdtemp(join(tmpdir(), "forge-comeback-"));
42 app = createApp({ dataDir, port: 0 });
43 servers = await serve(app);
44 base = servers.url;
45 const a = await createUser(app.db, {
46 origin: "seed",
47 trusted: true,
48 username: "alice",
49 email: "[email protected]",
50 password: "a-good-passphrase",
51 adminIfFirst: true,
52 });
53 if (!a.ok) throw new Error(a.error);
54 alice = a.value;
55 cookie = (
56 (
57 await fetch(`${base}/signin`, {
58 method: "POST",
59 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
60 redirect: "manual",
61 })
62 ).headers.get("set-cookie") ?? ""
63 ).split(";")[0]!;
64 const made = await createRepo(app, alice, { name: "notes", visibility: "private", description: "" });
65 if (!made.ok) throw new Error(String(made.error));
66 repo = made.value;
67 const seeded = await commitToBranch(app, alice, repo, {
68 message: "Start",
69 files: [{ path: "README.md", content: "hi\n" }],
70 });
71 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
72 giveHistory(app.db, repo.id);
73 }, 60_000);
74
75 afterAll(async () => {
76 servers.stop();
77 app.close();
78 await rm(dataDir, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 });
79 }, 60_000);
80
81 test("ship from the inbox returns to the inbox's decisions", async () => {
82 const pull = await newPull(true);
83 const res = await post(`/alice/notes/pulls/${pull.number}/ship`, {}, `${base}/asks`);
84 expect(res.status).toBe(303);
85 expect(res.headers.get("location")).toBe("/asks#next-ask");
86 expect(getPull(app.db, repo.id, pull.number)?.mergedAt).not.toBeNull();
87 });
88
89 test("ship ignores a cross-origin Referer", async () => {
90 const pull = await newPull(true);
91 const res = await post(`/alice/notes/pulls/${pull.number}/ship`, {}, "https://evil.example/asks");

Pins /asks?x=1 with no fragment, which contradicts the inbox rule. Change with the fix.

92 expect(res.headers.get("location")).toBe(`/alice/notes/pulls/${pull.number}`);
93 expect(getPull(app.db, repo.id, pull.number)?.mergedAt).not.toBeNull();
94 });
95
96 test("a refused ship still returns to the page it began on", async () => {
97 const pull = await newPull(true);
98 await post(`/alice/notes/pulls/${pull.number}/ship`, {});
99 const again = await post(`/alice/notes/pulls/${pull.number}/ship`, {}, `${base}/asks?x=1`);
100 expect(again.status).toBe(303);
101 expect(again.headers.get("location")).toBe("/asks?x=1#next-ask");
102 expect(again.headers.get("set-cookie") ?? "").toContain("already%20merged");
103 });
104
105 test("decline from the inbox returns to the inbox; a cross-origin Referer is ignored", async () => {
106 const pull = await newPull();
107 const res = await post(`/alice/notes/pulls/${pull.number}/state`, { state: "closed" }, `${base}/asks?x=1`);
108 expect(res.headers.get("location")).toBe("/asks?x=1#next-ask");
109 expect(getPull(app.db, repo.id, pull.number)?.state).toBe("closed");
110 const other = await newPull();
111 const foreign = await post(`/alice/notes/pulls/${other.number}/state`, { state: "closed" }, "https://evil.example/asks");
112 expect(foreign.headers.get("location")).toBe(`/alice/notes/pulls/${other.number}`);
113 });
114
115 test("a form's back field still wins, and a foreign one is dropped", async () => {
116 const pull = await newPull();
117 const res = await post(`/alice/notes/pulls/${pull.number}/state`, { state: "closed", back: "/asks" }, `${base}/elsewhere`);
118 expect(res.headers.get("location")).toBe("/asks#next-ask");
119 const other = await newPull();
120 const bad = await post(`/alice/notes/pulls/${other.number}/state`, { state: "closed", back: "//evil.example" });
121 expect(bad.headers.get("location")).toBe(`/alice/notes/pulls/${other.number}`);
122 });
123
124 test("say on a pull returns to where it began; a cross-origin Referer is ignored", async () => {
125 const pull = await newPull();
126 const res = await post(`/alice/notes/pulls/${pull.number}/say`, { text: "More tests." }, `${base}/asks`);
127 expect(res.headers.get("location")).toBe("/asks#next-ask");
128 const foreign = await post(`/alice/notes/pulls/${pull.number}/say`, { text: "Again." }, "https://evil.example/");
129 expect(foreign.headers.get("location")).toBe("/alice/notes");
130 });
131
132 test("decide and say on an issue return to where they began", async () => {
133 const issue = openIssue(app, alice, repo, { title: "Question", body: "" });
134 if (!issue.ok) throw new Error(String(issue.error));
135 const at = `/alice/notes/issues/${issue.value.number}`;
136 const said = await post(`${at}/comments`, { body: "An answer." }, `${base}/asks`);
137 expect(said.headers.get("location")).toBe("/asks#next-ask");
138 const foreign = await post(`${at}/comments`, { body: "Another." }, "https://evil.example/asks");
139 expect(foreign.headers.get("location")).toBe(`${at}#conversation`);
140 const decided = await post(`${at}/state`, { state: "closed", reason: "done" }, `${base}/asks`);
141 expect(decided.headers.get("location")).toBe("/asks#next-ask");
142 const stay = await post(`${at}/state`, { state: "open" }, "https://evil.example/asks");
143 expect(stay.headers.get("location")).toBe(at);
144 });
145 });
test/helpers/open-pull.ts added +38
@@ -0,0 +1,38 @@
1 /** One open pull on its own branch of `repo`, optionally with a green check. */
2 import type { App } from "../../src/app.ts";
3 import { openPull } from "../../src/actions/pulls.ts";
4 import { commitToBranch } from "../../src/actions/repos.ts";
5 import type { Pull } from "../../src/core/pulls.ts";
6 import type { Repo } from "../../src/core/repos.ts";
7 import { claimRun, createRun, finishRun } from "../../src/core/runs.ts";
8 import type { User } from "../../src/core/users.ts";
9
10 export async function openTopicPull(app: App, user: User, repo: Repo, n: number, green: boolean): Promise<Pull> {
11 const done = await commitToBranch(app, user, repo, {
12 branch: `topic/${n}`,
13 base: "main",
14 message: `change ${n}`,
15 files: [{ path: `F${n}.md`, content: `${n}\n` }],
16 });
17 if (!done.ok) throw new Error(JSON.stringify(done.error));
18 const opened = await openPull(app, user, repo, {
19 title: `change ${n}`,
20 body: "",
21 baseBranch: "main",
22 headBranch: `topic/${n}`,
23 });
24 if (!opened.ok) throw new Error(JSON.stringify(opened.error));
25 if (green) {
26 const run = createRun(app.db, {
27 repoId: repo.id,
28 kind: "check",
29 issueId: opened.value.id,
30 env: `pull-${opened.value.number}`,
31 commitOid: opened.value.headOid,
32 reason: "pull",
33 });
34 claimRun(app.db, run.id);
35 finishRun(app.db, run.id, { state: "ok", summary: "check passed" });
36 }
37 return opened.value;
38 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs