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

A new forge's owner can share an app with a second person, and the first step… #16383

Merged opened this in answer to

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

Merged

scout/forge:scout/16375-a-new-forge-s-owner-can-share-an-app-wit → main 0 commits fork 5 threads · 5 unresolved

  • Merged. scout/16375-a-new-forge-s-owner-can-share-an-app-wit was merged into main as aec99ce.

Review

Sign in to review this change.
13 files changed +116 −22
docs/features/new-app.md +4
@@ -35,3 +35,7 @@ pick **New app**.
3535 `name` and go through the same `newAppFromSentence`: the name is derived, a
3636 repeat gets `-2`, and nothing to name from is `no_name` (422 on the API). When
3737 both are given, `name` wins and `sentence` is ignored.
38
39 ## A private app says so
40
41 An app is private unless made public. Every door that makes one (the New app page, the terminal's new-app screen, the `new_app` tool) says in its answer that a signed-out visitor gets a 404 and that its visibility is changed in the app's settings. One function, `privateNotice` in `src/actions/apps.ts`, holds the words; a public app gets none. The tool carries it as `says`, beside `visibility`.
src/actions/apps.ts +10
@@ -851,3 +851,13 @@ async function commitFor(
851851 }
852852
853853 export { previewEnv };
854
855 /**
856 * What a new private app says of itself, the same in every door that makes one: who can open it
857 * and where to change that. Nothing for a public app.
858 */
859 export function privateNotice(repo: { readonly visibility: string }): string | undefined {
860 return repo.visibility === "private"
861 ? "Private: a signed-out visitor gets a 404. To make it public, change its visibility in the app's settings."
862 : undefined;
863 }
src/apps/process.ts +12 −4
@@ -19,6 +19,7 @@ import { backgroundArgv } from "./background.ts";
1919 import { buildCacheEnv, cacheKey, linkExact, noteSize, prepareBuildCache } from "./build_cache.ts";
2020 import { isReservedAppEnvName } from "../core/app_env.ts";
2121 import { isFeatureVarName } from "./feature_env.ts";
22 import { nameFailingTests } from "./push_gate.ts";
2223 import { formsOf, redactValues } from "../kernel/log.ts";
2324 import { err, ok, type Result } from "../kernel/result.ts";
2425 import { endedLine, liveTree } from "../runs/ended.ts";
@@ -683,27 +684,34 @@ export async function startProcess(
683684 input.signal.addEventListener("abort", () => testAbort.abort(), {
684685 once: true,
685686 });
687 // Once per start: what this app holds, to keep out of what it prints.
688 const secretForms = appSecretForms(input);
689 // The test's output kept to name its failures: redacted and capped as it is taken.
690 const testLines: string[] = [];
686691 const tested: Promise<Result<void, string>> =
687692 manifest.test === null || input.warm === true
688693 ? Promise.resolve(ok())
689694 : runStep("test", manifest.test, {
690695 cwd: input.dir,
outdated

Raw lines are stored unredacted and with no per-line length cap. Redact before storing, or redact the names in nameFailingTests.

691696 env: stepEnv,
692 log,
697 log: (line: string) => {
698 if (testLines.length < 5000) testLines.push(redactValues(line, secretForms).slice(0, 300));
699 log(line);
700 },
693701 signal: testAbort.signal,
694702 cell: stepCell(input, use, cacheDir),
outdated

This wiring has no test: nothing fails if the capture or the call is deleted. Add a gate test with a real failing bun test.

695703 build: stepLimits(input),
696704 }).then((result) => {
697705 noted();
698 return result;
706 return result.ok
707 ? result
708 : err(nameFailingTests(result.error, testLines));
699709 });
700710
701711 // The port is chosen, then released, then bound by the app: another
702712 // process can take it in between. An app that dies on an address-in-use
703713 // error is started again on a fresh port (`startOnFreshPort`).
704714 const pick = input.pickPort ?? freePort;
705 // Once per start: what this app holds, to keep out of what it prints.
706 const secretForms = appSecretForms(input);
707715 const launch = async (port: number): Promise<Launch> => {
708716 log(`$ ${manifest.run} (PORT=${port})`);
709717 const spawnedAt = Date.now();
src/apps/push_gate.ts +13 −1
@@ -6,6 +6,7 @@
66 */
77
88 import { during } from "../perf/jobs.ts";
9 import { parseBunTestFailure } from "../checks/bun-test.ts";
910 import { err, type Result } from "../kernel/result.ts";
1011
1112 /** Whether this deploy waits for its tests before it switches in. */
@@ -13,9 +14,20 @@ export function gatesPush(env: string, reason: string, hasLive: boolean, declare
1314 return env === "production" && reason === "push" && hasLive && declaresTest;
1415 }
1516
17 /**
18 * A red test step's error, with the failing tests' names from its output (up to three) when it is
19 * `bun test`'s.
20 */
21 export function nameFailingTests(error: string, lines: readonly string[]): string {
22 const names = parseBunTestFailure(lines)?.names.slice(0, 3) ?? [];
23 if (names.length === 0) return error;
24 const head = error.split("\n")[0] ?? error;
25 return `${head} — failing: ${names.map((n) => `"${n.slice(0, 80)}"`).join(", ")}`;
26 }
27
1628 /** The run's summary and the owner's line when the gate held a push back. */
1729 export function gateSummary(why: string, keptOid: string): string {
18 const first = (why.split("\n")[0] ?? "").trim().slice(0, 160);
30 const first = (why.split("\n")[0] ?? "").trim().slice(0, 240);
1931 return `held back: its tests failed (${first}); ${keptOid.slice(0, 7)} keeps serving`;
2032 }
2133
src/http/mcp/tools/new_app.ts +5 −2
@@ -2,7 +2,7 @@ import { appsRuntime } from "../../../apps/runtime.ts";
22 import { listActiveRuns } from "../../../core/runs.ts";
33 import { getUserByName } from "../../../core/users.ts";
44 import { repositoryLimitMessage } from "../../../actions/repos.ts";
5 import { NEW_APP_ERRORS, NO_NAME_ERROR, newApp, newAppFromSentence, type NewAppInput } from "../../../actions/apps.ts";
5 import { NEW_APP_ERRORS, NO_NAME_ERROR, newApp, newAppFromSentence, privateNotice, type NewAppInput } from "../../../actions/apps.ts";
66 import { appLimitWords } from "../../../actions/app_limit.ts";
77 import { storageLimitMessage } from "../../../core/storage.ts";
88 import { VERIFY_FIRST } from "../../../actions/verify_words.ts";
@@ -20,7 +20,7 @@ async function fromSentence(app: App, user: User, sentence: string, input: Omit<
2020
2121 export const tool: Tool = {
2222 name: "new_app",
23 doc: "`{ name?, sentence?, description?, owner?, visibility?, agent?, pick?, template? }`: make an app from a sentence: with `sentence` and no `name` the name is derived from it (`-2`, `-3` when taken), as the web and terminal do; `name` and `sentence` together keep the name; the first issue is `description`, else `sentence`; answers `{ repo, url, issue, agent, run }` (`run` is the first run's state, or `none`) and draws the `ui://forge/app` card: name, production URL, first issue, agent; refused as `POST /api/v1/apps` is (unverified, app_limit, no_such_agent, name_taken)",
23 doc: "`{ name?, sentence?, description?, owner?, visibility?, agent?, pick?, template? }`: make an app from a sentence: with `sentence` and no `name` the name is derived from it (`-2`, `-3` when taken), as the web and terminal do; `name` and `sentence` together keep the name; the first issue is `description`, else `sentence`; answers `{ repo, url, issue, agent, run, visibility, says? }` (`run` is the first run's state, or `none`) and draws the `ui://forge/app` card: name, production URL, first issue, agent; refused as `POST /api/v1/apps` is (unverified, app_limit, no_such_agent, name_taken)",
2424 description:
2525 "Make an app from a sentence: a repo, production, and with `description` a first issue.",
2626 inputSchema: {
@@ -79,12 +79,15 @@ export const tool: Tool = {
7979 }
8080 const { repo, app: record, issue } = made.value;
8181 const run = listActiveRuns(ctx.app.db, [repo.id])[0];
82 const notice = privateNotice(repo);
8283 return good({
8384 repo: `${repo.ownerName}/${repo.name}`,
8485 url: appsRuntime(ctx.app)?.urlFor(record, "production") ?? null,
8586 issue: issue === undefined ? null : issue.number,
8687 agent: issue?.assigneeName ?? null,
8788 run: run?.state ?? "none",
89 visibility: repo.visibility,
90 ...(notice === undefined ? {} : { says: notice }),
outdated

The private notice exists only in the MCP door. The page and terminal creation flows need it too, from one shared function. Add a test for the public case (no says).

8891 // A run that waits says on what, and links the control that changes it.
8992 ...(run === undefined ? {} : runHold(ctx.app.db, ctx.app.config.dataDir, run, user, ctx.url.origin)),
9093 });
src/http/mcp/tools/signup.ts +2 −2
@@ -8,9 +8,9 @@ import { SIGNUP_WORDS } from "../../../core/arg_words.ts";
88 export const tool: Tool = {
99 name: "signup",
1010 listedTo: "admin",
11 doc: "`{ mode?, billingLinks?, dryRun? }`: who may sign up: `open` (default), `invite` (only a person with an open invite link) or `closed` (no new accounts); without `mode` it reads the setting, with `mode` it is planned first; `billingLinks` `{small?, medium?, large?}` (https URLs) sets the home page's buy links; applying needs an admin token",
11 doc: "`{ mode?, billingLinks?, dryRun? }`: who may sign up: `open`, `invite` (only a person with an open invite link; a deployed forge starts here) or `closed` (no new accounts); without `mode` it reads the setting, with `mode` it is planned first; `billingLinks` `{small?, medium?, large?}` (https URLs) sets the home page's buy links; applying needs an admin token",
1212 description:
13 "Sign-ups: open (default); invite lets in only a person with an open invite link; closed refuses every new account",
13 "Sign-ups: open; invite (a deployed forge starts here) needs an invite link; closed refuses all",
1414 inputSchema: {
1515 type: "object",
1616 properties: {
src/tui/screens/newapp.ts +8 −4
@@ -8,7 +8,7 @@
88 */
99
1010 import { appLimitWords } from "../../actions/app_limit.ts";
11 import { NEW_APP_ERRORS, NO_NAME_ERROR, newAppFromSentence } from "../../actions/apps.ts";
11 import { NEW_APP_ERRORS, NO_NAME_ERROR, newAppFromSentence, privateNotice } from "../../actions/apps.ts";
1212 import { repositoryLimitMessage } from "../../actions/repos.ts";
1313 import { appsRuntime } from "../../apps/runtime.ts";
1414 import { templateChoices } from "../../apps/template_folders.ts";
@@ -74,10 +74,14 @@ export function newAppScreen(
7474 return;
7575 }
7676 const url = appsRuntime(f.app)?.urlFor(made.app, "production");
77 const notice = privateNotice(made.repo);
78 // Private or not holds whether or not anything serves apps, as on the page.
7779 ctx.toast(
78 url === undefined
79 ? `${made.repo.name} is an app, but nothing is serving apps on this forge.`
80 : `${made.repo.name} is starting at ${url}.${made.idle === undefined ? "" : ` ${made.idle}`}`,
80 `${
81 url === undefined
82 ? `${made.repo.name} is an app, but nothing is serving apps on this forge.`
83 : `${made.repo.name} is starting at ${url}.${made.idle === undefined ? "" : ` ${made.idle}`}`
84 }${notice === undefined ? "" : ` ${notice}`}`,
8185 "success",
8286 );
8387 ctx.push(repoScreen(f, ctx, local(f, made.repo)));
src/web/pages/apps.ts +3 −1
@@ -36,6 +36,7 @@ import {
3636 redeployEnv,
3737 stopEnv,
3838 terminalFor,
39 privateNotice,
3940 } from "../../actions/apps.ts";
4041 import { listAllAgents } from "../../actions/crew.ts";
4142 import { planningAvailable } from "../../crew/plan.ts";
@@ -603,7 +604,8 @@ export async function newAppSubmit(ctx: Ctx): Promise<Response> {
603604 : ` #${issue.number} is assigned to ${issue.assigneeName}.`;
604605 // The repository's home is the app page (repoHome), once the record
605606 // exists; the code is its Files step.
606 return flashTo(ctx, repoBase(repo), { message: `${first}${second}${idleWords}` });
607 const notice = privateNotice(repo);
608 return flashTo(ctx, repoBase(repo), { message: `${first}${second}${idleWords}${notice === undefined ? "" : ` ${notice}`}` });
607609 }
608610
609611 // ---- the repo home's strip ----
test/apps-template-doors.test.ts +6
@@ -8,6 +8,7 @@ import { afterAll, beforeAll, expect, setDefaultTimeout, test } from "bun:test";
88 import { mkdtemp, rm } from "node:fs/promises";
99 import { tmpdir } from "node:os";
1010 import { join } from "node:path";
11 import { privateNotice } from "../src/actions/apps.ts";
1112 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
1213 import { setRole } from "../src/actions/roles.ts";
1314 import { TEMPLATE_ERRORS } from "../src/apps/template_tip.ts";
@@ -154,7 +155,12 @@ test("the MCP tool copies the template and maps a refusal to its words", async (
154155 };
155156 const made = await call({ name: "from-mcp", description: "x", template: "giver/kit" });
156157 expect(made.error).toBe(false);
158 expect(made.text).toContain("Private: a signed-out visitor gets a 404");
157159 expect(readme("taker", "from-mcp")).toBe("# kit\n");
160 const open = await call({ name: "from-mcp-public", description: "x", visibility: "public" });
161 expect(open.error).toBe(false);
162 expect(open.text).not.toContain("Private:");
163 expect(privateNotice({ visibility: "public" })).toBeUndefined();
158164 const refused = await call({ name: "from-mcp-2", description: "x", template: "giver/secret" });
159165 expect(refused.error).toBe(true);
160166 expect(refused.text).toContain(TEMPLATE_ERRORS.no_such_template);
test/mcp-forge-protocol.test.ts +2 −2
@@ -307,8 +307,8 @@ describe("the forge over MCP: protocol", () => {
307307 const signup: string = byName.get("signup").description;
308308 expect(signup).not.toContain("Nothing reads it yet");
309309 expect(signup).not.toContain("not redeemed");
310 expect(signup).toContain("invite lets in only a person with an open invite link");
311 expect(signup).toContain("closed refuses every new account");
310 expect(signup).toContain("invite (a deployed forge starts here) needs an invite link");
311 expect(signup).toContain("closed refuses all");
312312 expect(byName.get("tell").inputSchema.required).toBeUndefined();
313313
314314 expect((await call(rw, "nothing/here")).body.error.code).toBe(-32601);
test/push-gate.test.ts +25 −4
@@ -9,7 +9,7 @@ import { tmpdir } from "node:os";
99 import { join } from "node:path";
1010 import { createApp, type App } from "../src/app.ts";
1111 import { AppsRuntime } from "../src/apps/runtime.ts";
12 import { gateBudgetMs, gatesPush, gateSummary, withinBudget } from "../src/apps/push_gate.ts";
12 import { gateBudgetMs, gatesPush, gateSummary, nameFailingTests, withinBudget } from "../src/apps/push_gate.ts";
1313 import { newApp } from "../src/actions/apps.ts";
1414 import { getAppByRepo } from "../src/core/apps.ts";
1515 import { commitToBranch } from "../src/actions/repos.ts";
@@ -114,12 +114,12 @@ describe("a direct push is gated on its tests", () => {
114114 "the deploy settling",
115115 );
116116
117 const push = async (test: string): Promise<string> => {
117 const push = async (test: string, extra: { path: string; content: string }[] = []): Promise<string> => {
118118 const committed = await commitToBranch(app, alice, repo, {
119119 branch: repo.defaultBranch,
120120 base: repo.defaultBranch,
121121 message: `test: ${test}`,
122 files: [{ path: "forge.json", content: `${JSON.stringify({ app: { run: "bun run src/server.ts", test }, note: test })}\n` }],
122 files: [...extra, { path: "forge.json", content: `${JSON.stringify({ app: { run: "bun run src/server.ts", test }, note: test })}\n` }],
123123 });
124124 if (!committed.ok) throw new Error(JSON.stringify(committed.error));
125125 return committed.value.commitOid;
@@ -170,9 +170,20 @@ describe("a direct push is gated on its tests", () => {
170170 const event = await gated;
171171 expect(event.payload["keptOid"]).toBe(green);
172172 expect(runtime.liveFor(record, "production")?.commitOid).toBe(green);
173
174173 });
175174
175 test("a real red bun test names its failing test in the held-back summary and event", async () => {
176 const record = getAppByRepo(app.db, repo.id)!;
177 const green = runtime.liveFor(record, "production")!.commitOid;
178 const gated = when((e) => (e?.kind === "app.gated" && e.repoId === repo.id && String(e.payload["why"] ?? "").includes("the named failure") ? e : undefined), "the named gated event");
179 const red = await push("bun test t/a.test.ts", [{ path: "t/a.test.ts", content: 'import { test, expect } from "bun:test";\ntest("the named failure", () => { expect(1).toBe(2); });\n' }]);
180 const failed = await settledAt(red);
181 expect(failed.state).toBe("failed");
182 expect(failed.summary).toContain("the named failure");
183 await gated;
184 expect(runtime.liveFor(record, "production")?.commitOid).toBe(green);
185 }, 60_000);
186
176187 test("a suite that outlives the budget is red too, and does not hold the deploy", async () => {
177188 const record = getAppByRepo(app.db, repo.id)!;
178189 const green = runtime.liveFor(record, "production")?.commitOid;
@@ -197,3 +208,13 @@ describe("a direct push is gated on its tests", () => {
197208 expect(runtime.liveFor(record, "production")?.commitOid).toBe(fixed);
198209 }, 60_000);
199210 });
211
212 describe("a held-back push names the failing test", () => {
213 test("bun test's failing names ride on the error and reach the summary", () => {
214 const lines = ["(fail) the contract is what the routes say [2ms]", " 3 pass", " 1 fail"];
215 const why = nameFailingTests("test exited with code 1 — 1 fail", lines);
216 expect(why).toContain('failing: "the contract is what the routes say"');
217 expect(gateSummary(why, "abcdef0123")).toContain("the contract is what the routes say");
218 expect(nameFailingTests("test exited with code 1", ["nothing useful"])).toBe("test exited with code 1");
219 });
220 });
test/tui-newapp.test.ts +17 −2
@@ -70,16 +70,24 @@ async function until(done: () => boolean): Promise<void> {
7070
7171 async function withScreen(
7272 user: User,
73 body: (h: { text: () => string; feed: (s: string) => Promise<void> }) => Promise<void>,
73 body: (h: { text: () => string; toasts: string[]; feed: (s: string) => Promise<void> }) => Promise<void>,
7474 ) {
7575 const terminal = headlessTerminal(120, 30);
7676 const { app: tui, session } = createForgeApp(app, identity(user), { terminal, exitHooks: false });
7777 tui.start();
78 // Every toast the screen raises, kept: one outlives the screen text.
79 const toasts: string[] = [];
80 const toast = tui.ctx.toast.bind(tui.ctx);
81 tui.ctx.toast = (message, ...rest) => {
82 toasts.push(message);
83 return toast(message, ...rest);
84 };
7885 tui.ctx.push(newAppScreen(session, tui.ctx, blank("New app")));
7986 try {
8087 await settleApp(tui);
8188 await body({
8289 text: () => tui.screen.toText(),
90 toasts,
8391 feed: async (s) => {
8492 terminal.feed(s);
8593 await settleApp(tui);
@@ -99,7 +107,7 @@ describe("the new app screen", () => {
99107 });
100108
101109 test("a sentence makes an app named from it, and lands on its repository", () =>
102 withScreen(alice, async ({ text, feed }) => {
110 withScreen(alice, async ({ text, toasts, feed }) => {
outdated

This asserts only that the app is private, which main already does, so it would not fail if the terminal's notice were removed. Assert that the toast carries "Private: a signed-out visitor gets a 404".

103111 await feed("a shared shopping list\r");
104112 await feed("\r"); // alice is in an organization: accept the prefilled owner
105113 await until(() => getRepo(app.db, "alice", "shared-shopping") !== undefined);
@@ -107,6 +115,13 @@ describe("the new app screen", () => {
107115 const repo = getRepo(app.db, "alice", "shared-shopping");
108116 expect(repo).toBeDefined();
109117 expect(text()).toContain("shared-shopping");
118 expect(repo!.visibility).toBe("private");
119 // The terminal door says so too, in the words every door shares.
120 const made = (t: string) => t.startsWith("shared-shopping is");
121 await until(() => toasts.some(made));
122 expect(toasts.find(made)).toContain(
123 "Private: a signed-out visitor gets a 404",
124 );
110125 }));
111126
112127 test("an empty sentence shows the no-name words and makes nothing", () =>
test/web-apps.test.ts +9
@@ -265,6 +265,7 @@ describe("apps, runs and the crew on the web", () => {
265265 expect(flashOf(created)).toContain(
266266 `hello is starting at http://hello.${DOMAIN}:${servers.port}`,
267267 );
268 expect(flashOf(created)).not.toContain("Private:");
268269 hello = getRepo(app.db, "alice", "hello")!;
269270 expect(hello).toBeDefined();
270271 expect(getAppByRepo(app.db, hello.id)?.slug).toBe("hello");
@@ -286,6 +287,14 @@ describe("apps, runs and the crew on the web", () => {
286287 expect(plainHome).not.toContain('href="/alice/plain?mode=studio"');
287288 });
288289
290 test("a private New app says it is private and where to change that", async () => {
291 const made = await web(alice, "/apps/new", {
292 form: { owner: "alice", name: "hush", description: "", visibility: "private" },
293 });
294 expect(made.status).toBe(303);
295 expect(flashOf(made)).toContain("Private: a signed-out visitor gets a 404");
296 });
297
289298 test("a refused New app keeps what was typed", async () => {
290299 const dup = await web(alice, "/apps/new", {
291300 form: { owner: "alice", name: "hello", visibility: "public" },

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs