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

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

Closed opened this in answer to
Closed without merging

scout/forge:scout/1110-ship-decline-say-and-decide-stay-on-the → main 6 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
14 files changed +208 −31
README.md +1
@@ -9,6 +9,7 @@ that pull's own preview — its own URL, on its own copy of production's data
99 and every deploy is the check on that pull. No agent can move the default
1010 branch, so the only way code reaches production is a merge a person made: the
1111 crew proposes, you decide what ships.
12 Ship, close, say and comment return to the page they were taken from, with a one-line flash and a link; the form carries a same-forge `back` path, never the Referer.
1213
1314 That view is the **studio**, and it is the front door — a browser with no
1415 `forge_mode` cookie lands there. It speaks four words for the whole loop:
src/web/flash.ts +23
@@ -12,6 +12,16 @@
1212
1313 import { cookieValue } from "../http/context.ts";
1414
15 /** Whether `to` is a path on this forge: one slash, no scheme, no control bytes. */
16 export function localPath(to: string): boolean {
17 return (
18 to.length <= 512 &&
19 /^\/(?![/\\])/.test(to) &&
20 // eslint-disable-next-line no-control-regex
21 !/[\u0000-\u001f\u007f]/.test(to)
22 );
23 }
24
1525 export const FLASH_COOKIE = "forge_flash";
1626
1727 export interface Flash {
@@ -19,6 +29,8 @@ export interface Flash {
1929 message: string;
2030 /** A one-time value rendered in a copyable monospace block. */
2131 code?: string;
32 /** The one place worth going to look: a path on this forge, and its words. */
33 link?: { href: string; label: string };
2234 }
2335
2436 // Cookies cap out around 4KB; a flash is a sentence, not a payload.
@@ -55,6 +67,16 @@ export function readFlash(request: Request): Flash | undefined {
5567 if (typeof value.message !== "string" || value.message === "")
5668 return undefined;
5769 const tone = value.tone;
70 const l = value.link as Record<string, unknown> | null | undefined;
71 const link =
72 typeof l === "object" &&
73 l !== null &&
74 typeof l.href === "string" &&
75 typeof l.label === "string" &&
76 localPath(l.href) &&
77 l.label !== ""
78 ? { href: l.href, label: l.label.slice(0, 80) }
79 : undefined;
5880 return {
5981 message: value.message.slice(0, MAX_FLASH),
6082 ...(tone === "success" || tone === "danger" || tone === "attn"
@@ -63,5 +85,6 @@ export function readFlash(request: Request): Flash | undefined {
6385 ...(typeof value.code === "string" && value.code !== ""
6486 ? { code: value.code.slice(0, 512) }
6587 : {}),
88 ...(link !== undefined ? { link } : {}),
6689 };
6790 }
src/web/form.ts +18
@@ -11,6 +11,8 @@
1111 import { BODY_MAX, readBounded, STRANGER_MAX } from "../http/limits.ts";
1212 import { scopeAllows, type TokenScope } from "../core/tokens.ts";
1313 import { crossOrigin, type Ctx } from "../http/context.ts";
14 import { localPath } from "./flash.ts";
15 import { html, type Html } from "./html.ts";
1416
1517 export type Form = Awaited<ReturnType<Request["formData"]>>;
1618
@@ -63,3 +65,19 @@ export function field(form: Form, name: string): string {
6365 export function prefersJson(ctx: Ctx): boolean {
6466 return (ctx.request.headers.get("accept") ?? "").includes("application/json");
6567 }
68
69 /**
70 * Where a decision was taken: the form's own `back` field when it is a path
71 * on this forge, else `fallback`. The Referer is never consulted — it is
72 * absent under some privacy settings, and a field a form carries is the page
73 * saying where it wants to be.
74 */
75 export function formBack(form: Form, fallback: string): string {
76 const back = field(form, "back");
77 return localPath(back) ? back : fallback;
78 }
79
80 /** The hidden field that makes a form come back to the page it is on. */
81 export function backInput(ctx: Ctx): Html {
82 return html`<input type="hidden" name="back" value="${ctx.url.pathname}${ctx.url.search}" />`;
83 }
src/web/layout.ts +4
@@ -392,6 +392,10 @@ function flashToast(flash: Flash): Html {
392392 ${icon(glyph)}
393393 <div class="toast-body">
394394 ${flash.message}
395 ${when(
396 flash.link,
397 (link) => html` · <a href="${link.href}">${link.label}</a>`,
398 )}
395399 ${when(
396400 flash.code,
397401 (code) =>
src/web/pages/board.ts +1 −1
@@ -501,7 +501,7 @@ function declinedStrip(ctx: Ctx, scope: BoardScope): Html | null {
501501 ><b>${d.repo.name}</b>: the planner declined the direction and waits
502502 for you. <q>${d.words}</q></span
503503 >
504 <input type="hidden" name="back" value="board" />
504 <input type="hidden" name="back" value="/board" />
505505 <input
506506 class="input"
507507 name="body"
src/web/pages/issues.ts +13 −11
@@ -24,7 +24,7 @@ import {
2424 signInFirst,
2525 signInHref,
2626 } from "../chrome.ts";
27 import { field, readForm } from "../form.ts";
27 import { field, formBack, readForm } from "../form.ts";
2828 import { html, raw, when, type Html } from "../html.ts";
2929 import { flashTo, page, redirect } from "../layout.ts";
3030 import { btn, empty, icon, field as formField } from "../ui.ts";
@@ -291,13 +291,13 @@ export async function issueCommentSubmit(ctx: Ctx): Promise<Response> {
291291 const form = await readForm(ctx, "rw");
292292 if (form instanceof Response) return form;
293293
294 // A comment posted from the board's "the planner declined" line returns to
295 // the board. A fixed word, never a URL from the form: no open redirect.
296 const back = field(form, "back") === "board" ? "/board" : undefined;
294 // A comment returns to the page whose form posted it (`formBack`: a path on
295 // this forge, never a URL), the board's "the planner declined" line included.
297296 const dest = `${repoBase(found.repo)}/issues/${found.issue.number}`;
297 const back = formBack(form, dest);
298298 const body = field(form, "body");
299299 if (body.trim() === "")
300 return flashTo(ctx, dest, {
300 return flashTo(ctx, back, {
301301 tone: "danger",
302302 message: "A comment needs something in it.",
303303 });
@@ -309,15 +309,17 @@ export async function issueCommentSubmit(ctx: Ctx): Promise<Response> {
309309 body,
310310 );
311311 if (!added.ok)
312 return flashTo(ctx, dest, {
312 return flashTo(ctx, back, {
313313 tone: "danger",
314314 message: originError(added.error) ?? "That comment could not be posted.",
315315 });
316 return back === undefined
317 ? flashTo(ctx, `${dest}#conversation`, { message: "Comment posted." })
318 : flashTo(ctx, back, {
319 message: `Answered on #${found.issue.number}. The planner plans again.`,
320 });
316 if (back === "/board")
317 return flashTo(ctx, back, {
318 message: `Answered on #${found.issue.number}. The planner plans again.`,
319 });
320 return flashTo(ctx, back === dest ? `${dest}#conversation` : back, {
321 message: "Comment posted.",
322 });
321323 }
322324
323325 export { parseNumber };
src/web/pages/pull.ts +7 −4
@@ -63,7 +63,7 @@ import {
6363 type DiffViewOptions,
6464 type ThreadView,
6565 } from "../diff-view.ts";
66 import { field, readForm } from "../form.ts";
66 import { field, formBack, readForm } from "../form.ts";
6767 import { html, raw, when, type Html } from "../html.ts";
6868 import { flashTo, page, redirect } from "../layout.ts";
6969 import { liveClientJs, liveMount } from "../live.ts";
@@ -844,9 +844,10 @@ export async function pullCommentSubmit(ctx: Ctx): Promise<Response> {
844844 if (form instanceof Response) return form;
845845
846846 const dest = `${repoBase(found.repo)}/pulls/${found.pull.number}`;
847 const back = formBack(form, dest);
847848 const bodyText = field(form, "body");
848849 if (bodyText.trim() === "")
849 return flashTo(ctx, dest, {
850 return flashTo(ctx, back, {
850851 tone: "danger",
851852 message: "A comment needs something in it.",
852853 });
@@ -858,11 +859,13 @@ export async function pullCommentSubmit(ctx: Ctx): Promise<Response> {
858859 bodyText,
859860 );
860861 if (!added.ok)
861 return flashTo(ctx, dest, {
862 return flashTo(ctx, back, {
862863 tone: "danger",
863864 message: originError(added.error) ?? "That comment could not be posted.",
864865 });
865 return flashTo(ctx, `${dest}#conversation`, { message: "Comment posted." });
866 return flashTo(ctx, back === dest ? `${dest}#conversation` : back, {
867 message: "Comment posted.",
868 });
866869 }
867870
868871 /** Match the diff viewer's per-file anchor id, so the redirect lands there. */
src/web/pages/thread.ts +6 −4
@@ -49,7 +49,7 @@ import {
4949 } from "../../core/users.ts";
5050 import type { Ctx } from "../../http/context.ts";
5151 import { commentCard } from "../comments.ts";
52 import { field, readForm } from "../form.ts";
52 import { backInput, field, formBack, readForm } from "../form.ts";
5353 import { html, raw, when, type Html } from "../html.ts";
5454 import { flashOrJson, flashTo } from "../layout.ts";
5555 import {
@@ -482,6 +482,7 @@ export function composer(ctx: Ctx, o: ComposerOptions): Html {
482482 data-box="Write a comment"
483483 data-submit-key
484484 >
485 ${backInput(ctx)}
485486 <label class="sr-only" for="comment-body">Comment</label>
486487 <textarea
487488 class="input"
@@ -725,6 +726,7 @@ export async function stateSubmit(
725726
726727 const wanted = field(form, "state") === "closed" ? "closed" : "open";
727728 const dest = `${repoBase(found.repo)}/${kind === "pull" ? "pulls" : "issues"}/${found.issue.number}`;
729 const back = formBack(form, dest);
728730 const why = field(form, "reason");
729731 const intoText = field(form, "into").trim();
730732 const into = intoText
@@ -736,7 +738,7 @@ export async function stateSubmit(
736738 into.length > 50 ||
737739 !into.every((n) => Number.isInteger(n) && n > 0)
738740 )
739 return flashOrJson(ctx, dest, {
741 return flashOrJson(ctx, back, {
740742 tone: "danger",
741743 message: "Close as done, dropped, or split into issue numbers.",
742744 });
@@ -771,9 +773,9 @@ export async function stateSubmit(
771773 : changed.error === "forbidden"
772774 ? "Only the author or someone with write access can do that."
773775 : "That could not be changed.");
774 return flashOrJson(ctx, dest, { tone: "danger", message });
776 return flashOrJson(ctx, back, { tone: "danger", message });
775777 }
776 return flashOrJson(ctx, dest, {
778 return flashOrJson(ctx, back, {
777779 message: wanted === "closed" ? "Closed." : "Reopened.",
778780 });
779781 }
src/web/studio/actions.ts +19 −6
@@ -16,11 +16,12 @@ import { DIRECTION_NOTE } from "../../crew/direct.ts";
1616 import { mergePull } from "../../actions/pulls.ts";
1717 import { revertPull, type RevertPullError } from "../../actions/revert.ts";
1818 import { getPull } from "../../core/pulls.ts";
19 import { getAppByRepo } from "../../core/apps.ts";
1920 import { canRead, getRepo, type Repo } from "../../core/repos.ts";
2021 import { bringUpToDate } from "../../crew/autonomy.ts";
2122 import type { Ctx } from "../../http/context.ts";
2223 import { loadRepo, notFoundPage, repoBase, signInFirst } from "../chrome.ts";
23 import { field, readForm, type Form } from "../form.ts";
24 import { field, formBack, readForm, type Form } from "../form.ts";
2425 import { flashOrJson, flashTo } from "../layout.ts";
2526 import { changeHref } from "./nouns.ts";
2627
@@ -109,6 +110,7 @@ export async function shipSubmit(ctx: Ctx): Promise<Response> {
109110 const form = await readForm(ctx, "rw");
110111 if (form instanceof Response) return form;
111112 const base = repoBase(repo);
113 const back = formBack(form, base);
112114 const number = Number(ctx.params.number);
113115 const pull = Number.isInteger(number)
114116 ? getPull(ctx.app.db, repo.id, number)
@@ -124,7 +126,7 @@ export async function shipSubmit(ctx: Ctx): Promise<Response> {
124126 merged.error.kind === "conflict"
125127 ) {
126128 const who = bringUpToDate(ctx.app, repo, pull, merged.error.files);
127 return flashOrJson(ctx, base, {
129 return flashOrJson(ctx, back, {
128130 tone: "danger" as const,
129131 message:
130132 who === undefined
@@ -132,9 +134,19 @@ export async function shipSubmit(ctx: Ctx): Promise<Response> {
132134 : `It conflicts with main (${merged.error.files.join(", ")}); ${who} is bringing it up to date${repo.autonomy === "autonomous" ? ", then it lands on its own" : ", then it comes back to you"}.`,
133135 });
134136 }
135 return flashOrJson(ctx, base, {
137 return flashOrJson(ctx, back, {
136138 ...(merged.ok
137 ? { message: `Shipped "${pull.title}". Production is redeploying.` }
139 ? {
140 ...(getAppByRepo(ctx.app.db, repo.id) === undefined
141 ? {
142 message: `Shipped "${pull.title}".`,
143 link: { href: `${base}/pulls/${pull.number}`, label: "see it" },
144 }
145 : {
146 message: `Shipped "${pull.title}"; production is redeploying.`,
147 link: { href: `${base}/app/production/open`, label: "see it live" },
148 }),
149 }
138150 : {
139151 tone: "danger" as const,
140152 message: `That could not ship: ${mergeWords(merged.error)}.`,
@@ -216,6 +228,7 @@ export async function saySubmit(ctx: Ctx): Promise<Response> {
216228 const form = await readForm(ctx, "rw");
217229 if (form instanceof Response) return form;
218230 const base = repoBase(repo);
231 const back = formBack(form, base);
219232 const number = Number(ctx.params.number);
220233 const pull = Number.isInteger(number)
221234 ? getPull(ctx.app.db, repo.id, number)
@@ -224,12 +237,12 @@ export async function saySubmit(ctx: Ctx): Promise<Response> {
224237 return notFoundPage(ctx);
225238 const text = field(form, "text").trim();
226239 if (text === "")
227 return flashTo(ctx, base, {
240 return flashTo(ctx, back, {
228241 tone: "danger",
229242 message: "Say something first.",
230243 });
231244 const said = addComment(ctx.app, ctx.auth.user, repo, pull, text);
232 return flashOrJson(ctx, base, {
245 return flashOrJson(ctx, back, {
233246 ...(said.ok
234247 ? { message: `Told ${pull.authorName}. It picks the change back up.` }
235248 : { tone: "danger" as const, message: "That could not be said." }),
src/web/studio/asks.ts +4 −1
@@ -51,6 +51,7 @@ import { waitsForPerson, type ReviewWait } from "../../crew/review.ts";
5151 import type { Ctx } from "../../http/context.ts";
5252 import { vitals } from "../../kernel/vitals.ts";
5353 import { repoBase } from "../chrome.ts";
54 import { backInput } from "../form.ts";
5455 import { html, when, type Html } from "../html.ts";
5556 import { btn, card, icon, row } from "../ui.ts";
5657 import { lookUrl } from "../../core/looks.ts";
@@ -853,7 +854,7 @@ const askFormId = (d: Decision): string => `ask-${d.id}`;
853854 * It sits after the panel's form, because a form inside a form is not
854855 * HTML; the button reaches it by id.
855856 */
856 export function decisionForm(d: Decision): Html | null {
857 export function decisionForm(ctx: Ctx, d: Decision): Html | null {
857858 const pull = d.pull;
858859 if (pull === undefined) return null;
859860 const base = repoBase(d.repo);
@@ -861,10 +862,12 @@ export function decisionForm(d: Decision): Html | null {
861862 if (d.kind === "stopped")
862863 return html`<form ${own} action="${base}/pulls/${pull.number}/state">
863864 <input type="hidden" name="state" value="closed" />
865 ${backInput(ctx)}
864866 </form>`;
865867 if (d.kind === "look" || d.kind === "review")
866868 return html`<form ${own} action="${base}/pulls/${pull.number}/ship">
867869 <input type="hidden" name="pull" value="${pull.number}" />
870 ${backInput(ctx)}
868871 </form>`;
869872 return null;
870873 }
src/web/studio/asks_page.ts +1 −1
@@ -268,7 +268,7 @@ export function needsYouSection(
268268 ${btn("Preview", { size: "sm" })}
269269 <span class="muted small">on the selected asks</span>
270270 </form>`}
271 ${decisions.map((d) => decisionForm(d))}
271 ${decisions.map((d) => decisionForm(ctx, d))}
272272 </section>`;
273273 return { body, scriptJs: pickable < 2 ? "" : SELECT_ALL_JS };
274274 }
src/web/studio/change.ts +3 −1
@@ -37,6 +37,7 @@ import {
3737 repoHeader,
3838 repoPalette,
3939 } from "../chrome.ts";
40 import { backInput } from "../form.ts";
4041 import { html, when, type Html } from "../html.ts";
4142 import type { IconName as Glyph } from "../icons.ts";
4243 import { fragment, page, redirect } from "../layout.ts";
@@ -483,6 +484,7 @@ async function changeConversation(
483484 )}.</p>
484485 <div class="bar mt">
485486 <form method="post" action="${thread}/ship">
487 ${backInput(ctx)}
486488 ${btn("Bring up to date", { size: "sm", variant: "primary" })}
487489 </form>
488490 </div>`
@@ -571,7 +573,7 @@ async function changeConversation(
571573 </div>
572574 <aside><div id="pull-preview">${preview}</div></aside>
573575 </div>
574 ${decision ? decisionForm(decision) : null}
576 ${decision ? decisionForm(ctx, decision) : null}
575577 ${liveMount({
576578 repo: base,
577579 thread: "pull",
test/planner-declined.test.ts +2 −2
@@ -233,7 +233,7 @@ describe("the planner declined, waiting for a person", () => {
233233 {
234234 method: "POST",
235235 headers: { cookie, origin: servers.url },
236 body: new URLSearchParams({ back: "board", body: "Plan the next season: herbs." }),
236 body: new URLSearchParams({ back: "/board", body: "Plan the next season: herbs." }),
237237 redirect: "manual",
238238 },
239239 );
@@ -247,7 +247,7 @@ describe("the planner declined, waiting for a person", () => {
247247 "waits for you",
248248 );
249249 });
250 test("`back` is a fixed word: anything else returns to the issue, never elsewhere", async () => {
250 test("`back` is a path on this forge: anything else returns to the issue, never elsewhere", async () => {
251251 const cookie = await signIn("alice");
252252 const res = await fetch(
253253 `${servers.url}/alice/garden/issues/${direction.number}/comments`,
test/studio.test.ts +106
@@ -400,6 +400,112 @@ describe("the studio", () => {
400400 expect(getUserByName(app.db, "scout")).toBeDefined();
401401 });
402402
403 test("a decision lands back on the page it was taken from, and says so with a link", async () => {
404 const openGreen = async (name: string) => {
405 const branch = await commitToBranch(app, alice, repo, {
406 branch: `feature/${name}`,
407 base: "main",
408 message: name,
409 files: [{ path: `${name}.md`, content: `${name}\n` }],
410 });
411 if (!branch.ok) throw new Error(JSON.stringify(branch.error));
412 const opened = await openPull(app, alice, repo, {
413 title: name,
414 body: "",
415 baseBranch: "main",
416 headBranch: `feature/${name}`,
417 });
418 if (!opened.ok) throw new Error(String(opened.error));
419 const run = createRun(app.db, {
420 repoId: repo.id,
421 kind: "check",
422 issueId: opened.value.id,
423 env: `pull-${opened.value.number}`,
424 commitOid: opened.value.headOid,
425 reason: "pull",
426 });
427 claimRun(app.db, run.id);
428 finishRun(app.db, run.id, { state: "ok", summary: "check passed" });
429 return opened.value;
430 };
431 const home = await openGreen("from-home");
432 const shipped = await post(`/alice/notes/pulls/${home.number}/ship`, {
433 back: "/",
434 });
435 expect(shipped.headers.get("location")).toBe("/");
436 expect(getPull(app.db, repo.id, home.number)?.mergedAt).not.toBeNull();
437 // The flash names what happened, with the one link that matters.
438 const flash = shipped.headers.get("set-cookie")?.split(";")[0] ?? "";
439 const page = await (await get("/", { cookie: `${cookie}; ${flash}` })).text();
440 expect(page).toContain(`Shipped &quot;from-home&quot;`);
441 // notes is an app: shipping redeploys production, and the link goes there.
442 expect(getAppByRepo(app.db, repo.id)).toBeDefined();
443 expect(page).toContain("; production is redeploying.");
444 expect(page).toContain(`<a href="/alice/notes/app/production/open">see it live`);
445
446 const there = await openGreen("from-pull");
447 const at = `/alice/notes/pulls/${there.number}`;
448 const stayed = await post(`${at}/ship`, { back: at });
449 expect(stayed.headers.get("location")).toBe(at);
450
451 // A comment through the form the page really renders comes back to that page.
452 const rendered = await (await get(at)).text();
453 const form = rendered.match(/<form[^>]*class="card comment-form"[\s\S]*?<\/form>/)?.[0] ?? "";
454 const action = form.match(/action="([^"]+)"/)?.[1] ?? "";
455 const backField = form.match(/name="back" value="([^"]+)"/)?.[1] ?? "";
456 expect(action).toBe(`${at}/comments`);
457 expect(backField).toBe(at);
458 const commented = await post(action, { back: backField, body: "Looks good." });
459 expect(commented.status).toBe(303);
460 expect(commented.headers.get("location")).toBe(`${at}#conversation`);
461 const hostile = await post(action, { back: "//evil.example", body: "Still fine." });
462 expect(hostile.headers.get("location")).toBe(`${at}#conversation`);
463
464 // A back that is not a path on this forge is ignored, never followed.
465 for (const [i, back] of [
466 "//evil.example",
467 "https://evil.example/",
468 "/\\evil",
469 "/ok\u0001path",
470 ].entries()) {
471 const third = await openGreen(`from-elsewhere-${i}`);
472 const odd = await post(`/alice/notes/pulls/${third.number}/ship`, { back });
473 expect(odd.headers.get("location")).toBe("/alice/notes");
474 expect(getPull(app.db, repo.id, third.number)?.mergedAt).not.toBeNull();
475 }
476
477 // Saying and closing stay put too.
478 const fourth = await openGreen("said");
479 const said = await post(`/alice/notes/pulls/${fourth.number}/say`, {
480 text: "Not quite.",
481 back: "/",
482 });
483 expect(said.headers.get("location")).toBe("/");
484 const closed = await post(`/alice/notes/pulls/${fourth.number}/state`, {
485 state: "closed",
486 back: "/",
487 });
488 expect(closed.headers.get("location")).toBe("/");
489
490 // Failures stay put too: a bad reason and a refused merge both flash on
491 // the page the decision was taken from.
492 const badReason = await post(`/alice/notes/pulls/${fourth.number}/state`, {
493 state: "closed",
494 reason: "nonsense",
495 back: "/",
496 });
497 expect(badReason.headers.get("location")).toBe("/");
498 const badFlash = badReason.headers.get("set-cookie")?.split(";")[0] ?? "";
499 expect(await (await get("/", { cookie: `${cookie}; ${badFlash}` })).text()).toContain(
500 "Close as done, dropped, or split",
501 );
502 const refused = await post(`/alice/notes/pulls/${fourth.number}/ship`, {
503 back: "/",
504 });
505 expect(refused.headers.get("location")).toBe("/");
506 expect(refused.headers.get("set-cookie")).toContain("forge_flash");
507 });
508
403509 test("a tell shipped long ago still reads shipped once it is buried under 250 later events", async () => {
404510 const told = openIssue(app, alice, repo, {
405511 title: "Buried tell",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs