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

Wire pin_demos: route, page, MCP tool, TUI screen and docs/features/ how-to #9317

Closed opened this
Closed without merging

scout/forge:scout/9310-wire-pin-demos-route-page-mcp-tool-tui-s → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
18 files changed +506 −12
docs/features/build-pins.md +3 −2
@@ -8,7 +8,8 @@ is trimmed to what main calls).
88
99 - Page: `/<owner>/<name>/builds` lists pins; `/builds/new` is the form (Branches has a Pin button per branch and a Builds link); Preview serves a pinned commit (`build_preview`); Delete is behind `/-/confirm`.
1010 - API: `GET/POST /api/v1/repos/:owner/:name/builds`, `PATCH`/`DELETE …/builds/:label` (rw scope, a person who writes; agents are refused).
11 - MCP: the read-only `builds` tool takes `{ repo }` and answers `{ items, next_cursor: null }`, the rows the API lists; a repository the caller cannot read is not found. Pinning, noting and deleting are not offered to agents.
11 - MCP: the read-only `builds` tool takes `{ repo }` and answers `{ items, next_cursor: null }`, the rows the API lists; a repository the caller cannot read is not found. Pinning, noting and deleting are not offered to agents; `action` + `label` edits a pin's demo (see `pin-demos.md`).
1212 - Terminal: on a repository, the palette's `<owner>/<name> — Builds` (`src/tui/screens/builds.ts`) lists the pins to anyone who may read it; a person who writes (never an agent) presses `p` to pin (prefilled with the next label and the default branch's tip), `n` to note, `d` to delete.
1313 - Notes are an append-only list on `refs/forge/notes`. `FORGE_NOTES_INTENT=<file>` copies each person's note once into that file under `## Iterator notes`.
14 - Left out: demos and displays, screenshots, the Iterations graph, the lineage on Branches.
14 - Demos: see `pin-demos.md`.
15 - Left out: displays, screenshots, the Iterations graph, the lineage on Branches.
docs/features/pin-demos.md added +12
@@ -0,0 +1,12 @@
1 # Pin demos
2
3 A pin's demo is a name, a version, how it opens (`file`, `env`, `shots`, or the repository's own `app.launch`), the page it opens and whether it is in the showcase. The facts live on the pin's tag. Only a person who writes the repository sets them — never an agent, never on a mirror. A demo that opens as a file gets its page captured in the background.
4
5 How to:
6
7 - **Page** — `/<owner>/<name>/builds/<label>/demo` (the *Demo* link on each pin of the Builds page): save the facts, build and keep its page, put it in or out of the showcase, clear it. A non-writer gets a 404.
8 - **API** (rw scope) — `PUT …/builds/:label/demo` `{ name, version, launch?, page, showcase }`; `DELETE …/demo` clears; `POST …/demo/showcase` `{ on }`; `POST …/demo/capture` answers `{ state }`, 202 while it runs, 422 `not_a_file` when the pin does not open as a file.
9 - **MCP** — the `builds` tool with `action` and `label`: `demo` (with `name`, `version`, `page`, `launch?`, `showcase?`), `showcase`, `unshowcase`, `clear_demo`, `build`. Without `action` it still only lists pins.
10 - **Terminal** — on the Builds screen a writer presses `m` (name, version, page), `w` (showcase on/off), `b` (build the page) or `x` (clear the demo).
11
12 Clearing a demo keeps the pin, its commit and its screenshots. Every change is a `build.demo` event.
src/actions/pin_demo_words.ts added +20
@@ -0,0 +1,20 @@
1 /** What a refused demo change says, and the HTTP status it earns: one wording for the page, the API, the MCP and the terminal. */
2
3 export const DEMO_WORDS: Readonly<Record<string, string>> = {
4 not_found: "That pin is gone.",
5 invalid_demo: "A demo is a name (60), a version (40), a launch (file, env or shots) and a plain page path.",
6 mirrored: "A mirror's builds are its origin's.",
7 not_a_file: "That pin does not open as a captured file, so there is nothing to build.",
8 moved: "That pin changed meanwhile; try again.",
9 git_failed: "Git refused the change.",
10 };
11
12 export const demoSays = (error: string): string => DEMO_WORDS[error] ?? "Only a person who writes this repository can do that.";
13
14 export const DEMO_STATUS: Readonly<Record<string, number>> = {
15 mirrored: 409,
16 moved: 409,
17 invalid_demo: 422,
18 not_a_file: 422,
19 git_failed: 500,
20 };
src/contract/openapi/routes/deleteApiV1ReposOwnerNameBuildsLabelDemo.ts added +15
@@ -0,0 +1,15 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "delete",
5 path: `${REPO}/builds/{label}/demo`,
6 summary: "Clear a pin's demo (rw scope, a person who writes); the pin, its commit and its screenshots stay",
7 auth: true,
8 status: 204,
9 refusals: {
10 forbidden: "403: not a person who writes the repository (an agent is refused)",
11 not_found: "404: no such repository or pin, or the caller cannot read it",
12 mirrored: "409: the repository mirrors an origin",
13 invalid_demo: "422: a name over 60 or version over 40 characters, a launch other than file, env or shots, or a page that is not a plain path",
14 },
15 };
src/contract/openapi/routes/index.ts +4
@@ -14,6 +14,7 @@ export { route as deleteApiV1ReposOwnerNameAppDomainsHost } from "./deleteApiV1R
1414 export { route as deleteApiV1ReposOwnerNameAppEnvVar } from "./deleteApiV1ReposOwnerNameAppEnvVar.ts";
1515 export { route as deleteApiV1ReposOwnerNameBranchesBranch } from "./deleteApiV1ReposOwnerNameBranchesBranch.ts";
1616 export { route as deleteApiV1ReposOwnerNameBuildsLabel } from "./deleteApiV1ReposOwnerNameBuildsLabel.ts";
17 export { route as deleteApiV1ReposOwnerNameBuildsLabelDemo } from "./deleteApiV1ReposOwnerNameBuildsLabelDemo.ts";
1718 export { route as deleteApiV1ReposOwnerNameBuildsLabelShotsFile } from "./deleteApiV1ReposOwnerNameBuildsLabelShotsFile.ts";
1819 export { route as deleteApiV1ReposOwnerNameCrewUsername } from "./deleteApiV1ReposOwnerNameCrewUsername.ts";
1920 export { route as deleteApiV1ReposOwnerNameEgressGrants } from "./deleteApiV1ReposOwnerNameEgressGrants.ts";
@@ -259,6 +260,8 @@ export { route as postApiV1ReposOwnerNameAppNotesIdUnban } from "./postApiV1Repo
259260 export { route as postApiV1ReposOwnerNameBranches } from "./postApiV1ReposOwnerNameBranches.ts";
260261 export { route as postApiV1ReposOwnerNameBuilds } from "./postApiV1ReposOwnerNameBuilds.ts";
261262 export { route as postApiV1ReposOwnerNameBuildsLabelCart } from "./postApiV1ReposOwnerNameBuildsLabelCart.ts";
263 export { route as postApiV1ReposOwnerNameBuildsLabelDemoCapture } from "./postApiV1ReposOwnerNameBuildsLabelDemoCapture.ts";
264 export { route as postApiV1ReposOwnerNameBuildsLabelDemoShowcase } from "./postApiV1ReposOwnerNameBuildsLabelDemoShowcase.ts";
262265 export { route as postApiV1ReposOwnerNameBuildsLabelShots } from "./postApiV1ReposOwnerNameBuildsLabelShots.ts";
263266 export { route as postApiV1ReposOwnerNameBuildsLabelShotsFile } from "./postApiV1ReposOwnerNameBuildsLabelShotsFile.ts";
264267 export { route as postApiV1ReposOwnerNameBuildsLabelShotsLooks } from "./postApiV1ReposOwnerNameBuildsLabelShotsLooks.ts";
@@ -334,6 +337,7 @@ export { route as putApiV1BoardsSlug } from "./putApiV1BoardsSlug.ts";
334337 export { route as putApiV1Front } from "./putApiV1Front.ts";
335338 export { route as putApiV1ReposOwnerNameAppEnvVar } from "./putApiV1ReposOwnerNameAppEnvVar.ts";
336339 export { route as putApiV1ReposOwnerNameAppMembers } from "./putApiV1ReposOwnerNameAppMembers.ts";
340 export { route as putApiV1ReposOwnerNameBuildsLabelDemo } from "./putApiV1ReposOwnerNameBuildsLabelDemo.ts";
337341 export { route as putApiV1ReposOwnerNameCrewUsername } from "./putApiV1ReposOwnerNameCrewUsername.ts";
338342 export { route as putApiV1ReposOwnerNameIssuesNumberAssignee } from "./putApiV1ReposOwnerNameIssuesNumberAssignee.ts";
339343 export { route as putApiV1ReposOwnerNameIssuesNumberLabels } from "./putApiV1ReposOwnerNameIssuesNumberLabels.ts";
src/contract/openapi/routes/postApiV1ReposOwnerNameBuildsLabelDemoCapture.ts added +15
@@ -0,0 +1,15 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: `${REPO}/builds/{label}/demo/capture`,
6 summary: "Build a pin's page and keep it (rw scope, a person who writes): answers { state } with 202 while the capture runs, 200 once kept; 422 not_a_file when the pin does not open as a file",
7 auth: true,
8 status: 202,
9 refusals: {
10 forbidden: "403: not a person who writes the repository (an agent is refused)",
11 not_found: "404: no such repository or pin, or the caller cannot read it",
12 mirrored: "409: the repository mirrors an origin",
13 invalid_demo: "422: a name over 60 or version over 40 characters, a launch other than file, env or shots, or a page that is not a plain path",
14 },
15 };
src/contract/openapi/routes/postApiV1ReposOwnerNameBuildsLabelDemoShowcase.ts added +15
@@ -0,0 +1,15 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: `${REPO}/builds/{label}/demo/showcase`,
6 summary: "Put a pin's demo in the showcase or take it out (rw scope, a person who writes): { on }",
7 auth: true,
8 status: 200,
9 refusals: {
10 forbidden: "403: not a person who writes the repository (an agent is refused)",
11 not_found: "404: no such repository or pin, or the caller cannot read it",
12 mirrored: "409: the repository mirrors an origin",
13 invalid_demo: "422: a name over 60 or version over 40 characters, a launch other than file, env or shots, or a page that is not a plain path",
14 },
15 };
src/contract/openapi/routes/putApiV1ReposOwnerNameBuildsLabelDemo.ts added +15
@@ -0,0 +1,15 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "put",
5 path: `${REPO}/builds/{label}/demo`,
6 summary: "Set a pin's demo (rw scope, a person who writes): { name, version, launch?, page, showcase }; a demo that opens as a file gets its page captured in the background",
7 auth: true,
8 status: 200,
9 refusals: {
10 forbidden: "403: not a person who writes the repository (an agent is refused)",
11 not_found: "404: no such repository or pin, or the caller cannot read it",
12 mirrored: "409: the repository mirrors an origin",
13 invalid_demo: "422: a name over 60 or version over 40 characters, a launch other than file, env or shots, or a page that is not a plain path",
14 },
15 };
src/http/api.ts +2
@@ -356,6 +356,7 @@ import { appRoutes } from "./api/app.ts";
356356 import { buildRoutes } from "./api/builds.ts";
357357 import { buildShotRoutes } from "./api/build_shots.ts";
358358 import { buildCartRoutes } from "./api/build_cart.ts";
359 import { pinDemoRoutes } from "./api/pin_demos.ts";
359360 import { iterationRoutes } from "./api/iterations.ts";
360361 import { appNoteRoutes } from "./api/app_notes.ts";
361362 import { reportRoutes } from "./api/reports.ts";
@@ -3639,6 +3640,7 @@ export function apiRoutes(router: Router<Handler>): void {
36393640 buildRoutes(router);
36403641 buildShotRoutes(router);
36413642 buildCartRoutes(router);
3643 pinDemoRoutes(router);
36423644 iterationRoutes(router);
36433645
36443646 egressGrantRoutes(router);
src/http/api/pin_demos.ts added +65
@@ -0,0 +1,65 @@
1 /**
2 * A pin's demo over the API (`actions/pin_demos.ts`): set it, clear it, put
3 * it in the showcase or take it out, and build its page. Every one needs
4 * the `rw` scope and a person who writes; an agent is refused.
5 */
6
7 import { DEMO_STATUS } from "../../actions/pin_demo_words.ts";
8 import { captureBuild, deleteDemo, saveDemo, setShowcase } from "../../actions/pin_demos.ts";
9 import { isLaunch } from "../../git/builds.ts";
10 import { loadRepo } from "../api.ts";
11 import type { Handler } from "../context.ts";
12 import { body, json, notFound, requireScope, respondAccess } from "../respond.ts";
13 import type { Router } from "../router.ts";
14
15 const text = (v: unknown, max: number): string => (typeof v === "string" ? v.slice(0, max) : "");
16
17 export function pinDemoRoutes(router: Router<Handler>): void {
18 // PUT { name, version, launch?, page, showcase } — set the demo; a file demo gets its capture started.
19 router.add("PUT", "/api/v1/repos/:owner/:name/builds/:label/demo", async (ctx) => {
20 const denied = requireScope(ctx, "rw");
21 if (denied) return denied;
22 const repo = loadRepo(ctx);
23 if (!repo) return notFound();
24 const b = await body(ctx.request);
25 const done = await saveDemo(ctx.app, ctx.auth.user, repo, ctx.params.label ?? "", {
26 name: text(b.name, 200),
27 version: text(b.version, 200),
28 ...(isLaunch(b.launch) ? { launch: b.launch } : {}),
29 page: text(b.page, 400),
30 showcase: b.showcase === true,
31 });
32 if (!done.ok) return respondAccess(done.error, DEMO_STATUS[done.error] ?? 422);
33 return json(done.value);
34 });
35
36 router.add("DELETE", "/api/v1/repos/:owner/:name/builds/:label/demo", async (ctx) => {
37 const denied = requireScope(ctx, "rw");
38 if (denied) return denied;
39 const repo = loadRepo(ctx);
40 if (!repo) return notFound();
41 const done = await deleteDemo(ctx.app, ctx.auth.user, repo, ctx.params.label ?? "");
42 return done.ok ? new Response(null, { status: 204 }) : respondAccess(done.error, DEMO_STATUS[done.error] ?? 422);
43 });
44
45 // POST { on: boolean } — in or out of the showcase.
46 router.add("POST", "/api/v1/repos/:owner/:name/builds/:label/demo/showcase", async (ctx) => {
47 const denied = requireScope(ctx, "rw");
48 if (denied) return denied;
49 const repo = loadRepo(ctx);
50 if (!repo) return notFound();
51 const b = await body(ctx.request);
52 const done = await setShowcase(ctx.app, ctx.auth.user, repo, ctx.params.label ?? "", b.on === true);
53 return done.ok ? json(done.value) : respondAccess(done.error, DEMO_STATUS[done.error] ?? 422);
54 });
55
56 // POST — build the pin's page and keep it: 202 while it runs.
57 router.add("POST", "/api/v1/repos/:owner/:name/builds/:label/demo/capture", async (ctx) => {
58 const denied = requireScope(ctx, "rw");
59 if (denied) return denied;
60 const repo = loadRepo(ctx);
61 if (!repo) return notFound();
62 const done = await captureBuild(ctx.app, ctx.auth.user, repo, ctx.params.label ?? "");
63 return done.ok ? json({ state: done.value }, done.value === "done" ? 200 : 202) : respondAccess(done.error, DEMO_STATUS[done.error] ?? 422);
64 });
65 }
src/http/mcp/tools/builds.ts +45 −7
@@ -1,20 +1,58 @@
1 import { listBuildPins } from "../../../git/builds.ts";
1 import { demoSays } from "../../../actions/pin_demo_words.ts";
2 import { captureBuild, deleteDemo, saveDemo, setShowcase } from "../../../actions/pin_demos.ts";
3 import { isLaunch, listBuildPins } from "../../../git/builds.ts";
24 import { repoDir } from "../../../git/repos.ts";
3 import { good, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
5 import { bad, good, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
6
7 const ACTIONS = ["demo", "showcase", "unshowcase", "clear_demo", "build"] as const;
48
59 export const tool: Tool = {
610 name: "builds",
7 doc: "`{ repo }`: the repository's build pins, `{ items, next_cursor: null }`, as GET `/api/v1/repos/:owner/:name/builds` lists them (label, commit, who pinned it, note, parent, source); read-only, pinning stays with people on the page, the API and the terminal",
8 description: "A repo's build pins (`refs/builds/`): label, commit, pinned by, note.",
11 doc: "`{ repo }`: the repository's build pins, `{ items, next_cursor: null }`, as GET `/api/v1/repos/:owner/:name/builds` lists them (label, commit, who pinned it, note, parent, source); with `action` (`demo` with `name`, `version`, `page`, `launch`, `showcase`; `showcase`; `unshowcase`; `clear_demo`; `build`) and `label`, a person who writes changes that pin's demo as the PUT/DELETE `…/builds/:label/demo` routes do, and an agent is refused; pinning and noting stay with people",
12 description: "A repo's build pins (`refs/builds/`): label, commit, pinned by, note. `action` + `label` edits a pin's demo.",
913 inputSchema: {
1014 type: "object",
11 properties: { repo: REPO_ARG },
15 properties: {
16 repo: REPO_ARG,
17 action: { type: "string", enum: [...ACTIONS] },
18 label: { type: "string", maxLength: 40 },
19 name: { type: "string", maxLength: 200 },
20 version: { type: "string", maxLength: 200 },
21 page: { type: "string", maxLength: 400 },
22 launch: { type: "string", enum: ["file", "env", "shots"] },
23 showcase: { type: "boolean" },
24 },
1225 required: ["repo"],
1326 },
14 writes: false,
27 writes: true,
28 readsWithout: "action",
1529 async run(ctx, user, args) {
1630 const repo = repoArg(ctx, user, args);
1731 if (isAnswer(repo)) return repo;
18 return good({ items: await listBuildPins(repoDir(ctx.app.reposRoot, repo.ownerName, repo.name)), next_cursor: null });
32 const dir = repoDir(ctx.app.reposRoot, repo.ownerName, repo.name);
33 const action = args["action"];
34 if (action === undefined) return good({ items: await listBuildPins(dir), next_cursor: null });
35 if (typeof action !== "string" || !(ACTIONS as readonly string[]).includes(action))
36 return bad("invalid_action", `action is one of ${ACTIONS.join(", ")}`);
37 const label = args["label"];
38 if (typeof label !== "string" || label === "") return bad("invalid_label", "label names the pin");
39 const text = (k: string, max: number): string => (typeof args[k] === "string" ? (args[k] as string).slice(0, max) : "");
40 const launch = args["launch"];
41 const done =
42 action === "demo"
43 ? await saveDemo(ctx.app, user, repo, label, {
44 name: text("name", 200),
45 version: text("version", 200),
46 ...(isLaunch(launch) ? { launch } : {}),
47 page: text("page", 400),
48 showcase: args["showcase"] === true,
49 })
50 : action === "clear_demo"
51 ? await deleteDemo(ctx.app, user, repo, label)
52 : action === "build"
53 ? await captureBuild(ctx.app, user, repo, label)
54 : await setShowcase(ctx.app, user, repo, label, action === "showcase");
55 if (!done.ok) return bad(done.error === "unauthorized" ? "forbidden" : done.error, demoSays(done.error));
56 return good(action === "build" ? { state: done.value } : { pin: done.value });
1957 },
2058 };
src/http/server.ts +3
@@ -183,6 +183,7 @@ import {
183183 branchDelete,
184184 branchesPage,
185185 } from "../web/pages/branches.ts";
186 import { pinDemoPage, pinDemoSubmit } from "../web/pages/pin_demo.ts";
186187 import { iterationsPage, noteSubmit } from "../web/pages/iterations.ts";
187188 import { buildsPage, deletePinSubmit, newBuildPage, pinBuildSubmit, previewBuildSubmit } from "../web/pages/builds.ts";
188189 import { shotImage, shotsPage } from "../web/pages/build_shots.ts";
@@ -1268,6 +1269,8 @@ export function buildRouter(): Router<Handler> {
12681269 // A pin's cart: its captured page, played sandboxed, and its picture (`arcade/carts.ts`).
12691270 router.add("GET", "/:owner/:name/builds/:label/cart", cartPage);
12701271 router.add("GET", "/:owner/:name/builds/:label/cart.png", cartArt);
1272 router.add("GET", "/:owner/:name/builds/:label/demo", pinDemoPage);
1273 router.add("POST", "/:owner/:name/builds/:label/demo", pinDemoSubmit);
12711274 router.add("GET", "/:owner/:name/iterations", iterationsPage);
12721275 router.add("POST", "/:owner/:name/builds", pinBuildSubmit);
12731276 router.add("POST", "/:owner/:name/builds/preview", previewBuildSubmit);
src/tui/screens/builds.ts +46 −2
@@ -10,6 +10,8 @@
1010
1111 import { setCart } from "../../actions/build_cart.ts";
1212 import { deletePin, notePin, pinBuild } from "../../actions/builds.ts";
13 import { demoSays } from "../../actions/pin_demo_words.ts";
14 import { captureBuild, deleteDemo, demoDefaults, demoFactsAt, saveDemo, setShowcase } from "../../actions/pin_demos.ts";
1315 import { canRead, canWrite, type Repo } from "../../core/repos.ts";
1416 import { listBuildPins, type BuildPin } from "../../git/builds.ts";
1517 import { refTip } from "../../git/read.ts";
@@ -42,7 +44,7 @@ const WORDS: Record<string, string> = {
4244 invalid_demo: "A cart is a name (60), a version (40) and a plain page path.",
4345 git_failed: "Git refused the change.",
4446 };
45 const say = (error: string): string => WORDS[error] ?? "Only a person who writes this repository can do that.";
47 const say = (error: string): string => WORDS[error] ?? demoSays(error);
4648
4749 /** Whether `f`'s person may pin, note or delete here: a writer who is not an agent. */
4850 export const mayPin = (f: Session, repo: Repo): boolean =>
@@ -115,6 +117,44 @@ export function buildsScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
115117 }),
116118 );
117119 };
120 /** `m`: name, version and page of the pin's demo; the launch stays as it was. */
121 const nameDemo = (picked: BuildPin): void => {
122 void ctx.track(
123 demoFactsAt(f.app, repo, picked.oid).then((facts) => {
124 const have = picked.demo ?? { ...demoDefaults(repo, picked.label, facts.pages), showcase: false };
125 ctx.push(
126 promptScreen(ctx, screen, {
127 title: `Demo of ${picked.label}`,
128 label: "name, version, then the page it opens",
129 value: `${have.name} ${have.version} ${have.page}`,
130 onSubmit: (entry) => {
131 const [name = "", version = "", page = "/"] = entry.trim().split(/\s+/);
132 if (name === "" || version === "") return "Give a name and a version.";
133 return ctx.track(
134 saveDemo(f.app, f.user, repo, picked.label, {
135 name,
136 version,
137 ...(have.launch === undefined ? {} : { launch: have.launch }),
138 page,
139 showcase: have.showcase,
140 }).then((r) => done(r.ok ? `Demo ${name} saved.` : say(r.error))),
141 );
142 },
143 }),
144 );
145 }),
146 );
147 };
148 const toggleShowcase = (picked: BuildPin): void => {
149 const on = picked.demo?.showcase !== true;
150 void ctx.track(setShowcase(f.app, f.user, repo, picked.label, on).then((r) => done(r.ok ? (on ? `${picked.label} is in the showcase.` : `${picked.label} is out of the showcase.`) : say(r.error))));
151 };
152 const build = (picked: BuildPin): void => {
153 void ctx.track(captureBuild(f.app, f.user, repo, picked.label).then((r) => done(r.ok ? (r.value === "done" ? "Its page is kept." : "Building its page.") : say(r.error))));
154 };
155 const clearDemo = (picked: BuildPin): void => {
156 void ctx.track(deleteDemo(f.app, f.user, repo, picked.label).then((r) => done(r.ok ? "Demo cleared; the pin stays." : say(r.error))));
157 };
118158 const ask = (picked: BuildPin): void => {
119159 ctx.push(
120160 confirmScreen(ctx, screen, {
@@ -136,7 +176,7 @@ export function buildsScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
136176 return [
137177 binding(["j", "k"], "move"),
138178 binding(["s"], "screenshots"),
139 ...(mayPin(f, repo) ? [binding(["p"], "pin"), binding(["n"], "note"), binding(["c"], "cart"), binding(["d"], "delete")] : []),
179 ...(mayPin(f, repo) ? [binding(["p"], "pin"), binding(["n"], "note"), binding(["c"], "cart"), binding(["m"], "demo"), binding(["w"], "showcase"), binding(["b"], "build page"), binding(["x"], "clear demo"), binding(["d"], "delete")] : []),
140180 binding(["esc", "q"], "back"),
141181 ];
142182 },
@@ -177,6 +217,10 @@ export function buildsScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
177217 else if (e.key === "p" && write) void ctx.track(pin());
178218 else if (e.key === "n" && write && picked !== undefined) addNote(picked);
179219 else if (e.key === "c" && write && picked !== undefined) nameCart(picked);
220 else if (e.key === "m" && write && picked !== undefined) nameDemo(picked);
221 else if (e.key === "w" && write && picked !== undefined) toggleShowcase(picked);
222 else if (e.key === "b" && write && picked !== undefined) build(picked);
223 else if (e.key === "x" && write && picked !== undefined) clearDemo(picked);
180224 else if (e.key === "d" && write && picked !== undefined) ask(picked);
181225 else return false;
182226 ctx.invalidate();
src/web/pages/builds.ts +4
@@ -113,6 +113,10 @@ export function buildsCard(
113113 >▶ ${n.pin.demo?.name ?? ""} ${n.pin.demo?.version ?? ""}</a
114114 >`,
115115 )}
116 ${when(
117 canPin && n.from === undefined,
118 () => html`<a class="build-shots small" href="${base}/builds/${encodeURIComponent(n.pin.label)}/demo">Demo</a>`,
119 )}
116120 ${when(
117121 n.from === undefined,
118122 () => html`<a class="build-shots small" href="${base}/builds/${encodeURIComponent(n.pin.label)}/shots">Screenshots</a>`,
src/web/pages/pin_demo.ts added +107
@@ -0,0 +1,107 @@
1 /**
2 * A pin's demo, edited: the form (`GET …/builds/:label/demo`) and the one
3 * POST behind every button on it — save, showcase, unshowcase, delete,
4 * build (`actions/pin_demos.ts`). A person who writes the repository sees
5 * it; anyone else is told the page is not there.
6 */
7
8 import { demoSays } from "../../actions/pin_demo_words.ts";
9 import { captureBuild, deleteDemo, demoDefaults, demoFactsAt, saveDemo, setShowcase, writerOf } from "../../actions/pin_demos.ts";
10 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
11 import { isLaunch, LAUNCHES, readBuildPin } from "../../git/builds.ts";
12 import { repoDir } from "../../git/repos.ts";
13 import type { Ctx } from "../../http/context.ts";
14 import { crumbsFor, loadRepo, notFoundPage, repoBase, repoHeader, repoPalette, signInFirst } from "../chrome.ts";
15 import { field as formValue, readForm } from "../form.ts";
16 import { html, when } from "../html.ts";
17 import { flashTo, page } from "../layout.ts";
18 import { btn, card, field, icon, selectField } from "../ui.ts";
19
20 const hiddenError = (e: string): boolean => e === "unauthorized" || e === "not_found" || e === "forbidden";
21
22 // GET /:owner/:name/builds/:label/demo — the pin's demo facts, for a writer.
23 export async function pinDemoPage(ctx: Ctx): Promise<Response> {
24 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
25 const repo = loadRepo(ctx);
26 if (!repo) return notFoundPage(ctx);
27 if (!ctx.auth.user) return signInFirst(ctx);
28 if (!writerOf(ctx.app, ctx.auth.user, repo).ok) return notFoundPage(ctx);
29 const label = ctx.params.label ?? "";
30 const pin = await readBuildPin(repoDir(ctx.app.reposRoot, repo.ownerName, repo.name), label);
31 if (pin === undefined) return notFoundPage(ctx);
32 const facts = await demoFactsAt(ctx.app, repo, pin.oid);
33 const have = pin.demo ?? { ...demoDefaults(repo, label, facts.pages), showcase: false };
34 const action = `${repoBase(repo)}/builds/${encodeURIComponent(label)}/demo`;
35 const body = html`${repoHeader(ctx, repo, "branches", { compact: true })}
36 <div class="mt">
37 ${card(
38 html`<form method="post" action="${action}" class="stack">
39 <input type="hidden" name="do" value="save" />
40 ${field({ label: "Name", name: "name", value: have.name, required: true, hint: "Pins sharing a name are one demo's builds." })}
41 ${field({ label: "Version", name: "version", value: have.version, required: true })}
42 ${selectField({
43 label: "Opens as",
44 name: "launch",
45 hint: `Automatic follows the repository${facts.launch === undefined ? "" : ` (${facts.launch})`}.`,
46 options: [
47 { value: "", label: "Automatic", selected: have.launch === undefined },
48 ...LAUNCHES.map((l) => ({ value: l, label: l, selected: have.launch === l })),
49 ],
50 })}
51 ${field({ label: "Page", name: "page", value: have.page, mono: true, hint: facts.pages.length === 0 ? "A plain path such as /." : `The repository offers: ${facts.pages.join(", ")}` })}
52 <label class="check"><input type="checkbox" name="showcase" value="1" ${have.showcase ? "checked" : ""} /> In the showcase (display pages)</label>
53 <div class="bar">
54 ${btn("Save demo", { variant: "primary" })}
55 ${btn("Back", { href: `${repoBase(repo)}/builds`, variant: "ghost" })}
56 </div>
57 </form>
58 ${when(pin.demo !== undefined, () => html`<form method="post" action="${action}" class="bar">
59 <button class="btn" data-size="sm" name="do" value="capture">Build and keep its page</button>
60 <button class="btn" data-size="sm" name="do" value="${pin.demo?.showcase === true ? "unshowcase" : "showcase"}">${pin.demo?.showcase === true ? "Take out of the showcase" : "Put in the showcase"}</button>
61 <button class="btn" data-size="sm" data-variant="danger" name="do" value="delete">Clear the demo</button>
62 </form>`)}`,
63 { head: html`${icon("pin")}<h2>Demo of ${label}</h2>` },
64 )}
65 </div>`;
66 return page({ ctx, title: `Demo ${label} · ${repo.name}`, crumbs: crumbsFor(repo), palette: repoPalette(ctx, repo), body });
67 }
68
69 // POST /:owner/:name/builds/:label/demo — `do` names what to do.
70 export async function pinDemoSubmit(ctx: Ctx): Promise<Response> {
71 const repo = loadRepo(ctx);
72 if (!repo) return notFoundPage(ctx);
73 if (!ctx.auth.user) return signInFirst(ctx);
74 const form = await readForm(ctx, "rw");
75 if (form instanceof Response) return form;
76 const label = ctx.params.label ?? "";
77 const user = ctx.auth.user;
78 const todo = formValue(form, "do");
79 const launch = formValue(form, "launch");
80 const edit = `${repoBase(repo)}/builds/${encodeURIComponent(label)}/demo`;
81 let said = "Demo saved.";
82 let result: { ok: boolean; error?: string };
83 if (todo === "save") {
84 result = await saveDemo(ctx.app, user, repo, label, {
85 name: formValue(form, "name").slice(0, 200),
86 version: formValue(form, "version").slice(0, 200),
87 ...(isLaunch(launch) ? { launch } : {}),
88 page: formValue(form, "page").slice(0, 400),
89 showcase: formValue(form, "showcase") !== "",
90 });
91 } else if (todo === "showcase" || todo === "unshowcase") {
92 result = await setShowcase(ctx.app, user, repo, label, todo === "showcase");
93 said = todo === "showcase" ? "In the showcase." : "Out of the showcase.";
94 } else if (todo === "delete") {
95 result = await deleteDemo(ctx.app, user, repo, label);
96 said = "Demo cleared; the pin stays.";
97 } else if (todo === "capture") {
98 result = await captureBuild(ctx.app, user, repo, label);
99 said = "Building its page.";
100 } else return flashTo(ctx, edit, { tone: "danger", message: "Say what to do." });
101 if (!result.ok) {
102 const error = result.error ?? "";
103 if (hiddenError(error)) return notFoundPage(ctx);
104 return flashTo(ctx, edit, { tone: "danger", message: demoSays(error) });
105 }
106 return flashTo(ctx, edit, { message: said });
107 }
test/conversation-confirm.test.ts +1 −1
@@ -121,7 +121,7 @@ describe("the one list of what asks first", () => {
121121 // settings and can be put back. A new `writes: true` tool is on neither list until someone decides.
122122 const NOT_ASKED = new Set([
123123 "access", "account_verify", "app_members", "app_notes", "asks_act", "asks_decide", "asks_proposal", "asks_undecide",
124 "assign", "attach_look", "bet", "board_pins", "board_write", "branches", "capacity", "valves", "cloud_accounts", "close", "confirm_wait",
124 "assign", "attach_look", "bet", "board_pins", "board_write", "branches", "builds", "capacity", "valves", "cloud_accounts", "close", "confirm_wait",
125125 "crew", "decisions_by", "detach", "edit", "email_verify", "feed_chips", "feed_dismiss", "flag_set", "flag_winner",
126126 "follow_mode", "front_page", "hold", "issue_teams", "keep_plan", "labels", "lift", "limb", "make_it_yours", "map", "merge", "new_app",
127127 "next_up", "week", "notify", "org_create", "origin_apps", "pins", "plan", "profile", "propose_to_parent_forge", "repo_labels", "reports",
test/pin-demos-wired.test.ts added +133
@@ -0,0 +1,133 @@
1 /** A pin's demo, reached: the API routes, the page, the MCP `builds` actions and the terminal's keys. */
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 { pinBuild } from "../src/actions/builds.ts";
7 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
8 import { createApp, type App } from "../src/app.ts";
9 import { getRepo, type Repo } from "../src/core/repos.ts";
10 import { createToken } from "../src/core/tokens.ts";
11 import { createUser, type User } from "../src/core/users.ts";
12 import { readBuildPin } from "../src/git/builds.ts";
13 import { repoDir } from "../src/git/repos.ts";
14 import { serve, type Servers } from "../src/http/server.ts";
15 import { createForgeApp } from "../src/tui/forge.ts";
16 import { buildsScreen } from "../src/tui/screens/builds.ts";
17 import { headlessTerminal } from "../src/tui/term/terminal.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19 import { settleApp } from "./helpers/tui.ts";
20
21 quietLogs();
22
23 let dataDir: string;
24 let app: App;
25 let servers: Servers;
26 let ada: User;
27 let repo: Repo;
28 const tok: Record<string, string> = {};
29 const pin = (label: string) => readBuildPin(repoDir(app.reposRoot, "ada", "game"), label);
30 const auth = (who: string) => ({ authorization: `Bearer ${tok[who]}`, "content-type": "application/json" });
31 const url = (label: string, tail = "") => `${servers.url}/api/v1/repos/ada/game/builds/${label}/demo${tail}`;
32
33 beforeAll(async () => {
34 dataDir = await mkdtemp(join(tmpdir(), "forge-pin-demos-wired-"));
35 app = createApp({ dataDir, port: 0 });
36 servers = await serve(app);
37 const make = async (username: string, kind?: "agent") => {
38 const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: username === "ada", ...(kind ? { kind } : {}) } as never);
39 if (!made.ok) throw new Error(made.error);
40 return made.value;
41 };
42 ada = await make("ada");
43 const sam = await make("sam");
44 tok["ada"] = createToken(app.db, ada.id, "rw", "rw").token;
45 tok["sam"] = createToken(app.db, sam.id, "rw", "rw").token;
46 const made = await createRepo(app, ada, { name: "game", visibility: "public" });
47 if (!made.ok) throw new Error(String(made.error));
48 repo = getRepo(app.db, "ada", "game")!;
49 const c = await commitToBranch(app, ada, repo, { message: "one", files: [{ path: "a.txt", content: "a\n" }] });
50 if (!c.ok) throw new Error(JSON.stringify(c.error));
51 for (const label of ["v1", "v2", "v3", "v4"]) {
52 const pinned = await pinBuild(app, ada, repo, { label, oid: c.value.commitOid });
53 if (!pinned.ok) throw new Error(String(pinned.error));
54 }
55 }, 30_000);
56
57 afterAll(async () => {
58 servers?.stop();
59 app?.close();
60 await rm(dataDir, { recursive: true, force: true });
61 });
62
63 test("the API sets, showcases, unshowcases and clears a demo; a stranger is refused", async () => {
64 const body = JSON.stringify({ name: "Game", version: "1", launch: "env", page: "/", showcase: false });
65 expect((await fetch(url("v1"), { method: "PUT", headers: auth("sam"), body })).status).toBe(403);
66 expect((await pin("v1"))?.demo).toBeUndefined();
67 expect((await fetch(url("v1"), { method: "PUT", headers: auth("ada"), body })).status).toBe(200);
68 expect((await pin("v1"))?.demo?.name).toBe("Game");
69 expect((await fetch(url("v1"), { method: "PUT", headers: auth("ada"), body: JSON.stringify({ name: "", version: "1", page: "/" }) })).status).toBe(422);
70 await fetch(url("v1", "/showcase"), { method: "POST", headers: auth("ada"), body: JSON.stringify({ on: true }) });
71 expect((await pin("v1"))?.demo?.showcase).toBe(true);
72 await fetch(url("v1", "/showcase"), { method: "POST", headers: auth("ada"), body: JSON.stringify({ on: false }) });
73 expect((await pin("v1"))?.demo?.showcase).toBe(false);
74 expect((await fetch(url("v1", "/capture"), { method: "POST", headers: auth("ada") })).status).toBe(422);
75 expect((await fetch(url("v1"), { method: "DELETE", headers: auth("ada") })).status).toBe(204);
76 expect((await pin("v1"))?.demo).toBeUndefined();
77 expect((await fetch(url("nope"), { method: "DELETE", headers: auth("ada") })).status).toBe(404);
78 });
79
80 test("the demo page is a writer's, and its POST saves", async () => {
81 const page = `${servers.url}/ada/game/builds/v2/demo`;
82 expect((await fetch(page, { headers: { authorization: auth("ada").authorization } })).status).toBe(200);
83 expect((await fetch(page, { headers: { authorization: auth("sam").authorization } })).status).toBe(404);
84 const form = new URLSearchParams({ do: "save", name: "Page demo", version: "2", launch: "env", page: "/", showcase: "1" });
85 const res = await fetch(page, { method: "POST", redirect: "manual", headers: { authorization: auth("ada").authorization, origin: servers.url }, body: form });
86 expect(res.status).toBeLessThan(400);
87 expect((await pin("v2"))?.demo).toMatchObject({ name: "Page demo", showcase: true });
88 const cross = await fetch(page, { method: "POST", redirect: "manual", headers: { authorization: auth("ada").authorization, origin: "https://evil.example" }, body: new URLSearchParams({ do: "delete" }) });
89 expect(cross.status).toBe(403);
90 expect((await pin("v2"))?.demo).toBeDefined();
91 });
92
93 async function mcp(who: string, args: unknown): Promise<{ error?: string; value?: any }> {
94 const res = await fetch(`${servers.url}/mcp`, {
95 method: "POST",
96 headers: { ...auth(who), accept: "application/json, text/event-stream" },
97 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "builds", arguments: args } }),
98 });
99 const body = (await res.json()) as any;
100 const text: string = body.result.content[0].text;
101 return body.result.isError === true ? { error: text } : { value: JSON.parse(text) };
102 }
103
104 test("the MCP builds tool edits a demo for a writer and refuses others", async () => {
105 const set = await mcp("ada", { repo: "ada/game", action: "demo", label: "v3", name: "Mcp", version: "3", launch: "env", page: "/" });
106 expect(set.value.pin.demo.name).toBe("Mcp");
107 expect((await mcp("ada", { repo: "ada/game", action: "showcase", label: "v3" })).value.pin.demo.showcase).toBe(true);
108 expect((await mcp("sam", { repo: "ada/game", action: "clear_demo", label: "v3" })).error).toContain("forbidden");
109 expect((await mcp("ada", { repo: "ada/game", action: "clear_demo", label: "v3" })).value.pin.demo).toBeUndefined();
110 expect((await mcp("ada", { repo: "ada/game", action: "demo" })).error).toContain("invalid_label");
111 });
112
113 test("the terminal's m, w and x keys set, showcase and clear a demo", async () => {
114 const terminal = headlessTerminal(100, 30);
115 const guest = { sshUsername: "git", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: ada };
116 const { app: tui, session } = createForgeApp(app, guest, { terminal, exitHooks: false });
117 tui.start();
118 tui.ctx.push(buildsScreen(session, tui.ctx, repo));
119 await settleApp(tui);
120 const press = async (...keys: string[]) => {
121 for (const key of keys) tui.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false });
122 await settleApp(tui);
123 };
124 // The first row is picked.
125 await press("m");
126 await press("enter");
127 expect((await pin("v1"))?.demo).toMatchObject({ name: "game", version: "v1", showcase: false });
128 await press("w");
129 expect((await pin("v1"))?.demo?.showcase).toBe(true);
130 await press("x");
131 expect((await pin("v1"))?.demo).toBeUndefined();
132 tui.stop?.();
133 });
test/security-floor-routes.test.ts +1
@@ -58,6 +58,7 @@ const UNSEEDED: Record<string, string> = {
5858 "/:owner/:name/bets/:id": BET,
5959 "/:owner/:name/builds/:label/cart": CART,
6060 "/:owner/:name/builds/:label/cart.png": CART,
61 "/:owner/:name/builds/:label/demo": "needs a pin with a demo saved on it; the seed pins nothing",
6162 "/:owner/:name/builds/:label/shots": SHOT,
6263 "/:owner/:name/builds/:label/shots/:file": SHOT,
6364 "/:owner/:name/looks/:env/:commit/:kind.png": LOOK,

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs