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

Client rehearsal: a forge with custom apps for a person with zero technical background, in one link, by Tuesday #1348

Closed opened this in answer to
Closed without merging

scout/forge:scout/1115-client-rehearsal-a-forge-with-custom-app → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
12 files changed +533 −7
docs/SPAWN.md +10
@@ -59,3 +59,13 @@ A spawner may give the child one credential: `modelKey`, an API-billed key (`sk-
5959 ## Callers
6060
6161 `POST /api/v1/forges {name, apps[], crew[], direction?, keepAccess?, modelKey?, budgetUsd?, dryRun}` (rw token, admin only) and the MCP `spawn` tool share `src/spawn/door.ts`. `dryRun` is true unless it is `false`: the answer is the plan and what is left behind, and nothing is made. `GET /api/v1/forges` lists the ledger's children. The child's org is its name; `crew` names the agents whose briefs travel. Errors: 401 unauthorized, 403 forbidden / cross_origin, 422 invalid, 409 refused / exists, 500 failed — each with one sentence. The MCP lets an `ro` token plan, never make.
62
63 ## A forge for someone who is not technical (#1115)
64
65 **New apps from a sentence.** `fresh` on the plan (`POST /api/v1/forges {fresh: [{description, name?}]}`, or one line per app in "New apps, from a sentence" on `/forges/new`) starts an app from nothing: the same scaffold every new app begins as, the sentence as its description and as its direction, so the crew builds toward it. Without a `name` the first words of the sentence are the name. At most 10, each one line of up to 200 characters, names distinct from the copied apps'. Each carried crew member joins a new app in the role they most often have on the copied ones (a builder when there are no copied apps). A plan with no new apps has no `fresh` field at all.
66
67 **The claimant's first screen** (`src/web/studio/client-home.ts`). On a spawned forge, `GET /` shows the apps and nothing else: for each, what it is for (its description), its helpers each "Working on it now" or "Waiting for your word", one box "What do you want changed or added?", and below it what they asked for with its state (Done, Being worked on, Waiting) and the helper's last answer. The page is bare: no menu, map, board or settings. "Show everything" is `/?all=1`, the home the forge always had (including the owner's next steps). The box posts to `POST /tell` with `plain=1`, the same tell as every other door (same-origin, verified email, who may direct the crew), answering in plain words.
68
69 **Left out, on purpose.** A custom domain at spawn (the child keeps `<name>--<parent's host>`; a domain is DNS the owner does, in the child's own settings). A budget still needs a model key, as before.
70
71 **Words that were nerdy** and what the client's screens say instead (`test/client-home.test.ts` keeps them out of the first screen): forge → "your apps"; repository/repo → app; agent, crew, builder, planner → helper; issue, tell → "what you asked for"; run → "working on it now"; production, preview, deploy → left out; admin → "the one in charge"; claim → "make your account to open them". The rehearsal on the live forge (a `client-demo` child with two apps and screenshots) needs a person's session on the live forge and has not been done; the owner's checklist is: spawn it from `/forges/new` with one copied app and one sentence, open the link in a private window, read the first screen aloud to someone who does not work in software, and add every word they stop on to this list.
src/actions/spawn.ts +52
@@ -15,10 +15,13 @@
1515 import { mkdir, readdir, rename } from "node:fs/promises";
1616 import { join } from "node:path";
1717 import { createApp, type App } from "../app.ts";
18 import { scaffoldFiles } from "../apps/scaffold.ts";
19 import { commitToBranch } from "./repos.ts";
1820 import {
1921 addCrew,
2022 BRIEF_MAX,
2123 createAgentRow,
24 type CrewRole,
2225 getAgentByName,
2326 listCrewRoles,
2427 setCrewRole,
@@ -265,6 +268,13 @@ async function make(
265268 });
266269 }
267270
271 /** The commonest of `roles`; a builder when there are none to count. */
272 function mostOften(roles: readonly CrewRole[]): CrewRole {
273 const counts = new Map<CrewRole, number>();
274 for (const r of roles) counts.set(r, (counts.get(r) ?? 0) + 1);
275 return [...counts].sort((a, b) => b[1] - a[1])[0]?.[0] ?? "builder";
276 }
277
268278 /**
269279 * Every step skips what is already there, so a resumed child is finished,
270280 * not doubled. Answers the child's claim token, minted afresh each time.
@@ -344,6 +354,33 @@ async function copyInto(
344354 copiedRepos.push({ parent, child: repo });
345355 }
346356
357 const freshRepos: Repo[] = [];
358 // Apps started from a sentence: the scaffold every new app begins as,
359 // with the sentence as its direction, so the crew builds toward it.
360 for (const f of plan.fresh ?? []) {
361 let repo = getRepo(child.db, org.username, f.name);
362 if (!repo) {
363 const made = await createRepo(child.db, child.reposRoot, {
364 ownerId: org.id,
365 name: f.name,
366 visibility: "private",
367 description: f.description,
368 });
369 if (!made.ok) return err(`could not make ${f.name}: ${made.error}`);
370 const committed = await commitToBranch(child, founder, made.value, {
371 message: `Start ${f.name}`,
372 files: scaffoldFiles({ name: f.name, description: f.description }),
373 });
374 if (!committed.ok) return err(`could not start ${f.name}`);
375 repo = made.value;
376 }
377 if (repo.autonomyDirection === "")
378 repo = updateRepoSettings(child.db, repo, {
379 autonomyDirection: plan.direction === "" ? f.description : `${plan.direction}\n\n${f.description}`,
380 });
381 freshRepos.push(repo);
382 }
383
347384 // The forge's own code, forked into the child with its full history,
348385 // so every child starts from the forge and can follow its parent.
349386 // A cross-forge fork: the history is copied by git, and the upstream
@@ -379,6 +416,21 @@ async function copyInto(
379416 setCrewRole(child.db, repo.id, theirs.user.id, role);
380417 }
381418
419 // A new app has no parent copy to take its crew from: each carried crew
420 // member joins it in the role they have most often on the copied apps.
421 for (const repo of freshRepos) {
422 for (const b of plan.briefs) {
423 const theirs = getAgentByName(child.db, b.agent);
424 if (!theirs) continue;
425 const roles = copiedRepos
426 .flatMap(({ parent }) => listCrewRoles(app.db, parent.id))
427 .filter((c) => c.agent.user.username === b.agent)
428 .map((c) => c.role);
429 addCrew(child.db, repo.id, theirs.user.id, founder.id);
430 setCrewRole(child.db, repo.id, theirs.user.id, mostOften(roles));
431 }
432 }
433
382434 // The child's own keys, made in its own directory now, so they exist
383435 // before its first boot and are provably not the parent's: the key that
384436 // seals its secrets, and its SSH host key.
src/spawn/door.ts +1
@@ -231,6 +231,7 @@ export async function spawnDoor(
231231 // by whoever opens the link.
232232 keepAccess: anon ? false : raw["keepAccess"],
233233 budgetUsd: raw["budgetUsd"],
234 fresh: raw["fresh"],
234235 ...(anon ? {} : { for: raw["for"] }),
235236 };
236237
src/spawn/plan.ts +54
@@ -10,6 +10,9 @@
1010 import { err, ok, type Result } from "../kernel/result.ts";
1111
1212 export const MAX_APPS = 50;
13 /** Apps started fresh from a one-line description, beside the copied ones. */
14 export const MAX_FRESH = 10;
15 export const MAX_FRESH_CHARS = 200;
1316 export const MAX_BRIEFS = 100;
1417 export const MAX_SUBSCRIPTIONS = 200;
1518 export const MAX_BRIEF_CHARS = 20_000;
@@ -30,6 +33,7 @@ export const KEY_BUDGET_NOTE =
3033 export const MAX_BUDGET_USD = 1000;
3134
3235 const NAME = /^[a-z0-9](?:[a-z0-9-]{0,37}[a-z0-9])?$/;
36 const FRESH_NAME = /^[a-z0-9][a-z0-9-]{0,28}[a-z0-9]$/;
3337 const APP_REF = /^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/;
3438
3539 /** An app the viewer can see, as the caller found it. */
@@ -62,6 +66,8 @@ export interface SpawnInput {
6266 * The key itself never enters the plan: only that there is one, capped.
6367 */
6468 readonly budgetUsd?: unknown;
69 /** Apps to start from nothing: a list of `{ description, name? }`; optional. */
70 readonly fresh?: unknown;
6571 }
6672
6773 /** What the parent has to offer. Extra fields are ignored, never copied. */
@@ -78,6 +84,12 @@ export interface PlannedApp {
7884 readonly bytes: number;
7985 }
8086
87 /** An app started fresh: its name and the one line it is to become. */
88 export interface PlannedFresh {
89 readonly name: string;
90 readonly description: string;
91 }
92
8193 export interface SpawnPlan {
8294 readonly name: string;
8395 readonly org: string;
@@ -92,6 +104,8 @@ export interface SpawnPlan {
92104 readonly budgetUsd: number | null;
93105 /** Whom the child is for, for the parent's client list; absent when unsaid. */
94106 readonly forWhom?: string;
107 /** Apps started fresh; absent when there are none. */
108 readonly fresh?: readonly PlannedFresh[];
95109 }
96110
97111 export interface DryRun {
@@ -113,6 +127,22 @@ export const LEFT_BEHIND: readonly string[] = [
113127 "user accounts",
114128 ];
115129
130 /** A name from a description: its first words, as the slug an app is named by. */
131 export function nameFromDescription(description: string): string {
132 const words = description
133 .toLowerCase()
134 .replace(/[^a-z0-9]+/g, " ")
135 .trim()
136 .split(" ")
137 .filter((w) => w !== "");
138 let name = "";
139 for (const w of words.slice(0, 4)) {
140 if (`${name}-${w}`.length > 30) break;
141 name = name === "" ? w : `${name}-${w}`;
142 }
143 return name.slice(0, 30).replace(/-+$/, "");
144 }
145
116146 const refuse = (field: string, reason: string) => err<Refusal>({ field, reason });
117147 const byText = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
118148
@@ -197,6 +227,28 @@ export function planSpawn(
197227 if (forWhom.length > MAX_FOR_CHARS) return refuse("for", `at most ${MAX_FOR_CHARS} characters`);
198228 }
199229
230 const fresh: PlannedFresh[] = [];
231 if (input.fresh !== undefined && input.fresh !== null) {
232 if (!Array.isArray(input.fresh)) return refuse("fresh", "must be a list of apps");
233 if (input.fresh.length > MAX_FRESH) return refuse("fresh", `at most ${MAX_FRESH} new apps`);
234 const taken = new Set(apps.map((a) => a.ref.split("/")[1]!.toLowerCase()));
235 for (const item of input.fresh as unknown[]) {
236 const o = (typeof item === "object" && item !== null ? item : {}) as Record<string, unknown>;
237 if (typeof o["description"] !== "string") return refuse("fresh", "a new app needs a line saying what it is for");
238 const description = o["description"].trim();
239 // One line, no control characters: it is shown on pages and written into files.
240 if (description === "" || description.length > MAX_FRESH_CHARS || /[\u0000-\u001f\u007f]/.test(description))
241 return refuse("fresh", `a new app is one line of 1-${MAX_FRESH_CHARS} characters`);
242 const name = o["name"] === undefined || o["name"] === "" ? nameFromDescription(description) : o["name"];
243 if (typeof name !== "string" || !FRESH_NAME.test(name))
244 return refuse("fresh", `"${description.slice(0, 40)}" needs a name of letters and digits, e.g. my-shop`);
245 if (taken.has(name)) return refuse("fresh", `two apps are named ${name}`);
246 taken.add(name);
247 fresh.push({ name, description });
248 }
249 fresh.sort((a, b) => byText(a.name, b.name));
250 }
251
200252 // `forWhom` only when said, so a plan without it hashes as it always did.
201253 return ok({
202254 name,
@@ -208,6 +260,7 @@ export function planSpawn(
208260 keepAccess,
209261 budgetUsd,
210262 ...(forWhom === "" ? {} : { forWhom }),
263 ...(fresh.length === 0 ? {} : { fresh }),
211264 });
212265 }
213266
@@ -217,6 +270,7 @@ const enc = new TextEncoder();
217270 export function dryRun(plan: SpawnPlan, source: SpawnSource): DryRun {
218271 const copied = [
219272 ...plan.apps.map((a) => `app ${a.ref} (full history, forge.json)`),
273 ...(plan.fresh ?? []).map((f) => `new app ${f.name}: ${f.description}`),
220274 ...plan.briefs.map((b) => `crew brief for ${b.agent}`),
221275 ...plan.subscriptions.map((s) => `subscription ${s} (name only)`),
222276 ...(plan.direction === "" ? [] : ["your words, as the child's direction"]),
src/web/pages/claim.ts +3 −3
@@ -128,9 +128,9 @@ function claimForm(
128128 ${pageHead("This forge is yours")}
129129 ${card(
130130 html`<p class="mb">
131 ${spawned.org.username} was made for you, with its apps and a crew
132 ready to build them. Make your account to take it: this first account
133 is the forge's admin, so it can change everything here.
131 ${spawned.org.username} was made for you: your apps are ready, and
132 helpers (computer assistants) are ready to work on them. Make your
133 account to open them. You will be the one in charge here.
134134 </p>
135135 <p class="mb" id="claim-access">${accessSentence(spawned, spawner)}</p>
136136 <form method="post" action="${ctx.url.pathname}">
src/web/pages/new-forge.ts +22
@@ -31,6 +31,8 @@ interface Values {
3131 readonly forWhom: string;
3232 readonly direction: string;
3333 readonly apps: readonly string[];
34 /** New apps, one line each: what each is for. */
35 readonly fresh: string;
3436 readonly crew: readonly string[];
3537 readonly keepAccess: boolean;
3638 readonly budgetUsd: string;
@@ -44,6 +46,7 @@ const EMPTY: Values = {
4446 forWhom: "",
4547 direction: "",
4648 apps: [],
49 fresh: "",
4750 crew: [],
4851 keepAccess: false,
4952 budgetUsd: "",
@@ -161,6 +164,15 @@ function formView(
161164 ? html`<span class="error" id="f-apps-err">${errors["apps"]}</span>`
162165 : null}
163166 </fieldset>
167 ${formField({
168 label: "New apps, from a sentence",
169 name: "fresh",
170 type: "textarea",
171 rows: 3,
172 value: values.fresh,
173 hint: "One app per line, in plain words: \"A booking page for my hair salon\". Each starts from nothing and the crew builds toward it.",
174 ...(errors["fresh"] ? { error: errors["fresh"] } : {}),
175 })}
164176 ${crew.length === 0
165177 ? null
166178 : html`<fieldset class="field">
@@ -317,6 +329,14 @@ function madeView(body: Record<string, unknown>): Html {
317329 </div>`;
318330 }
319331
332 /** The textarea's lines as new apps: blank lines dropped, each line a description. */
333 export const freshOf = (text: string): { description: string }[] =>
334 text
335 .split(/\r?\n/)
336 .map((l) => l.trim())
337 .filter((l) => l !== "")
338 .map((description) => ({ description }));
339
320340 const asBool = (form: Form, name: string): boolean =>
321341 field(form, name) === "on";
322342
@@ -343,6 +363,7 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
343363 forWhom: field(form, "for").trim(),
344364 direction: field(form, "direction"),
345365 apps: all(form, "apps"),
366 fresh: field(form, "fresh"),
346367 crew: all(form, "crew"),
347368 keepAccess: asBool(form, "keepAccess"),
348369 budgetUsd: field(form, "budgetUsd").trim(),
@@ -355,6 +376,7 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
355376 name: values.name,
356377 apps: values.apps,
357378 crew: values.crew,
379 fresh: freshOf(values.fresh),
358380 keepAccess: values.keepAccess,
359381 ...(values.forWhom === "" ? {} : { for: values.forWhom }),
360382 ...(values.direction.trim() === "" ? {} : { direction: values.direction }),
src/web/studio/actions.ts +17
@@ -47,12 +47,29 @@ async function tellFrom(
4747 back: string,
4848 ): Promise<Response> {
4949 const text = field(form, "text").trim();
50 // The handed-over forge's box (`client-home.ts`) answers in plain words.
51 const plain = field(form, "plain") === "1";
5052 if (text === "")
5153 return flashTo(ctx, back, {
5254 tone: "danger",
5355 message: "Say something first.",
5456 });
5557 const told = await tell(ctx.app, ctx.auth.user, repo, text);
58 if (!told.ok && plain)
59 return flashTo(ctx, back, {
60 tone: "danger",
61 message:
62 told.error === "unverified"
63 ? "Please confirm your email address first, then send this again."
64 : "That could not be sent. Please try again.",
65 });
66 if (told.ok && plain)
67 return flashTo(ctx, back, {
68 message:
69 told.value.routed === undefined
70 ? "Thank you. We have it, and a helper will pick it up soon."
71 : "Thank you. A helper is on it, and the answer will appear here.",
72 });
5673 if (!told.ok)
5774 return flashTo(ctx, back, {
5875 tone: "danger",
src/web/studio/client-home.ts added +147
@@ -0,0 +1,147 @@
1 /**
2 * The first screen of someone who was handed a forge (#1115): their apps,
3 * what each is for in plain words, who is working on it, one box to say what
4 * they want, and what came of what they asked. Nothing else — no map, no
5 * board, no settings — until they ask (`/?all=1`). Every word here is meant
6 * to pass "would a shop owner understand it"; `test/client-home.test.ts`
7 * keeps the jargon out.
8 */
9
10 import { listCrewRoles } from "../../core/agents.ts";
11 import { listComments, listIssues, type Issue } from "../../core/issues.ts";
12 import type { Repo } from "../../core/repos.ts";
13 import { listRuns } from "../../core/runs.ts";
14 import type { User } from "../../core/users.ts";
15 import type { Ctx } from "../../http/context.ts";
16 import { html, type Html } from "../html.ts";
17 import { page } from "../layout.ts";
18 import { btn, card, timeAgo } from "../ui.ts";
19 import { writableAppsOf } from "./asks.ts";
20
21 const MAX_APPS = 12;
22 const MAX_ASKS = 3;
23 const ANSWER_CHARS = 400;
24
25 /** The code repository every spawned forge carries is not one of the person's apps. */
26 const isTheirs = (r: Repo): boolean => r.name !== "forge";
27
28 /** What the app is for: its description, else the first line of what it was started for. */
29 export function whatItIsFor(repo: Repo): string {
30 const said = repo.description.trim() || repo.autonomyDirection.trim().split("\n")[0]!.trim();
31 return said === "" ? "Still being set up." : said;
32 }
33
34 export interface Helper {
35 readonly name: string;
36 readonly working: boolean;
37 }
38
39 /** The helpers on an app, each working (a job is running or queued) or waiting. */
40 export function helpersOf(ctx: Ctx, repo: Repo): Helper[] {
41 const busy = new Set<string>();
42 for (const run of listRuns(ctx.app.db, repo.id, { kind: "agent", limit: 50 }))
43 if ((run.state === "running" || run.state === "queued") && run.actorId !== null)
44 busy.add(run.actorId);
45 return listCrewRoles(ctx.app.db, repo.id).map(({ agent }) => ({
46 name: agent.user.username,
47 working: busy.has(agent.user.id),
48 }));
49 }
50
51 /** An ask in a word a person uses: done, being worked on, or waiting its turn. */
52 export function askState(issue: Issue): "Done" | "Being worked on" | "Waiting" {
53 if (issue.state === "closed") return "Done";
54 return issue.assigneeId === null ? "Waiting" : "Being worked on";
55 }
56
57 function helpersLine(helpers: readonly Helper[]): Html {
58 if (helpers.length === 0)
59 return html`<p class="muted small">No helpers yet. Whoever sent you this will add some.</p>`;
60 return html`<ul class="list">
61 ${helpers.map(
62 (h) =>
63 html`<li class="row">
64 <span>${h.name}</span><span class="spacer"></span>
65 <span class="${h.working ? "" : "muted"}"
66 >${h.working ? "Working on it now" : "Waiting for your word"}</span
67 >
68 </li>`,
69 )}
70 </ul>`;
71 }
72
73 /** What you asked on this app, newest first, each with the helper's answer when there is one. */
74 function asksOf(ctx: Ctx, user: User, repo: Repo): Html {
75 const asked = listIssues(ctx.app.db, repo.id, {
76 state: "all",
77 author: user.username,
78 limit: MAX_ASKS,
79 });
80 if (asked.length === 0) return html``;
81 return html`<h3 class="small muted">What you asked for</h3>
82 <ul class="list">
83 ${asked.map((issue) => {
84 const answer = listComments(ctx.app.db, issue.id)
85 .filter((c) => c.authorName !== user.username)
86 .at(-1);
87 return html`<li class="stack">
88 <div class="row">
89 <b>${issue.title}</b><span class="spacer"></span
90 ><span class="small muted"
91 >${askState(issue)} · ${timeAgo(issue.createdAt)}</span
92 >
93 </div>
94 ${answer === undefined
95 ? null
96 : html`<p class="small"><b>${answer.authorName} answered:</b>
97 ${answer.body.length > ANSWER_CHARS
98 ? `${answer.body.slice(0, ANSWER_CHARS).trimEnd()}…`
99 : answer.body}</p>`}
100 </li>`;
101 })}
102 </ul>`;
103 }
104
105 function appCard(ctx: Ctx, user: User, repo: Repo): Html {
106 const slug = `${repo.ownerName}/${repo.name}`;
107 return card(
108 html`<p class="mb">${whatItIsFor(repo)}</p>
109 ${helpersLine(helpersOf(ctx, repo))}
110 <form method="post" action="/tell" class="stack mt">
111 <input type="hidden" name="app" value="${slug}" />
112 <input type="hidden" name="plain" value="1" />
113 <label class="small muted" for="ask-${repo.id}">What do you want changed or added?</label>
114 <textarea
115 class="input"
116 id="ask-${repo.id}"
117 name="text"
118 rows="2"
119 maxlength="2000"
120 required
121 placeholder="Say it in your own words"
122 ></textarea>
123 <div class="form-actions">${btn("Send", { variant: "primary" })}</div>
124 </form>
125 ${asksOf(ctx, user, repo)}
126 <p class="mt small">${btn("Open", { href: `/${slug}`, size: "sm" })}</p>`,
127 { head: html`<h2>${repo.name}</h2>` },
128 );
129 }
130
131 /** GET / on a handed-over forge: the apps and nothing else. */
132 export function clientHome(ctx: Ctx, user: User): Response {
133 const apps = writableAppsOf(ctx, user).repos.filter(isTheirs).slice(0, MAX_APPS);
134 const body = html`<div class="narrow-wide stack">
135 <h1>Welcome, ${user.displayName || user.username}</h1>
136 <p>
137 These are your apps. Each one has helpers: computer assistants that build
138 it and keep improving it. Tell them what you want, in your own words, and
139 they answer right here.
140 </p>
141 ${apps.length === 0
142 ? card(html`<p>Your apps are still being set up. Come back in a few minutes.</p>`)
143 : apps.map((r) => appCard(ctx, user, r))}
144 <p class="small muted"><a href="/?all=1">Show everything</a></p>
145 </div>`;
146 return page({ ctx, title: "Your apps", body, bare: true });
147 }
src/web/studio/home.ts +6 −2
@@ -48,6 +48,7 @@ import { writableAppsOf } from "./asks.ts";
4848 import { needsYouSection, type AsksTop } from "./asks_page.ts";
4949 import { composer, feedJs, feedNote, feedRegion } from "./feed.ts";
5050 import { homeTabs } from "./home_tabs.ts";
51 import { clientHome } from "./client-home.ts";
5152 import { crewKeyNote } from "./crew.ts";
5253 import { everydayCard } from "../pages/everyday.ts";
5354 import { nextStepsCard } from "../pages/next-steps.ts";
@@ -163,10 +164,13 @@ export async function studioHome(
163164 user: User,
164165 top?: AsksTop,
165166 ): Promise<Response> {
166 const needsYou = needsYouSection(ctx, user, top);
167 const { repos: appRepos } = writableAppsOf(ctx, user);
168167 // A spawned forge says where it lives: the address its person shares.
169168 const spawned = await spawnedOrg(ctx.app);
169 // Handed over, the first screen is the apps alone; `?all=1` is the rest.
170 if (spawned !== undefined && !ctx.url.searchParams.has("all"))
171 return clientHome(ctx, user);
172 const needsYou = needsYouSection(ctx, user, top);
173 const { repos: appRepos } = writableAppsOf(ctx, user);
170174 const address = when(
171175 spawned?.url,
172176 (url) =>
test/client-home.test.ts added +219
@@ -0,0 +1,219 @@
1 /**
2 * The handed-over forge (#1115): a child made with a copied app and one
3 * started from a sentence; its claimant's first screen is the apps and
4 * nothing else, in words a shop owner knows; one box tells the crew, and
5 * what came of it shows on the app. Plus the plan's rules for a sentence.
6 */
7
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createRepo } from "../src/actions/repos.ts";
13 import { childDirOf, spawnForge, type SpawnDeps } from "../src/actions/spawn.ts";
14 import { createApp, type App } from "../src/app.ts";
15 import { addCrew, createAgentRow, setCrewRole } from "../src/core/agents.ts";
16 import { addComment, listIssues } from "../src/core/issues.ts";
17 import { getRepo } from "../src/core/repos.ts";
18 import { createUser, type User } from "../src/core/users.ts";
19 import { commitFiles } from "../src/git/write.ts";
20 import { repoDir } from "../src/git/repos.ts";
21 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
22 import { firstBoot } from "../src/spawn/first-boot.ts";
23 import { hostedPlacement } from "../src/spawn/placement.ts";
24 import { nameFromDescription, planSpawn, type SpawnSource } from "../src/spawn/plan.ts";
25 import { freshOf } from "../src/web/pages/new-forge.ts";
26 import { quietLogs } from "./helpers/globals.ts";
27
28 quietLogs();
29
30 const author = { name: "a", email: "[email protected]" };
31 const SALON = "A booking page for my hair salon";
32 const empty: SpawnSource = { catalog: [], briefs: [], subscriptions: [] };
33 const base = { name: "n", org: "n", apps: [], carryBriefs: false, carrySubscriptions: false };
34
35 describe("a new app from one sentence, in the plan", () => {
36 test("the name comes from the words, and the plan lists it", () => {
37 expect(nameFromDescription(SALON)).toBe("a-booking-page-for");
38 const plan = planSpawn({ ...base, fresh: [{ description: SALON }] }, empty);
39 if (!plan.ok) throw new Error("plan");
40 expect(plan.value.fresh).toEqual([{ name: "a-booking-page-for", description: SALON }]);
41 });
42 test("a plan without new apps has no `fresh` at all", () => {
43 const plan = planSpawn(base, empty);
44 if (!plan.ok) throw new Error("plan");
45 expect("fresh" in plan.value).toBe(false);
46 });
47 test("bad sentences are refused at the boundary", () => {
48 for (const fresh of [
49 "x",
50 [{}],
51 [{ description: "" }],
52 [{ description: "two\nlines" }],
53 [{ description: "x".repeat(201) }],
54 [{ description: "!!!" }],
55 [{ description: "ok", name: "../evil" }],
56 [{ description: "a shop" }, { description: "a shop" }],
57 Array.from({ length: 11 }, (_, i) => ({ description: `app ${i}` })),
58 ]) {
59 const plan = planSpawn({ ...base, fresh }, empty);
60 expect(plan.ok).toBe(false);
61 if (!plan.ok) expect(plan.error.field).toBe("fresh");
62 }
63 });
64 test("the form's lines become sentences, blanks dropped", () => {
65 expect(freshOf(" one \r\n\n two\n")).toEqual([{ description: "one" }, { description: "two" }]);
66 });
67 });
68
69 describe("the client's first screen", () => {
70 let dir = "";
71 let parent: App;
72 let alice: User;
73 let child: App;
74 let http: ForgeHttp;
75 const ORIGIN = "http://demo.test";
76 let cookie = "";
77
78 const url = (path: string) => `${ORIGIN}${path}`;
79 const get = (path: string) => http.handle(new Request(url(path), { headers: { cookie } }));
80 /** What a person reads: the page without its markup, scripts or styles. */
81 const seen = (html: string) =>
82 html
83 .replace(/<(head|script|style)[\s\S]*?<\/\1>/g, " ")
84 .replace(/<[^>]+>/g, " ")
85 .replace(/\s+/g, " ");
86
87 beforeAll(async () => {
88 dir = await mkdtemp(join(tmpdir(), "forge-client-home-"));
89 parent = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
90 const made = await createUser(parent.db, { trusted: true, username: "alice", email: "[email protected]", isAdmin: true });
91 if (!made.ok) throw new Error("user");
92 alice = made.value;
93 const repo = await createRepo(parent, alice, { name: "bakery", description: "Orders and the weekly menu" });
94 if (!repo.ok) throw new Error("repo");
95 const c = await commitFiles(repoDir(parent.reposRoot, "alice", "bakery"), {
96 branch: "main",
97 message: "the bakery",
98 files: [
99 { path: "README.md", content: "# bakery\n" },
100 { path: "forge.json", content: JSON.stringify({ app: { run: "bun run src/server.ts", health: "/healthz" } }) },
101 { path: "package.json", content: JSON.stringify({ name: "bakery" }) },
102 ],
103 author,
104 });
105 if (!c.ok) throw new Error("commit");
106 const agent = await createUser(parent.db, { trusted: true, username: "scout", email: "[email protected]", agent: true });
107 if (!agent.ok) throw new Error("agent");
108 createAgentRow(parent.db, { userId: agent.value.id, brief: "scout's brief", createdBy: alice.id });
109 addCrew(parent.db, repo.value.id, agent.value.id, alice.id);
110 setCrewRole(parent.db, repo.value.id, agent.value.id, "builder");
111 const deps: SpawnDeps = {
112 placement: hostedPlacement({ host: "forge.test" }),
113 request: new Request("https://forge.test/x", { method: "POST", headers: { origin: "https://forge.test" } }),
114 url: new URL("https://forge.test/x"),
115 };
116 const spawned = await spawnForge(
117 parent,
118 alice,
119 { ...base, name: "demo", org: "demo", apps: ["alice/bakery"], carryBriefs: true, fresh: [{ description: SALON, name: "salon" }] },
120 {
121 catalog: [{ ref: "alice/bakery", readable: true, bytes: 10, forgeJsonBytes: 0 }],
122 briefs: [{ agent: "scout", text: "scout's brief" }],
123 subscriptions: [],
124 },
125 deps,
126 );
127 if (!spawned.ok) throw new Error(JSON.stringify(spawned.error));
128 const token = (spawned.value.claimUrl ?? "").split("/claim#")[1] ?? "";
129 child = createApp({ dataDir: childDirOf(parent, spawned.value.bodyId), port: 0 });
130 await firstBoot(child);
131 http = forgeHttp(child);
132 const claimed = await http.handle(
133 new Request(url("/claim"), {
134 method: "POST",
135 headers: { origin: ORIGIN },
136 body: new URLSearchParams({ token, username: "dana", email: "[email protected]", password: "a-long-shop-passphrase" }),
137 }),
138 );
139 if (claimed.status !== 303) throw new Error(`claim ${claimed.status}`);
140 cookie = (claimed.headers.get("set-cookie") ?? "").split(";")[0]!;
141 }, 60_000);
142
143 afterAll(async () => {
144 http.close();
145 child.close();
146 parent.close();
147 await rm(dir, { recursive: true, force: true });
148 });
149
150 test("the sentence became an app the crew is directed to build", () => {
151 const repo = getRepo(child.db, "demo", "salon")!;
152 expect(repo.description).toBe(SALON);
153 expect(repo.autonomyDirection).toBe(SALON);
154 expect(getRepo(child.db, "demo", "bakery")).toBeDefined();
155 });
156
157 test("the home is the apps, each in plain words, and nothing else", async () => {
158 const res = await get("/");
159 expect(res.status).toBe(200);
160 const raw = await res.text();
161 const text = seen(raw);
162 expect(text).toContain("Welcome");
163 expect(text).toContain("Orders and the weekly menu");
164 expect(text).toContain(SALON);
165 expect(text).toContain("Waiting for your word");
166 expect(text).toContain("What do you want changed or added?");
167 // No map, no board, no settings until asked; and nothing a shop owner
168 // would have to look up.
169 for (const nerdy of [
170 "repo", "issue", "pull", "branch", "commit", "merge", "deploy", "agent",
171 "crew", "token", "API", "Map", "Board", "Settings", "Audit", "preview",
172 "production", "forge",
173 ])
174 expect(text).not.toMatch(new RegExp(`\\b${nerdy}`, "i"));
175 expect(raw).not.toContain('href="/map"');
176 // The code repository every handed-over forge carries is not one of the apps.
177 expect(raw).not.toContain("demo/forge");
178 });
179
180 test("everything is one click away", async () => {
181 const text = seen(await (await get("/?all=1")).text());
182 expect(text).toContain("Map");
183 });
184
185 test("what the client says becomes work, answered on the app, in plain words", async () => {
186 const said = "Please add a price list to the front page";
187 const sent = await http.handle(
188 new Request(url("/tell"), {
189 method: "POST",
190 headers: { cookie, origin: ORIGIN },
191 body: new URLSearchParams({ app: "demo/salon", plain: "1", text: said }),
192 }),
193 );
194 expect(sent.status).toBe(303);
195 expect(sent.headers.get("location")).toBe("/");
196 const repo = getRepo(child.db, "demo", "salon")!;
197 const issue = listIssues(child.db, repo.id, { state: "all", author: "dana" })[0];
198 if (issue === undefined) throw new Error(`not told: ${sent.headers.get("set-cookie")}`);
199 expect(issue.title).toBe(said);
200 const helper = await createUser(child.db, { trusted: true, username: "helper1", email: "[email protected]", agent: true });
201 if (!helper.ok) throw new Error("helper");
202 addComment(child.db, { issueId: issue.id, authorId: helper.value.id, body: "Done: the price list is on the front page." });
203 const text = seen(await (await get("/")).text());
204 expect(text).toContain("What you asked for");
205 expect(text).toContain(said);
206 expect(text).toContain("helper1 answered: Done: the price list is on the front page.");
207 });
208
209 test("a post from another origin is refused", async () => {
210 const res = await http.handle(
211 new Request(url("/tell"), {
212 method: "POST",
213 headers: { cookie, origin: "https://evil.test" },
214 body: new URLSearchParams({ app: "demo/salon", text: "x" }),
215 }),
216 );
217 expect(res.status).toBe(403);
218 });
219 });
test/first-login.test.ts +1 −1
@@ -45,7 +45,7 @@ describe("the first login to a spawned forge", () => {
4545 let daily = "";
4646
4747 const url = (path: string) => `${servers.url}${path}`;
48 const page = async (cookie: string, path = "/") =>
48 const page = async (cookie: string, path = "/?all=1") =>
4949 (await (await fetch(url(path), { headers: { cookie } })).text()).replace(
5050 /\s+/g,
5151 " ",
test/spawn-keys.test.ts +1 −1
@@ -399,7 +399,7 @@ describe("a spawned child's own keys and domain", () => {
399399 const cookie = (claimed.headers.get("set-cookie") ?? "").split(";")[0]!;
400400 const home = (
401401 await (
402 await fetch(`${childServers.url}/`, { headers: { cookie } })
402 await fetch(`${childServers.url}/?all=1`, { headers: { cookie } })
403403 ).text()
404404 ).replace(/\s+/g, " ");
405405 expect(home).toContain(

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs