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

mcp.test.ts, migrate.test.ts and studio-door.test.ts each split into test files of one concept #15371

Merged opened this

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

Merged

mason/forge:mason/15351-mcp-test-ts-migrate-test-ts-and-studio-d → main 0 commits fork 1 thread · 1 unresolved

  • Merged. mason/15351-mcp-test-ts-migrate-test-ts-and-studio-d was merged into main as e36d2f0.

Review

Sign in to review this change.
30 files changed +5765 −5056
docs/MCP.md +1 −1
@@ -337,7 +337,7 @@ can call `apps` and is refused `tell`.
337337 `src/http/oauth.ts`, `src/core/oauth.ts`, `src/web/pages/oauth.ts`,
338338 `test/oauth-flow.test.ts`.
339339
340 `src/http/mcp.ts`, `src/http/mcp/tools/`, `src/actions/tell.ts`, `test/mcp.test.ts`.
340 `src/http/mcp.ts`, `src/http/mcp/tools/`, `src/actions/tell.ts`, `test/mcp-forge-*.test.ts`.
341341
342342 ## `plan`
343343
docs/threats/compromised-vendor.md +1 −1
@@ -70,7 +70,7 @@ trusts: a package, a model provider, a hosting provider, an origin it syncs from
7070 whatever `clone_url` its reply names, and that address is vetted and pinned
7171 like a pasted one: a private, loopback, link-local or metadata answer is
7272 refused before git starts (#14756).
73 Enforced by: `test/migrate.test.ts`
73 Enforced by: `test/migrate-network.test.ts`
7474 - Pushes from an origin cannot rewrite what the forge protects.
7575 Enforced by: `test/origins-security-push.test.ts`
7676 - Backups are encrypted before they leave the machine.
scripts/test-times.json −2
@@ -45,7 +45,6 @@
4545 "test/helpers.test.ts": 0.7,
4646 "test/landing.test.ts": 9.4,
4747 "test/ledger.test.ts": 12.8,
48 "test/migrate.test.ts": 5.9,
4948 "test/offline.test.ts": 3.5,
5049 "test/pulls.test.ts": 14.6,
5150 "test/run-secrets.test.ts": 2.8,
@@ -57,7 +56,6 @@
5756 "test/standing.test.ts": 2.8,
5857 "test/steer.test.ts": 16.2,
5958 "test/studio-changes.test.ts": 2.3,
60 "test/studio-door.test.ts": 2.1,
6159 "test/studio-search.test.ts": 2.3,
6260 "test/studio-words.test.ts": 17,
6361 "test/studio.test.ts": 35.3,
test/mcp-forge-admin.test.ts added +311
@@ -0,0 +1,311 @@
1 /**
2 * The forge as an MCP server: one short JSON-RPC call per answer, a token
3 * and never a cookie, `ro` reads and `rw` acts, and every tool is the same
4 * action the pages call — so what a person may not do on a page they may
5 * not do here.
6 *
7 * This file: the admin tools: limits, egress_grants, board_pins, boards, feed_chips, whoami_can,
8 * mint_invite and model_ceiling. Split from mcp.test.ts by tool family, each file on its own forge
9 * from test/support/mcp-forge.ts (#15351).
10 */
11 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
12 import { type App } from "../src/app.ts";
13 import { createAgent } from "../src/actions/crew.ts";
14 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
15 import { type Repo } from "../src/core/repos.ts";
16 import { getAccountCeiling } from "../src/core/account_ceiling.ts";
17 import { createToken } from "../src/core/tokens.ts";
18 import { setMember } from "../src/core/roles.ts";
19 import { createUser, type User } from "../src/core/users.ts";
20 import { limitChanges, limitValue } from "../src/settings/limits.ts";
21 import { showBoard } from "../src/actions/boards.ts";
22 import { panelData } from "../src/boards/panel_data.ts";
23 import { mcpClient, startMcpForge, type McpForge } from "./support/mcp-forge.ts";
24
25 describe("the forge over MCP: admin", () => {
26 let forge: McpForge;
27 let app: App;
28 let base: string;
29 let alice: User;
30 let bob: User;
31 let rw: string;
32 let ro: string;
33 let bobRw: string;
34 let game: Repo;
35 const { tool } = mcpClient(() => forge.base);
36
37 beforeAll(async () => {
38 forge = await startMcpForge();
39 ({ app, base, alice, bob, rw, ro, bobRw, game } = forge);
40 }, 30_000);
41
42 afterAll(() => forge.stop());
43
44 test("limits: admins only, dry by default, an admin-scope token to change", async () => {
45 const key = "front.pinned_max";
46 const admin = createToken(app.db, alice.id, "admin", "admin").token;
47 // A non-admin and an agent (even one marked admin) are told nothing.
48 expect((await tool(bobRw, "limits")).error).toContain("no such tool");
49 const made = await createAgent(app, alice, { username: "limitbot", brief: "x" });
50 if (!made.ok) throw new Error(String(made.error));
51 app.db.query("UPDATE user SET is_admin = 1 WHERE id = ?1").run(made.value.user.id);
52 const botToken = createToken(app.db, made.value.user.id, "bot", "admin").token;
53 expect((await tool(botToken, "limits")).error).toContain("no such tool");
54
55 const before = limitValue(app.db, key);
56 const listed = await tool(ro, "limits");
57 expect(listed.value.limits.map((l: any) => l.key)).toContain(key);
58
59 // The default is a dry run: nothing changes, even with an admin token.
60 const dry = await tool(admin, "limits", { key, value: "13" });
61 expect(dry.value.says).toContain("Would set");
62 expect(limitValue(app.db, key)).toBe(before);
63
64 // Writing needs the admin scope.
65 const refused = await tool(ro, "limits", { key, value: "13", dryRun: false });
66 expect(refused.error).toContain("forbidden");
67 expect(limitValue(app.db, key)).toBe(before);
68
69 const done = await tool(admin, "limits", { key, value: "13", dryRun: false });
70 expect(done.value).toMatchObject({ key, from: before, to: 13 });
71 expect(limitValue(app.db, key)).toBe(13);
72 expect(limitChanges(app.db)[0]).toMatchObject({ key });
73 });
74
75 test("egress_grants: list, grant and revoke for a site admin; a non-admin is refused as the API refuses", async () => {
76 const dest = "100.89.95.68:8101";
77 const committed = await commitToBranch(app, alice, game, {
78 message: "Ask for the arm",
79 files: [{ path: "forge.json", content: JSON.stringify({ app: { run: "bun run src/server.ts" }, egress: [dest] }) }],
80 });
81 if (!committed.ok) throw new Error(JSON.stringify(committed.error));
82 const admin = createToken(app.db, alice.id, "admin", "admin").token;
83 const bobAdmin = createToken(app.db, bob.id, "bobadmin", "admin").token;
84 const repo = "alice/game";
85
86 const listed = await tool(admin, "egress_grants", { repo });
87 expect(listed.value.items).toEqual([
88 { destination: dest, asked: true, granted: false, grantedBy: null, grantedAt: null },
89 ]);
90
91 // Bob is no admin of the repository: told nothing of it.
92 expect((await tool(bobAdmin, "egress_grants", { repo })).error).toContain("not_found");
93 // A token below admin scope may not read or change.
94 expect((await tool(ro, "egress_grants", { repo })).error).toContain("forbidden");
95 expect((await tool(rw, "egress_grants", { repo, op: "grant", destination: dest })).error).toContain("forbidden");
96
97 const granted = await tool(admin, "egress_grants", { repo, op: "grant", destination: dest });
98 expect(granted.value).toMatchObject({ destination: dest, granted: true, grantedBy: "alice" });
99 expect((await tool(admin, "egress_grants", { repo, op: "grant", destination: "10.0.0.1:1" })).error).toContain("not_asked");
100
101 // The same words the API gives a repository admin who is no site admin.
102 const arm = await createRepo(app, bob, { name: "arm", visibility: "public", description: "" });
103 if (!arm.ok) throw new Error(String(arm.error));
104 await commitToBranch(app, bob, arm.value, {
105 message: "Ask for the arm",
106 files: [{ path: "forge.json", content: JSON.stringify({ app: { run: "bun run src/server.ts" }, egress: [dest] }) }],
107 });
108 const refused = await tool(bobAdmin, "egress_grants", { repo: "bob/arm", op: "grant", destination: dest });
109 const api = await fetch(`${base}/api/v1/repos/bob/arm/egress-grants`, {
110 method: "POST",
111 headers: { authorization: `Bearer ${bobAdmin}`, "content-type": "application/json" },
112 body: JSON.stringify({ destination: dest }),
113 });
114 expect(api.status).toBe(403);
115 expect(refused.error).toStartWith(`forbidden: ${((await api.json()) as any).message}`);
116
117 // An agent, even one marked site admin, may not change a grant.
118 const bot = await createAgent(app, alice, { username: "egressbot", brief: "x" });
119 if (!bot.ok) throw new Error(String(bot.error));
120 app.db.query("UPDATE user SET is_admin = 1 WHERE id = ?1").run(bot.value.user.id);
121 const botToken = createToken(app.db, bot.value.user.id, "bot", "admin").token;
122 const botGrant = await tool(botToken, "egress_grants", { repo: "bob/arm", op: "grant", destination: dest });
123 expect(botGrant.error).toContain("forbidden");
124
125 const revoked = await tool(admin, "egress_grants", { repo, op: "revoke", destination: dest });
126 expect(revoked.value).toEqual({ revoked: dest });
127 expect((await tool(admin, "egress_grants", { repo, op: "revoke", destination: dest })).error).toContain("no_such_grant");
128 expect((await tool(admin, "egress_grants", { repo })).value.items[0].granted).toBe(false);
129 });
130
131 test("board_pins: list, pin, move, unpin for an admin person; an agent and a non-admin are refused", async () => {
132 const board = { title: "Pinnable", range: "24h", refresh: "off", panels: [
133 { title: "One", chart: "number", query: { source: "runs", aggregate: "count" }, w: 1, h: 1 },
134 { title: "Two", chart: "number", query: { source: "runs", aggregate: "count" }, w: 1, h: 1 },
135 ] };
136 expect((await tool(rw, "board_write", { slug: "pinnable", board })).value).toMatchObject({ slug: "pinnable" });
137 const titles = async () => (await tool(rw, "board_pins")).value.pins.map((p: any) => p.title);
138 expect(await titles()).toEqual([]);
139 expect((await tool(rw, "board_pins", { op: "pin", slug: "pinnable", title: "One" })).value).toMatchObject({ slug: "pinnable", title: "One" });
140 await tool(rw, "board_pins", { op: "pin", slug: "pinnable", title: "Two" });
141 expect(await titles()).toEqual(["One", "Two"]);
142 await tool(rw, "board_pins", { op: "move", slug: "pinnable", title: "Two", by: -1 });
143 expect(await titles()).toEqual(["Two", "One"]);
144 expect((await tool(rw, "board_pins", { op: "move", slug: "pinnable", title: "Nope", by: 1 })).error).toContain("not_found");
145 expect((await tool(rw, "board_pins", { op: "pin", slug: "pinnable", title: "Nope" })).error).toContain("not_found");
146 await tool(rw, "board_pins", { op: "unpin", slug: "pinnable", title: "One" });
147 expect(await titles()).toEqual(["Two"]);
148 await tool(rw, "board_pins", { op: "unpin", slug: "pinnable", title: "Two" });
149 expect(await titles()).toEqual([]);
150
151 const made = await createAgent(app, alice, { username: "pinbot", brief: "x" });
152 if (!made.ok) throw new Error(String(made.error));
153 app.db.query("UPDATE user SET is_admin = 1 WHERE id = ?1").run(made.value.user.id);
154 const botToken = createToken(app.db, made.value.user.id, "bot", "rw").token;
155 for (const who of [bobRw, botToken]) {
156 expect((await tool(who, "board_pins")).error).toContain("forbidden");
157 expect((await tool(who, "board_pins", { op: "pin", slug: "pinnable", title: "One" })).error).toContain("forbidden");
158 }
159 expect(await titles()).toEqual([]);
160 await tool(rw, "board_delete", { slug: "pinnable" });
161 });
162
163 test("boards: list, read, write and delete for an admin person; an agent and a non-admin are refused", async () => {
164 const board = { title: "Runs", range: "24h", refresh: "off", panels: [{ title: "Failed", chart: "number", query: { source: "runs", aggregate: "count" }, w: 1, h: 1 }] };
165 const made = await createAgent(app, alice, { username: "boardbot", brief: "x" });
166 if (!made.ok) throw new Error(String(made.error));
167 app.db.query("UPDATE user SET is_admin = 1 WHERE id = ?1").run(made.value.user.id);
168 const botToken = createToken(app.db, made.value.user.id, "bot", "rw").token;
169 for (const who of [bobRw, botToken]) {
170 expect((await tool(who, "boards")).error).toContain("forbidden");
171 expect((await tool(who, "board_write", { slug: "runs", board })).error).toContain("forbidden");
172 expect((await tool(who, "board_delete", { slug: "runs" })).error).toContain("forbidden");
173 }
174
175 // A read-only token may not write.
176 expect((await tool(ro, "board_write", { slug: "runs", board })).error).toContain("forbidden");
177 expect((await tool(rw, "boards")).value.boards).toEqual([]);
178
179 const wrote = await tool(rw, "board_write", { slug: "runs", board });
180 expect(wrote.value).toMatchObject({ slug: "runs", title: "Runs" });
181 expect((await tool(rw, "boards")).value.boards.map((b: any) => b.slug)).toEqual(["runs"]);
182 expect((await tool(ro, "boards", { slug: "runs" })).value.panels[0].title).toBe("Failed");
183 expect((await tool(rw, "boards", { slug: "nope" })).error).toContain("not_found");
184
185 // A panel that cannot run, or a board that does not validate, is refused.
186 const broken = { ...board, panels: [{ ...board.panels[0], query: { source: "nothing" } }] };
187 expect((await tool(rw, "board_write", { slug: "broken", board: broken })).error).toContain("refused");
188 expect((await tool(rw, "board_write", { slug: "Bad Slug", board })).error).toContain("invalid");
189
190 expect((await tool(ro, "board_delete", { slug: "runs" })).error).toContain("forbidden");
191 expect((await tool(rw, "board_delete", { slug: "runs" })).value).toEqual({ deleted: "runs" });
192 expect((await tool(rw, "boards")).value.boards).toEqual([]);
193 expect((await tool(rw, "board_delete", { slug: "runs" })).error).toContain("not_found");
194 });
195
196 test("boards with a panel: its data through panelData, the window judged; an agent and a non-admin are refused", async () => {
197 const query = { source: "runs", aggregate: "count", groupBy: { bucket: "hour" } };
198 const board = { title: "Hourly", range: "7d", refresh: "off", panels: [{ title: "Runs", chart: "line", query, w: 1, h: 1 }] };
199 expect((await tool(rw, "board_write", { slug: "hourly", board })).value).toMatchObject({ slug: "hourly" });
200 const from = "2026-01-01T00:00:00.000Z";
201 const to = "2027-01-01T00:00:00.000Z";
202 const got = (await tool(ro, "boards", { slug: "hourly", panel: 0, from, to, step: "1d" })).value;
203 const shown = await showBoard(app, alice, "hourly");
204 if (!shown.ok) throw new Error("no board");
205 const direct = panelData(app.db, shown.value, shown.value.panels[0]!, { from, to, step: 86_400 });
206 if (!direct.ok) throw new Error(direct.error);
207 expect(got).toEqual({ board: "hourly", panel: 0, title: "Runs", chart: "line", from, to, step: 86_400, rows: direct.rows });
208 expect((await tool(rw, "boards", { slug: "hourly", panel: 0, step: 300 })).value.step).toBe(300);
209 expect((await tool(rw, "boards", { slug: "hourly", panel: 0 })).value.step).toBe(3600);
210 expect((await tool(rw, "boards", { slug: "hourly", panel: 0, step: "5x" })).error).toContain("invalid_window");
211 expect((await tool(rw, "boards", { slug: "hourly", panel: 0, from: "soon" })).error).toContain("invalid_window");
212 expect((await tool(rw, "boards", { slug: "hourly", panel: 1 })).error).toContain("not_found");
213 expect((await tool(rw, "boards", { slug: "nope", panel: 0 })).error).toContain("not_found");
214 const made = await createAgent(app, alice, { username: "databot", brief: "x" });
215 if (!made.ok) throw new Error(String(made.error));
216 app.db.query("UPDATE user SET is_admin = 1 WHERE id = ?1").run(made.value.user.id);
217 const botToken = createToken(app.db, made.value.user.id, "bot", "rw").token;
218 for (const who of [bobRw, botToken]) {
219 expect((await tool(who, "boards", { slug: "hourly", panel: 0 })).error).toContain("forbidden");
220 }
221 await tool(rw, "board_delete", { slug: "hourly" });
222 });
223
224 test("feed_chips reads and switches the chips the feed answers through", async () => {
225 app.bus.append({ kind: "app.serving", repoId: game.id, actorId: alice.id, payload: {} });
226 const kinds = async () => {
227 const r = await tool(rw, "feed", { limit: 50 });
228 return (r.value.items as { kind: string }[]).map((i) => i.kind);
229 };
230 const api = async () => {
231 const res = await fetch(`${base}/api/v1/feed?limit=50`, { headers: { authorization: `Bearer ${rw}` } });
232 return ((await res.json()) as { items: { kind: string }[] }).items.map((i) => i.kind);
233 };
234 expect(await kinds()).toContain("release");
235 expect((await tool(rw, "feed_chips")).value).toEqual({ kinds: [], people: [] });
236
237 const set = await tool(rw, "feed_chips", { kind: "kind", value: "releases", hidden: true });
238 expect(set.value).toEqual({ kinds: ["releases"], people: [] });
239 expect(await kinds()).not.toContain("release");
240 expect(await api()).not.toContain("release");
241 // A read-only token may read the chips, not switch them.
242 expect((await tool(ro, "feed_chips")).value).toEqual({ kinds: ["releases"], people: [] });
243 expect((await tool(ro, "feed_chips", { kind: "kind", value: "releases", hidden: false })).error).toContain("forbidden");
244 expect((await tool(rw, "feed_chips")).value.kinds).toEqual(["releases"]);
245
246 expect((await tool(rw, "feed_chips", { kind: "kind", value: "nope", hidden: true })).error).toBeDefined();
247 expect((await tool(rw, "feed_chips", { kind: "person", value: "nobody", hidden: true })).error).toBeDefined();
248 expect((await tool(rw, "feed_chips", { kind: "kind", value: "crew" })).error).toBeDefined();
249 const person = await tool(rw, "feed_chips", { kind: "person", value: "bob", hidden: true });
250 expect(person.value).toEqual({ kinds: ["releases"], people: ["bob"] });
251 await tool(rw, "feed_chips", { kind: "person", value: "bob", hidden: false });
252 const back = await tool(rw, "feed_chips", { kind: "kind", value: "releases", hidden: false });
253 expect(back.value).toEqual({ kinds: [], people: [] });
254 expect(await kinds()).toContain("release");
255 });
256
257 test("whoami_can: the caller's role and its row, for a guest, a member and an admin", async () => {
258 setMember(app.db, bob.id, false, alice.id, new Date());
259 const guest = (await tool(bobRw, "whoami_can")).value;
260 expect(guest.role).toBe("guest");
261 expect(guest.can).toEqual({ read: true, comment: true, contribute: true, make_it_yours: false, run_crew: false, administer: false });
262 setMember(app.db, bob.id, true, alice.id, new Date());
263 const member = (await tool(bobRw, "whoami_can")).value;
264 expect(member.role).toBe("member");
265 expect(member.can).toEqual({ read: true, comment: true, contribute: true, make_it_yours: true, run_crew: true, administer: false });
266 const admin = (await tool(ro, "whoami_can")).value;
267 expect(admin.role).toBe("admin");
268 expect(admin.can.administer).toBe(true);
269 });
270
271 test("mint_invite: an admin person with an admin token gets a link; anyone else is refused", async () => {
272 const admin = createToken(app.db, alice.id, "admin", "admin").token;
273 expect((await tool(bobRw, "mint_invite")).error).toContain("forbidden");
274 expect((await tool(rw, "mint_invite")).error).toContain("admin token");
275 expect((await tool(admin, "mint_invite", { days: 0 })).error).toContain("invalid");
276 const made = (await tool(admin, "mint_invite", { days: 3 })).value;
277 expect(made.link).toMatch(/\/signup\?invite=[\w-]+$/);
278 const token = made.link.split("invite=")[1];
279 expect(made.token).toBeUndefined();
280 expect(token.length).toBeGreaterThan(20);
281 const listed = await fetch(`${base}/api/v1/admin/invites`, { headers: { authorization: `Bearer ${admin}` } });
282 expect(JSON.stringify(await listed.json())).toContain(made.id);
283 });
284
285 test("model_ceiling: dry by default, an admin person with an admin token sets and clears it", async () => {
286 const admin = createToken(app.db, alice.id, "admin", "admin").token;
287 const readOnly = createToken(app.db, alice.id, "ro", "ro").token;
288 const target = (await createUser(app.db, { origin: "seed", trusted: true, username: "ceilee", email: "[email protected]", password: "a-good-passphrase" }));
289 if (!target.ok) throw new Error(target.error);
290 const id = target.value.id;
291 const args = { username: "ceilee", dailyUsd: 12, perRunUsd: 3 };
292 // A non-admin is refused.
293 expect((await tool(bobRw, "model_ceiling", { ...args, dryRun: false })).error).toContain("forbidden");
294 // A dry run changes nothing.
295 expect((await tool(admin, "model_ceiling", args)).value.says).toContain("nothing changed");
296 expect(getAccountCeiling(app.db, id)).toBeUndefined();
297 // A read-only token is refused.
298 expect((await tool(readOnly, "model_ceiling", { ...args, dryRun: false })).error).toContain("forbidden");
299 expect(getAccountCeiling(app.db, id)).toBeUndefined();
300 // Bad amounts are invalid; half a clear too.
301 for (const bad of [{ dailyUsd: 0 }, { dailyUsd: 1e9 }, { perRunUsd: null }])
302 expect((await tool(admin, "model_ceiling", { ...args, ...bad, dryRun: false })).error).toContain("invalid");
303 expect(getAccountCeiling(app.db, id)).toBeUndefined();
304 expect((await tool(admin, "model_ceiling", { ...args, dryRun: false })).value).toEqual({ username: "ceilee", dailyUsd: 12, perRunUsd: 3 });
305 expect(getAccountCeiling(app.db, id)).toEqual({ dailyUsd: 12, perRunUsd: 3 });
306 // Both null takes them back.
307 const cleared = await tool(admin, "model_ceiling", { username: "ceilee", dailyUsd: null, perRunUsd: null, dryRun: false });
308 expect(cleared.value).toEqual({ username: "ceilee", dailyUsd: null, perRunUsd: null });
309 expect(getAccountCeiling(app.db, id)).toBeUndefined();
310 });
311 });
test/mcp-forge-cards.test.ts added +324
@@ -0,0 +1,324 @@
1 /**
2 * The forge as an MCP server: one short JSON-RPC call per answer, a token
3 * and never a cookie, `ro` reads and `rw` acts, and every tool is the same
4 * action the pages call — so what a person may not do on a page they may
5 * not do here.
6 *
7 * This file: the ui:// cards each tool's answer carries. Split from mcp.test.ts by tool family,
8 * each file on its own forge from test/support/mcp-forge.ts (#15351).
9 */
10 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
11 import { type App } from "../src/app.ts";
12 import { openIssue } from "../src/actions/issues.ts";
13 import { openPull } from "../src/actions/pulls.ts";
14 import { commitToBranch } from "../src/actions/repos.ts";
15 import { type Repo } from "../src/core/repos.ts";
16 import { type User } from "../src/core/users.ts";
17 import { mcpClient, startMcpForge, type McpForge } from "./support/mcp-forge.ts";
18
19 describe("the forge over MCP: cards", () => {
20 let forge: McpForge;
21 let app: App;
22 let base: string;
23 let alice: User;
24 let rw: string;
25 let game: Repo;
26 const { call, listCall } = mcpClient(() => forge.base);
27
28 beforeAll(async () => {
29 forge = await startMcpForge();
30 ({ app, base, alice, rw, game } = forge);
31 }, 30_000);
32
33 afterAll(() => forge.stop());
34
35 test("ui:// card resources are listed, read, and tied to their tools", async () => {
36 const list = await call(rw, "resources/list");
37 const uris = list.body.result.resources.map((r: any) => r.uri).sort();
38 expect(uris).toEqual([
39 "ui://forge/app",
40 "ui://forge/asked",
41 "ui://forge/asks",
42 "ui://forge/board",
43 "ui://forge/capacity",
44 "ui://forge/crew",
45 "ui://forge/drill",
46 "ui://forge/explore",

Indentation is off on this entry (carried over from the original); align it with its neighbours.

47 "ui://forge/feed",
48 "ui://forge/flow",
49 "ui://forge/forge",
50 "ui://forge/forges",
51 "ui://forge/forks",
52 "ui://forge/health",
53 "ui://forge/held",
54 "ui://forge/issue",
55 "ui://forge/issues",
56 "ui://forge/map",
57 "ui://forge/milestones",
58 "ui://forge/pull",
59 "ui://forge/pulls",
60 "ui://forge/release",
61 "ui://forge/releases",
62 "ui://forge/reports",
63 "ui://forge/run",
64 "ui://forge/runs",
65 "ui://forge/scorecard",
66 "ui://forge/search",
67 "ui://forge/usage",
68 "ui://forge/wave",
69 ]);
70 const read = await call(rw, "resources/read", { uri: "ui://forge/app" });
71 const c = read.body.result.contents[0];
72 expect(c.mimeType).toBe("text/html;profile=mcp-app");
73 expect(c.text).toContain("ui/notifications/tool-result");
74 expect(c.text).not.toContain("innerHTML");
75 const nope = await call(rw, "resources/read", { uri: "ui://forge/nope" });
76 expect(nope.body.error.code).toBe(-32002);
77 const tools = (await listCall(rw)).body.result.tools;
78 const meta = (n: string) => tools.find((t: any) => t.name === n)._meta?.ui?.resourceUri;
79 expect(meta("apps")).toBe("ui://forge/app");
80 expect(meta("new_app")).toBe("ui://forge/app");
81 expect(meta("now")).toBe("ui://forge/crew");
82 expect(meta("asks")).toBe("ui://forge/asks");
83 expect(meta("milestones")).toBe("ui://forge/milestones");
84 expect(meta("asks_act")).toBe("ui://forge/asks");
85 expect(meta("map")).toBe("ui://forge/map");
86 expect(meta("boards")).toBe("ui://forge/board");
87 expect(meta("feed")).toBe("ui://forge/feed");
88 expect(meta("issue")).toBe("ui://forge/issue");
89 expect(meta("explore")).toBe("ui://forge/explore");
90 expect(meta("pull")).toBe("ui://forge/pull");
91 expect(meta("pulls")).toBe("ui://forge/pulls");
92 expect(meta("runs")).toBe("ui://forge/runs");
93 expect(meta("asked")).toBe("ui://forge/asked");
94 expect(meta("flow")).toBe("ui://forge/flow");
95 expect(meta("scorecard")).toBe("ui://forge/scorecard");
96 });
97
98 test("tools/call pull carries the card beside an unchanged text answer", async () => {
99 const branched = await commitToBranch(app, alice, game, {
100 branch: "card-wire",
101 message: "a change",
102 files: [{ path: "card.txt", content: "c\n" }],
103 });
104 if (!branched.ok) throw new Error(JSON.stringify(branched.error));
105 const opened = await openPull(app, alice, game, {
106 title: "Card wire",
107 baseBranch: "main",
108 headBranch: "card-wire",
109 });
110 if (!opened.ok) throw new Error(String(opened.error));
111 const n = opened.value.number;
112 const { body } = await call(rw, "tools/call", { name: "pull", arguments: { repo: "alice/game", number: n } });
113 const card = body.result.structuredContent.card;
114 expect(card.kind).toBe("pull");
115 expect(card.title).toBe(`#${n} Card wire`);
116 const branches = card.rows.find((r: any) => r.label === "Branches");
117 expect(branches.value).toBe("card-wire → main");
118 expect(branches.link).toBe(`${base}/alice/game/pulls/${n}`);
119 // No environment for this pull in the test runtime, so no preview to link.
120 expect(card.rows.some((r: any) => r.label === "Preview")).toBe(false);
121 const text = JSON.parse(body.result.content[0].text);
122 expect(text.title).toBe("Card wire");
123 expect(text.next).toEqual({ who: "reviewer", why: "no review yet" });
124 expect("card" in text).toBe(false);
125 });
126
127 test("the pull card shows title, state, check, branches and the preview; a merged pull has no check or preview", async () => {
128 const { cardFor } = await import("../src/web/studio/cards.ts");
129 const origin = "https://forge.test";
130 const open = cardFor(
131 "pull",
132 {
133 number: 7,
134 title: "<b>Add</b> a thing",
135 state: "open",
136 base: "main",
137 head: "scout/7",
138 check: { state: "ok" },
139 mergeable: false,
140 conflicts: ["a.ts"],
141 },
142 origin,
143 { repo: "alice/game", preview: "https://p.example/" },
144 )!;
145 expect(open.kind).toBe("pull");
146 expect(open.title).toBe("#7 <b>Add</b> a thing");
147 expect(open.status).toBe("open · check green · conflicts");
148 expect(open.rows.find((r) => r.label === "Branches")).toMatchObject({
149 value: "scout/7 → main",
150 link: "https://forge.test/alice/game/pulls/7",
151 });
152 expect(open.rows.find((r) => r.label === "Preview")?.link).toBe("https://p.example/");
153 const merged = cardFor(
154 "pull",
155 { number: 8, title: "Done", state: "merged", base: "main", head: "x", check: { state: "ok" } },
156 origin,
157 { repo: "alice/game" },
158 )!;
159 expect(merged.status).toBe("merged");
160 expect(merged.rows.some((r) => r.label === "Preview")).toBe(false);
161 const hostile = cardFor("pull", { number: 1, state: "open", check: { state: "running" } }, origin, {
162 repo: "a/b",
163 preview: "javascript:alert(1)",
164 })!;
165 expect(hostile.status).toBe("open · check running");
166 expect(hostile.rows.some((r) => r.label === "Preview")).toBe(false);
167 });
168
169 test("the issue card carries state, assignee, labels and what it waits for, with absolute links and no comments", async () => {
170 const { cardFor } = await import("../src/web/studio/cards.ts");
171 const answer = {
172 number: 7,
173 title: "<b>Fix</b>",
174 state: "open",
175 closeReason: null,
176 body: "secret body",
177 assignee: "scout",
178 labels: ["bug"],
179 untrusted: true,
180 comments: [{ author: "x", body: "COMMENTTEXT" }],
181 blockedBy: [{ number: 3, title: "T3", state: "open" }],
182 blocks: [],
183 };
184 const card = cardFor("issue", answer, "https://forge.test", { repo: "alice/game" })!;
185 expect(card.kind).toBe("issue");
186 expect(card.status).toBe("open");
187 expect(card.title).toBe("#7 <b>Fix</b>");
188 expect(card.rows[0]).toEqual({ label: "On the forge", value: "alice/game #7", link: "https://forge.test/alice/game/issues/7" });
189 expect(card.rows.find((r) => r.label === "Assignee")!.value).toBe("scout");
190 expect(card.rows.find((r) => r.label === "Labels")!.value).toBe("bug");
191 expect(card.rows.find((r) => r.label === "Waits for")!.link).toBe("https://forge.test/alice/game/issues/3");
192 expect(card.rows.some((r) => r.label === "Author" && r.value.startsWith("untrusted"))).toBe(true);
193 expect(JSON.stringify(card)).not.toContain("COMMENTTEXT");
194 expect(JSON.stringify(card)).not.toContain("secret body");
195 expect(cardFor("issue", answer, "https://forge.test")!.rows[0]!.link).toBeUndefined();
196 // A number that names a pull is not an issue: no card.
197 expect(cardFor("issue", { kind: "pull", tool: "pull" }, "https://forge.test", { repo: "alice/game" })).toBeUndefined();
198 expect(cardFor("issue", {}, "https://forge.test", { repo: "alice/game" })).toBeUndefined();
199 });
200
201 test("the asks card links each ask to its pull or issue, and to nothing unsafe", async () => {
202 const { cardFor } = await import("../src/web/studio/cards.ts");
203 const words = { decision: "Ship it?", options: ["ship", "close"] };
204 const rows = [
205 { line: "a", repo: "alice/game", number: 3, numberOf: "pull", words },
206 { line: "b", repo: "alice/game", number: 4, numberOf: "issue", words },
207 { line: "c", repo: "alice/game", words },
208 { line: "d", repo: "alice", number: 5, numberOf: "pull", words },
209 { line: "e", repo: "alice/game", number: 0, numberOf: "pull", words },
210 ];
211 const card = cardFor("asks", { rows }, "https://forge.test")!;
212 expect(card.rows.map((r) => r.link)).toEqual([
213 "https://forge.test/alice/game/pulls/3",
214 "https://forge.test/alice/game/issues/4",
215 undefined,
216 undefined,
217 undefined,
218 ]);
219 expect(cardFor("asks", { rows }, "javascript:x")!.rows.every((r) => r.link === undefined)).toBe(true);
220 });
221
222 test("the real asks result carries a link on a pull row and an issue row", async () => {
223 await commitToBranch(app, alice, game, { branch: "ask-links", message: "x", files: [{ path: "ask.txt", content: "a\n" }] });
224 const pull = await openPull(app, alice, game, { title: "Ask link pull", baseBranch: "main", headBranch: "ask-links" });
225 const issue = await openIssue(app, alice, game, { title: "Ask link issue", body: "" });
226 if (!pull.ok || !issue.ok) throw new Error("seed");
227 const { setAssignee } = await import("../src/core/issues.ts");
228 setAssignee(app.db, pull.value.id, alice.id);
229 setAssignee(app.db, issue.value.id, alice.id);
230 const { body } = await call(rw, "tools/call", { name: "asks", arguments: {} });
231 const rows: any[] = body.result.structuredContent.card.rows;
232 const linkOf = (label: string) => rows.find((r) => r.label.includes(label))?.link;
233 expect(linkOf("Ask link pull")).toMatch(new RegExp(`^https?://[^/]+/alice/game/pulls/${pull.value.number}$`));
234 expect(linkOf("Ask link issue")).toMatch(new RegExp(`^https?://[^/]+/alice/game/issues/${issue.value.number}$`));
235 const { askLinesFor } = await import("../src/web/studio/asks.ts");
236 const { cardFor } = await import("../src/web/studio/cards.ts");
237 const lines = askLinesFor(app.db, alice);
238 expect(lines.find((l) => l.id === `assigned:${pull.value.id}`)?.numberOf).toBe("pull");
239 expect(lines.find((l) => l.id === `assigned:${issue.value.id}`)?.numberOf).toBe("issue");
240 expect(cardFor("asks", { rows: lines }, "javascript:x")!.rows.every((r) => r.link === undefined)).toBe(true);
241 });
242
243 test("the feed card draws one linked row per item, twenty at most, escaped as text", async () => {
244 const { cardFor } = await import("../src/web/studio/cards.ts");
245 const items = Array.from({ length: 25 }, (_, n) => ({
246 actor: "scout",
247 what: n === 0 ? "<b>shipped</b>" : `did ${n}`,
248 app: "alice/game",
249 at: new Date().toISOString(),
250 link: `/alice/game/pulls/${n + 1}`,
251 }));
252 const card = cardFor("feed", { items }, "https://forge.test")!;
253 expect(card.kind).toBe("feed");
254 expect(card.title).toBe("Feed");
255 expect(card.status).toBe("Latest");
256 expect(card.rows).toHaveLength(20);
257 expect(card.rows[0]).toEqual({
258 label: "scout: <b>shipped</b>",
259 value: "alice/game · just now",
260 link: "https://forge.test/alice/game/pulls/1",
261 });
262 expect(cardFor("feed", { items, new: 3 })!.status).toBe("3 new since you last looked");
263 expect(cardFor("feed", { items: [{ what: "x", link: "//evil.test/" }] }, "https://forge.test")!.rows[0]!.link).toBeUndefined();
264 const { body } = await call(rw, "tools/call", { name: "feed", arguments: {} });
265 expect(body.result.structuredContent.card.kind).toBe("feed");
266 });
267
268 test("runs answers with the run card, newest first, twelve rows at most", async () => {
269 const { cardFor } = await import("../src/web/studio/cards.ts");
270 const runs = Array.from({ length: 15 }, (_, i) => ({
271 id: `r${i}`, kind: "agent", state: "done", number: i === 0 ? null : i, startedAt: 1, endedAt: 2,
272 }));
273 const id = "01m23vygyffx5hg2f5vm8r74sr";
274 runs[1]!.id = id;
275 const card = cardFor("runs", { runs }, "https://f.example", { repo: "alice/game" })!;
276 expect(card.kind).toBe("runs");
277 expect(card.title).toBe("Runs");
278 expect(card.rows[1]!.link).toBe(`https://f.example/alice/game/runs/${id}`);
279 expect(card.rows[0]!.link).toBeUndefined();
280 const nolink = cardFor("runs", { runs }, "https://f.example", { repo: "alice" })!;
281 expect(nolink.rows[1]!.link).toBeUndefined();
282 const { body } = await call(rw, "tools/call", { name: "runs", arguments: { repo: "alice/game" } });
283 expect(body.result.structuredContent.card.kind).toBe("runs");
284 const tools = (await listCall(rw)).body.result.tools;
285 expect(tools.find((t: any) => t.name === "runs")._meta?.ui?.resourceUri).toBe("ui://forge/runs");
286 });
287
288 test("a tool result carries the card it renders", async () => {
289 const { body } = await call(rw, "tools/call", { name: "apps", arguments: {} });
290 const card = body.result.structuredContent.card;
291 expect(card.kind).toBe("app");
292 expect(card.rows.some((r: any) => r.label === "alice/game")).toBe(true);
293 const asks = await call(rw, "tools/call", { name: "asks", arguments: {} });
294 expect(asks.body.result.structuredContent.card.kind).toBe("asks");
295 });
296
297 test("ship and close card actions never apply at once and always meet the target tool's required fields", async () => {
298 const { cardFor } = await import("../src/web/studio/cards.ts");
299 const tools = (await listCall(rw)).body.result.tools;
300 const cards = [
301 cardFor("apps", [{ app: "alice/game", live: "up" }]),
302 cardFor("now", [{ who: "scout", app: "alice/game", run: "r1", on: "#1", state: "going" }]),
303 cardFor("asks", {
304 rows: [
305 { line: "a", kind: "look", items: ["x:1"], repo: "alice/game", number: 3, words: {} },
306 { line: "b", kind: "review", items: ["x:2"], words: {} },
307 ],
308 }),
309 ];
310 let actions = 0;
311 for (const card of cards)
312 for (const a of [...card!.actions, ...card!.rows.flatMap((r) => r.actions ?? [])]) {
313 actions++;
314 expect(a.args["dryRun"]).not.toBe(false);
315 const t = tools.find((x: any) => x.name === a.tool);
316 // A words action gets `text` from the shell's field when pressed.
317 for (const f of (t.inputSchema.required ?? []).filter((f: string) => !(a.words && f === "text"))) {
318 expect(a.args[f]).toBeDefined();
319 expect(a.args[f]).not.toBe("");
320 }
321 }
322 expect(actions).toBeGreaterThan(2);
323 });
324 });
test/mcp-forge-new-app.test.ts added +134
@@ -0,0 +1,134 @@
1 /**
2 * The forge as an MCP server: one short JSON-RPC call per answer, a token
3 * and never a cookie, `ro` reads and `rw` acts, and every tool is the same
4 * action the pages call — so what a person may not do on a page they may
5 * not do here.
6 *
7 * This file: new_app: an app from a sentence. Split from mcp.test.ts by tool family, each file on
8 * its own forge from test/support/mcp-forge.ts (#15351).
9 */
10 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
11 import { chmodSync, writeFileSync } from "node:fs";
12 import { mkdtemp, rm } from "node:fs/promises";
13 import { tmpdir } from "node:os";
14 import { join } from "node:path";
15 import { type App } from "../src/app.ts";
16 import { createAgent } from "../src/actions/crew.ts";
17 import { listIssues } from "../src/core/issues.ts";
18 import { getRepo } from "../src/core/repos.ts";
19 import { type User } from "../src/core/users.ts";
20 import { mcpClient, startMcpForge, type McpForge } from "./support/mcp-forge.ts";
21
22 describe("the forge over MCP: new-app", () => {
23 let forge: McpForge;
24 let app: App;
25 let alice: User;
26 let rw: string;
27 let ro: string;
28 const { call, tool } = mcpClient(() => forge.base);
29
30 beforeAll(async () => {
31 forge = await startMcpForge();
32 ({ app, alice, rw, ro } = forge);
33 }, 30_000);
34
35 afterAll(() => forge.stop());
36
37 test("new_app makes an app from a sentence and apps reads it back", async () => {
38 const bot = await createAgent(app, alice, { username: "newappbot", brief: "builds" });
39 if (!bot.ok) throw new Error(String(bot.error));
40 const made = (await tool(rw, "new_app", {
41 name: "sentence",
42 description: "a page that says hello",
43 agent: "newappbot",
44 })) as any;
45 expect(made.value.repo).toBe("alice/sentence");
46 expect(made.value.issue).toBe(1);
47 expect(made.value.agent).toBe("newappbot");
48 expect(["queued", "running", "none"]).toContain(made.value.run);
49 const cardRes = await call(rw, "tools/call", { name: "new_app", arguments: { name: "carded", description: "<b>hi</b>", agent: "newappbot" } });
50 const card = cardRes.body.result.structuredContent.card;
51 expect(card.kind).toBe("app");
52 expect(card.title).toBe("New app");
53 const byLabel = (l: string) => card.rows.find((r: any) => r.label === l)?.value;
54 expect(byLabel("App")).toBe("alice/carded");
55 expect(byLabel("First issue")).toBe("#1");
56 expect(byLabel("Agent")).toBe("newappbot");
57 expect(byLabel("First run")).toBeDefined();
58 const seen = (await tool(rw, "apps")) as any;
59 const row = seen.value.find((r: any) => r.app === "alice/sentence");
60 expect(row).toBeDefined();
61 expect(row.url).toBe(made.value.url);
62 // The API's refusals, in its words.
63 expect((await tool(rw, "new_app", { name: "sentence" })).error).toContain("name_taken");
64 expect((await tool(rw, "new_app", { name: "other", agent: "nobody-here" })).error).toContain("no_such_agent");
65 // Without the rw scope nothing is made.
66 const denied = await tool(ro, "new_app", { name: "readonly" });
67 expect(denied.error).toContain("forbidden");
68 expect((await tool(rw, "apps") as any).value.some((r: any) => r.app === "alice/readonly")).toBe(false);
69 }, 30_000);
70
71 test("new_app names an app from a sentence alone, and -2 when taken", async () => {
72 const one = (await tool(rw, "new_app", { sentence: "a garden planner for my allotment" })) as any;
73 expect(one.value.repo).toMatch(/^alice\/[a-z0-9-]+$/);
74 expect(one.value.issue).toBe(1);
75 const two = (await tool(rw, "new_app", { sentence: "a garden planner for my allotment" })) as any;
76 expect(two.value.repo).toBe(`${one.value.repo}-2`);
77 const named = (await tool(rw, "new_app", { name: "keepname", sentence: "a garden planner" })) as any;
78 expect(named.value.repo).toBe("alice/keepname");
79 expect(named.value.issue).toBe(1);
80 // The derived path forwards visibility and agent, and `description` is the first issue over
81 // `sentence`.
82 const bot = await createAgent(app, alice, { username: "sentbot", brief: "builds" });
83 if (!bot.ok) throw new Error(String(bot.error));
84 const fwd = (await tool(rw, "new_app", {
85 sentence: "a recipe box for the family",
86 description: "Start with a list of recipes.",
87 visibility: "private",
88 agent: "sentbot",
89 })) as any;
90 expect(fwd.value.agent).toBe("sentbot");
91 const [slug] = fwd.value.repo.split("/").slice(1);
92 const made = getRepo(app.db, "alice", slug)!;
93 expect(made.visibility).toBe("private");
94 expect(listIssues(app.db, made.id, { state: "open" })[0]!.body).toContain("Start with a list of recipes.");
95 // A refusal maps as on the named path.
96 expect((await tool(rw, "new_app", { sentence: "a tide table", agent: "nobody-here" })).error).toContain("no_such_agent");
97 expect((await tool(rw, "new_app", { sentence: "!!!" })).error).toContain("no_name");
98 expect((await tool(rw, "new_app", {})).error).toContain("no_name");
99 }, 30_000);
100
101 test("new_app with pick lets the planner name the agent", async () => {
102 const picked = await createAgent(app, alice, { username: "pickbot", brief: "builds" });
103 if (!picked.ok) throw new Error(String(picked.error));
104 const dir = await mkdtemp(join(tmpdir(), "forge-mcp-pick-"));
105 const fake = join(dir, "fake-claude");
106 writeFileSync(
107 fake,
108 `#!/bin/sh
109 if [ "$1" = "--version" ]; then echo "2.1.0 (fake)"; exit 0; fi
110 printf '%s\\n' '{"is_error":false,"result":"{\\"summary\\":\\"Build it\\",\\"checklist\\":[\\"One\\"],\\"agent\\":\\"pickbot\\",\\"confidence\\":0.8}"}'
111 `,
112 );
113 chmodSync(fake, 0o755);
114 const real = process.env["FORGE_CLAUDE"];
115 process.env["FORGE_CLAUDE"] = fake;
116 try {
117 const made = (await tool(rw, "new_app", {
118 name: "picked",
119 description: "a page that says hello",
120 pick: true,
121 })) as any;
122 expect(made.error).toBeUndefined();
123 expect(made.value.agent).toBe("pickbot");
124 expect(typeof made.value.issue).toBe("number");
125 const row = ((await tool(rw, "apps")) as any).value.find((r: any) => r.app === "alice/picked");
126 expect(row.url).toBe(made.value.url);
127 if (row.url !== null) expect(typeof made.value.url).toBe("string");
128 } finally {
129 if (real === undefined) delete process.env["FORGE_CLAUDE"];
130 else process.env["FORGE_CLAUDE"] = real;
131 await rm(dir, { recursive: true, force: true });
132 }
133 }, 30_000);
134 });
test/mcp-forge-openapi.test.ts added +52
@@ -0,0 +1,52 @@
1 /**
2 * The forge as an MCP server: one short JSON-RPC call per answer, a token
3 * and never a cookie, `ro` reads and `rw` acts, and every tool is the same
4 * action the pages call — so what a person may not do on a page they may
5 * not do here.
6 *
7 * This file: the public API's OpenAPI document, beside the MCP server. Split from mcp.test.ts by
8 * tool family, each file on its own forge from test/support/mcp-forge.ts (#15351).
9 */
10 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
11 import { type App } from "../src/app.ts";
12 import { adminOpenapi } from "./helpers/openapi-doc.ts";
13 import { startMcpForge, type McpForge } from "./support/mcp-forge.ts";
14
15 describe("the forge over MCP: openapi", () => {
16 let forge: McpForge;
17 let app: App;
18 let base: string;
19
20 beforeAll(async () => {
21 forge = await startMcpForge();
22 ({ app, base } = forge);
23 }, 30_000);
24
25 afterAll(() => forge.stop());
26
27 test("GET /contract/openapi.json describes the public API", async () => {
28 const res = await adminOpenapi(app, base, "/contract/openapi.json");
29 expect(res.status).toBe(200);
30 const doc = (await res.json()) as any;
31 expect(doc.openapi).toBe("3.1.0");
32 expect(doc.paths["/mcp"].post).toBeDefined();
33 });
34
35 test("GET /contract/openapi.json serves the triage routes", async () => {
36 const doc = (await (await adminOpenapi(app, base, "/contract/openapi.json")).json()) as any;
37 const R = "/api/v1/repos/{owner}/{name}";
38 expect(doc.paths[`${R}/issues/{number}/teams`].get).toBeDefined();
39 expect(doc.paths[`${R}/issues/{number}/teams`].put).toBeDefined();
40 expect(doc.paths[`${R}/issues/{number}/labels`].put).toBeDefined();
41 expect(doc.paths[`${R}/pulls/{number}/labels`].put).toBeDefined();
42 expect(doc.paths[`${R}/issues/{number}/private`].post.responses["201"]).toBeDefined();
43 });
44
45 test("GET /api/v1/openapi.json answers the document itself", async () => {
46 const res = await fetch(`${base}/api/v1/openapi.json`, { redirect: "manual" });
47 expect(res.status).toBe(200);
48 expect(res.headers.get("location")).toBeNull();
49 expect(res.headers.get("cache-control")).toContain("public");
50 expect(res.headers.get("etag")).toBeTruthy();
51 });
52 });
test/mcp-forge-plan.test.ts added +163
@@ -0,0 +1,163 @@
1 /**
2 * The forge as an MCP server: one short JSON-RPC call per answer, a token
3 * and never a cookie, `ro` reads and `rw` acts, and every tool is the same
4 * action the pages call — so what a person may not do on a page they may
5 * not do here.
6 *
7 * This file: the plan's tools: map, wait_for and plan. Split from mcp.test.ts by tool family, each
8 * file on its own forge from test/support/mcp-forge.ts (#15351).
9 */
10 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
11 import { type App } from "../src/app.ts";
12 import { getRepoById, updateRepoSettings, type Repo } from "../src/core/repos.ts";
13 import { mcpClient, startMcpForge, type McpForge } from "./support/mcp-forge.ts";
14
15 describe("the forge over MCP: plan", () => {
16 let forge: McpForge;
17 let app: App;
18 let rw: string;
19 let ro: string;
20 let bobRw: string;
21 let game: Repo;
22 const { tool, listCall } = mcpClient(() => forge.base);
23
24 beforeAll(async () => {
25 forge = await startMcpForge();
26 ({ app, rw, ro, bobRw, game } = forge);
27 }, 30_000);
28
29 afterAll(() => forge.stop());
30
31 test("map and wait_for are the plan's own actions", async () => {
32 const a = (await tool(rw, "tell", { repo: "alice/game", text: "first" }))
33 .value.issue;
34 const b = (await tool(rw, "tell", { repo: "alice/game", text: "second" }))
35 .value.issue;
36 const listed = await listCall(rw);
37 const hints = Object.fromEntries(
38 listed.body.result.tools.map((t: any) => [
39 t.name,
40 t.annotations?.readOnlyHint ?? false,
41 ]),
42 );
43 // map writes only when given `first`, so it spells no read-only hint.
44 expect([hints.map, hints.wait_for]).toEqual([false, false]);
45
46 expect(
47 (await tool(rw, "wait_for", { app: "alice/game", issue: b, blockedBy: a }))
48 .value.says,
49 ).toBe(`#${b} waits for #${a}.`);
50 const map = (await tool(ro, "map", { app: "alice/game" })).value;
51 expect(map.ready.map((i: any) => i.number)).toContain(a);
52 expect(map.blockedOn.map((i: any) => i.number)).toContain(a);
53 expect(map.issues.find((i: any) => i.number === b).word).toBe("blocked");
54 expect(map.edges).toContainEqual({ issue: b, blockedBy: a });
55
56 // The API's words, for a loop, a stranger issue, and a read token.
57 expect(
58 (await tool(rw, "wait_for", { app: "alice/game", issue: a, blockedBy: b }))
59 .error,
60 ).toStartWith("cycle: that would make a loop");
61 expect(
62 (await tool(rw, "wait_for", { app: "alice/game", issue: a, blockedBy: 999 }))
63 .error,
64 ).toStartWith("no_such_issue: no issue #999");
65 expect(
66 (await tool(ro, "wait_for", { app: "alice/game", issue: a, blockedBy: b }))
67 .error,
68 ).toContain("forbidden");
69 // A private app is no such app to someone who cannot read it.
70 expect((await tool(bobRw, "map", { app: "alice/game" })).error).toContain(
71 "not_found",
72 );
73 expect(
74 (await tool(bobRw, "wait_for", { app: "alice/game", issue: b, blockedBy: a }))
75 .error,
76 ).toContain("not_found");
77
78 await tool(rw, "wait_for", { app: "alice/game", issue: b, blockedBy: a, stop: true });
79 const after = (await tool(ro, "map", { app: "alice/game" })).value;
80 expect(after.edges).not.toContainEqual({ issue: b, blockedBy: a });
81 expect(after.ready.map((i: any) => i.number)).toContain(b);
82 }, 30_000);
83
84 test("with plans need a nod on, the plan tool stores one proposal and opens nothing", async () => {
85 updateRepoSettings(app.db, getRepoById(app.db, game.id)!, { plansNeedNod: true });
86 const count = async () =>
87 (await tool(ro, "map", { app: "alice/game" })).value.issues.length;
88 const before = await count();
89 const issues = [
90 { key: "a", title: "First" },
91 { key: "b", title: "Second", blockedBy: ["a"] },
92 ];
93 const done = await tool(rw, "plan", {
94 app: "alice/game",
95 title: "Two steps",
96 why: "worth a look",
97 issues,
98 });
99 expect(done.value.status).toBe("proposed");
100 const row = app.db
101 .query<{ title: string; why: string; issues: string }, [string]>(
102 "SELECT title, why, issues FROM plan_proposal WHERE id = ?1",
103 )
104 .get(done.value.id)!;
105 expect(row.title).toBe("Two steps");
106 expect(JSON.parse(row.issues).map((i: any) => i.key)).toEqual(["a", "b"]);
107 expect(await count()).toBe(before);
108 // The checks run as ever: a loop is refused and stores nothing.
109 const loop = await tool(rw, "plan", {
110 app: "alice/game",
111 issues: [{ key: "x", title: "X", blockedBy: ["x"] }],
112 });
113 expect(loop.error).toContain("self");
114 });
115
116 test("plan opens linked issues all or none", async () => {
117 updateRepoSettings(app.db, getRepoById(app.db, game.id)!, { plansNeedNod: false });
118 const issues = [
119 { key: "a", title: "First" },
120 { key: "b", title: "Second", body: "two" },
121 { key: "c", title: "Third", blockedBy: ["a", "b"] },
122 ];
123 const done = (await tool(rw, "plan", { app: "alice/game", issues })).value;
124 const n = Object.fromEntries(
125 done.opened.map((o: any) => [o.key, o.number]),
126 );
127 expect(done.ready).toEqual(expect.arrayContaining([n.a, n.b]));
128 expect(done.ready).not.toContain(n.c);
129 const map = (await tool(ro, "map", { app: "alice/game" })).value;
130 expect(map.edges).toContainEqual({ issue: n.c, blockedBy: n.a });
131 expect(map.edges).toContainEqual({ issue: n.c, blockedBy: n.b });
132
133 const count = async () =>
134 (await tool(ro, "map", { app: "alice/game" })).value.issues.length;
135 const before = await count();
136 const loop = await tool(rw, "plan", {
137 app: "alice/game",
138 issues: [
139 { key: "x", title: "X", blockedBy: ["y"] },
140 { key: "y", title: "Y", blockedBy: ["x"] },
141 ],
142 });
143 expect(loop.error).toContain("cycle");
144 const unknown = await tool(rw, "plan", {
145 app: "alice/game",
146 issues: [{ key: "x", title: "X", blockedBy: ["nope"] }],
147 });
148 expect(unknown.error).toContain('"nope"');
149 const many = await tool(rw, "plan", {
150 app: "alice/game",
151 issues: Array.from({ length: 13 }, (_, i) => ({
152 key: `k${i}`,
153 title: "t",
154 })),
155 });
156 expect(many.error).toContain("too_many");
157 expect(await count()).toBe(before);
158
159 expect(
160 (await tool(ro, "plan", { app: "alice/game", issues })).error,
161 ).toContain("forbidden");
162 });
163 });
test/mcp-forge-protocol.test.ts added +367
@@ -0,0 +1,367 @@
1 /**
2 * The forge as an MCP server: one short JSON-RPC call per answer, a token
3 * and never a cookie, `ro` reads and `rw` acts, and every tool is the same
4 * action the pages call — so what a person may not do on a page they may
5 * not do here.
6 *
7 * This file: the transport and the protocol: a token and never a cookie, the bare 405, initialize,
8 * ping and tools/list, `ro` reads and does not act. Split from mcp.test.ts by tool family, each
9 * file on its own forge from test/support/mcp-forge.ts (#15351).
10 */
11 import { TOKEN_FREE_TOOLS } from "../src/core/mcp_card.ts";
12 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
13 import { type App } from "../src/app.ts";
14 import { listIssues } from "../src/core/issues.ts";
15 import { type Repo } from "../src/core/repos.ts";
16 import { mcpClient, startMcpForge, type McpForge } from "./support/mcp-forge.ts";
17
18 /** tools/list's order: the tools by name, then `report`. */
19 const sortedThenReport = (names: string[]): string[] => [
20 ...names.filter((n) => n !== "report" && n !== "start" && n !== "offer").sort((a, b) => a.localeCompare(b)),
21 "report",
22 "start",
23 "offer",
24 ];
25
26 describe("the forge over MCP: protocol", () => {
27 let forge: McpForge;
28 let app: App;
29 let base: string;
30 let rw: string;
31 let ro: string;
32 let game: Repo;
33 const { call, tool, listCall } = mcpClient(() => forge.base);
34
35 beforeAll(async () => {
36 forge = await startMcpForge();
37 ({ app, base, rw, ro, game } = forge);
38 }, 30_000);
39
40 afterAll(() => forge.stop());
41
42 test("a token is the only way in, and a stream is never offered", async () => {
43 const anon = await call(null, "resources/list");
44 expect(anon.res.status).toBe(401);
45 expect(anon.res.headers.get("www-authenticate")).toContain("Bearer");
46 const get = await fetch(`${base}/mcp`, {
47 headers: { authorization: `Bearer ${rw}` },
48 });
49 expect(get.status).toBe(405);
50 expect(get.headers.get("allow")).toBe("POST");
51 });
52
53 test("a browser opening /mcp reads what it is; a client still gets the bare 405", async () => {
54 const browser = await fetch(`${base}/mcp`, { headers: { accept: "text/html" } });
55 expect(browser.status).toBe(405);
56 expect(browser.headers.get("allow")).toBe("POST");
57 expect(browser.headers.get("x-content-type-options")).toBe("nosniff");
58 const text = await browser.text();
59 expect(text).toContain("This is the forge's MCP server");
60 expect(text).toContain("/llms.txt");
61 expect(text).toContain("/.well-known/mcp.json");
62 const stream = await fetch(`${base}/mcp`, { headers: { accept: "text/event-stream" } });
63 expect(stream.status).toBe(405);
64 expect(stream.headers.get("allow")).toBe("POST");
65 expect(await stream.text()).toContain("JSON-RPC over POST");
66 const bare = await fetch(`${base}/mcp`);
67 expect(bare.status).toBe(405);
68 expect(await bare.text()).toContain("MCP endpoint");
69 const anon = await (await fetch(`${base}/mcp`, { headers: { accept: "text/html" } })).text();
70 expect(anon).toContain('href="/signin?next=%2Fmcp"');
71 expect(anon).not.toContain('href="/settings/tokens">Settings');
72 const signedIn = await fetch(`${base}/mcp`, {
73 headers: { accept: "text/html", authorization: `Bearer ${rw}` },
74 });
75 expect(signedIn.status).toBe(405);
76 const page = await signedIn.text();
77 expect(page).toContain('<a href="/settings/tokens">Settings › Tokens</a>');
78 expect(page).not.toContain("to make a token");
79 });
80
81 test("it speaks the protocol: initialize, a notification, ping, tools/list", async () => {
82 const init = await call(rw, "initialize", {
83 protocolVersion: "2025-03-26",
84 capabilities: {},
85 clientInfo: { name: "test", version: "0" },
86 });
87 expect(init.res.status).toBe(200);
88 expect(init.res.headers.get("content-type")).toContain("application/json");
89 expect(init.body.result.protocolVersion).toBe("2025-03-26");
90 expect(init.body.result.serverInfo.name).toBe("forge");
91 expect(init.body.result.capabilities.tools).toEqual({});
92 expect(init.body.result.capabilities.resources).toEqual({});
93 // A version it has never heard of gets the one it prefers.
94 const future = await call(rw, "initialize", {
95 protocolVersion: "2031-01-01",
96 });
97 expect(future.body.result.protocolVersion).toBe("2025-06-18");
98
99 const note = await fetch(`${base}/mcp`, {
100 method: "POST",
101 headers: {
102 "content-type": "application/json",
103 authorization: `Bearer ${rw}`,
104 },
105 body: JSON.stringify({
106 jsonrpc: "2.0",
107 method: "notifications/initialized",
108 }),
109 });
110 expect(note.status).toBe(202);
111 expect((await call(rw, "ping")).body.result).toEqual({});
112
113 const listed = await listCall(rw);
114 const names = listed.body.result.tools.map((t: { name: string }) => t.name);
115 // Listed by name, one file each (#5924), and `report` last.
116 expect(names).toEqual(sortedThenReport([
117 "data",
118 "desk",
119 "drills",
120 "drop",
121 "sizes",
122 "releases",
123 "apps",
124 "app_deploy",
125 "new_app",
126 "repo",
127 "here",
128 "tell",
129 "templates",
130 "share",
131 "say",
132 "issue",
133 "pull",
134 "preview",
135 "pulls",
136 "queue_gates",
137 "variant",
138 "edit",
139 "close",
140 "read_file",
141 "release_keeper",
142 "write_file",
143 "asks",
144 "asks_act",
145 "asks_decide",
146 "asks_proposal",
147 "proposal_tokens",
148 "asks_undecide",
149 "seal",
150 "secrets",
151 "issue_teams",
152 "issues",
153 "iterations",
154 "keep_plan",
155 "knobs",
156 "orgs",
157 "now",
158 "open_pull",
159 "org_create",
160 "stop",
161 "health",
162 "forge_view",
163 "audit",
164 "model_grant",
165 "accounts",
166 "whoami_can",
167 "profile",
168 "mint_invite",
169 "tokens",
170 "invites",
171 "account_role",
172 "account_suspend",
173 "account_requests",
174 "account_access",
175 "flag_winner",
176 "restore_drill",
177 "model_ceiling",
178 "account_verify",
179 "outsiders",
180 "origins",
181 "decisions_by",
182 "archive",
183 "detach",
184 "trail",
185 "migrate",
186 "migrate_data",
187 "events",
188 "reports",
189 "branches",
190 "builds",
191 "commits",
192 "waves",
193 "probe",
194 "following",
195 "spawn",
196 "forges",
197 "claim_link",
198 "take_back",
199 "take_updates",
200 "sync",
201 "sever",
202 "flag_set",
203 "economics",
204 "follow_mode",
205 "forge",
206 "fork",
207 "forks",
208 "fork_tree",
209 "upstream",
210 "propose_to_parent_forge",
211 "forge_proposals",
212 "converge",
213 "crew",
214 "family",
215 "features",
216 "next_steps",
217 "notify",
218 "thought",
219 "asked",
220 "assigned",
221 "assign",
222 "app_members",
223 "app_notes",
224 "egress_grants",
225 "explore",
226 "person",
227 "bets",
228 "bet",
229 "pinned_forge",
230 "search",
231 "feed",
232 "feed_chips",
233 "feed_dismiss",
234 "feed_like",
235 "find_tool",
236 "maintenance",
237 "make_it_yours",
238 "origin_apps",
239 "front_page",
240 "map",
241 "merge",
242 "milestones",
243 "watch",
244 "runs",
245 "run_log",
246 "limb",
247 "returns",
248 "review",
249 "threads",
250 "snapshot_now",
251 "spend",
252 "subscriptions",
253 "usage",
254 "labels",
255 "land_past_gate",
256 "repo_labels",
257 "wait_for",
258 "next_up",
259 "week",
260 "lift",
261 "held",
262 "confirm_wait",
263 "attach_look",
264 "hold",
265 "plan",
266 "atlas",
267 "access",
268 "capacity",
269 "scorecard",
270 "flags",
271 "flow",
272 "valves",
273 "system",
274 "backups",
275 "telemetry_history",
276 "contribute",
277 "limits",
278 "app_env",
279 "agents", "app_data_import",
280 "teams",
281 "cloud_accounts",
282 "cloud_account",
283 "quotas",
284 "signup",
285 "ssh_keys",
286 "steer",
287 "email_verify",
288 "estimate",
289 "parent_unlink",
290 "vision",
291 "boards",
292 "board_write",
293 "board_pins",
294 "pins",
295 "board_delete",
296 "report",
297 "start",
298 ]));
299 const byName = new Map<string, any>(
300 listed.body.result.tools.map((t: any) => [t.name, t]),
301 );
302 // A write leaves readOnlyHint to its default, false.
303 expect(byName.get("tell").annotations).toBeUndefined();
304 // The signup tool says what the setting does today, not that nothing reads it.
305 const signup: string = byName.get("signup").description;
306 expect(signup).not.toContain("Nothing reads it yet");
307 expect(signup).not.toContain("not redeemed");
308 expect(signup).toContain("invite lets in only a person with an open invite link");
309 expect(signup).toContain("closed refuses every new account");
310 expect(byName.get("tell").inputSchema.required).toBeUndefined();
311
312 expect((await call(rw, "nothing/here")).body.error.code).toBe(-32601);
313 expect(
314 (await call(rw, "tools/call", { name: "nope" })).body.error.code,
315 ).toBe(-32602);
316 });
317
318 test("a read token may read and not act", async () => {
319 const refused = await tool(ro, "tell", {
320 repo: "alice/game",
321 text: "add a level",
322 });
323 expect(refused.error).toContain("forbidden");
324 expect(listIssues(app.db, game.id, { state: "open" })).toHaveLength(0);
325 });
326
327 test("a browser session is not a way in, even signed in", async () => {
328 const signin = await fetch(`${base}/signin`, {
329 method: "POST",
330 redirect: "manual",
331 headers: {
332 "content-type": "application/x-www-form-urlencoded",
333 origin: base,
334 },
335 body: new URLSearchParams({
336 username: "alice",
337 password: "a-good-passphrase",
338 }),
339 });
340 const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
341 expect(cookie).toContain("=");
342 const res = await fetch(`${base}/mcp`, {
343 method: "POST",
344 headers: { "content-type": "application/json", cookie, origin: base },
345 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "resources/list" }),
346 });
347 expect(res.status).toBe(401);
348 });
349
350 test("a signed-in cookie caller is a stranger: the five token-free tools, never the full list", async () => {
351 const signin = await fetch(`${base}/signin`, {
352 method: "POST",
353 redirect: "manual",
354 headers: { "content-type": "application/x-www-form-urlencoded", origin: base },
355 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
356 });
357 const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
358 const res = await fetch(`${base}/mcp`, {
359 method: "POST",
360 headers: { "content-type": "application/json", cookie, origin: base },
361 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }),
362 });
363 expect(res.status).toBe(200);
364 const names = ((await res.json()) as any).result.tools.map((t: { name: string }) => t.name).sort();
365 expect(names).toEqual([...TOKEN_FREE_TOOLS].sort());
366 });
367 });
test/mcp-forge-reads.test.ts added +378
@@ -0,0 +1,378 @@
1 /**
2 * The forge as an MCP server: one short JSON-RPC call per answer, a token
3 * and never a cookie, `ro` reads and `rw` acts, and every tool is the same
4 * action the pages call — so what a person may not do on a page they may
5 * not do here.
6 *
7 * This file: the read tools: repo, apps, now, audit, issue, following, probe and pull. Split from
8 * mcp.test.ts by tool family, each file on its own forge from test/support/mcp-forge.ts (#15351).
9 */
10 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
11 import { type App } from "../src/app.ts";
12 import { addToCrew, createAgent } from "../src/actions/crew.ts";
13 import { pullDir } from "../src/core/pulls.ts";
14 import { resolveOid } from "../src/git/merge.ts";
15 import { openPull } from "../src/actions/pulls.ts";
16 import { commitToBranch, createRepo, forkRepo } from "../src/actions/repos.ts";
17 import { addComment, createIssue } from "../src/core/issues.ts";
18 import { addDependency } from "../src/core/dependencies.ts";
19 import { getRepoById, type Repo } from "../src/core/repos.ts";
20 import { createRun, setRunBase } from "../src/core/runs.ts";
21 import { createToken } from "../src/core/tokens.ts";
22 import { createUser, type User } from "../src/core/users.ts";
23 import { mcpClient, startMcpForge, type McpForge } from "./support/mcp-forge.ts";
24
25 describe("the forge over MCP: reads", () => {
26 let forge: McpForge;
27 let app: App;
28 let base: string;
29 let alice: User;
30 let bob: User;
31 let rw: string;
32 let ro: string;
33 let bobRw: string;
34 let game: Repo;
35 const { call, tool, listCall } = mcpClient(() => forge.base);
36
37 beforeAll(async () => {
38 forge = await startMcpForge();
39 ({ app, base, alice, bob, rw, ro, bobRw, game } = forge);
40 }, 30_000);
41
42 afterAll(() => forge.stop());
43
44 test("repo and GET /api/v1/repos give the same audience; a stranger learns nothing of a private one", async () => {
45 const api = async (token: string | null, path: string) =>
46 fetch(`${base}/api/v1/repos/${path}`, {
47 headers: token === null ? {} : { authorization: `Bearer ${token}` },
48 });
49 const viaApi = (await (await api(rw, "alice/game")).json()) as any;
50 const viaMcp = await tool(rw, "repo", { repo: "alice/game" });
51 expect(viaApi.audience.level).toBe("private");
52 expect(viaMcp.value.audience).toEqual(viaApi.audience);
53 expect(viaApi.audience.sentence).toStartWith("Private: only you");
54
55 // Bob cannot read it: a 404 and the same refusal, with no names in either.
56 const denied = await api(bobRw, "alice/game");
57 expect(denied.status).toBe(404);
58 expect(JSON.stringify(await denied.json())).not.toContain("alice");
59 expect((await tool(bobRw, "repo", { repo: "alice/game" })).error).toContain("no such");
60 const anon = await api(null, "alice/game");
61 expect(anon.status).toBe(404);
62 expect(JSON.stringify(await anon.json())).not.toContain("alice");
63
64 // A public repository tells everyone the public sentence, signed out too.
65 const open = await createRepo(app, alice, { name: "wide", visibility: "public" });
66 if (!open.ok) throw new Error(String(open.error));
67 const pub = (await (await api(null, "alice/wide")).json()) as any;
68 expect(pub.audience.level).toBe("public");
69 expect(pub.audience.sentence).toStartWith("Public: anyone can read this");
70 expect(pub.audience.sentence).not.toContain("you");
71 const asBob = await tool(bobRw, "repo", { repo: "alice/wide" });
72 expect(asBob.value.audience).toEqual(
73 ((await (await api(bobRw, "alice/wide")).json()) as any).audience,
74 );
75 });
76
77 test("apps and now read what the studio reads", async () => {
78 const apps = await tool(ro, "apps");
79 expect(apps.value).toHaveLength(1);
80 expect(apps.value[0].app).toBe("alice/game");
81 expect((await tool(ro, "now")).value).toEqual([]);
82 // Bob cannot see alice's private app: not in his list, not by name.
83 expect((await tool(bobRw, "apps")).value).toEqual([]);
84 expect(
85 (await tool(bobRw, "following", { repo: "alice/game" })).error,
86 ).toContain("not_found");
87 });
88
89 test("audit reads each app's contract from git, or says it has none", async () => {
90 const all = await tool(ro, "audit");
91 expect(all.value).toHaveLength(1);
92 expect(all.value[0].app).toBe("alice/game");
93 expect(all.value[0].standing).toBe("unread");
94 const one = await tool(ro, "audit", { repo: "alice/game" });
95 expect(one.value[0].standing).toBe("unread");
96 expect((await tool(bobRw, "audit")).value).toEqual([]);
97 expect(
98 (await tool(bobRw, "audit", { repo: "alice/game" })).error,
99 ).toContain("not_found");
100 });
101
102 test("issue reads body, comments, labels and what it waits for; a sealed one is not found; a reader is marked untrusted", async () => {
103 const mk = (title: string, body = "", sealed = false) => {
104 const r = createIssue(app.db, { repoId: game.id, authorId: alice.id, title, body, sealed });
105 if (!r.ok) throw new Error(String(r.error));
106 return r.value;
107 };
108 const waiting = mk("wait for it", "the body");
109 const first = mk("first");
110 expect(addDependency(app.db, waiting, first, alice.id).ok).toBe(true);
111 const bot = await createAgent(app, alice, { username: "issuebot", brief: "x" });
112 if (!bot.ok) throw new Error(String(bot.error));
113 expect(addToCrew(app, alice, game, "issuebot").ok).toBe(true);
114 addComment(app.db, { issueId: waiting.id, authorId: alice.id, body: "one" });
115 addComment(app.db, { issueId: waiting.id, authorId: bot.value.user.id, body: "two" });
116
117 const read = (await tool(rw, "issue", { repo: "alice/game", number: waiting.number })).value;
118 expect(read).toMatchObject({
119 number: waiting.number,
120 title: "wait for it",
121 state: "open",
122 closeReason: null,
123 body: "the body",
124 labels: [],
125 assignee: null,
126 blockedBy: [{ number: first.number, title: "first", state: "open" }],
127 blocks: [],
128 });
129 // The sentence and the chain the page draws (#13641).
130 expect(read.standing).toMatchObject({
131 line: `Waits for #${first.number} (queued).`,
132 ready: false,
133 before: [[{ number: first.number, badge: "queued", holding: true }]],
134 after: [],
135 more: 0,
136 });
137 expect(read.comments.map((c: any) => [c.author, c.authorIsAgent, c.body])).toEqual([
138 ["alice", false, "one"],
139 ["issuebot", true, "two"],
140 ]);
141 expect(read.comments[0].at).toBeString();
142 expect(read.untrusted).toBeUndefined();
143 const other = (await tool(rw, "issue", { repo: "alice/game", number: first.number })).value;
144 expect(other.blocks.map((b: any) => b.number)).toEqual([waiting.number]);
145
146 // Not found: no such number, and a pull's number is not an issue's.
147 expect((await tool(rw, "issue", { repo: "alice/game", number: 9999 })).error).toContain("not_found");
148 const branched = await commitToBranch(app, alice, game, {
149 branch: "issue-kind",
150 message: "a change",
151 files: [{ path: "kind.txt", content: "k\n" }],
152 });
153 if (!branched.ok) throw new Error(JSON.stringify(branched.error));
154 const opened = await openPull(app, alice, game, {
155 title: "Not an issue",
156 baseBranch: "main",
157 headBranch: "issue-kind",
158 });
159 if (!opened.ok) throw new Error(String(opened.error));
160 expect((await tool(rw, "issue", { repo: "alice/game", number: opened.value.number })).value).toEqual({ kind: "pull", tool: "pull" });
161 // Through MCP the card is built from the answer's repo; a pull's number has none.
162 const viaPull = await call(rw, "tools/call", { name: "issue", arguments: { repo: "alice/game", number: opened.value.number } });
163 expect(viaPull.body.result.structuredContent).toBeUndefined();
164 const viaIssue = await call(rw, "tools/call", { name: "issue", arguments: { repo: "alice/game", number: waiting.number } });
165 const card = viaIssue.body.result.structuredContent.card;
166 expect(card.kind).toBe("issue");
167 expect(card.rows[0].link).toMatch(/^https?:\/\/.+\/alice\/game\/issues\/\d+$/);
168 expect(card.rows[0].link.endsWith(`/alice/game/issues/${waiting.number}`)).toBe(true);
169 expect(card.rows.find((r: any) => r.label === "Waits for").link.endsWith(`/alice/game/issues/${first.number}`)).toBe(true);
170
171 // Sealed: the writer reads it; a reader of a public repo is told not found.
172 const pub = await createRepo(app, alice, { name: "sealedpub", visibility: "public" });
173 if (!pub.ok) throw new Error(String(pub.error));
174 const secret = createIssue(app.db, { repoId: pub.value.id, authorId: alice.id, title: "hole", sealed: true });
175 if (!secret.ok) throw new Error(String(secret.error));
176 const open = createIssue(app.db, { repoId: pub.value.id, authorId: alice.id, title: "visible" });
177 if (!open.ok) throw new Error(String(open.error));
178 expect((await tool(rw, "issue", { repo: "alice/sealedpub", number: secret.value.number })).value.title).toBe("hole");
179 expect((await tool(bobRw, "issue", { repo: "alice/sealedpub", number: secret.value.number })).error).toContain("not_found");
180
181 // A public issue waiting on the sealed one: the reader must not learn its title.
182 expect(addDependency(app.db, open.value, secret.value, alice.id).ok).toBe(true);
183 expect((await tool(bobRw, "issue", { repo: "alice/sealedpub", number: open.value.number })).value.blockedBy).toEqual([]);
184 const waits = (await tool(rw, "issue", { repo: "alice/sealedpub", number: open.value.number })).value.blockedBy;
185 expect(waits).toHaveLength(1);
186 expect(waits[0]).toMatchObject({ number: secret.value.number, title: "hole" });
187 expect((await tool(bobRw, "issue", { repo: "alice/sealedpub", number: open.value.number })).value.blockedBy).not.toContainEqual(expect.objectContaining({ title: "hole" }));
188
189 // Untrusted: bob cannot write alice/sealedpub; a crew agent is told so.
190 addComment(app.db, { issueId: open.value.id, authorId: bob.id, body: "from a reader" });
191 addComment(app.db, { issueId: open.value.id, authorId: alice.id, body: "from the owner" });
192 expect(addToCrew(app, alice, pub.value, "issuebot").ok).toBe(true);
193 const botToken = createToken(app.db, bot.value.user.id, "bot", "ro").token;
194 const marked = (await tool(botToken, "issue", { repo: "alice/sealedpub", number: open.value.number })).value;
195 expect(marked.comments.map((c: any) => c.untrusted)).toEqual([true, undefined]);
196 expect(marked.untrusted).toBeUndefined();
197
198 // An issue a reader filed is marked itself, for the crew agent and not for the owner.
199 const theirs = createIssue(app.db, { repoId: pub.value.id, authorId: bob.id, title: "from bob" });
200 if (!theirs.ok) throw new Error(String(theirs.error));
201 expect((await tool(botToken, "issue", { repo: "alice/sealedpub", number: theirs.value.number })).value.untrusted).toBe(true);
202 expect((await tool(rw, "issue", { repo: "alice/sealedpub", number: theirs.value.number })).value.untrusted).toBeUndefined();
203 });
204
205 test("following, take_updates and converge are the fork's page", async () => {
206 const pub = await createRepo(app, alice, {
207 name: "open",
208 visibility: "public",
209 });
210 if (!pub.ok) throw new Error(String(pub.error));
211 await commitToBranch(app, alice, pub.value, {
212 message: "seed",
213 files: [{ path: "README.md", content: "# open\n" }],
214 });
215 const forked = await forkRepo(app, bob, pub.value);
216 if (!forked.ok) throw new Error(String(forked.error));
217 const fresh = (r: Repo) => getRepoById(app.db, r.id)!;
218
219 expect(
220 (await tool(bobRw, "following", { repo: "alice/open" })).error,
221 ).toContain("not_a_fork");
222 expect(
223 (await tool(bobRw, "following", { repo: "bob/open" })).value.state,
224 ).toBe("synced");
225 // Both sides change the same file: a decision, so not git's to take.
226 await commitToBranch(app, bob, fresh(forked.value), {
227 message: "bob",
228 files: [{ path: "README.md", content: "# open, by bob\n" }],
229 });
230 await commitToBranch(app, alice, fresh(pub.value), {
231 message: "alice",
232 files: [{ path: "README.md", content: "# open, by alice\n" }],
233 });
234 const stands = await tool(bobRw, "following", { repo: "bob/open" });
235 expect(stands.value.state).toBe("diverged");
236 expect(stands.value.conflicts).toEqual(["README.md"]);
237 expect(
238 (await tool(bobRw, "take_updates", { repo: "bob/open" })).error,
239 ).toContain("conflict");
240 // Alice reads bob's public fork and may not move it.
241 expect(
242 (await tool(ro, "following", { repo: "bob/open" })).value.state,
243 ).toBe("diverged");
244 const carol = await createUser(app.db, { origin: "seed", trusted: true,
245 username: "carol",
246 email: "[email protected]",
247 password: "a-good-passphrase",
248 });
249 if (!carol.ok) throw new Error(carol.error);
250 const carolRw = createToken(app.db, carol.value.id, "rw", "rw").token;
251 expect(
252 (await tool(carolRw, "take_updates", { repo: "bob/open" })).error,
253 ).toContain("write access");
254 expect(
255 (await tool(bobRw, "converge", { repo: "bob/open" })).value.kind,
256 ).toBe("no_crew");
257 });
258
259 test("probe only reads, yet needs the access the page needs", async () => {
260 const listed = await listCall(ro);
261 const hints = Object.fromEntries(
262 listed.body.result.tools.map((t: any) => [
263 t.name,
264 t.annotations?.readOnlyHint ?? false,
265 ]),
266 );
267 expect(hints["probe"]).toBe(true);
268 expect(hints["stop"]).toBe(false);
269 // A repo the token may read, with nothing to compare with: it gets as far
270 // as the app and its contract, read token or not.
271 for (const token of [rw, ro])
272 expect(
273 (await tool(token, "probe", { repo: "alice/game" })).error,
274 ).toMatch(/not_an_app|no_contract/);
275 // One it may not read is no such repository.
276 expect(
277 (await tool(bobRw, "probe", { repo: "alice/game" })).error,
278 ).toContain("not_found");
279 expect(
280 (await tool(rw, "probe", { repo: "alice/nothing" })).error,
281 ).toContain("not_found");
282 });
283
284 test("pull carries the base tip its check was merged with (#1810)", async () => {
285 const branched = await commitToBranch(app, alice, game, {
286 branch: "feat",
287 message: "a change",
288 files: [{ path: "b.txt", content: "b\n" }],
289 });
290 if (!branched.ok) throw new Error(JSON.stringify(branched.error));
291 const opened = await openPull(app, alice, game, {
292 title: "Change",
293 baseBranch: "main",
294 headBranch: "feat",
295 });
296 if (!opened.ok) throw new Error(String(opened.error));
297 const pull = opened.value;
298 expect((await tool(ro, "pull", { repo: "alice/game", number: pull.number })).value.check).toEqual({ state: "none", baseOid: "" });
299 const run = createRun(app.db, {
300 repoId: game.id,
301 kind: "check",
302 issueId: pull.id,
303 env: `pull-${pull.number}`,
304 commitOid: branched.value.commitOid,
305 });
306 setRunBase(app.db, run.id, "abc1234abc1234abc1234abc1234abc1234abc12");
307 const read = await tool(ro, "pull", { repo: "alice/game", number: pull.number });
308 expect(read.value.check.baseOid).toBe("abc1234abc1234abc1234abc1234abc1234abc12");
309 // That base is not main's tip: the green is from an older main.
310 expect(read.value.checkStale).toBe(true);
311 const tip = await resolveOid(
312 await pullDir(app.db, app.reposRoot, game, pull),
313 "refs/heads/main",
314 );
315 setRunBase(app.db, run.id, tip ?? "");
316 expect(
317 (await tool(ro, "pull", { repo: "alice/game", number: pull.number })).value.checkStale,
318 ).toBe(false);
319 });
320
321 test("pull says checkStale in the MCP and the API when its check was on an older base (#2237)", async () => {
322 const branched = await commitToBranch(app, alice, game, {
323 branch: "stale-feat",
324 message: "another change",
325 files: [{ path: "c.txt", content: "c\n" }],
326 });
327 if (!branched.ok) throw new Error(JSON.stringify(branched.error));
328 const opened = await openPull(app, alice, game, {
329 title: "Stale",
330 baseBranch: "main",
331 headBranch: "stale-feat",
332 });
333 if (!opened.ok) throw new Error(String(opened.error));
334 const pull = opened.value;
335 const viaApi = async () =>
336 (await (
337 await fetch(`${base}/api/v1/repos/alice/game/pulls/${pull.number}`, {
338 headers: { authorization: `Bearer ${ro}` },
339 })
340 ).json()) as any;
341 const viaMcp = async () =>
342 (await tool(ro, "pull", { repo: "alice/game", number: pull.number })).value;
343 // No check, or one that recorded no base: not stale.
344 expect((await viaMcp()).checkStale).toBe(false);
345 expect((await viaApi()).checkStale).toBe(false);
346 const run = createRun(app.db, {
347 repoId: game.id,
348 kind: "check",
349 issueId: pull.id,
350 env: `pull-${pull.number}`,
351 commitOid: branched.value.commitOid,
352 });
353 expect((await viaMcp()).checkStale).toBe(false);
354 // Checked on the base's tip: not stale.
355 const tip: string = (await viaApi()).status.baseOid;
356 setRunBase(app.db, run.id, tip);
357 expect((await viaMcp()).checkStale).toBe(false);
358 expect((await viaApi()).checkStale).toBe(false);
359 // The base moves on: the green is from an older main.
360 const moved = await commitToBranch(app, alice, game, {
361 message: "main moves",
362 files: [{ path: "d.txt", content: "d\n" }],
363 });
364 if (!moved.ok) throw new Error(JSON.stringify(moved.error));
365 expect((await viaMcp()).checkStale).toBe(true);
366 expect((await viaApi()).checkStale).toBe(true);
367 // A new check on the new tip is current again.
368 setRunBase(app.db, run.id, moved.value.commitOid);
369 expect((await viaMcp()).checkStale).toBe(false);
370 expect((await viaApi()).checkStale).toBe(false);
371 // Stale again, then closed: a pull that cannot land reads false, not noise.
372 setRunBase(app.db, run.id, tip);
373 expect((await viaApi()).checkStale).toBe(true);
374 app.db.run("UPDATE issue SET state = 'closed' WHERE id = ?", [pull.id]);
375 expect((await viaMcp()).checkStale).toBe(false);
376 expect((await viaApi()).checkStale).toBe(false);
377 });
378 });
test/mcp-forge-tell.test.ts added +272
@@ -0,0 +1,272 @@
1 /**
2 * The forge as an MCP server: one short JSON-RPC call per answer, a token
3 * and never a cookie, `ro` reads and `rw` acts, and every tool is the same
4 * action the pages call — so what a person may not do on a page they may
5 * not do here.
6 *
7 * This file: the conversation's tools: tell, thought, say, close and stop. Split from mcp.test.ts
8 * by tool family, each file on its own forge from test/support/mcp-forge.ts (#15351).
9 */
10 import { READ_ONLY_REFUSAL } from "../src/http/mcp/hints.ts";
11 import { seatAs } from "./helpers/seat.ts";
12 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
13 import { type App } from "../src/app.ts";
14 import { addToCrew, createAgent } from "../src/actions/crew.ts";
15 import { openIssue } from "../src/actions/issues.ts";
16 import { listIssues } from "../src/core/issues.ts";
17 import { type Repo } from "../src/core/repos.ts";
18 import { createRun, listRuns } from "../src/core/runs.ts";
19 import { createToken } from "../src/core/tokens.ts";
20 import { type User } from "../src/core/users.ts";
21 import { savePlacement } from "../src/core/placements.ts";
22 import { mcpClient, startMcpForge, type McpForge } from "./support/mcp-forge.ts";
23
24 describe("the forge over MCP: tell", () => {
25 let forge: McpForge;
26 let app: App;
27 let base: string;
28 let alice: User;
29 let rw: string;
30 let ro: string;
31 let bobRw: string;
32 let game: Repo;
33 const { tool } = mcpClient(() => forge.base);
34
35 beforeAll(async () => {
36 forge = await startMcpForge();
37 ({ app, base, alice, rw, ro, bobRw, game } = forge);
38 }, 30_000);
39
40 afterAll(() => forge.stop());
41
42 test("tell without a repo keeps a thought and returns its id", async () => {
43 const kept = await tool(rw, "tell", { text: " a thought, as typed " });
44 expect(typeof kept.value.thought).toBe("string");
45 const row = app.db
46 .query("SELECT author, text, source FROM thought WHERE id = ?1")
47 .get(kept.value.thought) as any;
48 expect(row).toEqual({ author: alice.id, text: " a thought, as typed ", source: "mcp" });
49 expect(listIssues(app.db, game.id, { state: "open" })).toHaveLength(0);
50 expect((await tool(rw, "tell", { text: 5 })).error).toContain("invalid");
51 expect((await tool(ro, "tell", { text: "x" })).error).toContain("forbidden");
52 // With a repo it is still an issue.
53 expect(
54 (await tool(rw, "tell", { repo: "nobody/none", text: "x" })).error,
55 ).toContain("not_found");
56 });
57
58 test("thought returns its placement to its author only (#652)", async () => {
59 const kept = await tool(rw, "tell", { text: "build a thing" });
60 const id = kept.value.thought;
61 expect((await tool(rw, "thought", { id })).value).toEqual({ id, placement: null, repeats: [], supersedes: [], supersededBy: null, repeatedBy: [] });
62 savePlacement(app.db, {
63 thoughtId: id, kind: "work", placed: [{ action: "opened", repo: "alice/game", number: 3 }],
64 reply: "Opened #3.", asked: false, decidedBy: "rule", placedAt: new Date().toISOString(),
65 });
66 const got = await tool(rw, "thought", { id });
67 expect(got.value.placement).toMatchObject({ kind: "work", reply: "Opened #3.", asked: false });
68 expect((await tool(bobRw, "thought", { id })).error).toContain("not_found");
69 expect((await tool(rw, "thought", { id: "nope" })).error).toContain("not_found");
70 });
71
72 test("tell is the studio's tell: an issue, a builder, a run", async () => {
73 const empty = await tool(rw, "tell", { repo: "alice/game", text: " " });
74 expect(empty.error).toContain("empty");
75 const nobody = await tool(rw, "tell", {
76 repo: "alice/game",
77 text: "add a second level\n\nwith a boss at the end",
78 });
79 expect(nobody.value.says).toContain("Nobody is on the crew");
80 const [first] = listIssues(app.db, game.id, { state: "open" });
81 expect(first!.title).toBe("add a second level");
82 expect(first!.body).toContain("boss at the end");
83
84 const made = await createAgent(app, alice, {
85 username: "bot",
86 brief: "Be brief.",
87 });
88 if (!made.ok) throw new Error(String(made.error));
89 expect(addToCrew(app, alice, game, "bot").ok).toBe(true);
90 const told = await tool(rw, "tell", {
91 repo: "alice/game",
92 text: "fix the jump",
93 });
94 expect(told.value.says).toContain("bot is on it");
95 expect(told.value.page).toBe(
96 `${base}/alice/game/issues/${told.value.issue}`,
97 );
98 // Assigned to the builder, which is what starts a run where a crew is
99 // running; here there is none, so the run is queued by hand the way the
100 // crew's router would.
101 const jump = listIssues(app.db, game.id, { state: "open" }).find(
102 (i) => i.title === "fix the jump",
103 )!;
104 expect(jump.assigneeId).toBe(made.value.user.id);
105 expect(listRuns(app.db, game.id, { kind: "agent", limit: 5 })).toHaveLength(
106 0,
107 );
108 createRun(app.db, {
109 repoId: game.id,
110 kind: "agent",
111 issueId: jump.id,
112 actorId: made.value.user.id,
113 reason: "assigned",
114 });
115
116 const now = await tool(rw, "now");
117 expect(now.value).toHaveLength(1);
118 expect(now.value[0].app).toBe("alice/game");
119 expect(now.value[0].who).toBe("bot");
120 expect(now.value[0].on).toContain("fix the jump");
121
122 // Stop is the page's stop: exact, once, and only a writer's.
123 expect(
124 (await tool(bobRw, "stop", { repo: "alice/game", run: now.value[0].run }))
125 .error,
126 ).toContain("not_found");
127 const stopped = await tool(rw, "stop", {
128 repo: "alice/game",
129 run: now.value[0].run,
130 });
131 expect(stopped.value.says).toContain("Stopped run");
132 expect(
133 (await tool(rw, "stop", { repo: "alice/game", run: now.value[0].run }))
134 .error,
135 ).toContain("finished");
136 expect((await tool(rw, "now")).value).toEqual([]);
137 });
138
139 test("say lands on the conversation", async () => {
140 const [issue] = listIssues(app.db, game.id, { state: "open" });
141 const said = await tool(rw, "say", {
142 repo: "alice/game",
143 number: issue!.number,
144 text: "keep it under 50 lines",
145 });
146 expect(said.value.says).toBe(`Said on #${issue!.number}.`);
147 expect(
148 (await tool(rw, "say", { repo: "alice/game", number: 999, text: "x" }))
149 .error,
150 ).toContain("not_found");
151 });
152
153 test("close is the PATCH route's action: the same refusals, the new state answered", async () => {
154 const made = await createAgent(app, alice, { username: "closer", brief: "x" });
155 if (!made.ok) throw new Error(String(made.error));
156 expect(addToCrew(app, alice, game, "closer").ok).toBe(true);
157 seatAs(app.db, game.id, made.value.user.id, "planner");
158 const botToken = createToken(app.db, made.value.user.id, "bot", "rw").token;
159 const mine = (title: string) => {
160 const o = openIssue(app, made.value.user, game, { title });
161 if (!o.ok) throw new Error(String(o.error));
162 return o.value;
163 };
164 const patch = async (token: string, number: number, payload: unknown) => {
165 const res = await fetch(`${base}/api/v1/repos/alice/game/issues/${number}`, {
166 method: "PATCH",
167 headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
168 body: JSON.stringify(payload),
169 });
170 return { status: res.status, json: (await res.json()) as any };
171 };
172
173 // Done with no commit naming it: refused, with the API's code.
174 const noNote = mine("a thing nobody did");
175 const viaApi = await patch(botToken, noNote.number, { state: "closed", reason: "done" });
176 expect(viaApi.json.error).toBe("forbidden");
177 const refused = await tool(botToken, "close", { repo: "alice/game", number: noNote.number, reason: "done" });
178 expect(refused.error).toContain("forbidden");
179 expect(refused.error).toContain("already done on main");
180 expect(viaApi.json.message).toContain("already done on main");
181
182 // Its own, dropped: closed, and the answer says so.
183 const own = mine("a thing to drop");
184 const dropped = await tool(botToken, "close", {
185 repo: "alice/game",
186 number: own.number,
187 reason: "dropped",
188 });
189 expect(dropped.value).toMatchObject({ number: own.number, state: "closed", closeReason: "dropped" });
190
191 // A person's ask is not an agent's to drop.
192 const asked = openIssue(app, alice, game, { title: "a person asks" });
193 if (!asked.ok) throw new Error(String(asked.error));
194 expect(
195 (await tool(botToken, "close", { repo: "alice/game", number: asked.value.number, reason: "dropped" })).error,
196 ).toContain("a person's ask stands in");
197 // Split into an issue that is not newer than the hand-over.
198 expect(
199 (await tool(botToken, "close", { repo: "alice/game", number: asked.value.number, reason: "split", into: [noNote.number] })).error,
200 ).toContain("opened after ");
201 // A closed issue is not the planner's to close again.
202 expect(
203 (await tool(botToken, "close", { repo: "alice/game", number: own.number })).error,
204 ).toContain("any other close is not the planner's");
205 // Nor does an agent reopen.
206 expect((await tool(botToken, "close", { repo: "alice/game", number: own.number, state: "open" })).error).toContain(
207 "forbidden",
208 );
209
210 // A person reopens it; closing defaults to done.
211 const reopened = await tool(rw, "close", { repo: "alice/game", number: own.number, state: "open" });
212 expect(reopened.value).toMatchObject({ state: "open", closeReason: null });
213 const closed = await tool(rw, "close", { repo: "alice/game", number: own.number });
214 expect(closed.value).toMatchObject({ state: "closed", closeReason: "done" });
215
216 // The boundary: bad words are refused before the action.
217 expect((await tool(rw, "close", { repo: "alice/game", number: own.number, state: "x" })).error).toContain("invalid_state");
218 expect((await tool(rw, "close", { repo: "alice/game", number: own.number, reason: "x" })).error).toContain("invalid_reason");
219 expect((await tool(rw, "close", { repo: "alice/game", number: own.number, into: [0] })).error).toContain("invalid_reason");
220 expect((await tool(ro, "close", { repo: "alice/game", number: own.number })).error).toContain(READ_ONLY_REFUSAL);
221 });
222
223 test("stop takes a run id from now, and refuses a stale or foreign one", async () => {
224 const run = createRun(app.db, {
225 repoId: game.id,
226 kind: "agent",
227 actorId: alice.id,
228 reason: "assigned",
229 });
230 expect(
231 (await tool(ro, "stop", { repo: "alice/game", run: run.id })).error,
232 ).toContain("forbidden");
233 expect(
234 (await tool(bobRw, "stop", { repo: "alice/game", run: run.id })).error,
235 ).toContain("not_found");
236 expect(
237 (await tool(rw, "stop", { repo: "alice/game", run: "nosuchrun" })).error,
238 ).toContain("not_found");
239 const stopped = await tool(rw, "stop", { repo: "alice/game", run: run.id });
240 expect(stopped.value.says).toBe(`Stopped run ${run.id}.`);
241 const stale = await tool(rw, "stop", { repo: "alice/game", run: run.id });
242 expect(stale.error).toContain("finished");
243 expect(stale.error).toContain("already ended");
244 });
245
246 test("a tell carries where it was told from, and refuses a malformed context", async () => {
247 const told = await tool(rw, "tell", {
248 repo: "alice/game",
249 text: "make the button blue",
250 context: {
251 page: "https://game.example/play?level=2",
252 run: "run_abc",
253 commit: "deadbeef1",
254 said: "the button is hard to see",
255 },
256 });
257 const issues = listIssues(app.db, game.id, {});
258 const issue = issues.find((i) => i.title === "make the button blue");
259 expect(issue?.body).toContain("page: https://game.example/play?level=2");
260 expect(issue?.body).toContain("commit: deadbeef1");
261 expect(issue?.body).toContain("their words: the button is hard to see");
262 expect(told).toBeDefined();
263 for (const context of [
264 { page: "javascript:alert(1)" },
265 { commit: "--upload-pack=x" },
266 "text",
267 ]) {
268 const refused = await tool(rw, "tell", { repo: "alice/game", text: "x", context });
269 expect(refused.error).toContain("invalid");
270 }
271 });
272 });
test/mcp.test.ts deleted −1849
@@ -1,1849 +0,0 @@
1 /**
2 * The forge as an MCP server: one short JSON-RPC call per answer, a token
3 * and never a cookie, `ro` reads and `rw` acts, and every tool is the same
4 * action the pages call — so what a person may not do on a page they may
5 * not do here.
6 */
7 import { TOKEN_FREE_TOOLS } from "../src/core/mcp_card.ts";
8 import { READ_ONLY_REFUSAL } from "../src/http/mcp/hints.ts";
9 import { seatAs } from "./helpers/seat.ts";
10 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
11 import { chmodSync, writeFileSync } from "node:fs";
12 import { mkdtemp, rm } from "node:fs/promises";
13 import { tmpdir } from "node:os";
14 import { join } from "node:path";
15 import { createApp, type App } from "../src/app.ts";
16 import { setSsh } from "../src/settings/ssh.ts";
17 import { addToCrew, createAgent } from "../src/actions/crew.ts";
18 import { pullDir } from "../src/core/pulls.ts";
19 import { resolveOid } from "../src/git/merge.ts";
20 import { openIssue } from "../src/actions/issues.ts";
21 import {} from "../src/core/agents.ts";
22 import { openPull } from "../src/actions/pulls.ts";
23 import { commitToBranch, createRepo, forkRepo } from "../src/actions/repos.ts";
24 import { createApp as insertApp } from "../src/core/apps.ts";
25 import { addComment, createIssue, listIssues } from "../src/core/issues.ts";
26 import { addDependency } from "../src/core/dependencies.ts";
27 import { getRepo, getRepoById, updateRepoSettings, type Repo } from "../src/core/repos.ts";
28 import { createRun, listRuns, setRunBase } from "../src/core/runs.ts";
29 import { getAccountCeiling } from "../src/core/account_ceiling.ts";
30 import { createToken } from "../src/core/tokens.ts";
31 import { setMember } from "../src/core/roles.ts";
32 import { createUser, type User } from "../src/core/users.ts";
33 import { savePlacement } from "../src/core/placements.ts";
34 import { serve, type Servers } from "../src/http/server.ts";
35 import { limitChanges, limitValue } from "../src/settings/limits.ts";
36 import { promote } from "./helpers/members.ts";
37 import { showBoard } from "../src/actions/boards.ts";
38 import { panelData } from "../src/boards/panel_data.ts";
39 import { listVia } from "./mcp-list.ts";
40 import { adminOpenapi } from "./helpers/openapi-doc.ts";
41 import { askForReviews } from "./helpers/reviews.ts";
42
43 /** tools/list's order: the tools by name, then `report`. */
44 const sortedThenReport = (names: string[]): string[] => [
45 ...names.filter((n) => n !== "report" && n !== "start" && n !== "offer").sort((a, b) => a.localeCompare(b)),
46 "report",
47 "start",
48 "offer",
49 ];
50
51 describe("the forge over MCP", () => {
52 let dataDir: string;
53 let app: App;
54 let servers: Servers;
55 let base: string;
56 let alice: User;
57 let bob: User;
58 let rw: string;
59 let ro: string;
60 let bobRw: string;
61 let game: Repo;
62 let nextId = 1;
63
64 const listCall = async (token: string) => ({
65 body: await listVia(async (p) => (await call(token, "tools/list", p)).body),
66 });
67
68 const call = async (
69 token: string | null,
70 method: string,
71 params?: unknown,
72 extra: Record<string, string> = {},
73 ) => {
74 const res = await fetch(`${base}/mcp`, {
75 method: "POST",
76 headers: {
77 "content-type": "application/json",
78 accept: "application/json, text/event-stream",
79 ...(token === null ? {} : { authorization: `Bearer ${token}` }),
80 ...extra,
81 },
82 body: JSON.stringify({ jsonrpc: "2.0", id: nextId++, method, params }),
83 });
84 return {
85 res,
86 body: res.status === 202 ? null : ((await res.json()) as any),
87 };
88 };
89 /** A tool's answer: its JSON value, or its error text. */
90 const tool = async (token: string, name: string, args: unknown = {}) => {
91 const { body } = await call(token, "tools/call", { name, arguments: args });
92 const text: string = body.result.content[0].text;
93 return body.result.isError === true
94 ? { error: text }
95 : { value: JSON.parse(text) };
96 };
97
98 beforeAll(async () => {
99 dataDir = await mkdtemp(join(tmpdir(), "forge-mcp-"));
100 app = createApp({ dataDir, port: 0 });
101 setSsh(app.db, true, "test");
102 servers = await serve(app);
103 base = servers.url;
104 const a = await createUser(app.db, { origin: "seed", trusted: true,
105 username: "alice",
106 email: "[email protected]",
107 password: "a-good-passphrase",
108 adminIfFirst: true,
109 });
110 if (!a.ok) throw new Error(a.error);
111 alice = a.value;
112 const b = await createUser(app.db, { origin: "seed", trusted: true,
113 username: "bob",
114 email: "[email protected]",
115 password: "a-good-passphrase",
116 });
117 if (!b.ok) throw new Error(b.error);
118 bob = b.value;
119 promote(app.db, bob);
120 rw = createToken(app.db, alice.id, "rw", "rw").token;
121 ro = createToken(app.db, alice.id, "ro", "ro").token;
122 bobRw = createToken(app.db, bob.id, "rw", "rw").token;
123 const made = await createRepo(app, alice, {
124 name: "game",
125 visibility: "private",
126 });
127 if (!made.ok) throw new Error(String(made.error));
128 game = made.value;
129 askForReviews(app.db, game.id);
130 await commitToBranch(app, alice, game, {
131 message: "seed",
132 files: [{ path: "README.md", content: "# game\n" }],
133 });
134 const record = insertApp(app.db, {
135 repoId: game.id,
136 slug: "game",
137 access: "private",
138 });
139 if (!record.ok) throw new Error(record.error);
140 }, 30_000);
141
142 afterAll(async () => {
143 servers.stop();
144 app.close();
145 await rm(dataDir, { recursive: true, force: true });
146 });
147
148 test("a token is the only way in, and a stream is never offered", async () => {
149 const anon = await call(null, "resources/list");
150 expect(anon.res.status).toBe(401);
151 expect(anon.res.headers.get("www-authenticate")).toContain("Bearer");
152 const get = await fetch(`${base}/mcp`, {
153 headers: { authorization: `Bearer ${rw}` },
154 });
155 expect(get.status).toBe(405);
156 expect(get.headers.get("allow")).toBe("POST");
157 });
158
159 test("a browser opening /mcp reads what it is; a client still gets the bare 405", async () => {
160 const browser = await fetch(`${base}/mcp`, { headers: { accept: "text/html" } });
161 expect(browser.status).toBe(405);
162 expect(browser.headers.get("allow")).toBe("POST");
163 expect(browser.headers.get("x-content-type-options")).toBe("nosniff");
164 const text = await browser.text();
165 expect(text).toContain("This is the forge's MCP server");
166 expect(text).toContain("/llms.txt");
167 expect(text).toContain("/.well-known/mcp.json");
168 const stream = await fetch(`${base}/mcp`, { headers: { accept: "text/event-stream" } });
169 expect(stream.status).toBe(405);
170 expect(stream.headers.get("allow")).toBe("POST");
171 expect(await stream.text()).toContain("JSON-RPC over POST");
172 const bare = await fetch(`${base}/mcp`);
173 expect(bare.status).toBe(405);
174 expect(await bare.text()).toContain("MCP endpoint");
175 const anon = await (await fetch(`${base}/mcp`, { headers: { accept: "text/html" } })).text();
176 expect(anon).toContain('href="/signin?next=%2Fmcp"');
177 expect(anon).not.toContain('href="/settings/tokens">Settings');
178 const signedIn = await fetch(`${base}/mcp`, {
179 headers: { accept: "text/html", authorization: `Bearer ${rw}` },
180 });
181 expect(signedIn.status).toBe(405);
182 const page = await signedIn.text();
183 expect(page).toContain('<a href="/settings/tokens">Settings › Tokens</a>');
184 expect(page).not.toContain("to make a token");
185 });
186
187 test("it speaks the protocol: initialize, a notification, ping, tools/list", async () => {
188 const init = await call(rw, "initialize", {
189 protocolVersion: "2025-03-26",
190 capabilities: {},
191 clientInfo: { name: "test", version: "0" },
192 });
193 expect(init.res.status).toBe(200);
194 expect(init.res.headers.get("content-type")).toContain("application/json");
195 expect(init.body.result.protocolVersion).toBe("2025-03-26");
196 expect(init.body.result.serverInfo.name).toBe("forge");
197 expect(init.body.result.capabilities.tools).toEqual({});
198 expect(init.body.result.capabilities.resources).toEqual({});
199 // A version it has never heard of gets the one it prefers.
200 const future = await call(rw, "initialize", {
201 protocolVersion: "2031-01-01",
202 });
203 expect(future.body.result.protocolVersion).toBe("2025-06-18");
204
205 const note = await fetch(`${base}/mcp`, {
206 method: "POST",
207 headers: {
208 "content-type": "application/json",
209 authorization: `Bearer ${rw}`,
210 },
211 body: JSON.stringify({
212 jsonrpc: "2.0",
213 method: "notifications/initialized",
214 }),
215 });
216 expect(note.status).toBe(202);
217 expect((await call(rw, "ping")).body.result).toEqual({});
218
219 const listed = await listCall(rw);
220 const names = listed.body.result.tools.map((t: { name: string }) => t.name);
221 // Listed by name, one file each (#5924), and `report` last.
222 expect(names).toEqual(sortedThenReport([
223 "data",
224 "desk",
225 "drills",
226 "drop",
227 "sizes",
228 "releases",
229 "apps",
230 "app_deploy",
231 "new_app",
232 "repo",
233 "here",
234 "tell",
235 "templates",
236 "share",
237 "say",
238 "issue",
239 "pull",
240 "preview",
241 "pulls",
242 "queue_gates",
243 "variant",
244 "edit",
245 "close",
246 "read_file",
247 "release_keeper",
248 "write_file",
249 "asks",
250 "asks_act",
251 "asks_decide",
252 "asks_proposal",
253 "proposal_tokens",
254 "asks_undecide",
255 "seal",
256 "secrets",
257 "issue_teams",
258 "issues",
259 "iterations",
260 "keep_plan",
261 "knobs",
262 "orgs",
263 "now",
264 "open_pull",
265 "org_create",
266 "stop",
267 "health",
268 "forge_view",
269 "audit",
270 "model_grant",
271 "accounts",
272 "whoami_can",
273 "profile",
274 "mint_invite",
275 "tokens",
276 "invites",
277 "account_role",
278 "account_suspend",
279 "account_requests",
280 "account_access",
281 "flag_winner",
282 "restore_drill",
283 "model_ceiling",
284 "account_verify",
285 "outsiders",
286 "origins",
287 "decisions_by",
288 "archive",
289 "detach",
290 "trail",
291 "migrate",
292 "migrate_data",
293 "events",
294 "reports",
295 "branches",
296 "builds",
297 "commits",
298 "waves",
299 "probe",
300 "following",
301 "spawn",
302 "forges",
303 "claim_link",
304 "take_back",
305 "take_updates",
306 "sync",
307 "sever",
308 "flag_set",
309 "economics",
310 "follow_mode",
311 "forge",
312 "fork",
313 "forks",
314 "fork_tree",
315 "upstream",
316 "propose_to_parent_forge",
317 "forge_proposals",
318 "converge",
319 "crew",
320 "family",
321 "features",
322 "next_steps",
323 "notify",
324 "thought",
325 "asked",
326 "assigned",
327 "assign",
328 "app_members",
329 "app_notes",
330 "egress_grants",
331 "explore",
332 "person",
333 "bets",
334 "bet",
335 "pinned_forge",
336 "search",
337 "feed",
338 "feed_chips",
339 "feed_dismiss",
340 "feed_like",
341 "find_tool",
342 "maintenance",
343 "make_it_yours",
344 "origin_apps",
345 "front_page",
346 "map",
347 "merge",
348 "milestones",
349 "watch",
350 "runs",
351 "run_log",
352 "limb",
353 "returns",
354 "review",
355 "threads",
356 "snapshot_now",
357 "spend",
358 "subscriptions",
359 "usage",
360 "labels",
361 "land_past_gate",
362 "repo_labels",
363 "wait_for",
364 "next_up",
365 "week",
366 "lift",
367 "held",
368 "confirm_wait",
369 "attach_look",
370 "hold",
371 "plan",
372 "atlas",
373 "access",
374 "capacity",
375 "scorecard",
376 "flags",
377 "flow",
378 "valves",
379 "system",
380 "backups",
381 "telemetry_history",
382 "contribute",
383 "limits",
384 "app_env",
385 "agents", "app_data_import",
386 "teams",
387 "cloud_accounts",
388 "cloud_account",
389 "quotas",
390 "signup",
391 "ssh_keys",
392 "steer",
393 "email_verify",
394 "estimate",
395 "parent_unlink",
396 "vision",
397 "boards",
398 "board_write",
399 "board_pins",
400 "pins",
401 "board_delete",
402 "report",
403 "start",
404 ]));
405 const byName = new Map<string, any>(
406 listed.body.result.tools.map((t: any) => [t.name, t]),
407 );
408 // A write leaves readOnlyHint to its default, false.
409 expect(byName.get("tell").annotations).toBeUndefined();
410 // The signup tool says what the setting does today, not that nothing reads it.
411 const signup: string = byName.get("signup").description;
412 expect(signup).not.toContain("Nothing reads it yet");
413 expect(signup).not.toContain("not redeemed");
414 expect(signup).toContain("invite lets in only a person with an open invite link");
415 expect(signup).toContain("closed refuses every new account");
416 expect(byName.get("tell").inputSchema.required).toBeUndefined();
417
418 expect((await call(rw, "nothing/here")).body.error.code).toBe(-32601);
419 expect(
420 (await call(rw, "tools/call", { name: "nope" })).body.error.code,
421 ).toBe(-32602);
422 });
423
424 test("repo and GET /api/v1/repos give the same audience; a stranger learns nothing of a private one", async () => {
425 const api = async (token: string | null, path: string) =>
426 fetch(`${base}/api/v1/repos/${path}`, {
427 headers: token === null ? {} : { authorization: `Bearer ${token}` },
428 });
429 const viaApi = (await (await api(rw, "alice/game")).json()) as any;
430 const viaMcp = await tool(rw, "repo", { repo: "alice/game" });
431 expect(viaApi.audience.level).toBe("private");
432 expect(viaMcp.value.audience).toEqual(viaApi.audience);
433 expect(viaApi.audience.sentence).toStartWith("Private: only you");
434
435 // Bob cannot read it: a 404 and the same refusal, with no names in either.
436 const denied = await api(bobRw, "alice/game");
437 expect(denied.status).toBe(404);
438 expect(JSON.stringify(await denied.json())).not.toContain("alice");
439 expect((await tool(bobRw, "repo", { repo: "alice/game" })).error).toContain("no such");
440 const anon = await api(null, "alice/game");
441 expect(anon.status).toBe(404);
442 expect(JSON.stringify(await anon.json())).not.toContain("alice");
443
444 // A public repository tells everyone the public sentence, signed out too.
445 const open = await createRepo(app, alice, { name: "wide", visibility: "public" });
446 if (!open.ok) throw new Error(String(open.error));
447 const pub = (await (await api(null, "alice/wide")).json()) as any;
448 expect(pub.audience.level).toBe("public");
449 expect(pub.audience.sentence).toStartWith("Public: anyone can read this");
450 expect(pub.audience.sentence).not.toContain("you");
451 const asBob = await tool(bobRw, "repo", { repo: "alice/wide" });
452 expect(asBob.value.audience).toEqual(
453 ((await (await api(bobRw, "alice/wide")).json()) as any).audience,
454 );
455 });
456
457 test("apps and now read what the studio reads", async () => {
458 const apps = await tool(ro, "apps");
459 expect(apps.value).toHaveLength(1);
460 expect(apps.value[0].app).toBe("alice/game");
461 expect((await tool(ro, "now")).value).toEqual([]);
462 // Bob cannot see alice's private app: not in his list, not by name.
463 expect((await tool(bobRw, "apps")).value).toEqual([]);
464 expect(
465 (await tool(bobRw, "following", { repo: "alice/game" })).error,
466 ).toContain("not_found");
467 });
468
469 test("audit reads each app's contract from git, or says it has none", async () => {
470 const all = await tool(ro, "audit");
471 expect(all.value).toHaveLength(1);
472 expect(all.value[0].app).toBe("alice/game");
473 expect(all.value[0].standing).toBe("unread");
474 const one = await tool(ro, "audit", { repo: "alice/game" });
475 expect(one.value[0].standing).toBe("unread");
476 expect((await tool(bobRw, "audit")).value).toEqual([]);
477 expect(
478 (await tool(bobRw, "audit", { repo: "alice/game" })).error,
479 ).toContain("not_found");
480 });
481
482 test("a read token may read and not act", async () => {
483 const refused = await tool(ro, "tell", {
484 repo: "alice/game",
485 text: "add a level",
486 });
487 expect(refused.error).toContain("forbidden");
488 expect(listIssues(app.db, game.id, { state: "open" })).toHaveLength(0);
489 });
490
491 test("tell without a repo keeps a thought and returns its id", async () => {
492 const kept = await tool(rw, "tell", { text: " a thought, as typed " });
493 expect(typeof kept.value.thought).toBe("string");
494 const row = app.db
495 .query("SELECT author, text, source FROM thought WHERE id = ?1")
496 .get(kept.value.thought) as any;
497 expect(row).toEqual({ author: alice.id, text: " a thought, as typed ", source: "mcp" });
498 expect(listIssues(app.db, game.id, { state: "open" })).toHaveLength(0);
499 expect((await tool(rw, "tell", { text: 5 })).error).toContain("invalid");
500 expect((await tool(ro, "tell", { text: "x" })).error).toContain("forbidden");
501 // With a repo it is still an issue.
502 expect(
503 (await tool(rw, "tell", { repo: "nobody/none", text: "x" })).error,
504 ).toContain("not_found");
505 });
506
507 test("thought returns its placement to its author only (#652)", async () => {
508 const kept = await tool(rw, "tell", { text: "build a thing" });
509 const id = kept.value.thought;
510 expect((await tool(rw, "thought", { id })).value).toEqual({ id, placement: null, repeats: [], supersedes: [], supersededBy: null, repeatedBy: [] });
511 savePlacement(app.db, {
512 thoughtId: id, kind: "work", placed: [{ action: "opened", repo: "alice/game", number: 3 }],
513 reply: "Opened #3.", asked: false, decidedBy: "rule", placedAt: new Date().toISOString(),
514 });
515 const got = await tool(rw, "thought", { id });
516 expect(got.value.placement).toMatchObject({ kind: "work", reply: "Opened #3.", asked: false });
517 expect((await tool(bobRw, "thought", { id })).error).toContain("not_found");
518 expect((await tool(rw, "thought", { id: "nope" })).error).toContain("not_found");
519 });
520
521 test("tell is the studio's tell: an issue, a builder, a run", async () => {
522 const empty = await tool(rw, "tell", { repo: "alice/game", text: " " });
523 expect(empty.error).toContain("empty");
524 const nobody = await tool(rw, "tell", {
525 repo: "alice/game",
526 text: "add a second level\n\nwith a boss at the end",
527 });
528 expect(nobody.value.says).toContain("Nobody is on the crew");
529 const [first] = listIssues(app.db, game.id, { state: "open" });
530 expect(first!.title).toBe("add a second level");
531 expect(first!.body).toContain("boss at the end");
532
533 const made = await createAgent(app, alice, {
534 username: "bot",
535 brief: "Be brief.",
536 });
537 if (!made.ok) throw new Error(String(made.error));
538 expect(addToCrew(app, alice, game, "bot").ok).toBe(true);
539 const told = await tool(rw, "tell", {
540 repo: "alice/game",
541 text: "fix the jump",
542 });
543 expect(told.value.says).toContain("bot is on it");
544 expect(told.value.page).toBe(
545 `${base}/alice/game/issues/${told.value.issue}`,
546 );
547 // Assigned to the builder, which is what starts a run where a crew is
548 // running; here there is none, so the run is queued by hand the way the
549 // crew's router would.
550 const jump = listIssues(app.db, game.id, { state: "open" }).find(
551 (i) => i.title === "fix the jump",
552 )!;
553 expect(jump.assigneeId).toBe(made.value.user.id);
554 expect(listRuns(app.db, game.id, { kind: "agent", limit: 5 })).toHaveLength(
555 0,
556 );
557 createRun(app.db, {
558 repoId: game.id,
559 kind: "agent",
560 issueId: jump.id,
561 actorId: made.value.user.id,
562 reason: "assigned",
563 });
564
565 const now = await tool(rw, "now");
566 expect(now.value).toHaveLength(1);
567 expect(now.value[0].app).toBe("alice/game");
568 expect(now.value[0].who).toBe("bot");
569 expect(now.value[0].on).toContain("fix the jump");
570
571 // Stop is the page's stop: exact, once, and only a writer's.
572 expect(
573 (await tool(bobRw, "stop", { repo: "alice/game", run: now.value[0].run }))
574 .error,
575 ).toContain("not_found");
576 const stopped = await tool(rw, "stop", {
577 repo: "alice/game",
578 run: now.value[0].run,
579 });
580 expect(stopped.value.says).toContain("Stopped run");
581 expect(
582 (await tool(rw, "stop", { repo: "alice/game", run: now.value[0].run }))
583 .error,
584 ).toContain("finished");
585 expect((await tool(rw, "now")).value).toEqual([]);
586 });
587
588 test("say lands on the conversation", async () => {
589 const [issue] = listIssues(app.db, game.id, { state: "open" });
590 const said = await tool(rw, "say", {
591 repo: "alice/game",
592 number: issue!.number,
593 text: "keep it under 50 lines",
594 });
595 expect(said.value.says).toBe(`Said on #${issue!.number}.`);
596 expect(
597 (await tool(rw, "say", { repo: "alice/game", number: 999, text: "x" }))
598 .error,
599 ).toContain("not_found");
600 });
601
602 test("close is the PATCH route's action: the same refusals, the new state answered", async () => {
603 const made = await createAgent(app, alice, { username: "closer", brief: "x" });
604 if (!made.ok) throw new Error(String(made.error));
605 expect(addToCrew(app, alice, game, "closer").ok).toBe(true);
606 seatAs(app.db, game.id, made.value.user.id, "planner");
607 const botToken = createToken(app.db, made.value.user.id, "bot", "rw").token;
608 const mine = (title: string) => {
609 const o = openIssue(app, made.value.user, game, { title });
610 if (!o.ok) throw new Error(String(o.error));
611 return o.value;
612 };
613 const patch = async (token: string, number: number, payload: unknown) => {
614 const res = await fetch(`${base}/api/v1/repos/alice/game/issues/${number}`, {
615 method: "PATCH",
616 headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
617 body: JSON.stringify(payload),
618 });
619 return { status: res.status, json: (await res.json()) as any };
620 };
621
622 // Done with no commit naming it: refused, with the API's code.
623 const noNote = mine("a thing nobody did");
624 const viaApi = await patch(botToken, noNote.number, { state: "closed", reason: "done" });
625 expect(viaApi.json.error).toBe("forbidden");
626 const refused = await tool(botToken, "close", { repo: "alice/game", number: noNote.number, reason: "done" });
627 expect(refused.error).toContain("forbidden");
628 expect(refused.error).toContain("already done on main");
629 expect(viaApi.json.message).toContain("already done on main");
630
631 // Its own, dropped: closed, and the answer says so.
632 const own = mine("a thing to drop");
633 const dropped = await tool(botToken, "close", {
634 repo: "alice/game",
635 number: own.number,
636 reason: "dropped",
637 });
638 expect(dropped.value).toMatchObject({ number: own.number, state: "closed", closeReason: "dropped" });
639
640 // A person's ask is not an agent's to drop.
641 const asked = openIssue(app, alice, game, { title: "a person asks" });
642 if (!asked.ok) throw new Error(String(asked.error));
643 expect(
644 (await tool(botToken, "close", { repo: "alice/game", number: asked.value.number, reason: "dropped" })).error,
645 ).toContain("a person's ask stands in");
646 // Split into an issue that is not newer than the hand-over.
647 expect(
648 (await tool(botToken, "close", { repo: "alice/game", number: asked.value.number, reason: "split", into: [noNote.number] })).error,
649 ).toContain("opened after ");
650 // A closed issue is not the planner's to close again.
651 expect(
652 (await tool(botToken, "close", { repo: "alice/game", number: own.number })).error,
653 ).toContain("any other close is not the planner's");
654 // Nor does an agent reopen.
655 expect((await tool(botToken, "close", { repo: "alice/game", number: own.number, state: "open" })).error).toContain(
656 "forbidden",
657 );
658
659 // A person reopens it; closing defaults to done.
660 const reopened = await tool(rw, "close", { repo: "alice/game", number: own.number, state: "open" });
661 expect(reopened.value).toMatchObject({ state: "open", closeReason: null });
662 const closed = await tool(rw, "close", { repo: "alice/game", number: own.number });
663 expect(closed.value).toMatchObject({ state: "closed", closeReason: "done" });
664
665 // The boundary: bad words are refused before the action.
666 expect((await tool(rw, "close", { repo: "alice/game", number: own.number, state: "x" })).error).toContain("invalid_state");
667 expect((await tool(rw, "close", { repo: "alice/game", number: own.number, reason: "x" })).error).toContain("invalid_reason");
668 expect((await tool(rw, "close", { repo: "alice/game", number: own.number, into: [0] })).error).toContain("invalid_reason");
669 expect((await tool(ro, "close", { repo: "alice/game", number: own.number })).error).toContain(READ_ONLY_REFUSAL);
670 });
671
672 test("issue reads body, comments, labels and what it waits for; a sealed one is not found; a reader is marked untrusted", async () => {
673 const mk = (title: string, body = "", sealed = false) => {
674 const r = createIssue(app.db, { repoId: game.id, authorId: alice.id, title, body, sealed });
675 if (!r.ok) throw new Error(String(r.error));
676 return r.value;
677 };
678 const waiting = mk("wait for it", "the body");
679 const first = mk("first");
680 expect(addDependency(app.db, waiting, first, alice.id).ok).toBe(true);
681 const bot = await createAgent(app, alice, { username: "issuebot", brief: "x" });
682 if (!bot.ok) throw new Error(String(bot.error));
683 expect(addToCrew(app, alice, game, "issuebot").ok).toBe(true);
684 addComment(app.db, { issueId: waiting.id, authorId: alice.id, body: "one" });
685 addComment(app.db, { issueId: waiting.id, authorId: bot.value.user.id, body: "two" });
686
687 const read = (await tool(rw, "issue", { repo: "alice/game", number: waiting.number })).value;
688 expect(read).toMatchObject({
689 number: waiting.number,
690 title: "wait for it",
691 state: "open",
692 closeReason: null,
693 body: "the body",
694 labels: [],
695 assignee: null,
696 blockedBy: [{ number: first.number, title: "first", state: "open" }],
697 blocks: [],
698 });
699 // The sentence and the chain the page draws (#13641).
700 expect(read.standing).toMatchObject({
701 line: `Waits for #${first.number} (queued).`,
702 ready: false,
703 before: [[{ number: first.number, badge: "queued", holding: true }]],
704 after: [],
705 more: 0,
706 });
707 expect(read.comments.map((c: any) => [c.author, c.authorIsAgent, c.body])).toEqual([
708 ["alice", false, "one"],
709 ["issuebot", true, "two"],
710 ]);
711 expect(read.comments[0].at).toBeString();
712 expect(read.untrusted).toBeUndefined();
713 const other = (await tool(rw, "issue", { repo: "alice/game", number: first.number })).value;
714 expect(other.blocks.map((b: any) => b.number)).toEqual([waiting.number]);
715
716 // Not found: no such number, and a pull's number is not an issue's.
717 expect((await tool(rw, "issue", { repo: "alice/game", number: 9999 })).error).toContain("not_found");
718 const branched = await commitToBranch(app, alice, game, {
719 branch: "issue-kind",
720 message: "a change",
721 files: [{ path: "kind.txt", content: "k\n" }],
722 });
723 if (!branched.ok) throw new Error(JSON.stringify(branched.error));
724 const opened = await openPull(app, alice, game, {
725 title: "Not an issue",
726 baseBranch: "main",
727 headBranch: "issue-kind",
728 });
729 if (!opened.ok) throw new Error(String(opened.error));
730 expect((await tool(rw, "issue", { repo: "alice/game", number: opened.value.number })).value).toEqual({ kind: "pull", tool: "pull" });
731 // Through MCP the card is built from the answer's repo; a pull's number has none.
732 const viaPull = await call(rw, "tools/call", { name: "issue", arguments: { repo: "alice/game", number: opened.value.number } });
733 expect(viaPull.body.result.structuredContent).toBeUndefined();
734 const viaIssue = await call(rw, "tools/call", { name: "issue", arguments: { repo: "alice/game", number: waiting.number } });
735 const card = viaIssue.body.result.structuredContent.card;
736 expect(card.kind).toBe("issue");
737 expect(card.rows[0].link).toMatch(/^https?:\/\/.+\/alice\/game\/issues\/\d+$/);
738 expect(card.rows[0].link.endsWith(`/alice/game/issues/${waiting.number}`)).toBe(true);
739 expect(card.rows.find((r: any) => r.label === "Waits for").link.endsWith(`/alice/game/issues/${first.number}`)).toBe(true);
740
741 // Sealed: the writer reads it; a reader of a public repo is told not found.
742 const pub = await createRepo(app, alice, { name: "sealedpub", visibility: "public" });
743 if (!pub.ok) throw new Error(String(pub.error));
744 const secret = createIssue(app.db, { repoId: pub.value.id, authorId: alice.id, title: "hole", sealed: true });
745 if (!secret.ok) throw new Error(String(secret.error));
746 const open = createIssue(app.db, { repoId: pub.value.id, authorId: alice.id, title: "visible" });
747 if (!open.ok) throw new Error(String(open.error));
748 expect((await tool(rw, "issue", { repo: "alice/sealedpub", number: secret.value.number })).value.title).toBe("hole");
749 expect((await tool(bobRw, "issue", { repo: "alice/sealedpub", number: secret.value.number })).error).toContain("not_found");
750
751 // A public issue waiting on the sealed one: the reader must not learn its title.
752 expect(addDependency(app.db, open.value, secret.value, alice.id).ok).toBe(true);
753 expect((await tool(bobRw, "issue", { repo: "alice/sealedpub", number: open.value.number })).value.blockedBy).toEqual([]);
754 const waits = (await tool(rw, "issue", { repo: "alice/sealedpub", number: open.value.number })).value.blockedBy;
755 expect(waits).toHaveLength(1);
756 expect(waits[0]).toMatchObject({ number: secret.value.number, title: "hole" });
757 expect((await tool(bobRw, "issue", { repo: "alice/sealedpub", number: open.value.number })).value.blockedBy).not.toContainEqual(expect.objectContaining({ title: "hole" }));
758
759 // Untrusted: bob cannot write alice/sealedpub; a crew agent is told so.
760 addComment(app.db, { issueId: open.value.id, authorId: bob.id, body: "from a reader" });
761 addComment(app.db, { issueId: open.value.id, authorId: alice.id, body: "from the owner" });
762 expect(addToCrew(app, alice, pub.value, "issuebot").ok).toBe(true);
763 const botToken = createToken(app.db, bot.value.user.id, "bot", "ro").token;
764 const marked = (await tool(botToken, "issue", { repo: "alice/sealedpub", number: open.value.number })).value;
765 expect(marked.comments.map((c: any) => c.untrusted)).toEqual([true, undefined]);
766 expect(marked.untrusted).toBeUndefined();
767
768 // An issue a reader filed is marked itself, for the crew agent and not for the owner.
769 const theirs = createIssue(app.db, { repoId: pub.value.id, authorId: bob.id, title: "from bob" });
770 if (!theirs.ok) throw new Error(String(theirs.error));
771 expect((await tool(botToken, "issue", { repo: "alice/sealedpub", number: theirs.value.number })).value.untrusted).toBe(true);
772 expect((await tool(rw, "issue", { repo: "alice/sealedpub", number: theirs.value.number })).value.untrusted).toBeUndefined();
773 });
774
775 test("following, take_updates and converge are the fork's page", async () => {
776 const pub = await createRepo(app, alice, {
777 name: "open",
778 visibility: "public",
779 });
780 if (!pub.ok) throw new Error(String(pub.error));
781 await commitToBranch(app, alice, pub.value, {
782 message: "seed",
783 files: [{ path: "README.md", content: "# open\n" }],
784 });
785 const forked = await forkRepo(app, bob, pub.value);
786 if (!forked.ok) throw new Error(String(forked.error));
787 const fresh = (r: Repo) => getRepoById(app.db, r.id)!;
788
789 expect(
790 (await tool(bobRw, "following", { repo: "alice/open" })).error,
791 ).toContain("not_a_fork");
792 expect(
793 (await tool(bobRw, "following", { repo: "bob/open" })).value.state,
794 ).toBe("synced");
795 // Both sides change the same file: a decision, so not git's to take.
796 await commitToBranch(app, bob, fresh(forked.value), {
797 message: "bob",
798 files: [{ path: "README.md", content: "# open, by bob\n" }],
799 });
800 await commitToBranch(app, alice, fresh(pub.value), {
801 message: "alice",
802 files: [{ path: "README.md", content: "# open, by alice\n" }],
803 });
804 const stands = await tool(bobRw, "following", { repo: "bob/open" });
805 expect(stands.value.state).toBe("diverged");
806 expect(stands.value.conflicts).toEqual(["README.md"]);
807 expect(
808 (await tool(bobRw, "take_updates", { repo: "bob/open" })).error,
809 ).toContain("conflict");
810 // Alice reads bob's public fork and may not move it.
811 expect(
812 (await tool(ro, "following", { repo: "bob/open" })).value.state,
813 ).toBe("diverged");
814 const carol = await createUser(app.db, { origin: "seed", trusted: true,
815 username: "carol",
816 email: "[email protected]",
817 password: "a-good-passphrase",
818 });
819 if (!carol.ok) throw new Error(carol.error);
820 const carolRw = createToken(app.db, carol.value.id, "rw", "rw").token;
821 expect(
822 (await tool(carolRw, "take_updates", { repo: "bob/open" })).error,
823 ).toContain("write access");
824 expect(
825 (await tool(bobRw, "converge", { repo: "bob/open" })).value.kind,
826 ).toBe("no_crew");
827 });
828
829 test("probe only reads, yet needs the access the page needs", async () => {
830 const listed = await listCall(ro);
831 const hints = Object.fromEntries(
832 listed.body.result.tools.map((t: any) => [
833 t.name,
834 t.annotations?.readOnlyHint ?? false,
835 ]),
836 );
837 expect(hints["probe"]).toBe(true);
838 expect(hints["stop"]).toBe(false);
839 // A repo the token may read, with nothing to compare with: it gets as far
840 // as the app and its contract, read token or not.
841 for (const token of [rw, ro])
842 expect(
843 (await tool(token, "probe", { repo: "alice/game" })).error,
844 ).toMatch(/not_an_app|no_contract/);
845 // One it may not read is no such repository.
846 expect(
847 (await tool(bobRw, "probe", { repo: "alice/game" })).error,
848 ).toContain("not_found");
849 expect(
850 (await tool(rw, "probe", { repo: "alice/nothing" })).error,
851 ).toContain("not_found");
852 });
853
854 test("pull carries the base tip its check was merged with (#1810)", async () => {
855 const branched = await commitToBranch(app, alice, game, {
856 branch: "feat",
857 message: "a change",
858 files: [{ path: "b.txt", content: "b\n" }],
859 });
860 if (!branched.ok) throw new Error(JSON.stringify(branched.error));
861 const opened = await openPull(app, alice, game, {
862 title: "Change",
863 baseBranch: "main",
864 headBranch: "feat",
865 });
866 if (!opened.ok) throw new Error(String(opened.error));
867 const pull = opened.value;
868 expect((await tool(ro, "pull", { repo: "alice/game", number: pull.number })).value.check).toEqual({ state: "none", baseOid: "" });
869 const run = createRun(app.db, {
870 repoId: game.id,
871 kind: "check",
872 issueId: pull.id,
873 env: `pull-${pull.number}`,
874 commitOid: branched.value.commitOid,
875 });
876 setRunBase(app.db, run.id, "abc1234abc1234abc1234abc1234abc1234abc12");
877 const read = await tool(ro, "pull", { repo: "alice/game", number: pull.number });
878 expect(read.value.check.baseOid).toBe("abc1234abc1234abc1234abc1234abc1234abc12");
879 // That base is not main's tip: the green is from an older main.
880 expect(read.value.checkStale).toBe(true);
881 const tip = await resolveOid(
882 await pullDir(app.db, app.reposRoot, game, pull),
883 "refs/heads/main",
884 );
885 setRunBase(app.db, run.id, tip ?? "");
886 expect(
887 (await tool(ro, "pull", { repo: "alice/game", number: pull.number })).value.checkStale,
888 ).toBe(false);
889 });
890
891 test("pull says checkStale in the MCP and the API when its check was on an older base (#2237)", async () => {
892 const branched = await commitToBranch(app, alice, game, {
893 branch: "stale-feat",
894 message: "another change",
895 files: [{ path: "c.txt", content: "c\n" }],
896 });
897 if (!branched.ok) throw new Error(JSON.stringify(branched.error));
898 const opened = await openPull(app, alice, game, {
899 title: "Stale",
900 baseBranch: "main",
901 headBranch: "stale-feat",
902 });
903 if (!opened.ok) throw new Error(String(opened.error));
904 const pull = opened.value;
905 const viaApi = async () =>
906 (await (
907 await fetch(`${base}/api/v1/repos/alice/game/pulls/${pull.number}`, {
908 headers: { authorization: `Bearer ${ro}` },
909 })
910 ).json()) as any;
911 const viaMcp = async () =>
912 (await tool(ro, "pull", { repo: "alice/game", number: pull.number })).value;
913 // No check, or one that recorded no base: not stale.
914 expect((await viaMcp()).checkStale).toBe(false);
915 expect((await viaApi()).checkStale).toBe(false);
916 const run = createRun(app.db, {
917 repoId: game.id,
918 kind: "check",
919 issueId: pull.id,
920 env: `pull-${pull.number}`,
921 commitOid: branched.value.commitOid,
922 });
923 expect((await viaMcp()).checkStale).toBe(false);
924 // Checked on the base's tip: not stale.
925 const tip: string = (await viaApi()).status.baseOid;
926 setRunBase(app.db, run.id, tip);
927 expect((await viaMcp()).checkStale).toBe(false);
928 expect((await viaApi()).checkStale).toBe(false);
929 // The base moves on: the green is from an older main.
930 const moved = await commitToBranch(app, alice, game, {
931 message: "main moves",
932 files: [{ path: "d.txt", content: "d\n" }],
933 });
934 if (!moved.ok) throw new Error(JSON.stringify(moved.error));
935 expect((await viaMcp()).checkStale).toBe(true);
936 expect((await viaApi()).checkStale).toBe(true);
937 // A new check on the new tip is current again.
938 setRunBase(app.db, run.id, moved.value.commitOid);
939 expect((await viaMcp()).checkStale).toBe(false);
940 expect((await viaApi()).checkStale).toBe(false);
941 // Stale again, then closed: a pull that cannot land reads false, not noise.
942 setRunBase(app.db, run.id, tip);
943 expect((await viaApi()).checkStale).toBe(true);
944 app.db.run("UPDATE issue SET state = 'closed' WHERE id = ?", [pull.id]);
945 expect((await viaMcp()).checkStale).toBe(false);
946 expect((await viaApi()).checkStale).toBe(false);
947 });
948
949 test("stop takes a run id from now, and refuses a stale or foreign one", async () => {
950 const run = createRun(app.db, {
951 repoId: game.id,
952 kind: "agent",
953 actorId: alice.id,
954 reason: "assigned",
955 });
956 expect(
957 (await tool(ro, "stop", { repo: "alice/game", run: run.id })).error,
958 ).toContain("forbidden");
959 expect(
960 (await tool(bobRw, "stop", { repo: "alice/game", run: run.id })).error,
961 ).toContain("not_found");
962 expect(
963 (await tool(rw, "stop", { repo: "alice/game", run: "nosuchrun" })).error,
964 ).toContain("not_found");
965 const stopped = await tool(rw, "stop", { repo: "alice/game", run: run.id });
966 expect(stopped.value.says).toBe(`Stopped run ${run.id}.`);
967 const stale = await tool(rw, "stop", { repo: "alice/game", run: run.id });
968 expect(stale.error).toContain("finished");
969 expect(stale.error).toContain("already ended");
970 });
971
972 test("map and wait_for are the plan's own actions", async () => {
973 const a = (await tool(rw, "tell", { repo: "alice/game", text: "first" }))
974 .value.issue;
975 const b = (await tool(rw, "tell", { repo: "alice/game", text: "second" }))
976 .value.issue;
977 const listed = await listCall(rw);
978 const hints = Object.fromEntries(
979 listed.body.result.tools.map((t: any) => [
980 t.name,
981 t.annotations?.readOnlyHint ?? false,
982 ]),
983 );
984 // map writes only when given `first`, so it spells no read-only hint.
985 expect([hints.map, hints.wait_for]).toEqual([false, false]);
986
987 expect(
988 (await tool(rw, "wait_for", { app: "alice/game", issue: b, blockedBy: a }))
989 .value.says,
990 ).toBe(`#${b} waits for #${a}.`);
991 const map = (await tool(ro, "map", { app: "alice/game" })).value;
992 expect(map.ready.map((i: any) => i.number)).toContain(a);
993 expect(map.blockedOn.map((i: any) => i.number)).toContain(a);
994 expect(map.issues.find((i: any) => i.number === b).word).toBe("blocked");
995 expect(map.edges).toContainEqual({ issue: b, blockedBy: a });
996
997 // The API's words, for a loop, a stranger issue, and a read token.
998 expect(
999 (await tool(rw, "wait_for", { app: "alice/game", issue: a, blockedBy: b }))
1000 .error,
1001 ).toStartWith("cycle: that would make a loop");
1002 expect(
1003 (await tool(rw, "wait_for", { app: "alice/game", issue: a, blockedBy: 999 }))
1004 .error,
1005 ).toStartWith("no_such_issue: no issue #999");
1006 expect(
1007 (await tool(ro, "wait_for", { app: "alice/game", issue: a, blockedBy: b }))
1008 .error,
1009 ).toContain("forbidden");
1010 // A private app is no such app to someone who cannot read it.
1011 expect((await tool(bobRw, "map", { app: "alice/game" })).error).toContain(
1012 "not_found",
1013 );
1014 expect(
1015 (await tool(bobRw, "wait_for", { app: "alice/game", issue: b, blockedBy: a }))
1016 .error,
1017 ).toContain("not_found");
1018
1019 await tool(rw, "wait_for", { app: "alice/game", issue: b, blockedBy: a, stop: true });
1020 const after = (await tool(ro, "map", { app: "alice/game" })).value;
1021 expect(after.edges).not.toContainEqual({ issue: b, blockedBy: a });
1022 expect(after.ready.map((i: any) => i.number)).toContain(b);
1023 }, 30_000);
1024
1025 test("with plans need a nod on, the plan tool stores one proposal and opens nothing", async () => {
1026 updateRepoSettings(app.db, getRepoById(app.db, game.id)!, { plansNeedNod: true });
1027 const count = async () =>
1028 (await tool(ro, "map", { app: "alice/game" })).value.issues.length;
1029 const before = await count();
1030 const issues = [
1031 { key: "a", title: "First" },
1032 { key: "b", title: "Second", blockedBy: ["a"] },
1033 ];
1034 const done = await tool(rw, "plan", {
1035 app: "alice/game",
1036 title: "Two steps",
1037 why: "worth a look",
1038 issues,
1039 });
1040 expect(done.value.status).toBe("proposed");
1041 const row = app.db
1042 .query<{ title: string; why: string; issues: string }, [string]>(
1043 "SELECT title, why, issues FROM plan_proposal WHERE id = ?1",
1044 )
1045 .get(done.value.id)!;
1046 expect(row.title).toBe("Two steps");
1047 expect(JSON.parse(row.issues).map((i: any) => i.key)).toEqual(["a", "b"]);
1048 expect(await count()).toBe(before);
1049 // The checks run as ever: a loop is refused and stores nothing.
1050 const loop = await tool(rw, "plan", {
1051 app: "alice/game",
1052 issues: [{ key: "x", title: "X", blockedBy: ["x"] }],
1053 });
1054 expect(loop.error).toContain("self");
1055 });
1056
1057 test("plan opens linked issues all or none", async () => {
1058 updateRepoSettings(app.db, getRepoById(app.db, game.id)!, { plansNeedNod: false });
1059 const issues = [
1060 { key: "a", title: "First" },
1061 { key: "b", title: "Second", body: "two" },
1062 { key: "c", title: "Third", blockedBy: ["a", "b"] },
1063 ];
1064 const done = (await tool(rw, "plan", { app: "alice/game", issues })).value;
1065 const n = Object.fromEntries(
1066 done.opened.map((o: any) => [o.key, o.number]),
1067 );
1068 expect(done.ready).toEqual(expect.arrayContaining([n.a, n.b]));
1069 expect(done.ready).not.toContain(n.c);
1070 const map = (await tool(ro, "map", { app: "alice/game" })).value;
1071 expect(map.edges).toContainEqual({ issue: n.c, blockedBy: n.a });
1072 expect(map.edges).toContainEqual({ issue: n.c, blockedBy: n.b });
1073
1074 const count = async () =>
1075 (await tool(ro, "map", { app: "alice/game" })).value.issues.length;
1076 const before = await count();
1077 const loop = await tool(rw, "plan", {
1078 app: "alice/game",
1079 issues: [
1080 { key: "x", title: "X", blockedBy: ["y"] },
1081 { key: "y", title: "Y", blockedBy: ["x"] },
1082 ],
1083 });
1084 expect(loop.error).toContain("cycle");
1085 const unknown = await tool(rw, "plan", {
1086 app: "alice/game",
1087 issues: [{ key: "x", title: "X", blockedBy: ["nope"] }],
1088 });
1089 expect(unknown.error).toContain('"nope"');
1090 const many = await tool(rw, "plan", {
1091 app: "alice/game",
1092 issues: Array.from({ length: 13 }, (_, i) => ({
1093 key: `k${i}`,
1094 title: "t",
1095 })),
1096 });
1097 expect(many.error).toContain("too_many");
1098 expect(await count()).toBe(before);
1099
1100 expect(
1101 (await tool(ro, "plan", { app: "alice/game", issues })).error,
1102 ).toContain("forbidden");
1103 });
1104
1105 test("a browser session is not a way in, even signed in", async () => {
1106 const signin = await fetch(`${base}/signin`, {
1107 method: "POST",
1108 redirect: "manual",
1109 headers: {
1110 "content-type": "application/x-www-form-urlencoded",
1111 origin: base,
1112 },
1113 body: new URLSearchParams({
1114 username: "alice",
1115 password: "a-good-passphrase",
1116 }),
1117 });
1118 const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
1119 expect(cookie).toContain("=");
1120 const res = await fetch(`${base}/mcp`, {
1121 method: "POST",
1122 headers: { "content-type": "application/json", cookie, origin: base },
1123 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "resources/list" }),
1124 });
1125 expect(res.status).toBe(401);
1126 });
1127 test("a signed-in cookie caller is a stranger: the five token-free tools, never the full list", async () => {
1128 const signin = await fetch(`${base}/signin`, {
1129 method: "POST",
1130 redirect: "manual",
1131 headers: { "content-type": "application/x-www-form-urlencoded", origin: base },
1132 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
1133 });
1134 const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
1135 const res = await fetch(`${base}/mcp`, {
1136 method: "POST",
1137 headers: { "content-type": "application/json", cookie, origin: base },
1138 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }),
1139 });
1140 expect(res.status).toBe(200);
1141 const names = ((await res.json()) as any).result.tools.map((t: { name: string }) => t.name).sort();
1142 expect(names).toEqual([...TOKEN_FREE_TOOLS].sort());
1143 });
1144 test("limits: admins only, dry by default, an admin-scope token to change", async () => {
1145 const key = "front.pinned_max";
1146 const admin = createToken(app.db, alice.id, "admin", "admin").token;
1147 // A non-admin and an agent (even one marked admin) are told nothing.
1148 expect((await tool(bobRw, "limits")).error).toContain("no such tool");
1149 const made = await createAgent(app, alice, { username: "limitbot", brief: "x" });
1150 if (!made.ok) throw new Error(String(made.error));
1151 app.db.query("UPDATE user SET is_admin = 1 WHERE id = ?1").run(made.value.user.id);
1152 const botToken = createToken(app.db, made.value.user.id, "bot", "admin").token;
1153 expect((await tool(botToken, "limits")).error).toContain("no such tool");
1154
1155 const before = limitValue(app.db, key);
1156 const listed = await tool(ro, "limits");
1157 expect(listed.value.limits.map((l: any) => l.key)).toContain(key);
1158
1159 // The default is a dry run: nothing changes, even with an admin token.
1160 const dry = await tool(admin, "limits", { key, value: "13" });
1161 expect(dry.value.says).toContain("Would set");
1162 expect(limitValue(app.db, key)).toBe(before);
1163
1164 // Writing needs the admin scope.
1165 const refused = await tool(ro, "limits", { key, value: "13", dryRun: false });
1166 expect(refused.error).toContain("forbidden");
1167 expect(limitValue(app.db, key)).toBe(before);
1168
1169 const done = await tool(admin, "limits", { key, value: "13", dryRun: false });
1170 expect(done.value).toMatchObject({ key, from: before, to: 13 });
1171 expect(limitValue(app.db, key)).toBe(13);
1172 expect(limitChanges(app.db)[0]).toMatchObject({ key });
1173 });
1174
1175 test("egress_grants: list, grant and revoke for a site admin; a non-admin is refused as the API refuses", async () => {
1176 const dest = "100.89.95.68:8101";
1177 const committed = await commitToBranch(app, alice, game, {
1178 message: "Ask for the arm",
1179 files: [{ path: "forge.json", content: JSON.stringify({ app: { run: "bun run src/server.ts" }, egress: [dest] }) }],
1180 });
1181 if (!committed.ok) throw new Error(JSON.stringify(committed.error));
1182 const admin = createToken(app.db, alice.id, "admin", "admin").token;
1183 const bobAdmin = createToken(app.db, bob.id, "bobadmin", "admin").token;
1184 const repo = "alice/game";
1185
1186 const listed = await tool(admin, "egress_grants", { repo });
1187 expect(listed.value.items).toEqual([
1188 { destination: dest, asked: true, granted: false, grantedBy: null, grantedAt: null },
1189 ]);
1190
1191 // Bob is no admin of the repository: told nothing of it.
1192 expect((await tool(bobAdmin, "egress_grants", { repo })).error).toContain("not_found");
1193 // A token below admin scope may not read or change.
1194 expect((await tool(ro, "egress_grants", { repo })).error).toContain("forbidden");
1195 expect((await tool(rw, "egress_grants", { repo, op: "grant", destination: dest })).error).toContain("forbidden");
1196
1197 const granted = await tool(admin, "egress_grants", { repo, op: "grant", destination: dest });
1198 expect(granted.value).toMatchObject({ destination: dest, granted: true, grantedBy: "alice" });
1199 expect((await tool(admin, "egress_grants", { repo, op: "grant", destination: "10.0.0.1:1" })).error).toContain("not_asked");
1200
1201 // The same words the API gives a repository admin who is no site admin.
1202 const arm = await createRepo(app, bob, { name: "arm", visibility: "public", description: "" });
1203 if (!arm.ok) throw new Error(String(arm.error));
1204 await commitToBranch(app, bob, arm.value, {
1205 message: "Ask for the arm",
1206 files: [{ path: "forge.json", content: JSON.stringify({ app: { run: "bun run src/server.ts" }, egress: [dest] }) }],
1207 });
1208 const refused = await tool(bobAdmin, "egress_grants", { repo: "bob/arm", op: "grant", destination: dest });
1209 const api = await fetch(`${base}/api/v1/repos/bob/arm/egress-grants`, {
1210 method: "POST",
1211 headers: { authorization: `Bearer ${bobAdmin}`, "content-type": "application/json" },
1212 body: JSON.stringify({ destination: dest }),
1213 });
1214 expect(api.status).toBe(403);
1215 expect(refused.error).toStartWith(`forbidden: ${((await api.json()) as any).message}`);
1216
1217 // An agent, even one marked site admin, may not change a grant.
1218 const bot = await createAgent(app, alice, { username: "egressbot", brief: "x" });
1219 if (!bot.ok) throw new Error(String(bot.error));
1220 app.db.query("UPDATE user SET is_admin = 1 WHERE id = ?1").run(bot.value.user.id);
1221 const botToken = createToken(app.db, bot.value.user.id, "bot", "admin").token;
1222 const botGrant = await tool(botToken, "egress_grants", { repo: "bob/arm", op: "grant", destination: dest });
1223 expect(botGrant.error).toContain("forbidden");
1224
1225 const revoked = await tool(admin, "egress_grants", { repo, op: "revoke", destination: dest });
1226 expect(revoked.value).toEqual({ revoked: dest });
1227 expect((await tool(admin, "egress_grants", { repo, op: "revoke", destination: dest })).error).toContain("no_such_grant");
1228 expect((await tool(admin, "egress_grants", { repo })).value.items[0].granted).toBe(false);
1229 });
1230
1231 test("board_pins: list, pin, move, unpin for an admin person; an agent and a non-admin are refused", async () => {
1232 const board = { title: "Pinnable", range: "24h", refresh: "off", panels: [
1233 { title: "One", chart: "number", query: { source: "runs", aggregate: "count" }, w: 1, h: 1 },
1234 { title: "Two", chart: "number", query: { source: "runs", aggregate: "count" }, w: 1, h: 1 },
1235 ] };
1236 expect((await tool(rw, "board_write", { slug: "pinnable", board })).value).toMatchObject({ slug: "pinnable" });
1237 const titles = async () => (await tool(rw, "board_pins")).value.pins.map((p: any) => p.title);
1238 expect(await titles()).toEqual([]);
1239 expect((await tool(rw, "board_pins", { op: "pin", slug: "pinnable", title: "One" })).value).toMatchObject({ slug: "pinnable", title: "One" });
1240 await tool(rw, "board_pins", { op: "pin", slug: "pinnable", title: "Two" });
1241 expect(await titles()).toEqual(["One", "Two"]);
1242 await tool(rw, "board_pins", { op: "move", slug: "pinnable", title: "Two", by: -1 });
1243 expect(await titles()).toEqual(["Two", "One"]);
1244 expect((await tool(rw, "board_pins", { op: "move", slug: "pinnable", title: "Nope", by: 1 })).error).toContain("not_found");
1245 expect((await tool(rw, "board_pins", { op: "pin", slug: "pinnable", title: "Nope" })).error).toContain("not_found");
1246 await tool(rw, "board_pins", { op: "unpin", slug: "pinnable", title: "One" });
1247 expect(await titles()).toEqual(["Two"]);
1248 await tool(rw, "board_pins", { op: "unpin", slug: "pinnable", title: "Two" });
1249 expect(await titles()).toEqual([]);
1250
1251 const made = await createAgent(app, alice, { username: "pinbot", brief: "x" });
1252 if (!made.ok) throw new Error(String(made.error));
1253 app.db.query("UPDATE user SET is_admin = 1 WHERE id = ?1").run(made.value.user.id);
1254 const botToken = createToken(app.db, made.value.user.id, "bot", "rw").token;
1255 for (const who of [bobRw, botToken]) {
1256 expect((await tool(who, "board_pins")).error).toContain("forbidden");
1257 expect((await tool(who, "board_pins", { op: "pin", slug: "pinnable", title: "One" })).error).toContain("forbidden");
1258 }
1259 expect(await titles()).toEqual([]);
1260 await tool(rw, "board_delete", { slug: "pinnable" });
1261 });
1262
1263 test("boards: list, read, write and delete for an admin person; an agent and a non-admin are refused", async () => {
1264 const board = { title: "Runs", range: "24h", refresh: "off", panels: [{ title: "Failed", chart: "number", query: { source: "runs", aggregate: "count" }, w: 1, h: 1 }] };
1265 const made = await createAgent(app, alice, { username: "boardbot", brief: "x" });
1266 if (!made.ok) throw new Error(String(made.error));
1267 app.db.query("UPDATE user SET is_admin = 1 WHERE id = ?1").run(made.value.user.id);
1268 const botToken = createToken(app.db, made.value.user.id, "bot", "rw").token;
1269 for (const who of [bobRw, botToken]) {
1270 expect((await tool(who, "boards")).error).toContain("forbidden");
1271 expect((await tool(who, "board_write", { slug: "runs", board })).error).toContain("forbidden");
1272 expect((await tool(who, "board_delete", { slug: "runs" })).error).toContain("forbidden");
1273 }
1274
1275 // A read-only token may not write.
1276 expect((await tool(ro, "board_write", { slug: "runs", board })).error).toContain("forbidden");
1277 expect((await tool(rw, "boards")).value.boards).toEqual([]);
1278
1279 const wrote = await tool(rw, "board_write", { slug: "runs", board });
1280 expect(wrote.value).toMatchObject({ slug: "runs", title: "Runs" });
1281 expect((await tool(rw, "boards")).value.boards.map((b: any) => b.slug)).toEqual(["runs"]);
1282 expect((await tool(ro, "boards", { slug: "runs" })).value.panels[0].title).toBe("Failed");
1283 expect((await tool(rw, "boards", { slug: "nope" })).error).toContain("not_found");
1284
1285 // A panel that cannot run, or a board that does not validate, is refused.
1286 const broken = { ...board, panels: [{ ...board.panels[0], query: { source: "nothing" } }] };
1287 expect((await tool(rw, "board_write", { slug: "broken", board: broken })).error).toContain("refused");
1288 expect((await tool(rw, "board_write", { slug: "Bad Slug", board })).error).toContain("invalid");
1289
1290 expect((await tool(ro, "board_delete", { slug: "runs" })).error).toContain("forbidden");
1291 expect((await tool(rw, "board_delete", { slug: "runs" })).value).toEqual({ deleted: "runs" });
1292 expect((await tool(rw, "boards")).value.boards).toEqual([]);
1293 expect((await tool(rw, "board_delete", { slug: "runs" })).error).toContain("not_found");
1294 });
1295
1296 test("boards with a panel: its data through panelData, the window judged; an agent and a non-admin are refused", async () => {
1297 const query = { source: "runs", aggregate: "count", groupBy: { bucket: "hour" } };
1298 const board = { title: "Hourly", range: "7d", refresh: "off", panels: [{ title: "Runs", chart: "line", query, w: 1, h: 1 }] };
1299 expect((await tool(rw, "board_write", { slug: "hourly", board })).value).toMatchObject({ slug: "hourly" });
1300 const from = "2026-01-01T00:00:00.000Z";
1301 const to = "2027-01-01T00:00:00.000Z";
1302 const got = (await tool(ro, "boards", { slug: "hourly", panel: 0, from, to, step: "1d" })).value;
1303 const shown = await showBoard(app, alice, "hourly");
1304 if (!shown.ok) throw new Error("no board");
1305 const direct = panelData(app.db, shown.value, shown.value.panels[0]!, { from, to, step: 86_400 });
1306 if (!direct.ok) throw new Error(direct.error);
1307 expect(got).toEqual({ board: "hourly", panel: 0, title: "Runs", chart: "line", from, to, step: 86_400, rows: direct.rows });
1308 expect((await tool(rw, "boards", { slug: "hourly", panel: 0, step: 300 })).value.step).toBe(300);
1309 expect((await tool(rw, "boards", { slug: "hourly", panel: 0 })).value.step).toBe(3600);
1310 expect((await tool(rw, "boards", { slug: "hourly", panel: 0, step: "5x" })).error).toContain("invalid_window");
1311 expect((await tool(rw, "boards", { slug: "hourly", panel: 0, from: "soon" })).error).toContain("invalid_window");
1312 expect((await tool(rw, "boards", { slug: "hourly", panel: 1 })).error).toContain("not_found");
1313 expect((await tool(rw, "boards", { slug: "nope", panel: 0 })).error).toContain("not_found");
1314 const made = await createAgent(app, alice, { username: "databot", brief: "x" });
1315 if (!made.ok) throw new Error(String(made.error));
1316 app.db.query("UPDATE user SET is_admin = 1 WHERE id = ?1").run(made.value.user.id);
1317 const botToken = createToken(app.db, made.value.user.id, "bot", "rw").token;
1318 for (const who of [bobRw, botToken]) {
1319 expect((await tool(who, "boards", { slug: "hourly", panel: 0 })).error).toContain("forbidden");
1320 }
1321 await tool(rw, "board_delete", { slug: "hourly" });
1322 });
1323
1324 test("ui:// card resources are listed, read, and tied to their tools", async () => {
1325 const list = await call(rw, "resources/list");
1326 const uris = list.body.result.resources.map((r: any) => r.uri).sort();
1327 expect(uris).toEqual([
1328 "ui://forge/app",
1329 "ui://forge/asked",
1330 "ui://forge/asks",
1331 "ui://forge/board",
1332 "ui://forge/capacity",
1333 "ui://forge/crew",
1334 "ui://forge/drill",
1335 "ui://forge/explore",
1336 "ui://forge/feed",
1337 "ui://forge/flow",
1338 "ui://forge/forge",
1339 "ui://forge/forges",
1340 "ui://forge/forks",
1341 "ui://forge/health",
1342 "ui://forge/held",
1343 "ui://forge/issue",
1344 "ui://forge/issues",
1345 "ui://forge/map",
1346 "ui://forge/milestones",
1347 "ui://forge/pull",
1348 "ui://forge/pulls",
1349 "ui://forge/release",
1350 "ui://forge/releases",
1351 "ui://forge/reports",
1352 "ui://forge/run",
1353 "ui://forge/runs",
1354 "ui://forge/scorecard",
1355 "ui://forge/search",
1356 "ui://forge/usage",
1357 "ui://forge/wave",
1358 ]);
1359 const read = await call(rw, "resources/read", { uri: "ui://forge/app" });
1360 const c = read.body.result.contents[0];
1361 expect(c.mimeType).toBe("text/html;profile=mcp-app");
1362 expect(c.text).toContain("ui/notifications/tool-result");
1363 expect(c.text).not.toContain("innerHTML");
1364 const nope = await call(rw, "resources/read", { uri: "ui://forge/nope" });
1365 expect(nope.body.error.code).toBe(-32002);
1366 const tools = (await listCall(rw)).body.result.tools;
1367 const meta = (n: string) => tools.find((t: any) => t.name === n)._meta?.ui?.resourceUri;
1368 expect(meta("apps")).toBe("ui://forge/app");
1369 expect(meta("new_app")).toBe("ui://forge/app");
1370 expect(meta("now")).toBe("ui://forge/crew");
1371 expect(meta("asks")).toBe("ui://forge/asks");
1372 expect(meta("milestones")).toBe("ui://forge/milestones");
1373 expect(meta("asks_act")).toBe("ui://forge/asks");
1374 expect(meta("map")).toBe("ui://forge/map");
1375 expect(meta("boards")).toBe("ui://forge/board");
1376 expect(meta("feed")).toBe("ui://forge/feed");
1377 expect(meta("issue")).toBe("ui://forge/issue");
1378 expect(meta("explore")).toBe("ui://forge/explore");
1379 expect(meta("pull")).toBe("ui://forge/pull");
1380 expect(meta("pulls")).toBe("ui://forge/pulls");
1381 expect(meta("runs")).toBe("ui://forge/runs");
1382 expect(meta("asked")).toBe("ui://forge/asked");
1383 expect(meta("flow")).toBe("ui://forge/flow");
1384 expect(meta("scorecard")).toBe("ui://forge/scorecard");
1385 });
1386
1387 test("tools/call pull carries the card beside an unchanged text answer", async () => {
1388 const branched = await commitToBranch(app, alice, game, {
1389 branch: "card-wire",
1390 message: "a change",
1391 files: [{ path: "card.txt", content: "c\n" }],
1392 });
1393 if (!branched.ok) throw new Error(JSON.stringify(branched.error));
1394 const opened = await openPull(app, alice, game, {
1395 title: "Card wire",
1396 baseBranch: "main",
1397 headBranch: "card-wire",
1398 });
1399 if (!opened.ok) throw new Error(String(opened.error));
1400 const n = opened.value.number;
1401 const { body } = await call(rw, "tools/call", { name: "pull", arguments: { repo: "alice/game", number: n } });
1402 const card = body.result.structuredContent.card;
1403 expect(card.kind).toBe("pull");
1404 expect(card.title).toBe(`#${n} Card wire`);
1405 const branches = card.rows.find((r: any) => r.label === "Branches");
1406 expect(branches.value).toBe("card-wire → main");
1407 expect(branches.link).toBe(`${base}/alice/game/pulls/${n}`);
1408 // No environment for this pull in the test runtime, so no preview to link.
1409 expect(card.rows.some((r: any) => r.label === "Preview")).toBe(false);
1410 const text = JSON.parse(body.result.content[0].text);
1411 expect(text.title).toBe("Card wire");
1412 expect(text.next).toEqual({ who: "reviewer", why: "no review yet" });
1413 expect("card" in text).toBe(false);
1414 });
1415
1416 test("the pull card shows title, state, check, branches and the preview; a merged pull has no check or preview", async () => {
1417 const { cardFor } = await import("../src/web/studio/cards.ts");
1418 const origin = "https://forge.test";
1419 const open = cardFor(
1420 "pull",
1421 {
1422 number: 7,
1423 title: "<b>Add</b> a thing",
1424 state: "open",
1425 base: "main",
1426 head: "scout/7",
1427 check: { state: "ok" },
1428 mergeable: false,
1429 conflicts: ["a.ts"],
1430 },
1431 origin,
1432 { repo: "alice/game", preview: "https://p.example/" },
1433 )!;
1434 expect(open.kind).toBe("pull");
1435 expect(open.title).toBe("#7 <b>Add</b> a thing");
1436 expect(open.status).toBe("open · check green · conflicts");
1437 expect(open.rows.find((r) => r.label === "Branches")).toMatchObject({
1438 value: "scout/7 → main",
1439 link: "https://forge.test/alice/game/pulls/7",
1440 });
1441 expect(open.rows.find((r) => r.label === "Preview")?.link).toBe("https://p.example/");
1442 const merged = cardFor(
1443 "pull",
1444 { number: 8, title: "Done", state: "merged", base: "main", head: "x", check: { state: "ok" } },
1445 origin,
1446 { repo: "alice/game" },
1447 )!;
1448 expect(merged.status).toBe("merged");
1449 expect(merged.rows.some((r) => r.label === "Preview")).toBe(false);
1450 const hostile = cardFor("pull", { number: 1, state: "open", check: { state: "running" } }, origin, {
1451 repo: "a/b",
1452 preview: "javascript:alert(1)",
1453 })!;
1454 expect(hostile.status).toBe("open · check running");
1455 expect(hostile.rows.some((r) => r.label === "Preview")).toBe(false);
1456 });
1457
1458 test("the issue card carries state, assignee, labels and what it waits for, with absolute links and no comments", async () => {
1459 const { cardFor } = await import("../src/web/studio/cards.ts");
1460 const answer = {
1461 number: 7,
1462 title: "<b>Fix</b>",
1463 state: "open",
1464 closeReason: null,
1465 body: "secret body",
1466 assignee: "scout",
1467 labels: ["bug"],
1468 untrusted: true,
1469 comments: [{ author: "x", body: "COMMENTTEXT" }],
1470 blockedBy: [{ number: 3, title: "T3", state: "open" }],
1471 blocks: [],
1472 };
1473 const card = cardFor("issue", answer, "https://forge.test", { repo: "alice/game" })!;
1474 expect(card.kind).toBe("issue");
1475 expect(card.status).toBe("open");
1476 expect(card.title).toBe("#7 <b>Fix</b>");
1477 expect(card.rows[0]).toEqual({ label: "On the forge", value: "alice/game #7", link: "https://forge.test/alice/game/issues/7" });
1478 expect(card.rows.find((r) => r.label === "Assignee")!.value).toBe("scout");
1479 expect(card.rows.find((r) => r.label === "Labels")!.value).toBe("bug");
1480 expect(card.rows.find((r) => r.label === "Waits for")!.link).toBe("https://forge.test/alice/game/issues/3");
1481 expect(card.rows.some((r) => r.label === "Author" && r.value.startsWith("untrusted"))).toBe(true);
1482 expect(JSON.stringify(card)).not.toContain("COMMENTTEXT");
1483 expect(JSON.stringify(card)).not.toContain("secret body");
1484 expect(cardFor("issue", answer, "https://forge.test")!.rows[0]!.link).toBeUndefined();
1485 // A number that names a pull is not an issue: no card.
1486 expect(cardFor("issue", { kind: "pull", tool: "pull" }, "https://forge.test", { repo: "alice/game" })).toBeUndefined();
1487 expect(cardFor("issue", {}, "https://forge.test", { repo: "alice/game" })).toBeUndefined();
1488 });
1489
1490 test("the asks card links each ask to its pull or issue, and to nothing unsafe", async () => {
1491 const { cardFor } = await import("../src/web/studio/cards.ts");
1492 const words = { decision: "Ship it?", options: ["ship", "close"] };
1493 const rows = [
1494 { line: "a", repo: "alice/game", number: 3, numberOf: "pull", words },
1495 { line: "b", repo: "alice/game", number: 4, numberOf: "issue", words },
1496 { line: "c", repo: "alice/game", words },
1497 { line: "d", repo: "alice", number: 5, numberOf: "pull", words },
1498 { line: "e", repo: "alice/game", number: 0, numberOf: "pull", words },
1499 ];
1500 const card = cardFor("asks", { rows }, "https://forge.test")!;
1501 expect(card.rows.map((r) => r.link)).toEqual([
1502 "https://forge.test/alice/game/pulls/3",
1503 "https://forge.test/alice/game/issues/4",
1504 undefined,
1505 undefined,
1506 undefined,
1507 ]);
1508 expect(cardFor("asks", { rows }, "javascript:x")!.rows.every((r) => r.link === undefined)).toBe(true);
1509 });
1510
1511 test("the real asks result carries a link on a pull row and an issue row", async () => {
1512 await commitToBranch(app, alice, game, { branch: "ask-links", message: "x", files: [{ path: "ask.txt", content: "a\n" }] });
1513 const pull = await openPull(app, alice, game, { title: "Ask link pull", baseBranch: "main", headBranch: "ask-links" });
1514 const issue = await openIssue(app, alice, game, { title: "Ask link issue", body: "" });
1515 if (!pull.ok || !issue.ok) throw new Error("seed");
1516 const { setAssignee } = await import("../src/core/issues.ts");
1517 setAssignee(app.db, pull.value.id, alice.id);
1518 setAssignee(app.db, issue.value.id, alice.id);
1519 const { body } = await call(rw, "tools/call", { name: "asks", arguments: {} });
1520 const rows: any[] = body.result.structuredContent.card.rows;
1521 const linkOf = (label: string) => rows.find((r) => r.label.includes(label))?.link;
1522 expect(linkOf("Ask link pull")).toMatch(new RegExp(`^https?://[^/]+/alice/game/pulls/${pull.value.number}$`));
1523 expect(linkOf("Ask link issue")).toMatch(new RegExp(`^https?://[^/]+/alice/game/issues/${issue.value.number}$`));
1524 const { askLinesFor } = await import("../src/web/studio/asks.ts");
1525 const { cardFor } = await import("../src/web/studio/cards.ts");
1526 const lines = askLinesFor(app.db, alice);
1527 expect(lines.find((l) => l.id === `assigned:${pull.value.id}`)?.numberOf).toBe("pull");
1528 expect(lines.find((l) => l.id === `assigned:${issue.value.id}`)?.numberOf).toBe("issue");
1529 expect(cardFor("asks", { rows: lines }, "javascript:x")!.rows.every((r) => r.link === undefined)).toBe(true);
1530 });
1531
1532 test("the feed card draws one linked row per item, twenty at most, escaped as text", async () => {
1533 const { cardFor } = await import("../src/web/studio/cards.ts");
1534 const items = Array.from({ length: 25 }, (_, n) => ({
1535 actor: "scout",
1536 what: n === 0 ? "<b>shipped</b>" : `did ${n}`,
1537 app: "alice/game",
1538 at: new Date().toISOString(),
1539 link: `/alice/game/pulls/${n + 1}`,
1540 }));
1541 const card = cardFor("feed", { items }, "https://forge.test")!;
1542 expect(card.kind).toBe("feed");
1543 expect(card.title).toBe("Feed");
1544 expect(card.status).toBe("Latest");
1545 expect(card.rows).toHaveLength(20);
1546 expect(card.rows[0]).toEqual({
1547 label: "scout: <b>shipped</b>",
1548 value: "alice/game · just now",
1549 link: "https://forge.test/alice/game/pulls/1",
1550 });
1551 expect(cardFor("feed", { items, new: 3 })!.status).toBe("3 new since you last looked");
1552 expect(cardFor("feed", { items: [{ what: "x", link: "//evil.test/" }] }, "https://forge.test")!.rows[0]!.link).toBeUndefined();
1553 const { body } = await call(rw, "tools/call", { name: "feed", arguments: {} });
1554 expect(body.result.structuredContent.card.kind).toBe("feed");
1555 });
1556
1557 test("runs answers with the run card, newest first, twelve rows at most", async () => {
1558 const { cardFor } = await import("../src/web/studio/cards.ts");
1559 const runs = Array.from({ length: 15 }, (_, i) => ({
1560 id: `r${i}`, kind: "agent", state: "done", number: i === 0 ? null : i, startedAt: 1, endedAt: 2,
1561 }));
1562 const id = "01m23vygyffx5hg2f5vm8r74sr";
1563 runs[1]!.id = id;
1564 const card = cardFor("runs", { runs }, "https://f.example", { repo: "alice/game" })!;
1565 expect(card.kind).toBe("runs");
1566 expect(card.title).toBe("Runs");
1567 expect(card.rows[1]!.link).toBe(`https://f.example/alice/game/runs/${id}`);
1568 expect(card.rows[0]!.link).toBeUndefined();
1569 const nolink = cardFor("runs", { runs }, "https://f.example", { repo: "alice" })!;
1570 expect(nolink.rows[1]!.link).toBeUndefined();
1571 const { body } = await call(rw, "tools/call", { name: "runs", arguments: { repo: "alice/game" } });
1572 expect(body.result.structuredContent.card.kind).toBe("runs");
1573 const tools = (await listCall(rw)).body.result.tools;
1574 expect(tools.find((t: any) => t.name === "runs")._meta?.ui?.resourceUri).toBe("ui://forge/runs");
1575 });
1576
1577 test("a tool result carries the card it renders", async () => {
1578 const { body } = await call(rw, "tools/call", { name: "apps", arguments: {} });
1579 const card = body.result.structuredContent.card;
1580 expect(card.kind).toBe("app");
1581 expect(card.rows.some((r: any) => r.label === "alice/game")).toBe(true);
1582 const asks = await call(rw, "tools/call", { name: "asks", arguments: {} });
1583 expect(asks.body.result.structuredContent.card.kind).toBe("asks");
1584 });
1585
1586 test("ship and close card actions never apply at once and always meet the target tool's required fields", async () => {
1587 const { cardFor } = await import("../src/web/studio/cards.ts");
1588 const tools = (await listCall(rw)).body.result.tools;
1589 const cards = [
1590 cardFor("apps", [{ app: "alice/game", live: "up" }]),
1591 cardFor("now", [{ who: "scout", app: "alice/game", run: "r1", on: "#1", state: "going" }]),
1592 cardFor("asks", {
1593 rows: [
1594 { line: "a", kind: "look", items: ["x:1"], repo: "alice/game", number: 3, words: {} },
1595 { line: "b", kind: "review", items: ["x:2"], words: {} },
1596 ],
1597 }),
1598 ];
1599 let actions = 0;
1600 for (const card of cards)
1601 for (const a of [...card!.actions, ...card!.rows.flatMap((r) => r.actions ?? [])]) {
1602 actions++;
1603 expect(a.args["dryRun"]).not.toBe(false);
1604 const t = tools.find((x: any) => x.name === a.tool);
1605 // A words action gets `text` from the shell's field when pressed.
1606 for (const f of (t.inputSchema.required ?? []).filter((f: string) => !(a.words && f === "text"))) {
1607 expect(a.args[f]).toBeDefined();
1608 expect(a.args[f]).not.toBe("");
1609 }
1610 }
1611 expect(actions).toBeGreaterThan(2);
1612 });
1613
1614 test("a tell carries where it was told from, and refuses a malformed context", async () => {
1615 const told = await tool(rw, "tell", {
1616 repo: "alice/game",
1617 text: "make the button blue",
1618 context: {
1619 page: "https://game.example/play?level=2",
1620 run: "run_abc",
1621 commit: "deadbeef1",
1622 said: "the button is hard to see",
1623 },
1624 });
1625 const issues = listIssues(app.db, game.id, {});
1626 const issue = issues.find((i) => i.title === "make the button blue");
1627 expect(issue?.body).toContain("page: https://game.example/play?level=2");
1628 expect(issue?.body).toContain("commit: deadbeef1");
1629 expect(issue?.body).toContain("their words: the button is hard to see");
1630 expect(told).toBeDefined();
1631 for (const context of [
1632 { page: "javascript:alert(1)" },
1633 { commit: "--upload-pack=x" },
1634 "text",
1635 ]) {
1636 const refused = await tool(rw, "tell", { repo: "alice/game", text: "x", context });
1637 expect(refused.error).toContain("invalid");
1638 }
1639 });
1640
1641 test("GET /contract/openapi.json describes the public API", async () => {
1642 const res = await adminOpenapi(app, base, "/contract/openapi.json");
1643 expect(res.status).toBe(200);
1644 const doc = (await res.json()) as any;
1645 expect(doc.openapi).toBe("3.1.0");
1646 expect(doc.paths["/mcp"].post).toBeDefined();
1647 });
1648 test("GET /contract/openapi.json serves the triage routes", async () => {
1649 const doc = (await (await adminOpenapi(app, base, "/contract/openapi.json")).json()) as any;
1650 const R = "/api/v1/repos/{owner}/{name}";
1651 expect(doc.paths[`${R}/issues/{number}/teams`].get).toBeDefined();
1652 expect(doc.paths[`${R}/issues/{number}/teams`].put).toBeDefined();
1653 expect(doc.paths[`${R}/issues/{number}/labels`].put).toBeDefined();
1654 expect(doc.paths[`${R}/pulls/{number}/labels`].put).toBeDefined();
1655 expect(doc.paths[`${R}/issues/{number}/private`].post.responses["201"]).toBeDefined();
1656 });
1657 test("GET /api/v1/openapi.json answers the document itself", async () => {
1658 const res = await fetch(`${base}/api/v1/openapi.json`, { redirect: "manual" });
1659 expect(res.status).toBe(200);
1660 expect(res.headers.get("location")).toBeNull();
1661 expect(res.headers.get("cache-control")).toContain("public");
1662 expect(res.headers.get("etag")).toBeTruthy();
1663 });
1664 test("feed_chips reads and switches the chips the feed answers through", async () => {
1665 app.bus.append({ kind: "app.serving", repoId: game.id, actorId: alice.id, payload: {} });
1666 const kinds = async () => {
1667 const r = await tool(rw, "feed", { limit: 50 });
1668 return (r.value.items as { kind: string }[]).map((i) => i.kind);
1669 };
1670 const api = async () => {
1671 const res = await fetch(`${base}/api/v1/feed?limit=50`, { headers: { authorization: `Bearer ${rw}` } });
1672 return ((await res.json()) as { items: { kind: string }[] }).items.map((i) => i.kind);
1673 };
1674 expect(await kinds()).toContain("release");
1675 expect((await tool(rw, "feed_chips")).value).toEqual({ kinds: [], people: [] });
1676
1677 const set = await tool(rw, "feed_chips", { kind: "kind", value: "releases", hidden: true });
1678 expect(set.value).toEqual({ kinds: ["releases"], people: [] });
1679 expect(await kinds()).not.toContain("release");
1680 expect(await api()).not.toContain("release");
1681 // A read-only token may read the chips, not switch them.
1682 expect((await tool(ro, "feed_chips")).value).toEqual({ kinds: ["releases"], people: [] });
1683 expect((await tool(ro, "feed_chips", { kind: "kind", value: "releases", hidden: false })).error).toContain("forbidden");
1684 expect((await tool(rw, "feed_chips")).value.kinds).toEqual(["releases"]);
1685
1686 expect((await tool(rw, "feed_chips", { kind: "kind", value: "nope", hidden: true })).error).toBeDefined();
1687 expect((await tool(rw, "feed_chips", { kind: "person", value: "nobody", hidden: true })).error).toBeDefined();
1688 expect((await tool(rw, "feed_chips", { kind: "kind", value: "crew" })).error).toBeDefined();
1689 const person = await tool(rw, "feed_chips", { kind: "person", value: "bob", hidden: true });
1690 expect(person.value).toEqual({ kinds: ["releases"], people: ["bob"] });
1691 await tool(rw, "feed_chips", { kind: "person", value: "bob", hidden: false });
1692 const back = await tool(rw, "feed_chips", { kind: "kind", value: "releases", hidden: false });
1693 expect(back.value).toEqual({ kinds: [], people: [] });
1694 expect(await kinds()).toContain("release");
1695 });
1696
1697 test("whoami_can: the caller's role and its row, for a guest, a member and an admin", async () => {
1698 setMember(app.db, bob.id, false, alice.id, new Date());
1699 const guest = (await tool(bobRw, "whoami_can")).value;
1700 expect(guest.role).toBe("guest");
1701 expect(guest.can).toEqual({ read: true, comment: true, contribute: true, make_it_yours: false, run_crew: false, administer: false });
1702 setMember(app.db, bob.id, true, alice.id, new Date());
1703 const member = (await tool(bobRw, "whoami_can")).value;
1704 expect(member.role).toBe("member");
1705 expect(member.can).toEqual({ read: true, comment: true, contribute: true, make_it_yours: true, run_crew: true, administer: false });
1706 const admin = (await tool(ro, "whoami_can")).value;
1707 expect(admin.role).toBe("admin");
1708 expect(admin.can.administer).toBe(true);
1709 });
1710
1711 test("mint_invite: an admin person with an admin token gets a link; anyone else is refused", async () => {
1712 const admin = createToken(app.db, alice.id, "admin", "admin").token;
1713 expect((await tool(bobRw, "mint_invite")).error).toContain("forbidden");
1714 expect((await tool(rw, "mint_invite")).error).toContain("admin token");
1715 expect((await tool(admin, "mint_invite", { days: 0 })).error).toContain("invalid");
1716 const made = (await tool(admin, "mint_invite", { days: 3 })).value;
1717 expect(made.link).toMatch(/\/signup\?invite=[\w-]+$/);
1718 const token = made.link.split("invite=")[1];
1719 expect(made.token).toBeUndefined();
1720 expect(token.length).toBeGreaterThan(20);
1721 const listed = await fetch(`${base}/api/v1/admin/invites`, { headers: { authorization: `Bearer ${admin}` } });
1722 expect(JSON.stringify(await listed.json())).toContain(made.id);
1723 });
1724
1725 test("model_ceiling: dry by default, an admin person with an admin token sets and clears it", async () => {
1726 const admin = createToken(app.db, alice.id, "admin", "admin").token;
1727 const readOnly = createToken(app.db, alice.id, "ro", "ro").token;
1728 const target = (await createUser(app.db, { origin: "seed", trusted: true, username: "ceilee", email: "[email protected]", password: "a-good-passphrase" }));
1729 if (!target.ok) throw new Error(target.error);
1730 const id = target.value.id;
1731 const args = { username: "ceilee", dailyUsd: 12, perRunUsd: 3 };
1732 // A non-admin is refused.
1733 expect((await tool(bobRw, "model_ceiling", { ...args, dryRun: false })).error).toContain("forbidden");
1734 // A dry run changes nothing.
1735 expect((await tool(admin, "model_ceiling", args)).value.says).toContain("nothing changed");
1736 expect(getAccountCeiling(app.db, id)).toBeUndefined();
1737 // A read-only token is refused.
1738 expect((await tool(readOnly, "model_ceiling", { ...args, dryRun: false })).error).toContain("forbidden");
1739 expect(getAccountCeiling(app.db, id)).toBeUndefined();
1740 // Bad amounts are invalid; half a clear too.
1741 for (const bad of [{ dailyUsd: 0 }, { dailyUsd: 1e9 }, { perRunUsd: null }])
1742 expect((await tool(admin, "model_ceiling", { ...args, ...bad, dryRun: false })).error).toContain("invalid");
1743 expect(getAccountCeiling(app.db, id)).toBeUndefined();
1744 expect((await tool(admin, "model_ceiling", { ...args, dryRun: false })).value).toEqual({ username: "ceilee", dailyUsd: 12, perRunUsd: 3 });
1745 expect(getAccountCeiling(app.db, id)).toEqual({ dailyUsd: 12, perRunUsd: 3 });
1746 // Both null takes them back.
1747 const cleared = await tool(admin, "model_ceiling", { username: "ceilee", dailyUsd: null, perRunUsd: null, dryRun: false });
1748 expect(cleared.value).toEqual({ username: "ceilee", dailyUsd: null, perRunUsd: null });
1749 expect(getAccountCeiling(app.db, id)).toBeUndefined();
1750 });
1751
1752 test("new_app makes an app from a sentence and apps reads it back", async () => {
1753 const bot = await createAgent(app, alice, { username: "newappbot", brief: "builds" });
1754 if (!bot.ok) throw new Error(String(bot.error));
1755 const made = (await tool(rw, "new_app", {
1756 name: "sentence",
1757 description: "a page that says hello",
1758 agent: "newappbot",
1759 })) as any;
1760 expect(made.value.repo).toBe("alice/sentence");
1761 expect(made.value.issue).toBe(1);
1762 expect(made.value.agent).toBe("newappbot");
1763 expect(["queued", "running", "none"]).toContain(made.value.run);
1764 const cardRes = await call(rw, "tools/call", { name: "new_app", arguments: { name: "carded", description: "<b>hi</b>", agent: "newappbot" } });
1765 const card = cardRes.body.result.structuredContent.card;
1766 expect(card.kind).toBe("app");
1767 expect(card.title).toBe("New app");
1768 const byLabel = (l: string) => card.rows.find((r: any) => r.label === l)?.value;
1769 expect(byLabel("App")).toBe("alice/carded");
1770 expect(byLabel("First issue")).toBe("#1");
1771 expect(byLabel("Agent")).toBe("newappbot");
1772 expect(byLabel("First run")).toBeDefined();
1773 const seen = (await tool(rw, "apps")) as any;
1774 const row = seen.value.find((r: any) => r.app === "alice/sentence");
1775 expect(row).toBeDefined();
1776 expect(row.url).toBe(made.value.url);
1777 // The API's refusals, in its words.
1778 expect((await tool(rw, "new_app", { name: "sentence" })).error).toContain("name_taken");
1779 expect((await tool(rw, "new_app", { name: "other", agent: "nobody-here" })).error).toContain("no_such_agent");
1780 // Without the rw scope nothing is made.
1781 const denied = await tool(ro, "new_app", { name: "readonly" });
1782 expect(denied.error).toContain("forbidden");
1783 expect((await tool(rw, "apps") as any).value.some((r: any) => r.app === "alice/readonly")).toBe(false);
1784 }, 30_000);
1785
1786 test("new_app names an app from a sentence alone, and -2 when taken", async () => {
1787 const one = (await tool(rw, "new_app", { sentence: "a garden planner for my allotment" })) as any;
1788 expect(one.value.repo).toMatch(/^alice\/[a-z0-9-]+$/);
1789 expect(one.value.issue).toBe(1);
1790 const two = (await tool(rw, "new_app", { sentence: "a garden planner for my allotment" })) as any;
1791 expect(two.value.repo).toBe(`${one.value.repo}-2`);
1792 const named = (await tool(rw, "new_app", { name: "keepname", sentence: "a garden planner" })) as any;
1793 expect(named.value.repo).toBe("alice/keepname");
1794 expect(named.value.issue).toBe(1);
1795 // The derived path forwards visibility and agent, and `description` is the first issue over
1796 // `sentence`.
1797 const bot = await createAgent(app, alice, { username: "sentbot", brief: "builds" });
1798 if (!bot.ok) throw new Error(String(bot.error));
1799 const fwd = (await tool(rw, "new_app", {
1800 sentence: "a recipe box for the family",
1801 description: "Start with a list of recipes.",
1802 visibility: "private",
1803 agent: "sentbot",
1804 })) as any;
1805 expect(fwd.value.agent).toBe("sentbot");
1806 const [slug] = fwd.value.repo.split("/").slice(1);
1807 const made = getRepo(app.db, "alice", slug)!;
1808 expect(made.visibility).toBe("private");
1809 expect(listIssues(app.db, made.id, { state: "open" })[0]!.body).toContain("Start with a list of recipes.");
1810 // A refusal maps as on the named path.
1811 expect((await tool(rw, "new_app", { sentence: "a tide table", agent: "nobody-here" })).error).toContain("no_such_agent");
1812 expect((await tool(rw, "new_app", { sentence: "!!!" })).error).toContain("no_name");
1813 expect((await tool(rw, "new_app", {})).error).toContain("no_name");
1814 }, 30_000);
1815
1816 test("new_app with pick lets the planner name the agent", async () => {
1817 const picked = await createAgent(app, alice, { username: "pickbot", brief: "builds" });
1818 if (!picked.ok) throw new Error(String(picked.error));
1819 const dir = await mkdtemp(join(tmpdir(), "forge-mcp-pick-"));
1820 const fake = join(dir, "fake-claude");
1821 writeFileSync(
1822 fake,
1823 `#!/bin/sh
1824 if [ "$1" = "--version" ]; then echo "2.1.0 (fake)"; exit 0; fi
1825 printf '%s\\n' '{"is_error":false,"result":"{\\"summary\\":\\"Build it\\",\\"checklist\\":[\\"One\\"],\\"agent\\":\\"pickbot\\",\\"confidence\\":0.8}"}'
1826 `,
1827 );
1828 chmodSync(fake, 0o755);
1829 const real = process.env["FORGE_CLAUDE"];
1830 process.env["FORGE_CLAUDE"] = fake;
1831 try {
1832 const made = (await tool(rw, "new_app", {
1833 name: "picked",
1834 description: "a page that says hello",
1835 pick: true,
1836 })) as any;
1837 expect(made.error).toBeUndefined();
1838 expect(made.value.agent).toBe("pickbot");
1839 expect(typeof made.value.issue).toBe("number");
1840 const row = ((await tool(rw, "apps")) as any).value.find((r: any) => r.app === "alice/picked");
1841 expect(row.url).toBe(made.value.url);
1842 if (row.url !== null) expect(typeof made.value.url).toBe("string");
1843 } finally {
1844 if (real === undefined) delete process.env["FORGE_CLAUDE"];
1845 else process.env["FORGE_CLAUDE"] = real;
1846 await rm(dir, { recursive: true, force: true });
1847 }
1848 }, 30_000);
1849 });
test/migrate-crew.test.ts added +129
@@ -0,0 +1,129 @@
1 /**
2 * Migrate, end to end: a repository brought here for good.
3 *
4 * The fixture is a real repository on a real forge — several branches, a
5 * lightweight and an annotated tag, a default branch that is not `main` —
6 * and the migration speaks real smart HTTP to it. What must hold: the whole
7 * history arrives (`git log --all` matches, every ref matches), the new
8 * repository is native (no origin, no remote configured, pushes land here
9 * and nowhere else), a refusal is words before anything exists, a failed
10 * clone leaves nothing behind, and a crew put on it is on it: on the crew,
11 * the repository an app, one issue carrying the importer's brief.
12 *
13 * This file: a crew put on the migrated repository, and migration mode. Split from migrate.test.ts,
14 * each file on its own forge from test/support/migrate-forge.ts (#15351).
15 */
16
17 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
18 import { migrationOrigin } from "../src/apps/migration_mode.ts";
19 import { createAgent, listCrew } from "../src/actions/crew.ts";
20 import { getAppByRepo } from "../src/core/apps.ts";
21 import { listIssues } from "../src/core/issues.ts";
22 import { getRepo } from "../src/core/repos.ts";
23 import { getFollow } from "../src/core/upstream_follow.ts";
24 import { quietLogs } from "./helpers/globals.ts";
25 import { startMigrateForge, type MigrateForge } from "./support/migrate-forge.ts";
26
27 quietLogs();
28
29 describe("migrate: crew", () => {
30 let forge: MigrateForge;
31 let app: MigrateForge["app"];
32 let alice: MigrateForge["alice"];
33 let bob: MigrateForge["bob"];
34 let fixtureUrl: MigrateForge["fixtureUrl"];
35 let migrate: MigrateForge["migrate"];
36
37 beforeAll(async () => {
38 forge = await startMigrateForge();
39 ({ app, alice, bob, fixtureUrl, migrate } = forge);
40 }, 30_000);
41
42 afterAll(() => forge.stop());
43
44 test("with a crew: on the crew, an app, the importer's brief, autonomy only when asked", async () => {
45 const agent = await createAgent(app, alice, {
46 username: "porter",
47 model: "",
48 brief: "Moves things in.",
49 });
50 expect(agent.ok).toBe(true);
51
52 for (const [name, autonomous] of [
53 ["crewed", true],
54 ["assisted", false],
55 ] as const) {
56 const job = await migrate(bob, {
57 source: { url: fixtureUrl },
58 name,
59 crew: { agent: "porter", autonomous },
60 });
61 expect(job?.error).toBeUndefined();
62 expect(job?.stage).toBe("done");
63 expect(job?.detail).toContain("porter is on it");
64
65 const repo = getRepo(app.db, "bob", name)!;
66 const crew = listCrew(app, bob, repo);
67 expect(crew.ok && crew.value.map((a) => a.user.username)).toEqual([
68 "porter",
69 ]);
70 expect(getAppByRepo(app.db, repo.id)).toBeDefined();
71 expect(repo.autonomy).toBe(autonomous ? "autonomous" : "off");
72 // The source is the upstream it follows: on when autonomous (#3442).
73 const follow = getFollow(app.db, repo.id)!;
74 expect([follow.url, follow.branch, follow.enabled]).toEqual([fixtureUrl, "trunk", autonomous]);
75
76 const issues = listIssues(app.db, repo.id, {
77 kind: "issue",
78 state: "open",
79 });
80 expect(issues.length).toBe(1);
81 const issue = issues[0]!;
82 expect(issue.title).toBe(`Make ${name} run here`);
83 expect(issue.assigneeName).toBe("porter");
84 // The importer's brief is the same whether or not the crew is
85 // autonomous; autonomy is the repository's setting, asserted above.
86 for (const words of [
87 "Adapt, don't rewrite",
88 "forge.json",
89 "`run`",
90 "`health`",
91 "PORT",
92 "FORGE_APP_DATA",
93 "no Dockerfile, no compose",
94 "could not fit",
95 "Its data:",
96 "Leave the old database untouched",
97 "one-shot import script",
98 "dump file in",
99 "how to make the dump",
100 "Never commit or read at boot a connection string",
101 fixtureUrl,
102 ])
103 expect(issue.body).toContain(words);
104 }
105 });
106
107 test("migration mode: the direction is parity with the origin, the brief asks for the checklist, the mode is kept", async () => {
108 const agent = await createAgent(app, alice, { username: "parity", model: "", brief: "Keeps parity." });
109 expect(agent.ok).toBe(true);
110 const job = await migrate(bob, {
111 source: { url: fixtureUrl },
112 name: "inmode",
113 crew: { agent: "parity", autonomous: false, mode: "migration" },
114 });
115 expect(job?.stage).toBe("done");
116 const repo = getRepo(app.db, "bob", "inmode")!;
117 expect(repo.autonomyDirection).toBe(`run natively here with parity to ${fixtureUrl}`);
118 expect(migrationOrigin(app.db, repo.id)).toBe(fixtureUrl);
119 const issue = listIssues(app.db, repo.id, { kind: "issue", state: "open" })[0]!;
120 expect(issue.body).toContain("MIGRATION.md");
121 expect(issue.body).toContain("one issue per unchecked line");
122 // Without the mode, no direction and no row.
123 const plain = await migrate(bob, { source: { url: fixtureUrl }, name: "notmode", crew: { agent: "parity", autonomous: false } });
124 expect(plain?.stage).toBe("done");
125 const other = getRepo(app.db, "bob", "notmode")!;
126 expect(migrationOrigin(app.db, other.id)).toBeUndefined();
127 expect(other.autonomyDirection).not.toContain("parity to");
128 });
129 });
test/migrate-network.test.ts added +238
@@ -0,0 +1,238 @@
1 /**
2 * Migrate, end to end: a repository brought here for good.
3 *
4 * The fixture is a real repository on a real forge — several branches, a
5 * lightweight and an annotated tag, a default branch that is not `main` —
6 * and the migration speaks real smart HTTP to it. What must hold: the whole
7 * history arrives (`git log --all` matches, every ref matches), the new
8 * repository is native (no origin, no remote configured, pushes land here
9 * and nowhere else), a refusal is words before anything exists, a failed
10 * clone leaves nothing behind, and a crew put on it is on it: on the crew,
11 * the repository an app, one issue carrying the importer's brief.
12 *
13 * This file: which addresses a migration may fetch: private networks, resolved names, pinning,
14 * other hosts and redirects. Split from migrate.test.ts, each file on its own forge from
15 * test/support/migrate-forge.ts (#15351).
16 */
17
18 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
19 import {
20 isPrivateHost,
21 migrateRepo,
22 fetchEnv,
23 resolveSource,
24 sameOriginHost,
25 vetClone,
26 } from "../src/actions/migrate.ts";
27 import { getRepo } from "../src/core/repos.ts";
28 import { settled } from "../src/origins/jobs.ts";
29 import { exemptOrigin } from "../src/origins/origin_fetch.ts";
30 import { quietLogs } from "./helpers/globals.ts";
31 import { startMigrateForge, type MigrateForge } from "./support/migrate-forge.ts";
32
33 quietLogs();
34
35 describe("migrate: network", () => {
36 let forge: MigrateForge;
37 let app: MigrateForge["app"];
38 let base: MigrateForge["base"];
39 let alice: MigrateForge["alice"];
40 let bob: MigrateForge["bob"];
41 let originId: MigrateForge["originId"];
42 let migrate: MigrateForge["migrate"];
43
44 beforeAll(async () => {
45 forge = await startMigrateForge();
46 ({ app, base, alice, bob, originId, migrate } = forge);
47 }, 30_000);
48
49 afterAll(() => forge.stop());
50
51 test("a pasted address inside the network is an admin's alone, unless the forge says otherwise", async () => {
52 for (const h of [
53 "127.0.0.1",
54 "localhost",
55 "app.localhost",
56 "10.1.2.3",
57 "172.20.0.1",
58 "192.168.1.9",
59 "169.254.1.1",
60 "::1",
61 "fd00::1",
62 "0.0.0.0",
63 "[::ffff:127.0.0.1]",
64 "::ffff:7f00:1",
65 "0:0:0:0:0:ffff:7f00:1",
66 "::FFFF:10.0.0.1",
67 "[::ffff:c0a8:1]",
68 "fe80::1",
69 "[::]",
70 ])
71 expect(isPrivateHost(h)).toBe(true);
72 for (const h of [
73 "github.com",
74 "8.8.8.8",
75 "172.32.0.1",
76 "git.open-platform.sh",
77 "2606:4700::1",
78 "::ffff:8.8.8.8",
79 "[2001:db8::1]",
80 ])
81 expect(isPrivateHost(h)).toBe(false);
82 // The forge without the personal-forge switch: bob is refused, alice
83 // (the admin) is not. The flag is flipped in place: this only proves
84 // anything because migrateRepo reads it on every call, which the
85 // refusal below (the app was built with it true) fails without.
86 const config = app.config as { migrateFromPrivateHosts?: boolean };
87 config.migrateFromPrivateHosts = false;
88 try {
89 const refused = await migrateRepo(app, bob, {
90 source: { url: `${base}/alice/hidden.git` },
91 });
92 expect(refused).toEqual({ ok: false, error: "private_host" });
93 const allowed = await migrateRepo(app, alice, {
94 source: { url: `${base}/alice/hidden.git` },
95 name: "peek",
96 });
97 expect(allowed.ok).toBe(true);
98 if (allowed.ok) await settled(allowed.value.job.id);
99 } finally {
100 config.migrateFromPrivateHosts = true;
101 }
102 });
103
104 test("a name that resolves to a private address is refused like the literal", async () => {
105 const config = app.config as { migrateFromPrivateHosts?: boolean };
106 config.migrateFromPrivateHosts = false;
107 try {
108 const refused = await migrateRepo(app, bob, {
109 source: { url: "https://looks-public.example/a/b.git" },
110 resolve: async () => ["10.0.0.5"],
111 });
112 expect(refused).toEqual({ ok: false, error: "private_host" });
113 } finally {
114 config.migrateFromPrivateHosts = true;
115 }
116 });
117
118 test("a vetted host is pinned to the vetted address; a trusted one is not", async () => {
119 const config = app.config as { migrateFromPrivateHosts?: boolean };
120 config.migrateFromPrivateHosts = false;
121 try {
122 const source = { url: "https://looks-public.example/a/b.git" };
123 const resolved = await resolveSource(app, bob, source, async () => ["93.184.216.34"]);
124 if (!resolved.ok) throw new Error("expected a resolved source");
125 const env = fetchEnv(resolved.value, {});
126 const pins = Object.entries(env).filter(([, v]) => v.startsWith("looks-public.example:443:"));
127 expect(pins).toEqual([[expect.any(String), "looks-public.example:443:93.184.216.34"]]);
128 expect(env["GIT_ALLOW_PROTOCOL"]).toBe("https:http");
129 // A host that does not resolve is not fetched unpinned.
130 const lost = await resolveSource(app, bob, source, async () => []);
131 expect(lost).toEqual({ ok: false, error: "unreachable" });
132 } finally {
133 config.migrateFromPrivateHosts = true;
134 }
135 // No vetting (the caller may reach private hosts), so no pin.
136 const open = await resolveSource(app, bob, { url: "https://looks-public.example/a/b.git" });
137 if (!open.ok) throw new Error("expected a resolved source");
138 expect(Object.values(fetchEnv(open.value, {})).some((v) => v.includes(":443:"))).toBe(false);
139 });
140
141 test("an origin's clone_url on another host is refused before any git runs (#14756)", async () => {
142 const refused = await resolveSource(app, alice, { originId, fullName: "octo/elsewhere" });
143 expect(refused).toEqual({ ok: false, error: "foreign_clone_host" });
144 const job = await migrateRepo(app, alice, {
145 source: { originId, fullName: "octo/elsewhere" },
146 });
147 expect(job).toEqual({ ok: false, error: "foreign_clone_host" });
148 expect(getRepo(app.db, "alice", "elsewhere")).toBeUndefined();
149 const origin = { webUrl: "https://code.example", apiUrl: "https://api.code.example/api/v1" };
150 expect(sameOriginHost("https://code.example/o/r.git", origin)).toBe(true);
151 expect(sameOriginHost("https://API.code.example/o/r.git", origin)).toBe(true);
152 expect(sameOriginHost("http://10.0.0.5:3000/o/r.git", origin)).toBe(false);
153 expect(sameOriginHost("https://code.example.evil/o/r.git", origin)).toBe(false);
154 // Scheme, host and port, not the name alone.
155 expect(sameOriginHost("https://code.example:8443/o/r.git", origin)).toBe(false);
156 expect(sameOriginHost("http://code.example/o/r.git", origin)).toBe(false);
157 expect(sameOriginHost("https://code.example:443/o/r.git", origin)).toBe(true);
158 // A password in it, or a scheme that is not http(s), is never the origin's.
159 expect(sameOriginHost("https://me:[email protected]/o/r.git", origin)).toBe(false);
160 for (const other of ["file:///etc/passwd", "ssh://code.example/o/r.git", "git://code.example/o/r.git"])
161 expect(sameOriginHost(other, origin)).toBe(false);
162 });
163
164 test("an origin's clone_url is vetted and pinned as a pasted address is (#14756)", async () => {
165 const config = app.config as { migrateFromPrivateHosts?: boolean };
166 config.migrateFromPrivateHosts = false;
167 // Not an admin: the vetting is for everyone who may not reach inside.
168 const plain = { ...alice, isAdmin: false };
169 try {
170 const at = "https://code.example/octo/x.git";
171 expect(await vetClone(app, plain, "http://127.0.0.1:3000/x.git")).toEqual({
172 ok: false,
173 error: "private_host",
174 });
175 expect(await vetClone(app, plain, at, async () => ["10.0.0.5"])).toEqual({
176 ok: false,
177 error: "private_host",
178 });
179 expect(await vetClone(app, plain, at, async () => ["169.254.169.254"])).toEqual({
180 ok: false,
181 error: "private_host",
182 });
183 const pinned = await vetClone(app, plain, at, async () => ["93.184.216.34"]);
184 if (!pinned.ok || pinned.value === undefined) throw new Error("expected a pin");
185 const env = fetchEnv({ pin: pinned.value }, {});
186 expect(Object.values(env)).toContain("code.example:443:93.184.216.34");
187 // The exemption is the operator's word, never the origin's: only the
188 // environment (FORGE_ORIGIN_ALLOW, or loopback on a dev forge) grants it.
189 const loop = "http://localhost:3000/x.git";
190 expect(exemptOrigin(loop, {})).toBe(false);
191 expect(exemptOrigin("http://169.254.169.254/x.git", { FORGE_DEV: "1" })).toBe(false);
192 expect(exemptOrigin(loop, { FORGE_DEV: "1" })).toBe(true);
193 expect(exemptOrigin("https://git.lan/x.git", { FORGE_ORIGIN_ALLOW: "git.lan" })).toBe(true);
194 // A loopback origin a dev forge let in is cloned as it was connected.
195 expect(await vetClone(app, plain, "http://127.0.0.1:3000/x.git", undefined, true)).toEqual({
196 ok: true,
197 value: undefined,
198 });
199 } finally {
200 config.migrateFromPrivateHosts = true;
201 }
202 });
203
204 test("a clone follows no redirect: the address that was checked is the only one fetched", async () => {
205 let hits = 0;
206 const target = Bun.serve({
207 port: 0,
208 hostname: "127.0.0.1",
209 fetch() {
210 hits++;
211 return new Response("here", { status: 200 });
212 },
213 });
214 const hop = Bun.serve({
215 port: 0,
216 hostname: "127.0.0.1",
217 fetch() {
218 return new Response(null, {
219 status: 302,
220 headers: {
221 location: `http://127.0.0.1:${target.port}/x.git/info/refs?service=git-upload-pack`,
222 },
223 });
224 },
225 });
226 try {
227 const job = await migrate(alice, {
228 source: { url: `http://127.0.0.1:${hop.port}/hop.git` },
229 name: "hopped",
230 });
231 expect(job?.stage).toBe("failed");
232 expect(hits).toBe(0);
233 } finally {
234 hop.stop(true);
235 target.stop(true);
236 }
237 });
238 });
test/migrate-origins.test.ts added +558
@@ -0,0 +1,558 @@
1 /**
2 * Migrate, end to end: a repository brought here for good.
3 *
4 * The fixture is a real repository on a real forge — several branches, a
5 * lightweight and an annotated tag, a default branch that is not `main` —
6 * and the migration speaks real smart HTTP to it. What must hold: the whole
7 * history arrives (`git log --all` matches, every ref matches), the new
8 * repository is native (no origin, no remote configured, pushes land here
9 * and nowhere else), a refusal is words before anything exists, a failed
10 * clone leaves nothing behind, and a crew put on it is on it: on the crew,
11 * the repository an app, one issue carrying the importer's brief.
12 *
13 * This file: from a connected origin and from GitHub: credentials, issues, pulls from forks, the
14 * app's branch, Connect GitHub. Split from migrate.test.ts, each file on its own forge from
15 * test/support/migrate-forge.ts (#15351).
16 */
17
18 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
19 import { join } from "node:path";
20 import { migrateRepo } from "../src/actions/migrate.ts";
21 import { createAgent } from "../src/actions/crew.ts";
22 import { connectOrigin } from "../src/actions/origins.ts";
23 import { getPull, pullStatus } from "../src/core/pulls.ts";
24 import { pullMayRun } from "../src/core/pull_trust.ts";
25 import { approveHere } from "../src/actions/pulls.ts";
26 import { labelsFor, listComments } from "../src/core/issues.ts";
27 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
28 import { getAppByRepo } from "../src/core/apps.ts";
29 import { listIssues } from "../src/core/issues.ts";
30 import { listOrigins } from "../src/core/origins.ts";
31 import { getRepo } from "../src/core/repos.ts";
32 import { type User } from "../src/core/users.ts";
33 import { repoDir } from "../src/git/repos.ts";
34 import { settled } from "../src/origins/jobs.ts";
35 import { forgetProviders } from "../src/origins/providers/index.ts";
36 import { newFakeOAuth, newFakeState, serveFakeForge } from "./fake-origin.ts";
37 import { quietLogs } from "./helpers/globals.ts";
38 import { git, startMigrateForge, type MigrateForge } from "./support/migrate-forge.ts";
39
40 quietLogs();
41
42 describe("migrate: origins", () => {
43 let forge: MigrateForge;
44 let dataDir: MigrateForge["dataDir"];
45 let app: MigrateForge["app"];
46 let base: MigrateForge["base"];
47 let alice: MigrateForge["alice"];
48 let bob: MigrateForge["bob"];
49 let aliceCookie: MigrateForge["aliceCookie"];
50 let bobCookie: MigrateForge["bobCookie"];
51 let originId: MigrateForge["originId"];
52 let octo: MigrateForge["octo"];
53 let upstreamSecret: MigrateForge["upstreamSecret"];
54 let person: MigrateForge["person"];
55 let browser: MigrateForge["browser"];
56 let api: MigrateForge["api"];
57 let migrate: MigrateForge["migrate"];
58
59 beforeAll(async () => {
60 forge = await startMigrateForge();
61 ({ dataDir, app, base, alice, bob, aliceCookie, bobCookie, originId, octo, upstreamSecret, person, browser, api, migrate } = forge);
62 }, 30_000);
63
64 afterAll(() => forge.stop());
65
66 test("from an origin: the origin's credential opens a private repository", async () => {
67 // Anonymous, by URL: refused by the upstream, and nothing left here.
68 const anon = await migrate(alice, {
69 source: { url: `${base}/octo/secret-widgets.git` },
70 });
71 expect(anon?.stage).toBe("failed");
72
73 // Picked from the origin: the header opens it.
74 const response = await api(aliceCookie, {
75 source: { originId, fullName: "octo/secret-widgets" },
76 });
77 expect(response.status).toBe(202);
78 const started = (await response.json()) as { job: { id: string } };
79 const job = await settled(started.job.id);
80 expect(job?.error).toBeUndefined();
81 expect(job?.stage).toBe("done");
82 const migrated = getRepo(app.db, "alice", "secret-widgets")!;
83 expect(migrated.origin).toBeNull();
84 expect(migrated.description).toBe("gears, privately");
85 const dir = repoDir(app.reposRoot, "alice", "secret-widgets");
86 expect((await git(["log", "--format=%s", "main"], dir)).out).toBe("first");
87 // The credential rode in the environment and stayed there.
88 const config = await Bun.file(join(dir, "config")).text();
89 expect(config).not.toContain(upstreamSecret);
90 expect(config).not.toContain("extraHeader");
91
92 // Someone else's origin is not a source.
93 const bobs = await api(bobCookie, {
94 source: { originId, fullName: "octo/secret-widgets" },
95 });
96 expect(((await bobs.json()) as { error: string }).error).toBe(
97 "no_such_origin",
98 );
99 });
100
101 test("one click from GitHub: the repository, 3 issues, 1 open pull request and a crew run on the app", async () => {
102 // Upstream: a private repository with a branch an open pull stands on.
103 const made = await createRepo(app, octo, {
104 name: "gadgets",
105 visibility: "private",
106 });
107 if (!made.ok) throw new Error(made.error);
108 for (const [branch, path] of [
109 ["main", "README.md"],
110 ["fix-typo", "typo.txt"],
111 ] as const) {
112 const done = await commitToBranch(app, octo, made.value, {
113 branch,
114 message: `on ${branch}`,
115 files: [{ path, content: "x\n" }],
116 });
117 if (!done.ok) throw new Error(String(done.error));
118 }
119 const upstreamDir = repoDir(app.reposRoot, "octo", "gadgets");
120 const headSha = (await git(["rev-parse", "fix-typo"], upstreamDir)).out;
121
122 // A fake GitHub API in front of it, seeded: 3 issues (one closed, one
123 // with a comment), 1 open pull request, and 1 closed one that stays.
124 const state = newFakeState("github", "octo", upstreamSecret);
125 const github = serveFakeForge(state);
126 // Git through the fake origin itself: a clone address names the origin (#14756).
127 state.gitAt = base;
128 state.repos.push({
129 id: 501,
130 fullName: "octo/gadgets",
131 description: "small machines",
132 cloneUrl: `${github.url}/octo/gadgets.git`,
133 htmlUrl: "https://github.com/octo/gadgets",
134 defaultBranch: "main",
135 private: true,
136 sizeKb: 2048,
137 });
138 state.labels.set("octo/gadgets", [{ id: 9, name: "bug", color: "d73a4a" }]);
139 state.issues.set("octo/gadgets", [
140 { id: 601, number: 1, title: "Crashes on start", body: "Stack trace.", user: "mona", labels: ["bug"], commentCount: 1 },
141 { id: 602, number: 2, title: "An old thing", user: "hubot", state: "closed", closedAt: "2026-01-02T00:00:00Z" },
142 { id: 603, number: 3, title: "Write the docs", user: "mona" },
143 {
144 id: 604,
145 number: 4,
146 title: "Fix the typo",
147 body: "One letter.",
148 user: "octocat",
149 pull: { base: "main", head: "fix-typo", headRepo: "octo/gadgets", headSha },
150 },
151 {
152 id: 605,
153 number: 5,
154 title: "Turned down",
155 user: "octocat",
156 state: "closed",
157 pull: { base: "main", head: "nope", headRepo: "octo/gadgets" },
158 },
159 ]);
160 state.comments.set("octo/gadgets", [
161 { id: 701, issueNumber: 1, body: "Same here.", user: "hubot" },
162 ]);
163 try {
164 forgetProviders(dataDir);
165 const connected = await connectOrigin(app, alice, {
166 host: github.url,
167 kind: "github",
168 token: upstreamSecret,
169 });
170 if (!connected.ok) throw new Error(JSON.stringify(connected.error));
171 const agent = await createAgent(app, alice, {
172 username: "mover",
173 model: "",
174 brief: "Moves things in.",
175 });
176 expect(agent.ok).toBe(true);
177
178 // The picker: a row, marked private, sized, with its one button —
179 // and the account it came through can be disconnected from here.
180 const html = await (await browser(aliceCookie, "/migrate")).text();
181 const row = new RegExp(`name="pick"\\s+value="(${connected.value.id}/octo/gadgets)"`).exec(html);
182 expect(row).not.toBeNull();
183 expect(html).toContain("2.0 MiB");
184 expect(html).toContain("Migrate with the crew");
185 expect(html).toContain(`action="/settings/origins/${connected.value.id}/delete"`);
186 expect(html).toContain('name="then" value="migrate"');
187
188 // The filter narrows the rows on the server too (no script needed).
189 const filtered = await (await browser(aliceCookie, "/migrate?q=nothing-like-it")).text();
190 expect(filtered).not.toContain('value="' + row![1] + '"');
191
192 // One click: the row's button and the form's fields as they stood.
193 const posted = await browser(aliceCookie, "/migrate", {
194 pick: row![1]!,
195 url: "",
196 owner: "alice",
197 name: "",
198 visibility: "private",
199 agent: "mover",
200 });
201 expect(posted.status).toBe(303);
202 const where = posted.headers.get("location")!;
203 const job = await settled(where.split("/").pop()!);
204 expect(job?.error).toBeUndefined();
205 expect(job?.stage).toBe("done");
206 expect(job?.detail).toContain("3 issues, 1 open pull request, 1 comment");
207 // It ends at the app: the repository's page is the app's.
208 const landed = await browser(aliceCookie, where);
209 expect(landed.headers.get("location")).toBe("/alice/gadgets");
210
211 const repo = getRepo(app.db, "alice", "gadgets")!;
212 expect(repo.origin).toBeNull();
213 expect(getAppByRepo(app.db, repo.id)).toBeDefined();
214
215 // The issues, open and closed, numbered as they were, by their
216 // GitHub authors, each linking back.
217 const carried = listIssues(app.db, repo.id, { kind: "issue", state: "all" })
218 .filter((i) => i.originAuthor !== null)
219 .sort((a, b) => a.number - b.number);
220 expect(carried.map((i) => [i.number, i.state, i.originAuthor])).toEqual([
221 [1, "open", "mona"],
222 [2, "closed", "hubot"],
223 [3, "open", "mona"],
224 ]);
225 expect(carried[0]!.body).toStartWith(
226 "> Migrated from [octo/gadgets#1](",
227 );
228 expect(carried[0]!.body).toContain("by @mona on GitHub.");
229 expect(carried[0]!.body).toContain("Stack trace.");
230 expect(labelsFor(app.db, carried[0]!.id).map((l) => l.name)).toEqual(["bug"]);
231 const comments = listComments(app.db, carried[0]!.id);
232 expect(comments.map((c) => [c.originAuthor, c.body])).toEqual([
233 ["hubot", "Same here."],
234 ]);
235
236 // One pull request — the open one — native here, on its branch.
237 const pulls = listIssues(app.db, repo.id, { kind: "pull", state: "all" });
238 expect(pulls.map((p) => p.number)).toEqual([4]);
239 const pull = getPull(app.db, repo.id, 4)!;
240 expect(pull.headBranch).toBe("fix-typo");
241 expect(pull.originHeadRepo).toBeNull();
242 expect(pull.body).toContain("by @octocat on GitHub.");
243 const dir = repoDir(app.reposRoot, "alice", "gadgets");
244 expect((await git(["rev-parse", "fix-typo"], dir)).out).toBe(headSha);
245
246 // The crew's brief is the next number, assigned to the agent: the
247 // durable event the dispatcher (`crew/dispatch.ts`, started by
248 // main.ts) queues the first run from.
249 const brief = listIssues(app.db, repo.id, { kind: "issue", state: "open" })
250 .find((i) => i.originAuthor === null)!;
251 expect(brief.number).toBe(5);
252 expect(brief.assigneeName).toBe("mover");
253 const assigned = app.db
254 .query<{ payload: string }, [string]>(
255 "SELECT payload FROM event WHERE repo_id = ?1 AND kind = 'issue.assigned'",
256 )
257 .all(repo.id)
258 .map((e) => JSON.parse(e.payload) as { number: number; agent?: boolean });
259 expect(assigned).toContainEqual(
260 expect.objectContaining({ number: 5, agent: true }),
261 );
262 // And the import said so once, not once per row.
263 const imported = app.db
264 .query<{ n: number }, [string]>(
265 "SELECT count(*) AS n FROM event WHERE repo_id = ?1 AND kind = 'repo.imported'",
266 )
267 .get(repo.id);
268 expect(imported?.n).toBe(1);
269 } finally {
270 github.stop();
271 }
272 });
273
274 test("a pull opened from a fork arrives with its head under refs/pull/<n>/head, waiting for a writer to let it run", async () => {
275 const made = await createRepo(app, octo, { name: "forked-pulls", visibility: "private" });
276 if (!made.ok) throw new Error(made.error);
277 for (const branch of ["main", "their-work"]) {
278 const done = await commitToBranch(app, octo, made.value, {
279 branch,
280 message: `on ${branch}`,
281 files: [{ path: `${branch}.txt`, content: "x\n" }],
282 });
283 if (!done.ok) throw new Error(String(done.error));
284 }
285 // The head lives only where GitHub keeps it: refs/pull/<n>/head.
286 const upstream = repoDir(app.reposRoot, "octo", "forked-pulls");
287 const sha = (await git(["rev-parse", "their-work"], upstream)).out;
288 expect((await git(["update-ref", "refs/pull/6/head", sha], upstream)).code).toBe(0);
289 expect((await git(["branch", "-D", "their-work"], upstream)).code).toBe(0);
290 // A branch of the source's own that happens to be called pull/6.
291 const mainSha = (await git(["rev-parse", "main"], upstream)).out;
292 expect((await git(["branch", "pull/6", "main"], upstream)).code).toBe(0);
293
294 const state = newFakeState("github", "octo", upstreamSecret);
295 const github = serveFakeForge(state);
296 // Git through the fake origin itself: a clone address names the origin (#14756).
297 state.gitAt = base;
298 state.repos.push({
299 id: 801,
300 fullName: "octo/forked-pulls",
301 cloneUrl: `${github.url}/octo/forked-pulls.git`,
302 defaultBranch: "main",
303 private: true,
304 });
305 state.issues.set("octo/forked-pulls", [
306 {
307 id: 806,
308 number: 6,
309 title: "From a fork",
310 user: "stranger",
311 pull: { base: "main", head: "their-work", headRepo: "stranger/forked-pulls", headSha: sha },
312 },
313 ]);
314 try {
315 forgetProviders(dataDir);
316 const connected = await connectOrigin(app, alice, {
317 host: github.url,
318 kind: "github",
319 token: upstreamSecret,
320 });
321 if (!connected.ok) throw new Error(JSON.stringify(connected.error));
322 const job = await migrate(alice, {
323 source: { originId: connected.value.id, fullName: "octo/forked-pulls" },
324 });
325 expect(job?.error).toBeUndefined();
326 expect(job?.detail).toContain(
327 "1 open pull request (1 from forks, waiting for your approval to run here)",
328 );
329 const repo = getRepo(app.db, "alice", "forked-pulls")!;
330 const pull = getPull(app.db, repo.id, 6)!;
331 // Still the stranger's: the head is where the forge keeps pull heads,
332 // the source's own pull/6 branch is untouched, and no push event
333 // carried the stranger's head to a check or a preview.
334 expect(pull.originHeadRepo).toBe("stranger/forked-pulls");
335 const dir = repoDir(app.reposRoot, "alice", "forked-pulls");
336 expect((await git(["rev-parse", "refs/pull/6/head"], dir)).out).toBe(sha);
337 expect((await git(["rev-parse", "refs/heads/pull/6"], dir)).out).toBe(mainSha);
338 const pushed = app.db
339 .query<{ payload: string }, [string]>(
340 "SELECT payload FROM event WHERE repo_id = ?1 AND kind = 'push'",
341 )
342 .all(repo.id)
343 .map((e) => JSON.stringify(JSON.parse(e.payload)));
344 expect(pushed.length).toBe(1);
345 expect(pushed[0]).not.toContain(sha);
346 expect(pushed[0]).not.toContain("refs/pull/");
347 // It runs only once a writer approves this head.
348 const status = await pullStatus(dir, pull);
349 expect(status.headOid).toBe(sha);
350 expect(pullMayRun(app.db, repo, pull, sha)).toBe(false);
351 const approved = await approveHere(app, alice, repo, pull);
352 expect(approved.ok).toBe(true);
353 expect(pullMayRun(app.db, repo, pull, sha)).toBe(true);
354 } finally {
355 github.stop();
356 }
357 });
358
359 test("the app's branch: the person's newest beats the source's default, by URL and from GitHub, and the brief names it", async () => {
360 // trevato/arm's shape: `main` is the upstream's tree (and the newest
361 // commit), `workbench` is the person's app, ahead of it.
362 const upstreamer = await person("upstreamer");
363 const made = await createRepo(app, upstreamer, { name: "arm", visibility: "public" });
364 if (!made.ok) throw new Error(made.error);
365 const put = async (user: User, branch: string, message: string) => {
366 const done = await commitToBranch(app, user, made.value, {
367 branch,
368 message,
369 files: [{ path: `${message}.txt`, content: "x\n" }],
370 });
371 if (!done.ok) throw new Error(String(done.error));
372 };
373 // Which tip is newer is the rule's own test (work-branch.test.ts);
374 // here, whose it is decides.
375 await put(upstreamer, "main", "upstream-start");
376 await put(alice, "workbench", "the-app");
377 await put(upstreamer, "main", "upstream-later");
378 const upstream = repoDir(app.reposRoot, "upstreamer", "arm");
379 const mainSha = (await git(["rev-parse", "main"], upstream)).out;
380 const workSha = (await git(["rev-parse", "workbench"], upstream)).out;
381 const agent = await createAgent(app, alice, { username: "armer", model: "", brief: "Moves things in." });
382 expect(agent.ok).toBe(true);
383 const briefOf = (owner: string, name: string): string =>
384 listIssues(app.db, getRepo(app.db, owner, name)!.id, { kind: "issue", state: "open" })
385 .find((i) => i.title === `Make ${name} run here`)!.body;
386
387 // By URL, the clone's own authors: alice's branch, not the source's main.
388 const byUrl = await migrate(alice, {
389 source: { url: `${base}/upstreamer/arm.git` },
390 name: "arm-url",
391 crew: { agent: "armer", autonomous: false },
392 });
393 expect(byUrl?.error).toBeUndefined();
394 expect(byUrl?.detail).toContain("Working on workbench, the branch with your newest commits");
395 expect(getRepo(app.db, "alice", "arm-url")!.defaultBranch).toBe("workbench");
396 expect(briefOf("alice", "arm-url")).toContain("The app is on the branch `workbench`");
397 expect(briefOf("alice", "arm-url")).toContain("open your pull against it");
398 // Someone with no commits there keeps the source's default.
399 const theirs = await migrate(bob, { source: { url: `${base}/upstreamer/arm.git` }, name: "arm-bob" });
400 expect(getRepo(app.db, "bob", "arm-bob")!.defaultBranch).toBe("main");
401 expect(theirs?.detail).toContain("Working on main, the source's default branch");
402 // A branch that is not one git would take is refused before anything exists.
403 const bad = await migrateRepo(app, alice, {
404 source: { url: `${base}/upstreamer/arm.git` },
405 name: "arm-bad",
406 branch: "--upload-pack=x",
407 });
408 expect(bad.ok ? "" : bad.error).toBe("invalid_branch");
409 expect(getRepo(app.db, "alice", "arm-bad")).toBeUndefined();
410
411 // From GitHub: the origin says whose each last commit is by login.
412 const state = newFakeState("github", "octo", upstreamSecret);
413 const github = serveFakeForge(state);
414 // Git through the fake origin itself: a clone address names the origin (#14756).
415 state.gitAt = base;
416 state.repos.push({
417 id: 901,
418 fullName: "octo/arm",
419 cloneUrl: `${github.url}/upstreamer/arm.git`,
420 defaultBranch: "main",
421 private: true,
422 });
423 state.branches.set("octo/arm", [
424 { name: "main", sha: mainSha },
425 { name: "workbench", sha: workSha },
426 ]);
427 state.commits.set("octo/arm", [
428 { sha: workSha, message: "<b>the app</b>\n\nbody", authorName: "Octo Cat", authorEmail: "[email protected]", login: "octo", date: "2026-10-19T12:00:00Z" },
429 { sha: mainSha, message: "upstream later", authorName: "Up Streamer", login: "upstreamer", date: "2026-10-20T09:00:00Z" },
430 ]);
431 try {
432 forgetProviders(dataDir);
433 const connected = await connectOrigin(app, alice, { host: github.url, kind: "github", token: upstreamSecret });
434 if (!connected.ok) throw new Error(JSON.stringify(connected.error));
435 const value = `${connected.value.id}/octo/arm`;
436
437 // The row links to its branches; the list shows each last commit,
438 // escaped, newest first, and selects the person's.
439 const listing = await (await browser(aliceCookie, "/migrate")).text();
440 expect(listing).not.toContain('id="migrate-branches"');
441 expect(listing).toContain(`href="/migrate?source=${encodeURIComponent(value)}&amp;branches=1#migrate-branches"`);
442 // A plain visit with the row selected asks the origin for nothing.
443 const asking = () => state.requests.filter((r) => r.path.endsWith("/branches") || r.path.endsWith("/commits")).length;
444 const before = asking();
445 const plain = await (await browser(aliceCookie, `/migrate?${new URLSearchParams({ source: value })}`)).text();
446 expect(plain).not.toContain('id="migrate-branches"');
447 expect(asking()).toBe(before);
448 const html = await (await browser(aliceCookie, `/migrate?${new URLSearchParams({ source: value, branches: "1" })}`)).text();
449 // One listing and one commit per branch; a reload within the minute costs none.
450 expect(asking()).toBe(before + 3);
451 await browser(aliceCookie, `/migrate?${new URLSearchParams({ source: value, branches: "1" })}`);
452 expect(asking()).toBe(before + 3);
453 const rows = [...html.matchAll(/data-branch="([^"]+)"/g)].map((m) => m[1]);
454 expect(rows).toEqual(["main", "workbench"]);
455 expect(html).toMatch(/value="workbench"\s+checked/);
456 expect(html).not.toMatch(/value="main"\s+checked/);
457 expect(html).toContain("&lt;b&gt;the app&lt;/b&gt;");
458 expect(html).not.toContain("<b>the app</b>");
459 expect(html).toMatch(/octo ·\s+<time datetime="2026-10-19T12:00:00(\.000)?Z">2026-10-19<\/time>/);
460 expect(html).toContain("default there");
461 // Asked for, another branch is the one selected.
462 const asked = await (await browser(aliceCookie, `/migrate?${new URLSearchParams({ source: value, branch: "main" })}`)).text();
463 expect(asked).toMatch(/value="main"\s+checked/);
464
465 // The Migrate button carries the branch chosen.
466 const chosen = await browser(aliceCookie, "/migrate", {
467 source: value, branch: "main", url: "", owner: "alice", name: "arm-main", visibility: "private", agent: "armer",
468 });
469 expect(chosen.status).toBe(303);
470 const chosenJob = await settled(chosen.headers.get("location")!.split("/").pop()!);
471 expect(chosenJob?.detail).toContain("Working on main, the branch picked");
472 expect(getRepo(app.db, "alice", "arm-main")!.defaultBranch).toBe("main");
473 expect(briefOf("alice", "arm-main")).toContain("The app is on the branch `main` — the branch the person who migrated it picked");
474
475 // Another row's button ignores a branch drawn for a different row:
476 // one click migrates by the rule — here, by the origin's login alone,
477 // since the clone's author (alice) is not the person connected (octo).
478 const oneClick = await browser(aliceCookie, "/migrate", {
479 pick: value, source: "elsewhere/x/y", branch: "main", url: "", owner: "alice", name: "arm-click", visibility: "private", agent: "armer",
480 });
481 expect(oneClick.status).toBe(303);
482 const clickJob = await settled(oneClick.headers.get("location")!.split("/").pop()!);
483 expect(clickJob?.error).toBeUndefined();
484 expect(getRepo(app.db, "alice", "arm-click")!.defaultBranch).toBe("workbench");
485 expect(briefOf("alice", "arm-click")).toContain("The app is on the branch `workbench` — the branch with the newest commits of the person who migrated it");
486 } finally {
487 github.stop();
488 }
489 }, 30_000);
490
491 test("Connect GitHub from /migrate comes back to /migrate, and so does Disconnect; nothing else can be named", async () => {
492 const state = newFakeState("github", "bobby", "bob-gh-token");
493 const oauth = newFakeOAuth("migrate-client");
494 state.oauth = oauth;
495 const github = serveFakeForge(state);
496 process.env.FORGE_GITHUB_CLIENT_ID = "migrate-client";
497 // A stand-in GitHub Enterprise: the operator registers its host, since the
498 // github.com application never serves another host (#14757).
499 process.env.FORGE_ORIGIN_CLIENT_ID = `${new URL(github.url).hostname}=migrate-client`;
500 try {
501 forgetProviders(dataDir);
502 const page = await (await browser(bobCookie, "/migrate")).text();
503 expect(page).toContain('action="/settings/origins/oauth"');
504 expect(page).toContain("Connect GitHub");
505 // One filled button on the page: Migrate. Connect is an outline.
506 expect(page.match(/data-variant="primary"/g)?.length).toBe(1);
507 expect(page).toMatch(/data-variant="outline"[^>]*>\s*(<svg[\s\S]*?<\/svg>)?\s*Connect GitHub/);
508
509 const started = await browser(bobCookie, "/settings/origins/oauth", {
510 kind: "github",
511 host: github.url,
512 then: "migrate",
513 });
514 expect(started.status).toBe(303);
515 const flowPage = started.headers.get("location")!;
516 expect(flowPage).toMatch(/^\/settings\/origins\/flows\/[^?]+\?then=migrate$/);
517 const waiting = await (await browser(bobCookie, flowPage)).text();
518 expect(waiting).toContain("WXYZ-1234");
519 expect(waiting).toContain("/poll?then=migrate");
520
521 oauth.approved = true;
522 const flowId = flowPage.split("/").pop()!.split("?")[0]!;
523 const polled = await browser(
524 bobCookie,
525 `/settings/origins/flows/${flowId}/poll?then=migrate`,
526 {},
527 );
528 expect(polled.headers.get("location")).toBe("/migrate?connected=1");
529 const origin = listOrigins(app.db, bob.id).find((o) => o.kind === "github")!;
530 expect(origin).toBeDefined();
531
532 // Connected: the page lists the account and offers Disconnect, not Connect.
533 const after = await (await browser(bobCookie, "/migrate?connected=1")).text();
534 expect(after).toContain('id="migrate-connected"');
535 expect(after).toContain(`action="/settings/origins/${origin.id}/delete"`);
536 expect(after).not.toContain('action="/settings/origins/oauth"');
537
538 // `then` is a word, not an address: anything else goes home.
539 const steered = await browser(bobCookie, "/settings/origins/oauth", {
540 kind: "github",
541 host: github.url,
542 then: "https://evil.test/",
543 });
544 expect(steered.headers.get("location")).not.toContain("then=");
545
546 const gone = await browser(bobCookie, `/settings/origins/${origin.id}/delete`, {
547 then: "migrate",
548 });
549 expect(gone.status).toBe(303);
550 expect(gone.headers.get("location")).toBe("/migrate");
551 expect(listOrigins(app.db, bob.id).some((o) => o.id === origin.id)).toBe(false);
552 } finally {
553 delete process.env.FORGE_GITHUB_CLIENT_ID;
554 delete process.env.FORGE_ORIGIN_CLIENT_ID;
555 github.stop();
556 }
557 });
558 });
test/migrate-page.test.ts added +236
@@ -0,0 +1,236 @@
1 /**
2 * Migrate, end to end: a repository brought here for good.
3 *
4 * The fixture is a real repository on a real forge — several branches, a
5 * lightweight and an annotated tag, a default branch that is not `main` —
6 * and the migration speaks real smart HTTP to it. What must hold: the whole
7 * history arrives (`git log --all` matches, every ref matches), the new
8 * repository is native (no origin, no remote configured, pushes land here
9 * and nowhere else), a refusal is words before anything exists, a failed
10 * clone leaves nothing behind, and a crew put on it is on it: on the crew,
11 * the repository an app, one issue carrying the importer's brief.
12 *
13 * This file: the /migrate page, the picker and the job page. Split from migrate.test.ts, each file
14 * on its own forge from test/support/migrate-forge.ts (#15351).
15 */
16
17 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
18 import { backlink } from "../src/origins/carry.ts";
19 import { formatKib, matchesFilter } from "../src/web/pages/migrate.ts";
20 import { getRepo } from "../src/core/repos.ts";
21 import { advance, createJob, settled } from "../src/origins/jobs.ts";
22 import { STAGE_BADGE_JS } from "../src/web/stage-row.ts";
23 import { quietLogs } from "./helpers/globals.ts";
24 import { withScripts } from "./helpers/page-script.ts";
25 import { startMigrateForge, type MigrateForge } from "./support/migrate-forge.ts";
26
27 quietLogs();
28
29 describe("migrate: page", () => {
30 let forge: MigrateForge;
31 let app: MigrateForge["app"];
32 let servers: MigrateForge["servers"];
33 let forgejo: MigrateForge["forgejo"];
34 let alice: MigrateForge["alice"];
35 let aliceCookie: MigrateForge["aliceCookie"];
36 let bobCookie: MigrateForge["bobCookie"];
37 let fixtureUrl: MigrateForge["fixtureUrl"];
38 let browser: MigrateForge["browser"];
39
40 beforeAll(async () => {
41 forge = await startMigrateForge({ agents: ["porter"] });
42 ({ app, servers, forgejo, alice, aliceCookie, bobCookie, fixtureUrl, browser } = forge);
43 }, 30_000);
44
45 afterAll(() => forge.stop());
46
47 test("the picker's pieces: sizes in binary units, a filter on name or description, a backlink that cannot be steered", () => {
48 expect(formatKib(0)).toBe("");
49 expect(formatKib(512)).toBe("512 KiB");
50 expect(formatKib(1536)).toBe("1.5 MiB");
51 expect(formatKib(20 * 1024)).toBe("20 MiB");
52 expect(formatKib(3 * 1024 * 1024)).toBe("3.0 GiB");
53 expect(matchesFilter({ fullName: "octo/Gadgets", description: "" }, "gadg")).toBe(true);
54 expect(matchesFilter({ fullName: "octo/x", description: "Small machines" }, "MACHINE")).toBe(true);
55 expect(matchesFilter({ fullName: "octo/x", description: "" }, "y")).toBe(false);
56
57 expect(
58 backlink({ number: 7, author: "mona", htmlUrl: "https://github.com/o/r/issues/7" }, "o/r", "GitHub"),
59 ).toBe("> Migrated from [o/r#7](https://github.com/o/r/issues/7) by @mona on GitHub.");
60 // A link that is not http(s) is named, not linked; a login cannot
61 // smuggle markdown or a mention of someone else.
62 const hostile = backlink(
63 { number: 7, author: "x](javascript:alert(1)) @admin", htmlUrl: "javascript:alert(1)" },
64 "o/r",
65 "GitHub",
66 );
67 expect(hostile).not.toContain("javascript:");
68 expect(hostile).not.toContain("](");
69 expect(hostile).toBe("> Migrated from o/r#7 by @xjavascriptalert1admin on GitHub.");
70 });
71
72 test("the page: the form, the plus menu, the job, and who may see it", async () => {
73 const anonymous = await browser("", "/migrate");
74 expect(anonymous.status).toBe(303);
75 expect(anonymous.headers.get("location")).toStartWith("/signin");
76
77 const html = await (await browser(aliceCookie, "/migrate")).text();
78 expect(html).toContain('action="/migrate"');
79 expect(html).toContain('name="url"');
80 // Each repository is a row whose button is the form's submitter.
81 expect(html).toMatch(/name="pick"\s+value="[^"]+\/octo\/secret-widgets"/);
82 expect(html).toContain("octo/secret-widgets");
83 expect(html).toContain("Put a crew on it");
84 expect(html).toContain('name="agent"');
85 expect(html).toContain('name="autonomous"');
86 // The "+" menu carries it on every page, beside New repository.
87 const home = await (await browser(aliceCookie, "/")).text();
88 expect(home).toContain('href="/migrate"');
89 expect(home.indexOf('href="/new"')).toBeLessThan(
90 home.indexOf('href="/migrate"'),
91 );
92
93 // A cross-site post is refused before anything happens.
94 const forged = await browser(
95 aliceCookie,
96 "/migrate",
97 { url: fixtureUrl, name: "forged" },
98 "https://evil.test",
99 );
100 expect(forged.status).toBe(403);
101 expect(getRepo(app.db, "alice", "forged")).toBeUndefined();
102
103 const posted = await browser(aliceCookie, "/migrate", {
104 source: "",
105 url: fixtureUrl,
106 owner: "alice",
107 name: "copy",
108 agent: "porter",
109 autonomous: "on",
110 });
111 expect(posted.status).toBe(303);
112 const where = posted.headers.get("location")!;
113 expect(where).toStartWith("/migrate/jobs/");
114 await settled(where.split("/").pop()!);
115 // Nobody else watches alice's migration.
116 expect((await browser(bobCookie, where)).status).toBe(404);
117 const landed = await browser(aliceCookie, where);
118 expect(landed.status).toBe(303);
119 expect(landed.headers.get("location")).toBe("/alice/copy");
120 const repoPage = await (
121 await browser(
122 `${aliceCookie}; ${(landed.headers.get("set-cookie") ?? "").split(";")[0]}`,
123 "/alice/copy",
124 )
125 ).text();
126 expect(repoPage).toContain("Migrated as alice/copy");
127 expect(getRepo(app.db, "alice", "copy")?.autonomy).toBe("autonomous");
128 });
129
130 test("the job page follows its stages over the stream, with no meta refresh", async () => {
131 const follow = async (end: Partial<Parameters<typeof advance>[1]>) => {
132 const job = createJob("", "octo/streamed", {
133 kind: "migrate",
134 actorId: alice.id,
135 });
136 const page = await (
137 await browser(aliceCookie, `/migrate/jobs/${job.id}`)
138 ).text();
139 expect(page).not.toContain('http-equiv="refresh"');
140 expect(page).toContain(`data-job="${job.id}"`);
141 expect(page).toContain("<noscript>");
142 expect(page).toContain("Reload");
143 const streamPath = `/api/v1/migrate/${job.id}/stream`;
144 // Another person's stream is not found, as their page is.
145 expect((await browser(bobCookie, streamPath)).status).toBe(404);
146 const res = await browser(aliceCookie, streamPath);
147 expect(res.status).toBe(200);
148 advance(job.id, { stage: "fetching", detail: "receiving 61%" });
149 advance(job.id, end);
150 // The stream ends itself on a terminal stage.
151 const text = await new Response(res.body).text();
152 return { job, text };
153 };
154
155 const ok = await follow({ stage: "done", detail: "migrated" });
156 expect(ok.text).toContain("event: migrate.creating");
157 expect(ok.text).toContain("event: migrate.fetching");
158 expect(ok.text).toContain("event: migrate.done");
159
160 const bad = await follow({ stage: "failed", error: "clone went wrong" });
161 expect(bad.text).toContain("event: migrate.fetching");
162 expect(bad.text).toContain("event: migrate.failed");
163 expect(bad.text).toContain("clone went wrong");
164 // Failed is a page that stands, with the reason, and no stream of its own.
165 const stands = await (
166 await browser(aliceCookie, `/migrate/jobs/${bad.job.id}`)
167 ).text();
168 expect(stands).toContain("clone went wrong");
169 expect(stands).not.toContain("error-note");
170 expect(stands).toMatch(
171 /<div class="field" data-invalid>\s*<span class="error" role="alert"[^>]*>clone went wrong/,
172 );
173 expect(stands).not.toContain("EventSource");
174 expect(stands).not.toContain('http-equiv="refresh"');
175 });
176
177 test("a link prefills the form and starts nothing", async () => {
178 const host = new URL(forgejo.url).host;
179 expect(host).toContain(":"); // the fake forge has a port; the label would not
180 const already = getRepo(app.db, "alice", "secret-widgets")?.id;
181 const get = async (qs: string) =>
182 (await browser(aliceCookie, `/migrate?${qs}`)).text();
183
184 const hit = await get(
185 new URLSearchParams({ from: `${host}/octo/secret-widgets`, crew: "porter" }).toString(),
186 );
187 expect(hit).toMatch(/name="source" value="[^"]+\/octo\/secret-widgets"/);
188 expect(hit).toMatch(/aria-current="true"/);
189 expect(hit).toMatch(/<option[^>]*value="porter"[^>]*selected|selected[^>]*value="porter"/);
190 expect(hit).not.toContain("prefill-unmatched");
191
192 const miss = await get(
193 new URLSearchParams({
194 from: `other.example/octo/secret-widgets`,
195 crew: `<script>alert(1)</script>`,
196 }).toString(),
197 );
198 expect(miss).toContain("prefill-unmatched");
199 expect(miss).toContain("from=other.example/octo/secret-widgets");
200 expect(miss).not.toContain("<script>alert(1)");
201 expect(miss).toContain("&lt;script&gt;");
202 expect(miss).not.toContain('name="source" value=');
203 expect(miss).not.toContain('aria-current="true"');
204
205 // A link starts nothing: no repository, no job.
206 expect(getRepo(app.db, "alice", "secret-widgets")?.id).toBe(already);
207 });
208
209 test("the job page draws each stage as a row with a state badge, and no stage-dot", async () => {
210 const job = createJob("", "octo/rows", { kind: "migrate", actorId: alice.id });
211 advance(job.id, { stage: "fetching", detail: "receiving 61%" });
212 const page = await (await browser(aliceCookie, `/migrate/jobs/${job.id}`)).text();
213 expect(page).not.toContain("stage-dot");
214 expect(page).not.toContain("stage-detail");
215 // The page's script is built from the table the rows are drawn from.
216 expect(await withScripts(servers.url, page)).toContain(`var badges = ${STAGE_BADGE_JS};`);
217 expect(page).toMatch(/<li data-stage-name="creating" data-state="done">[\s\S]*?class="row"[\s\S]*?>Done</);
218 expect(page).toMatch(/data-stage-name="fetching" data-state="now">[\s\S]*?receiving 61%[\s\S]*?>Running</);
219 expect(page).toMatch(/data-stage-name="crew" data-state="todo">[\s\S]*?>Waiting</);
220 expect(page).toMatch(/<ol class="list stages" aria-live="polite">/);
221 // Every stage has a `.row-meta` for the live update to write into.
222 const items = page.match(/<li data-stage-name=[\s\S]*?<\/li>/g) ?? [];
223 expect(items.length).toBeGreaterThan(0);
224 for (const li of items) expect(li).toContain('class="row-meta"');
225 });
226
227 test("mark the stage it failed on, and keep the earlier ones done", async () => {
228 const job = createJob("", "octo/broke", { kind: "migrate", actorId: alice.id });
229 advance(job.id, { stage: "fetching", detail: "receiving 3%" });
230 advance(job.id, { stage: "failed", error: "clone went wrong" });
231 const page = await (await browser(aliceCookie, `/migrate/jobs/${job.id}`)).text();
232 expect(page).toMatch(/data-stage-name="creating" data-state="done"/);
233 expect(page).toMatch(/data-stage-name="fetching" data-state="failed">[\s\S]*?data-variant="danger"\s*>Failed</);
234 expect(page).toMatch(/data-stage-name="crew" data-state="todo"/);
235 });
236 });
test/migrate-prefill.test.ts added +42
@@ -0,0 +1,42 @@
1 /**
2 * The /migrate form's prefill from a link: `from` matched to a connected
3 * origin's repository, `crew` to an agent, and whatever does not match
4 * named and capped, never guessed. Split from migrate.test.ts (#15351).
5 */
6
7 import { describe, expect, test } from "bun:test";
8 import { prefill } from "../src/web/pages/migrate-prefill.ts";
9
10 describe("migrate prefill", () => {
11 const origins = [
12 { id: "o1", host: "git.example.test:3000", repos: [{ fullName: "Octo/Widgets" }] },
13 { id: "o2", host: "git.open-platform.sh", repos: [{ fullName: "trevato/forge" }] },
14 ];
15 const agents = ["porter", "scout"];
16
17 test("a host with a port, and one without", () => {
18 expect(prefill({ from: "git.example.test:3000/octo/widgets" }, origins, agents).repo).toEqual({
19 originId: "o1",
20 fullName: "Octo/Widgets",
21 });
22 const plain = prefill({ from: "GIT.open-platform.sh/trevato/forge", crew: "scout" }, origins, agents);
23 expect(plain.repo?.originId).toBe("o2");
24 expect(plain.agent).toBe("scout");
25 expect(plain.unmatched).toEqual([]);
26 });
27
28 test("a mismatch is named, never guessed (not the display label)", () => {
29 const r = prefill({ from: "git/trevato/forge", crew: "nobody" }, origins, agents);
30 expect(r.repo).toBeUndefined();
31 expect(r.agent).toBeUndefined();
32 expect(r.unmatched).toEqual(["from=git/trevato/forge", "crew=nobody"]);
33 expect(prefill({ from: "git.example.test/octo/widgets" }, origins, agents).repo).toBeUndefined();
34 });
35
36 test("a hostile or oversized value is ignored and capped", () => {
37 const r = prefill({ from: "<img src=x onerror=1>/a/b", crew: "x".repeat(500) }, origins, agents);
38 expect(r.repo).toBeUndefined();
39 expect(r.unmatched).toHaveLength(2);
40 expect(r.unmatched.every((u) => u.length < 100)).toBe(true);
41 });
42 });
test/migrate-trail.test.ts added +144
@@ -0,0 +1,144 @@
1 /**
2 * Migrate, end to end: a repository brought here for good.
3 *
4 * The fixture is a real repository on a real forge — several branches, a
5 * lightweight and an annotated tag, a default branch that is not `main` —
6 * and the migration speaks real smart HTTP to it. What must hold: the whole
7 * history arrives (`git log --all` matches, every ref matches), the new
8 * repository is native (no origin, no remote configured, pushes land here
9 * and nowhere else), a refusal is words before anything exists, a failed
10 * clone leaves nothing behind, and a crew put on it is on it: on the crew,
11 * the repository an app, one issue carrying the importer's brief.
12 *
13 * This file: a migrated fork's trail, shown and hidden. Split from migrate.test.ts, each file on
14 * its own forge from test/support/migrate-forge.ts (#15351).
15 */
16
17 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
18 import { getProvenance, recordProvenance, setProvenanceShown } from "../src/core/provenance.ts";
19 import { getRepo } from "../src/core/repos.ts";
20 import { quietLogs } from "./helpers/globals.ts";
21 import { startMigrateForge, type MigrateForge } from "./support/migrate-forge.ts";
22
23 quietLogs();
24
25 describe("migrate: trail", () => {
26 let forge: MigrateForge;
27 let app: MigrateForge["app"];
28 let base: MigrateForge["base"];
29 let alice: MigrateForge["alice"];
30 let aliceCookie: MigrateForge["aliceCookie"];
31 let bobCookie: MigrateForge["bobCookie"];
32 let originId: MigrateForge["originId"];
33 let browser: MigrateForge["browser"];
34 let migrate: MigrateForge["migrate"];
35
36 beforeAll(async () => {
37 forge = await startMigrateForge();
38 ({ app, base, alice, aliceCookie, bobCookie, originId, browser, migrate } = forge);
39 }, 30_000);
40
41 afterAll(() => forge.stop());
42
43 test("a migrated fork shows its trail, and its owner can hide it and bring it back", async () => {
44 const job = await migrate(alice, {
45 source: { originId, fullName: "octo/arm" },
46 visibility: "public",
47 });
48 expect(job?.error).toBeUndefined();
49 const repo = getRepo(app.db, "alice", "arm")!;
50 const lineage = async (cookie: string): Promise<string> => {
51 const page = await (await browser(cookie, "/alice/arm")).text();
52 return /<p class="muted small break" data-lineage>[\s\S]*?<\/p>/.exec(page)?.[0] ?? "";
53 };
54 const shown = await lineage("");
55 expect(shown).toContain("Migrated from");
56 expect(shown).toContain(
57 '<a href="https://code.example/octo/arm" rel="noopener noreferrer">code.example/octo/arm</a>',
58 );
59 expect(shown).toContain("fork of");
60 expect(shown).toContain(
61 '<a href="https://code.example/TheRobotStudio/arm" rel="noopener noreferrer">TheRobotStudio/arm</a>',
62 );
63 const facts = async () =>
64 ((await (await browser("", "/api/v1/repos/alice/arm")).json()) as {
65 provenance: { source: string; parents: { url: string }[] } | null;
66 }).provenance;
67 expect((await facts())?.source).toBe("code.example/octo/arm");
68 expect((await facts())?.parents[0]?.url).toBe(
69 "https://code.example/TheRobotStudio/arm",
70 );
71
72 // Not bob's to hide: he can read it, not administer it.
73 const refused = await browser(bobCookie, "/alice/arm/settings/provenance", {
74 shown: "0",
75 });
76 expect(refused.status).not.toBe(303);
77 expect(getProvenance(app.db, repo.id)?.shown).toBe(true);
78
79 // Off: gone for anyone else and from the API, the record kept.
80 const settings = await (await browser(aliceCookie, "/alice/arm/settings")).text();
81 expect(settings).toContain("Hide where this came from");
82 const off = await browser(aliceCookie, "/alice/arm/settings/provenance", {
83 shown: "0",
84 });
85 expect(off.status).toBe(303);
86 expect(await lineage("")).toBe("");
87 expect(await lineage(bobCookie)).toBe("");
88 expect(await facts()).toBeNull();
89 expect(getProvenance(app.db, repo.id)).toMatchObject({
90 sourceUrl: "https://code.example/octo/arm",
91 parents: ["TheRobotStudio/arm"],
92 shown: false,
93 });
94
95 // On again, by the API this time: back as it was.
96 const on = await fetch(`${base}/api/v1/repos/alice/arm`, {
97 method: "PATCH",
98 headers: {
99 "content-type": "application/json",
100 cookie: aliceCookie,
101 origin: new URL(base).origin,
102 },
103 body: JSON.stringify({ showProvenance: true }),
104 });
105 expect(on.status).toBe(200);
106 expect(await lineage("")).toBe(shown);
107 });
108
109 test("a private source migrated as public keeps its trail hidden until its owner shows it", async () => {
110 const job = await migrate(alice, {
111 source: { originId, fullName: "octo/hush" },
112 visibility: "public",
113 });
114 expect(job?.error).toBeUndefined();
115 const repo = getRepo(app.db, "alice", "hush")!;
116 expect(repo.visibility).toBe("public");
117 const page = await (await browser("", "/alice/hush")).text();
118 expect(page).not.toContain("data-lineage");
119 expect(page).not.toContain("octo/hush");
120 const api = (await (await browser("", "/api/v1/repos/alice/hush")).json()) as {
121 provenance: unknown;
122 };
123 expect(api.provenance).toBeNull();
124 expect(getProvenance(app.db, repo.id)).toMatchObject({
125 sourceUrl: "https://code.example/octo/hush",
126 parents: ["TheRobotStudio/hush"],
127 shown: false,
128 });
129 const settings = await (await browser(aliceCookie, "/alice/hush/settings")).text();
130 expect(settings).toContain("Hidden; the record is kept.");
131 expect(settings.indexOf("nobody else sees it")).toBeGreaterThan(settings.indexOf("data-page-help"));
132 expect(settings).not.toContain("Hide where this came from");
133 expect(settings).toMatch(/<button[^>]*>\s*Show where this came from/);
134
135 // A second record (a re-migration's) leaves the owner's choice alone.
136 setProvenanceShown(app.db, repo.id, true);
137 recordProvenance(app.db, repo.id, {
138 url: "https://code.example/octo/hush",
139 parents: [],
140 shown: false,
141 });
142 expect(getProvenance(app.db, repo.id)?.shown).toBe(true);
143 });
144 });
test/migrate-url.test.ts added +234
@@ -0,0 +1,234 @@
1 /**
2 * Migrate, end to end: a repository brought here for good.
3 *
4 * The fixture is a real repository on a real forge — several branches, a
5 * lightweight and an annotated tag, a default branch that is not `main` —
6 * and the migration speaks real smart HTTP to it. What must hold: the whole
7 * history arrives (`git log --all` matches, every ref matches), the new
8 * repository is native (no origin, no remote configured, pushes land here
9 * and nowhere else), a refusal is words before anything exists, a failed
10 * clone leaves nothing behind, and a crew put on it is on it: on the crew,
11 * the repository an app, one issue carrying the importer's brief.
12 *
13 * This file: by URL: the whole history arrives, and what cannot work is refused in words before
14 * anything exists, a failed clone leaving nothing behind. Split from migrate.test.ts, each file on
15 * its own forge from test/support/migrate-forge.ts (#15351).
16 */
17
18 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
19 import { existsSync } from "node:fs";
20 import { join } from "node:path";
21 import { migrateRepo, migrateMessage, migrateUrl } from "../src/actions/migrate.ts";
22 import { createRepo } from "../src/actions/repos.ts";
23 import { getProvenance } from "../src/core/provenance.ts";
24 import { getRepo } from "../src/core/repos.ts";
25 import { addTeamMember, createOrg, createTeam } from "../src/core/orgs.ts";
26 import { repoDir } from "../src/git/repos.ts";
27 import { settled } from "../src/origins/jobs.ts";
28 import { quietLogs } from "./helpers/globals.ts";
29 import {
30 allCommits,
31 allRefs,
32 git,
33 startMigrateForge,
34 type MigrateForge,
35 } from "./support/migrate-forge.ts";
36
37 quietLogs();
38
39 describe("migrate: url", () => {
40 let forge: MigrateForge;
41 let work: MigrateForge["work"];
42 let app: MigrateForge["app"];
43 let base: MigrateForge["base"];
44 let alice: MigrateForge["alice"];
45 let bob: MigrateForge["bob"];
46 let bobCookie: MigrateForge["bobCookie"];
47 let bobToken: MigrateForge["bobToken"];
48 let fixtureUrl: MigrateForge["fixtureUrl"];
49 let browser: MigrateForge["browser"];
50 let apiToken: MigrateForge["apiToken"];
51 let api: MigrateForge["api"];
52 let migrate: MigrateForge["migrate"];
53
54 beforeAll(async () => {
55 forge = await startMigrateForge();
56 ({ work, app, base, alice, bob, bobCookie, bobToken, fixtureUrl, browser, apiToken, api, migrate } = forge);
57 }, 30_000);
58
59 afterAll(() => forge.stop());
60
61 test("by URL: the whole history arrives in a native repository, and pushes stay here", async () => {
62 const sourceDir = repoDir(app.reposRoot, "alice", "fixture");
63 const sourceRefs = await allRefs(sourceDir);
64
65 // By token, so the non-cookie door to the endpoint stays covered.
66 const response = await apiToken(bobToken, { source: { url: fixtureUrl } });
67 expect(response.status).toBe(202);
68 const started = (await response.json()) as {
69 repo: { name: string };
70 job: { id: string };
71 };
72 expect(started.repo.name).toBe("fixture");
73 const job = await settled(started.job.id);
74 expect(job?.error).toBeUndefined();
75 expect(job?.stage).toBe("done");
76 expect(job?.detail).toContain("3 branches, 2 tags");
77
78 const migrated = getRepo(app.db, "bob", "fixture")!;
79 // Where it came from is kept as a link, the `.git` dropped; a plain
80 // http host on loopback is not asked what it forks (#3293).
81 expect(getProvenance(app.db, migrated.id)).toMatchObject({
82 sourceUrl: `${base}/alice/fixture`,
83 parents: [],
84 shown: true,
85 });
86 const dir = repoDir(app.reposRoot, "bob", "fixture");
87 // Every commit, every branch, every tag — the annotated one as itself.
88 expect(await allCommits(dir)).toEqual(await allCommits(sourceDir));
89 expect(await allRefs(dir)).toBe(sourceRefs);
90 expect((await git(["cat-file", "-t", "refs/tags/v2"], dir)).out).toBe(
91 "tag",
92 );
93 // The source's default branch is kept.
94 expect(migrated.defaultBranch).toBe("trunk");
95 expect((await git(["symbolic-ref", "HEAD"], dir)).out).toBe(
96 "refs/heads/trunk",
97 );
98 // Native: no origin row, no remote in its config — nothing a push could
99 // write through to, so pushes land here and the source never hears.
100 expect(migrated.origin).toBeNull();
101 expect((await git(["config", "--get-regexp", "^remote\\."], dir)).out).toBe(
102 "",
103 );
104
105 // A real push lands here, and the source never hears of it.
106 const clone = join(work, "bob-fixture");
107 const url = new URL(`${base}/bob/fixture.git`);
108 url.username = "bob";
109 url.password = bobToken;
110 expect(
111 (await git(["clone", "--quiet", url.toString(), clone], work)).code,
112 ).toBe(0);
113 await Bun.write(join(clone, "bob.txt"), "mine now\n");
114 expect((await git(["add", "."], clone)).code).toBe(0);
115 expect((await git(["commit", "-qm", "bob's change"], clone)).code).toBe(0);
116 const pushed = await git(
117 ["push", "--quiet", "origin", "HEAD:refs/heads/bobs"],
118 clone,
119 );
120 expect(pushed.err).toBe("");
121 expect(pushed.code).toBe(0);
122 expect(
123 (await git(["rev-parse", "--verify", "refs/heads/bobs"], dir)).code,
124 ).toBe(0);
125 expect(await allRefs(sourceDir)).toBe(sourceRefs);
126 });
127
128 test("a URL git must not run is refused in words before anything exists", async () => {
129 const count = () =>
130 (app.db.query("SELECT COUNT(*) AS n FROM repo").get() as { n: number }).n;
131 const before = count();
132 // What a hostile URL would touch if git ever ran it: a path of this
133 // test's own.
134 const canary = join(work, "touched-by-git");
135 for (const url of [
136 "file:///etc",
137 `ext::sh -c touch% ${canary}`,
138 "ssh://[email protected]/a/b.git",
139 "[email protected]:a/b.git",
140 `--upload-pack=touch ${canary}`,
141 "https://user:[email protected]/a/b.git",
142 "",
143 ])
144 expect(await migrateRepo(app, bob, { source: { url } })).toEqual({
145 ok: false,
146 error: "invalid_url",
147 });
148 expect(existsSync(canary)).toBe(false);
149 // On the wire it is a 422 with words.
150 const response = await api(bobCookie, { source: { url: "file:///etc" } });
151 expect(response.status).toBe(422);
152 const body = (await response.json()) as { error: string; message: string };
153 expect(body.error).toBe("invalid_url");
154 expect(body.message).toContain("not a URL this forge will clone from");
155 // What a person meant is what they get.
156 expect(migrateUrl("github.com/a/b")).toBe("https://github.com/a/b");
157 expect(migrateUrl("git://example.com/a/b.git")).toBeUndefined();
158 expect(migrateUrl("https://example.com/a/b.git")).toBe(
159 "https://example.com/a/b.git",
160 );
161 expect(migrateMessage("invalid_url")).toContain("git:// address is not supported");
162 expect(count()).toBe(before);
163 });
164
165 test("a name, an agent or a form that cannot work is refused before anything exists", async () => {
166 const made = await createRepo(app, bob, { name: "taken" });
167 expect(made.ok).toBe(true);
168 const count = () =>
169 (app.db.query("SELECT COUNT(*) AS n FROM repo").get() as { n: number }).n;
170 const before = count();
171 const refused = (input: Parameters<typeof migrateRepo>[2]) =>
172 migrateRepo(app, bob, input).then((r) => (r.ok ? "ok" : r.error));
173 expect(await refused({ source: { url: fixtureUrl }, name: "taken" })).toBe(
174 "name_taken",
175 );
176 expect(
177 await refused({
178 source: { url: fixtureUrl },
179 name: "no spaces allowed",
180 }),
181 ).toBe("invalid_name");
182 expect(
183 await refused({
184 source: { url: fixtureUrl },
185 name: "other",
186 crew: { agent: "nobody-here", autonomous: false },
187 }),
188 ).toBe("no_such_agent");
189
190 // The same refusal on the web: the form again, with the reason in it.
191 const page = await browser(bobCookie, "/migrate", {
192 url: fixtureUrl,
193 owner: "bob",
194 name: "taken",
195 });
196 expect(page.status).toBe(422);
197 expect(await page.text()).toContain(
198 "already has a repository by that name",
199 );
200 const both = await browser(bobCookie, "/migrate", {
201 source: "x/octo/y",
202 url: fixtureUrl,
203 });
204 expect(await both.text()).toContain("not both");
205 expect(count()).toBe(before);
206 });
207
208 test("into an org, a writer who is not its admin is refused before anything exists (#14779)", async () => {
209 const org = createOrg(app.db, "acme-migrate", alice.id);
210 if (!org.ok) throw new Error(org.error);
211 const team = createTeam(app.db, org.value.id, "writers", "write");
212 if (!team.ok) throw new Error(team.error);
213 expect(addTeamMember(app.db, team.value, bob.id)).toBe(true);
214 const count = () => (app.db.query("SELECT COUNT(*) AS n FROM repo").get() as { n: number }).n;
215 const before = count();
216 const started = await migrateRepo(app, bob, { source: { url: fixtureUrl }, owner: "acme-migrate", name: "pulled-in" });
217 expect(started.ok ? "ok" : started.error).toBe("owner_admin");
218 expect(migrateMessage("owner_admin")).toContain("Only that organization's admins");
219 expect(count()).toBe(before);
220 const response = await api(bobCookie, { source: { url: fixtureUrl }, owner: "acme-migrate", name: "pulled-in" });
221 expect(response.status).toBe(403);
222 expect(count()).toBe(before);
223 });
224
225 test("a clone that fails leaves nothing behind", async () => {
226 const job = await migrate(bob, {
227 source: { url: `${base}/alice/hidden.git` },
228 });
229 expect(job?.stage).toBe("failed");
230 expect(job?.error).toContain("could not be read");
231 expect(getRepo(app.db, "bob", "hidden")).toBeUndefined();
232 expect(existsSync(repoDir(app.reposRoot, "bob", "hidden"))).toBe(false);
233 });
234 });
test/migrate.test.ts deleted −1610
@@ -1,1610 +0,0 @@
1 /**
2 * Migrate, end to end: a repository brought here for good.
3 *
4 * The fixture is a real repository on a real forge — several branches, a
5 * lightweight and an annotated tag, a default branch that is not `main` —
6 * and the migration speaks real smart HTTP to it. What must hold: the whole
7 * history arrives (`git log --all` matches, every ref matches), the new
8 * repository is native (no origin, no remote configured, pushes land here
9 * and nowhere else), a refusal is words before anything exists, a failed
10 * clone leaves nothing behind, and a crew put on it is on it: on the crew,
11 * the repository an app, one issue carrying the importer's brief.
12 */
13
14 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
15 import { migrationOrigin } from "../src/apps/migration_mode.ts";
16 import { existsSync } from "node:fs";
17 import { mkdtemp, rm } from "node:fs/promises";
18 import { tmpdir } from "node:os";
19 import { join } from "node:path";
20 import { createApp, type App } from "../src/app.ts";
21 import {
22 isPrivateHost,
23 migrateRepo,
24 fetchEnv,
25 migrateMessage,
26 resolveSource,
27 sameOriginHost,
28 vetClone,
29 migrateUrl,
30 } from "../src/actions/migrate.ts";
31 import { createAgent, listCrew } from "../src/actions/crew.ts";
32 import { connectOrigin } from "../src/actions/origins.ts";
33 import { getPull, pullStatus } from "../src/core/pulls.ts";
34 import { pullMayRun } from "../src/core/pull_trust.ts";
35 import { approveHere } from "../src/actions/pulls.ts";
36 import { labelsFor, listComments } from "../src/core/issues.ts";
37 import { backlink } from "../src/origins/carry.ts";
38 import { formatKib, matchesFilter } from "../src/web/pages/migrate.ts";
39 import {
40 commitToBranch,
41 createRepo,
42 updateRepoSettings,
43 } from "../src/actions/repos.ts";
44 import { getAppByRepo } from "../src/core/apps.ts";
45 import { listIssues } from "../src/core/issues.ts";
46 import { listOrigins } from "../src/core/origins.ts";
47 import {
48 getProvenance,
49 recordProvenance,
50 setProvenanceShown,
51 } from "../src/core/provenance.ts";
52 import { getRepo, type Repo } from "../src/core/repos.ts";
53 import { addTeamMember, createOrg, createTeam } from "../src/core/orgs.ts";
54 import { createUser, type User } from "../src/core/users.ts";
55 import { repoDir } from "../src/git/repos.ts";
56 import { serve, type Servers } from "../src/http/server.ts";
57 import { createToken } from "../src/core/tokens.ts";
58 import { createSession } from "../src/core/sessions.ts";
59 import { advance, createJob, settled } from "../src/origins/jobs.ts";
60 import { getFollow } from "../src/core/upstream_follow.ts";
61 import { forgetProviders } from "../src/origins/providers/index.ts";
62 import {
63 newFakeOAuth,
64 newFakeState,
65 serveFakeForge,
66 type FakeForge,
67 } from "./fake-origin.ts";
68 import { gitClientEnv } from "./helpers/git-client.ts";
69 import { STAGE_BADGE_JS } from "../src/web/stage-row.ts";
70 import { prefill } from "../src/web/pages/migrate-prefill.ts";
71 import { exemptOrigin } from "../src/origins/origin_fetch.ts";
72 import { quietLogs } from "./helpers/globals.ts";
73 import { promote } from "./helpers/members.ts";
74 import { withScripts } from "./helpers/page-script.ts";
75
76 quietLogs();
77
78 async function git(args: string[], cwd: string) {
79 const proc = Bun.spawn(["git", ...args], {
80 cwd,
81 env: gitClientEnv(),
82 stdout: "pipe",
83 stderr: "pipe",
84 });
85 const [out, err, code] = await Promise.all([
86 new Response(proc.stdout).text(),
87 new Response(proc.stderr).text(),
88 proc.exited,
89 ]);
90 return { code, out: out.trim(), err: err.trim() };
91 }
92
93 /** Every commit reachable from any ref, as a sorted list. */
94 async function allCommits(dir: string): Promise<string[]> {
95 return (await git(["log", "--all", "--format=%H"], dir)).out
96 .split("\n")
97 .sort();
98 }
99
100 /** Every branch and tag with the object it names. */
101 async function allRefs(dir: string): Promise<string> {
102 return (
103 await git(
104 [
105 "for-each-ref",
106 "--format=%(refname) %(objectname)",
107 "refs/heads",
108 "refs/tags",
109 ],
110 dir,
111 )
112 ).out;
113 }
114
115 describe("migrate", () => {
116 let dataDir: string;
117 let work: string;
118 let app: App;
119 let servers: Servers;
120 let forgejo: FakeForge;
121 let base: string;
122 /** The fake origin, which passes git on to this forge: a clone address names it (#14756). */
123 let originBase: string;
124 let alice: User;
125 let bob: User;
126 let aliceCookie = "";
127 let bobCookie = "";
128 let bobToken = "";
129 let fixtureUrl = "";
130 let originId = "";
131 let octo: User;
132 // octo's credential at the "upstream": a token, since a password would
133 // cost an argon2 verify on every git request.
134 let upstreamSecret = "";
135
136 const person = async (
137 username: string,
138 adminIfFirst = false,
139 ): Promise<User> => {
140 const made = await createUser(app.db, {
141 origin: "seed",
142 trusted: true,
143 username,
144 email: `${username}@forge.test`,
145 adminIfFirst,
146 });
147 if (!made.ok) throw new Error(String(made.error));
148 promote(app.db, made.value);
149 return made.value;
150 };
151
152 const cookieOf = (user: User): string =>
153 `forge_session=${createSession(app.db, user.id).token}`;
154
155 const browser = (
156 cookie: string,
157 path: string,
158 form?: Record<string, string>,
159 origin?: string,
160 ): Promise<Response> =>
161 fetch(`${base}${path}`, {
162 method: form === undefined ? "GET" : "POST",
163 headers: {
164 cookie,
165 ...(form === undefined
166 ? {}
167 : { origin: origin ?? new URL(base).origin }),
168 },
169 redirect: "manual",
170 ...(form === undefined ? {} : { body: new URLSearchParams(form) }),
171 });
172
173 /** The same call with a bearer token: no cookie, no origin header. */
174 const apiToken = (token: string, payload: unknown): Promise<Response> =>
175 fetch(`${base}/api/v1/migrate`, {
176 method: "POST",
177 headers: {
178 "content-type": "application/json",
179 authorization: `Bearer ${token}`,
180 },
181 body: JSON.stringify(payload),
182 });
183
184 const api = (cookie: string, payload: unknown): Promise<Response> =>
185 fetch(`${base}/api/v1/migrate`, {
186 method: "POST",
187 headers: {
188 "content-type": "application/json",
189 cookie,
190 origin: new URL(base).origin,
191 },
192 body: JSON.stringify(payload),
193 });
194
195 /** Start a migration and wait for it; the job is returned as it ended. */
196 const migrate = async (
197 user: User,
198 input: Parameters<typeof migrateRepo>[2],
199 ) => {
200 const started = await migrateRepo(app, user, input);
201 if (!started.ok) throw new Error(started.error);
202 return settled(started.value.job.id);
203 };
204
205 beforeAll(async () => {
206 dataDir = await mkdtemp(join(tmpdir(), "forge-migrate-"));
207 work = await mkdtemp(join(tmpdir(), "forge-migrate-work-"));
208 // The fixture's source is the forge itself, on loopback: a private host,
209 // which a personal forge may say is fine. Its hook socket is what a
210 // real push needs; no argon2 per request (sessions and tokens, not
211 // passwords).
212 app = createApp({ dataDir, port: 0, migrateFromPrivateHosts: true });
213 servers = await serve(app);
214 base = `http://127.0.0.1:${servers.port}`;
215 // No passwords: argon2 is the slow part of an account, and every
216 // request here rides a session or a token.
217 alice = await person("alice", true);
218 bob = await person("bob");
219 octo = await person("octo");
220 upstreamSecret = createToken(app.db, octo.id, "upstream", "rw").token;
221 aliceCookie = cookieOf(alice);
222 bobCookie = cookieOf(bob);
223 bobToken = createToken(app.db, bob.id, "cli", "rw").token;
224
225 // The fixture: alice's public repository with three branches, two tags
226 // (one annotated), and `trunk` as its default — not the forge's `main`.
227 const made = await createRepo(app, alice, {
228 name: "fixture",
229 visibility: "public",
230 });
231 if (!made.ok) throw new Error(made.error);
232 const fixture = made.value;
233 const commit = async (
234 user: User,
235 repo: Repo,
236 branch: string,
237 path: string,
238 message: string,
239 ) => {
240 const done = await commitToBranch(app, user, repo, {
241 branch,
242 message,
243 files: [{ path, content: `${message}\n` }],
244 });
245 if (!done.ok) throw new Error(String(done.error));
246 };
247 await commit(alice, fixture, "main", "README.md", "first");
248 await commit(alice, fixture, "main", "a.txt", "second");
249 await commit(alice, fixture, "trunk", "trunk.txt", "on trunk");
250 await commit(alice, fixture, "feature", "feature.txt", "a feature");
251 await commit(alice, fixture, "feature", "feature2.txt", "more feature");
252 const settings = await updateRepoSettings(app, alice, fixture, {
253 defaultBranch: "trunk",
254 });
255 if (!settings.ok) throw new Error(settings.error);
256 const dir = repoDir(app.reposRoot, "alice", "fixture");
257 expect((await git(["tag", "v1", "main~1"], dir)).code).toBe(0);
258 expect(
259 (await git(["tag", "-a", "v2", "-m", "the second", "feature"], dir)).code,
260 ).toBe(0);
261 fixtureUrl = `${base}/alice/fixture.git`;
262
263 // A repository alice keeps private: no anonymous clone reaches it.
264 const hidden = await createRepo(app, alice, {
265 name: "hidden",
266 visibility: "private",
267 });
268 if (!hidden.ok) throw new Error(hidden.error);
269 await commit(alice, hidden.value, "main", "README.md", "secret");
270
271 // A private repository behind a fake origin whose clone URL points at
272 // it: only the origin's credential (octo's) opens it.
273 const widgets = await createRepo(app, octo, {
274 name: "secret-widgets",
275 visibility: "private",
276 });
277 if (!widgets.ok) throw new Error(widgets.error);
278 await commit(octo, widgets.value, "main", "README.md", "first");
279 const state = newFakeState("forgejo", "octo", upstreamSecret);
280 forgejo = serveFakeForge(state);
281 state.gitAt = base;
282 originBase = forgejo.url;
283 state.repos.push({
284 id: 77,
285 fullName: "octo/secret-widgets",
286 description: "gears, privately",
287 cloneUrl: `${originBase}/octo/secret-widgets.git`,
288 htmlUrl: `${base}/octo/secret-widgets`,
289 defaultBranch: "main",
290 private: true,
291 });
292 // A public fork on the origin, whose host says what it forks (#3293).
293 state.repos.push({
294 id: 78,
295 fullName: "octo/arm",
296 description: "an arm, forked",
297 cloneUrl: `${originBase}/octo/secret-widgets.git`,
298 htmlUrl: "https://code.example/octo/arm",
299 defaultBranch: "main",
300 fork: true,
301 parent: "TheRobotStudio/arm",
302 });
303 // A private fork: its name is not ours to publish, whatever it becomes.
304 state.repos.push({
305 id: 79,
306 fullName: "octo/hush",
307 description: "a quiet fork",
308 cloneUrl: `${originBase}/octo/secret-widgets.git`,
309 htmlUrl: "https://code.example/octo/hush",
310 defaultBranch: "main",
311 private: true,
312 fork: true,
313 parent: "TheRobotStudio/hush",
314 });
315 // An origin's reply naming a clone address on another host: the
316 // metadata service, as an attacker's own Forgejo would (#14756).
317 state.repos.push({
318 id: 80,
319 fullName: "octo/elsewhere",
320 description: "",
321 cloneUrl: "http://169.254.169.254/internal/secret.git",
322 htmlUrl: "https://code.example/octo/elsewhere",
323 defaultBranch: "main",
324 private: false,
325 });
326 forgetProviders(dataDir);
327 const connected = await browser(aliceCookie, "/settings/origins/token", {
328 host: forgejo.url,
329 token: upstreamSecret,
330 });
331 expect(connected.status).toBe(303);
332 originId = listOrigins(app.db, alice.id)[0]!.id;
333 }, 30_000);
334
335 afterAll(async () => {
336 forgejo.stop();
337 servers.stop();
338 app.close();
339 forgetProviders(dataDir);
340 for (const dir of [dataDir, work])
341 await rm(dir, { recursive: true, force: true });
342 });
343
344 test("by URL: the whole history arrives in a native repository, and pushes stay here", async () => {
345 const sourceDir = repoDir(app.reposRoot, "alice", "fixture");
346 const sourceRefs = await allRefs(sourceDir);
347
348 // By token, so the non-cookie door to the endpoint stays covered.
349 const response = await apiToken(bobToken, { source: { url: fixtureUrl } });
350 expect(response.status).toBe(202);
351 const started = (await response.json()) as {
352 repo: { name: string };
353 job: { id: string };
354 };
355 expect(started.repo.name).toBe("fixture");
356 const job = await settled(started.job.id);
357 expect(job?.error).toBeUndefined();
358 expect(job?.stage).toBe("done");
359 expect(job?.detail).toContain("3 branches, 2 tags");
360
361 const migrated = getRepo(app.db, "bob", "fixture")!;
362 // Where it came from is kept as a link, the `.git` dropped; a plain
363 // http host on loopback is not asked what it forks (#3293).
364 expect(getProvenance(app.db, migrated.id)).toMatchObject({
365 sourceUrl: `${base}/alice/fixture`,
366 parents: [],
367 shown: true,
368 });
369 const dir = repoDir(app.reposRoot, "bob", "fixture");
370 // Every commit, every branch, every tag — the annotated one as itself.
371 expect(await allCommits(dir)).toEqual(await allCommits(sourceDir));
372 expect(await allRefs(dir)).toBe(sourceRefs);
373 expect((await git(["cat-file", "-t", "refs/tags/v2"], dir)).out).toBe(
374 "tag",
375 );
376 // The source's default branch is kept.
377 expect(migrated.defaultBranch).toBe("trunk");
378 expect((await git(["symbolic-ref", "HEAD"], dir)).out).toBe(
379 "refs/heads/trunk",
380 );
381 // Native: no origin row, no remote in its config — nothing a push could
382 // write through to, so pushes land here and the source never hears.
383 expect(migrated.origin).toBeNull();
384 expect((await git(["config", "--get-regexp", "^remote\\."], dir)).out).toBe(
385 "",
386 );
387
388 // A real push lands here, and the source never hears of it.
389 const clone = join(work, "bob-fixture");
390 const url = new URL(`${base}/bob/fixture.git`);
391 url.username = "bob";
392 url.password = bobToken;
393 expect(
394 (await git(["clone", "--quiet", url.toString(), clone], work)).code,
395 ).toBe(0);
396 await Bun.write(join(clone, "bob.txt"), "mine now\n");
397 expect((await git(["add", "."], clone)).code).toBe(0);
398 expect((await git(["commit", "-qm", "bob's change"], clone)).code).toBe(0);
399 const pushed = await git(
400 ["push", "--quiet", "origin", "HEAD:refs/heads/bobs"],
401 clone,
402 );
403 expect(pushed.err).toBe("");
404 expect(pushed.code).toBe(0);
405 expect(
406 (await git(["rev-parse", "--verify", "refs/heads/bobs"], dir)).code,
407 ).toBe(0);
408 expect(await allRefs(sourceDir)).toBe(sourceRefs);
409 });
410
411 test("a URL git must not run is refused in words before anything exists", async () => {
412 const count = () =>
413 (app.db.query("SELECT COUNT(*) AS n FROM repo").get() as { n: number }).n;
414 const before = count();
415 // What a hostile URL would touch if git ever ran it: a path of this
416 // test's own.
417 const canary = join(work, "touched-by-git");
418 for (const url of [
419 "file:///etc",
420 `ext::sh -c touch% ${canary}`,
421 "ssh://[email protected]/a/b.git",
422 "[email protected]:a/b.git",
423 `--upload-pack=touch ${canary}`,
424 "https://user:[email protected]/a/b.git",
425 "",
426 ])
427 expect(await migrateRepo(app, bob, { source: { url } })).toEqual({
428 ok: false,
429 error: "invalid_url",
430 });
431 expect(existsSync(canary)).toBe(false);
432 // On the wire it is a 422 with words.
433 const response = await api(bobCookie, { source: { url: "file:///etc" } });
434 expect(response.status).toBe(422);
435 const body = (await response.json()) as { error: string; message: string };
436 expect(body.error).toBe("invalid_url");
437 expect(body.message).toContain("not a URL this forge will clone from");
438 // What a person meant is what they get.
439 expect(migrateUrl("github.com/a/b")).toBe("https://github.com/a/b");
440 expect(migrateUrl("git://example.com/a/b.git")).toBeUndefined();
441 expect(migrateUrl("https://example.com/a/b.git")).toBe(
442 "https://example.com/a/b.git",
443 );
444 expect(migrateMessage("invalid_url")).toContain("git:// address is not supported");
445 expect(count()).toBe(before);
446 });
447
448 test("a name, an agent or a form that cannot work is refused before anything exists", async () => {
449 const made = await createRepo(app, bob, { name: "taken" });
450 expect(made.ok).toBe(true);
451 const count = () =>
452 (app.db.query("SELECT COUNT(*) AS n FROM repo").get() as { n: number }).n;
453 const before = count();
454 const refused = (input: Parameters<typeof migrateRepo>[2]) =>
455 migrateRepo(app, bob, input).then((r) => (r.ok ? "ok" : r.error));
456 expect(await refused({ source: { url: fixtureUrl }, name: "taken" })).toBe(
457 "name_taken",
458 );
459 expect(
460 await refused({
461 source: { url: fixtureUrl },
462 name: "no spaces allowed",
463 }),
464 ).toBe("invalid_name");
465 expect(
466 await refused({
467 source: { url: fixtureUrl },
468 name: "other",
469 crew: { agent: "nobody-here", autonomous: false },
470 }),
471 ).toBe("no_such_agent");
472
473 // The same refusal on the web: the form again, with the reason in it.
474 const page = await browser(bobCookie, "/migrate", {
475 url: fixtureUrl,
476 owner: "bob",
477 name: "taken",
478 });
479 expect(page.status).toBe(422);
480 expect(await page.text()).toContain(
481 "already has a repository by that name",
482 );
483 const both = await browser(bobCookie, "/migrate", {
484 source: "x/octo/y",
485 url: fixtureUrl,
486 });
487 expect(await both.text()).toContain("not both");
488 expect(count()).toBe(before);
489 });
490
491 test("into an org, a writer who is not its admin is refused before anything exists (#14779)", async () => {
492 const org = createOrg(app.db, "acme-migrate", alice.id);
493 if (!org.ok) throw new Error(org.error);
494 const team = createTeam(app.db, org.value.id, "writers", "write");
495 if (!team.ok) throw new Error(team.error);
496 expect(addTeamMember(app.db, team.value, bob.id)).toBe(true);
497 const count = () => (app.db.query("SELECT COUNT(*) AS n FROM repo").get() as { n: number }).n;
498 const before = count();
499 const started = await migrateRepo(app, bob, { source: { url: fixtureUrl }, owner: "acme-migrate", name: "pulled-in" });
500 expect(started.ok ? "ok" : started.error).toBe("owner_admin");
501 expect(migrateMessage("owner_admin")).toContain("Only that organization's admins");
502 expect(count()).toBe(before);
503 const response = await api(bobCookie, { source: { url: fixtureUrl }, owner: "acme-migrate", name: "pulled-in" });
504 expect(response.status).toBe(403);
505 expect(count()).toBe(before);
506 });
507
508 test("a clone that fails leaves nothing behind", async () => {
509 const job = await migrate(bob, {
510 source: { url: `${base}/alice/hidden.git` },
511 });
512 expect(job?.stage).toBe("failed");
513 expect(job?.error).toContain("could not be read");
514 expect(getRepo(app.db, "bob", "hidden")).toBeUndefined();
515 expect(existsSync(repoDir(app.reposRoot, "bob", "hidden"))).toBe(false);
516 });
517
518 test("with a crew: on the crew, an app, the importer's brief, autonomy only when asked", async () => {
519 const agent = await createAgent(app, alice, {
520 username: "porter",
521 model: "",
522 brief: "Moves things in.",
523 });
524 expect(agent.ok).toBe(true);
525
526 for (const [name, autonomous] of [
527 ["crewed", true],
528 ["assisted", false],
529 ] as const) {
530 const job = await migrate(bob, {
531 source: { url: fixtureUrl },
532 name,
533 crew: { agent: "porter", autonomous },
534 });
535 expect(job?.error).toBeUndefined();
536 expect(job?.stage).toBe("done");
537 expect(job?.detail).toContain("porter is on it");
538
539 const repo = getRepo(app.db, "bob", name)!;
540 const crew = listCrew(app, bob, repo);
541 expect(crew.ok && crew.value.map((a) => a.user.username)).toEqual([
542 "porter",
543 ]);
544 expect(getAppByRepo(app.db, repo.id)).toBeDefined();
545 expect(repo.autonomy).toBe(autonomous ? "autonomous" : "off");
546 // The source is the upstream it follows: on when autonomous (#3442).
547 const follow = getFollow(app.db, repo.id)!;
548 expect([follow.url, follow.branch, follow.enabled]).toEqual([fixtureUrl, "trunk", autonomous]);
549
550 const issues = listIssues(app.db, repo.id, {
551 kind: "issue",
552 state: "open",
553 });
554 expect(issues.length).toBe(1);
555 const issue = issues[0]!;
556 expect(issue.title).toBe(`Make ${name} run here`);
557 expect(issue.assigneeName).toBe("porter");
558 // The importer's brief is the same whether or not the crew is
559 // autonomous; autonomy is the repository's setting, asserted above.
560 for (const words of [
561 "Adapt, don't rewrite",
562 "forge.json",
563 "`run`",
564 "`health`",
565 "PORT",
566 "FORGE_APP_DATA",
567 "no Dockerfile, no compose",
568 "could not fit",
569 "Its data:",
570 "Leave the old database untouched",
571 "one-shot import script",
572 "dump file in",
573 "how to make the dump",
574 "Never commit or read at boot a connection string",
575 fixtureUrl,
576 ])
577 expect(issue.body).toContain(words);
578 }
579 });
580
581 test("migration mode: the direction is parity with the origin, the brief asks for the checklist, the mode is kept", async () => {
582 const agent = await createAgent(app, alice, { username: "parity", model: "", brief: "Keeps parity." });
583 expect(agent.ok).toBe(true);
584 const job = await migrate(bob, {
585 source: { url: fixtureUrl },
586 name: "inmode",
587 crew: { agent: "parity", autonomous: false, mode: "migration" },
588 });
589 expect(job?.stage).toBe("done");
590 const repo = getRepo(app.db, "bob", "inmode")!;
591 expect(repo.autonomyDirection).toBe(`run natively here with parity to ${fixtureUrl}`);
592 expect(migrationOrigin(app.db, repo.id)).toBe(fixtureUrl);
593 const issue = listIssues(app.db, repo.id, { kind: "issue", state: "open" })[0]!;
594 expect(issue.body).toContain("MIGRATION.md");
595 expect(issue.body).toContain("one issue per unchecked line");
596 // Without the mode, no direction and no row.
597 const plain = await migrate(bob, { source: { url: fixtureUrl }, name: "notmode", crew: { agent: "parity", autonomous: false } });
598 expect(plain?.stage).toBe("done");
599 const other = getRepo(app.db, "bob", "notmode")!;
600 expect(migrationOrigin(app.db, other.id)).toBeUndefined();
601 expect(other.autonomyDirection).not.toContain("parity to");
602 });
603
604 test("from an origin: the origin's credential opens a private repository", async () => {
605 // Anonymous, by URL: refused by the upstream, and nothing left here.
606 const anon = await migrate(alice, {
607 source: { url: `${base}/octo/secret-widgets.git` },
608 });
609 expect(anon?.stage).toBe("failed");
610
611 // Picked from the origin: the header opens it.
612 const response = await api(aliceCookie, {
613 source: { originId, fullName: "octo/secret-widgets" },
614 });
615 expect(response.status).toBe(202);
616 const started = (await response.json()) as { job: { id: string } };
617 const job = await settled(started.job.id);
618 expect(job?.error).toBeUndefined();
619 expect(job?.stage).toBe("done");
620 const migrated = getRepo(app.db, "alice", "secret-widgets")!;
621 expect(migrated.origin).toBeNull();
622 expect(migrated.description).toBe("gears, privately");
623 const dir = repoDir(app.reposRoot, "alice", "secret-widgets");
624 expect((await git(["log", "--format=%s", "main"], dir)).out).toBe("first");
625 // The credential rode in the environment and stayed there.
626 const config = await Bun.file(join(dir, "config")).text();
627 expect(config).not.toContain(upstreamSecret);
628 expect(config).not.toContain("extraHeader");
629
630 // Someone else's origin is not a source.
631 const bobs = await api(bobCookie, {
632 source: { originId, fullName: "octo/secret-widgets" },
633 });
634 expect(((await bobs.json()) as { error: string }).error).toBe(
635 "no_such_origin",
636 );
637 });
638
639 test("a migrated fork shows its trail, and its owner can hide it and bring it back", async () => {
640 const job = await migrate(alice, {
641 source: { originId, fullName: "octo/arm" },
642 visibility: "public",
643 });
644 expect(job?.error).toBeUndefined();
645 const repo = getRepo(app.db, "alice", "arm")!;
646 const lineage = async (cookie: string): Promise<string> => {
647 const page = await (await browser(cookie, "/alice/arm")).text();
648 return /<p class="muted small break" data-lineage>[\s\S]*?<\/p>/.exec(page)?.[0] ?? "";
649 };
650 const shown = await lineage("");
651 expect(shown).toContain("Migrated from");
652 expect(shown).toContain(
653 '<a href="https://code.example/octo/arm" rel="noopener noreferrer">code.example/octo/arm</a>',
654 );
655 expect(shown).toContain("fork of");
656 expect(shown).toContain(
657 '<a href="https://code.example/TheRobotStudio/arm" rel="noopener noreferrer">TheRobotStudio/arm</a>',
658 );
659 const facts = async () =>
660 ((await (await browser("", "/api/v1/repos/alice/arm")).json()) as {
661 provenance: { source: string; parents: { url: string }[] } | null;
662 }).provenance;
663 expect((await facts())?.source).toBe("code.example/octo/arm");
664 expect((await facts())?.parents[0]?.url).toBe(
665 "https://code.example/TheRobotStudio/arm",
666 );
667
668 // Not bob's to hide: he can read it, not administer it.
669 const refused = await browser(bobCookie, "/alice/arm/settings/provenance", {
670 shown: "0",
671 });
672 expect(refused.status).not.toBe(303);
673 expect(getProvenance(app.db, repo.id)?.shown).toBe(true);
674
675 // Off: gone for anyone else and from the API, the record kept.
676 const settings = await (await browser(aliceCookie, "/alice/arm/settings")).text();
677 expect(settings).toContain("Hide where this came from");
678 const off = await browser(aliceCookie, "/alice/arm/settings/provenance", {
679 shown: "0",
680 });
681 expect(off.status).toBe(303);
682 expect(await lineage("")).toBe("");
683 expect(await lineage(bobCookie)).toBe("");
684 expect(await facts()).toBeNull();
685 expect(getProvenance(app.db, repo.id)).toMatchObject({
686 sourceUrl: "https://code.example/octo/arm",
687 parents: ["TheRobotStudio/arm"],
688 shown: false,
689 });
690
691 // On again, by the API this time: back as it was.
692 const on = await fetch(`${base}/api/v1/repos/alice/arm`, {
693 method: "PATCH",
694 headers: {
695 "content-type": "application/json",
696 cookie: aliceCookie,
697 origin: new URL(base).origin,
698 },
699 body: JSON.stringify({ showProvenance: true }),
700 });
701 expect(on.status).toBe(200);
702 expect(await lineage("")).toBe(shown);
703 });
704
705 test("a private source migrated as public keeps its trail hidden until its owner shows it", async () => {
706 const job = await migrate(alice, {
707 source: { originId, fullName: "octo/hush" },
708 visibility: "public",
709 });
710 expect(job?.error).toBeUndefined();
711 const repo = getRepo(app.db, "alice", "hush")!;
712 expect(repo.visibility).toBe("public");
713 const page = await (await browser("", "/alice/hush")).text();
714 expect(page).not.toContain("data-lineage");
715 expect(page).not.toContain("octo/hush");
716 const api = (await (await browser("", "/api/v1/repos/alice/hush")).json()) as {
717 provenance: unknown;
718 };
719 expect(api.provenance).toBeNull();
720 expect(getProvenance(app.db, repo.id)).toMatchObject({
721 sourceUrl: "https://code.example/octo/hush",
722 parents: ["TheRobotStudio/hush"],
723 shown: false,
724 });
725 const settings = await (await browser(aliceCookie, "/alice/hush/settings")).text();
726 expect(settings).toContain("Hidden; the record is kept.");
727 expect(settings.indexOf("nobody else sees it")).toBeGreaterThan(settings.indexOf("data-page-help"));
728 expect(settings).not.toContain("Hide where this came from");
729 expect(settings).toMatch(/<button[^>]*>\s*Show where this came from/);
730
731 // A second record (a re-migration's) leaves the owner's choice alone.
732 setProvenanceShown(app.db, repo.id, true);
733 recordProvenance(app.db, repo.id, {
734 url: "https://code.example/octo/hush",
735 parents: [],
736 shown: false,
737 });
738 expect(getProvenance(app.db, repo.id)?.shown).toBe(true);
739 });
740
741 test("one click from GitHub: the repository, 3 issues, 1 open pull request and a crew run on the app", async () => {
742 // Upstream: a private repository with a branch an open pull stands on.
743 const made = await createRepo(app, octo, {
744 name: "gadgets",
745 visibility: "private",
746 });
747 if (!made.ok) throw new Error(made.error);
748 for (const [branch, path] of [
749 ["main", "README.md"],
750 ["fix-typo", "typo.txt"],
751 ] as const) {
752 const done = await commitToBranch(app, octo, made.value, {
753 branch,
754 message: `on ${branch}`,
755 files: [{ path, content: "x\n" }],
756 });
757 if (!done.ok) throw new Error(String(done.error));
758 }
759 const upstreamDir = repoDir(app.reposRoot, "octo", "gadgets");
760 const headSha = (await git(["rev-parse", "fix-typo"], upstreamDir)).out;
761
762 // A fake GitHub API in front of it, seeded: 3 issues (one closed, one
763 // with a comment), 1 open pull request, and 1 closed one that stays.
764 const state = newFakeState("github", "octo", upstreamSecret);
765 const github = serveFakeForge(state);
766 // Git through the fake origin itself: a clone address names the origin (#14756).
767 state.gitAt = base;
768 state.repos.push({
769 id: 501,
770 fullName: "octo/gadgets",
771 description: "small machines",
772 cloneUrl: `${github.url}/octo/gadgets.git`,
773 htmlUrl: "https://github.com/octo/gadgets",
774 defaultBranch: "main",
775 private: true,
776 sizeKb: 2048,
777 });
778 state.labels.set("octo/gadgets", [{ id: 9, name: "bug", color: "d73a4a" }]);
779 state.issues.set("octo/gadgets", [
780 { id: 601, number: 1, title: "Crashes on start", body: "Stack trace.", user: "mona", labels: ["bug"], commentCount: 1 },
781 { id: 602, number: 2, title: "An old thing", user: "hubot", state: "closed", closedAt: "2026-01-02T00:00:00Z" },
782 { id: 603, number: 3, title: "Write the docs", user: "mona" },
783 {
784 id: 604,
785 number: 4,
786 title: "Fix the typo",
787 body: "One letter.",
788 user: "octocat",
789 pull: { base: "main", head: "fix-typo", headRepo: "octo/gadgets", headSha },
790 },
791 {
792 id: 605,
793 number: 5,
794 title: "Turned down",
795 user: "octocat",
796 state: "closed",
797 pull: { base: "main", head: "nope", headRepo: "octo/gadgets" },
798 },
799 ]);
800 state.comments.set("octo/gadgets", [
801 { id: 701, issueNumber: 1, body: "Same here.", user: "hubot" },
802 ]);
803 try {
804 forgetProviders(dataDir);
805 const connected = await connectOrigin(app, alice, {
806 host: github.url,
807 kind: "github",
808 token: upstreamSecret,
809 });
810 if (!connected.ok) throw new Error(JSON.stringify(connected.error));
811 const agent = await createAgent(app, alice, {
812 username: "mover",
813 model: "",
814 brief: "Moves things in.",
815 });
816 expect(agent.ok).toBe(true);
817
818 // The picker: a row, marked private, sized, with its one button —
819 // and the account it came through can be disconnected from here.
820 const html = await (await browser(aliceCookie, "/migrate")).text();
821 const row = new RegExp(`name="pick"\\s+value="(${connected.value.id}/octo/gadgets)"`).exec(html);
822 expect(row).not.toBeNull();
823 expect(html).toContain("2.0 MiB");
824 expect(html).toContain("Migrate with the crew");
825 expect(html).toContain(`action="/settings/origins/${connected.value.id}/delete"`);
826 expect(html).toContain('name="then" value="migrate"');
827
828 // The filter narrows the rows on the server too (no script needed).
829 const filtered = await (await browser(aliceCookie, "/migrate?q=nothing-like-it")).text();
830 expect(filtered).not.toContain('value="' + row![1] + '"');
831
832 // One click: the row's button and the form's fields as they stood.
833 const posted = await browser(aliceCookie, "/migrate", {
834 pick: row![1]!,
835 url: "",
836 owner: "alice",
837 name: "",
838 visibility: "private",
839 agent: "mover",
840 });
841 expect(posted.status).toBe(303);
842 const where = posted.headers.get("location")!;
843 const job = await settled(where.split("/").pop()!);
844 expect(job?.error).toBeUndefined();
845 expect(job?.stage).toBe("done");
846 expect(job?.detail).toContain("3 issues, 1 open pull request, 1 comment");
847 // It ends at the app: the repository's page is the app's.
848 const landed = await browser(aliceCookie, where);
849 expect(landed.headers.get("location")).toBe("/alice/gadgets");
850
851 const repo = getRepo(app.db, "alice", "gadgets")!;
852 expect(repo.origin).toBeNull();
853 expect(getAppByRepo(app.db, repo.id)).toBeDefined();
854
855 // The issues, open and closed, numbered as they were, by their
856 // GitHub authors, each linking back.
857 const carried = listIssues(app.db, repo.id, { kind: "issue", state: "all" })
858 .filter((i) => i.originAuthor !== null)
859 .sort((a, b) => a.number - b.number);
860 expect(carried.map((i) => [i.number, i.state, i.originAuthor])).toEqual([
861 [1, "open", "mona"],
862 [2, "closed", "hubot"],
863 [3, "open", "mona"],
864 ]);
865 expect(carried[0]!.body).toStartWith(
866 "> Migrated from [octo/gadgets#1](",
867 );
868 expect(carried[0]!.body).toContain("by @mona on GitHub.");
869 expect(carried[0]!.body).toContain("Stack trace.");
870 expect(labelsFor(app.db, carried[0]!.id).map((l) => l.name)).toEqual(["bug"]);
871 const comments = listComments(app.db, carried[0]!.id);
872 expect(comments.map((c) => [c.originAuthor, c.body])).toEqual([
873 ["hubot", "Same here."],
874 ]);
875
876 // One pull request — the open one — native here, on its branch.
877 const pulls = listIssues(app.db, repo.id, { kind: "pull", state: "all" });
878 expect(pulls.map((p) => p.number)).toEqual([4]);
879 const pull = getPull(app.db, repo.id, 4)!;
880 expect(pull.headBranch).toBe("fix-typo");
881 expect(pull.originHeadRepo).toBeNull();
882 expect(pull.body).toContain("by @octocat on GitHub.");
883 const dir = repoDir(app.reposRoot, "alice", "gadgets");
884 expect((await git(["rev-parse", "fix-typo"], dir)).out).toBe(headSha);
885
886 // The crew's brief is the next number, assigned to the agent: the
887 // durable event the dispatcher (`crew/dispatch.ts`, started by
888 // main.ts) queues the first run from.
889 const brief = listIssues(app.db, repo.id, { kind: "issue", state: "open" })
890 .find((i) => i.originAuthor === null)!;
891 expect(brief.number).toBe(5);
892 expect(brief.assigneeName).toBe("mover");
893 const assigned = app.db
894 .query<{ payload: string }, [string]>(
895 "SELECT payload FROM event WHERE repo_id = ?1 AND kind = 'issue.assigned'",
896 )
897 .all(repo.id)
898 .map((e) => JSON.parse(e.payload) as { number: number; agent?: boolean });
899 expect(assigned).toContainEqual(
900 expect.objectContaining({ number: 5, agent: true }),
901 );
902 // And the import said so once, not once per row.
903 const imported = app.db
904 .query<{ n: number }, [string]>(
905 "SELECT count(*) AS n FROM event WHERE repo_id = ?1 AND kind = 'repo.imported'",
906 )
907 .get(repo.id);
908 expect(imported?.n).toBe(1);
909 } finally {
910 github.stop();
911 }
912 });
913
914 test("a pull opened from a fork arrives with its head under refs/pull/<n>/head, waiting for a writer to let it run", async () => {
915 const made = await createRepo(app, octo, { name: "forked-pulls", visibility: "private" });
916 if (!made.ok) throw new Error(made.error);
917 for (const branch of ["main", "their-work"]) {
918 const done = await commitToBranch(app, octo, made.value, {
919 branch,
920 message: `on ${branch}`,
921 files: [{ path: `${branch}.txt`, content: "x\n" }],
922 });
923 if (!done.ok) throw new Error(String(done.error));
924 }
925 // The head lives only where GitHub keeps it: refs/pull/<n>/head.
926 const upstream = repoDir(app.reposRoot, "octo", "forked-pulls");
927 const sha = (await git(["rev-parse", "their-work"], upstream)).out;
928 expect((await git(["update-ref", "refs/pull/6/head", sha], upstream)).code).toBe(0);
929 expect((await git(["branch", "-D", "their-work"], upstream)).code).toBe(0);
930 // A branch of the source's own that happens to be called pull/6.
931 const mainSha = (await git(["rev-parse", "main"], upstream)).out;
932 expect((await git(["branch", "pull/6", "main"], upstream)).code).toBe(0);
933
934 const state = newFakeState("github", "octo", upstreamSecret);
935 const github = serveFakeForge(state);
936 // Git through the fake origin itself: a clone address names the origin (#14756).
937 state.gitAt = base;
938 state.repos.push({
939 id: 801,
940 fullName: "octo/forked-pulls",
941 cloneUrl: `${github.url}/octo/forked-pulls.git`,
942 defaultBranch: "main",
943 private: true,
944 });
945 state.issues.set("octo/forked-pulls", [
946 {
947 id: 806,
948 number: 6,
949 title: "From a fork",
950 user: "stranger",
951 pull: { base: "main", head: "their-work", headRepo: "stranger/forked-pulls", headSha: sha },
952 },
953 ]);
954 try {
955 forgetProviders(dataDir);
956 const connected = await connectOrigin(app, alice, {
957 host: github.url,
958 kind: "github",
959 token: upstreamSecret,
960 });
961 if (!connected.ok) throw new Error(JSON.stringify(connected.error));
962 const job = await migrate(alice, {
963 source: { originId: connected.value.id, fullName: "octo/forked-pulls" },
964 });
965 expect(job?.error).toBeUndefined();
966 expect(job?.detail).toContain(
967 "1 open pull request (1 from forks, waiting for your approval to run here)",
968 );
969 const repo = getRepo(app.db, "alice", "forked-pulls")!;
970 const pull = getPull(app.db, repo.id, 6)!;
971 // Still the stranger's: the head is where the forge keeps pull heads,
972 // the source's own pull/6 branch is untouched, and no push event
973 // carried the stranger's head to a check or a preview.
974 expect(pull.originHeadRepo).toBe("stranger/forked-pulls");
975 const dir = repoDir(app.reposRoot, "alice", "forked-pulls");
976 expect((await git(["rev-parse", "refs/pull/6/head"], dir)).out).toBe(sha);
977 expect((await git(["rev-parse", "refs/heads/pull/6"], dir)).out).toBe(mainSha);
978 const pushed = app.db
979 .query<{ payload: string }, [string]>(
980 "SELECT payload FROM event WHERE repo_id = ?1 AND kind = 'push'",
981 )
982 .all(repo.id)
983 .map((e) => JSON.stringify(JSON.parse(e.payload)));
984 expect(pushed.length).toBe(1);
985 expect(pushed[0]).not.toContain(sha);
986 expect(pushed[0]).not.toContain("refs/pull/");
987 // It runs only once a writer approves this head.
988 const status = await pullStatus(dir, pull);
989 expect(status.headOid).toBe(sha);
990 expect(pullMayRun(app.db, repo, pull, sha)).toBe(false);
991 const approved = await approveHere(app, alice, repo, pull);
992 expect(approved.ok).toBe(true);
993 expect(pullMayRun(app.db, repo, pull, sha)).toBe(true);
994 } finally {
995 github.stop();
996 }
997 });
998
999 test("the app's branch: the person's newest beats the source's default, by URL and from GitHub, and the brief names it", async () => {
1000 // trevato/arm's shape: `main` is the upstream's tree (and the newest
1001 // commit), `workbench` is the person's app, ahead of it.
1002 const upstreamer = await person("upstreamer");
1003 const made = await createRepo(app, upstreamer, { name: "arm", visibility: "public" });
1004 if (!made.ok) throw new Error(made.error);
1005 const put = async (user: User, branch: string, message: string) => {
1006 const done = await commitToBranch(app, user, made.value, {
1007 branch,
1008 message,
1009 files: [{ path: `${message}.txt`, content: "x\n" }],
1010 });
1011 if (!done.ok) throw new Error(String(done.error));
1012 };
1013 // Which tip is newer is the rule's own test (work-branch.test.ts);
1014 // here, whose it is decides.
1015 await put(upstreamer, "main", "upstream-start");
1016 await put(alice, "workbench", "the-app");
1017 await put(upstreamer, "main", "upstream-later");
1018 const upstream = repoDir(app.reposRoot, "upstreamer", "arm");
1019 const mainSha = (await git(["rev-parse", "main"], upstream)).out;
1020 const workSha = (await git(["rev-parse", "workbench"], upstream)).out;
1021 const agent = await createAgent(app, alice, { username: "armer", model: "", brief: "Moves things in." });
1022 expect(agent.ok).toBe(true);
1023 const briefOf = (owner: string, name: string): string =>
1024 listIssues(app.db, getRepo(app.db, owner, name)!.id, { kind: "issue", state: "open" })
1025 .find((i) => i.title === `Make ${name} run here`)!.body;
1026
1027 // By URL, the clone's own authors: alice's branch, not the source's main.
1028 const byUrl = await migrate(alice, {
1029 source: { url: `${base}/upstreamer/arm.git` },
1030 name: "arm-url",
1031 crew: { agent: "armer", autonomous: false },
1032 });
1033 expect(byUrl?.error).toBeUndefined();
1034 expect(byUrl?.detail).toContain("Working on workbench, the branch with your newest commits");
1035 expect(getRepo(app.db, "alice", "arm-url")!.defaultBranch).toBe("workbench");
1036 expect(briefOf("alice", "arm-url")).toContain("The app is on the branch `workbench`");
1037 expect(briefOf("alice", "arm-url")).toContain("open your pull against it");
1038 // Someone with no commits there keeps the source's default.
1039 const theirs = await migrate(bob, { source: { url: `${base}/upstreamer/arm.git` }, name: "arm-bob" });
1040 expect(getRepo(app.db, "bob", "arm-bob")!.defaultBranch).toBe("main");
1041 expect(theirs?.detail).toContain("Working on main, the source's default branch");
1042 // A branch that is not one git would take is refused before anything exists.
1043 const bad = await migrateRepo(app, alice, {
1044 source: { url: `${base}/upstreamer/arm.git` },
1045 name: "arm-bad",
1046 branch: "--upload-pack=x",
1047 });
1048 expect(bad.ok ? "" : bad.error).toBe("invalid_branch");
1049 expect(getRepo(app.db, "alice", "arm-bad")).toBeUndefined();
1050
1051 // From GitHub: the origin says whose each last commit is by login.
1052 const state = newFakeState("github", "octo", upstreamSecret);
1053 const github = serveFakeForge(state);
1054 // Git through the fake origin itself: a clone address names the origin (#14756).
1055 state.gitAt = base;
1056 state.repos.push({
1057 id: 901,
1058 fullName: "octo/arm",
1059 cloneUrl: `${github.url}/upstreamer/arm.git`,
1060 defaultBranch: "main",
1061 private: true,
1062 });
1063 state.branches.set("octo/arm", [
1064 { name: "main", sha: mainSha },
1065 { name: "workbench", sha: workSha },
1066 ]);
1067 state.commits.set("octo/arm", [
1068 { sha: workSha, message: "<b>the app</b>\n\nbody", authorName: "Octo Cat", authorEmail: "[email protected]", login: "octo", date: "2026-10-19T12:00:00Z" },
1069 { sha: mainSha, message: "upstream later", authorName: "Up Streamer", login: "upstreamer", date: "2026-10-20T09:00:00Z" },
1070 ]);
1071 try {
1072 forgetProviders(dataDir);
1073 const connected = await connectOrigin(app, alice, { host: github.url, kind: "github", token: upstreamSecret });
1074 if (!connected.ok) throw new Error(JSON.stringify(connected.error));
1075 const value = `${connected.value.id}/octo/arm`;
1076
1077 // The row links to its branches; the list shows each last commit,
1078 // escaped, newest first, and selects the person's.
1079 const listing = await (await browser(aliceCookie, "/migrate")).text();
1080 expect(listing).not.toContain('id="migrate-branches"');
1081 expect(listing).toContain(`href="/migrate?source=${encodeURIComponent(value)}&amp;branches=1#migrate-branches"`);
1082 // A plain visit with the row selected asks the origin for nothing.
1083 const asking = () => state.requests.filter((r) => r.path.endsWith("/branches") || r.path.endsWith("/commits")).length;
1084 const before = asking();
1085 const plain = await (await browser(aliceCookie, `/migrate?${new URLSearchParams({ source: value })}`)).text();
1086 expect(plain).not.toContain('id="migrate-branches"');
1087 expect(asking()).toBe(before);
1088 const html = await (await browser(aliceCookie, `/migrate?${new URLSearchParams({ source: value, branches: "1" })}`)).text();
1089 // One listing and one commit per branch; a reload within the minute costs none.
1090 expect(asking()).toBe(before + 3);
1091 await browser(aliceCookie, `/migrate?${new URLSearchParams({ source: value, branches: "1" })}`);
1092 expect(asking()).toBe(before + 3);
1093 const rows = [...html.matchAll(/data-branch="([^"]+)"/g)].map((m) => m[1]);
1094 expect(rows).toEqual(["main", "workbench"]);
1095 expect(html).toMatch(/value="workbench"\s+checked/);
1096 expect(html).not.toMatch(/value="main"\s+checked/);
1097 expect(html).toContain("&lt;b&gt;the app&lt;/b&gt;");
1098 expect(html).not.toContain("<b>the app</b>");
1099 expect(html).toMatch(/octo ·\s+<time datetime="2026-10-19T12:00:00(\.000)?Z">2026-10-19<\/time>/);
1100 expect(html).toContain("default there");
1101 // Asked for, another branch is the one selected.
1102 const asked = await (await browser(aliceCookie, `/migrate?${new URLSearchParams({ source: value, branch: "main" })}`)).text();
1103 expect(asked).toMatch(/value="main"\s+checked/);
1104
1105 // The Migrate button carries the branch chosen.
1106 const chosen = await browser(aliceCookie, "/migrate", {
1107 source: value, branch: "main", url: "", owner: "alice", name: "arm-main", visibility: "private", agent: "armer",
1108 });
1109 expect(chosen.status).toBe(303);
1110 const chosenJob = await settled(chosen.headers.get("location")!.split("/").pop()!);
1111 expect(chosenJob?.detail).toContain("Working on main, the branch picked");
1112 expect(getRepo(app.db, "alice", "arm-main")!.defaultBranch).toBe("main");
1113 expect(briefOf("alice", "arm-main")).toContain("The app is on the branch `main` — the branch the person who migrated it picked");
1114
1115 // Another row's button ignores a branch drawn for a different row:
1116 // one click migrates by the rule — here, by the origin's login alone,
1117 // since the clone's author (alice) is not the person connected (octo).
1118 const oneClick = await browser(aliceCookie, "/migrate", {
1119 pick: value, source: "elsewhere/x/y", branch: "main", url: "", owner: "alice", name: "arm-click", visibility: "private", agent: "armer",
1120 });
1121 expect(oneClick.status).toBe(303);
1122 const clickJob = await settled(oneClick.headers.get("location")!.split("/").pop()!);
1123 expect(clickJob?.error).toBeUndefined();
1124 expect(getRepo(app.db, "alice", "arm-click")!.defaultBranch).toBe("workbench");
1125 expect(briefOf("alice", "arm-click")).toContain("The app is on the branch `workbench` — the branch with the newest commits of the person who migrated it");
1126 } finally {
1127 github.stop();
1128 }
1129 }, 30_000);
1130
1131 test("Connect GitHub from /migrate comes back to /migrate, and so does Disconnect; nothing else can be named", async () => {
1132 const state = newFakeState("github", "bobby", "bob-gh-token");
1133 const oauth = newFakeOAuth("migrate-client");
1134 state.oauth = oauth;
1135 const github = serveFakeForge(state);
1136 process.env.FORGE_GITHUB_CLIENT_ID = "migrate-client";
1137 // A stand-in GitHub Enterprise: the operator registers its host, since the
1138 // github.com application never serves another host (#14757).
1139 process.env.FORGE_ORIGIN_CLIENT_ID = `${new URL(github.url).hostname}=migrate-client`;
1140 try {
1141 forgetProviders(dataDir);
1142 const page = await (await browser(bobCookie, "/migrate")).text();
1143 expect(page).toContain('action="/settings/origins/oauth"');
1144 expect(page).toContain("Connect GitHub");
1145 // One filled button on the page: Migrate. Connect is an outline.
1146 expect(page.match(/data-variant="primary"/g)?.length).toBe(1);
1147 expect(page).toMatch(/data-variant="outline"[^>]*>\s*(<svg[\s\S]*?<\/svg>)?\s*Connect GitHub/);
1148
1149 const started = await browser(bobCookie, "/settings/origins/oauth", {
1150 kind: "github",
1151 host: github.url,
1152 then: "migrate",
1153 });
1154 expect(started.status).toBe(303);
1155 const flowPage = started.headers.get("location")!;
1156 expect(flowPage).toMatch(/^\/settings\/origins\/flows\/[^?]+\?then=migrate$/);
1157 const waiting = await (await browser(bobCookie, flowPage)).text();
1158 expect(waiting).toContain("WXYZ-1234");
1159 expect(waiting).toContain("/poll?then=migrate");
1160
1161 oauth.approved = true;
1162 const flowId = flowPage.split("/").pop()!.split("?")[0]!;
1163 const polled = await browser(
1164 bobCookie,
1165 `/settings/origins/flows/${flowId}/poll?then=migrate`,
1166 {},
1167 );
1168 expect(polled.headers.get("location")).toBe("/migrate?connected=1");
1169 const origin = listOrigins(app.db, bob.id).find((o) => o.kind === "github")!;
1170 expect(origin).toBeDefined();
1171
1172 // Connected: the page lists the account and offers Disconnect, not Connect.
1173 const after = await (await browser(bobCookie, "/migrate?connected=1")).text();
1174 expect(after).toContain('id="migrate-connected"');
1175 expect(after).toContain(`action="/settings/origins/${origin.id}/delete"`);
1176 expect(after).not.toContain('action="/settings/origins/oauth"');
1177
1178 // `then` is a word, not an address: anything else goes home.
1179 const steered = await browser(bobCookie, "/settings/origins/oauth", {
1180 kind: "github",
1181 host: github.url,
1182 then: "https://evil.test/",
1183 });
1184 expect(steered.headers.get("location")).not.toContain("then=");
1185
1186 const gone = await browser(bobCookie, `/settings/origins/${origin.id}/delete`, {
1187 then: "migrate",
1188 });
1189 expect(gone.status).toBe(303);
1190 expect(gone.headers.get("location")).toBe("/migrate");
1191 expect(listOrigins(app.db, bob.id).some((o) => o.id === origin.id)).toBe(false);
1192 } finally {
1193 delete process.env.FORGE_GITHUB_CLIENT_ID;
1194 delete process.env.FORGE_ORIGIN_CLIENT_ID;
1195 github.stop();
1196 }
1197 });
1198
1199 test("the picker's pieces: sizes in binary units, a filter on name or description, a backlink that cannot be steered", () => {
1200 expect(formatKib(0)).toBe("");
1201 expect(formatKib(512)).toBe("512 KiB");
1202 expect(formatKib(1536)).toBe("1.5 MiB");
1203 expect(formatKib(20 * 1024)).toBe("20 MiB");
1204 expect(formatKib(3 * 1024 * 1024)).toBe("3.0 GiB");
1205 expect(matchesFilter({ fullName: "octo/Gadgets", description: "" }, "gadg")).toBe(true);
1206 expect(matchesFilter({ fullName: "octo/x", description: "Small machines" }, "MACHINE")).toBe(true);
1207 expect(matchesFilter({ fullName: "octo/x", description: "" }, "y")).toBe(false);
1208
1209 expect(
1210 backlink({ number: 7, author: "mona", htmlUrl: "https://github.com/o/r/issues/7" }, "o/r", "GitHub"),
1211 ).toBe("> Migrated from [o/r#7](https://github.com/o/r/issues/7) by @mona on GitHub.");
1212 // A link that is not http(s) is named, not linked; a login cannot
1213 // smuggle markdown or a mention of someone else.
1214 const hostile = backlink(
1215 { number: 7, author: "x](javascript:alert(1)) @admin", htmlUrl: "javascript:alert(1)" },
1216 "o/r",
1217 "GitHub",
1218 );
1219 expect(hostile).not.toContain("javascript:");
1220 expect(hostile).not.toContain("](");
1221 expect(hostile).toBe("> Migrated from o/r#7 by @xjavascriptalert1admin on GitHub.");
1222 });
1223
1224 test("the page: the form, the plus menu, the job, and who may see it", async () => {
1225 const anonymous = await browser("", "/migrate");
1226 expect(anonymous.status).toBe(303);
1227 expect(anonymous.headers.get("location")).toStartWith("/signin");
1228
1229 const html = await (await browser(aliceCookie, "/migrate")).text();
1230 expect(html).toContain('action="/migrate"');
1231 expect(html).toContain('name="url"');
1232 // Each repository is a row whose button is the form's submitter.
1233 expect(html).toMatch(/name="pick"\s+value="[^"]+\/octo\/secret-widgets"/);
1234 expect(html).toContain("octo/secret-widgets");
1235 expect(html).toContain("Put a crew on it");
1236 expect(html).toContain('name="agent"');
1237 expect(html).toContain('name="autonomous"');
1238 // The "+" menu carries it on every page, beside New repository.
1239 const home = await (await browser(aliceCookie, "/")).text();
1240 expect(home).toContain('href="/migrate"');
1241 expect(home.indexOf('href="/new"')).toBeLessThan(
1242 home.indexOf('href="/migrate"'),
1243 );
1244
1245 // A cross-site post is refused before anything happens.
1246 const forged = await browser(
1247 aliceCookie,
1248 "/migrate",
1249 { url: fixtureUrl, name: "forged" },
1250 "https://evil.test",
1251 );
1252 expect(forged.status).toBe(403);
1253 expect(getRepo(app.db, "alice", "forged")).toBeUndefined();
1254
1255 const posted = await browser(aliceCookie, "/migrate", {
1256 source: "",
1257 url: fixtureUrl,
1258 owner: "alice",
1259 name: "copy",
1260 agent: "porter",
1261 autonomous: "on",
1262 });
1263 expect(posted.status).toBe(303);
1264 const where = posted.headers.get("location")!;
1265 expect(where).toStartWith("/migrate/jobs/");
1266 await settled(where.split("/").pop()!);
1267 // Nobody else watches alice's migration.
1268 expect((await browser(bobCookie, where)).status).toBe(404);
1269 const landed = await browser(aliceCookie, where);
1270 expect(landed.status).toBe(303);
1271 expect(landed.headers.get("location")).toBe("/alice/copy");
1272 const repoPage = await (
1273 await browser(
1274 `${aliceCookie}; ${(landed.headers.get("set-cookie") ?? "").split(";")[0]}`,
1275 "/alice/copy",
1276 )
1277 ).text();
1278 expect(repoPage).toContain("Migrated as alice/copy");
1279 expect(getRepo(app.db, "alice", "copy")?.autonomy).toBe("autonomous");
1280 });
1281
1282 test("the job page follows its stages over the stream, with no meta refresh", async () => {
1283 const follow = async (end: Partial<Parameters<typeof advance>[1]>) => {
1284 const job = createJob("", "octo/streamed", {
1285 kind: "migrate",
1286 actorId: alice.id,
1287 });
1288 const page = await (
1289 await browser(aliceCookie, `/migrate/jobs/${job.id}`)
1290 ).text();
1291 expect(page).not.toContain('http-equiv="refresh"');
1292 expect(page).toContain(`data-job="${job.id}"`);
1293 expect(page).toContain("<noscript>");
1294 expect(page).toContain("Reload");
1295 const streamPath = `/api/v1/migrate/${job.id}/stream`;
1296 // Another person's stream is not found, as their page is.
1297 expect((await browser(bobCookie, streamPath)).status).toBe(404);
1298 const res = await browser(aliceCookie, streamPath);
1299 expect(res.status).toBe(200);
1300 advance(job.id, { stage: "fetching", detail: "receiving 61%" });
1301 advance(job.id, end);
1302 // The stream ends itself on a terminal stage.
1303 const text = await new Response(res.body).text();
1304 return { job, text };
1305 };
1306
1307 const ok = await follow({ stage: "done", detail: "migrated" });
1308 expect(ok.text).toContain("event: migrate.creating");
1309 expect(ok.text).toContain("event: migrate.fetching");
1310 expect(ok.text).toContain("event: migrate.done");
1311
1312 const bad = await follow({ stage: "failed", error: "clone went wrong" });
1313 expect(bad.text).toContain("event: migrate.fetching");
1314 expect(bad.text).toContain("event: migrate.failed");
1315 expect(bad.text).toContain("clone went wrong");
1316 // Failed is a page that stands, with the reason, and no stream of its own.
1317 const stands = await (
1318 await browser(aliceCookie, `/migrate/jobs/${bad.job.id}`)
1319 ).text();
1320 expect(stands).toContain("clone went wrong");
1321 expect(stands).not.toContain("error-note");
1322 expect(stands).toMatch(
1323 /<div class="field" data-invalid>\s*<span class="error" role="alert"[^>]*>clone went wrong/,
1324 );
1325 expect(stands).not.toContain("EventSource");
1326 expect(stands).not.toContain('http-equiv="refresh"');
1327 });
1328
1329 test("a link prefills the form and starts nothing", async () => {
1330 const host = new URL(forgejo.url).host;
1331 expect(host).toContain(":"); // the fake forge has a port; the label would not
1332 const already = getRepo(app.db, "alice", "secret-widgets")?.id;
1333 const get = async (qs: string) =>
1334 (await browser(aliceCookie, `/migrate?${qs}`)).text();
1335
1336 const hit = await get(
1337 new URLSearchParams({ from: `${host}/octo/secret-widgets`, crew: "porter" }).toString(),
1338 );
1339 expect(hit).toMatch(/name="source" value="[^"]+\/octo\/secret-widgets"/);
1340 expect(hit).toMatch(/aria-current="true"/);
1341 expect(hit).toMatch(/<option[^>]*value="porter"[^>]*selected|selected[^>]*value="porter"/);
1342 expect(hit).not.toContain("prefill-unmatched");
1343
1344 const miss = await get(
1345 new URLSearchParams({
1346 from: `other.example/octo/secret-widgets`,
1347 crew: `<script>alert(1)</script>`,
1348 }).toString(),
1349 );
1350 expect(miss).toContain("prefill-unmatched");
1351 expect(miss).toContain("from=other.example/octo/secret-widgets");
1352 expect(miss).not.toContain("<script>alert(1)");
1353 expect(miss).toContain("&lt;script&gt;");
1354 expect(miss).not.toContain('name="source" value=');
1355 expect(miss).not.toContain('aria-current="true"');
1356
1357 // A link starts nothing: no repository, no job.
1358 expect(getRepo(app.db, "alice", "secret-widgets")?.id).toBe(already);
1359 });
1360
1361 test("a pasted address inside the network is an admin's alone, unless the forge says otherwise", async () => {
1362 for (const h of [
1363 "127.0.0.1",
1364 "localhost",
1365 "app.localhost",
1366 "10.1.2.3",
1367 "172.20.0.1",
1368 "192.168.1.9",
1369 "169.254.1.1",
1370 "::1",
1371 "fd00::1",
1372 "0.0.0.0",
1373 "[::ffff:127.0.0.1]",
1374 "::ffff:7f00:1",
1375 "0:0:0:0:0:ffff:7f00:1",
1376 "::FFFF:10.0.0.1",
1377 "[::ffff:c0a8:1]",
1378 "fe80::1",
1379 "[::]",
1380 ])
1381 expect(isPrivateHost(h)).toBe(true);
1382 for (const h of [
1383 "github.com",
1384 "8.8.8.8",
1385 "172.32.0.1",
1386 "git.open-platform.sh",
1387 "2606:4700::1",
1388 "::ffff:8.8.8.8",
1389 "[2001:db8::1]",
1390 ])
1391 expect(isPrivateHost(h)).toBe(false);
1392 // The forge without the personal-forge switch: bob is refused, alice
1393 // (the admin) is not. The flag is flipped in place: this only proves
1394 // anything because migrateRepo reads it on every call, which the
1395 // refusal below (the app was built with it true) fails without.
1396 const config = app.config as { migrateFromPrivateHosts?: boolean };
1397 config.migrateFromPrivateHosts = false;
1398 try {
1399 const refused = await migrateRepo(app, bob, {
1400 source: { url: `${base}/alice/hidden.git` },
1401 });
1402 expect(refused).toEqual({ ok: false, error: "private_host" });
1403 const allowed = await migrateRepo(app, alice, {
1404 source: { url: `${base}/alice/hidden.git` },
1405 name: "peek",
1406 });
1407 expect(allowed.ok).toBe(true);
1408 if (allowed.ok) await settled(allowed.value.job.id);
1409 } finally {
1410 config.migrateFromPrivateHosts = true;
1411 }
1412 });
1413
1414 test("a name that resolves to a private address is refused like the literal", async () => {
1415 const config = app.config as { migrateFromPrivateHosts?: boolean };
1416 config.migrateFromPrivateHosts = false;
1417 try {
1418 const refused = await migrateRepo(app, bob, {
1419 source: { url: "https://looks-public.example/a/b.git" },
1420 resolve: async () => ["10.0.0.5"],
1421 });
1422 expect(refused).toEqual({ ok: false, error: "private_host" });
1423 } finally {
1424 config.migrateFromPrivateHosts = true;
1425 }
1426 });
1427
1428 test("a vetted host is pinned to the vetted address; a trusted one is not", async () => {
1429 const config = app.config as { migrateFromPrivateHosts?: boolean };
1430 config.migrateFromPrivateHosts = false;
1431 try {
1432 const source = { url: "https://looks-public.example/a/b.git" };
1433 const resolved = await resolveSource(app, bob, source, async () => ["93.184.216.34"]);
1434 if (!resolved.ok) throw new Error("expected a resolved source");
1435 const env = fetchEnv(resolved.value, {});
1436 const pins = Object.entries(env).filter(([, v]) => v.startsWith("looks-public.example:443:"));
1437 expect(pins).toEqual([[expect.any(String), "looks-public.example:443:93.184.216.34"]]);
1438 expect(env["GIT_ALLOW_PROTOCOL"]).toBe("https:http");
1439 // A host that does not resolve is not fetched unpinned.
1440 const lost = await resolveSource(app, bob, source, async () => []);
1441 expect(lost).toEqual({ ok: false, error: "unreachable" });
1442 } finally {
1443 config.migrateFromPrivateHosts = true;
1444 }
1445 // No vetting (the caller may reach private hosts), so no pin.
1446 const open = await resolveSource(app, bob, { url: "https://looks-public.example/a/b.git" });
1447 if (!open.ok) throw new Error("expected a resolved source");
1448 expect(Object.values(fetchEnv(open.value, {})).some((v) => v.includes(":443:"))).toBe(false);
1449 });
1450
1451 test("an origin's clone_url on another host is refused before any git runs (#14756)", async () => {
1452 const refused = await resolveSource(app, alice, { originId, fullName: "octo/elsewhere" });
1453 expect(refused).toEqual({ ok: false, error: "foreign_clone_host" });
1454 const job = await migrateRepo(app, alice, {
1455 source: { originId, fullName: "octo/elsewhere" },
1456 });
1457 expect(job).toEqual({ ok: false, error: "foreign_clone_host" });
1458 expect(getRepo(app.db, "alice", "elsewhere")).toBeUndefined();
1459 const origin = { webUrl: "https://code.example", apiUrl: "https://api.code.example/api/v1" };
1460 expect(sameOriginHost("https://code.example/o/r.git", origin)).toBe(true);
1461 expect(sameOriginHost("https://API.code.example/o/r.git", origin)).toBe(true);
1462 expect(sameOriginHost("http://10.0.0.5:3000/o/r.git", origin)).toBe(false);
1463 expect(sameOriginHost("https://code.example.evil/o/r.git", origin)).toBe(false);
1464 // Scheme, host and port, not the name alone.
1465 expect(sameOriginHost("https://code.example:8443/o/r.git", origin)).toBe(false);
1466 expect(sameOriginHost("http://code.example/o/r.git", origin)).toBe(false);
1467 expect(sameOriginHost("https://code.example:443/o/r.git", origin)).toBe(true);
1468 // A password in it, or a scheme that is not http(s), is never the origin's.
1469 expect(sameOriginHost("https://me:[email protected]/o/r.git", origin)).toBe(false);
1470 for (const other of ["file:///etc/passwd", "ssh://code.example/o/r.git", "git://code.example/o/r.git"])
1471 expect(sameOriginHost(other, origin)).toBe(false);
1472 });
1473
1474 test("an origin's clone_url is vetted and pinned as a pasted address is (#14756)", async () => {
1475 const config = app.config as { migrateFromPrivateHosts?: boolean };
1476 config.migrateFromPrivateHosts = false;
1477 // Not an admin: the vetting is for everyone who may not reach inside.
1478 const plain = { ...alice, isAdmin: false };
1479 try {
1480 const at = "https://code.example/octo/x.git";
1481 expect(await vetClone(app, plain, "http://127.0.0.1:3000/x.git")).toEqual({
1482 ok: false,
1483 error: "private_host",
1484 });
1485 expect(await vetClone(app, plain, at, async () => ["10.0.0.5"])).toEqual({
1486 ok: false,
1487 error: "private_host",
1488 });
1489 expect(await vetClone(app, plain, at, async () => ["169.254.169.254"])).toEqual({
1490 ok: false,
1491 error: "private_host",
1492 });
1493 const pinned = await vetClone(app, plain, at, async () => ["93.184.216.34"]);
1494 if (!pinned.ok || pinned.value === undefined) throw new Error("expected a pin");
1495 const env = fetchEnv({ pin: pinned.value }, {});
1496 expect(Object.values(env)).toContain("code.example:443:93.184.216.34");
1497 // The exemption is the operator's word, never the origin's: only the
1498 // environment (FORGE_ORIGIN_ALLOW, or loopback on a dev forge) grants it.
1499 const loop = "http://localhost:3000/x.git";
1500 expect(exemptOrigin(loop, {})).toBe(false);
1501 expect(exemptOrigin("http://169.254.169.254/x.git", { FORGE_DEV: "1" })).toBe(false);
1502 expect(exemptOrigin(loop, { FORGE_DEV: "1" })).toBe(true);
1503 expect(exemptOrigin("https://git.lan/x.git", { FORGE_ORIGIN_ALLOW: "git.lan" })).toBe(true);
1504 // A loopback origin a dev forge let in is cloned as it was connected.
1505 expect(await vetClone(app, plain, "http://127.0.0.1:3000/x.git", undefined, true)).toEqual({
1506 ok: true,
1507 value: undefined,
1508 });
1509 } finally {
1510 config.migrateFromPrivateHosts = true;
1511 }
1512 });
1513
1514 test("a clone follows no redirect: the address that was checked is the only one fetched", async () => {
1515 let hits = 0;
1516 const target = Bun.serve({
1517 port: 0,
1518 hostname: "127.0.0.1",
1519 fetch() {
1520 hits++;
1521 return new Response("here", { status: 200 });
1522 },
1523 });
1524 const hop = Bun.serve({
1525 port: 0,
1526 hostname: "127.0.0.1",
1527 fetch() {
1528 return new Response(null, {
1529 status: 302,
1530 headers: {
1531 location: `http://127.0.0.1:${target.port}/x.git/info/refs?service=git-upload-pack`,
1532 },
1533 });
1534 },
1535 });
1536 try {
1537 const job = await migrate(alice, {
1538 source: { url: `http://127.0.0.1:${hop.port}/hop.git` },
1539 name: "hopped",
1540 });
1541 expect(job?.stage).toBe("failed");
1542 expect(hits).toBe(0);
1543 } finally {
1544 hop.stop(true);
1545 target.stop(true);
1546 }
1547 });
1548
1549 test("the job page draws each stage as a row with a state badge, and no stage-dot", async () => {
1550 const job = createJob("", "octo/rows", { kind: "migrate", actorId: alice.id });
1551 advance(job.id, { stage: "fetching", detail: "receiving 61%" });
1552 const page = await (await browser(aliceCookie, `/migrate/jobs/${job.id}`)).text();
1553 expect(page).not.toContain("stage-dot");
1554 expect(page).not.toContain("stage-detail");
1555 // The page's script is built from the table the rows are drawn from.
1556 expect(await withScripts(servers.url, page)).toContain(`var badges = ${STAGE_BADGE_JS};`);
1557 expect(page).toMatch(/<li data-stage-name="creating" data-state="done">[\s\S]*?class="row"[\s\S]*?>Done</);
1558 expect(page).toMatch(/data-stage-name="fetching" data-state="now">[\s\S]*?receiving 61%[\s\S]*?>Running</);
1559 expect(page).toMatch(/data-stage-name="crew" data-state="todo">[\s\S]*?>Waiting</);
1560 expect(page).toMatch(/<ol class="list stages" aria-live="polite">/);
1561 // Every stage has a `.row-meta` for the live update to write into.
1562 const items = page.match(/<li data-stage-name=[\s\S]*?<\/li>/g) ?? [];
1563 expect(items.length).toBeGreaterThan(0);
1564 for (const li of items) expect(li).toContain('class="row-meta"');
1565 });
1566
1567 test("mark the stage it failed on, and keep the earlier ones done", async () => {
1568 const job = createJob("", "octo/broke", { kind: "migrate", actorId: alice.id });
1569 advance(job.id, { stage: "fetching", detail: "receiving 3%" });
1570 advance(job.id, { stage: "failed", error: "clone went wrong" });
1571 const page = await (await browser(aliceCookie, `/migrate/jobs/${job.id}`)).text();
1572 expect(page).toMatch(/data-stage-name="creating" data-state="done"/);
1573 expect(page).toMatch(/data-stage-name="fetching" data-state="failed">[\s\S]*?data-variant="danger"\s*>Failed</);
1574 expect(page).toMatch(/data-stage-name="crew" data-state="todo"/);
1575 });
1576 });
1577
1578 describe("migrate prefill", () => {
1579 const origins = [
1580 { id: "o1", host: "git.example.test:3000", repos: [{ fullName: "Octo/Widgets" }] },
1581 { id: "o2", host: "git.open-platform.sh", repos: [{ fullName: "trevato/forge" }] },
1582 ];
1583 const agents = ["porter", "scout"];
1584
1585 test("a host with a port, and one without", () => {
1586 expect(prefill({ from: "git.example.test:3000/octo/widgets" }, origins, agents).repo).toEqual({
1587 originId: "o1",
1588 fullName: "Octo/Widgets",
1589 });
1590 const plain = prefill({ from: "GIT.open-platform.sh/trevato/forge", crew: "scout" }, origins, agents);
1591 expect(plain.repo?.originId).toBe("o2");
1592 expect(plain.agent).toBe("scout");
1593 expect(plain.unmatched).toEqual([]);
1594 });
1595
1596 test("a mismatch is named, never guessed (not the display label)", () => {
1597 const r = prefill({ from: "git/trevato/forge", crew: "nobody" }, origins, agents);
1598 expect(r.repo).toBeUndefined();
1599 expect(r.agent).toBeUndefined();
1600 expect(r.unmatched).toEqual(["from=git/trevato/forge", "crew=nobody"]);
1601 expect(prefill({ from: "git.example.test/octo/widgets" }, origins, agents).repo).toBeUndefined();
1602 });
1603
1604 test("a hostile or oversized value is ignored and capped", () => {
1605 const r = prefill({ from: "<img src=x onerror=1>/a/b", crew: "x".repeat(500) }, origins, agents);
1606 expect(r.repo).toBeUndefined();
1607 expect(r.unmatched).toHaveLength(2);
1608 expect(r.unmatched.every((u) => u.length < 100)).toBe(true);
1609 });
1610 });
test/studio-door-app-state.test.ts added +623
@@ -0,0 +1,623 @@
1 /**
2 * The studio, one door of it: the app's live fragment, /:owner/:name/app/state. Split from
3 * studio-door.test.ts so each door runs on its own forge from test/support/studio-forge.ts
4 * (#15351); the rest of the studio's suite is test/studio*.test.ts.
5 */
6
7 import { afterAll, beforeAll, beforeEach, describe, expect, test } from "bun:test";
8 import { enableApp } from "../src/actions/apps.ts";
9 import { previewEnv } from "../src/apps/data.ts";
10 import { getAppByRepo, type AppRecord } from "../src/core/apps.ts";
11 import { mergePull, openPull } from "../src/actions/pulls.ts";
12 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
13 import type { Repo } from "../src/core/repos.ts";
14 import { claimRun, createRun, finishRun, getRun, markServing } from "../src/core/runs.ts";
15 import { liveClientJs } from "../src/web/live.ts";
16 import { getUserByName } from "../src/core/users.ts";
17 import { startStudioForge, type StudioForge } from "./support/studio-forge.ts";
18
19 let forge: StudioForge;
20 let app: StudioForge["app"];
21 let base: StudioForge["base"];
22 let signIn: StudioForge["signIn"];
23 let putEnv: StudioForge["putEnv"];
24 let clearEnvs: StudioForge["clearEnvs"];
25
26 beforeAll(async () => {
27 forge = await startStudioForge();
28 ({ app, base, signIn, putEnv, clearEnvs } = forge);
29 });
30
31 afterAll(() => forge.stop());
32
33 /**
34 * GET /:owner/:name/app/state — the fragment the studio page's live client
35 * fetches on a deploy run event, and swaps into `#app-head`/`#app-previews`
36 * in place of a reload. It is authorized exactly as the studio page, and
37 * renders from the same `appPanels` function the page's first paint does.
38 */
39 describe("the app's live fragment: /:owner/:name/app/state", () => {
40 let repo: Repo;
41 let record: AppRecord;
42 let owner: string;
43 let stranger: string;
44
45 const get = (path: string, cookie: string) =>
46 fetch(`${base}${path}`, {
47 headers: { cookie: `${cookie}; forge_mode=studio` },
48 redirect: "manual",
49 });
50
51 beforeAll(async () => {
52 const alice = getUserByName(app.db, "alice")!;
53 owner = await signIn("alice");
54 stranger = await signIn("carol");
55 const made = await createRepo(app, alice, {
56 name: "vault",
57 visibility: "private",
58 description: "",
59 });
60 if (!made.ok) throw new Error(String(made.error));
61 repo = made.value;
62 const seeded = await commitToBranch(app, alice, repo, {
63 message: "Start",
64 files: [{ path: "README.md", content: "v\n" }],
65 });
66 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
67 const enabled = await enableApp(app, alice, repo, { slug: "vault" });
68 if (!enabled.ok) throw new Error(String(enabled.error));
69 record = getAppByRepo(app.db, repo.id)!;
70 });
71
72 // Every test starts from an app nothing has deployed: one test's preview
73 // or production slot would otherwise show in the next's head card. Each
74 // opens a pull of its own, and reads only that pull's row.
75 beforeEach(() => clearEnvs(record));
76
77 test("renders the head card for a viewer who may see it, with the security floor's headers; refuses one who may not, same as the page", async () => {
78 const fragment = await get("/alice/vault/app/state", owner);
79 expect(fragment.status).toBe(200);
80 expect(fragment.headers.get("x-content-type-options")).toBe("nosniff");
81 expect(fragment.headers.get("referrer-policy")).toBe("same-origin");
82 const text = await fragment.text();
83 expect(text).toContain('id="app-head"');
84 expect(text).toContain('id="app-previews"');
85 expect(text).toContain("not running");
86
87 const page = await (await get("/alice/vault", owner)).text();
88 expect(page).toContain("not running");
89
90 const refusedFragment = await get("/alice/vault/app/state", stranger);
91 expect(refusedFragment.status).toBe(404);
92 const refusedPage = await get("/alice/vault", stranger);
93 expect(refusedPage.status).toBe(404);
94 });
95
96 test("a change's page has a state fragment of its own: its current word, drawn by the page's own function, refused to whoever the page refuses, and named by the client script (#1094)", async () => {
97 const branch = await commitToBranch(app, getUserByName(app.db, "alice")!, repo, {
98 branch: "feature/ship-it",
99 base: "main",
100 message: "Ship it",
101 files: [{ path: "SHIP.md", content: "ship\n" }],
102 });
103 if (!branch.ok) throw new Error(JSON.stringify(branch.error));
104 const opened = await openPull(app, getUserByName(app.db, "alice")!, repo, {
105 title: "Ship it",
106 body: "",
107 baseBranch: "main",
108 headBranch: "feature/ship-it",
109 });
110 if (!opened.ok) throw new Error(String(opened.error));
111 const n = opened.value.number;
112
113 const fragment = await get(`/alice/vault/pulls/${n}/state`, owner);
114 expect(fragment.status).toBe(200);
115 expect(fragment.headers.get("x-content-type-options")).toBe("nosniff");
116 expect(fragment.headers.get("referrer-policy")).toBe("same-origin");
117 const text = await fragment.text();
118 expect(text).toContain('id="pull-check"');
119 expect(text).toContain('id="pull-preview"');
120 expect(text).toContain("studio-pull-check");
121 // The page's first paint carries the very same check line.
122 const pageText = await (await get(`/alice/vault/pulls/${n}`, owner)).text();
123 const line = (t: string) =>
124 t.match(/<p[^>]*studio-pull-check[^>]*>[\s\S]*?<\/p>/)?.[0];
125 expect(line(text)).toBeDefined();
126 expect(line(pageText)).toBe(line(text));
127 expect(pageText).toContain('id="pull-check"');
128 expect(pageText).toContain('data-head="');
129
130 expect((await get(`/alice/vault/pulls/${n}/state`, stranger)).status).toBe(404);
131 expect((await get(`/alice/vault/pulls/999/state`, owner)).status).toBe(404);
132
133 const merged = await mergePull(app, getUserByName(app.db, "alice")!, repo, opened.value, "squash");
134 if (!merged.ok) throw new Error(String(merged.error));
135 const after = await (await get(`/alice/vault/pulls/${n}/state`, owner)).text();
136 expect(line(after)).not.toBe(line(text));
137 // The squash lands a new commit; the fragment names it, so a page that
138 // saw the merge live can match production's serving against it.
139 const headOf = (t: string) => t.match(/data-head="([0-9a-f]{40})"/)?.[1];
140 expect(headOf(text)).toBeDefined();
141 expect(headOf(after)).toBeDefined();
142 expect(headOf(after)).not.toBe(headOf(text));
143 expect(liveClientJs).toContain("#pull-check [data-head]");
144
145 expect(liveClientJs).toContain("'/pulls/' + number + '/state'");
146 expect(liveClientJs).toContain("'pull.merged'");
147 expect(liveClientJs).toContain("'app.serving'");
148 });
149
150 test("Now has an address of its own: the page's region names it, the fragment answers with the same region, and unchanged bytes come back 304", async () => {
151 const page = await (await get("/alice/vault", owner)).text();
152 expect(page).toContain('id="live-now"');
153 expect(page).toContain('data-live-src="/alice/vault/app/now"');
154
155 const first = await get("/alice/vault/app/now", owner);
156 expect(first.status).toBe(200);
157 expect(first.headers.get("x-content-type-options")).toBe("nosniff");
158 expect(first.headers.get("cache-control")).toBe("no-store");
159 const etag = first.headers.get("etag");
160 expect(etag).toMatch(/^"[0-9a-f]{16}"$/);
161 const text = await first.text();
162 // The tag rides in the markup as well, for a proxy that drops the header.
163 expect(text).toMatch(/^\s*<div data-etag="[0-9a-f]{16}"/);
164 expect(`"${/data-etag="([0-9a-f]{16})"/.exec(text)![1]}"`).toBe(etag!);
165 expect(text).toContain('id="live-now"');
166 expect(text).toContain('data-live="run.queued,run.started,run.finished,pull.*,issue.*"');
167 expect(text).toContain('data-live-src="/alice/vault/app/now"');
168 expect(text).toContain("<h2>Now</h2>");
169
170 // The same bytes again: nothing to paint, and nothing sent to paint.
171 const again = await fetch(`${base}/alice/vault/app/now`, {
172 headers: {
173 cookie: `${owner}; forge_mode=studio`,
174 "if-none-match": etag!,
175 },
176 });
177 expect(again.status).toBe(304);
178 expect(again.headers.get("etag")).toBe(etag);
179 expect(await again.text()).toBe("");
180
181 // A stale tag is answered in full.
182 const stale = await fetch(`${base}/alice/vault/app/now`, {
183 headers: { cookie: `${owner}; forge_mode=studio`, "if-none-match": '"0"' },
184 });
185 expect(stale.status).toBe(200);
186 expect(await stale.text()).toContain("<h2>Now</h2>");
187
188 expect((await get("/alice/vault/app/now", stranger)).status).toBe(404);
189 expect((await fetch(`${base}/alice/vault/app/now`)).status).toBe(404);
190 });
191
192 test("a preview flips from deploying to live between two calls, and the link stays correct", async () => {
193 const alice = getUserByName(app.db, "alice")!;
194 const branch = await commitToBranch(app, alice, repo, {
195 branch: "feature/x",
196 base: repo.defaultBranch,
197 message: "Add X",
198 files: [{ path: "X.md", content: "x\n" }],
199 });
200 if (!branch.ok) throw new Error(JSON.stringify(branch.error));
201 const opened = await openPull(app, alice, repo, {
202 title: "Add X",
203 body: "",
204 baseBranch: repo.defaultBranch,
205 headBranch: "feature/x",
206 });
207 if (!opened.ok) throw new Error(String(opened.error));
208 const pull = opened.value;
209 const env = previewEnv(pull.number);
210 const link = `href="/alice/vault/app/${env}/open"`;
211
212 const deployRun = createRun(app.db, {
213 repoId: repo.id,
214 kind: "deploy",
215 env,
216 commitOid: pull.headOid,
217 reason: "pull",
218 });
219 claimRun(app.db, deployRun.id);
220 putEnv(record, env, {
221 deploying: {
222 run: { id: deployRun.id, commitOid: pull.headOid },
223 abort: new AbortController(),
224 },
225 });
226 const starting = await (await get("/alice/vault/app/state", owner)).text();
227 expect(starting).toContain("starting");
228 expect(starting).not.toContain(">live<");
229 expect(starting).toContain(link);
230
231 finishRun(app.db, deployRun.id, { state: "ok", summary: "deploy" });
232 putEnv(record, env, {
233 live: {
234 commitOid: pull.headOid,
235 handle: { port: 4321 },
236 runId: deployRun.id,
237 since: new Date().toISOString(),
238 manifest: { tty: null },
239 },
240 });
241 const live = await (await get("/alice/vault/app/state", owner)).text();
242 expect(live).not.toContain("starting");
243 expect(live).toContain(">live<");
244 expect(live).toContain(link);
245 });
246
247 test("the fragment's markup is what the live client's status announcement reads: the head's word in a badge, a preview row's word beside its `#N title`", async () => {
248 // `live.ts`'s `announceSwap` finds the head's word at `.page-head h1
249 // .badge` and, for a preview row, the pull's label at the start of
250 // `.row-meta` beside its word at `.row-trail .badge`. If this markup
251 // ever moves, the announcement goes silent without a test failing here.
252 const text = await (await get("/alice/vault/app/state", owner)).text();
253 expect(text).toContain('class="page-head"');
254 expect(text).toMatch(/class="page-head"[\s\S]*?<h1 class="bar">[\s\S]*?class="badge"[^>]*>not running</);
255
256 const alice = getUserByName(app.db, "alice")!;
257 const branch = await commitToBranch(app, alice, repo, {
258 branch: "feature/announce",
259 base: repo.defaultBranch,
260 message: "Add Y",
261 files: [{ path: "Y.md", content: "y\n" }],
262 });
263 if (!branch.ok) throw new Error(JSON.stringify(branch.error));
264 const opened = await openPull(app, alice, repo, {
265 title: "Add Y",
266 body: "",
267 baseBranch: repo.defaultBranch,
268 headBranch: "feature/announce",
269 });
270 if (!opened.ok) throw new Error(String(opened.error));
271 const pull = opened.value;
272 const env = previewEnv(pull.number);
273 const deployRun = createRun(app.db, {
274 repoId: repo.id,
275 kind: "deploy",
276 env,
277 commitOid: pull.headOid,
278 reason: "pull",
279 });
280 claimRun(app.db, deployRun.id);
281 finishRun(app.db, deployRun.id, { state: "ok", summary: "deploy" });
282 putEnv(record, env, {
283 live: {
284 commitOid: pull.headOid,
285 handle: { port: 4323 },
286 runId: deployRun.id,
287 since: new Date().toISOString(),
288 manifest: { tty: null },
289 },
290 });
291 const withPreview = await (
292 await get("/alice/vault/app/state", owner)
293 ).text();
294 const label = `#${pull.number} Add Y`;
295 expect(withPreview).toContain(`class="row-meta"`);
296 expect(withPreview).toContain(`class="row-trail"`);
297 expect(withPreview).toContain(label);
298 expect(
299 new RegExp(`${label}[\\s\\S]*?class="row-trail"[\\s\\S]*?>live<`).test(
300 withPreview,
301 ),
302 ).toBe(true);
303 });
304
305 test("the head measures from the push, not from the permit it waited for: a deploy queued 5s reads 6.0s after the push and names the wait", async () => {
306 const createdAt = new Date(Date.now() - 20_000).toISOString();
307 const deployStartedAt = new Date(
308 Date.parse(createdAt) + 5_000,
309 ).toISOString();
310 const servingAt = new Date(
311 Date.parse(deployStartedAt) + 1_000,
312 ).toISOString();
313 const deployRun = createRun(app.db, {
314 repoId: repo.id,
315 kind: "deploy",
316 env: "production",
317 commitOid: "cafebabe",
318 reason: "push",
319 });
320 claimRun(app.db, deployRun.id);
321 finishRun(app.db, deployRun.id, { state: "ok", summary: "deploy" });
322 putEnv(record, "production", {
323 live: {
324 commitOid: "cafebabe",
325 handle: { port: 4322 },
326 runId: deployRun.id,
327 since: servingAt,
328 servingAt,
329 createdAt,
330 deployStartedAt,
331 manifest: { tty: null },
332 },
333 });
334
335 const head = await (await get("/alice/vault/app/state", owner)).text();
336 expect(head).toContain("live 6.0s after the push · 5.0s queued");
337 expect(head).not.toContain("1.0s after the push");
338
339 // The same deployment with no wait for a permit says only the one
340 // number, exactly as it always has.
341 putEnv(record, "production", {
342 live: {
343 commitOid: "cafebabe",
344 handle: { port: 4322 },
345 runId: deployRun.id,
346 since: servingAt,
347 servingAt,
348 createdAt: deployStartedAt,
349 deployStartedAt,
350 manifest: { tty: null },
351 },
352 });
353 const prompt = await (await get("/alice/vault/app/state", owner)).text();
354 expect(prompt).toContain("live 1.0s after the push");
355 expect(prompt).not.toContain("queued");
356
357 // A deploy no push asked for — a redeploy someone pressed — carries no
358 // push instant, and its words never claim one.
359 putEnv(record, "production", {
360 live: {
361 commitOid: "cafebabe",
362 handle: { port: 4322 },
363 runId: deployRun.id,
364 since: servingAt,
365 servingAt,
366 deployStartedAt,
367 manifest: { tty: null },
368 },
369 });
370 const pressed = await (await get("/alice/vault/app/state", owner)).text();
371 expect(pressed).toContain("live 1.0s after the deploy started");
372 expect(pressed).not.toContain("after the push");
373 });
374
375 test("app.serving reaches the repo's stream with the shape the live client keys on, the instant the swap-in happens — before its run has finished", async () => {
376 const deployRun = createRun(app.db, {
377 repoId: repo.id,
378 kind: "deploy",
379 env: "production",
380 commitOid: "deadbeef",
381 reason: "push",
382 });
383 claimRun(app.db, deployRun.id);
384 const served = markServing(app.db, deployRun.id);
385 expect(served?.servingAt).toBeDefined();
386
387 const stream = await fetch(`${base}/alice/vault/stream`, {
388 headers: { cookie: owner },
389 });
390 const reader = stream.body!.getReader();
391 const decoder = new TextDecoder();
392 let buffer = "";
393 // The stream says it is connected as it subscribes: from here on, an
394 // append reaches it — no sleep stands in for that.
395 while (!buffer.includes(": connected\n\n")) {
396 const { done, value } = await reader.read();
397 if (done) throw new Error("the stream closed before it connected");
398 buffer += decoder.decode(value);
399 }
400
401 // The exact append `AppsRuntime` makes at the swap-in (runtime.ts),
402 // republished here so the test does not have to spin up a real deploy.
403 app.bus.append({
404 kind: "app.serving",
405 repoId: repo.id,
406 payload: {
407 app: record.slug,
408 env: "production",
409 commitOid: deployRun.commitOid,
410 servingAt: served!.servingAt,
411 testsRunning: true,
412 },
413 });
414
415 let event: Record<string, unknown> | undefined;
416 const deadline = Date.now() + 5_000;
417 while (!event && Date.now() < deadline) {
418 const { done, value } = await reader.read();
419 if (done) break;
420 buffer += decoder.decode(value);
421 const frames = buffer.split("\n\n");
422 buffer = frames.pop() ?? "";
423 for (const frame of frames) {
424 if (!/^event: app\.serving$/m.test(frame)) continue;
425 const data = /^data: (.*)$/m.exec(frame)?.[1];
426 if (data !== undefined) event = JSON.parse(data);
427 }
428 }
429 if (!event) throw new Error(`never came: still waiting while !event`);
430 await reader.cancel().catch(() => {});
431 expect(event).toBeDefined();
432 expect(event?.["kind"]).toBe("app.serving");
433 const payload = event?.["payload"] as Record<string, unknown>;
434 expect(payload["app"]).toBe(record.slug);
435 expect(payload["env"]).toBe("production");
436 expect(payload["commitOid"]).toBe(deployRun.commitOid);
437 expect(payload["servingAt"]).toBe(served!.servingAt);
438 expect(payload["testsRunning"]).toBe(true);
439
440 // finishRun never ran: run.finished has not fired, yet app.serving
441 // already has. That gap is the whole point of the issue.
442 expect(getRun(app.db, deployRun.id)?.state).toBe("running");
443 });
444
445 test("production's Open the app link appears only once it is serving, and the fragment after a swap flips it", async () => {
446 const link = 'href="/alice/vault/app/production/open"';
447 const deployRun = createRun(app.db, {
448 repoId: repo.id,
449 kind: "deploy",
450 env: "production",
451 commitOid: "cafed00d",
452 reason: "push",
453 });
454 claimRun(app.db, deployRun.id);
455 putEnv(record, "production", {
456 deploying: {
457 run: { id: deployRun.id, commitOid: "cafed00d" },
458 abort: new AbortController(),
459 },
460 });
461 const deploying = await (await get("/alice/vault/app/state", owner)).text();
462 expect(deploying).toContain("starting");
463 expect(deploying).not.toContain(link);
464
465 finishRun(app.db, deployRun.id, { state: "ok", summary: "deploy" });
466 putEnv(record, "production", {
467 live: {
468 commitOid: "cafed00d",
469 handle: { port: 4325 },
470 runId: deployRun.id,
471 since: new Date().toISOString(),
472 manifest: { tty: null },
473 },
474 });
475 const serving = await (await get("/alice/vault/app/state", owner)).text();
476 expect(serving).toContain(">live<");
477 expect(serving).toContain(link);
478 });
479 test("a preview row says how fast it got there in envFacts' own words, links its deploy run, and keeps its link and sentence while deploying or after its tests failed", async () => {
480 const alice = getUserByName(app.db, "alice")!;
481 const branch = await commitToBranch(app, alice, repo, {
482 branch: "feature/fast",
483 base: repo.defaultBranch,
484 message: "Add F",
485 files: [{ path: "F.md", content: "f\n" }],
486 });
487 if (!branch.ok) throw new Error(JSON.stringify(branch.error));
488 const opened = await openPull(app, alice, repo, {
489 title: "Add F",
490 body: "",
491 baseBranch: repo.defaultBranch,
492 headBranch: "feature/fast",
493 });
494 if (!opened.ok) throw new Error(String(opened.error));
495 const pull = opened.value;
496 const env = previewEnv(pull.number);
497 const open = `href="/alice/vault/app/${env}/open"`;
498 const label = `#${pull.number} Add F`;
499 const deployRun = createRun(app.db, {
500 repoId: repo.id,
501 kind: "deploy",
502 env,
503 commitOid: pull.headOid,
504 reason: "pull",
505 });
506 const runLink = `href="/alice/vault/runs/${deployRun.id}"`;
507 // This pull's own row out of the previews panel, so nothing the head
508 // card or another pull's row says can pass for it.
509 const rowOf = (text: string): string => {
510 const panel = text.slice(text.indexOf('id="app-previews"'));
511 const at = panel.indexOf(label);
512 expect(at).toBeGreaterThan(-1);
513 return panel.slice(panel.lastIndexOf("<li>", at), panel.indexOf("</li>", at));
514 };
515
516 claimRun(app.db, deployRun.id);
517 putEnv(record, env, {
518 deploying: {
519 run: { id: deployRun.id, commitOid: pull.headOid },
520 abort: new AbortController(),
521 },
522 });
523 const deploying = rowOf(
524 await (await get("/alice/vault/app/state", owner)).text(),
525 );
526 expect(deploying).toContain(open);
527 expect(deploying).toContain(runLink);
528 expect(deploying).toContain("deploy in progress");
529 expect(deploying).not.toContain("after the push");
530 expect(deploying).not.toContain("0.0s");
531
532 finishRun(app.db, deployRun.id, { state: "ok", summary: "deploy" });
533 const createdAt = new Date(Date.now() - 60_000).toISOString();
534 const servingAt = new Date(Date.parse(createdAt) + 3_400).toISOString();
535 putEnv(record, env, {
536 live: {
537 commitOid: pull.headOid,
538 handle: { port: 4324 },
539 runId: deployRun.id,
540 since: servingAt,
541 servingAt,
542 createdAt,
543 deployStartedAt: createdAt,
544 manifest: { tty: null },
545 },
546 });
547 const live = rowOf(await (await get("/alice/vault/app/state", owner)).text());
548 expect(live).toContain(open);
549 expect(live).toContain("live 3.4s after the push");
550 expect(live).toContain(pull.headOid.slice(0, 7));
551 expect(live).toContain(runLink);
552 expect(live).toContain(">live<");
553 // The live client keys its announcement on the meta line's first words.
554 expect(live).toMatch(new RegExp(`class="row-meta">#${pull.number} Add F ·`));
555 // The page's first paint draws the same row.
556 expect(await (await get("/alice/vault", owner)).text()).toContain(
557 "live 3.4s after the push",
558 );
559
560 putEnv(record, env, {
561 live: {
562 commitOid: pull.headOid,
563 handle: { port: 4324 },
564 runId: deployRun.id,
565 since: servingAt,
566 servingAt,
567 createdAt,
568 deployStartedAt: createdAt,
569 testsFailed: "2 failing",
570 manifest: { tty: null },
571 },
572 });
573 const red = rowOf(await (await get("/alice/vault/app/state", owner)).text());
574 expect(red).toContain(open);
575 expect(red).toContain(runLink);
576 expect(red).toContain("serving · tests failed: 2 failing");
577 expect(red).toContain("live 3.4s after the push");
578 // One badge, not green, and the row still links to the preview.
579 expect(red).toMatch(/data-variant="attn"[^]*?serving · tests failed<\/span/);
580 expect(red).not.toContain('data-variant="success"');
581 expect(red).not.toContain(">live<");
582
583 putEnv(record, env, {
584 deploying: {
585 run: { id: deployRun.id, commitOid: pull.headOid },
586 abort: new AbortController(),
587 },
588 live: {
589 commitOid: pull.headOid,
590 handle: { port: 4324 },
591 runId: deployRun.id,
592 since: servingAt,
593 servingAt,
594 createdAt,
595 deployStartedAt: createdAt,
596 manifest: { tty: null },
597 },
598 });
599 const verifying = rowOf(
600 await (await get("/alice/vault/app/state", owner)).text(),
601 );
602 expect(verifying).toContain(open);
603 expect(verifying).toContain("serving · verifying</span");
604 expect(verifying).not.toContain('data-variant="success"');
605 expect(verifying).not.toContain('data-variant="attn"');
606
607 putEnv(record, env, {
608 live: {
609 commitOid: pull.headOid,
610 handle: { port: 4324 },
611 runId: deployRun.id,
612 since: servingAt,
613 manifest: { tty: null },
614 },
615 });
616 const unmeasured = rowOf(
617 await (await get("/alice/vault/app/state", owner)).text(),
618 );
619 expect(unmeasured).toContain(open);
620 expect(unmeasured).not.toContain("after the");
621 expect(unmeasured).not.toContain("0.0s");
622 });
623 });
test/studio-door-head.test.ts added +234
@@ -0,0 +1,234 @@
1 /**
2 * The studio, one door of it: the studio head of an app that is not up. Split from
3 * studio-door.test.ts so each door runs on its own forge from test/support/studio-forge.ts
4 * (#15351); the rest of the studio's suite is test/studio*.test.ts.
5 */
6
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { enableApp } from "../src/actions/apps.ts";
9 import { getAppByRepo, type AppRecord } from "../src/core/apps.ts";
10 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
11 import type { Repo } from "../src/core/repos.ts";
12 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
13 import { getUserByName } from "../src/core/users.ts";
14 import { startStudioForge, type Slot, type StudioForge } from "./support/studio-forge.ts";
15
16 let forge: StudioForge;
17 let app: StudioForge["app"];
18 let base: StudioForge["base"];
19 let signIn: StudioForge["signIn"];
20 let putEnv: StudioForge["putEnv"];
21
22 beforeAll(async () => {
23 forge = await startStudioForge();
24 ({ app, base, signIn, putEnv } = forge);
25 });
26
27 afterAll(() => forge.stop());
28
29 /**
30 * The studio head of an app that is not up: the same facts the App page
31 * shows — why, the deploy that says the rest, and the way to try again.
32 */
33 describe("the studio head says why the app is not up", () => {
34 let repo: Repo;
35 let record: AppRecord;
36 let deploy: string;
37 let writer: string;
38 let reader: string;
39
40 const head = (cookie: string) =>
41 fetch(`${base}/alice/notes`, {
42 headers: { cookie: `${cookie}; forge_mode=studio` },
43 redirect: "manual",
44 }).then((r) => r.text());
45
46 /** The home's own shelf row for this app — the badge issue #201 is about. */
47 // The shelf's rows are `/apps` (#599: home is the feed).
48 const shelfBadge = async (cookie: string): Promise<string> => {
49 const home = await (
50 await fetch(`${base}/apps`, {
51 headers: { cookie: `${cookie}; forge_mode=studio` },
52 redirect: "manual",
53 })
54 ).text();
55 const at = home.indexOf('href="/alice/notes"');
56 expect(at).toBeGreaterThan(-1);
57 const start = home.lastIndexOf("<li>", at);
58 const row = home.slice(start, home.indexOf("</li>", at) + 5);
59 return row.match(/<span class="badge"[^>]*>([\s\S]*?)<\/span>/)?.[1] ?? "";
60 };
61
62 /** Production as the runtime holds it, in place of a real deploy. */
63 const put = (slot: Omit<Slot, "app" | "env" | "chain" | "restarts">): void =>
64 putEnv(record, "production", slot);
65
66 beforeAll(async () => {
67 const alice = getUserByName(app.db, "alice")!;
68 writer = await signIn("alice");
69 reader = await signIn("bob");
70 const made = await createRepo(app, alice, {
71 name: "notes",
72 visibility: "public",
73 description: "a place for notes",
74 });
75 if (!made.ok) throw new Error(String(made.error));
76 repo = made.value;
77 const seeded = await commitToBranch(app, alice, repo, {
78 message: "Start",
79 files: [{ path: "README.md", content: "notes\n" }],
80 });
81 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
82 const enabled = await enableApp(app, alice, repo, { slug: "notes" });
83 if (!enabled.ok) throw new Error(String(enabled.error));
84 record = getAppByRepo(app.db, repo.id)!;
85 const run = createRun(app.db, {
86 repoId: repo.id,
87 kind: "deploy",
88 env: "production",
89 commitOid: seeded.value.commitOid,
90 reason: "push",
91 });
92 claimRun(app.db, run.id);
93 finishRun(app.db, run.id, {
94 state: "failed",
95 summary: "the deploy failed",
96 });
97 deploy = run.id;
98 });
99
100 test("a failed production says what failed, links its deploy, and offers Redeploy to a writer only — and offers no live link to the host", async () => {
101 put({
102 lastError: "the deploy failed: <install> exited 1",
103 lastRunId: deploy,
104 });
105 const mine = await head(writer);
106 expect(mine).toContain("not up");
107 // The error is the app's own output: shown, and escaped.
108 expect(mine).toContain("the deploy failed: &lt;install&gt; exited 1");
109 expect(mine).not.toContain("<install>");
110 expect(mine).toContain(`href="/alice/notes/runs/${deploy}"`);
111 expect(mine).toContain('action="/alice/notes/app/production/redeploy"');
112 expect(mine).toContain('href="/-/confirm?to=%2Falice%2Fnotes%2Fapp%2Fproduction%2Fstop"');
113 expect(mine).not.toContain('href="/alice/notes/app/production/open"');
114 expect(mine).toContain('title="The last deploy failed"');
115
116 const theirs = await head(reader);
117 expect(theirs).toContain("not up");
118 expect(theirs).toContain("the deploy failed: &lt;install&gt; exited 1");
119 expect(theirs).toContain(`href="/alice/notes/runs/${deploy}"`);
120 expect(theirs).not.toContain("/app/production/redeploy");
121 expect(theirs).not.toContain("%2Fapp%2Fproduction%2Fstop");
122 expect(theirs).not.toContain('href="/alice/notes/app/production/open"');
123 });
124
125 // Issue #201: the shelf used to print the runtime's raw `EnvState` for a
126 // failed or deploying production, disagreeing with the app's own head
127 // above — which has always spoken the studio's five-ish words.
128 test("a failed production reads 'not up' on the home shelf too, never the runtime's own word 'failed'", async () => {
129 put({
130 lastError: "the deploy failed: <install> exited 1",
131 lastRunId: deploy,
132 });
133 expect(await shelfBadge(writer)).toBe("not up");
134 });
135
136 test("a stopped production says it is not running and offers Redeploy, not Stop — and no live link to the host", async () => {
137 put({ lastRunId: deploy });
138 const mine = await head(writer);
139 expect(mine).toContain("not running");
140 expect(mine).toContain('action="/alice/notes/app/production/redeploy"');
141 expect(mine).not.toContain('href="/-/confirm?to=%2Falice%2Fnotes%2Fapp%2Fproduction%2Fstop"');
142 expect(mine).not.toContain('href="/alice/notes/app/production/open"');
143 expect(mine).toContain('title="Nothing is running yet. The app starts when it is deployed."');
144 expect(await shelfBadge(writer)).toBe("not running");
145 });
146
147 test("a deploying production says so where the button was, not a link to a host nothing is serving yet", async () => {
148 put({
149 deploying: { run: { id: deploy, commitOid: "0".repeat(40) } },
150 });
151 const mine = await head(writer);
152 expect(mine).toContain("starting");
153 expect(mine).not.toContain('href="/alice/notes/app/production/open"');
154 expect(mine).toContain('title="Still deploying"');
155 // The runtime's own word for this state is "deploying" — the shelf
156 // says "starting" instead, same as the head above.
157 expect(await shelfBadge(writer)).toBe("starting");
158 });
159
160 test("a serving app with red tests still reads as serving, with the failure in its own words, and is still open-able", async () => {
161 put({
162 live: {
163 commitOid: "0".repeat(40),
164 handle: { port: 4321 },
165 runId: deploy,
166 since: new Date(Date.now() - 60_000).toISOString(),
167 testsFailed: "1 of 3 tests failed",
168 manifest: { tty: null },
169 },
170 });
171 const mine = await head(writer);
172 expect(mine).toContain("serving · tests failed");
173 expect(mine).not.toContain("not up");
174 expect(mine).toContain("serving · tests failed: 1 of 3 tests failed");
175 expect(mine).toContain('href="/alice/notes/app/production/open"');
176 expect(await shelfBadge(writer)).toBe("serving · tests failed");
177 });
178
179 test("a newer push that failed to come up while an older deploy keeps serving: live, not plain green, both commits named, its run linked", async () => {
180 const failed = createRun(app.db, {
181 repoId: repo.id,
182 kind: "deploy",
183 env: "production",
184 commitOid: "2".repeat(40),
185 reason: "push",
186 });
187 claimRun(app.db, failed.id);
188 finishRun(app.db, failed.id, {
189 state: "failed",
190 summary: "forge.json: JSON Parse error: Unexpected token '}'",
191 });
192 put({
193 live: {
194 commitOid: "1".repeat(40),
195 handle: { port: 4321 },
196 runId: deploy,
197 since: new Date(Date.now() - 60_000).toISOString(),
198 manifest: { tty: null },
199 },
200 lastError: "forge.json: JSON Parse error: Unexpected token '}'",
201 lastRunId: failed.id,
202 lastErrorCommitOid: "2".repeat(40),
203 });
204 const mine = await head(writer);
205 // It answers — still "live", never "not up" — but not untroubled green.
206 expect(mine).toContain("live");
207 expect(mine).not.toContain("not up");
208 expect(mine).toContain('href="/alice/notes/app/production/open"');
209 // Both commits, named.
210 expect(mine).toContain("1111111");
211 expect(mine).toContain("2222222");
212 expect(mine).toContain("did not come up");
213 expect(mine).toContain(
214 "forge.json: JSON Parse error: Unexpected token &#39;}&#39;",
215 );
216 // The failed run's log, one click away.
217 expect(mine).toContain(`href="/alice/notes/runs/${failed.id}"`);
218 });
219
220 test("a clean deploy with no failure behind it is unchanged: plain live, no failed-run link", async () => {
221 put({
222 live: {
223 commitOid: "1".repeat(40),
224 handle: { port: 4321 },
225 runId: deploy,
226 since: new Date(Date.now() - 60_000).toISOString(),
227 manifest: { tty: null },
228 },
229 });
230 const mine = await head(writer);
231 expect(mine).toContain("live");
232 expect(mine).not.toContain("did not come up");
233 });
234 });
test/studio-door-home.test.ts added +185
@@ -0,0 +1,185 @@
1 /**
2 * The studio, one door of it: the studio home's live regions. Split from studio-door.test.ts
3 * so each door runs on its own forge from test/support/studio-forge.ts
4 * (#15351); the rest of the studio's suite is test/studio*.test.ts.
5 */
6
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { enableApp } from "../src/actions/apps.ts";
9 import { addToCrew, createAgent } from "../src/actions/crew.ts";
10 import { assignIssue, openIssue, setIssueState } from "../src/actions/issues.ts";
11 import { mergePull, openPull } from "../src/actions/pulls.ts";
12 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
13 import { KIND_CHIPS, setChip } from "../src/core/feed_chips.ts";
14 import type { Issue } from "../src/core/issues.ts";
15 import type { Pull } from "../src/core/pulls.ts";
16 import type { Repo } from "../src/core/repos.ts";
17 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
18 import { getUserByName, type User } from "../src/core/users.ts";
19 import { withScripts } from "./helpers/page-script.ts";
20 import { startStudioForge, type StudioForge } from "./support/studio-forge.ts";
21
22 let forge: StudioForge;
23 let app: StudioForge["app"];
24 let servers: StudioForge["servers"];
25 let base: StudioForge["base"];
26 let signIn: StudioForge["signIn"];
27
28 beforeAll(async () => {
29 forge = await startStudioForge();
30 ({ app, servers, base, signIn } = forge);
31 });
32
33 afterAll(() => forge.stop());
34
35 /**
36 * The studio home keeps itself current: Asks you, Your apps and On you are
37 * each a live region — no second fragment endpoint, the same `studioHome`
38 * render as the first paint, fetched again on a matching event and swapped
39 * in place by `liveRegionsJs` (`src/web/client.ts`).
40 */
41 describe("the studio home keeps itself current", () => {
42 let alice: User;
43 let repo: Repo;
44 let cookie: string;
45 let pull: Pull;
46 let readme: Issue;
47
48 const get = (extraCookie = "") =>
49 fetch(`${base}/feed`, {
50 headers: {
51 cookie: `${cookie}${extraCookie}; forge_mode=studio`,
52 },
53 redirect: "manual",
54 });
55
56 beforeAll(async () => {
57 alice = getUserByName(app.db, "alice")!;
58 cookie = await signIn("alice");
59 const made = await createRepo(app, alice, {
60 name: "signals",
61 visibility: "private",
62 description: "",
63 });
64 if (!made.ok) throw new Error(String(made.error));
65 repo = made.value;
66 const seeded = await commitToBranch(app, alice, repo, {
67 message: "Start",
68 files: [{ path: "README.md", content: "s\n" }],
69 });
70 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
71 const enabled = await enableApp(app, alice, repo, { slug: "signals" });
72 if (!enabled.ok) throw new Error(String(enabled.error));
73 const scout = await createAgent(app, alice, { username: "scout" });
74 if (!scout.ok) throw new Error(String(scout.error));
75 expect(addToCrew(app, alice, repo, "scout").ok).toBe(true);
76 const scoutUser = getUserByName(app.db, "scout")!;
77 const branch = await commitToBranch(app, alice, repo, {
78 branch: "feature/x",
79 base: "main",
80 message: "Add x",
81 files: [{ path: "x.md", content: "x\n" }],
82 });
83 if (!branch.ok) throw new Error(JSON.stringify(branch.error));
84 const opened = await openPull(app, scoutUser, repo, {
85 title: "Add x",
86 body: "",
87 baseBranch: "main",
88 headBranch: "feature/x",
89 });
90 if (!opened.ok) throw new Error(String(opened.error));
91 pull = opened.value;
92 const run = createRun(app.db, {
93 repoId: repo.id,
94 kind: "check",
95 issueId: pull.id,
96 env: `pull-${pull.number}`,
97 commitOid: pull.headOid,
98 reason: "pull",
99 });
100 claimRun(app.db, run.id);
101 finishRun(app.db, run.id, { state: "ok", summary: "check passed" });
102
103 const asked = openIssue(app, alice, repo, { title: "Write the README" });
104 if (!asked.ok) throw new Error(String(asked.error));
105 readme = asked.value;
106 expect(assignIssue(app, alice, repo, readme, alice).ok).toBe(true);
107 });
108
109 test("Your apps is a live region and the home has no On you, with the security floor's headers", async () => {
110 const res = await get();
111 expect(res.status).toBe(200);
112 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
113 expect(res.headers.get("referrer-policy")).toBe("same-origin");
114 const home = await res.text();
115 expect(home).toMatch(/id="live-apps"\s*\n?\s*data-live="/);
116 expect(home).not.toContain("live-on-you");
117 expect(await withScripts(servers.url, home)).toContain("new EventSource('/events')");
118 });
119
120 test("chips do not touch Your apps: it lists apps, not feed items", async () => {
121 for (const kind of KIND_CHIPS) setChip(app.db, alice.id, { kind: "kind", value: kind }, true);
122 const res = await fetch(`${base}/live/apps`, { headers: { cookie: `${cookie}; forge_mode=studio` } });
123 expect(await res.text()).toContain(`${repo.name}`);
124 for (const kind of KIND_CHIPS) setChip(app.db, alice.id, { kind: "kind", value: kind }, false);
125 });
126
127 test("each region on the home has an address of its own, answering with that region alone and 304 when it has not changed", async () => {
128 const page = await (await get()).text();
129 expect(page).toContain('data-live-src="/live/apps"');
130 expect(page).not.toContain("/live/on-you");
131
132 const headers = { cookie: `${cookie}; forge_mode=studio` };
133 const apps = await fetch(`${base}/live/apps`, { headers });
134 expect(apps.status).toBe(200);
135 const appsText = await apps.text();
136 expect(appsText).toContain('id="live-apps"');
137 expect(appsText).toContain(`${repo.name}`);
138 expect(appsText).not.toContain("<html");
139 const tag = apps.headers.get("etag");
140 expect(tag).toMatch(/^"[0-9a-f]{16}"$/);
141 const unchanged = await fetch(`${base}/live/apps`, {
142 headers: { ...headers, "if-none-match": tag! },
143 });
144 expect(unchanged.status).toBe(304);
145
146 const onYou = await fetch(`${base}/live/on-you`, { headers });
147 expect(onYou.status).toBe(200);
148 expect(await onYou.text()).toContain('id="live-on-you"');
149
150 // Signed out, the regions are nobody's.
151 expect((await fetch(`${base}/live/apps`)).status).toBe(404);
152 expect((await fetch(`${base}/live/on-you`)).status).toBe(404);
153 });
154
155 test("a signed-out request gets a signed-out home: no per-viewer live regions, nothing of alice's", async () => {
156 const res = await fetch(`${base}/`, {
157 headers: { cookie: "forge_mode=studio" },
158 redirect: "manual",
159 });
160 expect(res.status).toBe(200);
161 const home = await res.text();
162 expect(home).not.toContain('id="live-asks"');
163 expect(home).not.toContain('id="live-on-you"');
164 expect(home).not.toContain("Add x");
165 expect(home).not.toContain("Write the README");
166 });
167
168 test("a card leaves On you once its issue closes", async () => {
169 // The On you region alone: the timeline still tells of the issue, as a
170 // post does after it is done (#599).
171 const onYou = () =>
172 fetch(`${base}/live/on-you`, {
173 headers: { cookie: `${cookie}; forge_mode=studio` },
174 }).then((r) => r.text());
175 const before = await onYou();
176 expect(before).toContain("Write the README");
177
178 const merged = await mergePull(app, alice, repo, pull, "squash");
179 expect(merged.ok).toBe(true);
180 expect(setIssueState(app, alice, repo, readme, "closed").ok).toBe(true);
181
182 const after = await onYou();
183 expect(after).not.toContain("Write the README");
184 });
185 });
test/studio-door-owner-page.test.ts added +271
@@ -0,0 +1,271 @@
1 /**
2 * The studio, one door of it: an owner's page, an app listed once. Split from studio-door.test.ts
3 * so each door runs on its own forge from test/support/studio-forge.ts
4 * (#15351); the rest of the studio's suite is test/studio*.test.ts.
5 */
6
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { enableApp } from "../src/actions/apps.ts";
9 import { createOrg } from "../src/actions/orgs.ts";
10 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
11 import { createUser } from "../src/core/users.ts";
12 import { promote } from "./helpers/members.ts";
13 import { startStudioForge, type StudioForge } from "./support/studio-forge.ts";
14
15 let forge: StudioForge;
16 let app: StudioForge["app"];
17 let base: StudioForge["base"];
18 let signIn: StudioForge["signIn"];
19
20 beforeAll(async () => {
21 forge = await startStudioForge();
22 ({ app, base, signIn } = forge);
23 });
24
25 afterAll(() => forge.stop());
26
27 describe("an owner's page lists an app once, not once in each vocabulary (#221)", () => {
28 const occurrences = (haystack: string, needle: string): number =>
29 haystack.split(needle).length - 1;
30
31 test("a person with one app and one plain repository renders each once, in every mode; one with no app shows a visitor no apps card at all", async () => {
32 const dan = await createUser(app.db, { origin: "seed", trusted: true,
33 username: "dan",
34 email: "[email protected]",
35 password: "a-good-passphrase",
36 adminIfFirst: true,
37 });
38 if (!dan.ok) throw new Error(dan.error);
39 promote(app.db, dan.value);
40 const cookie = await signIn("dan", "a-good-passphrase");
41
42 const madeApp = await createRepo(app, dan.value, {
43 name: "beacon",
44 visibility: "public",
45 description: "a lighthouse",
46 });
47 if (!madeApp.ok) throw new Error(String(madeApp.error));
48 const appSeeded = await commitToBranch(app, dan.value, madeApp.value, {
49 message: "Start",
50 files: [{ path: "README.md", content: "hi\n" }],
51 });
52 if (!appSeeded.ok) throw new Error(JSON.stringify(appSeeded.error));
53 // Not "beacon": alice's app in the terminal's block holds that slug.
54 const enabled = await enableApp(app, dan.value, madeApp.value, {
55 slug: "dan-beacon",
56 });
57 if (!enabled.ok) throw new Error(String(enabled.error));
58
59 const madePlain = await createRepo(app, dan.value, {
60 name: "scratch",
61 visibility: "public",
62 description: "not an app",
63 });
64 if (!madePlain.ok) throw new Error(String(madePlain.error));
65 const plainSeeded = await commitToBranch(app, dan.value, madePlain.value, {
66 message: "Start",
67 files: [{ path: "README.md", content: "hi\n" }],
68 });
69 if (!plainSeeded.ok) throw new Error(JSON.stringify(plainSeeded.error));
70
71 const studio = await (
72 await fetch(`${base}/dan`, {
73 headers: { cookie: `${cookie}; forge_mode=studio` },
74 redirect: "manual",
75 })
76 ).text();
77 expect(occurrences(studio, 'href="/dan/beacon"')).toBe(1);
78 expect(occurrences(studio, 'href="/dan/scratch"')).toBe(1);
79 expect(studio).toContain("<h2>Other repositories</h2>");
80
81 const dev = await (
82 await fetch(`${base}/dan`, {
83 headers: { cookie: `${cookie}; forge_mode=dev` },
84 redirect: "manual",
85 })
86 ).text();
87 expect(occurrences(dev, 'href="/dan/beacon"')).toBe(1);
88 expect(occurrences(dev, 'href="/dan/scratch"')).toBe(1);
89 expect(dev).toContain("<h2>Apps</h2>");
90 expect(dev).toContain("<h2>Other repositories</h2>");
91
92 // Someone with repositories and no app: a visitor is not shown an empty
93 // apps card, and the list is simply their repositories.
94 const gus = await createUser(app.db, { origin: "seed", trusted: true,
95 username: "gus",
96 email: "[email protected]",
97 password: "a-good-passphrase",
98 });
99 if (!gus.ok) throw new Error(gus.error);
100 promote(app.db, gus.value);
101 const plainOnly = await createRepo(app, gus.value, {
102 name: "notebook",
103 visibility: "public",
104 description: "",
105 });
106 if (!plainOnly.ok) throw new Error(String(plainOnly.error));
107 const visit = await (
108 await fetch(`${base}/gus`, {
109 headers: { cookie: `${cookie}; forge_mode=studio` },
110 redirect: "manual",
111 })
112 ).text();
113 expect(visit).not.toContain("No apps yet");
114 expect(visit).toContain("<h2>Repositories</h2>");
115 expect(visit).toContain('href="/gus/notebook"');
116 });
117
118 test("an owner whose only repository is an app reads the empty list below as no other repositories, not as a bug", async () => {
119 const eve = await createUser(app.db, { origin: "seed", trusted: true,
120 username: "eve",
121 email: "[email protected]",
122 password: "a-good-passphrase",
123 });
124 if (!eve.ok) throw new Error(eve.error);
125 promote(app.db, eve.value);
126 const cookie = await signIn("eve", "a-good-passphrase");
127
128 const madeApp = await createRepo(app, eve.value, {
129 name: "lighthouse",
130 visibility: "public",
131 });
132 if (!madeApp.ok) throw new Error(String(madeApp.error));
133 const seeded = await commitToBranch(app, eve.value, madeApp.value, {
134 message: "Start",
135 files: [{ path: "README.md", content: "hi\n" }],
136 });
137 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
138 const enabled = await enableApp(app, eve.value, madeApp.value, {
139 slug: "lighthouse",
140 });
141 if (!enabled.ok) throw new Error(String(enabled.error));
142
143 const studio = await (
144 await fetch(`${base}/eve`, {
145 headers: { cookie: `${cookie}; forge_mode=studio` },
146 redirect: "manual",
147 })
148 ).text();
149 expect(occurrences(studio, 'href="/eve/lighthouse"')).toBe(1);
150 expect(studio).toContain("No other repositories");
151 expect(studio).not.toContain("<h2>Other repositories</h2>");
152 });
153
154 test("a private app on a public repository shows its state only to its writers: a visitor gets a plain row", async () => {
155 const hal = await createUser(app.db, { origin: "seed", trusted: true,
156 username: "hal",
157 email: "[email protected]",
158 password: "a-good-passphrase",
159 });
160 if (!hal.ok) throw new Error(hal.error);
161 promote(app.db, hal.value);
162 const ownerCookie = await signIn("hal", "a-good-passphrase");
163 const made = await createRepo(app, hal.value, {
164 name: "ledger",
165 visibility: "public",
166 description: "the books",
167 });
168 if (!made.ok) throw new Error(String(made.error));
169 const seeded = await commitToBranch(app, hal.value, made.value, {
170 message: "Start",
171 files: [{ path: "README.md", content: "hi\n" }],
172 });
173 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
174 const enabled = await enableApp(app, hal.value, made.value, {
175 slug: "hal-ledger",
176 access: "private",
177 });
178 if (!enabled.ok) throw new Error(String(enabled.error));
179 const ivy = await createUser(app.db, { origin: "seed", trusted: true,
180 username: "ivy",
181 email: "[email protected]",
182 password: "a-good-passphrase",
183 });
184 if (!ivy.ok) throw new Error(ivy.error);
185 promote(app.db, ivy.value);
186 const strangerCookie = await signIn("ivy", "a-good-passphrase");
187
188 const visit = (cookie?: string) =>
189 fetch(`${base}/hal`, {
190 headers: cookie === undefined ? {} : { cookie },
191 redirect: "manual",
192 }).then((r) => r.text());
193 // The palette index lists other, public apps and their state; the page is what is under test.
194 const bare = (html: string) => html.replace(/<script[^>]*id="palette-index">.*?<\/script>/s, "");
195 for (const page of [bare(await visit()), bare(await visit(strangerCookie))]) {
196 // The repository is public, so it is listed — once, plainly.
197 expect(occurrences(page, 'href="/hal/ledger"')).toBe(1);
198 expect(page).toContain("the books");
199 expect(page).not.toContain("not running");
200 expect(page).not.toContain("quiet");
201 expect(page).not.toContain('class="studio-word"');
202 }
203 // Nor does the palette hand a visitor the private app's door.
204 for (const raw of [await visit(), await visit(strangerCookie)])
205 expect(raw).not.toContain("/hal/ledger/app/production/open");
206 const own = await visit(ownerCookie);
207 expect(own).toContain("not running");
208 });
209
210 test("an org's page draws the same way: its app once, its plain repository once, and Members/Teams unmoved", async () => {
211 const fay = await createUser(app.db, { origin: "seed", trusted: true,
212 username: "fay",
213 email: "[email protected]",
214 password: "a-good-passphrase",
215 });
216 if (!fay.ok) throw new Error(fay.error);
217 promote(app.db, fay.value);
218 const cookie = await signIn("fay", "a-good-passphrase");
219
220 const org = await createOrg(app, fay.value, "vega");
221 if (!org.ok) throw new Error(org.error);
222
223 const madeApp = await createRepo(app, fay.value, {
224 name: "anvil",
225 owner: "vega",
226 visibility: "public",
227 });
228 if (!madeApp.ok) throw new Error(String(madeApp.error));
229 const appSeeded = await commitToBranch(app, fay.value, madeApp.value, {
230 message: "Start",
231 files: [{ path: "README.md", content: "hi\n" }],
232 });
233 if (!appSeeded.ok) throw new Error(JSON.stringify(appSeeded.error));
234 const enabled = await enableApp(app, fay.value, madeApp.value, {
235 slug: "anvil",
236 });
237 if (!enabled.ok) throw new Error(String(enabled.error));
238
239 const madePlain = await createRepo(app, fay.value, {
240 name: "ledger",
241 owner: "vega",
242 visibility: "public",
243 });
244 if (!madePlain.ok) throw new Error(String(madePlain.error));
245 const plainSeeded = await commitToBranch(app, fay.value, madePlain.value, {
246 message: "Start",
247 files: [{ path: "README.md", content: "hi\n" }],
248 });
249 if (!plainSeeded.ok) throw new Error(JSON.stringify(plainSeeded.error));
250
251 const studio = await (
252 await fetch(`${base}/vega`, {
253 headers: { cookie: `${cookie}; forge_mode=studio` },
254 redirect: "manual",
255 })
256 ).text();
257 expect(occurrences(studio, 'href="/vega/anvil"')).toBe(1);
258 expect(occurrences(studio, 'href="/vega/ledger"')).toBe(1);
259 expect(studio).toContain('<h2>Members</h2>');
260 expect(studio).toContain('<h2 id="teams">Teams</h2>');
261
262 const dev = await (
263 await fetch(`${base}/vega`, {
264 headers: { cookie: `${cookie}; forge_mode=dev` },
265 redirect: "manual",
266 })
267 ).text();
268 expect(occurrences(dev, 'href="/vega/anvil"')).toBe(1);
269 expect(occurrences(dev, 'href="/vega/ledger"')).toBe(1);
270 });
271 });
test/studio-door-previews.test.ts added +155
@@ -0,0 +1,155 @@
1 /**
2 * The studio, one door of it: every open pull's preview on the studio page. Split from
3 * studio-door.test.ts so each door runs on its own forge from test/support/studio-forge.ts
4 * (#15351); the rest of the studio's suite is test/studio*.test.ts.
5 */
6
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { enableApp } from "../src/actions/apps.ts";
9 import { previewEnv } from "../src/apps/data.ts";
10 import { getAppByRepo, type AppRecord } from "../src/core/apps.ts";
11 import { mergePull, openPull } from "../src/actions/pulls.ts";
12 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
13 import type { Repo } from "../src/core/repos.ts";
14 import { getUserByName } from "../src/core/users.ts";
15 import { ageApp } from "./helpers/history.ts";
16 import { startStudioForge, type StudioForge } from "./support/studio-forge.ts";
17
18 let forge: StudioForge;
19 let app: StudioForge["app"];
20 let base: StudioForge["base"];
21 let signIn: StudioForge["signIn"];
22 let putEnv: StudioForge["putEnv"];
23
24 beforeAll(async () => {
25 forge = await startStudioForge();
26 ({ app, base, signIn, putEnv } = forge);
27 });
28
29 afterAll(() => forge.stop());
30
31 describe("every open pull's preview on the studio page", () => {
32 let cookie: string;
33 let repo: Repo;
34 let record: AppRecord;
35
36 const get = (path: string) =>
37 fetch(`${base}${path}`, {
38 headers: { cookie: `${cookie}; forge_mode=studio` },
39 redirect: "manual",
40 });
41
42 // The tests take turns on one repository: the first leaves no pull open,
43 // which is the second's start.
44 beforeAll(async () => {
45 const alice = getUserByName(app.db, "alice")!;
46 cookie = await signIn("alice");
47 const made = await createRepo(app, alice, {
48 name: "widget",
49 visibility: "public",
50 description: "",
51 });
52 if (!made.ok) throw new Error(String(made.error));
53 repo = made.value;
54 const seeded = await commitToBranch(app, alice, repo, {
55 message: "Start",
56 files: [{ path: "README.md", content: "w\n" }],
57 });
58 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
59 const enabled = await enableApp(app, alice, repo, { slug: "widget" });
60 if (!enabled.ok) throw new Error(String(enabled.error));
61 record = getAppByRepo(app.db, repo.id)!;
62 // An older app: a new one shows only its progress, without the list (#10299).
63 ageApp(app.db, repo.id);
64 });
65
66 test("an open pull's preview host and open link render; none do once nothing is open", async () => {
67 const alice = getUserByName(app.db, "alice")!;
68 const before = await (await get("/alice/widget")).text();
69 expect(before).not.toContain("<h2>Previews</h2>");
70
71 const branch = await commitToBranch(app, alice, repo, {
72 branch: "feature/x",
73 base: repo.defaultBranch,
74 message: "Add X",
75 files: [{ path: "X.md", content: "x\n" }],
76 });
77 if (!branch.ok) throw new Error(JSON.stringify(branch.error));
78 const opened = await openPull(app, alice, repo, {
79 title: "Add X",
80 body: "",
81 baseBranch: repo.defaultBranch,
82 headBranch: "feature/x",
83 });
84 if (!opened.ok) throw new Error(String(opened.error));
85 const pull = opened.value;
86
87 const page = await (await get("/alice/widget")).text();
88 expect(page).toContain("<h2>Previews</h2>");
89 expect(page).toContain(`href="/alice/widget/app/pull-${pull.number}/open"`);
90 expect(page).toContain(`#${pull.number} Add X`);
91
92 const merged = await mergePull(app, alice, repo, pull, "squash");
93 expect(merged.ok).toBe(true);
94 const after = await (await get("/alice/widget")).text();
95 expect(after).not.toContain("<h2>Previews</h2>");
96 expect(after).not.toContain(`pull-${pull.number}/open`);
97 });
98
99 test("a change's page names its preview's data as its own copy and gives the moment it was taken; production's card does not", async () => {
100 const alice = getUserByName(app.db, "alice")!;
101 const branch = await commitToBranch(app, alice, repo, {
102 branch: "feature/y",
103 base: repo.defaultBranch,
104 message: "Add Y",
105 files: [{ path: "Y.md", content: "y\n" }],
106 });
107 if (!branch.ok) throw new Error(JSON.stringify(branch.error));
108 const opened = await openPull(app, alice, repo, {
109 title: "Add Y",
110 body: "",
111 baseBranch: repo.defaultBranch,
112 headBranch: "feature/y",
113 });
114 if (!opened.ok) throw new Error(String(opened.error));
115 const pull = opened.value;
116 const env = previewEnv(pull.number);
117
118 // Production and the preview both serving, as a deploy leaves them;
119 // test/apps.test.ts proves a real preview gets its copy of the data.
120 const serving = (commitOid: string) => ({
121 live: {
122 commitOid,
123 handle: { port: 4321 },
124 runId: "fake",
125 since: new Date().toISOString(),
126 manifest: { tty: null },
127 },
128 });
129 putEnv(record, "production", serving("0".repeat(40)));
130 putEnv(record, env, serving(pull.headOid));
131
132 const note = "its own copy of production's data, taken";
133
134 const appPage = await (await get("/alice/widget")).text();
135 expect(appPage).toContain(note);
136 // Production's own card, above the previews list, never says it.
137 const production = appPage.slice(0, appPage.indexOf("<h2>Previews</h2>"));
138 expect(production).not.toContain(note);
139
140 const changePage = await (
141 await get(`/alice/widget/pulls/${pull.number}`)
142 ).text();
143 expect(changePage).toContain("<h2>Preview</h2>");
144 expect(changePage).toContain(note);
145 // One flow (#14241): the notes, the thread and the comment box run down one column and the
146 // preview sits beside them in the same block, so nothing tall on the side opens a gap above the
147 // thread.
148 expect(changePage).toContain('<div class="split" data-pull>');
149 expect(changePage).not.toContain("data-top");
150 const flow = changePage.slice(changePage.indexOf('<div class="split" data-pull>'));
151 expect(flow.indexOf("comment-form")).toBeGreaterThan(-1);
152 expect(flow.indexOf("comment-form")).toBeLessThan(flow.indexOf('id="pull-preview"'));
153 expect(flow.slice(0, flow.indexOf('id="pull-preview"')).match(/<aside>/g)?.length).toBe(1);
154 });
155 });
test/studio-door-terminal.test.ts added +136
@@ -0,0 +1,136 @@
1 /**
2 * The studio, one door of it: the studio app page's terminal. Split from studio-door.test.ts
3 * so each door runs on its own forge from test/support/studio-forge.ts
4 * (#15351); the rest of the studio's suite is test/studio*.test.ts.
5 */
6
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { type App } from "../src/app.ts";
9 import { enableApp } from "../src/actions/apps.ts";
10 import { getAppByRepo, type AppRecord } from "../src/core/apps.ts";
11 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
12 import type { Repo } from "../src/core/repos.ts";
13 import { getUserByName } from "../src/core/users.ts";
14 import { startStudioForge, type StudioForge } from "./support/studio-forge.ts";
15
16 let forge: StudioForge;
17 let app: StudioForge["app"];
18 let base: StudioForge["base"];
19 let signIn: StudioForge["signIn"];
20 let putEnv: StudioForge["putEnv"];
21
22 beforeAll(async () => {
23 forge = await startStudioForge();
24 ({ app, base, signIn, putEnv } = forge);
25 });
26
27 afterAll(() => forge.stop());
28
29 /**
30 * The studio app page's Terminal — the one door an operator has into what
31 * is running. `terminalFor` (`src/actions/apps.ts`) is the single fact both
32 * this page and the dev App page read; this only checks it is drawn (or
33 * withheld) correctly, not recomputed.
34 */
35 describe("the studio app page's terminal", () => {
36 let repo: Repo;
37 let record: AppRecord;
38 let writer: string;
39 let reader: string;
40 // What the forge had before this block gave it a listener and a key.
41 let before: Pick<App["config"], "sshPort" | "sshHostKey">;
42
43 const putLive = (tty: string | null): void =>
44 putEnv(record, "production", {
45 live: {
46 commitOid: "a".repeat(40),
47 handle: { port: 4321 },
48 runId: "fake",
49 since: new Date().toISOString(),
50 manifest: { tty },
51 },
52 });
53
54 const appPage = (cookie: string) =>
55 fetch(`${base}/alice/beacon`, {
56 headers: { cookie: `${cookie}; forge_mode=studio` },
57 redirect: "manual",
58 }).then((r) => r.text());
59
60 beforeAll(async () => {
61 before = { ...app.config };
62 app.config.sshPort = 2222;
63 app.config.sshHostKey =
64 "SHA256:abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG";
65 const alice = getUserByName(app.db, "alice")!;
66 writer = await signIn("alice");
67 reader = await signIn("bob");
68 const made = await createRepo(app, alice, {
69 name: "beacon",
70 visibility: "public",
71 description: "a light that stays on",
72 });
73 if (!made.ok) throw new Error(String(made.error));
74 repo = made.value;
75 const seeded = await commitToBranch(app, alice, repo, {
76 message: "Start",
77 files: [{ path: "README.md", content: "beacon\n" }],
78 });
79 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
80 const enabled = await enableApp(app, alice, repo, { slug: "beacon" });
81 if (!enabled.ok) throw new Error(String(enabled.error));
82 record = getAppByRepo(app.db, repo.id)!;
83 });
84
85 afterAll(() => {
86 if (before.sshPort === undefined) delete app.config.sshPort;
87 else app.config.sshPort = before.sshPort;
88 if (before.sshHostKey === undefined) delete app.config.sshHostKey;
89 else app.config.sshHostKey = before.sshHostKey;
90 });
91
92 test("a writer sees the exact command and the host key; a reader sees neither", async () => {
93 putLive("bun run src/tty.ts");
94 const mine = await appPage(writer);
95 expect(mine).toContain("ssh -p 2222 [email protected]");
96 expect(mine).toContain("host key SHA256:abcdefghijklmnopqrstuvwxyz");
97 // Wrapped in the marker an email-scanning edge honours, so the
98 // login@host in the command is never rewritten into a mailto: link —
99 // and the command itself sits between the markers unchanged.
100 expect(mine).toContain(
101 "<!--email_off-->ssh -p 2222 [email protected]<!--/email_off-->",
102 );
103 const theirs = await appPage(reader);
104 expect(theirs).not.toContain("ssh -p 2222 [email protected]");
105 expect(theirs).not.toContain("The terminal is off");
106 });
107
108 test("an app with no tty says the terminal is off, to a writer only", async () => {
109 putLive(null);
110 const mine = await appPage(writer);
111 expect(mine).toContain("The terminal is off");
112 expect(mine).not.toContain("ssh -p 2222 [email protected]");
113 const theirs = await appPage(reader);
114 expect(theirs).not.toContain("The terminal is off");
115 });
116
117 // Issue #283: a hosted forge (an app of another forge) defaults
118 // FORGE_SSH_PORT to 0, so serve() never opens a listener — every app on
119 // it declares a tty but has nothing to connect it to. The generic "The
120 // terminal is off." leaves a reader with no idea why or what to do; this
121 // asserts the line names FORGE_SSH_PORT instead, composed from the same
122 // sshPort field the other tests here already pin (#77's ground) rather
123 // than by shutting a real listener down.
124 test("a hosted forge with no SSH listener says the terminal is off, with nothing an operator would act on (#11948)", async () => {
125 putLive("bun run src/tty.ts");
126 app.config.sshPort = 0;
127 try {
128 const mine = await appPage(writer);
129 expect(mine).not.toContain("FORGE_SSH_PORT");
130 expect(mine).toContain("The terminal is off.");
131 expect(mine).not.toContain("ssh -p 2222 [email protected]");
132 } finally {
133 app.config.sshPort = 2222;
134 }
135 });
136 });
test/studio-door.test.ts deleted −1593
@@ -1,1593 +0,0 @@
1 /**
2 * The studio: the owner's page, every preview, the home that keeps itself
3 * current, the head, the terminal and the live fragment. One of the files
4 * the studio's suite was split into so no one file sets the gate's floor
5 * (#2038); the rest are test/studio*.test.ts.
6 *
7 * One forge for the whole file (#3566): each block below owns its own
8 * people and repositories on it, and one runtime — registered, never
9 * started — holds the environments a block puts where a deploy would
10 * have, so nothing here waits on an install, a health check or a clock.
11 */
12
13 import {
14 afterAll,
15 beforeAll,
16 beforeEach,
17 describe,
18 expect,
19 test,
20 } from "bun:test";
21 import { mkdtemp, rm } from "node:fs/promises";
22 import { tmpdir } from "node:os";
23 import { join } from "node:path";
24 import { createApp, type App } from "../src/app.ts";
25 import { setSsh } from "../src/settings/ssh.ts";
26 import { enableApp } from "../src/actions/apps.ts";
27 import { previewEnv, type EnvName } from "../src/apps/data.ts";
28 import { AppsRuntime } from "../src/apps/runtime.ts";
29 import { getAppByRepo, type AppRecord } from "../src/core/apps.ts";
30 import { addToCrew, createAgent } from "../src/actions/crew.ts";
31 import { createOrg } from "../src/actions/orgs.ts";
32 import {
33 assignIssue,
34 openIssue,
35 setIssueState,
36 } from "../src/actions/issues.ts";
37 import { mergePull, openPull } from "../src/actions/pulls.ts";
38 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
39 import { KIND_CHIPS, setChip } from "../src/core/feed_chips.ts";
40 import type { Issue } from "../src/core/issues.ts";
41 import type { Pull } from "../src/core/pulls.ts";
42 import type { Repo } from "../src/core/repos.ts";
43 import {
44 claimRun,
45 createRun,
46 finishRun,
47 getRun,
48 markServing,
49 } from "../src/core/runs.ts";
50 import { liveClientJs } from "../src/web/live.ts";
51 import { createUser, getUserByName, type User } from "../src/core/users.ts";
52 import { serve, type Servers } from "../src/http/server.ts";
53 import { promote } from "./helpers/members.ts";
54 import { withScripts } from "./helpers/page-script.ts";
55 import { ageApp } from "./helpers/history.ts";
56
57 let dataDir: string;
58 let app: App;
59 let servers: Servers;
60 let base: string;
61 let runtime: AppsRuntime;
62
63 beforeAll(async () => {
64 dataDir = await mkdtemp(join(tmpdir(), "forge-studio-door-"));
65 // The terminal's block reads its command off this host.
66 app = createApp({ dataDir, port: 0, host: "forge.example" });
67 setSsh(app.db, true, "test");
68 servers = await serve(app);
69 base = servers.url;
70 runtime = new AppsRuntime(app, {
71 domain: "apps.test",
72 scheme: "http",
73 publicPort: servers.port,
74 forgeUrl: servers.url,
75 concurrency: 1,
76 });
77 // The forge's first account, and so its admin; bob and carol are readers
78 // and strangers to alice's apps.
79 await person("alice", true);
80 await person("bob");
81 await person("carol");
82 });
83
84 afterAll(async () => {
85 // The slots stand in for deploys; there is no process behind them to stop.
86 slots().clear();
87 await runtime.stop();
88 servers.stop();
89 app.close();
90 await rm(dataDir, { recursive: true, force: true });
91 });
92
93 const PASSWORD = "a-good-passphrase";
94
95 /** A person on the shared forge, promoted past the newcomer's limits. */
96 async function person(username: string, adminIfFirst = false): Promise<User> {
97 const made = await createUser(app.db, { origin: "seed", trusted: true,
98 username,
99 email: `${username}@forge.local`,
100 password: PASSWORD,
101 adminIfFirst,
102 });
103 if (!made.ok) throw new Error(made.error);
104 promote(app.db, made.value);
105 return made.value;
106 }
107
108 /** The session cookie `username` signs in with. */
109 const signIn = async (username: string, password = PASSWORD): Promise<string> =>
110 (
111 (
112 await fetch(`${base}/signin`, {
113 method: "POST",
114 body: new URLSearchParams({ username, password }),
115 redirect: "manual",
116 })
117 ).headers.get("set-cookie") ?? ""
118 ).split(";")[0]!;
119
120 /**
121 * An environment as the runtime holds it, without running a deploy: the
122 * pages read `runtime.status(record)`, and a real one would mean a real
123 * install and a real health check for a rendering test.
124 */
125 interface Slot {
126 readonly app: AppRecord;
127 readonly env: EnvName;
128 readonly chain: Promise<void>;
129 readonly restarts: number[];
130 readonly deploying?: unknown;
131 readonly live?: unknown;
132 readonly lastError?: string;
133 readonly lastRunId?: string;
134 readonly lastErrorCommitOid?: string;
135 }
136 const slots = (): Map<string, Slot> =>
137 (runtime as unknown as { envs: Map<string, Slot> }).envs;
138
139 const putEnv = (
140 record: AppRecord,
141 env: EnvName,
142 slot: Omit<Slot, "app" | "env" | "chain" | "restarts">,
143 ): void => {
144 slots().set(`${record.id}/${env}`, {
145 app: record,
146 env,
147 chain: Promise.resolve(),
148 restarts: [],
149 ...slot,
150 });
151 };
152
153 /** Take every environment of `record` away, as if none had ever deployed. */
154 const clearEnvs = (record: AppRecord): void => {
155 for (const key of [...slots().keys()])
156 if (key.startsWith(`${record.id}/`)) slots().delete(key);
157 };
158
159 describe("an owner's page lists an app once, not once in each vocabulary (#221)", () => {
160 const occurrences = (haystack: string, needle: string): number =>
161 haystack.split(needle).length - 1;
162
163 test("a person with one app and one plain repository renders each once, in every mode; one with no app shows a visitor no apps card at all", async () => {
164 const dan = await createUser(app.db, { origin: "seed", trusted: true,
165 username: "dan",
166 email: "[email protected]",
167 password: "a-good-passphrase",
168 adminIfFirst: true,
169 });
170 if (!dan.ok) throw new Error(dan.error);
171 promote(app.db, dan.value);
172 const cookie = await signIn("dan", "a-good-passphrase");
173
174 const madeApp = await createRepo(app, dan.value, {
175 name: "beacon",
176 visibility: "public",
177 description: "a lighthouse",
178 });
179 if (!madeApp.ok) throw new Error(String(madeApp.error));
180 const appSeeded = await commitToBranch(app, dan.value, madeApp.value, {
181 message: "Start",
182 files: [{ path: "README.md", content: "hi\n" }],
183 });
184 if (!appSeeded.ok) throw new Error(JSON.stringify(appSeeded.error));
185 // Not "beacon": alice's app in the terminal's block holds that slug.
186 const enabled = await enableApp(app, dan.value, madeApp.value, {
187 slug: "dan-beacon",
188 });
189 if (!enabled.ok) throw new Error(String(enabled.error));
190
191 const madePlain = await createRepo(app, dan.value, {
192 name: "scratch",
193 visibility: "public",
194 description: "not an app",
195 });
196 if (!madePlain.ok) throw new Error(String(madePlain.error));
197 const plainSeeded = await commitToBranch(app, dan.value, madePlain.value, {
198 message: "Start",
199 files: [{ path: "README.md", content: "hi\n" }],
200 });
201 if (!plainSeeded.ok) throw new Error(JSON.stringify(plainSeeded.error));
202
203 const studio = await (
204 await fetch(`${base}/dan`, {
205 headers: { cookie: `${cookie}; forge_mode=studio` },
206 redirect: "manual",
207 })
208 ).text();
209 expect(occurrences(studio, 'href="/dan/beacon"')).toBe(1);
210 expect(occurrences(studio, 'href="/dan/scratch"')).toBe(1);
211 expect(studio).toContain("<h2>Other repositories</h2>");
212
213 const dev = await (
214 await fetch(`${base}/dan`, {
215 headers: { cookie: `${cookie}; forge_mode=dev` },
216 redirect: "manual",
217 })
218 ).text();
219 expect(occurrences(dev, 'href="/dan/beacon"')).toBe(1);
220 expect(occurrences(dev, 'href="/dan/scratch"')).toBe(1);
221 expect(dev).toContain("<h2>Apps</h2>");
222 expect(dev).toContain("<h2>Other repositories</h2>");
223
224 // Someone with repositories and no app: a visitor is not shown an empty
225 // apps card, and the list is simply their repositories.
226 const gus = await createUser(app.db, { origin: "seed", trusted: true,
227 username: "gus",
228 email: "[email protected]",
229 password: "a-good-passphrase",
230 });
231 if (!gus.ok) throw new Error(gus.error);
232 promote(app.db, gus.value);
233 const plainOnly = await createRepo(app, gus.value, {
234 name: "notebook",
235 visibility: "public",
236 description: "",
237 });
238 if (!plainOnly.ok) throw new Error(String(plainOnly.error));
239 const visit = await (
240 await fetch(`${base}/gus`, {
241 headers: { cookie: `${cookie}; forge_mode=studio` },
242 redirect: "manual",
243 })
244 ).text();
245 expect(visit).not.toContain("No apps yet");
246 expect(visit).toContain("<h2>Repositories</h2>");
247 expect(visit).toContain('href="/gus/notebook"');
248 });
249
250 test("an owner whose only repository is an app reads the empty list below as no other repositories, not as a bug", async () => {
251 const eve = await createUser(app.db, { origin: "seed", trusted: true,
252 username: "eve",
253 email: "[email protected]",
254 password: "a-good-passphrase",
255 });
256 if (!eve.ok) throw new Error(eve.error);
257 promote(app.db, eve.value);
258 const cookie = await signIn("eve", "a-good-passphrase");
259
260 const madeApp = await createRepo(app, eve.value, {
261 name: "lighthouse",
262 visibility: "public",
263 });
264 if (!madeApp.ok) throw new Error(String(madeApp.error));
265 const seeded = await commitToBranch(app, eve.value, madeApp.value, {
266 message: "Start",
267 files: [{ path: "README.md", content: "hi\n" }],
268 });
269 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
270 const enabled = await enableApp(app, eve.value, madeApp.value, {
271 slug: "lighthouse",
272 });
273 if (!enabled.ok) throw new Error(String(enabled.error));
274
275 const studio = await (
276 await fetch(`${base}/eve`, {
277 headers: { cookie: `${cookie}; forge_mode=studio` },
278 redirect: "manual",
279 })
280 ).text();
281 expect(occurrences(studio, 'href="/eve/lighthouse"')).toBe(1);
282 expect(studio).toContain("No other repositories");
283 expect(studio).not.toContain("<h2>Other repositories</h2>");
284 });
285
286 test("a private app on a public repository shows its state only to its writers: a visitor gets a plain row", async () => {
287 const hal = await createUser(app.db, { origin: "seed", trusted: true,
288 username: "hal",
289 email: "[email protected]",
290 password: "a-good-passphrase",
291 });
292 if (!hal.ok) throw new Error(hal.error);
293 promote(app.db, hal.value);
294 const ownerCookie = await signIn("hal", "a-good-passphrase");
295 const made = await createRepo(app, hal.value, {
296 name: "ledger",
297 visibility: "public",
298 description: "the books",
299 });
300 if (!made.ok) throw new Error(String(made.error));
301 const seeded = await commitToBranch(app, hal.value, made.value, {
302 message: "Start",
303 files: [{ path: "README.md", content: "hi\n" }],
304 });
305 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
306 const enabled = await enableApp(app, hal.value, made.value, {
307 slug: "hal-ledger",
308 access: "private",
309 });
310 if (!enabled.ok) throw new Error(String(enabled.error));
311 const ivy = await createUser(app.db, { origin: "seed", trusted: true,
312 username: "ivy",
313 email: "[email protected]",
314 password: "a-good-passphrase",
315 });
316 if (!ivy.ok) throw new Error(ivy.error);
317 promote(app.db, ivy.value);
318 const strangerCookie = await signIn("ivy", "a-good-passphrase");
319
320 const visit = (cookie?: string) =>
321 fetch(`${base}/hal`, {
322 headers: cookie === undefined ? {} : { cookie },
323 redirect: "manual",
324 }).then((r) => r.text());
325 // The palette index lists other, public apps and their state; the page is what is under test.
326 const bare = (html: string) => html.replace(/<script[^>]*id="palette-index">.*?<\/script>/s, "");
327 for (const page of [bare(await visit()), bare(await visit(strangerCookie))]) {
328 // The repository is public, so it is listed — once, plainly.
329 expect(occurrences(page, 'href="/hal/ledger"')).toBe(1);
330 expect(page).toContain("the books");
331 expect(page).not.toContain("not running");
332 expect(page).not.toContain("quiet");
333 expect(page).not.toContain('class="studio-word"');
334 }
335 // Nor does the palette hand a visitor the private app's door.
336 for (const raw of [await visit(), await visit(strangerCookie)])
337 expect(raw).not.toContain("/hal/ledger/app/production/open");
338 const own = await visit(ownerCookie);
339 expect(own).toContain("not running");
340 });
341
342 test("an org's page draws the same way: its app once, its plain repository once, and Members/Teams unmoved", async () => {
343 const fay = await createUser(app.db, { origin: "seed", trusted: true,
344 username: "fay",
345 email: "[email protected]",
346 password: "a-good-passphrase",
347 });
348 if (!fay.ok) throw new Error(fay.error);
349 promote(app.db, fay.value);
350 const cookie = await signIn("fay", "a-good-passphrase");
351
352 const org = await createOrg(app, fay.value, "vega");
353 if (!org.ok) throw new Error(org.error);
354
355 const madeApp = await createRepo(app, fay.value, {
356 name: "anvil",
357 owner: "vega",
358 visibility: "public",
359 });
360 if (!madeApp.ok) throw new Error(String(madeApp.error));
361 const appSeeded = await commitToBranch(app, fay.value, madeApp.value, {
362 message: "Start",
363 files: [{ path: "README.md", content: "hi\n" }],
364 });
365 if (!appSeeded.ok) throw new Error(JSON.stringify(appSeeded.error));
366 const enabled = await enableApp(app, fay.value, madeApp.value, {
367 slug: "anvil",
368 });
369 if (!enabled.ok) throw new Error(String(enabled.error));
370
371 const madePlain = await createRepo(app, fay.value, {
372 name: "ledger",
373 owner: "vega",
374 visibility: "public",
375 });
376 if (!madePlain.ok) throw new Error(String(madePlain.error));
377 const plainSeeded = await commitToBranch(app, fay.value, madePlain.value, {
378 message: "Start",
379 files: [{ path: "README.md", content: "hi\n" }],
380 });
381 if (!plainSeeded.ok) throw new Error(JSON.stringify(plainSeeded.error));
382
383 const studio = await (
384 await fetch(`${base}/vega`, {
385 headers: { cookie: `${cookie}; forge_mode=studio` },
386 redirect: "manual",
387 })
388 ).text();
389 expect(occurrences(studio, 'href="/vega/anvil"')).toBe(1);
390 expect(occurrences(studio, 'href="/vega/ledger"')).toBe(1);
391 expect(studio).toContain('<h2>Members</h2>');
392 expect(studio).toContain('<h2 id="teams">Teams</h2>');
393
394 const dev = await (
395 await fetch(`${base}/vega`, {
396 headers: { cookie: `${cookie}; forge_mode=dev` },
397 redirect: "manual",
398 })
399 ).text();
400 expect(occurrences(dev, 'href="/vega/anvil"')).toBe(1);
401 expect(occurrences(dev, 'href="/vega/ledger"')).toBe(1);
402 });
403 });
404
405 describe("every open pull's preview on the studio page", () => {
406 let cookie: string;
407 let repo: Repo;
408 let record: AppRecord;
409
410 const get = (path: string) =>
411 fetch(`${base}${path}`, {
412 headers: { cookie: `${cookie}; forge_mode=studio` },
413 redirect: "manual",
414 });
415
416 // The tests take turns on one repository: the first leaves no pull open,
417 // which is the second's start.
418 beforeAll(async () => {
419 const alice = getUserByName(app.db, "alice")!;
420 cookie = await signIn("alice");
421 const made = await createRepo(app, alice, {
422 name: "widget",
423 visibility: "public",
424 description: "",
425 });
426 if (!made.ok) throw new Error(String(made.error));
427 repo = made.value;
428 const seeded = await commitToBranch(app, alice, repo, {
429 message: "Start",
430 files: [{ path: "README.md", content: "w\n" }],
431 });
432 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
433 const enabled = await enableApp(app, alice, repo, { slug: "widget" });
434 if (!enabled.ok) throw new Error(String(enabled.error));
435 record = getAppByRepo(app.db, repo.id)!;
436 // An older app: a new one shows only its progress, without the list (#10299).
437 ageApp(app.db, repo.id);
438 });
439
440 test("an open pull's preview host and open link render; none do once nothing is open", async () => {
441 const alice = getUserByName(app.db, "alice")!;
442 const before = await (await get("/alice/widget")).text();
443 expect(before).not.toContain("<h2>Previews</h2>");
444
445 const branch = await commitToBranch(app, alice, repo, {
446 branch: "feature/x",
447 base: repo.defaultBranch,
448 message: "Add X",
449 files: [{ path: "X.md", content: "x\n" }],
450 });
451 if (!branch.ok) throw new Error(JSON.stringify(branch.error));
452 const opened = await openPull(app, alice, repo, {
453 title: "Add X",
454 body: "",
455 baseBranch: repo.defaultBranch,
456 headBranch: "feature/x",
457 });
458 if (!opened.ok) throw new Error(String(opened.error));
459 const pull = opened.value;
460
461 const page = await (await get("/alice/widget")).text();
462 expect(page).toContain("<h2>Previews</h2>");
463 expect(page).toContain(`href="/alice/widget/app/pull-${pull.number}/open"`);
464 expect(page).toContain(`#${pull.number} Add X`);
465
466 const merged = await mergePull(app, alice, repo, pull, "squash");
467 expect(merged.ok).toBe(true);
468 const after = await (await get("/alice/widget")).text();
469 expect(after).not.toContain("<h2>Previews</h2>");
470 expect(after).not.toContain(`pull-${pull.number}/open`);
471 });
472
473 test("a change's page names its preview's data as its own copy and gives the moment it was taken; production's card does not", async () => {
474 const alice = getUserByName(app.db, "alice")!;
475 const branch = await commitToBranch(app, alice, repo, {
476 branch: "feature/y",
477 base: repo.defaultBranch,
478 message: "Add Y",
479 files: [{ path: "Y.md", content: "y\n" }],
480 });
481 if (!branch.ok) throw new Error(JSON.stringify(branch.error));
482 const opened = await openPull(app, alice, repo, {
483 title: "Add Y",
484 body: "",
485 baseBranch: repo.defaultBranch,
486 headBranch: "feature/y",
487 });
488 if (!opened.ok) throw new Error(String(opened.error));
489 const pull = opened.value;
490 const env = previewEnv(pull.number);
491
492 // Production and the preview both serving, as a deploy leaves them;
493 // test/apps.test.ts proves a real preview gets its copy of the data.
494 const serving = (commitOid: string) => ({
495 live: {
496 commitOid,
497 handle: { port: 4321 },
498 runId: "fake",
499 since: new Date().toISOString(),
500 manifest: { tty: null },
501 },
502 });
503 putEnv(record, "production", serving("0".repeat(40)));
504 putEnv(record, env, serving(pull.headOid));
505
506 const note = "its own copy of production's data, taken";
507
508 const appPage = await (await get("/alice/widget")).text();
509 expect(appPage).toContain(note);
510 // Production's own card, above the previews list, never says it.
511 const production = appPage.slice(0, appPage.indexOf("<h2>Previews</h2>"));
512 expect(production).not.toContain(note);
513
514 const changePage = await (
515 await get(`/alice/widget/pulls/${pull.number}`)
516 ).text();
517 expect(changePage).toContain("<h2>Preview</h2>");
518 expect(changePage).toContain(note);
519 // One flow (#14241): the notes, the thread and the comment box run down one column and the
520 // preview sits beside them in the same block, so nothing tall on the side opens a gap above the thread.
521 expect(changePage).toContain('<div class="split" data-pull>');
522 expect(changePage).not.toContain("data-top");
523 const flow = changePage.slice(changePage.indexOf('<div class="split" data-pull>'));
524 expect(flow.indexOf("comment-form")).toBeGreaterThan(-1);
525 expect(flow.indexOf("comment-form")).toBeLessThan(flow.indexOf('id="pull-preview"'));
526 expect(flow.slice(0, flow.indexOf('id="pull-preview"')).match(/<aside>/g)?.length).toBe(1);
527 });
528 });
529
530 /**
531 * The studio home keeps itself current: Asks you, Your apps and On you are
532 * each a live region — no second fragment endpoint, the same `studioHome`
533 * render as the first paint, fetched again on a matching event and swapped
534 * in place by `liveRegionsJs` (`src/web/client.ts`).
535 */
536 describe("the studio home keeps itself current", () => {
537 let alice: User;
538 let repo: Repo;
539 let cookie: string;
540 let pull: Pull;
541 let readme: Issue;
542
543 const get = (extraCookie = "") =>
544 fetch(`${base}/feed`, {
545 headers: {
546 cookie: `${cookie}${extraCookie}; forge_mode=studio`,
547 },
548 redirect: "manual",
549 });
550
551 beforeAll(async () => {
552 alice = getUserByName(app.db, "alice")!;
553 cookie = await signIn("alice");
554 const made = await createRepo(app, alice, {
555 name: "signals",
556 visibility: "private",
557 description: "",
558 });
559 if (!made.ok) throw new Error(String(made.error));
560 repo = made.value;
561 const seeded = await commitToBranch(app, alice, repo, {
562 message: "Start",
563 files: [{ path: "README.md", content: "s\n" }],
564 });
565 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
566 const enabled = await enableApp(app, alice, repo, { slug: "signals" });
567 if (!enabled.ok) throw new Error(String(enabled.error));
568 const scout = await createAgent(app, alice, { username: "scout" });
569 if (!scout.ok) throw new Error(String(scout.error));
570 expect(addToCrew(app, alice, repo, "scout").ok).toBe(true);
571 const scoutUser = getUserByName(app.db, "scout")!;
572 const branch = await commitToBranch(app, alice, repo, {
573 branch: "feature/x",
574 base: "main",
575 message: "Add x",
576 files: [{ path: "x.md", content: "x\n" }],
577 });
578 if (!branch.ok) throw new Error(JSON.stringify(branch.error));
579 const opened = await openPull(app, scoutUser, repo, {
580 title: "Add x",
581 body: "",
582 baseBranch: "main",
583 headBranch: "feature/x",
584 });
585 if (!opened.ok) throw new Error(String(opened.error));
586 pull = opened.value;
587 const run = createRun(app.db, {
588 repoId: repo.id,
589 kind: "check",
590 issueId: pull.id,
591 env: `pull-${pull.number}`,
592 commitOid: pull.headOid,
593 reason: "pull",
594 });
595 claimRun(app.db, run.id);
596 finishRun(app.db, run.id, { state: "ok", summary: "check passed" });
597
598 const asked = openIssue(app, alice, repo, { title: "Write the README" });
599 if (!asked.ok) throw new Error(String(asked.error));
600 readme = asked.value;
601 expect(assignIssue(app, alice, repo, readme, alice).ok).toBe(true);
602 });
603
604 test("Your apps is a live region and the home has no On you, with the security floor's headers", async () => {
605 const res = await get();
606 expect(res.status).toBe(200);
607 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
608 expect(res.headers.get("referrer-policy")).toBe("same-origin");
609 const home = await res.text();
610 expect(home).toMatch(/id="live-apps"\s*\n?\s*data-live="/);
611 expect(home).not.toContain("live-on-you");
612 expect(await withScripts(servers.url, home)).toContain("new EventSource('/events')");
613 });
614
615 test("chips do not touch Your apps: it lists apps, not feed items", async () => {
616 for (const kind of KIND_CHIPS) setChip(app.db, alice.id, { kind: "kind", value: kind }, true);
617 const res = await fetch(`${base}/live/apps`, { headers: { cookie: `${cookie}; forge_mode=studio` } });
618 expect(await res.text()).toContain(`${repo.name}`);
619 for (const kind of KIND_CHIPS) setChip(app.db, alice.id, { kind: "kind", value: kind }, false);
620 });
621
622 test("each region on the home has an address of its own, answering with that region alone and 304 when it has not changed", async () => {
623 const page = await (await get()).text();
624 expect(page).toContain('data-live-src="/live/apps"');
625 expect(page).not.toContain("/live/on-you");
626
627 const headers = { cookie: `${cookie}; forge_mode=studio` };
628 const apps = await fetch(`${base}/live/apps`, { headers });
629 expect(apps.status).toBe(200);
630 const appsText = await apps.text();
631 expect(appsText).toContain('id="live-apps"');
632 expect(appsText).toContain(`${repo.name}`);
633 expect(appsText).not.toContain("<html");
634 const tag = apps.headers.get("etag");
635 expect(tag).toMatch(/^"[0-9a-f]{16}"$/);
636 const unchanged = await fetch(`${base}/live/apps`, {
637 headers: { ...headers, "if-none-match": tag! },
638 });
639 expect(unchanged.status).toBe(304);
640
641 const onYou = await fetch(`${base}/live/on-you`, { headers });
642 expect(onYou.status).toBe(200);
643 expect(await onYou.text()).toContain('id="live-on-you"');
644
645 // Signed out, the regions are nobody's.
646 expect((await fetch(`${base}/live/apps`)).status).toBe(404);
647 expect((await fetch(`${base}/live/on-you`)).status).toBe(404);
648 });
649
650 test("a signed-out request gets a signed-out home: no per-viewer live regions, nothing of alice's", async () => {
651 const res = await fetch(`${base}/`, {
652 headers: { cookie: "forge_mode=studio" },
653 redirect: "manual",
654 });
655 expect(res.status).toBe(200);
656 const home = await res.text();
657 expect(home).not.toContain('id="live-asks"');
658 expect(home).not.toContain('id="live-on-you"');
659 expect(home).not.toContain("Add x");
660 expect(home).not.toContain("Write the README");
661 });
662
663 test("a card leaves On you once its issue closes", async () => {
664 // The On you region alone: the timeline still tells of the issue, as a
665 // post does after it is done (#599).
666 const onYou = () =>
667 fetch(`${base}/live/on-you`, {
668 headers: { cookie: `${cookie}; forge_mode=studio` },
669 }).then((r) => r.text());
670 const before = await onYou();
671 expect(before).toContain("Write the README");
672
673 const merged = await mergePull(app, alice, repo, pull, "squash");
674 expect(merged.ok).toBe(true);
675 expect(setIssueState(app, alice, repo, readme, "closed").ok).toBe(true);
676
677 const after = await onYou();
678 expect(after).not.toContain("Write the README");
679 });
680 });
681
682 /**
683 * The studio head of an app that is not up: the same facts the App page
684 * shows — why, the deploy that says the rest, and the way to try again.
685 */
686 describe("the studio head says why the app is not up", () => {
687 let repo: Repo;
688 let record: AppRecord;
689 let deploy: string;
690 let writer: string;
691 let reader: string;
692
693 const head = (cookie: string) =>
694 fetch(`${base}/alice/notes`, {
695 headers: { cookie: `${cookie}; forge_mode=studio` },
696 redirect: "manual",
697 }).then((r) => r.text());
698
699 /** The home's own shelf row for this app — the badge issue #201 is about. */
700 // The shelf's rows are `/apps` (#599: home is the feed).
701 const shelfBadge = async (cookie: string): Promise<string> => {
702 const home = await (
703 await fetch(`${base}/apps`, {
704 headers: { cookie: `${cookie}; forge_mode=studio` },
705 redirect: "manual",
706 })
707 ).text();
708 const at = home.indexOf('href="/alice/notes"');
709 expect(at).toBeGreaterThan(-1);
710 const start = home.lastIndexOf("<li>", at);
711 const row = home.slice(start, home.indexOf("</li>", at) + 5);
712 return row.match(/<span class="badge"[^>]*>([\s\S]*?)<\/span>/)?.[1] ?? "";
713 };
714
715 /** Production as the runtime holds it, in place of a real deploy. */
716 const put = (slot: Omit<Slot, "app" | "env" | "chain" | "restarts">): void =>
717 putEnv(record, "production", slot);
718
719 beforeAll(async () => {
720 const alice = getUserByName(app.db, "alice")!;
721 writer = await signIn("alice");
722 reader = await signIn("bob");
723 const made = await createRepo(app, alice, {
724 name: "notes",
725 visibility: "public",
726 description: "a place for notes",
727 });
728 if (!made.ok) throw new Error(String(made.error));
729 repo = made.value;
730 const seeded = await commitToBranch(app, alice, repo, {
731 message: "Start",
732 files: [{ path: "README.md", content: "notes\n" }],
733 });
734 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
735 const enabled = await enableApp(app, alice, repo, { slug: "notes" });
736 if (!enabled.ok) throw new Error(String(enabled.error));
737 record = getAppByRepo(app.db, repo.id)!;
738 const run = createRun(app.db, {
739 repoId: repo.id,
740 kind: "deploy",
741 env: "production",
742 commitOid: seeded.value.commitOid,
743 reason: "push",
744 });
745 claimRun(app.db, run.id);
746 finishRun(app.db, run.id, {
747 state: "failed",
748 summary: "the deploy failed",
749 });
750 deploy = run.id;
751 });
752
753 test("a failed production says what failed, links its deploy, and offers Redeploy to a writer only — and offers no live link to the host", async () => {
754 put({
755 lastError: "the deploy failed: <install> exited 1",
756 lastRunId: deploy,
757 });
758 const mine = await head(writer);
759 expect(mine).toContain("not up");
760 // The error is the app's own output: shown, and escaped.
761 expect(mine).toContain("the deploy failed: &lt;install&gt; exited 1");
762 expect(mine).not.toContain("<install>");
763 expect(mine).toContain(`href="/alice/notes/runs/${deploy}"`);
764 expect(mine).toContain('action="/alice/notes/app/production/redeploy"');
765 expect(mine).toContain('href="/-/confirm?to=%2Falice%2Fnotes%2Fapp%2Fproduction%2Fstop"');
766 expect(mine).not.toContain('href="/alice/notes/app/production/open"');
767 expect(mine).toContain('title="The last deploy failed"');
768
769 const theirs = await head(reader);
770 expect(theirs).toContain("not up");
771 expect(theirs).toContain("the deploy failed: &lt;install&gt; exited 1");
772 expect(theirs).toContain(`href="/alice/notes/runs/${deploy}"`);
773 expect(theirs).not.toContain("/app/production/redeploy");
774 expect(theirs).not.toContain("%2Fapp%2Fproduction%2Fstop");
775 expect(theirs).not.toContain('href="/alice/notes/app/production/open"');
776 });
777
778 // Issue #201: the shelf used to print the runtime's raw `EnvState` for a
779 // failed or deploying production, disagreeing with the app's own head
780 // above — which has always spoken the studio's five-ish words.
781 test("a failed production reads 'not up' on the home shelf too, never the runtime's own word 'failed'", async () => {
782 put({
783 lastError: "the deploy failed: <install> exited 1",
784 lastRunId: deploy,
785 });
786 expect(await shelfBadge(writer)).toBe("not up");
787 });
788
789 test("a stopped production says it is not running and offers Redeploy, not Stop — and no live link to the host", async () => {
790 put({ lastRunId: deploy });
791 const mine = await head(writer);
792 expect(mine).toContain("not running");
793 expect(mine).toContain('action="/alice/notes/app/production/redeploy"');
794 expect(mine).not.toContain('href="/-/confirm?to=%2Falice%2Fnotes%2Fapp%2Fproduction%2Fstop"');
795 expect(mine).not.toContain('href="/alice/notes/app/production/open"');
796 expect(mine).toContain('title="Nothing is running yet. The app starts when it is deployed."');
797 expect(await shelfBadge(writer)).toBe("not running");
798 });
799
800 test("a deploying production says so where the button was, not a link to a host nothing is serving yet", async () => {
801 put({
802 deploying: { run: { id: deploy, commitOid: "0".repeat(40) } },
803 });
804 const mine = await head(writer);
805 expect(mine).toContain("starting");
806 expect(mine).not.toContain('href="/alice/notes/app/production/open"');
807 expect(mine).toContain('title="Still deploying"');
808 // The runtime's own word for this state is "deploying" — the shelf
809 // says "starting" instead, same as the head above.
810 expect(await shelfBadge(writer)).toBe("starting");
811 });
812
813 test("a serving app with red tests still reads as serving, with the failure in its own words, and is still open-able", async () => {
814 put({
815 live: {
816 commitOid: "0".repeat(40),
817 handle: { port: 4321 },
818 runId: deploy,
819 since: new Date(Date.now() - 60_000).toISOString(),
820 testsFailed: "1 of 3 tests failed",
821 manifest: { tty: null },
822 },
823 });
824 const mine = await head(writer);
825 expect(mine).toContain("serving · tests failed");
826 expect(mine).not.toContain("not up");
827 expect(mine).toContain("serving · tests failed: 1 of 3 tests failed");
828 expect(mine).toContain('href="/alice/notes/app/production/open"');
829 expect(await shelfBadge(writer)).toBe("serving · tests failed");
830 });
831
832 test("a newer push that failed to come up while an older deploy keeps serving: live, not plain green, both commits named, its run linked", async () => {
833 const failed = createRun(app.db, {
834 repoId: repo.id,
835 kind: "deploy",
836 env: "production",
837 commitOid: "2".repeat(40),
838 reason: "push",
839 });
840 claimRun(app.db, failed.id);
841 finishRun(app.db, failed.id, {
842 state: "failed",
843 summary: "forge.json: JSON Parse error: Unexpected token '}'",
844 });
845 put({
846 live: {
847 commitOid: "1".repeat(40),
848 handle: { port: 4321 },
849 runId: deploy,
850 since: new Date(Date.now() - 60_000).toISOString(),
851 manifest: { tty: null },
852 },
853 lastError: "forge.json: JSON Parse error: Unexpected token '}'",
854 lastRunId: failed.id,
855 lastErrorCommitOid: "2".repeat(40),
856 });
857 const mine = await head(writer);
858 // It answers — still "live", never "not up" — but not untroubled green.
859 expect(mine).toContain("live");
860 expect(mine).not.toContain("not up");
861 expect(mine).toContain('href="/alice/notes/app/production/open"');
862 // Both commits, named.
863 expect(mine).toContain("1111111");
864 expect(mine).toContain("2222222");
865 expect(mine).toContain("did not come up");
866 expect(mine).toContain(
867 "forge.json: JSON Parse error: Unexpected token &#39;}&#39;",
868 );
869 // The failed run's log, one click away.
870 expect(mine).toContain(`href="/alice/notes/runs/${failed.id}"`);
871 });
872
873 test("a clean deploy with no failure behind it is unchanged: plain live, no failed-run link", async () => {
874 put({
875 live: {
876 commitOid: "1".repeat(40),
877 handle: { port: 4321 },
878 runId: deploy,
879 since: new Date(Date.now() - 60_000).toISOString(),
880 manifest: { tty: null },
881 },
882 });
883 const mine = await head(writer);
884 expect(mine).toContain("live");
885 expect(mine).not.toContain("did not come up");
886 });
887 });
888
889 /**
890 * The studio app page's Terminal — the one door an operator has into what
891 * is running. `terminalFor` (`src/actions/apps.ts`) is the single fact both
892 * this page and the dev App page read; this only checks it is drawn (or
893 * withheld) correctly, not recomputed.
894 */
895 describe("the studio app page's terminal", () => {
896 let repo: Repo;
897 let record: AppRecord;
898 let writer: string;
899 let reader: string;
900 // What the forge had before this block gave it a listener and a key.
901 let before: Pick<App["config"], "sshPort" | "sshHostKey">;
902
903 const putLive = (tty: string | null): void =>
904 putEnv(record, "production", {
905 live: {
906 commitOid: "a".repeat(40),
907 handle: { port: 4321 },
908 runId: "fake",
909 since: new Date().toISOString(),
910 manifest: { tty },
911 },
912 });
913
914 const appPage = (cookie: string) =>
915 fetch(`${base}/alice/beacon`, {
916 headers: { cookie: `${cookie}; forge_mode=studio` },
917 redirect: "manual",
918 }).then((r) => r.text());
919
920 beforeAll(async () => {
921 before = { ...app.config };
922 app.config.sshPort = 2222;
923 app.config.sshHostKey =
924 "SHA256:abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG";
925 const alice = getUserByName(app.db, "alice")!;
926 writer = await signIn("alice");
927 reader = await signIn("bob");
928 const made = await createRepo(app, alice, {
929 name: "beacon",
930 visibility: "public",
931 description: "a light that stays on",
932 });
933 if (!made.ok) throw new Error(String(made.error));
934 repo = made.value;
935 const seeded = await commitToBranch(app, alice, repo, {
936 message: "Start",
937 files: [{ path: "README.md", content: "beacon\n" }],
938 });
939 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
940 const enabled = await enableApp(app, alice, repo, { slug: "beacon" });
941 if (!enabled.ok) throw new Error(String(enabled.error));
942 record = getAppByRepo(app.db, repo.id)!;
943 });
944
945 afterAll(() => {
946 if (before.sshPort === undefined) delete app.config.sshPort;
947 else app.config.sshPort = before.sshPort;
948 if (before.sshHostKey === undefined) delete app.config.sshHostKey;
949 else app.config.sshHostKey = before.sshHostKey;
950 });
951
952 test("a writer sees the exact command and the host key; a reader sees neither", async () => {
953 putLive("bun run src/tty.ts");
954 const mine = await appPage(writer);
955 expect(mine).toContain("ssh -p 2222 [email protected]");
956 expect(mine).toContain("host key SHA256:abcdefghijklmnopqrstuvwxyz");
957 // Wrapped in the marker an email-scanning edge honours, so the
958 // login@host in the command is never rewritten into a mailto: link —
959 // and the command itself sits between the markers unchanged.
960 expect(mine).toContain(
961 "<!--email_off-->ssh -p 2222 [email protected]<!--/email_off-->",
962 );
963 const theirs = await appPage(reader);
964 expect(theirs).not.toContain("ssh -p 2222 [email protected]");
965 expect(theirs).not.toContain("The terminal is off");
966 });
967
968 test("an app with no tty says the terminal is off, to a writer only", async () => {
969 putLive(null);
970 const mine = await appPage(writer);
971 expect(mine).toContain("The terminal is off");
972 expect(mine).not.toContain("ssh -p 2222 [email protected]");
973 const theirs = await appPage(reader);
974 expect(theirs).not.toContain("The terminal is off");
975 });
976
977 // Issue #283: a hosted forge (an app of another forge) defaults
978 // FORGE_SSH_PORT to 0, so serve() never opens a listener — every app on
979 // it declares a tty but has nothing to connect it to. The generic "The
980 // terminal is off." leaves a reader with no idea why or what to do; this
981 // asserts the line names FORGE_SSH_PORT instead, composed from the same
982 // sshPort field the other tests here already pin (#77's ground) rather
983 // than by shutting a real listener down.
984 test("a hosted forge with no SSH listener says the terminal is off, with nothing an operator would act on (#11948)", async () => {
985 putLive("bun run src/tty.ts");
986 app.config.sshPort = 0;
987 try {
988 const mine = await appPage(writer);
989 expect(mine).not.toContain("FORGE_SSH_PORT");
990 expect(mine).toContain("The terminal is off.");
991 expect(mine).not.toContain("ssh -p 2222 [email protected]");
992 } finally {
993 app.config.sshPort = 2222;
994 }
995 });
996 });
997
998 /**
999 * GET /:owner/:name/app/state — the fragment the studio page's live client
1000 * fetches on a deploy run event, and swaps into `#app-head`/`#app-previews`
1001 * in place of a reload. It is authorized exactly as the studio page, and
1002 * renders from the same `appPanels` function the page's first paint does.
1003 */
1004 describe("the app's live fragment: /:owner/:name/app/state", () => {
1005 let repo: Repo;
1006 let record: AppRecord;
1007 let owner: string;
1008 let stranger: string;
1009
1010 const get = (path: string, cookie: string) =>
1011 fetch(`${base}${path}`, {
1012 headers: { cookie: `${cookie}; forge_mode=studio` },
1013 redirect: "manual",
1014 });
1015
1016 beforeAll(async () => {
1017 const alice = getUserByName(app.db, "alice")!;
1018 owner = await signIn("alice");
1019 stranger = await signIn("carol");
1020 const made = await createRepo(app, alice, {
1021 name: "vault",
1022 visibility: "private",
1023 description: "",
1024 });
1025 if (!made.ok) throw new Error(String(made.error));
1026 repo = made.value;
1027 const seeded = await commitToBranch(app, alice, repo, {
1028 message: "Start",
1029 files: [{ path: "README.md", content: "v\n" }],
1030 });
1031 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
1032 const enabled = await enableApp(app, alice, repo, { slug: "vault" });
1033 if (!enabled.ok) throw new Error(String(enabled.error));
1034 record = getAppByRepo(app.db, repo.id)!;
1035 });
1036
1037 // Every test starts from an app nothing has deployed: one test's preview
1038 // or production slot would otherwise show in the next's head card. Each
1039 // opens a pull of its own, and reads only that pull's row.
1040 beforeEach(() => clearEnvs(record));
1041
1042 test("renders the head card for a viewer who may see it, with the security floor's headers; refuses one who may not, same as the page", async () => {
1043 const fragment = await get("/alice/vault/app/state", owner);
1044 expect(fragment.status).toBe(200);
1045 expect(fragment.headers.get("x-content-type-options")).toBe("nosniff");
1046 expect(fragment.headers.get("referrer-policy")).toBe("same-origin");
1047 const text = await fragment.text();
1048 expect(text).toContain('id="app-head"');
1049 expect(text).toContain('id="app-previews"');
1050 expect(text).toContain("not running");
1051
1052 const page = await (await get("/alice/vault", owner)).text();
1053 expect(page).toContain("not running");
1054
1055 const refusedFragment = await get("/alice/vault/app/state", stranger);
1056 expect(refusedFragment.status).toBe(404);
1057 const refusedPage = await get("/alice/vault", stranger);
1058 expect(refusedPage.status).toBe(404);
1059 });
1060
1061 test("a change's page has a state fragment of its own: its current word, drawn by the page's own function, refused to whoever the page refuses, and named by the client script (#1094)", async () => {
1062 const branch = await commitToBranch(app, getUserByName(app.db, "alice")!, repo, {
1063 branch: "feature/ship-it",
1064 base: "main",
1065 message: "Ship it",
1066 files: [{ path: "SHIP.md", content: "ship\n" }],
1067 });
1068 if (!branch.ok) throw new Error(JSON.stringify(branch.error));
1069 const opened = await openPull(app, getUserByName(app.db, "alice")!, repo, {
1070 title: "Ship it",
1071 body: "",
1072 baseBranch: "main",
1073 headBranch: "feature/ship-it",
1074 });
1075 if (!opened.ok) throw new Error(String(opened.error));
1076 const n = opened.value.number;
1077
1078 const fragment = await get(`/alice/vault/pulls/${n}/state`, owner);
1079 expect(fragment.status).toBe(200);
1080 expect(fragment.headers.get("x-content-type-options")).toBe("nosniff");
1081 expect(fragment.headers.get("referrer-policy")).toBe("same-origin");
1082 const text = await fragment.text();
1083 expect(text).toContain('id="pull-check"');
1084 expect(text).toContain('id="pull-preview"');
1085 expect(text).toContain("studio-pull-check");
1086 // The page's first paint carries the very same check line.
1087 const pageText = await (await get(`/alice/vault/pulls/${n}`, owner)).text();
1088 const line = (t: string) =>
1089 t.match(/<p[^>]*studio-pull-check[^>]*>[\s\S]*?<\/p>/)?.[0];
1090 expect(line(text)).toBeDefined();
1091 expect(line(pageText)).toBe(line(text));
1092 expect(pageText).toContain('id="pull-check"');
1093 expect(pageText).toContain('data-head="');
1094
1095 expect((await get(`/alice/vault/pulls/${n}/state`, stranger)).status).toBe(404);
1096 expect((await get(`/alice/vault/pulls/999/state`, owner)).status).toBe(404);
1097
1098 const merged = await mergePull(app, getUserByName(app.db, "alice")!, repo, opened.value, "squash");
1099 if (!merged.ok) throw new Error(String(merged.error));
1100 const after = await (await get(`/alice/vault/pulls/${n}/state`, owner)).text();
1101 expect(line(after)).not.toBe(line(text));
1102 // The squash lands a new commit; the fragment names it, so a page that
1103 // saw the merge live can match production's serving against it.
1104 const headOf = (t: string) => t.match(/data-head="([0-9a-f]{40})"/)?.[1];
1105 expect(headOf(text)).toBeDefined();
1106 expect(headOf(after)).toBeDefined();
1107 expect(headOf(after)).not.toBe(headOf(text));
1108 expect(liveClientJs).toContain("#pull-check [data-head]");
1109
1110 expect(liveClientJs).toContain("'/pulls/' + number + '/state'");
1111 expect(liveClientJs).toContain("'pull.merged'");
1112 expect(liveClientJs).toContain("'app.serving'");
1113 });
1114
1115 test("Now has an address of its own: the page's region names it, the fragment answers with the same region, and unchanged bytes come back 304", async () => {
1116 const page = await (await get("/alice/vault", owner)).text();
1117 expect(page).toContain('id="live-now"');
1118 expect(page).toContain('data-live-src="/alice/vault/app/now"');
1119
1120 const first = await get("/alice/vault/app/now", owner);
1121 expect(first.status).toBe(200);
1122 expect(first.headers.get("x-content-type-options")).toBe("nosniff");
1123 expect(first.headers.get("cache-control")).toBe("no-store");
1124 const etag = first.headers.get("etag");
1125 expect(etag).toMatch(/^"[0-9a-f]{16}"$/);
1126 const text = await first.text();
1127 // The tag rides in the markup as well, for a proxy that drops the header.
1128 expect(text).toMatch(/^\s*<div data-etag="[0-9a-f]{16}"/);
1129 expect(`"${/data-etag="([0-9a-f]{16})"/.exec(text)![1]}"`).toBe(etag!);
1130 expect(text).toContain('id="live-now"');
1131 expect(text).toContain('data-live="run.queued,run.started,run.finished,pull.*,issue.*"');
1132 expect(text).toContain('data-live-src="/alice/vault/app/now"');
1133 expect(text).toContain("<h2>Now</h2>");
1134
1135 // The same bytes again: nothing to paint, and nothing sent to paint.
1136 const again = await fetch(`${base}/alice/vault/app/now`, {
1137 headers: {
1138 cookie: `${owner}; forge_mode=studio`,
1139 "if-none-match": etag!,
1140 },
1141 });
1142 expect(again.status).toBe(304);
1143 expect(again.headers.get("etag")).toBe(etag);
1144 expect(await again.text()).toBe("");
1145
1146 // A stale tag is answered in full.
1147 const stale = await fetch(`${base}/alice/vault/app/now`, {
1148 headers: { cookie: `${owner}; forge_mode=studio`, "if-none-match": '"0"' },
1149 });
1150 expect(stale.status).toBe(200);
1151 expect(await stale.text()).toContain("<h2>Now</h2>");
1152
1153 expect((await get("/alice/vault/app/now", stranger)).status).toBe(404);
1154 expect((await fetch(`${base}/alice/vault/app/now`)).status).toBe(404);
1155 });
1156
1157 test("a preview flips from deploying to live between two calls, and the link stays correct", async () => {
1158 const alice = getUserByName(app.db, "alice")!;
1159 const branch = await commitToBranch(app, alice, repo, {
1160 branch: "feature/x",
1161 base: repo.defaultBranch,
1162 message: "Add X",
1163 files: [{ path: "X.md", content: "x\n" }],
1164 });
1165 if (!branch.ok) throw new Error(JSON.stringify(branch.error));
1166 const opened = await openPull(app, alice, repo, {
1167 title: "Add X",
1168 body: "",
1169 baseBranch: repo.defaultBranch,
1170 headBranch: "feature/x",
1171 });
1172 if (!opened.ok) throw new Error(String(opened.error));
1173 const pull = opened.value;
1174 const env = previewEnv(pull.number);
1175 const link = `href="/alice/vault/app/${env}/open"`;
1176
1177 const deployRun = createRun(app.db, {
1178 repoId: repo.id,
1179 kind: "deploy",
1180 env,
1181 commitOid: pull.headOid,
1182 reason: "pull",
1183 });
1184 claimRun(app.db, deployRun.id);
1185 putEnv(record, env, {
1186 deploying: {
1187 run: { id: deployRun.id, commitOid: pull.headOid },
1188 abort: new AbortController(),
1189 },
1190 });
1191 const starting = await (await get("/alice/vault/app/state", owner)).text();
1192 expect(starting).toContain("starting");
1193 expect(starting).not.toContain(">live<");
1194 expect(starting).toContain(link);
1195
1196 finishRun(app.db, deployRun.id, { state: "ok", summary: "deploy" });
1197 putEnv(record, env, {
1198 live: {
1199 commitOid: pull.headOid,
1200 handle: { port: 4321 },
1201 runId: deployRun.id,
1202 since: new Date().toISOString(),
1203 manifest: { tty: null },
1204 },
1205 });
1206 const live = await (await get("/alice/vault/app/state", owner)).text();
1207 expect(live).not.toContain("starting");
1208 expect(live).toContain(">live<");
1209 expect(live).toContain(link);
1210 });
1211
1212 test("the fragment's markup is what the live client's status announcement reads: the head's word in a badge, a preview row's word beside its `#N title`", async () => {
1213 // `live.ts`'s `announceSwap` finds the head's word at `.page-head h1
1214 // .badge` and, for a preview row, the pull's label at the start of
1215 // `.row-meta` beside its word at `.row-trail .badge`. If this markup
1216 // ever moves, the announcement goes silent without a test failing here.
1217 const text = await (await get("/alice/vault/app/state", owner)).text();
1218 expect(text).toContain('class="page-head"');
1219 expect(text).toMatch(/class="page-head"[\s\S]*?<h1 class="bar">[\s\S]*?class="badge"[^>]*>not running</);
1220
1221 const alice = getUserByName(app.db, "alice")!;
1222 const branch = await commitToBranch(app, alice, repo, {
1223 branch: "feature/announce",
1224 base: repo.defaultBranch,
1225 message: "Add Y",
1226 files: [{ path: "Y.md", content: "y\n" }],
1227 });
1228 if (!branch.ok) throw new Error(JSON.stringify(branch.error));
1229 const opened = await openPull(app, alice, repo, {
1230 title: "Add Y",
1231 body: "",
1232 baseBranch: repo.defaultBranch,
1233 headBranch: "feature/announce",
1234 });
1235 if (!opened.ok) throw new Error(String(opened.error));
1236 const pull = opened.value;
1237 const env = previewEnv(pull.number);
1238 const deployRun = createRun(app.db, {
1239 repoId: repo.id,
1240 kind: "deploy",
1241 env,
1242 commitOid: pull.headOid,
1243 reason: "pull",
1244 });
1245 claimRun(app.db, deployRun.id);
1246 finishRun(app.db, deployRun.id, { state: "ok", summary: "deploy" });
1247 putEnv(record, env, {
1248 live: {
1249 commitOid: pull.headOid,
1250 handle: { port: 4323 },
1251 runId: deployRun.id,
1252 since: new Date().toISOString(),
1253 manifest: { tty: null },
1254 },
1255 });
1256 const withPreview = await (
1257 await get("/alice/vault/app/state", owner)
1258 ).text();
1259 const label = `#${pull.number} Add Y`;
1260 expect(withPreview).toContain(`class="row-meta"`);
1261 expect(withPreview).toContain(`class="row-trail"`);
1262 expect(withPreview).toContain(label);
1263 expect(
1264 new RegExp(`${label}[\\s\\S]*?class="row-trail"[\\s\\S]*?>live<`).test(
1265 withPreview,
1266 ),
1267 ).toBe(true);
1268 });
1269
1270 test("the head measures from the push, not from the permit it waited for: a deploy queued 5s reads 6.0s after the push and names the wait", async () => {
1271 const createdAt = new Date(Date.now() - 20_000).toISOString();
1272 const deployStartedAt = new Date(
1273 Date.parse(createdAt) + 5_000,
1274 ).toISOString();
1275 const servingAt = new Date(
1276 Date.parse(deployStartedAt) + 1_000,
1277 ).toISOString();
1278 const deployRun = createRun(app.db, {
1279 repoId: repo.id,
1280 kind: "deploy",
1281 env: "production",
1282 commitOid: "cafebabe",
1283 reason: "push",
1284 });
1285 claimRun(app.db, deployRun.id);
1286 finishRun(app.db, deployRun.id, { state: "ok", summary: "deploy" });
1287 putEnv(record, "production", {
1288 live: {
1289 commitOid: "cafebabe",
1290 handle: { port: 4322 },
1291 runId: deployRun.id,
1292 since: servingAt,
1293 servingAt,
1294 createdAt,
1295 deployStartedAt,
1296 manifest: { tty: null },
1297 },
1298 });
1299
1300 const head = await (await get("/alice/vault/app/state", owner)).text();
1301 expect(head).toContain("live 6.0s after the push · 5.0s queued");
1302 expect(head).not.toContain("1.0s after the push");
1303
1304 // The same deployment with no wait for a permit says only the one
1305 // number, exactly as it always has.
1306 putEnv(record, "production", {
1307 live: {
1308 commitOid: "cafebabe",
1309 handle: { port: 4322 },
1310 runId: deployRun.id,
1311 since: servingAt,
1312 servingAt,
1313 createdAt: deployStartedAt,
1314 deployStartedAt,
1315 manifest: { tty: null },
1316 },
1317 });
1318 const prompt = await (await get("/alice/vault/app/state", owner)).text();
1319 expect(prompt).toContain("live 1.0s after the push");
1320 expect(prompt).not.toContain("queued");
1321
1322 // A deploy no push asked for — a redeploy someone pressed — carries no
1323 // push instant, and its words never claim one.
1324 putEnv(record, "production", {
1325 live: {
1326 commitOid: "cafebabe",
1327 handle: { port: 4322 },
1328 runId: deployRun.id,
1329 since: servingAt,
1330 servingAt,
1331 deployStartedAt,
1332 manifest: { tty: null },
1333 },
1334 });
1335 const pressed = await (await get("/alice/vault/app/state", owner)).text();
1336 expect(pressed).toContain("live 1.0s after the deploy started");
1337 expect(pressed).not.toContain("after the push");
1338 });
1339
1340 test("app.serving reaches the repo's stream with the shape the live client keys on, the instant the swap-in happens — before its run has finished", async () => {
1341 const deployRun = createRun(app.db, {
1342 repoId: repo.id,
1343 kind: "deploy",
1344 env: "production",
1345 commitOid: "deadbeef",
1346 reason: "push",
1347 });
1348 claimRun(app.db, deployRun.id);
1349 const served = markServing(app.db, deployRun.id);
1350 expect(served?.servingAt).toBeDefined();
1351
1352 const stream = await fetch(`${base}/alice/vault/stream`, {
1353 headers: { cookie: owner },
1354 });
1355 const reader = stream.body!.getReader();
1356 const decoder = new TextDecoder();
1357 let buffer = "";
1358 // The stream says it is connected as it subscribes: from here on, an
1359 // append reaches it — no sleep stands in for that.
1360 while (!buffer.includes(": connected\n\n")) {
1361 const { done, value } = await reader.read();
1362 if (done) throw new Error("the stream closed before it connected");
1363 buffer += decoder.decode(value);
1364 }
1365
1366 // The exact append `AppsRuntime` makes at the swap-in (runtime.ts),
1367 // republished here so the test does not have to spin up a real deploy.
1368 app.bus.append({
1369 kind: "app.serving",
1370 repoId: repo.id,
1371 payload: {
1372 app: record.slug,
1373 env: "production",
1374 commitOid: deployRun.commitOid,
1375 servingAt: served!.servingAt,
1376 testsRunning: true,
1377 },
1378 });
1379
1380 let event: Record<string, unknown> | undefined;
1381 const deadline = Date.now() + 5_000;
1382 while (!event && Date.now() < deadline) {
1383 const { done, value } = await reader.read();
1384 if (done) break;
1385 buffer += decoder.decode(value);
1386 const frames = buffer.split("\n\n");
1387 buffer = frames.pop() ?? "";
1388 for (const frame of frames) {
1389 if (!/^event: app\.serving$/m.test(frame)) continue;
1390 const data = /^data: (.*)$/m.exec(frame)?.[1];
1391 if (data !== undefined) event = JSON.parse(data);
1392 }
1393 }
1394 if (!event) throw new Error(`never came: still waiting while !event`);
1395 await reader.cancel().catch(() => {});
1396 expect(event).toBeDefined();
1397 expect(event?.["kind"]).toBe("app.serving");
1398 const payload = event?.["payload"] as Record<string, unknown>;
1399 expect(payload["app"]).toBe(record.slug);
1400 expect(payload["env"]).toBe("production");
1401 expect(payload["commitOid"]).toBe(deployRun.commitOid);
1402 expect(payload["servingAt"]).toBe(served!.servingAt);
1403 expect(payload["testsRunning"]).toBe(true);
1404
1405 // finishRun never ran: run.finished has not fired, yet app.serving
1406 // already has. That gap is the whole point of the issue.
1407 expect(getRun(app.db, deployRun.id)?.state).toBe("running");
1408 });
1409
1410 test("production's Open the app link appears only once it is serving, and the fragment after a swap flips it", async () => {
1411 const link = 'href="/alice/vault/app/production/open"';
1412 const deployRun = createRun(app.db, {
1413 repoId: repo.id,
1414 kind: "deploy",
1415 env: "production",
1416 commitOid: "cafed00d",
1417 reason: "push",
1418 });
1419 claimRun(app.db, deployRun.id);
1420 putEnv(record, "production", {
1421 deploying: {
1422 run: { id: deployRun.id, commitOid: "cafed00d" },
1423 abort: new AbortController(),
1424 },
1425 });
1426 const deploying = await (await get("/alice/vault/app/state", owner)).text();
1427 expect(deploying).toContain("starting");
1428 expect(deploying).not.toContain(link);
1429
1430 finishRun(app.db, deployRun.id, { state: "ok", summary: "deploy" });
1431 putEnv(record, "production", {
1432 live: {
1433 commitOid: "cafed00d",
1434 handle: { port: 4325 },
1435 runId: deployRun.id,
1436 since: new Date().toISOString(),
1437 manifest: { tty: null },
1438 },
1439 });
1440 const serving = await (await get("/alice/vault/app/state", owner)).text();
1441 expect(serving).toContain(">live<");
1442 expect(serving).toContain(link);
1443 });
1444 test("a preview row says how fast it got there in envFacts' own words, links its deploy run, and keeps its link and sentence while deploying or after its tests failed", async () => {
1445 const alice = getUserByName(app.db, "alice")!;
1446 const branch = await commitToBranch(app, alice, repo, {
1447 branch: "feature/fast",
1448 base: repo.defaultBranch,
1449 message: "Add F",
1450 files: [{ path: "F.md", content: "f\n" }],
1451 });
1452 if (!branch.ok) throw new Error(JSON.stringify(branch.error));
1453 const opened = await openPull(app, alice, repo, {
1454 title: "Add F",
1455 body: "",
1456 baseBranch: repo.defaultBranch,
1457 headBranch: "feature/fast",
1458 });
1459 if (!opened.ok) throw new Error(String(opened.error));
1460 const pull = opened.value;
1461 const env = previewEnv(pull.number);
1462 const open = `href="/alice/vault/app/${env}/open"`;
1463 const label = `#${pull.number} Add F`;
1464 const deployRun = createRun(app.db, {
1465 repoId: repo.id,
1466 kind: "deploy",
1467 env,
1468 commitOid: pull.headOid,
1469 reason: "pull",
1470 });
1471 const runLink = `href="/alice/vault/runs/${deployRun.id}"`;
1472 // This pull's own row out of the previews panel, so nothing the head
1473 // card or another pull's row says can pass for it.
1474 const rowOf = (text: string): string => {
1475 const panel = text.slice(text.indexOf('id="app-previews"'));
1476 const at = panel.indexOf(label);
1477 expect(at).toBeGreaterThan(-1);
1478 return panel.slice(panel.lastIndexOf("<li>", at), panel.indexOf("</li>", at));
1479 };
1480
1481 claimRun(app.db, deployRun.id);
1482 putEnv(record, env, {
1483 deploying: {
1484 run: { id: deployRun.id, commitOid: pull.headOid },
1485 abort: new AbortController(),
1486 },
1487 });
1488 const deploying = rowOf(
1489 await (await get("/alice/vault/app/state", owner)).text(),
1490 );
1491 expect(deploying).toContain(open);
1492 expect(deploying).toContain(runLink);
1493 expect(deploying).toContain("deploy in progress");
1494 expect(deploying).not.toContain("after the push");
1495 expect(deploying).not.toContain("0.0s");
1496
1497 finishRun(app.db, deployRun.id, { state: "ok", summary: "deploy" });
1498 const createdAt = new Date(Date.now() - 60_000).toISOString();
1499 const servingAt = new Date(Date.parse(createdAt) + 3_400).toISOString();
1500 putEnv(record, env, {
1501 live: {
1502 commitOid: pull.headOid,
1503 handle: { port: 4324 },
1504 runId: deployRun.id,
1505 since: servingAt,
1506 servingAt,
1507 createdAt,
1508 deployStartedAt: createdAt,
1509 manifest: { tty: null },
1510 },
1511 });
1512 const live = rowOf(await (await get("/alice/vault/app/state", owner)).text());
1513 expect(live).toContain(open);
1514 expect(live).toContain("live 3.4s after the push");
1515 expect(live).toContain(pull.headOid.slice(0, 7));
1516 expect(live).toContain(runLink);
1517 expect(live).toContain(">live<");
1518 // The live client keys its announcement on the meta line's first words.
1519 expect(live).toMatch(new RegExp(`class="row-meta">#${pull.number} Add F ·`));
1520 // The page's first paint draws the same row.
1521 expect(await (await get("/alice/vault", owner)).text()).toContain(
1522 "live 3.4s after the push",
1523 );
1524
1525 putEnv(record, env, {
1526 live: {
1527 commitOid: pull.headOid,
1528 handle: { port: 4324 },
1529 runId: deployRun.id,
1530 since: servingAt,
1531 servingAt,
1532 createdAt,
1533 deployStartedAt: createdAt,
1534 testsFailed: "2 failing",
1535 manifest: { tty: null },
1536 },
1537 });
1538 const red = rowOf(await (await get("/alice/vault/app/state", owner)).text());
1539 expect(red).toContain(open);
1540 expect(red).toContain(runLink);
1541 expect(red).toContain("serving · tests failed: 2 failing");
1542 expect(red).toContain("live 3.4s after the push");
1543 // One badge, not green, and the row still links to the preview.
1544 expect(red).toMatch(/data-variant="attn"[^]*?serving · tests failed<\/span/);
1545 expect(red).not.toContain('data-variant="success"');
1546 expect(red).not.toContain(">live<");
1547
1548 putEnv(record, env, {
1549 deploying: {
1550 run: { id: deployRun.id, commitOid: pull.headOid },
1551 abort: new AbortController(),
1552 },
1553 live: {
1554 commitOid: pull.headOid,
1555 handle: { port: 4324 },
1556 runId: deployRun.id,
1557 since: servingAt,
1558 servingAt,
1559 createdAt,
1560 deployStartedAt: createdAt,
1561 manifest: { tty: null },
1562 },
1563 });
1564 const verifying = rowOf(
1565 await (await get("/alice/vault/app/state", owner)).text(),
1566 );
1567 expect(verifying).toContain(open);
1568 expect(verifying).toContain("serving · verifying</span");
1569 expect(verifying).not.toContain('data-variant="success"');
1570 expect(verifying).not.toContain('data-variant="attn"');
1571
1572 putEnv(record, env, {
1573 live: {
1574 commitOid: pull.headOid,
1575 handle: { port: 4324 },
1576 runId: deployRun.id,
1577 since: servingAt,
1578 manifest: { tty: null },
1579 },
1580 });
1581 const unmeasured = rowOf(
1582 await (await get("/alice/vault/app/state", owner)).text(),
1583 );
1584 expect(unmeasured).toContain(open);
1585 expect(unmeasured).not.toContain("after the");
1586 expect(unmeasured).not.toContain("0.0s");
1587 });
1588 });
1589
1590 /**
1591 * On its own: the slots line counts what the loop counts — the builders —
1592 * while Now still shows every run in flight, review and plan included.
1593 */
test/support/mcp-forge.ts added +134
@@ -0,0 +1,134 @@
1 /**
2 * The forge the `mcp-forge-*.test.ts` files drive over MCP: alice (the first
3 * user, an admin), bob (a promoted member), an `rw` and an `ro` token of
4 * alice's and an `rw` token of bob's, and alice's private repository `game`
5 * with one commit and an app record. One forge per test file, so the files
6 * split from `mcp.test.ts` run apart and in parallel (#15351).
7 *
8 * `mcpClient` is the JSON-RPC caller those files share: `call` posts one
9 * request, `tool` reads a tool's answer, `listCall` walks `tools/list`.
10 */
11
12 import { mkdtemp, rm } from "node:fs/promises";
13 import { tmpdir } from "node:os";
14 import { join } from "node:path";
15 import { createApp, type App } from "../../src/app.ts";
16 import { setSsh } from "../../src/settings/ssh.ts";
17 import { commitToBranch, createRepo } from "../../src/actions/repos.ts";
18 import { createApp as insertApp } from "../../src/core/apps.ts";
19 import type { Repo } from "../../src/core/repos.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 import { promote } from "../helpers/members.ts";
24 import { askForReviews } from "../helpers/reviews.ts";
25 import { listVia } from "../mcp-list.ts";
26
27 export interface McpForge {
28 readonly dataDir: string;
29 readonly app: App;
30 readonly servers: Servers;
31 /** The forge's origin, `http://127.0.0.1:<port>`. */
32 readonly base: string;
33 readonly alice: User;
34 readonly bob: User;
35 /** alice's read-write token. */
36 readonly rw: string;
37 /** alice's read-only token. */
38 readonly ro: string;
39 /** bob's read-write token. */
40 readonly bobRw: string;
41 /** alice's private repository, with a README and an app record. */
42 readonly game: Repo;
43 /** Stops the servers, closes the database, removes `dataDir`. */
44 stop(): Promise<void>;
45 }
46
47 export async function startMcpForge(): Promise<McpForge> {
48 const dataDir = await mkdtemp(join(tmpdir(), "forge-mcp-"));
49 const app = createApp({ dataDir, port: 0 });
50 setSsh(app.db, true, "test");
51 const servers = await serve(app);
52 const a = await createUser(app.db, { origin: "seed", trusted: true,
53 username: "alice",
54 email: "[email protected]",
55 password: "a-good-passphrase",
56 adminIfFirst: true,
57 });
58 if (!a.ok) throw new Error(a.error);
59 const alice = a.value;
60 const b = await createUser(app.db, { origin: "seed", trusted: true,
61 username: "bob",
62 email: "[email protected]",
63 password: "a-good-passphrase",
64 });
65 if (!b.ok) throw new Error(b.error);
66 const bob = b.value;
67 promote(app.db, bob);
68 const rw = createToken(app.db, alice.id, "rw", "rw").token;
69 const ro = createToken(app.db, alice.id, "ro", "ro").token;
70 const bobRw = createToken(app.db, bob.id, "rw", "rw").token;
71 const made = await createRepo(app, alice, {
72 name: "game",
73 visibility: "private",
74 });
75 if (!made.ok) throw new Error(String(made.error));
76 const game = made.value;
77 askForReviews(app.db, game.id);
78 await commitToBranch(app, alice, game, {
79 message: "seed",
80 files: [{ path: "README.md", content: "# game\n" }],
81 });
82 const record = insertApp(app.db, {
83 repoId: game.id,
84 slug: "game",
85 access: "private",
86 });
87 if (!record.ok) throw new Error(record.error);
88 return {
89 dataDir, app, servers, base: servers.url, alice, bob, rw, ro, bobRw, game,
90 async stop() {
91 servers.stop();
92 app.close();
93 await rm(dataDir, { recursive: true, force: true });
94 },
95 };
96 }
97
98 /** The JSON-RPC caller for the forge at `base()`, read at each call. */
99 export function mcpClient(base: () => string) {
100 let nextId = 1;
101 const call = async (
102 token: string | null,
103 method: string,
104 params?: unknown,
105 extra: Record<string, string> = {},
106 ) => {
107 const res = await fetch(`${base()}/mcp`, {
108 method: "POST",
109 headers: {
110 "content-type": "application/json",
111 accept: "application/json, text/event-stream",
112 ...(token === null ? {} : { authorization: `Bearer ${token}` }),
113 ...extra,
114 },
115 body: JSON.stringify({ jsonrpc: "2.0", id: nextId++, method, params }),
116 });
117 return {
118 res,
119 body: res.status === 202 ? null : ((await res.json()) as any),
120 };
121 };
122 /** A tool's answer: its JSON value, or its error text. */
123 const tool = async (token: string, name: string, args: unknown = {}) => {
124 const { body } = await call(token, "tools/call", { name, arguments: args });
125 const text: string = body.result.content[0].text;
126 return body.result.isError === true
127 ? { error: text }
128 : { value: JSON.parse(text) };
129 };
130 const listCall = async (token: string) => ({
131 body: await listVia(async (p) => (await call(token, "tools/list", p)).body),
132 });
133 return { call, tool, listCall };
134 }
test/support/migrate-forge.ts added +320
@@ -0,0 +1,320 @@
1 /**
2 * The forge the `migrate-*.test.ts` files bring repositories into, split
3 * from migrate.test.ts (#15351). One forge per test file:
4 *
5 * - alice (the first user, an admin), bob and octo, with sessions and
6 * tokens and no passwords (argon2 is the slow part of an account);
7 * - alice's public `fixture`: three branches, a lightweight and an
8 * annotated tag, and `trunk` as its default, at `fixtureUrl`;
9 * - alice's private `hidden`, which no anonymous clone reaches;
10 * - a fake Forgejo origin (`forgejo`, at `originBase`) that passes git on
11 * to this forge, listing octo's private `secret-widgets`, a public and a
12 * private fork, and one repository whose clone address is on another
13 * host; alice is connected to it as `originId`.
14 * - the agents `options.agents` names, on alice's crew.
15 */
16 import { expect } from "bun:test";
17 import { mkdtemp, rm } from "node:fs/promises";
18 import { tmpdir } from "node:os";
19 import { join } from "node:path";
20 import { createApp, type App } from "../../src/app.ts";
21 import { migrateRepo } from "../../src/actions/migrate.ts";
22 import { createAgent } from "../../src/actions/crew.ts";
23 import { commitToBranch, createRepo, updateRepoSettings } from "../../src/actions/repos.ts";
24 import { listOrigins } from "../../src/core/origins.ts";
25 import { type Repo } from "../../src/core/repos.ts";
26 import { createUser, type User } from "../../src/core/users.ts";
27 import { repoDir } from "../../src/git/repos.ts";
28 import { serve, type Servers } from "../../src/http/server.ts";
29 import { createToken } from "../../src/core/tokens.ts";
30 import { createSession } from "../../src/core/sessions.ts";
31 import { settled } from "../../src/origins/jobs.ts";
32 import { forgetProviders } from "../../src/origins/providers/index.ts";
33 import { newFakeState, serveFakeForge, type FakeForge } from "../fake-origin.ts";
34 import { gitClientEnv } from "../helpers/git-client.ts";
35 import { promote } from "../helpers/members.ts";
36
37 export async function git(args: string[], cwd: string) {
38 const proc = Bun.spawn(["git", ...args], {
39 cwd,
40 env: gitClientEnv(),
41 stdout: "pipe",
42 stderr: "pipe",
43 });
44 const [out, err, code] = await Promise.all([
45 new Response(proc.stdout).text(),
46 new Response(proc.stderr).text(),
47 proc.exited,
48 ]);
49 return { code, out: out.trim(), err: err.trim() };
50 }
51
52 /** Every commit reachable from any ref, as a sorted list. */
53 export async function allCommits(dir: string): Promise<string[]> {
54 return (await git(["log", "--all", "--format=%H"], dir)).out
55 .split("\n")
56 .sort();
57 }
58
59 /** Every branch and tag with the object it names. */
60 export async function allRefs(dir: string): Promise<string> {
61 return (
62 await git(
63 [
64 "for-each-ref",
65 "--format=%(refname) %(objectname)",
66 "refs/heads",
67 "refs/tags",
68 ],
69 dir,
70 )
71 ).out;
72 }
73
74 /** The forge, its fixture and fake origin, and the calls the tests make on it. */
75 export type MigrateForge = Awaited<ReturnType<typeof startMigrateForge>>;
76
77 /** What a test file's forge starts with beyond the fixture. */
78 export interface MigrateForgeOptions {
79 /** Agents alice has on her crew from the start, for a page that lists them. */
80 readonly agents?: readonly string[];
81 }
82
83 export async function startMigrateForge(options: MigrateForgeOptions = {}) {
84 let dataDir: string;
85 let work: string;
86 let app: App;
87 let servers: Servers;
88 let forgejo: FakeForge;
89 let base: string;
90 /** The fake origin, which passes git on to this forge: a clone address names it (#14756). */
91 let originBase: string;
92 let alice: User;
93 let bob: User;
94 let aliceCookie = "";
95 let bobCookie = "";
96 let bobToken = "";
97 let fixtureUrl = "";
98 let originId = "";
99 let octo: User;
100 // octo's credential at the "upstream": a token, since a password would
101 // cost an argon2 verify on every git request.
102 let upstreamSecret = "";
103
104 const person = async (
105 username: string,
106 adminIfFirst = false,
107 ): Promise<User> => {
108 const made = await createUser(app.db, {
109 origin: "seed",
110 trusted: true,
111 username,
112 email: `${username}@forge.test`,
113 adminIfFirst,
114 });
115 if (!made.ok) throw new Error(String(made.error));
116 promote(app.db, made.value);
117 return made.value;
118 };
119
120 const cookieOf = (user: User): string =>
121 `forge_session=${createSession(app.db, user.id).token}`;
122
123 const browser = (
124 cookie: string,
125 path: string,
126 form?: Record<string, string>,
127 origin?: string,
128 ): Promise<Response> =>
129 fetch(`${base}${path}`, {
130 method: form === undefined ? "GET" : "POST",
131 headers: {
132 cookie,
133 ...(form === undefined
134 ? {}
135 : { origin: origin ?? new URL(base).origin }),
136 },
137 redirect: "manual",
138 ...(form === undefined ? {} : { body: new URLSearchParams(form) }),
139 });
140
141 /** The same call with a bearer token: no cookie, no origin header. */
142 const apiToken = (token: string, payload: unknown): Promise<Response> =>
143 fetch(`${base}/api/v1/migrate`, {
144 method: "POST",
145 headers: {
146 "content-type": "application/json",
147 authorization: `Bearer ${token}`,
148 },
149 body: JSON.stringify(payload),
150 });
151
152 const api = (cookie: string, payload: unknown): Promise<Response> =>
153 fetch(`${base}/api/v1/migrate`, {
154 method: "POST",
155 headers: {
156 "content-type": "application/json",
157 cookie,
158 origin: new URL(base).origin,
159 },
160 body: JSON.stringify(payload),
161 });
162
163 /** Start a migration and wait for it; the job is returned as it ended. */
164 const migrate = async (
165 user: User,
166 input: Parameters<typeof migrateRepo>[2],
167 ) => {
168 const started = await migrateRepo(app, user, input);
169 if (!started.ok) throw new Error(started.error);
170 return settled(started.value.job.id);
171 };
172
173 dataDir = await mkdtemp(join(tmpdir(), "forge-migrate-"));
174 work = await mkdtemp(join(tmpdir(), "forge-migrate-work-"));
175 // The fixture's source is the forge itself, on loopback: a private host,
176 // which a personal forge may say is fine. Its hook socket is what a
177 // real push needs; no argon2 per request (sessions and tokens, not
178 // passwords).
179 app = createApp({ dataDir, port: 0, migrateFromPrivateHosts: true });
180 servers = await serve(app);
181 base = `http://127.0.0.1:${servers.port}`;
182 // No passwords: argon2 is the slow part of an account, and every
183 // request here rides a session or a token.
184 alice = await person("alice", true);
185 bob = await person("bob");
186 octo = await person("octo");
187 upstreamSecret = createToken(app.db, octo.id, "upstream", "rw").token;
188 aliceCookie = cookieOf(alice);
189 bobCookie = cookieOf(bob);
190 bobToken = createToken(app.db, bob.id, "cli", "rw").token;
191
192 // The fixture: alice's public repository with three branches, two tags
193 // (one annotated), and `trunk` as its default — not the forge's `main`.
194 const made = await createRepo(app, alice, {
195 name: "fixture",
196 visibility: "public",
197 });
198 if (!made.ok) throw new Error(made.error);
199 const fixture = made.value;
200 const commit = async (
201 user: User,
202 repo: Repo,
203 branch: string,
204 path: string,
205 message: string,
206 ) => {
207 const done = await commitToBranch(app, user, repo, {
208 branch,
209 message,
210 files: [{ path, content: `${message}\n` }],
211 });
212 if (!done.ok) throw new Error(String(done.error));
213 };
214 await commit(alice, fixture, "main", "README.md", "first");
215 await commit(alice, fixture, "main", "a.txt", "second");
216 await commit(alice, fixture, "trunk", "trunk.txt", "on trunk");
217 await commit(alice, fixture, "feature", "feature.txt", "a feature");
218 await commit(alice, fixture, "feature", "feature2.txt", "more feature");
219 const settings = await updateRepoSettings(app, alice, fixture, {
220 defaultBranch: "trunk",
221 });
222 if (!settings.ok) throw new Error(settings.error);
223 const dir = repoDir(app.reposRoot, "alice", "fixture");
224 expect((await git(["tag", "v1", "main~1"], dir)).code).toBe(0);
225 expect(
226 (await git(["tag", "-a", "v2", "-m", "the second", "feature"], dir)).code,
227 ).toBe(0);
228 fixtureUrl = `${base}/alice/fixture.git`;
229
230 // A repository alice keeps private: no anonymous clone reaches it.
231 const hidden = await createRepo(app, alice, {
232 name: "hidden",
233 visibility: "private",
234 });
235 if (!hidden.ok) throw new Error(hidden.error);
236 await commit(alice, hidden.value, "main", "README.md", "secret");
237
238 // A private repository behind a fake origin whose clone URL points at
239 // it: only the origin's credential (octo's) opens it.
240 const widgets = await createRepo(app, octo, {
241 name: "secret-widgets",
242 visibility: "private",
243 });
244 if (!widgets.ok) throw new Error(widgets.error);
245 await commit(octo, widgets.value, "main", "README.md", "first");
246 const state = newFakeState("forgejo", "octo", upstreamSecret);
247 forgejo = serveFakeForge(state);
248 state.gitAt = base;
249 originBase = forgejo.url;
250 state.repos.push({
251 id: 77,
252 fullName: "octo/secret-widgets",
253 description: "gears, privately",
254 cloneUrl: `${originBase}/octo/secret-widgets.git`,
255 htmlUrl: `${base}/octo/secret-widgets`,
256 defaultBranch: "main",
257 private: true,
258 });
259 // A public fork on the origin, whose host says what it forks (#3293).
260 state.repos.push({
261 id: 78,
262 fullName: "octo/arm",
263 description: "an arm, forked",
264 cloneUrl: `${originBase}/octo/secret-widgets.git`,
265 htmlUrl: "https://code.example/octo/arm",
266 defaultBranch: "main",
267 fork: true,
268 parent: "TheRobotStudio/arm",
269 });
270 // A private fork: its name is not ours to publish, whatever it becomes.
271 state.repos.push({
272 id: 79,
273 fullName: "octo/hush",
274 description: "a quiet fork",
275 cloneUrl: `${originBase}/octo/secret-widgets.git`,
276 htmlUrl: "https://code.example/octo/hush",
277 defaultBranch: "main",
278 private: true,
279 fork: true,
280 parent: "TheRobotStudio/hush",
281 });
282 // An origin's reply naming a clone address on another host: the
283 // metadata service, as an attacker's own Forgejo would (#14756).
284 state.repos.push({
285 id: 80,
286 fullName: "octo/elsewhere",
287 description: "",
288 cloneUrl: "http://169.254.169.254/internal/secret.git",
289 htmlUrl: "https://code.example/octo/elsewhere",
290 defaultBranch: "main",
291 private: false,
292 });
293 forgetProviders(dataDir);
294 const connected = await browser(aliceCookie, "/settings/origins/token", {
295 host: forgejo.url,
296 token: upstreamSecret,
297 });
298 expect(connected.status).toBe(303);
299 originId = listOrigins(app.db, alice.id)[0]!.id;
300
301 for (const username of options.agents ?? []) {
302 const agent = await createAgent(app, alice, { username, model: "", brief: "Moves things in." });
303 if (!agent.ok) throw new Error(String(agent.error));
304 }
305
306 return {
307 dataDir, work, app, servers, forgejo, base, originBase, alice, bob,
308 aliceCookie, bobCookie, bobToken, fixtureUrl, originId, octo, upstreamSecret,
309 person, cookieOf, browser, apiToken, api, migrate,
310 /** Stops the origin and the servers, closes the database, removes the directories. */
311 async stop() {
312 forgejo.stop();
313 servers.stop();
314 app.close();
315 forgetProviders(dataDir);
316 for (const dir of [dataDir, work])
317 await rm(dir, { recursive: true, force: true });
318 },
319 };
320 }
test/support/studio-forge.ts added +123
@@ -0,0 +1,123 @@
1 /**
2 * The forge the `studio-door-*.test.ts` files draw the studio on, one per
3 * file (#15351): alice (its first account, and so its admin), bob and carol
4 * (readers, and strangers to alice's apps), on host `forge.example` (the
5 * terminal's block reads its command off it), and one apps runtime —
6 * registered, never started — that holds the environments a test puts
7 * where a deploy would have, so nothing waits on an install, a health check
8 * or a clock.
9 */
10
11 import { mkdtemp, rm } from "node:fs/promises";
12 import { tmpdir } from "node:os";
13 import { join } from "node:path";
14 import { createApp, type App } from "../../src/app.ts";
15 import { setSsh } from "../../src/settings/ssh.ts";
16 import type { EnvName } from "../../src/apps/data.ts";
17 import { AppsRuntime } from "../../src/apps/runtime.ts";
18 import type { AppRecord } from "../../src/core/apps.ts";
19 import { createUser, type User } from "../../src/core/users.ts";
20 import { serve, type Servers } from "../../src/http/server.ts";
21 import { promote } from "../helpers/members.ts";
22
23 /** Every person's passphrase on a studio forge. */
24 export const PASSWORD = "a-good-passphrase";
25
26 /**
27 * An environment as the runtime holds it, without running a deploy: the
28 * pages read `runtime.status(record)`, and a real one would mean a real
29 * install and a real health check for a rendering test.
30 */
31 export interface Slot {
32 readonly app: AppRecord;
33 readonly env: EnvName;
34 readonly chain: Promise<void>;
35 readonly restarts: number[];
36 readonly deploying?: unknown;
37 readonly live?: unknown;
38 readonly lastError?: string;
39 readonly lastRunId?: string;
40 readonly lastErrorCommitOid?: string;
41 }
42
43 export type StudioForge = Awaited<ReturnType<typeof startStudioForge>>;
44
45 export async function startStudioForge() {
46 const dataDir = await mkdtemp(join(tmpdir(), "forge-studio-door-"));
47 const app: App = createApp({ dataDir, port: 0, host: "forge.example" });
48 setSsh(app.db, true, "test");
49 const servers: Servers = await serve(app);
50 const base = servers.url;
51 const runtime = new AppsRuntime(app, {
52 domain: "apps.test",
53 scheme: "http",
54 publicPort: servers.port,
55 forgeUrl: servers.url,
56 concurrency: 1,
57 });
58
59 /** A person on the forge, promoted past the newcomer's limits. */
60 async function person(username: string, adminIfFirst = false): Promise<User> {
61 const made = await createUser(app.db, { origin: "seed", trusted: true,
62 username,
63 email: `${username}@forge.local`,
64 password: PASSWORD,
65 adminIfFirst,
66 });
67 if (!made.ok) throw new Error(made.error);
68 promote(app.db, made.value);
69 return made.value;
70 }
71
72 /** The session cookie `username` signs in with. */
73 const signIn = async (username: string, password = PASSWORD): Promise<string> =>
74 (
75 (
76 await fetch(`${base}/signin`, {
77 method: "POST",
78 body: new URLSearchParams({ username, password }),
79 redirect: "manual",
80 })
81 ).headers.get("set-cookie") ?? ""
82 ).split(";")[0]!;
83
84 const slots = (): Map<string, Slot> =>
85 (runtime as unknown as { envs: Map<string, Slot> }).envs;
86
87 const putEnv = (
88 record: AppRecord,
89 env: EnvName,
90 slot: Omit<Slot, "app" | "env" | "chain" | "restarts">,
91 ): void => {
92 slots().set(`${record.id}/${env}`, {
93 app: record,
94 env,
95 chain: Promise.resolve(),
96 restarts: [],
97 ...slot,
98 });
99 };
100
101 /** Take every environment of `record` away, as if none had ever deployed. */
102 const clearEnvs = (record: AppRecord): void => {
103 for (const key of [...slots().keys()])
104 if (key.startsWith(`${record.id}/`)) slots().delete(key);
105 };
106
107 await person("alice", true);
108 await person("bob");
109 await person("carol");
110
111 return {
112 dataDir, app, servers, base, runtime,
113 person, signIn, slots, putEnv, clearEnvs,
114 async stop() {
115 // The slots stand in for deploys; there is no process behind them to stop.
116 slots().clear();
117 await runtime.stop();
118 servers.stop();
119 app.close();
120 await rm(dataDir, { recursive: true, force: true });
121 },
122 };
123 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs