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

A pull can carry a look a person attached: an image at a stated width, beside the crew's own looks #1001

Closed opened this in answer to
Closed without merging

scout/forge:scout/791-a-pull-can-carry-a-look-a-person-attache → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
13 files changed +796 −2
docs/APPS.md +13
@@ -754,6 +754,19 @@ its pull closes. Files live under `<data>/looks/<app id>/<env>/`; rows in
754754 on `PATH`, `FORGE_CHROMIUM`, or the Mac's own; the image ships one. A forge
755755 without one says so once at boot, and on every pull.
756756
757 **A look a person attaches (#791).** A person who can write the repository
758 may put a picture of their own on a pull: `POST
759 /api/v1/repos/:owner/:name/pulls/:number/looks` with
760 `{"width": "phone"|"desktop", "shows": "<one line, at most 200 characters>",
761 "image": "<PNG or JPEG, base64>"}` — at most 4 MB of image — or the MCP's
762 `attach_look` (dry run by default). The type is found from the bytes, not
763 believed. An agent, a reader and a stranger are refused; the crew's own
764 looks keep the preview's path. `GET` the same route lists them. They are
765 kept apart from the preview's looks (table `pull_look`, files under
766 `<data>/looks/attached/`), so a retake never sweeps them away, and show on
767 the change's page as "Attached looks", the writers' to see and fetch, at
768 `/:owner/:name/pulls/:number/looks/:id`.
769
757770 ## The crew
758771
759772 An agent is created once (`New agent`: a name, a model, a brief) and given
src/actions/pull_looks.ts added +154
@@ -0,0 +1,154 @@
1 /**
2 * Attaching a look to a pull (#791). A person who writes the repository
3 * hands over an image (a PNG or a JPEG), the width it was taken at and one
4 * line on what it shows. The bytes are checked as bytes — the claimed type
5 * is never believed — and what is kept is only ever from a writer: a
6 * reader and a stranger are refused before a byte is looked at. An agent
7 * is refused too; the crew's own looks come from the preview.
8 */
9
10 import { mkdirSync, rmSync, writeFileSync } from "node:fs";
11 import { dirname, join } from "node:path";
12 import type { App } from "../app.ts";
13 import {
14 addAttachedLook,
15 attachedPath,
16 cleanShows,
17 isAttachedKind,
18 newAttachedId,
19 type AttachedLook,
20 type AttachedMime,
21 } from "../core/pull_looks.ts";
22 import type { Pull } from "../core/pulls.ts";
23 import { canRead, canWrite, type Repo } from "../core/repos.ts";
24 import type { User } from "../core/users.ts";
25 import { isPng, pngHeader } from "../design/image/png.ts";
26 import { err, ok, type Result } from "../kernel/result.ts";
27 import type { AccessError } from "./access.ts";
28
29 /** The most an image may weigh: a few megabytes. */
30 export const ATTACHED_MAX_BYTES = 4 * 1024 * 1024;
31 /** The request that carries one: the image in base64, and a little JSON. */
32 export const ATTACH_BODY_MAX = Math.ceil((ATTACHED_MAX_BYTES * 4) / 3) + 16 * 1024;
33
34 export type AttachError =
35 | AccessError
36 | "bad_width"
37 | "empty_shows"
38 | "shows_too_long"
39 | "not_base64"
40 | "empty_image"
41 | "image_too_large"
42 | "not_an_image";
43
44 /** What the bytes are, by their own signature; undefined if neither. */
45 export function sniffImage(bytes: Uint8Array): AttachedMime | undefined {
46 if (isPng(bytes)) return pngHeader(bytes).ok ? "image/png" : undefined;
47 if (
48 bytes.length > 4 &&
49 bytes[0] === 0xff &&
50 bytes[1] === 0xd8 &&
51 bytes[2] === 0xff &&
52 // The end-of-image marker closes a whole file.
53 bytes[bytes.length - 2] === 0xff &&
54 bytes[bytes.length - 1] === 0xd9
55 )
56 return "image/jpeg";
57 return undefined;
58 }
59
60 /** Strict base64 (standard alphabet, padding optional); nothing else passes. */
61 function decodeBase64(raw: string): Uint8Array | undefined {
62 // A data: URL's prefix is tolerated; anything else non-base64 is not.
63 const text = raw.replace(/^data:image\/(png|jpeg);base64,/, "").trim();
64 if (!/^[A-Za-z0-9+/\s]*={0,2}$/.test(text)) return undefined;
65 return new Uint8Array(Buffer.from(text, "base64"));
66 }
67
68 export interface AttachInput {
69 readonly width: string;
70 readonly shows: string;
71 /** The image, base64. */
72 readonly image: string;
73 }
74
75 /** A person, never an agent, who writes the repository the pull is in. */
76 export function requireAttacher(
77 app: App,
78 actor: User | undefined,
79 repo: Repo,
80 pull: Pull,
81 ): Result<User, AccessError> {
82 if (pull.repoId !== repo.id || !canRead(app.db, repo, actor))
83 return err("not_found");
84 if (!actor) return err("unauthorized");
85 if (actor.kind !== "user" || !canWrite(app.db, repo, actor))
86 return err("forbidden");
87 return ok(actor);
88 }
89
90 export function attachLook(
91 app: App,
92 actor: User | undefined,
93 repo: Repo,
94 pull: Pull,
95 input: AttachInput,
96 dry = false,
97 ): Result<AttachedLook, AttachError> {
98 const who = requireAttacher(app, actor, repo, pull);
99 if (!who.ok) return who;
100 const person = who.value;
101 const kind = input.width.trim().toLowerCase();
102 if (!isAttachedKind(kind)) return err("bad_width");
103 const shows = cleanShows(input.shows);
104 if (!shows.ok) return shows;
105 if (input.image.trim() === "") return err("empty_image");
106 // Judged on its length before it is decoded, so no big buffer is made.
107 if (input.image.length > ATTACH_BODY_MAX) return err("image_too_large");
108 const bytes = decodeBase64(input.image);
109 if (bytes === undefined) return err("not_base64");
110 if (bytes.length === 0) return err("empty_image");
111 if (bytes.length > ATTACHED_MAX_BYTES) return err("image_too_large");
112 const mime = sniffImage(bytes);
113 if (mime === undefined) return err("not_an_image");
114 const id = newAttachedId();
115 const path = attachedPath(repo.id, pull.id, id, mime);
116 const row = {
117 id,
118 pullId: pull.id,
119 kind,
120 shows: shows.value,
121 mime,
122 path,
123 userId: person.id,
124 };
125 if (dry)
126 return ok({ ...row, userName: person.username, createdAt: new Date().toISOString() });
127 const file = join(app.config.dataDir, path);
128 mkdirSync(dirname(file), { recursive: true });
129 writeFileSync(file, bytes);
130 let look: AttachedLook;
131 try {
132 look = addAttachedLook(app.db, row);
133 } catch (error) {
134 rmSync(file, { force: true });
135 throw error;
136 }
137 app.bus.append({
138 kind: "pull.look_attached",
139 repoId: repo.id,
140 actorId: person.id,
141 payload: { number: pull.number, width: kind, shows: shows.value },
142 });
143 return ok(look);
144 }
145
146 export const attachedJson = (look: AttachedLook, url: string) => ({
147 id: look.id,
148 width: look.kind,
149 shows: look.shows,
150 type: look.mime,
151 by: look.userName,
152 createdAt: look.createdAt,
153 url,
154 });
src/core/pull_looks.ts added +130
@@ -0,0 +1,130 @@
1 /**
2 * A look a person attached to a pull (#791): an image taken at a stated
3 * width, with one line on what it shows. It is kept beside the crew's own
4 * looks (`core/looks.ts`) but apart from them — a retake of the preview
5 * never sweeps it away. Pure data: no authz, no events, no files.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { id as newId } from "../kernel/id.ts";
10 import { err, ok, type Result } from "../kernel/result.ts";
11
12 /** The widths a person states: a phone's, or a desktop's. */
13 export type AttachedKind = "phone" | "desktop";
14 export const ATTACHED_KINDS: readonly AttachedKind[] = ["phone", "desktop"];
15 export const isAttachedKind = (v: string): v is AttachedKind =>
16 (ATTACHED_KINDS as readonly string[]).includes(v);
17
18 export type AttachedMime = "image/png" | "image/jpeg";
19
20 /** One line, with room. */
21 export const SHOWS_MAX = 200;
22
23 /** The line as it will be kept: plain, one line, or why it will not be. */
24 export function cleanShows(
25 raw: string,
26 ): Result<string, "empty_shows" | "shows_too_long"> {
27 // Control characters (but not spaces) are dropped before the line is judged.
28 const line = raw
29 // eslint-disable-next-line no-control-regex
30 .replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, "")
31 .replace(/\s+/g, " ")
32 .trim();
33 if (line === "") return err("empty_shows");
34 if (line.length > SHOWS_MAX) return err("shows_too_long");
35 return ok(line);
36 }
37
38 export interface AttachedLook {
39 readonly id: string;
40 readonly pullId: string;
41 readonly kind: AttachedKind;
42 readonly shows: string;
43 readonly mime: AttachedMime;
44 /** Relative to the data directory. */
45 readonly path: string;
46 readonly userId: string;
47 readonly userName: string;
48 readonly createdAt: string;
49 }
50
51 interface Row {
52 id: string;
53 pull_id: string;
54 kind: AttachedKind;
55 shows: string;
56 mime: AttachedMime;
57 path: string;
58 user_id: string;
59 user_name: string;
60 created_at: string;
61 }
62
63 const SELECT = `SELECT pull_look.*, user.username AS user_name
64 FROM pull_look JOIN user ON user.id = pull_look.user_id`;
65
66 const toLook = (r: Row): AttachedLook => ({
67 id: r.id,
68 pullId: r.pull_id,
69 kind: r.kind,
70 shows: r.shows,
71 mime: r.mime,
72 path: r.path,
73 userId: r.user_id,
74 userName: r.user_name,
75 createdAt: r.created_at,
76 });
77
78 /** Kept in a file named by its own id, under the pull. */
79 export const attachedPath = (
80 repoId: string,
81 pullId: string,
82 lookId: string,
83 mime: AttachedMime,
84 ): string =>
85 `looks/attached/${repoId}/${pullId}/${lookId}.${mime === "image/png" ? "png" : "jpg"}`;
86
87 export const newAttachedId = (): string => newId();
88
89 export function addAttachedLook(
90 db: Database,
91 input: Omit<AttachedLook, "createdAt" | "userName">,
92 ): AttachedLook {
93 db.query(
94 `INSERT INTO pull_look (id, pull_id, kind, shows, mime, path, user_id)
95 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)`,
96 ).run(
97 input.id,
98 input.pullId,
99 input.kind,
100 input.shows,
101 input.mime,
102 input.path,
103 input.userId,
104 );
105 return getAttachedLook(db, input.pullId, input.id)!;
106 }
107
108 export function getAttachedLook(
109 db: Database,
110 pullId: string,
111 id: string,
112 ): AttachedLook | undefined {
113 const row = db
114 .query<Row, [string, string]>(
115 `${SELECT} WHERE pull_look.pull_id = ?1 AND pull_look.id = ?2`,
116 )
117 .get(pullId, id);
118 return row ? toLook(row) : undefined;
119 }
120
121 /** A pull's attached looks, newest first. */
122 export function attachedLooks(db: Database, pullId: string): AttachedLook[] {
123 return db
124 .query<Row, [string]>(
125 `${SELECT} WHERE pull_look.pull_id = ?1
126 ORDER BY pull_look.created_at DESC, pull_look.id DESC`,
127 )
128 .all(pullId)
129 .map(toLook);
130 }
src/core/schema.ts +17
@@ -1540,4 +1540,21 @@ export const migrations: readonly string[] = [
15401540 SELECT RAISE(ABORT, 'a sealed repository is never public');
15411541 END;
15421542 `,
1543 // 71 — a look a person attached to a pull (#791): an image at a stated
1544 // width and one line on what it shows, kept beside the crew's own looks
1545 // but not among them — a retake of the preview never sweeps it away. Rows
1546 // go with the pull.
1547 `
1548 CREATE TABLE pull_look (
1549 id TEXT PRIMARY KEY,
1550 pull_id TEXT NOT NULL REFERENCES issue(id) ON DELETE CASCADE,
1551 kind TEXT NOT NULL CHECK (kind IN ('phone','desktop')),
1552 shows TEXT NOT NULL,
1553 mime TEXT NOT NULL CHECK (mime IN ('image/png','image/jpeg')),
1554 path TEXT NOT NULL,
1555 user_id TEXT NOT NULL REFERENCES user(id),
1556 created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
1557 );
1558 CREATE INDEX pull_look_pull ON pull_look(pull_id, created_at);
1559 `,
15431560 ];
src/design/activity.ts +1
@@ -107,6 +107,7 @@ const WORDS: Record<string, string> = {
107107 "pull.labeled": "labelled a pull request",
108108 "pull.held": "held a pull request",
109109 "pull.released": "released a pull request",
110 "pull.look_attached": "attached a look to a pull request",
110111 "pull.thread_resolved": "resolved a review thread",
111112 "repo.created": "created a repository",
112113 "repo.forked": "forked a repository",
src/http/api.ts +65
@@ -96,6 +96,14 @@ import {
9696 MAX_REVIEW_LINES,
9797 type ReviewInput,
9898 } from "../actions/pulls.ts";
99 import {
100 ATTACH_BODY_MAX,
101 attachedJson,
102 attachLook,
103 requireAttacher,
104 } from "../actions/pull_looks.ts";
105 import { attachedLooks } from "../core/pull_looks.ts";
106 import { attachedUrl, mayFetchAttached } from "../web/pages/looks.ts";
99107 import { holdPull, releasePull } from "../actions/holds.ts";
100108 import { getHold, type Hold } from "../core/holds.ts";
101109 import { watchMilestone } from "../actions/watches.ts";
@@ -2855,6 +2863,63 @@ export function apiRoutes(router: Router<Handler>): void {
28552863 },
28562864 );
28572865
2866 // A look a person attaches to a pull (#791): an image (PNG or JPEG, as
2867 // base64), the width it was taken at and one line on what it shows. The
2868 // crew's own looks come from the preview and keep that path.
2869 router.add(
2870 "GET",
2871 "/api/v1/repos/:owner/:name/pulls/:number/looks",
2872 (ctx) => {
2873 const found = loadPull(ctx);
2874 if ("error" in found) return found.error;
2875 const looks = mayFetchAttached(ctx, found.repo)
2876 ? attachedLooks(ctx.app.db, found.pull.id)
2877 : [];
2878 return json({
2879 looks: looks.map((l) =>
2880 attachedJson(l, attachedUrl(found.repo, found.pull, l)),
2881 ),
2882 });
2883 },
2884 );
2885 router.add(
2886 "POST",
2887 "/api/v1/repos/:owner/:name/pulls/:number/looks",
2888 async (ctx) => {
2889 const denied = requireScope(ctx, "rw");
2890 if (denied) return denied;
2891 const found = loadPull(ctx);
2892 if ("error" in found) return found.error;
2893 // Who may post is settled before the body is read.
2894 const who = requireAttacher(ctx.app, ctx.auth.user, found.repo, found.pull);
2895 if (!who.ok) return respondAccess(who.error, 403);
2896 const input = await boundedBody(ctx.request, ATTACH_BODY_MAX);
2897 if (input === "too_large")
2898 return apiError("too_large", 413, "the image is too large");
2899 const attached = attachLook(ctx.app, ctx.auth.user, found.repo, found.pull, {
2900 width: str(input.width),
2901 shows: str(input.shows),
2902 image: str(input.image),
2903 });
2904 if (!attached.ok)
2905 return respondAccess(
2906 attached.error,
2907 attached.error === "image_too_large"
2908 ? 413
2909 : attached.error === "not_an_image"
2910 ? 415
2911 : 422,
2912 );
2913 return json(
2914 attachedJson(
2915 attached.value,
2916 attachedUrl(found.repo, found.pull, attached.value),
2917 ),
2918 201,
2919 );
2920 },
2921 );
2922
28582923 // Line-anchored review comments. The anchor is (path, side, line) in the
28592924 // pull's current diff; the server takes the content hash, so a client never
28602925 // handles one — and a later force-push marks the comment `outdated`.
src/http/mcp.ts +78
@@ -33,6 +33,7 @@ import {
3333 unlinkIssue,
3434 } from "../actions/dependencies.ts";
3535 import { holdPull, releasePull } from "../actions/holds.ts";
36 import { ATTACHED_MAX_BYTES, attachLook } from "../actions/pull_looks.ts";
3637 import { openPlan, parsePlan, PLAN_MAX } from "../actions/plan.ts";
3738 import { cancelRepoRun } from "../actions/runs.ts";
3839 import { clientRows } from "../spawn/clients.ts";
@@ -169,6 +170,16 @@ function repoArg(ctx: Ctx, user: User, args: Args): Repo | Answer {
169170 : bad("not_found", "no such app or repository (owner/name)");
170171 }
171172
173 const ATTACH_WORDS: Readonly<Record<string, string>> = {
174 bad_width: "width is phone or desktop",
175 empty_shows: "say what it shows in one line (shows)",
176 shows_too_long: "say what it shows in one line, at most 200 characters (shows)",
177 empty_image: "send the image, base64 (image)",
178 not_base64: "image is not base64",
179 image_too_large: `the image is over ${ATTACHED_MAX_BYTES / 1024 / 1024} MB`,
180 not_an_image: "image is not a PNG or a JPEG",
181 };
182
172183 const APP_ARG = {
173184 type: "string",
174185 description: "The app, as owner/name.",
@@ -1528,6 +1539,73 @@ const TOOLS: readonly Tool[] = [
15281539 });
15291540 },
15301541 },
1542 {
1543 name: "attach_look",
1544 description: `Attach a look to a pull: an image a person took at a stated width, shown beside the crew's own looks on the change's page. For a person who can write the app (an agent is refused: its own looks come from the preview). \`image\` is a PNG or JPEG, base64, at most ${ATTACHED_MAX_BYTES / 1024 / 1024} MB; \`width\` is phone or desktop; \`shows\` is one line (at most 200 characters) on what it shows. It plans first — \`dryRun\` is true unless you say false — and checks everything, storing nothing.`,
1545 inputSchema: {
1546 type: "object",
1547 properties: {
1548 app: APP_ARG,
1549 pull: { type: "integer", description: "The pull's number." },
1550 width: {
1551 type: "string",
1552 enum: ["phone", "desktop"],
1553 description: "The width the image was taken at.",
1554 },
1555 shows: {
1556 type: "string",
1557 description: "One line on what the image shows.",
1558 },
1559 image: { type: "string", description: "The PNG or JPEG, base64." },
1560 dryRun: {
1561 type: "boolean",
1562 description: "Check only (the default). Send false to attach it.",
1563 },
1564 },
1565 required: ["app", "pull", "width", "shows", "image"],
1566 },
1567 writes: true,
1568 dryByDefault: true,
1569 run(ctx, user, args) {
1570 const repo = planRepo(ctx, user, args);
1571 if (isAnswer(repo)) return repo;
1572 const n = args["pull"];
1573 const pull =
1574 typeof n === "number" && Number.isInteger(n) && n > 0
1575 ? getPull(ctx.app.db, repo.id, n)
1576 : undefined;
1577 if (pull === undefined)
1578 return bad("no_such_pull", `no pull #${String(n)}`);
1579 const dry = args["dryRun"] !== false;
1580 const name = `${repo.ownerName}/${repo.name}#${pull.number}`;
1581 const attached = attachLook(
1582 ctx.app,
1583 user,
1584 repo,
1585 pull,
1586 {
1587 width: str(args["width"]),
1588 shows: str(args["shows"]),
1589 image: typeof args["image"] === "string" ? args["image"] : "",
1590 },
1591 dry,
1592 );
1593 if (!attached.ok)
1594 return bad(
1595 attached.error,
1596 ATTACH_WORDS[attached.error] ??
1597 "attaching a look is for a person who can write this app",
1598 );
1599 return good({
1600 says: dry
1601 ? `Would attach a ${attached.value.kind} look to ${name}: "${attached.value.shows}". Nothing changed; send dryRun: false to do it.`
1602 : `Attached a ${attached.value.kind} look to ${name}. It shows beside the crew's own.`,
1603 attached: !dry,
1604 look: { id: attached.value.id, width: attached.value.kind },
1605 dryRun: dry,
1606 });
1607 },
1608 },
15311609 {
15321610 name: "plan",
15331611 description: `Open several small issues and link them in one call: all of them or none. Each item has a key, a title, a body and optionally blockedBy, a list of keys of this plan or numbers of issues already open. Where the app has pillars (umbrella issues titled like "P0 Trust: …"), each item also says what it is for: pillar, the one it serves, or later: true with why, one sentence, which puts it behind the Later gate instead of on the ready list; an item that says neither is refused. A bad link (loop, unknown key) refuses the whole plan and names the item. At most ${PLAN_MAX} issues. Answers with the numbers opened, by key, what is ready now, and what waits for later.`,
src/http/server.ts +2 −1
@@ -228,7 +228,7 @@ import {
228228 runSteer,
229229 runsList,
230230 } from "../web/pages/runs.ts";
231 import { lookImage } from "../web/pages/looks.ts";
231 import { attachedImage, lookImage } from "../web/pages/looks.ts";
232232 import { bigRedirect, boardPage } from "../web/pages/board.ts";
233233 import { returnsPage } from "../web/pages/returns.ts";
234234 import {
@@ -962,6 +962,7 @@ export function buildRouter(): Router<Handler> {
962962 router.add("POST", "/:owner/:name/runs/:id/steer", runSteer);
963963 // The pictures of an environment, read like the repository.
964964 router.add("GET", "/:owner/:name/looks/:env/:commit/:kind.png", lookImage);
965 router.add("GET", "/:owner/:name/pulls/:number/looks/:id", attachedImage);
965966
966967 // Live event stream for a repo the viewer can read.
967968 // Everything the viewer may see, live. Pages with live regions listen here.
src/web/pages/looks.ts +67
@@ -27,6 +27,8 @@ import type { Pull } from "../../core/pulls.ts";
2727 import { canEnterApp, canSeeOwnerFacts, type Repo } from "../../core/repos.ts";
2828 import type { Ctx } from "../../http/context.ts";
2929 import { notFound } from "../../http/respond.ts";
30 import { getPull, type Pull as PullRow } from "../../core/pulls.ts";
31 import { attachedLooks, getAttachedLook, type AttachedLook } from "../../core/pull_looks.ts";
3032 import { keepLook } from "../../looks/service.ts";
3133 import { loadRepo, repoBase } from "../chrome.ts";
3234 import { html, when, type Html } from "../html.ts";
@@ -259,3 +261,68 @@ export function lookThumb(href: string, src: string): Html {
259261 ><img src="${src}" width="30" height="40" alt="" loading="lazy"
260262 /></a>`;
261263 }
264
265 /**
266 * Whether this viewer may see what a person attached to a pull. The
267 * writers, all of them — as with the pictures the owner is shown. Only a
268 * writer can attach one, so nothing a stranger sends is ever on the list.
269 */
270 export const mayFetchAttached = (ctx: Ctx, repo: Repo): boolean =>
271 canSeeOwnerFacts(ctx.app.db, repo, ctx.auth.user);
272
273 /** Where an attached look is served. */
274 export const attachedUrl = (repo: Repo, pull: { number: number }, look: AttachedLook): string =>
275 `${repoBase(repo)}/pulls/${pull.number}/looks/${look.id}`;
276
277 // GET /:owner/:name/pulls/:number/looks/:id — the bytes of an attached look,
278 // served under the type the bytes were found to be, never one the sender named.
279 export function attachedImage(ctx: Ctx): Response {
280 const repo = loadRepo(ctx);
281 const raw = ctx.params.number ?? "";
282 const number = /^[1-9][0-9]{0,9}$/.test(raw) ? Number(raw) : undefined;
283 if (!repo || number === undefined || !mayFetchAttached(ctx, repo))
284 return notFound();
285 const pull = getPull(ctx.app.db, repo.id, number);
286 const look =
287 pull === undefined
288 ? undefined
289 : getAttachedLook(ctx.app.db, pull.id, ctx.params.id ?? "");
290 if (look === undefined) return notFound();
291 const path = join(ctx.app.config.dataDir, look.path);
292 if (!existsSync(path)) return notFound();
293 return new Response(Bun.file(path), {
294 headers: {
295 "content-type": look.mime,
296 // Named by its own id, which is never reused.
297 "cache-control": "private, max-age=31536000, immutable",
298 "content-disposition": "inline",
299 },
300 });
301 }
302
303 /**
304 * The looks people attached to a pull, at the widths they stated, each
305 * with its line and who attached it. Nothing for a viewer who may not see
306 * them, and nothing when there are none.
307 */
308 export function attachedCard(ctx: Ctx, repo: Repo, pull: PullRow): Html {
309 if (!mayFetchAttached(ctx, repo)) return html``;
310 const looks = attachedLooks(ctx.app.db, pull.id);
311 if (looks.length === 0) return html``;
312 const figure = (look: AttachedLook): Html => {
313 const url = attachedUrl(repo, pull, look);
314 return html`<figure class="look-attached look-attached-${look.kind}">
315 <a class="look look-${look.kind}" href="${url}"
316 ><img src="${url}" alt="${look.shows}" loading="lazy"
317 /></a>
318 <figcaption class="muted small">
319 ${look.kind} · ${look.shows} · ${look.userName} · ${time(look.createdAt)}
320 </figcaption>
321 </figure>`;
322 };
323 return card(html`<div class="look-pair look-pair-attached">${looks.map(figure)}</div>`, {
324 head: html`${icon("eye")}
325 <h2>Attached looks</h2>`,
326 extra: "look-card",
327 });
328 }
src/web/studio/change.ts +2 −1
@@ -57,7 +57,7 @@ import {
5757 type Tone,
5858 } from "../ui.ts";
5959 import { previewCard } from "../pages/apps.ts";
60 import { lookCard } from "../pages/looks.ts";
60 import { attachedCard, lookCard } from "../pages/looks.ts";
6161 import { pullState } from "../pages/pulls.ts";
6262 import { workSpent } from "../pages/runs.ts";
6363 import {
@@ -501,6 +501,7 @@ async function changeConversation(
501501 ${when(wall, (w) => wallCard(w))} ${decisionSection}
502502 ${takeBackSection}
503503 ${when(record, (r) => lookCard(ctx, repo, r, pull, pull.headOid))}
504 ${attachedCard(ctx, repo, pull)}
504505 <div class="split">
505506 <div>
506507 ${talk.node}
src/web/style/content.ts +4
@@ -810,6 +810,10 @@ form.inline { display: inline; margin-left: auto; }
810810 .look img { display: block; width: 100%; height: auto; }
811811 .look-phone { flex: 0 0 200px; }
812812 .look-desktop { flex: 1 1 320px; min-width: 0; max-width: 1280px; }
813 .look-attached { margin: 0; display: flex; flex-direction: column; gap: 6px; }
814 .look-pair-attached { flex-wrap: wrap; }
815 .look-pair-attached .look-attached-desktop { flex: 1 1 320px; min-width: 0; max-width: 1280px; }
816 .look-pair-attached .look-attached-phone { flex: 0 0 200px; }
813817 @media (max-width: 640px) {
814818 .look-pair { flex-direction: column; }
815819 .look-phone { flex-basis: auto; width: 200px; }
test/mcp.test.ts +1
@@ -192,6 +192,7 @@ describe("the forge over MCP", () => {
192192 "link",
193193 "unlink",
194194 "hold",
195 "attach_look",
195196 "plan",
196197 "capacity",
197198 "report",
test/pull-looks.test.ts added +262
@@ -0,0 +1,262 @@
1 /**
2 * A pull can carry a look a person attached (#791): an image at a stated
3 * width and one line on what it shows, shown on the change's page. The
4 * refusals come first: a stranger, a reader, an agent, an oversized or
5 * non-image upload; and nothing a stranger sends is ever shown.
6 */
7
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { existsSync } from "node:fs";
10 import { mkdtemp, rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { addToCrew, createAgent } from "../src/actions/crew.ts";
14 import { ATTACHED_MAX_BYTES, sniffImage } from "../src/actions/pull_looks.ts";
15 import { openPull } from "../src/actions/pulls.ts";
16 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
17 import { createApp, type App } from "../src/app.ts";
18 import { attachedLooks } from "../src/core/pull_looks.ts";
19 import type { Pull } from "../src/core/pulls.ts";
20 import { createToken } from "../src/core/tokens.ts";
21 import { createUser, type User } from "../src/core/users.ts";
22 import { serve, type Servers } from "../src/http/server.ts";
23
24 const PNG = Buffer.from(
25 "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==",
26 "base64",
27 );
28 const JPEG = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0, 0x10, 0xff, 0xd9]);
29 const b64 = (b: Uint8Array) => Buffer.from(b).toString("base64");
30
31 describe("a look a person attaches to a pull", () => {
32 let dataDir: string;
33 let app: App;
34 let servers: Servers;
35 let base: string;
36 let pull: Pull;
37 let alice: User;
38 const tokens: Record<string, string> = {};
39
40 const person = async (username: string): Promise<User> => {
41 const made = await createUser(app.db, {
42 trusted: true,
43 username,
44 email: `${username}@forge.local`,
45 password: "a-good-passphrase",
46 adminIfFirst: username === "alice",
47 });
48 if (!made.ok) throw new Error(made.error);
49 return made.value;
50 };
51
52 beforeAll(async () => {
53 dataDir = await mkdtemp(join(tmpdir(), "forge-pull-looks-"));
54 app = createApp({ dataDir, port: 0 });
55 alice = await person("alice");
56 const bob = await person("bob");
57 const bot = await createAgent(app, alice, { username: "bot" });
58 if (!bot.ok) throw new Error(String(bot.error));
59 const made = await createRepo(app, alice, {
60 name: "garden",
61 visibility: "public",
62 });
63 if (!made.ok) throw new Error(String(made.error));
64 const repo = made.value;
65 await commitToBranch(app, alice, repo, {
66 message: "seed",
67 files: [{ path: "README.md", content: "# garden\n" }],
68 });
69 await commitToBranch(app, alice, repo, {
70 branch: "one",
71 base: "main",
72 message: "one",
73 files: [{ path: "one.md", content: "x\n" }],
74 });
75 const opened = await openPull(app, alice, repo, {
76 title: "Change one",
77 body: "",
78 baseBranch: "main",
79 headBranch: "one",
80 });
81 if (!opened.ok) throw new Error(String(opened.error));
82 pull = opened.value;
83 expect(addToCrew(app, alice, repo, "bot").ok).toBe(true);
84 tokens["alice"] = createToken(app.db, alice.id, "t", "rw").token;
85 tokens["aliceRo"] = createToken(app.db, alice.id, "t", "ro").token;
86 tokens["bob"] = createToken(app.db, bob.id, "t", "rw").token;
87 tokens["bot"] = createToken(app.db, bot.value.user.id, "run", "rw").token;
88 servers = await serve(app);
89 base = servers.url;
90 }, 30_000);
91
92 afterAll(async () => {
93 servers.stop();
94 app.close();
95 await rm(dataDir, { recursive: true, force: true });
96 });
97
98 const post = (token: string | null, payload: unknown, raw?: string) =>
99 fetch(`${base}/api/v1/repos/alice/garden/pulls/${pull.number}/looks`, {
100 method: "POST",
101 headers: {
102 ...(token === null ? {} : { authorization: `Bearer ${token}` }),
103 "content-type": "application/json",
104 },
105 body: raw ?? JSON.stringify(payload),
106 });
107 const good = (over: Record<string, unknown> = {}) => ({
108 width: "phone",
109 shows: "the empty state on a phone",
110 image: b64(PNG),
111 ...over,
112 });
113 const stored = () => attachedLooks(app.db, pull.id);
114 const mcp = async (token: string, args: Record<string, unknown>) => {
115 const res = await fetch(`${base}/mcp`, {
116 method: "POST",
117 headers: {
118 "content-type": "application/json",
119 accept: "application/json, text/event-stream",
120 authorization: `Bearer ${token}`,
121 },
122 body: JSON.stringify({
123 jsonrpc: "2.0",
124 id: 1,
125 method: "tools/call",
126 params: { name: "attach_look", arguments: args },
127 }),
128 });
129 const body = (await res.json()) as any;
130 const text: string = body.result.content[0].text;
131 return body.result.isError === true
132 ? { error: text, value: undefined }
133 : { error: undefined, value: JSON.parse(text) };
134 };
135
136 test("a stranger, a reader, a read-only token and an agent are refused, and nothing is kept", async () => {
137 expect((await post(null, good())).status).toBe(401);
138 expect((await post(tokens["bob"]!, good())).status).toBe(403);
139 expect((await post(tokens["aliceRo"]!, good())).status).toBeGreaterThanOrEqual(401);
140 expect((await post(tokens["bot"]!, good())).status).toBe(403);
141 const told = await mcp(tokens["bob"]!, {
142 app: "alice/garden",
143 pull: pull.number,
144 ...good(),
145 dryRun: false,
146 });
147 expect(told.error).toContain("forbidden");
148 expect(
149 (
150 await mcp(tokens["bot"]!, {
151 app: "alice/garden",
152 pull: pull.number,
153 ...good(),
154 dryRun: false,
155 })
156 ).error,
157 ).toContain("forbidden");
158 expect(stored()).toEqual([]);
159 });
160
161 test("an oversized, non-image or malformed upload is refused", async () => {
162 const big = Buffer.concat([PNG, Buffer.alloc(ATTACHED_MAX_BYTES + 1)]);
163 const bigRes = await post(tokens["alice"]!, good({ image: b64(big) }));
164 expect(bigRes.status).toBe(413);
165 const text = b64(Buffer.from("<script>alert(1)</script>"));
166 expect((await post(tokens["alice"]!, good({ image: text }))).status).toBe(415);
167 // A PNG signature with nothing behind it, and a JPEG cut short.
168 expect(
169 (await post(tokens["alice"]!, good({ image: b64(PNG.subarray(0, 12)) }))).status,
170 ).toBe(415);
171 expect(
172 (await post(tokens["alice"]!, good({ image: b64(JPEG.subarray(0, 5)) }))).status,
173 ).toBe(415);
174 expect((await post(tokens["alice"]!, good({ image: "not base64!!" }))).status).toBe(422);
175 expect((await post(tokens["alice"]!, good({ image: "" }))).status).toBe(422);
176 expect((await post(tokens["alice"]!, good({ width: "tablet" }))).status).toBe(422);
177 expect((await post(tokens["alice"]!, good({ shows: " " }))).status).toBe(422);
178 expect((await post(tokens["alice"]!, good({ shows: "x".repeat(201) }))).status).toBe(422);
179 expect((await post(tokens["alice"]!, null, "{not json")).status).toBe(422);
180 expect(stored()).toEqual([]);
181 });
182
183 test("the type is found from the bytes, never taken from the sender", () => {
184 expect(sniffImage(PNG)).toBe("image/png");
185 expect(sniffImage(JPEG)).toBe("image/jpeg");
186 expect(sniffImage(Buffer.from("GIF89a"))).toBeUndefined();
187 });
188
189 test("a writer attaches a look at each width, and the change's page shows both", async () => {
190 const phone = await post(tokens["alice"]!, good());
191 expect(phone.status).toBe(201);
192 const made = (await phone.json()) as any;
193 expect(made.width).toBe("phone");
194 const desktop = await post(
195 tokens["alice"]!,
196 good({ width: "Desktop", shows: "the board <b>wide</b>", image: b64(JPEG) }),
197 );
198 expect(desktop.status).toBe(201);
199 expect(stored().map((l) => l.kind).sort()).toEqual(["desktop", "phone"]);
200 expect(existsSync(join(dataDir, stored()[0]!.path))).toBe(true);
201
202 const signin = await fetch(`${base}/signin`, {
203 method: "POST",
204 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
205 redirect: "manual",
206 });
207 const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
208 const html = await (
209 await fetch(`${base}/alice/garden/pulls/${pull.number}`, { headers: { cookie } })
210 ).text();
211 expect(html).toContain("Attached looks");
212 expect(html).toContain("look-attached-phone");
213 expect(html).toContain("look-attached-desktop");
214 expect(html).toContain("the empty state on a phone");
215 // The line is escaped.
216 expect(html).not.toContain("<b>wide</b>");
217 expect(html).toContain("&lt;b&gt;wide&lt;/b&gt;");
218
219 // The bytes are served to a writer under the type they were found to be.
220 const img = await fetch(`${base}${made.url}`, { headers: { cookie } });
221 expect(img.status).toBe(200);
222 expect(img.headers.get("content-type")).toBe("image/png");
223 expect(Buffer.from(await img.arrayBuffer()).equals(PNG)).toBe(true);
224 // A stranger is shown neither the card nor the bytes.
225 const stranger = await (
226 await fetch(`${base}/alice/garden/pulls/${pull.number}`)
227 ).text();
228 expect(stranger).not.toContain("Attached looks");
229 expect((await fetch(`${base}${made.url}`)).status).toBe(404);
230 expect(
231 (await fetch(`${base}${made.url}`, { headers: { authorization: `Bearer ${tokens["bob"]}` } })).status,
232 ).toBe(404);
233 });
234
235 test("the list is the writers' and the MCP attaches for a person", async () => {
236 const listed = await fetch(
237 `${base}/api/v1/repos/alice/garden/pulls/${pull.number}/looks`,
238 { headers: { authorization: `Bearer ${tokens["alice"]}` } },
239 );
240 expect(((await listed.json()) as any).looks.length).toBe(2);
241 const hidden = await fetch(
242 `${base}/api/v1/repos/alice/garden/pulls/${pull.number}/looks`,
243 { headers: { authorization: `Bearer ${tokens["bob"]}` } },
244 );
245 expect(((await hidden.json()) as any).looks).toEqual([]);
246
247 const args = {
248 app: "alice/garden",
249 pull: pull.number,
250 ...good({ width: "desktop", shows: "via the MCP" }),
251 };
252 const dry = await mcp(tokens["alice"]!, args);
253 expect(dry.value.dryRun).toBe(true);
254 expect(stored().length).toBe(2);
255 const done = await mcp(tokens["alice"]!, { ...args, dryRun: false });
256 expect(done.value.attached).toBe(true);
257 expect(stored().length).toBe(3);
258 expect((await mcp(tokens["alice"]!, { ...args, image: "AAAA", dryRun: false })).error).toContain(
259 "not a PNG or a JPEG",
260 );
261 });
262 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs