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

Talk workspace W4: the forge on itself — a dev forge with seeded data, memory and sleep budget #17353

opened this

Merged 30h 39m ago, live in production

scout/forge:scout/17122-talk-workspace-w4-the-forge-on-itself-a → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/17122-talk-workspace-w4-the-forge-on-itself-a was merged into main as 2d6b4d3.

Review

Sign in to review this change.
10 files changed +154 −10
docs/features/talk-workspace.md +5
@@ -39,3 +39,8 @@ Not yet: the dev server reading the working tree, so the dev frame does not relo
3939 - **Test what I touched** (Diff tab, `T` in the terminal's `p` view): the working tree is laid over the branch's tip in a checkout of its own (the dev server's is not disturbed), and `bun test` runs there, in the cell an app of the repository runs in (`src/actions/touched_run.ts`): the tests the changed files reach (`reach` over the branch's `scripts/test-impact.json`; with no map, the tests that name a changed file, said to be a guess) plus every rule test the gate holds a change to (`RULE_TESTS`). The plan is `src/actions/touched_plan.ts`; only test file names it validated reach the command, never typed text. The output streams into the Diff tab as it prints (the pane redraws on the run's events), and in the terminal's `p` view on reload. A line names any registry a new page (terminal door, how-to), added route (its mark in `src/http/marks/`) or new migration (its pin) still needs, before the check does. Only a writer of a repository that is an app can run it; one run per person and branch, a second press answers the one going.
4040 - **Open pull** (Diff tab, `P` in the terminal): one action. What is not committed is committed first, as one commit through `commitToBranch` (a workspace's branch is never the default branch, so the protected-branch case does not arise here), then `openPull` opens the pull; a branch that already has a pull is answered with it. The full suite runs on the pull, as on any (`src/actions/work_pull.ts`).
4141
42 ## The forge on itself (#17122, W4)
outdated

Two blank lines before the heading; keep one.

43
44 Choosing `trevato/forge` and pressing **Start dev server** (`d` in the terminal) starts a dev forge from the branch: its `bun run dev` runs in a dev cell, and because a dev cell is never production (`FORGE_APP_ENV=preview`), the forge seeds its own admin and a small world to look at (`src/spawn/preview-seed.ts`), in the cell's own data. The frame tells it who is looking: the person who started the cell, a writer, as the admin of their own dev environment, signed under the key derived for that cell alone (`devIdentityHeaders` in `src/apps/dev_budget.ts`, the rule a preview follows), so the dev forge opens on its seeded admin and not on a sign-in the sandboxed frame cannot do. The page and the terminal's `p` view both say the budget.
45
46 The budget (`src/apps/dev_budget.ts`, within #16840): a dev cell holds at most 1024 MiB and one core, lowered from what the app declares and never raised above it, and it sleeps after ten minutes nobody looks at it (`DEV_IDLE_MS`).
src/apps/dev_budget.ts added +40
@@ -0,0 +1,40 @@
1 /**
2 * What a dev cell is held to (#17122, W4 of #16940, within #16840's per-cell budgets): a memory
3 * ceiling lower than a running app's, the idle sleep of `dev_cell.ts`, and, so a dev forge opens on
4 * its seeded world and not on a sign-in it cannot show, the identity its frame speaks as. Plain
5 * data in, plain data out.
6 */
7
8 import { createHmac } from "node:crypto";
9 import type { DeclaredLimits } from "./contain.ts";
10 import { DEV_IDLE_MS } from "./dev_cell.ts";
11
12 /** A dev cell's memory, MiB: a small forge idles near 600 MB, and a branch is no production. */
13 const DEV_MEMORY_MIB = 1024;
14 const DEV_CPUS = 1;
15
16 /**
17 * The app's declared limits, lowered to a dev cell's budget; never raised above what it declared.
18 */
19 export function devLimits(declared: DeclaredLimits | undefined): DeclaredLimits {
20 return {
21 ...declared,
22 memoryMiB: Math.min(declared?.memoryMiB ?? DEV_MEMORY_MIB, DEV_MEMORY_MIB),
23 cpus: Math.min(declared?.cpus ?? DEV_CPUS, DEV_CPUS),
24 };
25 }
26
27 /** The budget as the page and the terminal both say it. */
28 export const devBudgetWords = (): string => `at most ${String(DEV_MEMORY_MIB)} MiB of memory, and it sleeps after ${String(DEV_IDLE_MS / 60_000)} minutes unused`;

Nothing tests that dev_launch applies devLimits to the launched cell; removing that line keeps every test green. Add a launch-level test.

29
30 const IDENTITY_MS = 5 * 60_000;
31
32 /**
33 * The headers that tell the dev server who looks at its frame: the cell's owner, a writer, as the
34 * admin of their own dev environment, signed under the key derived for it alone (the rule a preview
35 * follows, `spawn/preview-owner.ts`). A forge run this way opens on its seeded admin.
36 */
37 export function devIdentityHeaders(key: string, userId: string, username: string, now = Date.now()): Record<string, string> {
38 const identity = `${userId}|${username}|admin|${String(now + IDENTITY_MS)}`;
39 return { "x-forge-identity": identity, "x-forge-signature": createHmac("sha256", key).update(identity).digest("base64url") };
40 }
src/apps/dev_cell.ts +2
@@ -28,6 +28,8 @@ export interface DevRun {
2828 */
2929 readonly dir?: string;
3030 readonly oid?: string;
31 /** The key derived for this dev environment alone; the frame signs who is looking with it. */
32 readonly identity?: string;
3133 }
3234
3335 /** What a launch is told: the cell's secret path and the branch's checkout it runs in. */
src/apps/dev_launch.ts +10 −7
@@ -26,6 +26,7 @@ import { parseManifest } from "./manifest.ts";
2626 import { startProcess, type ProcessHandle } from "./process.ts";
2727 import { devCommand } from "./dev_command.ts";
2828 import type { DevLaunch, DevRun } from "./dev_cell.ts";
29 import { devLimits } from "./dev_budget.ts";
2930
3031 const LINES = 20;
3132
@@ -60,8 +61,9 @@ export async function syncCheckout(bare: string, dir: string, branch: string): P
6061 return set.ok ? ok(tip) : err("could not check the branch out");
6162 }
6263
63 const wrap = (handle: ProcessHandle, recent: string[], dir: string, oid: string): DevRun => ({
64 const wrap = (handle: ProcessHandle, recent: string[], dir: string, oid: string, identity: string): DevRun => ({
6465 dir,
66 identity,
6567 oid,
6668 port: handle.port,
6769 exited: handle.exited,
@@ -72,9 +74,9 @@ const wrap = (handle: ProcessHandle, recent: string[], dir: string, oid: string)
7274 /**
7375 * The launcher for `branch` of `repo`, for `userId`: checked out, then the dev server started and
7476 * waited for. An error is words a person can read: no app here, nothing to run, or the server's
75 * last lines.
77 * last lines. `start` is the seam a test hands a stand-in for the process.
7678 */
77 export function launcherFor(app: App, record: AppRecord, repo: Repo, userId: string, branch: string, base: string): DevLaunch {
79 export function launcherFor(app: App, record: AppRecord, repo: Repo, userId: string, branch: string, base: string, start: typeof startProcess = startProcess): DevLaunch {
7880 const key = devKey(userId, repo.id, branch);
7981 const env = devEnv(key);
8082 return async ({ token, signal }) => {
@@ -90,16 +92,17 @@ export function launcherFor(app: App, record: AppRecord, repo: Repo, userId: str
9092 const run = devCommand({ forgeJson, packageJson, run: parsed.value.run });
9193 if (run === undefined) return err("this branch declares no dev command");
9294 const recent: string[] = [];
93 const started = await startProcess({
95 const devSecret = devIdentityKey(identityKey(app.config.dataDir, record.id), env);
96 const started = await start({
9497 dir,
9598 dataDir: envDataDir(app.config.dataDir, record.id, env),
96 manifest: { ...parsed.value, run, test: null, ready: Math.max(parsed.value.ready, 60) },
99 manifest: { ...parsed.value, run, test: null, ready: Math.max(parsed.value.ready, 60), limits: devLimits(parsed.value.limits) },
97100 env,
98101 url: `${base}/talk/dev/${token}/`,
99102 commitOid: synced.value,
100103 forgeUrl: rt.options.forgeUrl,
101104 repo: `${repo.ownerName}/${repo.name}`,
102 identityKey: devIdentityKey(identityKey(app.config.dataDir, record.id), env),
105 identityKey: devSecret,
103106 log: (line) => {
104107 recent.push(line.slice(0, 300));
105108 if (recent.length > LINES) recent.shift();
@@ -108,6 +111,6 @@ export function launcherFor(app: App, record: AppRecord, repo: Repo, userId: str
108111 cell: rt.cellFor(record, env),
109112 });
110113 if (!started.ok) return err(`${started.error.stage}: ${started.error.message}`);
111 return ok(wrap(started.value.handle, recent, dir, synced.value));
114 return ok(wrap(started.value.handle, recent, dir, synced.value, devSecret));
112115 };
113116 }
src/tui/screens/talk_chats.ts +2 −1
@@ -38,6 +38,7 @@ import { talkDisplayScreen } from "./talk_display.ts";
3838 import { commitWorking, discardWorking, openForEdit, saveWorking, uncommittedLine, workingWords } from "../../actions/working_tree.ts";
3939 import { startTouched, touchedLines, touchedRun, TOUCHED_WORDS } from "../../actions/touched_run.ts";
4040 import { openWorkingPull, workPullWords } from "../../actions/work_pull.ts";
41 import { devBudgetWords } from "../../apps/dev_budget.ts";
4142 import { devBranch, devReading, paneStatus, startDev, stopDev } from "../../actions/dev_workspace.ts";
4243 import { conversationPulls, liveReceipts, paneCrew, paneFell, paneInfo, type LiveReceipt } from "../../core/talk_work.ts";
4344 import { tapRunLogs } from "../../runs/log.ts";
@@ -367,7 +368,7 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
367368 `${name} · ${ws.shows === undefined ? "Production" : `Pull #${String(ws.shows)}`}${pointedAt(picked, steer).path === undefined ? "" : ` · ${pointedAt(picked, steer).path ?? ""}`}`,
368369 paneInfo(f.app.db, ws.repo, ws.shows),
369370 `Status: ${((st) => (st.state === "error" ? `${st.word}; ask the crew to fix it` : st.word))(paneStatus({ url, dev, crew: paneCrew(f.app.db, f.app.config.dataDir, ws.repo.id, f.user, { runs: mayReadRuns(f.app, f.user, ws.repo), logs: false }) }))}`,
370 `Dev server: ${dev === undefined ? `not running; d starts ${branch} with hot reload` : `${dev.state} on ${branch}; d stops it`}${dev?.state === "live" ? " (the page frames it, sandboxed: sign-in and forms that post do not work in it; it sleeps after 10 minutes unused)" : ""}`,
371 `Dev server: ${dev === undefined ? `not running; d starts ${branch} with hot reload` : `${dev.state} on ${branch}; d stops it`}${dev?.state === "live" ? ` (the page frames it, sandboxed: sign-in and forms that post do not work in it; it holds ${devBudgetWords()})` : ""}`,
371372 ...(fell === undefined ? [] : [fell]),
372373 // The working tree, as the Diff tab says it: changed here, not a commit until asked (#17120).
373374 ...(buildHere === undefined || f.user === undefined ? [] : uncommittedLine(f.app, f.user, ws.repo, buildHere.branch)),
src/web/pages/talk_dev.ts +2
@@ -12,6 +12,7 @@
1212 */
1313
1414 import { devBranch, startDev, stopDev } from "../../actions/dev_workspace.ts";
15 import { devIdentityHeaders } from "../../apps/dev_budget.ts";
1516 import { devCellsOf } from "../../apps/dev_cell.ts";
1617 import { canWrite, getRepo, getRepoById } from "../../core/repos.ts";
1718 import { getUserById } from "../../core/users.ts";
@@ -96,6 +97,7 @@ export async function talkDevFrame(ctx: Ctx): Promise<Response> {
9697 const v = ctx.request.headers.get(name);
9798 if (v !== null) headers.set(name, v);
9899 }
100 if (cell.run.identity !== undefined) for (const [k, v] of Object.entries(devIdentityHeaders(cell.run.identity, owner.id, owner.username))) headers.set(k, v);
99101 const base = `/talk/dev/${token}/`;
100102 let answer: Response;
101103 try {
src/web/pages/talk_preview.ts +2 −1
@@ -11,6 +11,7 @@
1111 * streaming beside it carries on.
1212 */
1313
14 import { devBudgetWords } from "../../apps/dev_budget.ts";
1415 import { devBranch, devReading, paneStatus } from "../../actions/dev_workspace.ts";
1516 import { touchedRun } from "../../actions/touched_run.ts";
1617 import { requireWriter } from "../../actions/access.ts";
@@ -158,7 +159,7 @@ export async function talkPane(ctx: Ctx, user: User, name: string | undefined, w
158159 ${url === undefined || view !== "preview" ? null : iconBtn("sync", "Reload the preview", { variant: "ghost", type: "button", extra: "js-only talk-reload" })}
159160 ${url === undefined ? null : btn(icon("external"), { href: url, label: `Open ${name} on its own`, title: "Open on its own", variant: "ghost", external: true, extra: "btn-icon" })}
160161 </div>
161 <p class="talk-pane-info small muted" data-pane-info>${paneInfo(ctx.app.db, ws.repo, ws.shows)}${ws.shows === undefined ? null : html` · <a href="/${name}/pulls/${String(ws.shows)}">the pull</a>`}${devFrame === undefined ? null : html` · The dev server runs in a sandboxed frame: sign-in and forms that post do not work in it.`}</p>
162 <p class="talk-pane-info small muted" data-pane-info>${paneInfo(ctx.app.db, ws.repo, ws.shows)}${ws.shows === undefined ? null : html` · <a href="/${name}/pulls/${String(ws.shows)}">the pull</a>`}${devFrame === undefined ? null : html` · The dev server runs in a sandboxed frame: sign-in and forms that post do not work in it. It holds ${devBudgetWords()}.`}</p>
162163 ${togetherHtml(ctx.app.db, ws.repo, user, "live")}
163164 ${fellLine}
164165 ${panel}
test/dev-budget.test.ts added +28
@@ -0,0 +1,28 @@
1 /**
2 * A dev forge's budget and who its frame speaks as (#17122, W4 of #16940).
3 */
4 import { describe, expect, test } from "bun:test";
5 import { createHmac } from "node:crypto";
6 import { devBudgetWords, devIdentityHeaders, devLimits } from "../src/apps/dev_budget.ts";
7 import { DEV_IDLE_MS } from "../src/apps/dev_cell.ts";
8
9 describe("a dev cell's budget", () => {
10 test("is lowered to the dev memory and one core, whatever production declares", () => {
11 expect(devLimits({ memoryMiB: 2048, cpus: 2, diskMiB: 8192 })).toEqual({ memoryMiB: 1024, cpus: 1, diskMiB: 8192 });
12 expect(devLimits(undefined)).toEqual({ memoryMiB: 1024, cpus: 1 });
13 });
14 test("is never raised above what the app declared", () => {
15 expect(devLimits({ memoryMiB: 256 }).memoryMiB).toBe(256);
16 });
17 test("is said the same in words for both doors", () => {
18 expect(devBudgetWords()).toBe(`at most 1024 MiB of memory, and it sleeps after ${String(DEV_IDLE_MS / 60_000)} minutes unused`);
19 });
20 });
21
22 describe("the identity a dev frame speaks as", () => {
23 test("names the owner as admin, signed under the key given, for five minutes", () => {
24 const h = devIdentityHeaders("k", "u1", "alice", 1000);
25 expect(h["x-forge-identity"]).toBe("u1|alice|admin|301000");
26 expect(h["x-forge-signature"]).toBe(createHmac("sha256", "k").update("u1|alice|admin|301000").digest("base64url"));
27 });
28 });
test/dev-cell-launch.test.ts +6 −1
@@ -5,6 +5,7 @@
55 * process then runs as an app's does.
66 */
77 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { createHmac } from "node:crypto";
89 import { rm } from "node:fs/promises";
910 import { newApp } from "../src/actions/apps.ts";
1011 import { commitToBranch } from "../src/actions/repos.ts";
@@ -18,7 +19,7 @@ import { quietLogs } from "./helpers/globals.ts";
1819
1920 quietLogs();
2021
21 const SERVER = `Bun.serve({ port: Number(process.env.PORT), hostname: "127.0.0.1", fetch: (r) => new URL(r.url).pathname === "/key" ? new Response(String(process.env.FORGE_APP_IDENTITY_KEY) + "|" + String(process.env.FORGE_TOKEN)) : new Response(require("fs").readFileSync("message.txt", "utf8")) });`;
22 const SERVER = `Bun.serve({ port: Number(process.env.PORT), hostname: "127.0.0.1", fetch: (r) => new URL(r.url).pathname === "/who" ? new Response(String(r.headers.get("x-forge-identity")) + "~" + String(r.headers.get("x-forge-signature")) + "~" + String(process.env.FORGE_APP_IDENTITY_KEY)) : new URL(r.url).pathname === "/key" ? new Response(String(process.env.FORGE_APP_IDENTITY_KEY) + "|" + String(process.env.FORGE_TOKEN)) : new Response(require("fs").readFileSync("message.txt", "utf8")) });`;
2223
2324 describe("a dev cell for a branch", () => {
2425 let forge: AppsForge;
@@ -60,6 +61,10 @@ describe("a dev cell for a branch", () => {
6061 const seen = await (await fetch(`${forge.servers.url}/talk/dev/${reading.token}/key`)).text();
6162 expect(seen).not.toContain(identityKey(forge.app.config.dataDir, getAppByRepo(forge.app.db, repo.id)!.id));
6263 expect(seen).toEndWith("|undefined");
64 // The frame tells the server who looks, signed under the key derived for the dev cell alone.
65 const [identity, signature, key] = (await (await fetch(`${forge.servers.url}/talk/dev/${reading.token}/who`, { headers: { "x-forge-identity": "x|root|admin|9999999999999" } })).text()).split("~");
66 expect(identity).toStartWith(`${forge.alice.id}|${forge.alice.username}|admin|`);
67 expect(signature).toBe(createHmac("sha256", key!).update(identity!).digest("base64url"));
6368 await put("second");
6469 // The push event syncs the branch's new tip in; the hot server then answers with the new file.
6570 await pollUntil(async () => (await ask()) === "second", "the commit reaching the running server", 30_000);
test/dev-launch-limits.test.ts added +57
@@ -0,0 +1,57 @@
1 /**
2 * The dev cell is launched with the lowered budget (#17122): what `launcherFor` hands
3 * `startProcess` carries `devLimits`, so removing that line from the launcher fails here.
4 * `startProcess` is replaced by a recorder that refuses, so no process or cell is needed.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { rm } from "node:fs/promises";
8 import { newApp } from "../src/actions/apps.ts";
9 import { commitToBranch } from "../src/actions/repos.ts";
10 import { getAppByRepo } from "../src/core/apps.ts";
11 import { getRepo } from "../src/core/repos.ts";
12 import { launcherFor } from "../src/apps/dev_launch.ts";
13 import { err, type Result } from "../src/kernel/result.ts";
14 import type { StartError, StartedProcess, StartInput } from "../src/apps/process.ts";
15 import { startAppsForge, type AppsForge } from "./helpers/apps-forge.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17
18 quietLogs();
19
20 const seen: StartInput[] = [];
21 const record_ = (input: StartInput): Promise<Result<StartedProcess, StartError>> => {
22 seen.push(input);
23 return Promise.resolve(err({ stage: "start", message: "recorded" }));
24 };
25
26 describe("launching a dev cell", () => {
27 let forge: AppsForge;
28 beforeAll(async () => {
29 forge = await startAppsForge();
30 });
31 afterAll(async () => {
32 await forge.runtime.stop?.();
33 await forge.servers.stop?.();
34 await rm(forge.dataDir, { recursive: true, force: true });
35 });
36
37 test("hands the process the dev budget, below what the app declares", async () => {
38 const made = await newApp(forge.app, forge.alice, { name: "limapp", visibility: "private" });
39 if (!made.ok) throw new Error(String(made.error));
40 const repo = getRepo(forge.app.db, forge.alice.username, "limapp");
41 if (repo === undefined) throw new Error("repo");
42 const c = await commitToBranch(forge.app, forge.alice, repo, {
43 branch: repo.defaultBranch,
44 message: "files",
45 files: [{ path: "forge.json", content: JSON.stringify({ app: { run: "bun server.ts", dev: "bun --hot server.ts", limits: { memory: 4096, cpus: 4 } } }) }],
46 });
47 if (!c.ok) throw new Error(JSON.stringify(c.error));
48 const record = getAppByRepo(forge.app.db, repo.id);
49 if (record === undefined) throw new Error("record");
50 const launch = launcherFor(forge.app, record, repo, forge.alice.id, repo.defaultBranch, forge.servers.url, record_);
51 const result = await launch({ token: "t", signal: new AbortController().signal });
52 expect(result.ok).toBe(false);
53 expect(seen).toHaveLength(1);
54 expect(seen[0]!.manifest.limits?.memoryMiB).toBe(1024);
55 expect(seen[0]!.manifest.limits?.cpus).toBe(1);
56 }, 30_000);
57 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs