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

Apps without a login 2: a tiny model in the browser fills the app's spec, and the compiler catches every failure #18117

opened this in answer to

Merged 10h 10m ago, live in production

mason/forge:mason/18044-apps-without-a-login-2-a-tiny-model-in-t → main 0 commits fork 3 threads · 3 unresolved

  • Merged. mason/18044-apps-without-a-login-2-a-tiny-model-in-t was merged into main as 4147a37.

Review

Sign in to review this change.
13 files changed +480 −27
docs/features/tab.md +16 −1
@@ -43,10 +43,25 @@ Removing an app asks for its title, typed (a form field, so it works with script
4343 Making an app is page-only: it needs the worker's database and the service worker, which exist only in a browser tab, and the terminal reaches the forge over SSH, so its palette entry only names the feature (`src/tui/screens/tab.ts`). Size: `/tab`'s script is held under a byte budget by `test/tab-apps.test.ts`.
4444
4545 Entries live on this device, in this browser, and are gone if the site's data is cleared. Left out: importing or exporting
46 the file, and a model filling the spec.
46 the file.
4747
4848 ## Take an app with you (#18045)
4949
5050 The forge's home links its app as one file, `app.json` (`src/tab/spec.ts`): `{format: "forge-app", version: 1, kind: "issues", name, records?}`, a typed spec and never code, with the issues or without as the person chooses. Choosing the file (a multipart form the worker reads, `src/tab/wire.ts`) or pasting its text into *Import an app* validates it like a model's answer (shape, each field, no unknown keys, at most 200 records and 100,000 characters) and refuses one that does not fit in words, keeping nothing; one that fits sets the app's name and adds its records. The terminal says the same in `TAB_MOVE` (`src/tui/screens/tab.ts`). Tests: `test/tab.test.ts`.
5151
5252 Not done: the Apple app reading the file; carrying apps to a shared forge on sign-in and read-only revocable links (they need an account on a shared forge, and the move in `browser-forge-move.md` carries the database file, not specs). A download holds the oldest 200 issues and the page says so; an import is one transaction, and a refusal gives the text back to correct.
53
54 ## A small model fills the spec (#18044)

This whole section is duplicated below and describes the dropped design (POST /make, starter issues, /tab/f/spec). Delete this copy and keep the one that matches the code.

55
56 On `/tab` a person with no login can describe an app in a sentence. Two writers fill the same spec, never code:
57
58 - **The compiler** (`compile`, `src/tab/compile.ts`) needs no model, and the home's plain form (`POST /apps`) works with no script and no GPU.
59 - **The model** is optional. `/tab` offers it only when the browser has an on-device model (`src/tab/model.ts`: the Prompt API, `LanguageModel`), so a device without one sees no control and does not even fetch the model's code (`/tab/model.js`, kept apart so `/tab`'s script stays under its budget). Nothing is downloaded until the person presses the button, and the page names the size first. Once on, "Make it" asks the model first. The prompt is one short line plus the sentence; the output is constrained by a small flat closed JSON schema (`src/tab/fill.ts`): `title`, `kind` (list, tracker, counter, notes, board), and for a tracker its `unit`, for a board its `noun` and `columns`.
60
61 Every answer is judged in the forge's worker (`settle`, called by `POST /apps`): it must be JSON, hold only those fields, and each must fit its bound; the kind's words and defaults then come from the one `blockFor` the compiler uses, so the model never writes a label, a button or any text a page runs. A timeout (90 s on the page), a throw, no GPU, invalid JSON or a refused field leaves the compiler to write the app, so the person always gets one. The first line of the app's *How this app was made* page says which wrote it. The page's words (`TAB_MODEL`) and the terminal's state once that the model is optional, about 2 GB, downloads only when pressed, never leaves the device, and that this forge's own models are not used.
62
63 Tests: `test/tab-fill.test.ts` runs a stand-in model through a good answer, invalid JSON, a timeout, a throw and refused fields; each ends in a valid app and the right author.
64
65 ### What was chosen, and what was not measured
66
67 The runtime is the browser's own Prompt API: it adds no dependency, no weights hosted or proxied by this forge, takes a JSON schema as a constraint, and keeps the prompt on the device. WebLLM and wllama were not chosen: they need their weights and runtime from a third-party host, which this page's policy (`connect-src 'self'`) does not allow and which would be a request leaving the device. **Not measured:** download size, time to first app and memory on a phone-class device. The run that built this had no device, no GPU and no route to a model, and a figure written without one would be invented. The "about 2 GB" on the page is the browser's own figure for its model, not ours. What a person with a phone gets today: most phones lack the Prompt API, so the tier is not offered and the compiler writes the app, with no download and no model memory. Where the API exists, the numbers have to come from a real device before this tier is relied on.
src/tab/apps.ts +5 −2
@@ -3,14 +3,15 @@
33 * tab's own SQLite. Nothing is generated as code: a page is the spec drawn by `render.ts`. Every
44 * route returns a `TabReply`; a path it does not own returns null.
55 */
6 import { compile } from "./compile.ts";
76 import { esc } from "./escape.ts";
7 import { settle } from "./fill.ts";
88 import type { TabDb, TabReply, TabRequest } from "./forge.ts";
99 import { ROOT, renderApp, type Rec } from "./render.ts";
1010 import { shell } from "./shell.ts";
1111 import { decodeApp, entryText, SPEC_VERSION, type BlockApp } from "./blocks.ts";
1212
1313 export const SAY_MAX = 300;
14 const ANSWER_MAX = 4000;
1415
1516 export function migrateApps(db: TabDb): void {
1617 db.run("CREATE TABLE IF NOT EXISTS made (id INTEGER PRIMARY KEY, title TEXT NOT NULL, spec TEXT NOT NULL, why TEXT NOT NULL, created INTEGER NOT NULL)");
@@ -78,7 +79,9 @@ export function handleApps(db: TabDb, req: TabRequest, path: string, now: number
7879 if (req.method === "POST" && parts.length === 0) {
7980 const say = (req.form.say ?? "").trim();
8081 if (say === "" || say.length > SAY_MAX) return refuse(`Say what the app should do, in up to ${SAY_MAX} characters.`);
81 const made = compile(say);
82 // The page may bring a model's answer; it is judged here, and the compiler stands in for any
83 // that fails.
84 const made = settle(say, (req.form.answer ?? "").slice(0, ANSWER_MAX) || null);
8285 db.run("INSERT INTO made (title, spec, why, created) VALUES (?, ?, ?, ?)", [made.app.title, JSON.stringify(made.app), JSON.stringify(made.why), now]);
8386 return back(Number(db.all("SELECT max(id) AS id FROM made")[0]?.id));
8487 }
src/tab/boot.ts +55 −1
@@ -4,6 +4,7 @@
44 * service worker, so closing the tab stops the forge.
55 */
66 import { activated, type Registration } from "./active.ts";
7 import type { Runtime } from "./fill.ts";
78 import type { TabRequest } from "./forge.ts";
89
910 // The few browser globals this file touches, named here rather than pulling in the DOM library.
@@ -94,6 +95,53 @@ function ask(req: TabRequest): Promise<{ status: number; location?: string }> {
9495 });
9596 }
9697
98 /** How long the model may take before the compiler writes the app instead. */
99 const MODEL_WAIT_MS = 90000;
100
101 // The model, once the person has turned it on; null until then, and always null where the browser
102 // has none.
103 let runtime: Runtime | null = null;
104 interface ModelCode {
105 offer(): Promise<"available" | "downloadable" | null>;
106 turnOn(onProgress: (fraction: number) => void): Promise<Runtime>;
107 askModel(runtime: Runtime, say: string, ms: number): Promise<string | null>;
108 }
109 let code: Promise<ModelCode> | null = null;
110 const modelCode = (from: string): Promise<ModelCode> => (code ??= import(/* @vite-ignore */ from));
111
112 // The model is offered only where the browser can run one, and nothing is fetched until it is
113 // pressed.
114 async function offerModel(): Promise<void> {
115 const section = document.getElementById("tab-model");
116 const get = document.getElementById("tab-model-get");
117 const status = document.getElementById("tab-model-status");
118 if (section === null || get === null || status === null) return;
119 if (!("LanguageModel" in globalThis)) return;
120 const from = section.dataset.code!;
121 const state = await (await modelCode(from)).offer();
122 if (state === null) return;
123 section.hidden = false;
124 if (state === "available") get.textContent = "Turn on the model (it is already on this device)";
125 get.addEventListener("click", () => {
126 get.disabled = true;
127 status.textContent = "Starting the model…";
128 void modelCode(from).then((m) => m.turnOn((fraction) => {
129 status.textContent = `Downloading the model: ${Math.round(fraction * 100)}%`;
130 }).then(
131 (r) => {
132 runtime = r;
133 status.textContent = "The model is on. It runs on this device, and \"Make it\" now asks it first.";
134 get.hidden = true;
135 },
136 (error) => {
137 console.warn("tab forge: model", error);
138 status.textContent = "The model could not start here. The compiler still writes apps.";
139 get.disabled = false;
140 },
141 ));
142 });
143 }
144
97145 // Script runs, so the button can work: show it (it is hidden for a page without JavaScript).
98146 const button = document.getElementById("tab-start");
99147 const go = document.getElementById("tab-go");
@@ -101,6 +149,7 @@ if (button !== null && go !== null) {
101149 go.hidden = false;
102150 say("Not started.");
103151 button.addEventListener("click", () => void start(button));
152 void offerModel();
104153 }
105154
106155 // "Make an app": the compiler is a separate file, fetched the first time the box is used, so the
@@ -125,7 +174,12 @@ if (make !== null && sayBox !== null && previewFrame !== null && button !== null
125174 const sentence = sayBox.value.trim();
126175 if (sentence === "") return;
127176 if (holder === null && !(await start(button))) return;
128 const done = await ask({ method: "POST", path: "/apps", form: { say: sentence } });
177 let answer: string | null = null;
178 if (runtime !== null && code !== null) {
179 say("Writing the app with the model…");
180 answer = await (await code).askModel(runtime, sentence, MODEL_WAIT_MS);
181 }
182 const done = await ask({ method: "POST", path: "/apps", form: answer === null ? { say: sentence } : { say: sentence, answer } });
129183 if (done.location !== undefined) {
130184 document.getElementById("tab-frame")!.src = done.location;
131185 previewFrame.hidden = true;
src/tab/compile.ts +27 −6
@@ -44,6 +44,28 @@ function columnsOf(say: string): string[] | null {
4444 return names.length >= 2 ? names.map((n) => n.charAt(0).toUpperCase() + n.slice(1)) : null;
4545 }
4646
47 export const KINDS = ["list", "tracker", "counter", "notes", "board"] as const;
48 export type Kind = (typeof KINDS)[number];
49
50 /**
51 * One block of a kind, with that kind's words and defaults: the compiler's and the model's one way
52 * to build it.
53 */
54 export function blockFor(kind: Kind, label: string, o: { unit?: string; step?: number; options?: readonly string[]; noun?: string } = {}): Block {
55 const base = { name: "main", options: [] as string[], value: 0, formula: "", label };
56 if (kind === "board") {
57 const noun = o.noun ?? "card";
58 return { ...base, kind, options: [...(o.options ?? ["To do", "Doing", "Done"])], noun, add: `Add a ${noun}` };
59 }
60 if (kind === "tracker") {
61 const step = o.step ?? 1;
62 return { ...base, kind, ...(o.unit === undefined || o.unit === "" ? {} : { unit: o.unit }), step, value: step, add: "Add" };
63 }
64 if (kind === "counter") return { ...base, kind, step: 1, value: 0 };
65 if (kind === "notes") return { ...base, kind, placeholder: "Write a note", add: "Save", emptyTitle: "No notes yet", emptyHint: "Write the first one above." };
66 return { ...base, kind, placeholder: "Add an item", add: "Add", emptyTitle: "Nothing here yet", emptyHint: "Add the first item above." };
67 }
68
4769 /**
4870 * Compile one sentence. An empty sentence compiles to an empty list, so the preview is never blank.
4971 */
@@ -56,7 +78,6 @@ export function compile(sentence: string): Compiled {
5678 if (glyph !== undefined) why.push(`${glyph} fits a word you used.`);
5779
5880 let block: Block;
59 const base = { name: "main", options: [] as string[], value: 0, formula: "" };
6081 const board = word(say, "board|kanban|pipeline|sprint|columns?|lanes?|stages?|to-?do,? doing,? (?:and )?done");
6182 const tracker = word(say, "track(?:er|ing)?|log|habit|daily|each day|every day|per day|history") ?? (KNOWN_UNIT.test(say) ? "a number with a unit" : null);
6283 const counter = word(say, "count(?:er|ing)?|tally|clicks?|score");
@@ -64,23 +85,23 @@ export function compile(sentence: string): Compiled {
6485 if (board !== null) {
6586 const cols = columnsOf(say) ?? ["To do", "Doing", "Done"];
6687 const noun = NOUNS.find(([re]) => word(say, re) !== null)?.[1] ?? "card";
67 block = { ...base, kind: "board", label: title, options: cols, noun, add: `Add a ${noun}` };
88 block = blockFor("board", title, { options: cols, noun });
6889 why.push(`“${board}” means cards that move, so it is a board.`, columnsOf(say) === null ? "No columns named, so: To do, Doing, Done." : `Columns are the ones you named: ${cols.join(", ")}.`, `A card is called a ${noun}.`);
6990 } else if (tracker !== null && counter === null) {
7091 const unitHit = KNOWN_UNIT.exec(say);
7192 const known = UNITS.find(([re]) => word(say, re) !== null);
7293 const unit = unitHit?.[2]?.toLowerCase() ?? known?.[1] ?? "";
7394 const step = unitHit?.[1] !== undefined ? Number(unitHit[1]) : (known?.[2] ?? 1);
74 block = { ...base, kind: "tracker", label: title, ...(unit === "" ? {} : { unit }), step, value: step, add: "Add" };
95 block = blockFor("tracker", title, { unit, step });
7596 why.push(`“${tracker}” means a number each day, so it is a tracker.`, unit === "" ? "No unit named, so it counts plain numbers." : `The unit is ${unit}.`, `One tap adds ${step}${unit === "" ? "" : ` ${unit}`}.`);
7697 } else if (counter !== null) {
77 block = { ...base, kind: "counter", label: title, step: 1, value: 0 };
98 block = blockFor("counter", title);
7899 why.push(`“${counter}” means one number that goes up and down, so it is a counter.`);
79100 } else if (notes !== null) {
80 block = { ...base, kind: "notes", label: title, placeholder: "Write a note", add: "Save", emptyTitle: "No notes yet", emptyHint: "Write the first one above." };
101 block = blockFor("notes", title);
81102 why.push(`“${notes}” means free text, newest first, so it is notes.`);
82103 } else {
83 block = { ...base, kind: "list", label: title, placeholder: "Add an item", add: "Add", emptyTitle: "Nothing here yet", emptyHint: "Add the first item above." };
104 block = blockFor("list", title);
84105 why.push(say === "" ? "A list is where an empty sentence starts." : "No word asked for anything else, so it is a list you can tick off.");
85106 }
86107 return { app: { version: SPEC_VERSION, title, ...(glyph === undefined ? {} : { glyph }), blocks: [block] }, why };
src/tab/fill.ts added +112
@@ -0,0 +1,112 @@
1 /**
2 * Writing an app's spec from a sentence. A model, when the device has one, only fills the small
3 * flat schema below; its answer is checked (`fromAnswer`) and any failure (no answer in time, not
4 * JSON, a field that is not in the schema, a value that does not fit) leaves the deterministic
5 * `compile`, which needs no model, to write it. Either way the person gets a valid app, and
6 * `settle` says in words which one wrote it. No code is generated or run: the answer is data.
7 * Pure: the browser page and the tests share it.
8 */
9 import { blockFor, compile, KINDS, type Compiled, type Kind } from "./compile.ts";
10 import { SPEC_VERSION } from "./blocks.ts";
11
12 /**
13 * The one thing a model must be: something that answers a prompt, constrained by a schema, until
14 * aborted.
15 */
16 export interface Runtime {
17 prompt(text: string, schema: object, signal: AbortSignal): Promise<string>;
18 }
19
20 const TITLE_MAX = 40;
21 const UNIT_MAX = 20;
22 const OPTIONS_MAX = 6;
23 const OPTION_MAX = 24;
24
25 /**
26 * The schema the model fills: a title, which kind of app, and the few words that kind needs. Flat,
27 * closed, no unions.
28 */
29 const FILL_SCHEMA = {
30 type: "object",
31 properties: {
32 title: { type: "string", maxLength: TITLE_MAX },
33 kind: { type: "string", enum: KINDS },
34 unit: { type: "string", maxLength: UNIT_MAX },
35 noun: { type: "string", maxLength: UNIT_MAX },
36 columns: { type: "array", maxItems: OPTIONS_MAX, items: { type: "string", maxLength: OPTION_MAX } },
37 },
38 required: ["title", "kind"],
39 additionalProperties: false,
40 } as const;
41
42 /** The short prompt: the person's sentence between two fixed lines. */
43 const promptFor = (say: string): string =>
44 `Reply with JSON only. The person describes an app. Pick its kind (${KINDS.join(", ")}) and a short title; a tracker may have a unit, a board may have a noun for a card and its columns.\nThe app: ${say}`;
45
46 const text = (v: unknown, max: number): string | null => (typeof v === "string" && v.trim() !== "" && v.length <= max && !/[\u0000-\u001f\u007f]/.test(v) ? v.trim() : null);
47
48 /**
49 * The model's answer as an app, or null: JSON, an object with a known `kind` and a `title`, no
50 * field outside the schema, each value within its bound.
51 */
52 function fromAnswer(answer: string): Compiled | null {
53 let raw: unknown;
54 try {
55 raw = JSON.parse(answer);
56 } catch {
57 return null;
58 }
59 if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null;
60 const o = raw as Record<string, unknown>;
61 if (Object.keys(o).some((k) => !(k in FILL_SCHEMA.properties))) return null;
62 const title = text(o.title, TITLE_MAX);
63 const kind = KINDS.find((k) => k === o.kind);
64 if (title === null || kind === undefined) return null;
65 const optional = (v: unknown, max: number): string | undefined | null => (v === undefined ? undefined : text(v, max));
66 const unit = optional(o.unit, UNIT_MAX);
67 const noun = optional(o.noun, UNIT_MAX);
68 if (unit === null || noun === null) return null;
69 let columns: string[] | undefined;
70 if (o.columns !== undefined) {
71 if (!Array.isArray(o.columns) || o.columns.length > OPTIONS_MAX) return null;
72 const names = o.columns.map((c) => text(c, OPTION_MAX));
73 if (names.some((n) => n === null)) return null;
74 columns = names as string[];
75 if (columns.length === 1) return null;
76 }
77 const block = blockFor(kind as Kind, title, { ...(unit === undefined ? {} : { unit }), ...(noun === undefined ? {} : { noun }), ...(columns === undefined || columns.length === 0 ? {} : { options: columns }) });
78 return {
79 app: { version: SPEC_VERSION, title, blocks: [block] },
80 why: [`The model chose a ${kind}, titled “${title}”.`],
81 };
82 }
83
84 /**
85 * Asks the model, giving up after `ms`: its raw answer, or null when it timed out, threw or said
86 * nothing.
87 */
88 export async function askModel(runtime: Runtime, say: string, ms: number): Promise<string | null> {
89 const stop = new AbortController();
90 const timer = setTimeout(() => stop.abort(), ms);
91 try {
92 const answer = runtime.prompt(promptFor(say), FILL_SCHEMA, stop.signal);
93 answer.catch(() => undefined);
94 const late = new Promise<null>((resolve) => stop.signal.addEventListener("abort", () => resolve(null)));
95 return (await Promise.race([answer, late])) || null;
96 } catch {
97 return null;
98 } finally {
99 clearTimeout(timer);
100 }
101 }
102
103 /**
104 * The app to keep: the model's answer when it checks out, else the compiler's. Its first "why" line
105 * says which one wrote it.
106 */
107 export function settle(say: string, answer: string | null): Compiled {
108 const modelled = answer === null ? null : fromAnswer(answer);
109 if (modelled !== null) return { app: modelled.app, why: ["A small model on this device wrote this app's spec; its answer was checked against the schema before it was kept.", ...modelled.why] };
110 const compiled = compile(say);
111 return { app: compiled.app, why: ["The compiler wrote this app's spec: no model was used, or its answer did not fit the schema.", ...compiled.why] };
112 }
src/tab/model.ts added +63
@@ -0,0 +1,63 @@
1 /**
2 * The optional small model, in the browser: the Prompt API (`LanguageModel`), which runs the
3 * browser's own on-device model, takes a JSON schema to constrain its output, and sends nothing off
4 * the device. It is the entry of `/tab/model.js`, which the page fetches only where the browser has
5 * the API. `offer` says whether this browser has it (so a device that cannot run it is never shown
6 * a control); `turnOn` starts the download the person asked for and returns a `Runtime`.
7 */
8 import type { Runtime } from "./fill.ts";
9
10 export { askModel } from "./fill.ts";
11
12 interface Session {
13 prompt(text: string, options: { responseConstraint: object; signal: AbortSignal }): Promise<string>;
14 clone(): Promise<Session>;
15 destroy(): void;
16 }
17 interface Options {
18 expectedInputs: { type: "text"; languages: string[] }[];
19 expectedOutputs: { type: "text"; languages: string[] }[];
20 monitor?: (m: { addEventListener(type: "downloadprogress", listener: (e: { loaded: number }) => void): void }) => void;
21 }
22 interface Api {
23 availability(options: Options): Promise<string>;
24 create(options: Options): Promise<Session>;
25 }
26
27 const OPTIONS: Options = { expectedInputs: [{ type: "text", languages: ["en"] }], expectedOutputs: [{ type: "text", languages: ["en"] }] };
28 const api = (): Api | undefined => (globalThis as { LanguageModel?: Api }).LanguageModel;
29
30 /**
31 * "available" when the model is already on this device, "downloadable" when it can be fetched, null
32 * when this browser cannot run one.
33 */
34 export async function offer(): Promise<"available" | "downloadable" | null> {
35 try {
36 const state = await api()?.availability(OPTIONS);
37 if (state === "available") return "available";
38 if (state === "downloadable" || state === "downloading") return "downloadable";
39 return null;
40 } catch {
41 return null;
42 }
43 }
44
45 /**
46 * Starts the model (downloading it if it is not here), reporting the fraction fetched; throws in
47 * words the page can show.
48 */
49 export async function turnOn(onProgress: (fraction: number) => void): Promise<Runtime> {
50 const lm = api();
51 if (lm === undefined) throw new Error("This browser has no on-device model.");
52 const base = await lm.create({ ...OPTIONS, monitor: (m) => m.addEventListener("downloadprogress", (e) => onProgress(e.loaded)) });
53 return {
54 async prompt(text, schema, signal) {
55 const one = await base.clone();
56 try {
57 return await one.prompt(text, { responseConstraint: schema, signal });
58 } finally {
59 one.destroy();
60 }
61 },
62 };
63 }
src/tab/words.ts +11 −1
@@ -18,5 +18,15 @@ export const TAB_LEFT_OUT = "No git, shell or installs here: those need a real L
1818 /** How an app leaves and enters: one file, checked on the way in. */
1919 export const TAB_MOVE = "An app is one JSON file: download it from the forge's home (with its issues or without) and choose it (or paste it) in another tab forge, which refuses a file that does not fit.";
2020
21 /**
22 * The optional model, said before anything is downloaded. It only fills the app's spec (a title, a
23 * kind and a few words, checked against a schema); the compiler writes the spec when there is no
24 * model or its answer does not fit.
25 */
26 export const TAB_MODEL: readonly string[] = [
27 "Optional, about 2 GB: the browser's own model, downloaded only when you press the button.",
28 "Your sentence and its answer never leave this device, and this forge's own models are not used.",
29 ];
30
2131 /** The terminal's one sentence: the facts and where the page is. */
22 export const tabLine = (): string => `${TAB_FACTS.join(" ")} ${TAB_LEFT_OUT} ${TAB_MOVE} Open /tab in a browser to start it and to make an app from a sentence.`;
32 export const tabLine = (): string => `${TAB_FACTS.join(" ")} ${TAB_LEFT_OUT} ${TAB_MOVE} ${TAB_MODEL.join(" ")} Open /tab in a browser to start it and to make an app from a sentence.`;
src/web/pages/tab.ts +7 −1
@@ -6,7 +6,7 @@
66 */
77
88 import type { Ctx } from "../../http/context.ts";
9 import { TAB_FACTS, TAB_LEFT_OUT, TAB_TITLE } from "../../tab/words.ts";
9 import { TAB_FACTS, TAB_MODEL, TAB_LEFT_OUT, TAB_TITLE } from "../../tab/words.ts";
1010 import { pageHead } from "../chrome.ts";
1111 import { html } from "../html.ts";
1212 import { page } from "../layout.ts";
@@ -29,6 +29,12 @@ export async function tabPage(ctx: Ctx): Promise<Response> {
2929 Start it
3030 </button>
3131 </p>
32 <section id="tab-model" hidden data-code="/tab/model.js">

Principles 1 and 8: four rows of explanation, repeated in the terminal line. State each fact once, in plain words, and let the button carry the rest.

33 <h2>A small model, if you want one</h2>
34 ${rowList(TAB_MODEL.map((fact) => row({ title: fact })))}
35 <p><button id="tab-model-get" class="btn" type="button">Download and turn on the model</button></p>
36 <p id="tab-model-status" class="muted" role="status"></p>
37 </section>
3238 <p id="tab-status" class="muted" role="status">${boot === null ? "The tab forge could not be built here." : ""}</p>
3339 <iframe id="tab-frame" class="tab-frame" title="The forge in this tab" src="about:blank" hidden></iframe>`;
3440 return page({ ctx, title: TAB_TITLE, description: "A forge that runs in this browser tab, on this device.", frameSelf: true, ...(boot === null ? {} : { scriptJs: boot.code }), body });
src/web/tab-asset.ts +7 −5
@@ -3,7 +3,8 @@
33 * than a file read.
44 *
55 * - `/tab/worker.js`, `/tab/sw.js` and `/tab/make.js` (the compiler, fetched only when the "Make an
6 * app" box is used): `src/tab/worker.ts`, `src/tab/sw.ts` and `src/tab/make.ts`, bundled by
6 * app" box is used) and `/tab/model.js` (the optional model's code, fetched only where the
7 * browser has one): `src/tab/worker.ts`, `sw.ts`, `make.ts` and `model.ts`, bundled by
78 * `Bun.build` at first use. Fixed paths (a service worker's scope comes from its path), answered
89 * with a validator and `no-cache`.
910 * - `/tab/v/<hash>/sqlite3.mjs` and `sqlite3.wasm`: the vendored SQLite wasm
@@ -66,7 +67,7 @@ export function sqliteVendor(): Vendor {
6667
6768 export const sqliteModulePath = (): string => `/tab/v/${sqliteVendor().hash}/sqlite3.mjs`;
6869
69 type Name = "boot" | "worker" | "sw" | "make";
70 type Name = "boot" | "worker" | "sw" | "make" | "model";
7071 let building: Promise<Record<Name, BuiltAsset | null>> | null = null;
7172 /**
7273 * One of the tab's scripts, all three built once per process (the paths are literal so the tree
@@ -75,13 +76,14 @@ let building: Promise<Record<Name, BuiltAsset | null>> | null = null;
7576 export async function tabScript(name: Name): Promise<BuiltAsset | null> {
7677 building ??= (async () => {
7778 const at = (url: URL) => Bun.fileURLToPath(url);
78 const [boot, worker, sw, make] = await Promise.all([
79 const [boot, worker, sw, make, model] = await Promise.all([
7980 bundleEntry(at(new URL("../tab/boot.ts", import.meta.url)), "tab-boot", "web.tab_asset_failed"),
8081 bundleEntry(at(new URL("../tab/worker.ts", import.meta.url)), "tab-worker", "web.tab_asset_failed"),
8182 bundleEntry(at(new URL("../tab/sw.ts", import.meta.url)), "tab-sw", "web.tab_asset_failed"),
8283 bundleEntry(at(new URL("../tab/make.ts", import.meta.url)), "tab-make", "web.tab_asset_failed"),
84 bundleEntry(at(new URL("../tab/model.ts", import.meta.url)), "tab-model", "web.tab_asset_failed"),
8385 ]);
84 return { boot, worker, sw, make };
86 return { boot, worker, sw, make, model };
8587 })();
8688 return (await building)[name];
8789 }
@@ -98,7 +100,7 @@ function validated(request: Request, body: string, type: string, csp: string): R
98100 /** GET /tab/:name: the worker, the service worker or the stylesheet. */
99101 export async function tabFile(request: Request, name: string): Promise<Response> {
100102 if (name === "f.css") return validated(request, STYLE, "text/css; charset=utf-8", PLAIN_CSP);
101 const scripts: Record<string, Name> = { "worker.js": "worker", "sw.js": "sw", "make.js": "make" };
103 const scripts: Record<string, Name> = { "worker.js": "worker", "sw.js": "sw", "make.js": "make", "model.js": "model" };
102104 const script = Object.hasOwn(scripts, name) ? scripts[name] : undefined;
103105 if (script === undefined) return missing();
104106 const built = await tabScript(script);
test/support/tab-db.ts added +13
@@ -0,0 +1,13 @@
1 import { Database } from "bun:sqlite";
2 import { migrate, type TabDb } from "../../src/tab/forge.ts";
3
4 /** A fresh in-memory tab forge database, migrated. */
5 export const open = (): TabDb => {
6 const db = new Database(":memory:");
7 const tab: TabDb = {
8 run: (sql, bind) => void db.query(sql).run(...(bind ?? [])),
9 all: (sql, bind) => db.query(sql).all(...(bind ?? [])) as Record<string, string | number>[],
10 };
11 migrate(tab);
12 return tab;
13 };
test/tab-apps.test.ts +1 −10
@@ -2,24 +2,15 @@
22 * Apps in the tab (#18043): a sentence compiles to a spec, a fixed renderer draws it, and the
33 * records stay.
44 */
5 import { Database } from "bun:sqlite";
65 import { describe, expect, test } from "bun:test";
76 import { compile } from "../src/tab/compile.ts";
7 import { open } from "./support/tab-db.ts";
88 import { handle, migrate, type TabDb } from "../src/tab/forge.ts";
99 import { preview } from "../src/tab/make.ts";
1010 import { renderApp } from "../src/tab/render.ts";
1111 import { decodeApp } from "../src/tab/blocks.ts";
1212 import { TAB_FACTS } from "../src/tab/words.ts";
1313
14 const open = (): TabDb => {
15 const db = new Database(":memory:");
16 const tab: TabDb = {
17 run: (sql, bind) => void db.query(sql).run(...(bind ?? [])),
18 all: (sql, bind) => db.query(sql).all(...(bind ?? [])) as Record<string, string | number>[],
19 };
20 migrate(tab);
21 return tab;
22 };
2314 const NOW = new Date(2026, 11, 4, 12).getTime();
2415 const post = (db: TabDb, path: string, form: Record<string, string>) => handle(db, { method: "POST", path, form }, NOW);
2516 const get = (db: TabDb, path: string) => handle(db, { method: "GET", path, form: {} }, NOW);
test/tab-fill.test.ts added +160
@@ -0,0 +1,160 @@
1 /**
2 * A small model fills an app's spec in a tab; a stand-in model stands for it, and every outcome
3 * ends in a valid app that the "How this app was made" page says who wrote.
4 */
5 import { afterEach, describe, expect, test } from "bun:test";
6 import { decodeApp } from "../src/tab/blocks.ts";
7 import { askModel, type Runtime, settle } from "../src/tab/fill.ts";
8 import { handle, type TabDb } from "../src/tab/forge.ts";
9 import { open } from "./support/tab-db.ts";
10 import { TAB_MODEL, tabLine } from "../src/tab/words.ts";
11
12 const say = "track the water I drink";
13 const good = JSON.stringify({ title: "Water log", kind: "tracker", unit: "glasses" });
14 const stand = (answer: () => Promise<string>): Runtime => ({ prompt: () => answer() });
15
16 /**
17 * One sentence through the stand-in and the forge: the reply and the source page of the app made.
18 */
19 async function make(db: TabDb, runtime: Runtime, ms = 20) {
20 const answer = await askModel(runtime, say, ms);
21 const reply = handle(db, { method: "POST", path: "/apps", form: answer === null ? { say } : { say, answer } });
22 const source = handle(db, { method: "GET", path: reply.location!.replace("/tab/f", "") + "/source", form: {} }).html;
23 const page = handle(db, { method: "GET", path: reply.location!.replace("/tab/f", ""), form: {} }).html;
24 return { reply, source, page };
25 }
26
27 describe("a model fills the spec, and the compiler stands in for any failure", () => {
28 test("a good answer is kept, checked, and the page says a model wrote it", async () => {
29 const got = await make(open(), stand(async () => good));
30 expect(got.reply.status).toBe(303);
31 expect(got.source).toContain("small model on this device wrote");
32 expect(got.source).toContain("Water log");
33 expect(got.page).toContain("glasses");
34 });
35
36 test("invalid JSON falls back to the compiler, which still makes an app", async () => {
37 const got = await make(open(), stand(async () => "Sure! { title: nope"));
38 expect(got.reply.status).toBe(303);
39 expect(got.source).toContain("compiler wrote");
40 expect(got.source).toContain("Track the water I drink");
41 });
42
43 test("a timeout falls back to the compiler, and the model is told to stop", async () => {
44 let stopped = false;
45 const slow: Runtime = { prompt: (_t, _s, signal) => new Promise((_, reject) => signal.addEventListener("abort", () => ((stopped = true), reject(new Error("aborted"))))) };
46 const got = await make(open(), slow, 10);
47 expect(stopped).toBe(true);
48 expect(got.reply.status).toBe(303);
49 expect(got.source).toContain("compiler wrote");
50 });
51
52 test("a model that throws, or answers nothing, falls back too", async () => {
53 expect(await askModel(stand(async () => { throw new Error("no GPU"); }), "x", 20)).toBeNull();
54 expect(await askModel(stand(async () => ""), "x", 20)).toBeNull();
55 expect((await make(open(), stand(async () => { throw new Error("no GPU"); }))).source).toContain("compiler wrote");
56 });
57
58 test("a refused field, a wrong type or an oversize value is not kept as the model's", () => {
59 const refused = [
60 JSON.stringify({ title: "A", kind: "list", script: "alert(1)" }),
61 JSON.stringify({ title: "A", kind: "game" }),
62 JSON.stringify({ title: 5, kind: "list" }),
63 JSON.stringify({ title: "x".repeat(41), kind: "list" }),
64 JSON.stringify({ title: "A", kind: "board", columns: ["only"] }),
65 JSON.stringify({ title: "A", kind: "board", columns: "To do" }),
66 JSON.stringify({ title: "A", kind: "tracker", unit: "x".repeat(21) }),
67 JSON.stringify({ kind: "list" }),
68 JSON.stringify([good]),
69 "null",
70 ];
71 for (const answer of refused) {
72 const made = settle("a plain idea", answer);
73 expect(made.why[0]).toContain("compiler wrote");
74 expect(decodeApp(JSON.stringify(made.app)).ok).toBe(true);
75 }
76 expect(settle("a plain idea", good).why[0]).toContain("model");
77 });
78
79 test("a board answer keeps its columns and noun", () => {
80 const made = settle("x", JSON.stringify({ title: "Bugs", kind: "board", noun: "bug", columns: ["New", "Fixed"] }));
81 expect(made.app.blocks[0]).toMatchObject({ kind: "board", options: ["New", "Fixed"], noun: "bug" });
82 });
83
84 test("the compiler needs no model: the plain form makes an app with no answer, and an oversize answer is ignored", () => {
85 const db = open();
86 const r = handle(db, { method: "POST", path: "/apps", form: { say: "a board for my bugs", answer: "x".repeat(10000) } });
87 expect(r.status).toBe(303);
88 expect(handle(db, { method: "GET", path: r.location!.replace("/tab/f", "") + "/source", form: {} }).html).toContain("compiler wrote");
89 });
90
91 test("a model's text is escaped on the page", async () => {
92 const answer = JSON.stringify({ title: "<img src=x onerror=1>", kind: "list" });
93 const got = await make(open(), stand(async () => answer));
94 expect(got.page).not.toContain("<img");
95 expect(got.source).not.toContain("<img");
96 });
97
98 test("the words say the model is optional, local and checked", () => {
99 expect(TAB_MODEL.join(" ")).toMatch(/Optional/);
100 expect(TAB_MODEL.join(" ")).toMatch(/never leave/);
101 expect(TAB_MODEL.join(" ")).toMatch(/only when you press/);
102 expect(tabLine()).toContain(TAB_MODEL[0]!);
103 });
104 });
105
106 describe("the browser's on-device model", () => {
107 const g = globalThis as { LanguageModel?: unknown };
108 const saved = g.LanguageModel;
109 afterEach(() => {
110 if (saved === undefined) delete g.LanguageModel;
111 else g.LanguageModel = saved;
112 });
113
114 test("offer is null without the API, on an error and when unavailable; downloading counts as downloadable", async () => {
115 const { offer } = await import("../src/tab/model.ts");
116 delete g.LanguageModel;
117 expect(await offer()).toBeNull();
118 for (const [state, want] of [["unavailable", null], ["downloadable", "downloadable"], ["downloading", "downloadable"], ["available", "available"]] as const) {
outdated

Reading the page source for a string does not test that the control is hidden. Also restore globalThis.LanguageModel in a finally, and cover turnOn and prompt with a fake API.

119 g.LanguageModel = { availability: async () => state };
120 expect(await offer()).toBe(want);
121 }
122 g.LanguageModel = { availability: async () => { throw new Error("x"); } };
123 expect(await offer()).toBeNull();
124 });
125
126 test("turnOn reports download progress, and prompt clones the session and destroys the clone", async () => {
127 const { turnOn } = await import("../src/tab/model.ts");
128 const log: string[] = [];
129 const clone = { prompt: async (text: string, o: { responseConstraint: object }) => { log.push(`prompt:${text}:${JSON.stringify(o.responseConstraint)}`); return "{}"; }, clone: async () => clone, destroy: () => { log.push("destroy"); } };
130 const base = { ...clone, clone: async () => clone };
131 g.LanguageModel = {
132 availability: async () => "downloadable",
133 create: async (o: { monitor?: (m: { addEventListener(t: string, l: (e: { loaded: number }) => void): void }) => void }) => {
134 o.monitor?.({ addEventListener: (_t, l) => { l({ loaded: 0.5 }); l({ loaded: 1 }); } });
135 return base;
136 },
137 };
138 const seen: number[] = [];
139 const runtime = await turnOn((f) => seen.push(f));
140 expect(seen).toEqual([0.5, 1]);
141 expect(await runtime.prompt("hi", { type: "object" }, new AbortController().signal)).toBe("{}");
142 expect(log).toEqual(['prompt:hi:{"type":"object"}', "destroy"]);
143 });
144
145 test("the clone is destroyed when the prompt throws", async () => {
146 const { turnOn } = await import("../src/tab/model.ts");
147 let destroyed = 0;
148 const clone = { prompt: async () => { throw new Error("no gpu"); }, clone: async () => clone, destroy: () => { destroyed++; } };
149 g.LanguageModel = { availability: async () => "available", create: async () => clone };
150 const runtime = await turnOn(() => {});
151 await expect(runtime.prompt("hi", {}, new AbortController().signal)).rejects.toThrow("no gpu");
152 expect(destroyed).toBe(1);
153 });
154
155 test("turnOn says so in words when the browser has no model", async () => {
156 const { turnOn } = await import("../src/tab/model.ts");
157 delete g.LanguageModel;
158 await expect(turnOn(() => {})).rejects.toThrow("no on-device model");
159 });
160 });
test/timers-named.test.ts +3
@@ -81,6 +81,9 @@ const ALLOWED: readonly Allowed[] = [
8181 ...allow("setTimeout", "the tab forge's service worker runs in a browser, not here: one deadline on asking the page, resolves a promise", [
8282 ["src/tab/sw.ts", "() => resolve(null)"],
8383 ]),
84 ...allow("setTimeout", "the tab's model deadline runs in a browser page, not here: one per sentence, cleared when the answer lands, only aborts the model's call", [
85 ["src/tab/fill.ts", "() => stop.abort()"],
86 ]),
8487 ...allow("setTimeout", "a service's restart pause: one timer, only resolves a promise, cleared when the app stops", [
8588 ["src/apps/supervise.ts", "resolve"],
8689 ]),

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

Keyboard shortcuts

Docs