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

A person who opens the forge's link can start their own forge from the first… #11183

Parked opened this in answer to
Closed without merging

scout/forge:scout/11153-a-person-who-opens-the-forge-s-link-can → main 17 commits fork 6 threads · 6 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
22 files changed +724 −20
AGENTS.md +2
@@ -25,5 +25,7 @@ State shared between modules through process memory, not the database, is named
2525
2626 `src/core/transfer.ts`: the old owner/name pairs a transfer left behind (`repo_redirect`), held per database after the first request reads them and dropped by `transferRepo`, so a request under a path nothing moved from costs no statement (#569).
2727
28 `src/http/stranger_window.ts`: a fixed one-minute count per socket address for `/start/check` and `/start/ready`, at most 4096 addresses held (a full table is emptied, which only lets requests through), gone on restart. `src/web/pages/start.ts` holds the count of ready probes in flight (at most 4).
29
2830 ## Awake ceiling and the boot
2931 `FORGE_CHILD_AWAKE_MAX` counts forges in use. Hosted children the boot opens (so their apps come back) are exempt from `awakeCount` until a credentialed request reaches them or they sleep (`bootOpened` in `src/spawn/host.ts`). The exempt set holds only body ids of existing finished children and is emptied when the parent closes, so it is bounded by the number of children. Cell children are always counted; they are not opened by the boot.
docs/design/audit.md +2
@@ -132,6 +132,8 @@ Machine routes are not pages and have no entry: `/audit.csv`,
132132 - `/login` — `http/server.ts` (`signinAlias`) · the address people type to sign in · it is `/signin`, keeping a same-origin `next` · none (308, no page of its own).
133133 - `/sign-in` — `http/server.ts` (`signinAlias`) · the same, hyphenated · it is `/signin` · none (308, no page of its own).
134134 - `/signup` — `pages/site.ts` · make an account · `/signup` passkey flow (`signup-passkey.ts`) · colours 3 (file).
135 - `/start/check` — `pages/start.ts` · live check of the name typed on the front door · `/` · none (a fragment).
136 - `/start/ready` — `pages/start.ts` · whether the new forge is awake yet · `/claim` · none (a fragment).
135137 - `/signup/requested` — `pages/site.ts` · what a stranger whose request waits is told · `/signin` · colours 3 (file).
136138 - `/verify` — `pages/site.ts` · confirm an email address · none · colours 3 (file).
137139 - `/recover` — `pages/passkeys.ts` · get back in without a password · `/settings/passkeys` · none seen.
docs/features/start-forge.md added +9
@@ -0,0 +1,9 @@
1 # Start my forge
2
3 A person who opens the forge's link can start their own forge from its first screen (#11153): one field, one button, no account first.
4
5 - **Page:** `/` for a visitor (`src/web/pages/start.ts`). Type a name; the line under the field says free or taken as you type (`GET /start/check`). *Start my forge* posts to `POST /start`, which goes through the same spawn door as `/forges/new` and `POST /api/v1/forges` (`spawnDoor`: the free plan, a visitor's three forges a day). The answer is a page that waits until the new forge answers (`GET /start/ready`, up to two minutes), then goes to its claim page, where the person chooses a username and password. The claim code rides the link's fragment. A refusal is said on the home page above the same form. A signed-in person is sent to `/forges/new?name=…`.
6 - **Terminal:** the palette's *Start my forge* (any person, not an agent; `src/tui/screens/start_forge.ts`): `n` asks for a name, says at once if it is taken, and makes the forge through the same door; the claim link is shown once. The full form with its extras is *New forge*.
7 - **Names:** `src/spawn/name_state.ts`: free, or taken with one near name to try; a word the forge keeps (`core/reserved.ts`, which includes `start`) reads taken.
8 - **Limits:** `/start/check` 60 and `/start/ready` 90 a minute per socket address (`src/http/stranger_window.ts`, 429 with `retry-after`), and at most 4 children probed at once from everyone; over that the answer is "not yet" and the page asks again.
9 - **A new forge's first screen** says its two ways to begin (`nextLine`, `src/web/pages/next-steps.ts`); the waking page says "Setting up" for a forge made in the last ten minutes, from the ledger the proxy already read.
src/actions/spawn.ts +1 −1
@@ -163,7 +163,7 @@ const fail = (message: string) => err<SpawnError>({ kind: "failed", message });
163163
164164 export const childDirOf = (app: App, bodyId: string): string =>
165165 join(app.config.dataDir, "children", bodyId);
166 const ledgerPath = (app: App, name: string): string =>
166 export const ledgerPath = (app: App, name: string): string =>
167167 join(app.config.dataDir, "spawn", `${name}.json`);
168168
169169 /** Live child URL from name + the parent's origin (ignores stale ledger.url), so old subdomain ledgers still resolve. */
src/core/reserved.ts +1
@@ -113,6 +113,7 @@ export const SYSTEM_NAMES: readonly string[] = [
113113 "plugins",
114114 "signin",
115115 "signup",
116 "start",
116117 "sitemap.xml",
117118 "releases",
118119 "releases.json",
src/http/server.ts +4
@@ -275,6 +275,7 @@ import { familyPage } from "../web/pages/family.ts";
275275 import { forgeLinkRevoke, forgeLinkSubmit, forgeLinkUndo, forgeRemoveConfirm, forgeRemoveSubmit, forgeStopSubmit,
276276 forgeOwnCodeSubmit, forgesPage } from "../web/pages/forges.ts";
277277 import { forgeItSubmit } from "../web/pages/forge-it.ts";
278 import { startCheck, startReady, startSubmit } from "../web/pages/start.ts";
278279 import { newForgePage, newForgeSubmit } from "../web/pages/new-forge.ts";
279280 import { askedPage } from "../web/studio/asked_page.ts";
280281 import { notesOverrule, notesSave, notesView } from "../web/pages/notes.ts";
@@ -846,6 +847,9 @@ export function buildRouter(): Router<Handler> {
846847 router.add("POST", "/forges/:name/own-code", forgeOwnCodeSubmit);
847848 router.add("GET", "/forges/:name/remove", forgeRemoveConfirm);
848849 router.add("POST", "/forges/:name/remove", forgeRemoveSubmit);
850 router.add("GET", "/start/check", startCheck);
851 router.add("GET", "/start/ready", startReady);
852 router.add("POST", "/start", (ctx) => startSubmit(ctx, studioDoor));
849853 router.add("GET", "/forges/new", newForgePage);
850854 router.add("POST", "/forges/new", newForgeSubmit);
851855 // The front page as a stranger sees it, for anyone; a site admin there
src/http/stranger_window.ts added +24
@@ -0,0 +1,24 @@
1 /**
2 * A small fixed window per socket address, for a stranger's cheap reads that
3 * still touch the disk or a child (`/start/check`, `/start/ready`). In
4 * memory, bounded: at most `MAX_KEYS` addresses are held, and a full table
5 * forgets everyone, which only ever lets a request through. Seconds to wait
6 * when refused, or undefined when the request may go on.
7 */
8
9 const MAX_KEYS = 4096;
10 const windows = new Map<string, { start: number; n: number }>();
11
12 export function strangerWindow(key: string, limit: number, windowMs = 60_000, now = Date.now()): number | undefined {
13 const seen = windows.get(key);
14 if (seen === undefined || now - seen.start >= windowMs) {
15 if (windows.size >= MAX_KEYS) windows.clear();
16 windows.set(key, { start: now, n: 1 });
17 return undefined;
18 }
19 seen.n += 1;
20 return seen.n > limit ? Math.max(1, Math.ceil((seen.start + windowMs - now) / 1000)) : undefined;
21 }
22
23 /** Forget every window (tests). */
24 export const resetStrangerWindows = (): void => windows.clear();
src/spawn/door.ts +3
@@ -54,6 +54,9 @@ export function useProbe(app: App, probe: (url: string) => Probe): void {
5454 probes.set(app, probe);
5555 }
5656
57 /** The probe of a child's public address: the test's stand-in when one is set. */
58 export const probeFor = (app: App, url: string): Probe => (probes.get(app) ?? probeOf)(url);
59
5760 /** Tests (and an external placement, one day) swap where children live. */
5861 export function usePlacement(app: App, placement: Placement): void {
5962 placements.set(app, placement);
src/spawn/host.ts +6 −2
@@ -44,6 +44,8 @@ interface ChildLedger {
4444 readonly done: boolean;
4545 readonly placement: PlacementKind;
4646 readonly size: Size;
47 /** When the ledger says it was made, ISO; the waking page says "setting up" for a new one. */
48 readonly createdAt?: string;
4749 }
4850
4951 function readLedgerSync(app: App, name: string): ChildLedger | undefined {
@@ -56,6 +58,7 @@ function readLedgerSync(app: App, name: string): ChildLedger | undefined {
5658 done?: unknown;
5759 placement?: unknown;
5860 size?: unknown;
61 createdAt?: unknown;
5962 };
6063 if (typeof parsed.name !== "string" || typeof parsed.bodyId !== "string") return undefined;
6164 return {
@@ -65,6 +68,7 @@ function readLedgerSync(app: App, name: string): ChildLedger | undefined {
6568 done: parsed.done === true,
6669 placement: parsed.placement === "cell" ? "cell" : "hosted",
6770 size: isSize(parsed.size) ? parsed.size : DEFAULT_SIZE,
71 ...(typeof parsed.createdAt === "string" ? { createdAt: parsed.createdAt } : {}),
6872 };
6973 } catch {
7074 return undefined;
@@ -644,7 +648,7 @@ export async function answerFromCell(parent: App, request: Request, named?: stri
644648 const starting = settleCell(parent, ledger);
645649 // Only so many wait on one cell: the rest are told it is waking at once, so a crowd cannot pin connections and bodies.
646650 const waiting = waiters.get(ledger.bodyId) ?? 0;
647 if (waiting >= wakeLimits.waiters) return wakingResponse(parent, request, ledger.name);
651 if (waiting >= wakeLimits.waiters) return wakingResponse(parent, request, ledger.name, undefined, 5, ledger.createdAt);
648652 waiters.set(ledger.bodyId, waiting + 1);
649653 let woke: CellChild | undefined;
650654 try {
@@ -662,7 +666,7 @@ export async function answerFromCell(parent: App, request: Request, named?: stri
662666 release();
663667 }
664668 }
665 return wakingResponse(parent, request, ledger.name);
669 return wakingResponse(parent, request, ledger.name, undefined, 5, ledger.createdAt);
666670 }
667671
668672 /** How long a request waits for a sleeping cell forge before it is told it is waking, and how many may wait on one cell. */
src/spawn/name_state.ts added +53
@@ -0,0 +1,53 @@
1 /**
2 * Whether a forge name is free, in words (#11153): one answer for the home
3 * page's live line, its post and the terminal's start screen. A stat call and
4 * a lookup of reserved words; never a spawn.
5 */
6
7 import type { App } from "../app.ts";
8 import { ledgerPath } from "../actions/spawn.ts";
9 import { reservedName } from "../core/reserved.ts";
10 import { NAME } from "./plan.ts";
11
12 /** What a name is: free or not, the sentence to say, and the near name to offer when it is taken. */
13 export interface NameState {
14 readonly free: boolean;
15 readonly message: string;
16 readonly suggest?: string;
17 }
18
19 /** A name as typed: trimmed, lowercased, bounded. */
20 export const cleanName = (raw: string): string => raw.slice(0, 80).trim().toLowerCase();
21
22 /** Whether a name is held: an existing forge, or a word the forge keeps (its own, the crew's, the owner's). */
23 async function held(app: App, name: string): Promise<boolean> {
24 return reservedName(app.db, name) !== undefined || (await Bun.file(ledgerPath(app, name)).exists());
25 }
26
27 /** Whether a made forge of this name has a ledger: the only names the ready probe is asked about. */
28 export const isMade = (app: App, name: string): Promise<boolean> =>
29 NAME.test(name) ? Bun.file(ledgerPath(app, name)).exists() : Promise.resolve(false);
30
31 async function suggestion(app: App, name: string): Promise<string | undefined> {
32 for (const tail of ["-forge", "-2", "-3", "-app"]) {
33 const next = `${name.slice(0, 39 - tail.length)}${tail}`;
34 if (NAME.test(next) && !(await held(app, next))) return next;
35 }
36 return undefined;
37 }
38
39 export async function nameState(app: App, raw: string): Promise<NameState> {
40 const name = cleanName(raw);
41 if (name === "") return { free: false, message: "" };
42 if (!NAME.test(name))
43 return { free: false, message: "Use 1 to 39 lowercase letters, digits and dashes, not starting or ending with a dash." };
44 if (await held(app, name)) {
45 const suggest = await suggestion(app, name);
46 return {
47 free: false,
48 message: `${name} is taken.${suggest === undefined ? " Pick another name." : ` Try ${suggest}.`}`,
49 ...(suggest === undefined ? {} : { suggest }),
50 };
51 }
52 return { free: true, message: `${name} is free.` };
53 }
src/spawn/plan.ts +1 −1
@@ -34,7 +34,7 @@ export const MAX_BUDGET_USD = 1000;
3434
3535 /** One line saying what a fresh app is. */
3636 export const MAX_FRESH_CHARS = 200;
37 const NAME = /^[a-z0-9](?:[a-z0-9-]{0,37}[a-z0-9])?$/;
37 export const NAME = /^[a-z0-9](?:[a-z0-9-]{0,37}[a-z0-9])?$/;
3838 const PLAN_KEY = /^[a-z][a-z0-9-]{0,19}$/;
3939 const APP_REF = /^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/;
4040
src/tui/screens/entries.ts +2
@@ -15,6 +15,7 @@ import { entry as archived } from "./archived.ts";
1515 import { entry as audit } from "./audit.ts";
1616 import { entry as appTemplates } from "./app_templates.ts";
1717 import { entry as dotfiles } from "./dotfiles.ts";
18 import { entry as startForge } from "./start_forge.ts";
1819 import { entry as devices } from "./devices.ts";
1920 import { entry as bets } from "./bets.ts";
2021 import { entry as billing } from "./billing.ts";
@@ -172,6 +173,7 @@ export const ENTRIES: readonly PaletteEntry[] = [
172173 originAhead,
173174 profile,
174175 dotfiles,
176 startForge,
175177 now,
176178 frontMilestones,
177179 forgeView,
src/tui/screens/start_forge.ts added +88
@@ -0,0 +1,88 @@
1 /**
2 * "Start my forge" in the terminal (#11153): the home page's one field. `n`
3 * asks for a name, says at once if it is taken (the page's live line, from
4 * `nameState`), and a free one goes through `spawnDoor` as the page and
5 * `POST /api/v1/forges` do: the same plan, the same limits. The claim link
6 * is then shown once and kept nowhere. The full form, with its extras, is
7 * the New forge screen.
8 */
9 import { spawnDoor } from "../../spawn/door.ts";
10 import { cleanName, nameState } from "../../spawn/name_state.ts";
11 import type { Ctx, Screen } from "../app/app.ts";
12 import { binding } from "../app/keys.ts";
13 import type { Session } from "../session.ts";
14 import { style } from "../term/style.ts";
15 import { truncate } from "../term/width.ts";
16 import { linkScreen, promptScreen } from "./common.ts";
17 import type { PaletteEntry } from "./entries.ts";
18
19 export function startForgeScreen(f: Session, ctx: Ctx): Screen {
20 let note = "n names your forge. Its claim link is shown once.";
21 let busy = false;
22 let last = "";
23
24 const start = async (typed: string): Promise<void> => {
25 const name = cleanName(typed);
26 const url = new URL(f.app.config.url ?? `http://${f.app.config.host ?? "localhost"}`);
27 const made = await spawnDoor(
28 { app: f.app, request: new Request(url.href, { method: "POST" }), url, params: {}, auth: { user: f.user, scope: undefined, via: "none" as const }, theme: undefined },
29 f.user,
30 { name, dryRun: false },
31 );
32 const link = made.body["claimUrl"];
33 if (made.status < 400 && typeof link === "string") {
34 note = `${name} is ready.`;
35 ctx.toast(`${name} is ready`, "success");
36 ctx.push(linkScreen(ctx, link));
37 } else {
38 note = String(made.body["message"] ?? "Your forge could not be made just now.");
39 ctx.toast(note, "danger");
40 }
41 };
42
43 // The prompt closes as it submits, so a name that is not free is said on this screen and `n` reopens the prompt with it.
44 const offer = (typed: string): string | undefined | Promise<void> => {
45 if (busy) return "Still starting the last one.";
46 if (cleanName(typed) === "") return "Type a name.";
47 last = typed;
48 busy = true;
49 return (async () => {
50 try {
51 const state = await nameState(f.app, typed);
52 if (state.free) await start(typed);
53 else {
54 note = state.message;
55 ctx.toast(state.message, "attn");
56 }
57 } finally {
58 busy = false;
59 ctx.invalidate();
60 }
61 })();
62 };
63
64 const screen: Screen = {
65 title: "Start my forge",
66 keys: [binding(["n"], "name your forge")],
67 render(area, s) {
68 const c = ctx.theme.c;
69 s.text(area.x, area.y, truncate(note, area.w), style(c.mutedFg, c.bg), area.x + area.w);
70 },
71 key(e) {
72 if (e.ctrl || e.alt || e.key !== "n") return false;
73 ctx.push(promptScreen(ctx, screen, { title: "Name your forge", label: "lowercase letters, digits and dashes", value: last, onSubmit: offer }));
74 return true;
75 },
76 };
77 return screen;
78 }
79
80 /** A person's, as the page is: any signed-in person starts a forge; an agent does not. */
81 export const entry: PaletteEntry = {
82 id: "start-forge",
83 title: "Start my forge",
84 hint: "name a forge and get its claim link",
85 after: ["new-forge", "forges"],
86 offered: (session) => session.user?.kind === "user",
87 run: (session, ctx) => ctx.push(startForgeScreen(session, ctx)),
88 };
src/web/pages/agents.ts +1 −1
@@ -70,7 +70,7 @@ export function agentsPage(ctx: Ctx): Response {
7070 description:
7171 "What this forge is and how an AI assistant can help you use it: build one of its public apps, report a problem, or get a forge of your own.",
7272 body: html`${pageHead("For AI assistants", {
73 sub: html`What this forge is. Plain text: <a href="/llms.txt">/llms.txt</a>`,
73 sub: html`<a href="/llms.txt">/llms.txt</a>. People: <a href="/#start">start here</a>.`,
7474 })}
7575 <section class="stack" aria-labelledby="agent-forge-h">
7676 <h2 id="agent-forge-h">Get a forge of your own</h2>
src/web/pages/next-steps.ts +5
@@ -108,3 +108,8 @@ export function nextStepsOf(
108108 ): Promise<readonly NextStep[] | undefined> {
109109 return nextStepsFor(ctx.app, user);
110110 }
111
112 /** A spawned forge's first screen, before its crew has anything to show: the two ways to begin, as the home's door links (#11153). */
113 export function nextLine(): Html {
114 return html`<p class="home-doors" id="next-line"><a href="/apps/new">Make an app</a> <a href="/migrate">Bring your code</a></p>`;
115 }
src/web/pages/start.ts added +184
@@ -0,0 +1,184 @@
1 /**

Both doors: nothing in src/tui/ starts a forge, and there is no docs/features/ how-to.

2 * "Start my forge" (#11153): the home page's one field and one button for a
3 * stranger. The name is checked as it is typed (`GET /start/check`), the post
4 * goes through the same door as `/forges/new` and the API (`spawnDoor`: the
5 * free plan, the visitor's rate limits), and the answer is one hop to the new
6 * forge's claim page, where the person chooses a username and a password and
7 * is signed in. The claim code rides the link's fragment, so nobody copies it.
8 *
9 * The hop is a page with a link and one line of script, not a 303: the page's
10 * `form-action 'self'` stops a browser following a form post to another origin.
11 * A refusal is said on the home page itself, above the same form.
12 */
13
14 import { childUrlOf, noRoom, probeFor, spawnDoor } from "../../spawn/door.ts";
15 import { cleanName, isMade, nameState } from "../../spawn/name_state.ts";
16 import type { Ctx } from "../../http/context.ts";
17 import { clientBucket } from "../../http/peer.ts";
18 import { json } from "../../http/respond.ts";
19 import { strangerWindow } from "../../http/stranger_window.ts";
20 import { field, readForm } from "../form.ts";
21 import { html, type Html } from "../html.ts";
22 import { page, redirect } from "../layout.ts";
23 import { btn, field as formField } from "../ui.ts";
24 import { pageHead } from "../chrome.ts";
25
26 /** Asks per address per minute: a person typing or waiting stays far under; a script does not. */
27 export const CHECKS_PER_MINUTE = 60;
28 export const READY_PER_MINUTE = 90;
29 /** Probes of children in flight at once, from everyone: a crowd waiting cannot become a crowd of connections. */
30 export const READY_PROBES = 4;
31 let probing = 0;
32
33 const slowDown = (wait: number): Response =>
34 json({ error: "rate_limited", message: "Slow down a little." }, 429, { "cache-control": "no-store", "retry-after": String(wait) });
35
36 // GET /start/ready?name= — whether the new forge's health answers. Only a
37 // name this forge made is asked about, at the address it derives itself.
38 export async function startReady(ctx: Ctx): Promise<Response> {
39 const wait = strangerWindow(`ready:${clientBucket(ctx.request)}`, READY_PER_MINUTE);
40 if (wait !== undefined) return slowDown(wait);
41 const name = cleanName(ctx.url.searchParams.get("name") ?? "");
42 let ready = false;
43 // Over the cap the answer is "not yet", and the page asks again.
44 if (probing < READY_PROBES && (await isMade(ctx.app, name))) {
45 probing += 1;
46 try {
47 ready = await probeFor(ctx.app, childUrlOf(ctx.app, name))();
48 } finally {
49 probing -= 1;
50 }
51 }
52 return json({ ready }, 200, { "cache-control": "no-store" });
53 }
54
55 // GET /start/check?name= — a stat call, never a spawn.
56 export async function startCheck(ctx: Ctx): Promise<Response> {
57 const wait = strangerWindow(`check:${clientBucket(ctx.request)}`, CHECKS_PER_MINUTE);
58 if (wait !== undefined) return slowDown(wait);
59 const state = await nameState(ctx.app, ctx.url.searchParams.get("name") ?? "");
60 return json(state, 200, { "cache-control": "no-store" });
61 }
62
63 /** The field, its live line and the one button. `error` is a refusal to say again. */
64 export function startForm(ctx: Ctx, values: { name?: string; error?: string } = {}): Html {
65 return html`<form method="post" action="/start" class="stack-tight door-start" id="start">
66 ${formField({
67 label: "Name your forge",
outdated

Unauthenticated, unthrottled probe of a child's address on every call. Rate limit by socket address.

68 name: "name",
69 id: "start-name",
70 value: values.name ?? "",
71 required: true,
72 spellcheck: false,
73 })}
74 <p class="small" id="start-status" role="status" aria-live="polite"></p>
75 ${values.error === undefined ? null : html`<p class="error" id="start-error" role="alert">${values.error}</p>`}
76 ${btn("Start my forge", { variant: "primary", size: "lg" })}
outdated

Unthrottled disk stats per keystroke from any stranger; rate limit by socket address.

77 </form>`;
78 }
79
80 /** The live check: waits for a pause in typing, then says free or taken. */
81 export const startJs = /* js */ `
82 (function () {
outdated

Design P1: the hint, the label and the status line say the same thing three ways; keep one.

83 var input = document.getElementById('start-name');
84 var out = document.getElementById('start-status');
85 if (!input || !out || !window.fetch) return;
86 var timer = 0, seq = 0;
87 input.setAttribute('autocomplete', 'off');
88 input.setAttribute('autocapitalize', 'none');
89 input.addEventListener('input', function () {
90 clearTimeout(timer);
91 var at = input.selectionStart;
92 var lower = input.value.toLowerCase();
93 if (lower !== input.value) { input.value = lower; try { input.setSelectionRange(at, at); } catch (e) {} }
94 var mine = ++seq, value = input.value;
95 if (!value.trim()) { out.textContent = ''; return; }
96 timer = setTimeout(function () {
97 fetch('/start/check?name=' + encodeURIComponent(value), { credentials: 'omit' })
98 .then(function (r) { return r.ok ? r.json() : null; })
99 .then(function (s) {
100 if (!s || mine !== seq) return;
101 out.textContent = s.message;
102 out.className = 'small ' + (s.free ? 'muted' : 'error');
103 })
104 .catch(function () {});
105 }, 250);
106 });
107 })();
108 `;
109
110 /** Holds the person here until the new forge answers, then goes: bounded, and honest when it never does. */
111 export const waitJs = /* js */ `
112 (function () {
113 var box = document.getElementById('setup');
114 if (!box || !window.fetch) return;
115 var name = box.dataset.name, claim = box.dataset.claim;
116 var until = Date.now() + 120000, wait = 1000;
117 function late() {
118 document.getElementById('setup-status').textContent = 'Setting up ' + name + ' has not finished.';
119 document.getElementById('setup-late').hidden = false;
120 }
121 function ask() {
122 if (Date.now() > until) return late();
123 fetch('/start/ready?name=' + encodeURIComponent(name), { credentials: 'omit' })
124 .then(function (r) { return r.json(); })
125 .then(function (s) { if (s.ready) location.replace(claim); else setTimeout(ask, wait = Math.min(wait + 500, 3000)); })
126 .catch(function () { setTimeout(ask, 3000); });
127 }
128 ask();
129 })();
130 `;
131
132 /** What to do next, per refusal: never a bare error. */
133 function refusal(status: number, message: string): string {
134 if (status === 429)
135 return `${message}. Wait a little and press the button again, or run your own forge from the steps further down.`;
136 if (status === 422) return `${message.replace(/^(name|org): /, "")}. Pick another name.`;
137 if (status === 409 && /exists|already/.test(message)) return `That name is taken. Pick another name.`;
138 if (status === 409) return `${message}. Try again in a little while, or run your own forge from the steps further down.`;
139 return "Your forge could not be made just now. Try again in a minute, or run your own forge from the steps further down.";
140 }
141
142 /** The home page again, as the refusal's status: 429 stays, everything else is the person's to fix (422). */
143 const refused = (res: Response, status: number): Response =>
144 new Response(res.body, { status: status === 429 ? 429 : 422, headers: res.headers });
145
146 // POST /start
147 export async function startSubmit(
148 ctx: Ctx,
149 /** The home page again, with the refusal above its form. */
150 again: (ctx: Ctx, start: { name: string; error: string }) => Response,
151 ): Promise<Response> {
152 const form = await readForm(ctx, undefined);
153 if (form instanceof Response) return form;
154 const name = cleanName(field(form, "name"));
155 // A signed-in person has the full form, with their own claim link to send.
156 if (ctx.auth.user !== undefined)
157 return redirect(`/forges/new?name=${encodeURIComponent(name.slice(0, 38))}`, { url: ctx.url, forgeUrl: ctx.app.config.url });
158 const full = noRoom(ctx.app);
159 if (full !== undefined) return refused(again(ctx, { name, error: refusal(409, `This forge has no room for another forge right now (${full})`) }), 409);
160 const state = await nameState(ctx.app, name);
161 if (!state.free && state.message !== "" && /is taken/.test(state.message))
162 return refused(again(ctx, { name, error: state.message }), 422);
163 const door = await spawnDoor(ctx, undefined, { name, dryRun: false });
164 const claim = door.body["claimUrl"];
165 if (door.status < 400 && typeof claim === "string") {
166 const response = page({
167 ctx,
168 title: `Setting up ${name}`,
169 body: html`<div class="narrow stack" id="setup" data-name="${name}" data-claim="${claim}">
170 ${pageHead(`Setting up ${name}`)}
171 <p role="status" aria-live="polite" id="setup-status">Setting up ${name}…</p>
172 <p id="setup-late" hidden>${name} is taking longer than it should. It may still come up:
173 ${btn("Open it anyway", { href: claim, variant: "primary", size: "lg" })}</p>
174 <noscript><p>${btn("Open my forge", { href: claim, variant: "primary", size: "lg" })}</p></noscript>
175 </div>`,
176 scriptJs: waitJs,
177 });
178 response.headers.set("cache-control", "no-store");
179 return response;
180 }
181 const status = door.status < 400 ? 409 : door.status;
182 const message = door.status < 400 ? "exists: already" : String(door.body["message"] ?? "");
183 return refused(again(ctx, { name, error: refusal(status, message) }), status);
184 }
src/web/pages/waking.ts +13 −5
@@ -12,21 +12,29 @@ import { btn, empty } from "../ui.ts";
1212 import { html } from "../html.ts";
1313 import { page } from "../layout.ts";
1414
15 /** Waking (`why` undefined, 503) or refused (`why` a sentence, 429), as a page when the visitor asks for HTML. */
16 export function wakingResponse(app: App, request: Request, name: string, why?: string, retryS = 5): Response {
15 /** A forge made in the last ten minutes was never asleep: it is being set up. */
16 const NEW_MS = 10 * 60_000;
17 const isNew = (madeAt: string | undefined): boolean => madeAt !== undefined && Date.now() - Date.parse(madeAt) < NEW_MS;
18
19 /**
20 * Waking (`why` undefined, 503; `madeAt` is when the ledger the caller holds says it was made)
21 * or refused (`why` a sentence, 429), as a page when the visitor asks for HTML.
22 */
23 export function wakingResponse(app: App, request: Request, name: string, why?: string, retryS = 5, madeAt?: string): Response {
1724 if (!(request.headers.get("accept") ?? "").includes("text/html")) return wakingText(name, why, retryS);
1825 const url = new URL(request.url);
26 const fresh = why === undefined && isNew(madeAt);
1927 const ctx: Ctx = { app, request, url, params: {}, auth: { user: undefined, scope: undefined, via: "none" }, theme: undefined };
2028 const response = page(
2129 {
2230 ctx,
2331 bare: true,
24 title: why === undefined ? "Waking up" : "Not now",
32 title: why !== undefined ? "Not now" : fresh ? "Setting up" : "Waking up",
2533 body: html`<div class="narrow-wide">
2634 ${empty({
2735 icon: "history",
28 title: why === undefined ? "Waking up" : "Not now",
29 note: why ?? `${name} was asleep. It is waking up and this page tries again by itself in a few seconds.`,
36 title: why !== undefined ? "Not now" : fresh ? "Setting up" : "Waking up",
37 note: why ?? (fresh ? `${name} is being set up and this page tries again by itself in a few seconds.` : `${name} was asleep. It is waking up and this page tries again by itself in a few seconds.`),
3038 action: btn("Try again", { href: url.pathname, variant: "primary" }),
3139 })}
3240 </div>`,
src/web/studio/home.ts +12 −10
@@ -86,10 +86,11 @@ import { sinceYouWere } from "./since.ts";
8686 import { homeTabs, unshippedAsks } from "./home_tabs.ts";
8787 import { crewKeyCard } from "./crew_key.ts";
8888 import { everydayCard } from "../pages/everyday.ts";
89 import { nextStepsCard, nextStepsOf } from "../pages/next-steps.ts";
89 import { nextLine, nextStepsCard, nextStepsOf } from "../pages/next-steps.ts";
9090 import { spawnedOrg } from "../../spawn/claim.ts";
9191 import { clientApps } from "./client_home.ts";
9292 import { passkeyJs } from "../passkey-client.ts";
93 import { startForm, startJs } from "../pages/start.ts";
9394
9495 /** The events that can change what is on you. */
9596 const ON_YOU_LIVE =
@@ -320,7 +321,7 @@ export async function studioHome(
320321 ) {
321322 const apps = await clientApps(ctx, user);
322323 const lean = html`<h1 class="sr-only">Home</h1>
323 ${firstSteps} ${address} ${crewKeyCard(ctx)} ${heldLine(ctx, user)} ${apps}
324 ${spawned === undefined ? null : nextLine()} ${firstSteps} ${address} ${crewKeyCard(ctx)} ${heldLine(ctx, user)} ${apps}
324325 <div class="stack">
325326 ${composer(ctx, user)}
326327 <p class="small muted">
@@ -751,7 +752,7 @@ function agentPrompt(origin: string): string {
751752 * `/front` is the same page for anyone; a site admin there also gets the
752753 * controls that decide it.
753754 */
754 export function studioDoor(ctx: Ctx): Response {
755 export function studioDoor(ctx: Ctx, start?: { name: string; error: string }): Response {
755756 // The door draws what is in memory; a pack pushed since is picked up for the next visit.
756757 void refreshCatalogQuietly(ctx.app, 5_000);
757758 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
@@ -776,7 +777,8 @@ export function studioDoor(ctx: Ctx): Response {
776777 const back = ctx.url.pathname === "/" ? "/" + ctx.url.search : "/";
777778 const nextQuery = back === "/" ? "" : `?next=${encodeURIComponent(back)}`;
778779 const ssh = sshCommand(ctx.app);
779 const signup = offersSignup(ctx) && accounts;
780 const offers = offersSignup(ctx);
781 const signup = offers && accounts;
780782 // Closed is a door with nothing behind it; invite still lands an invite link's holder.
781783 const origin = (ctx.app.config.url ?? ctx.url.origin).replace(/\/$/, "");
782784 const prompt = agentPrompt(origin);
@@ -786,11 +788,11 @@ export function studioDoor(ctx: Ctx): Response {
786788 <h1>Software for what you're building.<br /><span class="muted">Yours to keep.</span></h1>
787789 <div class="door-under">
788790 <div class="door-lead">
789 <p class="door-support">Say what you need. An AI crew builds it, for a business or a game studio.</p>
790 <div class="bar">
791 ${btn("Get your own forge", { href: "#yours", variant: "primary", size: "lg" })}
792 ${when(made.length > 0, () => btn("See what it built", { href: "#made", size: "lg" }))}
793 </div>
791 <p class="door-support">Your own forge, free to try: say what you need and an AI crew builds it.</p>
792 ${offers
793 ? startForm(ctx, start)
794 : btn("Get your own forge", { href: "#yours", variant: "primary", size: "lg" })}
795 ${when(made.length > 0, () => html`<p class="small"><a href="#made">See what it built</a></p>`)}
794796 <div class="door-agent">
795797 <p>
796798 Have an AI assistant? Give it this:
@@ -911,7 +913,7 @@ bun run src/main.ts</code></pre>
911913 title: "forge: software for what you're building, yours to keep",
912914 description: "Your own forge, with a private AI crew that builds your apps, games and business tools. Open source, and yours to keep.",
913915 body,
914 scriptJs: `${liveClientJs}\n${liveRegionsJs}`,
916 scriptJs: `${liveClientJs}\n${liveRegionsJs}\n${startJs}`,
915917 jsonLd: siteStructuredData(origin, running().version),
916918 ...(visitor
917919 ? {
test/forge-looks.test.ts +1
@@ -47,6 +47,7 @@ const NOT_A_PAGE: Record<string, string> = {
4747 "/first-admin": "the setup form for a forge with no admin yet",
4848 "/signin": "a sign-in form, not a page of the forge",
4949 "/signup": "a sign-up form, not a page of the forge",
50 "/start": "the start-a-forge form, a POST door; covered by test/start-forge.test.ts",
5051 "/recover": "an account-recovery form, not a page of the forge",
5152 "/verify": "answers 400 without the emailed code",
5253 "/logout": "a mutation, answers 404 to a GET",
test/palette-roster.test.ts +2
@@ -83,6 +83,7 @@ test("a site-admin person is offered the whole roster", () => {
8383 ["new-org", "New organization", "an organization you own, for a client's apps"],
8484 ["migrate", "Migrate a repository", "bring one in from an origin or a URL, pick its branch, put a crew on it"],
8585 ["new-forge", "New forge", "spawn a client's forge and get its claim link"],
86 ["start-forge", "Start my forge", "name a forge and get its claim link"],
8687 ["asked", "Asked", "your thoughts and what became of them"],
8788 ["thought-notes", "Notes", "write an idea and watch it become shipped work"],
8889 ["decider", "Decider", "what it closed, deferred and asked you about today"],
@@ -310,6 +311,7 @@ test("a member person is offered the signed-in roster without the admin entries"
310311 ["new-org", "New organization", "an organization you own, for a client's apps"],
311312 ["migrate", "Migrate a repository", "bring one in from an origin or a URL, pick its branch, put a crew on it"],
312313 ["new-forge", "New forge", "spawn a client's forge and get its claim link"],
314 ["start-forge", "Start my forge", "name a forge and get its claim link"],
313315 ["asked", "Asked", "your thoughts and what became of them"],
314316 ["thought-notes", "Notes", "write an idea and watch it become shipped work"],
315317 ["decider", "Decider", "what it closed, deferred and asked you about today"],
test/start-forge.test.ts added +240
@@ -0,0 +1,240 @@
1 /**
2 * "Start my forge" (#11153): the home page of a stranger carries the one
3 * field and the one button; the name is checked live; the post makes a forge
4 * through the spawn door and hands the person to its claim page; a refusal is
5 * said on the home page. A new forge with no crew credit says its two ways forward.
6 */
7 import { afterAll, beforeAll, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp } from "../src/app.ts";
12 import { createUser } from "../src/core/users.ts";
13 import { createSession } from "../src/core/sessions.ts";
14 import { serve } from "../src/http/server.ts";
15 import { usePlacement, useProbe } from "../src/spawn/door.ts";
16 import { bootHostedChild } from "../src/spawn/host.ts";
17 import { ok } from "../src/kernel/result.ts";
18 import { resetStrangerWindows } from "../src/http/stranger_window.ts";
19 import { CHECKS_PER_MINUTE, READY_PER_MINUTE, READY_PROBES } from "../src/web/pages/start.ts";
20 import { quietLogs } from "./helpers/globals.ts";
21
22 quietLogs();
23
24 let dir = "";
25 let app: ReturnType<typeof createApp>;
26 let servers: Awaited<ReturnType<typeof serve>>;
27 let roomLeft = true;
28 const spawned: string[] = [];
29
30 beforeAll(async () => {
31 dir = await mkdtemp(join(tmpdir(), "forge-start-"));
32 app = createApp({ dataDir: dir, port: 0 });
33 useProbe(app, () => async () => true);
34 usePlacement(app, {
35 place: async (plan: { name: string }) => ok({ url: `https://${plan.name}.fake.test`, bodyId: `fake-${plan.name}` }),
36 retire: async () => ok(),
37 room: () => (roomLeft ? undefined : { message: "the test host is full" }),
38 } as never);
39 servers = await serve(app);
40 });
41 afterAll(async () => {
42 for (const name of spawned) await bootHostedChild(app, name);
43 servers.stop();
44 app.close();
45 await rm(dir, { recursive: true, force: true });
46 });
47
48 const post = (name: string, headers: Record<string, string> = {}) =>
49 fetch(servers.url + "/start", {
50 method: "POST",
51 redirect: "manual",
52 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url, ...headers },
53 body: new URLSearchParams({ name }),
54 });
55
56 test("a stranger's home has a labelled field and one Start my forge button", async () => {
57 const home = await (await fetch(servers.url + "/")).text();
58 expect(home).toContain('action="/start"');
59 expect(home).toMatch(/<label[^>]*for="start-name"[^>]*>\s*Name your forge/);
60 expect(home).toContain("Start my forge");
61 expect(home).toContain("free to try");
62 // The form asks for the name only.
63 const form = home.slice(home.indexOf('id="start"'), home.indexOf("</form>", home.indexOf('id="start"')));
64 expect(form.match(/<input/g)?.length).toBe(1);
65 });
66
67 test("the live check says free, taken, and what a bad name needs", async () => {
68 const say = async (n: string) => (await (await fetch(`${servers.url}/start/check?name=${encodeURIComponent(n)}`)).json()) as { free: boolean; message: string };
69 expect(await say("Fresh-One")).toMatchObject({ free: true, message: "fresh-one is free." });
70 expect((await say("-bad")).free).toBe(false);
71 expect((await say("")).message).toBe("");
72 const made = await post("taken-one");
73 expect(made.status).toBe(200);
74 spawned.push("taken-one");
75 expect(await say("taken-one")).toMatchObject({ free: false });
76 });
77
78 test("the post makes the forge and hands over its claim link, once, uncached", async () => {
79 const res = await post("hello-forge");
80 spawned.push("hello-forge");
81 expect(res.status).toBe(200);
82 expect(res.headers.get("cache-control")).toBe("no-store");
83 const page = await res.text();
84 expect(page).toMatch(/href="https?:\/\/hello-forge--[^"]*\/claim#[A-Za-z0-9_-]{43}"/);
85 // The person waits here until the new forge's health answers, then goes.
86 expect(page).toContain("Setting up hello-forge…");
87 expect(page).toContain('id="setup" data-name="hello-forge"');
88 expect(page).not.toContain("is ready");
89 const ready = (await (await fetch(`${servers.url}/start/ready?name=hello-forge`)).json()) as { ready: boolean };
90 expect(ready.ready).toBe(true);
91 // Only a forge this one made is asked about.
92 expect(((await (await fetch(`${servers.url}/start/ready?name=nobody-here`)).json()) as { ready: boolean }).ready).toBe(false);
93 });
94
95 test("a forge that does not answer yet is not ready", async () => {
96 useProbe(app, () => async () => false);
97 const said = (await (await fetch(`${servers.url}/start/ready?name=hello-forge`)).json()) as { ready: boolean };
98 useProbe(app, () => async () => true);
99 expect(said.ready).toBe(false);
100 });
101
102 test("reserved and existing names read taken with one suggestion", async () => {
103 const say = async (n: string) => (await (await fetch(`${servers.url}/start/check?name=${n}`)).json()) as { free: boolean; message: string };
104 const forge = await say("forge");
105 expect(forge.free).toBe(false);
106 expect(forge.message).toMatch(/^forge is taken\. Try [a-z0-9-]+\.$/);
107 const refused = await post("forge");
108 expect(refused.status).toBe(422);
109 expect(await refused.text()).toContain("forge is taken.");
110 expect(await Bun.file(join(dir, "spawn", "forge.json")).exists()).toBe(false);
111 });
112
113 test("the first view is the sentence, the field and one button; the assistant links are plain links in the hero", async () => {
114 const home = await (await fetch(servers.url + "/")).text();
115 const hero = home.slice(home.indexOf('class="door-hero"'), home.indexOf('id="made"'));
116 // No section of its own for the assistant: the hero holds it, as links.
117 expect(home).not.toContain('id="assistant"');
118 expect(hero).toMatch(/<a [^>]*href="https:\/\/chatgpt\.com\/\?q=[^"]*"[^>]*>Open in ChatGPT<\/a>/);
119 expect(hero).toContain("Copy the message");
120 // One primary button for the start, and the header does not repeat it.
121 expect(hero.match(/Start my forge/g)?.length).toBe(1);
122 expect(home.match(/Start my forge/g)?.length).toBe(1);
123 expect(home).not.toContain('href="#start"');
124 // One explanation of the field: the label, and the live line under it. No address hint.
125 expect(home).not.toContain("Its address:");
126 expect(home).not.toContain("data-address");
127 expect(home).not.toContain("&lt;name&gt;");
128 });
129
130 test("a forge made minutes ago is being set up, not waking; the caller's ledger says so, no file is read", async () => {
131 const { wakingResponse } = await import("../src/web/pages/waking.ts");
132 const html = (madeAt?: string) =>
133 wakingResponse(app, new Request(servers.url + "/", { headers: { accept: "text/html" } }), "hello-forge", undefined, 5, madeAt).text();
134 const fresh = await html(new Date().toISOString());
135 expect(fresh).toContain("being set up");
136 expect(fresh).not.toContain("was asleep");
137 expect(await html(new Date(Date.now() - 3_600_000).toISOString())).toContain("was asleep");
138 expect(await html()).toContain("was asleep");
139 });
140
141 test("the next line of a spawned forge names the two ways to begin, as links", async () => {
142 const { nextLine } = await import("../src/web/pages/next-steps.ts");
143 const line = nextLine().toString();
144 expect(line).toContain('href="/apps/new"');
145 expect(line).toContain('href="/migrate"');
146 expect(line).not.toContain("<b>");
147 });
148
149 test("a taken name is said on the home page with what to do", async () => {
150 const res = await post("taken-one");
151 expect(res.status).toBe(422);
152 const page = await res.text();
153 expect(page).toContain('id="start-error"');
154 expect(page).toContain("taken-one is taken. Try ");
155 expect(page).toContain('value="taken-one"');
156 expect(page).not.toContain("/claim#");
157 });
158
159 test("a bad name and no room are said in words, never a dead end", async () => {
160 expect(await (await post("Bad_Name!")).text()).toContain("Pick another name.");
161 roomLeft = false;
162 const full = await post("no-room-yet");
163 roomLeft = true;
164 expect(full.status).toBe(422);
165 expect(await full.text()).toContain("run your own forge");
166 });
167
168 test("a post from another origin is refused", async () => {
169 const res = await post("evil-one", { origin: "https://evil.example" });
170 expect(res.status).toBeGreaterThanOrEqual(400);
171 expect(await Bun.file(join(dir, "spawn", "evil-one.json")).exists()).toBe(false);
172 });
173
174 test("the strangers' rate limit shows as a refusal on the home page", async () => {
175 let last: Response | undefined;
176 for (let i = 0; i < 30; i++) {
177 last = await post(`rate-${i}`);
178 spawned.push(`rate-${i}`);
179 if (last.status === 429) break;
180 }
181 expect(last?.status).toBe(429);
182 expect(await last!.text()).toContain("Wait a little");
183 });
184
185 test("a signed-in person is sent to the full form with the name", async () => {
186 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
187 if (!made.ok) throw new Error(made.error);
188 const session = createSession(app.db, made.value.id);
189 const res = await post("mine-now", { cookie: `forge_session=${typeof session === "string" ? session : (session as { token: string }).token}` });
190 expect(res.status).toBe(303);
191 expect(res.headers.get("location")).toBe("/forges/new?name=mine-now");
192 expect(await Bun.file(join(dir, "spawn", "mine-now.json")).exists()).toBe(false);
193 });
194
195 test("the live check and the ready probe are limited by the socket address", async () => {
196 resetStrangerWindows();
197 let refused: Response | undefined;
198 for (let i = 0; i < CHECKS_PER_MINUTE + 2 && refused === undefined; i++) {
199 const r = await fetch(`${servers.url}/start/check?name=probe-${i}`);
200 if (r.status === 429) refused = r;
201 }
202 expect(refused?.status).toBe(429);
203 expect(Number(refused!.headers.get("retry-after"))).toBeGreaterThan(0);
204 expect(refused!.headers.get("cache-control")).toBe("no-store");
205 // A different request kind has its own count, and the window lets a quiet client through again.
206 expect((await fetch(`${servers.url}/start/ready?name=nobody-here`)).status).toBe(200);
207 resetStrangerWindows();
208 expect((await fetch(`${servers.url}/start/check?name=probe-again`)).status).toBe(200);
209 let slow: Response | undefined;
210 for (let i = 0; i < READY_PER_MINUTE + 2 && slow === undefined; i++) {
211 const r = await fetch(`${servers.url}/start/ready?name=nobody-here`);
212 if (r.status === 429) slow = r;
213 }
214 expect(slow?.status).toBe(429);
215 resetStrangerWindows();
216 });
217
218 test("at most READY_PROBES children are probed at once; the rest are told not yet", async () => {
219 let open = 0;
220 let most = 0;
221 const release: Array<() => void> = [];
222 useProbe(app, () => async () => {
223 open += 1;
224 most = Math.max(most, open);
225 await new Promise<void>((done) => release.push(done));
226 open -= 1;
227 return true;
228 });
229 resetStrangerWindows();
230 const asks = Array.from({ length: READY_PROBES + 3 }, () => fetch(`${servers.url}/start/ready?name=hello-forge`));
231 while (release.length < READY_PROBES) await Bun.sleep(10);
232 await Bun.sleep(50);
233 expect(most).toBe(READY_PROBES);
234 release.splice(0).forEach((done) => done());
235 const answers = (await Promise.all(asks.map((r) => r.then((x) => x.json())))) as Array<{ ready: boolean }>;
236 while (release.length > 0) release.splice(0).forEach((done) => done());
237 useProbe(app, () => async () => true);
238 expect(answers.filter((a) => a.ready).length).toBe(READY_PROBES);
239 expect(answers.filter((a) => !a.ready).length).toBe(3);
240 });
test/tui-start-forge.test.ts added +70
@@ -0,0 +1,70 @@
1 /** "Start my forge" in the terminal (#11153): a name is checked, a free one makes a forge and shows its link; an agent is not offered it. */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App as Forge } from "../src/app.ts";
7 import { createUser, getUserByName } from "../src/core/users.ts";
8 import { ok } from "../src/kernel/result.ts";
9 import { usePlacement, useProbe } from "../src/spawn/door.ts";
10 import { createForgeApp } from "../src/tui/forge.ts";
11 import { entry } from "../src/tui/screens/start_forge.ts";
12 import { Session } from "../src/tui/session.ts";
13 import { headlessTerminal } from "../src/tui/term/terminal.ts";
14 import { quietLogs } from "./helpers/globals.ts";
15 import { settleApp } from "./helpers/tui.ts";
16
17 quietLogs();
18 let dir = "";
19 let forge: Forge;
20
21 beforeAll(async () => {
22 dir = await mkdtemp(join(tmpdir(), "forge-tui-start-"));
23 forge = createApp({ dataDir: dir, port: 0 });
24 useProbe(forge, () => async () => true);
25 usePlacement(forge, {
26 place: async (plan: { name: string }) => ok({ url: `https://${plan.name}.fake.test`, bodyId: `fake-${plan.name}` }),
27 retire: async () => ok(),
28 room: () => undefined,
29 } as never);
30 const made = await createUser(forge.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
31 if (!made.ok) throw new Error(made.error);
32 });
33 afterAll(async () => {
34 forge.close();
35 await rm(dir, { recursive: true, force: true });
36 });
37
38 test("a taken name is said, a free one makes the forge and shows its claim link; an agent is not offered it", async () => {
39 const bob = getUserByName(forge.db, "bob")!;
40 const { app } = createForgeApp(forge, { sshUsername: "t", remoteAddress: "127.0.0.1", user: bob }, { terminal: headlessTerminal(140, 32), exitHooks: false });
41 app.start();
42 const k = (key: string) => app.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false });
43 const type = (text: string) => { for (const ch of text) k(ch); };
44 app.dispatch({ type: "key", key: "k", ctrl: true, alt: false, shift: false });
45 type("Start my forge");
46 k("enter");
47 await settleApp(app);
48 // A word the forge keeps is taken, and nothing is made.
49 k("n");
50 type("forge");
51 k("enter");
52 await settleApp(app);
53 await Bun.sleep(100);
54 await settleApp(app);
55 expect(app.screen.toText()).toContain("forge is taken.");
56 expect(await Bun.file(join(dir, "spawn", "forge.json")).exists()).toBe(false);
57 // A free name makes it, and the link is shown.
58 k("n");
59 for (let i = 0; i < 5; i++) k("backspace");
60 type("tui-made");
61 k("enter");
62 await settleApp(app);
63 await Bun.sleep(300);
64 await settleApp(app);
65 expect(await Bun.file(join(dir, "spawn", "tui-made.json")).exists()).toBe(true);
66 expect(app.screen.toText()).toContain("/claim");
67 app.stop();
68 const agent = { ...bob, kind: "agent" } as typeof bob;
69 expect(entry.offered(new Session(forge, { sshUsername: "t", remoteAddress: "127.0.0.1", user: agent }))).toBe(false);
70 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs