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

A tab-forge app leaves as one spec file and comes back in, with or without its records #18399

opened this

Merged 2h 33m ago, live in production

mason/forge:mason/18397-a-tab-forge-app-leaves-as-one-spec-file → main 0 commits fork 2 threads · 2 unresolved

  • Merged. mason/18397-a-tab-forge-app-leaves-as-one-spec-file was merged into main as 081ac9e.

Review

Sign in to review this change.
5 files changed +180 −5
docs/features/tab.md +5 −2
@@ -47,8 +47,11 @@ Removing an app asks for its title, typed (a form field, so it works with script
4747
4848 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`.
4949
50 Entries live on this device, in this browser, and are gone if the site's data is cleared. Left out: importing or exporting
51 the file.
50 Entries live on this device, in this browser, and are gone if the site's data is cleared.
51
outdated

'Left out: importing or exporting the file.' is now false, and the next section says the opposite. Remove the sentence.

52 ## An app as a file (#18397)
53
54 On an app's page, *Save as file* downloads one JSON file (`src/tab/file.ts`), and *Save as file with its entries* adds a `records` list; *Open an app file* on `/tab` (a file to choose or text to paste) adds the app and keeps no more than the records that fit. The file is the Blocks JSON of `src/tab/blocks.ts`, the format shared with forge-apple, so the Apple app reads and writes the same file: `{version: 1, title, glyph?, blocks, records?: [{block, text, n, col, day}]}`. A file is read like a model's answer (`decodeApp`, `LIMITS`) after its size is capped at 200,000 characters before parsing; a bad file is refused in words and adds nothing, a record that does not fit its block is dropped, a save with entries drops the newest ones that would not fit under the same cap, and no model is asked. Tests: `test/tab-file.test.ts`.
5255
5356 ## Take an app with you (#18045)
5457
src/tab/apps.ts +32 −2
@@ -7,6 +7,7 @@ import { esc } from "./escape.ts";
77 import { settle } from "./fill.ts";
88 import type { TabDb, TabReply, TabRequest } from "./forge.ts";
99 import { ROOT, renderApp, type Rec } from "./render.ts";
10 import { fileName, openFile, saveFile, FILE_MAX } from "./file.ts";
1011 import { linkForm, MOVE_PATH } from "./share.ts";
1112 import { shell } from "./shell.ts";
1213 import { TAB_KEEP, TAB_KEEP_LABEL, TAB_LINK, TAB_LINK_LABEL } from "./words.ts";
@@ -50,11 +51,17 @@ export function appRows(db: TabDb): { id: number; title: string; glyph: string;
5051 });
5152 }
5253
54 /** Open a file: choose it, or paste its text (script off works: a plain multipart form). */
55 const openForm = `<form method="post" action="${ROOT}/apps/open" enctype="multipart/form-data" class="add"><label>Open an app file <input type="file" name="file" accept=".json,application/json"></label><label>or paste its text <textarea name="text" maxlength="${FILE_MAX}"></textarea></label><button>Open file</button></form>`;
56
57 /** The page's two ways to save: the app alone, or with its entries. */
58 const saveLinks = (id: number): string => `<p><a href="${ROOT}/apps/${id}/file">Save as file</a> or <a href="${ROOT}/apps/${id}/file?records=1">Save as file with its entries</a>: one JSON file the Apple app reads too.</p>`;
59
5360 /** The home page's list of apps, with the sentence that makes one when script is off. */
5461 export function appsHome(db: TabDb): string {
5562 const apps = appRows(db);
5663 const list = apps.length === 0 ? "" : `<ul class="items">${apps.map((a) => `<li><a href="${ROOT}/apps/${a.id}">${esc(a.glyph)} ${esc(a.title)}</a>${a.broken ? ' <span class="muted">cannot be drawn</span>' : ""}</li>`).join("")}</ul>`;
57 return `<h2>Your apps</h2>${list}<form method="post" action="${ROOT}/apps" class="add"><input name="say" maxlength="${SAY_MAX}" required placeholder="Track my water, a shopping list…" aria-label="Make an app"><button>Make an app</button></form>`;
64 return `<h2>Your apps</h2>${list}<form method="post" action="${ROOT}/apps" class="add"><input name="say" maxlength="${SAY_MAX}" required placeholder="Track my water, a shopping list…" aria-label="Make an app"><button>Make an app</button></form>${openForm}`;
5865 }
5966
6067 const records = (db: TabDb, app: number): Rec[] =>
@@ -75,6 +82,24 @@ function source(s: Stored): string {
7582 const removeForm = (id: number, title: string): string =>
7683 `<form method="post" action="${ROOT}/apps/${id}/delete" class="remove"><label>Type “${esc(title)}” to remove this app and its entries<input name="confirm" autocomplete="off" required></label><button class="danger">Remove this app</button></form>`;
7784
85 /** Add the app a file holds, with its records; a file that does not fit adds nothing. */
86 function openApp(db: TabDb, req: TabRequest, now: number): TabReply {
87 const text = (req.form.file ?? "").trim() !== "" ? req.form.file! : (req.form.text ?? "");
88 const got = openFile(text);
89 if (!got.ok) return refuse(`${got.why} Nothing was added.`);
90 db.run("BEGIN");
91 try {
92 db.run("INSERT INTO made (title, spec, why, created) VALUES (?, ?, ?, ?)", [got.app.title, JSON.stringify(got.app), JSON.stringify(["Opened from a file."]), now]);
93 const id = Number(db.all("SELECT max(id) AS id FROM made")[0]?.id);
94 for (const r of got.records) db.run("INSERT INTO rec (app, block, text, n, col, day, created) VALUES (?, ?, ?, ?, ?, ?, ?)", [id, r.block, r.text, r.n, r.col, r.day, now]);
95 db.run("COMMIT");
96 return back(id);
97 } catch {
98 db.run("ROLLBACK");
99 return shell("Not saved", "<p>The file could not be saved. Nothing was added.</p>", 500);
100 }
101 }
102
78103 export function handleApps(db: TabDb, req: TabRequest, path: string, now: number): TabReply | null {
79104 if (!path.startsWith("/apps")) return null;
80105 const parts = path.split("/").slice(2);
@@ -87,6 +112,7 @@ export function handleApps(db: TabDb, req: TabRequest, path: string, now: number
87112 db.run("INSERT INTO made (title, spec, why, created) VALUES (?, ?, ?, ?)", [made.app.title, JSON.stringify(made.app), JSON.stringify(made.why), now]);
88113 return back(Number(db.all("SELECT max(id) AS id FROM made")[0]?.id));
89114 }
115 if (req.method === "POST" && parts[0] === "open" && parts.length === 1) return openApp(db, req, now);
90116 const id = /^\d{1,9}$/.test(parts[0] ?? "") ? Number(parts[0]) : 0;
91117 const row = id === 0 ? undefined : db.all("SELECT title FROM made WHERE id = ?", [id])[0];
92118 if (row === undefined) return notFound();
@@ -95,7 +121,11 @@ export function handleApps(db: TabDb, req: TabRequest, path: string, now: number
95121 if (req.method === "GET" && parts.length === 1)
96122 return found === null
97123 ? shell(title, `<h1>${esc(title)}</h1><p>This app's spec cannot be read, so it cannot be drawn. It can still be removed.</p>${removeForm(id, title)}`)
98 : shell(found.app.title, `${renderApp(found.app, { appId: id, records: records(db, id), today: dayOf(now) })}<p><a href="${ROOT}/apps/${id}/source">How this app was made</a></p><p class="muted">${esc(TAB_LINK)}</p>${linkForm(found.app, TAB_LINK_LABEL)}<p class="muted">${esc(TAB_KEEP)}</p>${linkForm(found.app, TAB_KEEP_LABEL, MOVE_PATH)}${removeForm(id, title)}`, 200, false);
124 : shell(found.app.title, `${renderApp(found.app, { appId: id, records: records(db, id), today: dayOf(now) })}<p><a href="${ROOT}/apps/${id}/source">How this app was made</a></p><p class="muted">${esc(TAB_LINK)}</p>${linkForm(found.app, TAB_LINK_LABEL)}${saveLinks(id)}<p class="muted">${esc(TAB_KEEP)}</p>${linkForm(found.app, TAB_KEEP_LABEL, MOVE_PATH)}${removeForm(id, title)}`, 200, false);
125 if (req.method === "GET" && parts[1] === "file" && parts.length === 2 && found !== null) {
126 const withRecords = ["1", "true"].includes(new URLSearchParams(req.query ?? "").get("records") ?? "");
127 return { status: 200, html: saveFile(found.app, withRecords ? records(db, id) : undefined), file: { type: "application/json", name: fileName(found.app) } };
128 }
99129 if (req.method === "GET" && parts[1] === "source" && parts.length === 2) return found === null ? notFound() : shell(`${found.app.title}: why`, source(found));
100130 if (req.method !== "POST") return shell("Not allowed", "<p>That is not something this forge does.</p>", 405);
101131 if (parts[1] === "delete" && parts.length === 2) {
src/tab/file.ts added +65
@@ -0,0 +1,65 @@
1 /**
2 * An app as one file (#18397): the Blocks JSON of `blocks.ts` (the format shared with forge-apple),
3 * with an optional `records` list beside it. Plain data in, plain data out. A file is untrusted:
4 * its size is capped before it is parsed, the spec is read by `decodeApp` (so `LIMITS` apply), and
5 * a record is kept only when it fits its block; one that does not is dropped, never repaired.
6 */
7 import { decodeApp, entryText, LIMITS, type BlockApp } from "./blocks.ts";
8 import type { Rec } from "./render.ts";
9
10 /** The most characters of a file read here: the spec's limit, and room for the records. */
11 export const FILE_MAX = 200000;
12 /** The most records a file brings. */
13 export const RECORDS_MAX = 1000;
14
15 /** A record as it travels: where it belongs and what it holds, nothing of this device's ids. */
16 export type FileRecord = Omit<Rec, "id">;
17
18 export type Opened = { readonly ok: true; readonly app: BlockApp; readonly records: readonly FileRecord[] } | { readonly ok: false; readonly why: string };
19
20 const DAY = /^\d{4}-\d{2}-\d{2}$/;
21
22 /**
23 * The file's text for `app`, with as many of `records` as fit: the oldest are kept and the rest
24 * dropped from the end until the text is within `FILE_MAX`, so this forge can always open what it
25 * wrote.
outdated

Cap the output so it fits FILE_MAX: drop records from the end until JSON.stringify(out, null, 2).length <= FILE_MAX. Today a big export is a file this forge itself refuses to open. Add a test for it.

26 */
27 export function saveFile(app: BlockApp, records?: readonly Rec[]): string {
28 const text = (n: number): string => JSON.stringify({ ...app, records: (records ?? []).slice(0, n).map(({ block, text, n, col, day }) => ({ block, text, n, col, day })) }, null, 2);
29 if (records === undefined) return JSON.stringify(app, null, 2);
30 let lo = 0;
31 let hi = Math.min(records.length, RECORDS_MAX);
32 while (lo < hi) {
33 const mid = Math.ceil((lo + hi) / 2);
34 if (text(mid).length <= FILE_MAX) lo = mid;
35 else hi = mid - 1;
36 }
37 return text(lo);
38 }
39
40 /** The download's name: the title as letters, digits and dashes. */
41 export const fileName = (app: BlockApp): string => `${app.title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "app"}.json`;
42
43 function record(raw: unknown, app: BlockApp): FileRecord | null {
44 if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null;
45 const r = raw as Record<string, unknown>;
46 const block = app.blocks[typeof r.block === "number" ? r.block : -1];
47 if (block === undefined || typeof r.n !== "number" || !Number.isFinite(r.n) || Math.abs(r.n) > 1e9) return null;
48 const columns = block.kind === "board" ? (block.options.length > 0 ? block.options.length : 3) : 2;
49 if (typeof r.col !== "number" || !Number.isInteger(r.col) || r.col < 0 || r.col >= columns) return null;
50 if (typeof r.day !== "string" || !DAY.test(r.day) || typeof r.text !== "string") return null;
51 return { block: r.block as number, text: entryText(r.text), n: r.n, col: r.col, day: r.day };
52 }
53
54 /** Read a file's text: the app (checked as a model's answer is) and the records that fit it. */
55 export function openFile(text: string): Opened {
56 if (text.length > FILE_MAX) return { ok: false, why: "This file is too large to open here." };
57 let raw: unknown;
58 try { raw = JSON.parse(text); } catch { return { ok: false, why: "This is not an app file: it is not JSON." }; }
59 const decoded = decodeApp(raw);
60 if (!decoded.ok) return decoded;
61 if (JSON.stringify(decoded.app).length > LIMITS.json) return { ok: false, why: "This app is too large to open here." };
62 const list = (raw as { records?: unknown }).records;
63 const records = Array.isArray(list) ? list.slice(0, RECORDS_MAX).map((r) => record(r, decoded.app)).filter((r): r is FileRecord => r !== null) : [];
64 return { ok: true, app: decoded.app, records };
65 }
src/tab/words.ts +1 −1
@@ -16,7 +16,7 @@ export const TAB_FACTS: readonly string[] = [
1616 export const TAB_LEFT_OUT = "No git, shell or installs here: those need a real Linux machine.";
1717
1818 /** How an app leaves and enters: one file, checked on the way in. */
19 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.";
19 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. An app made in the tab is saved the same way from its page, with its entries or without, and opened with *Open an app file*.";
2020
2121 /**
2222 * The link an app's page offers beside the file: the button's label and what it does, said the same
test/tab-file.test.ts added +77
@@ -0,0 +1,77 @@
1 /** An app as one file (#18397): out and back in, with and without records. */
2 import { describe, expect, test } from "bun:test";
3 import { open } from "./support/tab-db.ts";
4 import { handle, migrate, type TabDb } from "../src/tab/forge.ts";
5 import { FILE_MAX } from "../src/tab/file.ts";
6
7 const NOW = new Date(2026, 11, 4, 12).getTime();
8 const post = (db: TabDb, path: string, form: Record<string, string>) => handle(db, { method: "POST", path, form }, NOW);
9 const get = (db: TabDb, path: string, query = "") => handle(db, { method: "GET", path, query, form: {} }, NOW);
10 const fresh = async (): Promise<TabDb> => { const db = await open(); migrate(db); return db; };
11 const count = (db: TabDb, table: string) => Number(db.all(`SELECT count(*) AS n FROM ${table}`)[0]?.n);
12
13 async function made(): Promise<TabDb> {
14 const db = await fresh();
15 post(db, "/apps", { say: "track my water" });
16 post(db, "/apps/1/0/tap", { n: "2" });
17 post(db, "/apps/1/0/tap", { n: "3" });
18 return db;
19 }
20
21 describe("an app file", () => {
22 test("saves as a JSON download, with or without its entries", async () => {
23 const db = await made();
24 const bare = get(db, "/apps/1/file");
25 expect(bare.file).toMatchObject({ type: "application/json", name: "track-my-water.json" });
26 expect(JSON.parse(bare.html).records).toBeUndefined();
27 expect(JSON.parse(get(db, "/apps/1/file", "records=1").html).records).toHaveLength(2);
28 expect(get(db, "/apps/9/file").status).toBe(404);
29 expect(get(db, "/apps/1").html).toContain("Save as file");
30 });
31
32 test("round trip: export then open yields an equal app, with and without entries", async () => {
33 const db = await made();
34 for (const [query, n] of [["", 0], ["records=1", 2]] as const) {
35 const out = get(db, "/apps/1/file", query).html;
36 const into = await fresh();
37 const reply = post(into, "/apps/open", { file: out });
38 expect(reply.status).toBe(303);
39 expect(JSON.parse(String(into.all("SELECT spec FROM made")[0]?.spec))).toEqual(JSON.parse(String(db.all("SELECT spec FROM made")[0]?.spec)));
40 expect(count(into, "rec")).toBe(n);
41 expect(get(into, "/apps/1/file", query).html).toBe(out);
42 }
43 });
44
45 test("pasted text opens too; bad records are dropped, a good app is kept", async () => {
46 const db = await fresh();
47 const text = JSON.stringify({ version: 1, title: "<b>T</b>", blocks: [{ kind: "list", name: "l", label: "L" }], records: [
48 { block: 0, text: "ok", n: 0, col: 0, day: "2026-12-01" }, { block: 5, text: "x", n: 0, col: 0, day: "2026-12-01" },
49 { block: 0, text: "x", n: 0, col: 9, day: "2026-12-01" }, { block: 0, text: "x", n: 0, col: 0, day: "bad" }, 7] });
50 expect(post(db, "/apps/open", { text }).status).toBe(303);
51 expect(count(db, "rec")).toBe(1);
52 expect(get(db, "/").html).toContain("&lt;b&gt;T&lt;/b&gt;");
53 });
54
55 test("a file that does not fit adds nothing, in words", async () => {
56 const db = await fresh();
57 for (const text of ["", "not json", "[1]", JSON.stringify({ version: 2, title: "T", blocks: [] }), "x".repeat(FILE_MAX + 1)]) {
58 const reply = post(db, "/apps/open", { file: text });
59 expect(reply.status).toBe(422);
60 expect(reply.html).toContain("Nothing was added.");
61 }
62 expect(count(db, "made")).toBe(0);
63 });
64
65 test("a large export still opens: records are dropped from the end to fit", async () => {
66 const db = await made();
67 const big = "x".repeat(480);
68 for (let i = 0; i < 900; i++) db.run("INSERT INTO rec (app, block, text, n, col, day, created) VALUES (1, 0, ?, 1, 0, '2026-12-01', ?)", [`${i}${big}`, NOW]);
69 const out = get(db, "/apps/1/file", "records=1").html;
70 expect(out.length).toBeLessThanOrEqual(FILE_MAX);
71 const into = await fresh();
72 expect(post(into, "/apps/open", { file: out }).status).toBe(303);
73 const kept = count(into, "rec");
74 expect(kept).toBeGreaterThan(100);
75 expect(kept).toBeLessThan(902);
76 });
77 });

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

Keyboard shortcuts

Docs