Python
Hosted demo: the web UI on Modal behind a passcode, with a run cap
neuregex68321f2d8349
diff --git a/.env.example b/.env.exampleindex 5013f9b..fba1cf3 100644--- a/.env.example+++ b/.env.example@@ -6,5 +6,7 @@ FREEFIELD_MODAL_PROFILE=COMFY_BASE_URL=https://YOUR-WORKSPACE--freefield-serve.modal.run# Written by `python tools/setup_token.py`, which stores the same value in the Modal secret "freefield".FREEFIELD_TOKEN=+# Passcode of the hosted demo (infra/web_app.py), written by `python tools/setup_demo.py`; only --link reads it here.+FREEFIELD_DEMO_PASSCODE=# Let the web UI and the CLI run draft apps too (their workflows have not been run on a GPU yet).# FREEFIELD_DRAFTS=1diff --git a/README.md b/README.mdindex 5763d83..fa9d4be 100644--- a/README.md+++ b/README.md@@ -204,6 +204,23 @@ the values, the seed that was used, and timings), so they survive a closed tab,restart; runs still going when the server stops are picked up again. *Recreate* puts any result's inputs and settingsback in the form.+### A private link to the studio++To let someone else use your Freefield (a reviewer, a friend) without installing anything, the same web app runs on+Modal next to the backend, behind a passcode:++```sh+python tools/setup_demo.py # once: a passcode → Modal secret "freefield-demo" and .env+modal deploy infra/web_app.py # the web UI on a small CPU container that scales to zero+python tools/setup_demo.py --link # the link to share: https://<workspace>--freefield-demo.modal.run/?key=…+```++The link sets the passcode as a cookie; without it every page and API call gets a passcode page. Runs are capped at+30 a day (UTC) and 2 at a time, so a shared link cannot run up the GPU bill (`FREEFIELD_MAX_RUNS_PER_DAY` and+`FREEFIELD_MAX_ACTIVE` at deploy time change that); the GPU pill shows how many are left. Lab marks are read-only+there, uploads stop at 100 MB, and the history lives in the `freefield-web` volume. Running `setup_demo.py` again+changes the passcode and locks out the old link once you redeploy.+Any ComfyUI works as the backend: run `comfy-api-proxy` next to it and `python infra/gateway.py` in front, and point`COMFY_BASE_URL` at the gateway. Pointing it straight at a `comfy-api-proxy` (or another Comfy API v2 endpoint) workstoo; only the unload-between-apps step is skipped. An app marked `draft` (none is, today) stays locked in the UI anddiff --git a/infra/web_app.py b/infra/web_app.pynew file mode 100644index 0000000..c41ee94--- /dev/null+++ b/infra/web_app.py@@ -0,0 +1,91 @@+"""Freefield's web UI on Modal: a private link that anyone with the passcode can use (the judges' "live link").++ python tools/setup_demo.py # once: a passcode → Modal secret "freefield-demo" and .env+ modal deploy infra/modal_app.py # the GPU backend, if it is not deployed yet+ modal deploy infra/web_app.py # this: the web UI, CPU only, scales to zero+ python tools/setup_demo.py --link # the link to share: https://<workspace>--freefield-demo.modal.run/?key=…++It is the same `npm run serve` as on your machine, with server/guard.ts switched on: every page and API call needs+the passcode (the link sets it as a cookie), runs are capped per UTC day (FREEFIELD_MAX_RUNS_PER_DAY, default 30)+and at the same time (FREEFIELD_MAX_ACTIVE, default 2), lab marks are read-only and uploads stop at 100 MB. The+limits are read from your environment when you deploy:++ FREEFIELD_MAX_RUNS_PER_DAY=15 modal deploy infra/web_app.py+ (PowerShell: $env:FREEFIELD_MAX_RUNS_PER_DAY = "15"; modal deploy infra/web_app.py)++It talks to the backend of the "freefield" app (function serve) with the gateway token of the "freefield" secret.+History and the run count live in the "freefield-web" volume, so they survive the container going to sleep.+"""+from __future__ import annotations++import os+import subprocess+import sys+import threading+import time+from pathlib import Path++import modal++ROOT = Path(__file__).resolve().parent.parent+if modal.is_local(): # the same guard as infra/modal_app.py: never deploy into another Modal workspace+ sys.path.insert(0, str(ROOT))+ from infra.modal_profile import enforce+ enforce(ROOT)+LIMITS = {+ "FREEFIELD_MAX_RUNS_PER_DAY": os.environ.get("FREEFIELD_MAX_RUNS_PER_DAY", "30"),+ "FREEFIELD_MAX_ACTIVE": os.environ.get("FREEFIELD_MAX_ACTIVE", "2"),+}+BACKEND_URL = os.environ.get("FREEFIELD_BACKEND_URL", "") # empty: look up the deployed "freefield" app++app = modal.App("freefield-web")+web_volume = modal.Volume.from_name("freefield-web", create_if_missing=True)+image = (+ modal.Image.from_registry("node:22.12.0-bookworm-slim", add_python="3.12")+ .add_local_file(ROOT / "package.json", "/freefield/package.json", copy=True)+ .add_local_file(ROOT / "package-lock.json", "/freefield/package-lock.json", copy=True)+ .run_commands("cd /freefield && npm ci --omit=dev --no-audit --no-fund")+ # code last, so editing it does not reinstall the packages+ .add_local_dir(ROOT / "server", "/freefield/server")+ .add_local_dir(ROOT / "web", "/freefield/web")+ .add_local_dir(ROOT / "apps", "/freefield/apps")+ .add_local_dir(ROOT / "schema", "/freefield/schema")+ .add_local_file(ROOT / "docs" / "vram-map.json", "/freefield/docs/vram-map.json")+)+if (ROOT / "lab" / "flags.json").exists(): # the lab's "mediocre" marks, shown read-only+ image = image.add_local_file(ROOT / "lab" / "flags.json", "/freefield/lab/flags.json")+++def keep_committing(every: float = 20.0) -> None:+ """History files and the run count reach the volume even if the container stops without warning."""+ while True:+ time.sleep(every)+ try:+ web_volume.commit()+ except Exception as e: # noqa: BLE001 - a missed commit is retried on the next turn+ print(f"volume commit failed: {e}")+++ image=image,+ secrets=[modal.Secret.from_name("freefield"), # FREEFIELD_TOKEN, the gateway's bearer token+ modal.Secret.from_name("freefield-demo"), # FREEFIELD_PASSCODE, from tools/setup_demo.py+ modal.Secret.from_dict({**LIMITS, "BACKEND_URL": BACKEND_URL})],+ volumes={"/data": web_volume},+ cpu=1.0,+ memory=1024,+ max_containers=1, # one history and one run count+ scaledown_window=900,+ timeout=24 * 3600,+)[email protected](max_inputs=100)[email protected]_server(3000, startup_timeout=120, label="freefield-demo")+def web():+ if not os.environ.get("FREEFIELD_PASSCODE"):+ raise RuntimeError('the Modal secret "freefield-demo" has no FREEFIELD_PASSCODE: run python tools/setup_demo.py')+ backend = os.environ.get("BACKEND_URL") or modal.Function.from_name("freefield", "serve").get_web_url()+ env = {**os.environ, "COMFY_BASE_URL": backend, "FREEFIELD_OUT": "/data/out", "FREEFIELD_HOST": "0.0.0.0",+ "PORT": "3000"}+ subprocess.Popen(["node", "--experimental-strip-types", "--disable-warning=ExperimentalWarning", "server/server.ts"],+ cwd="/freefield", env=env)+ threading.Thread(target=keep_committing, daemon=True).start()diff --git a/server/guard.ts b/server/guard.tsnew file mode 100644index 0000000..5a02eab--- /dev/null+++ b/server/guard.ts@@ -0,0 +1,142 @@+// What a hosted Freefield allows: a passcode at the door and a cap on runs. Off unless configured.+// FREEFIELD_PASSCODE every request needs it: once as ?key=… (it becomes a cookie), or the form at /+// FREEFIELD_MAX_RUNS_PER_DAY runs started per UTC day across all visitors (counted in <out>/limits.json)+// FREEFIELD_MAX_ACTIVE runs going at the same time+// Running locally with none of these set, nothing changes.+import { createHmac, timingSafeEqual } from "node:crypto";+import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";+import { dirname } from "node:path";++export type GuardOptions = {+ passcode?: string;+ maxRunsPerDay?: number;+ maxActive?: number;+ stateFile?: string;+ now?: () => Date;+};++const COOKIE = "ff_key";++export class Guard {+ readonly passcode?: string;+ readonly maxRunsPerDay?: number;+ readonly maxActive?: number;+ private readonly stateFile?: string;+ private readonly now: () => Date;+ private readonly cookieValue?: string;+ private state: { day: string; runs: number };++ constructor(opts: GuardOptions = {}) {+ this.passcode = opts.passcode || undefined;+ this.maxRunsPerDay = opts.maxRunsPerDay && opts.maxRunsPerDay > 0 ? opts.maxRunsPerDay : undefined;+ this.maxActive = opts.maxActive && opts.maxActive > 0 ? opts.maxActive : undefined;+ this.stateFile = opts.stateFile;+ this.now = opts.now ?? (() => new Date());+ // the cookie holds a keyed hash of the passcode, never the passcode itself+ this.cookieValue = this.passcode ? createHmac("sha256", this.passcode).update("freefield-visitor").digest("hex") : undefined;+ this.state = this.load();+ }++ static fromEnv(stateFile: string, env: NodeJS.ProcessEnv = process.env): Guard {+ const num = (v?: string) => (v && /^\d+$/.test(v) ? Number(v) : undefined);+ return new Guard({ passcode: env.FREEFIELD_PASSCODE, maxRunsPerDay: num(env.FREEFIELD_MAX_RUNS_PER_DAY),+ maxActive: num(env.FREEFIELD_MAX_ACTIVE), stateFile });+ }++ get hosted(): boolean {+ return Boolean(this.passcode || this.maxRunsPerDay || this.maxActive);+ }++ /** Does this request carry the passcode (as the cookie)? Always true without a passcode. */+ admits(cookieHeader: string | undefined): boolean {+ if (!this.cookieValue) return true;+ const got = parseCookies(cookieHeader)[COOKIE];+ return Boolean(got) && same(got, this.cookieValue);+ }++ /** A correct ?key= becomes the cookie; the caller redirects to the same URL without it. */+ login(key: string | null): string | null {+ if (!this.passcode || !key || !same(key, this.passcode)) return null;+ return `${COOKIE}=${this.cookieValue}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${60 * 60 * 24 * 30}`;+ }++ /** Why a new run may not start now, or null when it may. `active` = runs still going. */+ refuse(active: number): string | null {+ this.roll();+ if (this.maxActive && active >= this.maxActive) {+ return `${active} run(s) are still going on this demo (it allows ${this.maxActive} at a time); try again when one finishes`;+ }+ if (this.maxRunsPerDay && this.state.runs >= this.maxRunsPerDay) {+ return `this demo's ${this.maxRunsPerDay} runs for today (UTC) are used up; it resets at 00:00 UTC`;+ }+ return null;+ }++ /** Count one run that was accepted. */+ record(): void {+ this.roll();+ this.state.runs += 1;+ this.save();+ }++ status(active: number) {+ this.roll();+ return {+ runs_today: this.state.runs, max_runs_per_day: this.maxRunsPerDay ?? null, max_active: this.maxActive ?? null,+ runs_left: this.maxRunsPerDay ? Math.max(0, this.maxRunsPerDay - this.state.runs) : null, active,+ };+ }++ private today(): string {+ return this.now().toISOString().slice(0, 10);+ }++ private roll(): void {+ if (this.state.day !== this.today()) this.state = { day: this.today(), runs: 0 };+ }++ private load(): { day: string; runs: number } {+ try {+ if (this.stateFile && existsSync(this.stateFile)) {+ const s = JSON.parse(readFileSync(this.stateFile, "utf-8"));+ if (typeof s.day === "string" && Number.isInteger(s.runs)) return { day: s.day, runs: s.runs };+ }+ } catch { /* a damaged file starts the count again */ }+ return { day: this.today(), runs: 0 };+ }++ private save(): void {+ if (!this.stateFile) return;+ mkdirSync(dirname(this.stateFile), { recursive: true });+ const tmp = `${this.stateFile}.tmp`;+ writeFileSync(tmp, JSON.stringify(this.state) + "\n");+ renameSync(tmp, this.stateFile);+ }+}++export function parseCookies(header: string | undefined): Record<string, string> {+ const out: Record<string, string> = {};+ for (const part of (header ?? "").split(";")) {+ const i = part.indexOf("=");+ if (i > 0) out[part.slice(0, i).trim()] = part.slice(i + 1).trim();+ }+ return out;+}++function same(a: string, b: string): boolean {+ const x = Buffer.from(a);+ const y = Buffer.from(b);+ return x.length === y.length && timingSafeEqual(x, y);+}++/** The page a visitor without the cookie gets: one field for the passcode. */+export const DOOR_HTML = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">+<title>Freefield</title>+<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect x='1' y='1' width='30' height='30' rx='9' fill='%23e8ff5a'/%3E%3Cpath d='M8 11.5h16M8 16.5h9M8 21.5h12' stroke='%2311140a' stroke-width='3' stroke-linecap='round'/%3E%3Ccircle cx='22.5' cy='16.5' r='1.9' fill='%2311140a'/%3E%3C/svg%3E">+<style>+:root{color-scheme:dark}body{margin:0;min-height:100vh;display:grid;place-items:center;background:#09090a;color:#f4f4f2;font:15px/1.5 system-ui,sans-serif}+form{display:grid;gap:12px;width:min(320px,calc(100vw - 32px))}h1{margin:0;font-size:22px}p{margin:0;color:#9b9ba3}+input,button{font:inherit;padding:10px 12px;border-radius:8px;border:1px solid #2e2e33;background:#151517;color:inherit}+button{background:#e8ff5a;color:#11140a;border:0;font-weight:600;cursor:pointer}</style></head>+<body><form method="get" action="/"><h1>Freefield</h1><p>This demo is private. Enter the passcode you were given.</p>+<input name="key" type="password" autocomplete="current-password" aria-label="Passcode" required autofocus><button>Open</button></form></body></html>`;diff --git a/server/server.ts b/server/server.tsindex cc53f97..32f850d 100644--- a/server/server.ts+++ b/server/server.ts@@ -14,6 +14,9 @@// GET /api/flags lab examples marked "mediocre" from the UI (lab/flags.json)// POST /api/flags JSON { key, mediocre, note? }: mark or unmark one example// Everything else is served from web/ when it exists (with byte ranges, so videos seek everywhere).+// Hosted (server/guard.ts): FREEFIELD_PASSCODE closes every route behind a passcode, FREEFIELD_MAX_RUNS_PER_DAY and+// FREEFIELD_MAX_ACTIVE cap the runs (429 past them), lab marks become read-only and uploads are capped at+// FREEFIELD_MAX_UPLOAD_MB. FREEFIELD_OUT moves out/ (history, the run count), FREEFIELD_HOST the listening address.// web/examples/ holds one example per app, written by lab/publish.py; /api/apps carries it along.import { createServer, type IncomingMessage, type ServerResponse } from "node:http";import { createReadStream, existsSync, readFileSync, statSync } from "node:fs";@@ -22,6 +25,7 @@ import { loadRegistry, repoRoot, isFileInput, type App } from "./registry.ts";import { explainSubmitError, InputError, resolveValues, Runner, type Values } from "./runner.ts";import { History } from "./history.ts";import { Flags } from "./flags.ts";+import { DOOR_HTML, Guard } from "./guard.ts";const root = repoRoot();const { apps, problems } = loadRegistry(root);@@ -37,6 +41,9 @@ const vram = new Map<string, VramRow>(let runner: Runner | null = null;const getRunner = () => (runner ??= new Runner());const draftsAllowed = process.env.FREEFIELD_DRAFTS === "1";+const outDir = process.env.FREEFIELD_OUT || join(root, "out");+const guard = Guard.fromEnv(join(outDir, "limits.json"));+const maxUploadMb = Number(process.env.FREEFIELD_MAX_UPLOAD_MB || (guard.hosted ? 100 : 0));// the backend scales to zero 10 minutes after its last request (infra/modal_app.py scaledown_window).// lastContact only moves on real work (a run, a wake): status checks must not keep the GPU alive.@@ -44,7 +51,7 @@ const WARM_MS = 9 * 60 * 1000;let lastContact = 0;let waking: { since: number; error?: string } | null = null;const contact = () => { lastContact = Date.now(); };-const history = new History(join(root, "out", "history"), {+const history = new History(join(outDir, "history"), {onContact: contact,appInfo: (id) => {const app = apps.find((a) => a.id === id);@@ -127,7 +134,12 @@ function sendFile(req: IncomingMessage, res: ServerResponse, file: string, cacheasync function toRequest(req: IncomingMessage): Promise<Request> {const chunks: Buffer[] = [];- for await (const c of req) chunks.push(c as Buffer);+ let size = 0;+ for await (const c of req) {+ size += (c as Buffer).byteLength;+ if (maxUploadMb && size > maxUploadMb * 2 ** 20) throw new InputError(`uploads are limited to ${maxUploadMb} MB here`);+ chunks.push(c as Buffer);+ }return new Request(`http://local${req.url}`, {method: req.method,headers: req.headers as Record<string, string>,@@ -180,14 +192,18 @@ function startRun(app: App, values: Values, preset?: string) {return history.view(entry);}+const DONE = ["succeeded", "failed", "canceled", "expired", "lost"];+const activeRuns = () => history.list(undefined, 50).filter((e) => !DONE.includes(e.status)).length;+let gpuCache: { at: number; body: unknown } | null = null;async function gpuStatus(withDevice = false) {const configured = Boolean(process.env.COMFY_BASE_URL);- const host = configured ? new URL(process.env.COMFY_BASE_URL!).host : null;+ const host = configured ? (guard.hosted ? "Modal" : new URL(process.env.COMFY_BASE_URL!).host) : null;const warm = Date.now() - lastContact < WARM_MS;+ const running = activeRuns();const base = { configured, host, warm, last_contact: lastContact ? new Date(lastContact).toISOString() : null,waking: waking ? { seconds: Math.round((Date.now() - waking.since) / 1000), error: waking.error ?? null } : null,- running: history.list(undefined, 50).filter((e) => !["succeeded", "failed", "canceled", "expired", "lost"].includes(e.status)).length };+ running, demo: guard.hosted ? guard.status(running) : null };// only on request and only while warm: looking never starts a GPU, and the background poll never touches itif (!withDevice || !warm || !configured) return { ...base, device: null };if (gpuCache && Date.now() - gpuCache.at < 5000) return { ...base, device: gpuCache.body };@@ -227,6 +243,20 @@ const server = createServer(async (req, res) => {try {const url = new URL(req.url ?? "/", "http://local");const parts = url.pathname.split("/").filter(Boolean).map(decodeURIComponent);+ if (guard.passcode) {+ const key = url.searchParams.get("key");+ const cookie = key !== null ? guard.login(key) : null;+ if (cookie) { // the passcode leaves the address bar and lives on as a cookie+ url.searchParams.delete("key");+ res.writeHead(303, { "set-cookie": cookie, location: url.pathname + url.search, "cache-control": "no-store" });+ return res.end();+ }+ if (!guard.admits(req.headers.cookie)) {+ if (parts[0] === "api") return send(res, 401, { error: "this demo needs its passcode: open the link you were given" });+ res.writeHead(401, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });+ return res.end(DOOR_HTML);+ }+ }if (parts[0] === "api") {const [, area, id, sub, arg] = parts;if (req.method === "GET" && area === "apps" && parts.length === 2) {@@ -234,15 +264,20 @@ const server = createServer(async (req, res) => {const sorted = [...apps].sort((a, b) => order[a.section] - order[b.section]|| Number(b.status === "ready") - Number(a.status === "ready") || a.name.localeCompare(b.name));const examples = loadExamples();- return send(res, 200, { apps: sorted.map((a) => ({ ...publicApp(a), example: examples[a.id] ?? null })), drafts: draftsAllowed });+ return send(res, 200, { apps: sorted.map((a) => ({ ...publicApp(a), example: examples[a.id] ?? null })), drafts: draftsAllowed,+ hosted: guard.hosted });}if (req.method === "POST" && area === "apps" && sub === "run") {const app = byId.get(id);if (!app) return send(res, 404, { error: "unknown app" });if (!app.workflowPath) throw new InputError(`${app.id} has no workflow yet`);if (!runnable(app)) throw new InputError(`${app.id} is a draft; start the server with FREEFIELD_DRAFTS=1 to run it anyway`);+ const refused = guard.refuse(activeRuns());+ if (refused) return send(res, 429, { error: refused });const { values, preset } = await readValues(app, await toRequest(req));- return send(res, 202, startRun(app, resolveValues(app, values), preset));+ const view = startRun(app, resolveValues(app, values), preset);+ guard.record();+ return send(res, 202, view);}if (area === "history") {if (req.method === "GET" && !id) return send(res, 200, { entries: history.list(url.searchParams.get("app") || undefined) });@@ -273,6 +308,7 @@ const server = createServer(async (req, res) => {if (area === "flags" && parts.length === 2) {if (req.method === "GET") return send(res, 200, { mediocre: flags.list() });if (req.method === "POST") {+ if (guard.hosted) return send(res, 403, { error: "lab marks are read-only on the hosted demo" });const body = await (await toRequest(req)).json().catch(() => null) as { key?: unknown; mediocre?: unknown; note?: unknown } | null;if (!body || typeof body.key !== "string" || typeof body.mediocre !== "boolean") throw new InputError("expected JSON { key, mediocre, note? }");try {@@ -312,4 +348,6 @@ const server = createServer(async (req, res) => {history.resume(async (jobId) => getRunner().jobs().get(jobId));const port = Number(process.env.PORT ?? 3000);-server.listen(port, "127.0.0.1", () => console.log(`freefield on http://127.0.0.1:${port} (${apps.length} apps)`));+const host = process.env.FREEFIELD_HOST || "127.0.0.1";+server.listen(port, host, () => console.log(`freefield on http://${host}:${port} (${apps.length} apps)`+ + (guard.passcode ? " · passcode required" : "") + (guard.maxRunsPerDay ? ` · ${guard.maxRunsPerDay} runs a day` : "")));diff --git a/test/guard.test.ts b/test/guard.test.tsnew file mode 100644index 0000000..a80f176--- /dev/null+++ b/test/guard.test.ts@@ -0,0 +1,52 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { mkdtempSync, readFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { Guard, parseCookies } from "../server/guard.ts";++test("without settings the guard lets everything through", () => {+ const g = new Guard();+ assert.equal(g.hosted, false);+ assert.equal(g.admits(undefined), true);+ assert.equal(g.login("anything"), null);+ assert.equal(g.refuse(99), null);+});++test("the passcode becomes a cookie that holds a hash, not the passcode", () => {+ const g = new Guard({ passcode: "open-sesame" });+ assert.equal(g.admits(undefined), false);+ assert.equal(g.login("wrong"), null);+ assert.equal(g.login(null), null);+ const cookie = g.login("open-sesame")!;+ assert.match(cookie, /HttpOnly; Secure; SameSite=Lax/);+ assert.ok(!cookie.includes("open-sesame"));+ const pair = cookie.split(";")[0];+ assert.equal(g.admits(`other=1; ${pair}`), true);+ assert.equal(g.admits("ff_key=deadbeef"), false);+ assert.equal(new Guard({ passcode: "another" }).admits(pair), false);+});++test("runs are capped per UTC day and at the same time, and the count survives a restart", () => {+ const dir = mkdtempSync(join(tmpdir(), "ff-guard-"));+ const file = join(dir, "limits.json");+ let now = new Date("2026-10-28T23:50:00Z");+ const g = new Guard({ maxRunsPerDay: 2, maxActive: 1, stateFile: file, now: () => now });+ assert.equal(g.refuse(0), null);+ g.record();+ assert.match(g.refuse(1)!, /1 at a time/);+ assert.equal(g.refuse(0), null);+ g.record();+ assert.match(g.refuse(0)!, /2 runs for today/);+ assert.deepEqual(JSON.parse(readFileSync(file, "utf-8")), { day: "2026-10-28", runs: 2 });+ const again = new Guard({ maxRunsPerDay: 2, stateFile: file, now: () => now });+ assert.equal(again.status(0).runs_left, 0);+ now = new Date("2026-10-29T00:01:00Z");+ assert.equal(again.refuse(0), null);+ assert.equal(again.status(0).runs_left, 2);+});++test("cookies parse with spaces and values that hold '='", () => {+ assert.deepEqual(parseCookies(" a=1;b=x=y ; c="), { a: "1", b: "x=y", c: "" });+ assert.deepEqual(parseCookies(undefined), {});+});diff --git a/tools/setup_demo.py b/tools/setup_demo.pynew file mode 100644index 0000000..d71db29--- /dev/null+++ b/tools/setup_demo.py@@ -0,0 +1,90 @@+#!/usr/bin/env python3+"""The passcode of the hosted demo (infra/web_app.py), and the link to share.++ python tools/setup_demo.py # new passcode → Modal secret "freefield-demo" and .env (FREEFIELD_DEMO_PASSCODE)+ python tools/setup_demo.py --link # print the link: the deployed demo URL with ?key=<passcode>++The hosted web UI reads FREEFIELD_PASSCODE from the Modal secret; .env keeps the same value under another name+(FREEFIELD_DEMO_PASSCODE) so that `npm run serve` on your machine stays open. Run it again to change the passcode,+then `modal deploy infra/web_app.py` so the container picks it up; anyone holding the old link is locked out.+"""+from __future__ import annotations++import argparse+import re+import secrets+import shutil+import subprocess+import sys+from pathlib import Path++ROOT = Path(__file__).resolve().parent.parent+KEY = "FREEFIELD_DEMO_PASSCODE"+++def read_env(env: Path) -> str:+ return env.read_text(encoding="utf-8") if env.exists() else ""+++def link(env: Path) -> int:+ m = re.search(rf"^{KEY}=(\S+)\s*$", read_env(env), flags=re.M)+ if not m:+ print(f"no {KEY} in .env yet: run python tools/setup_demo.py", file=sys.stderr)+ return 1+ try:+ import modal+ url = modal.Function.from_name("freefield-web", "web").get_web_url()+ except Exception as e: # noqa: BLE001 - not deployed yet, or no Modal login here+ print(f"could not find the deployed demo ({e}); deploy it with modal deploy infra/web_app.py", file=sys.stderr)+ return 1+ print(f"{url.rstrip('/')}/?key={m[1]}")+ return 0+++def main(argv: list[str] | None = None) -> int:+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ ap.add_argument("--link", action="store_true", help="print the link to share and change nothing")+ a = ap.parse_args(argv)+ env = ROOT / ".env"+ if a.link:+ return link(env)++ if not env.exists():+ shutil.copy(ROOT / ".env.example", env)+ print("created .env from .env.example")+ sys.path.insert(0, str(ROOT))+ from infra.modal_profile import check+ active, pinned, ok = check(ROOT)+ if not ok:+ print(f'Modal profile "{active}" is active, but .env pins "{pinned}"; nothing changed. '+ f"Switch with: modal profile activate {pinned}", file=sys.stderr)+ return 1++ passcode = secrets.token_urlsafe(12)+ cmd = [sys.executable, "-m", "modal", "secret", "create", "freefield-demo", f"FREEFIELD_PASSCODE={passcode}", "--force"]+ try:+ r = subprocess.run(cmd, capture_output=True, text=True, timeout=120)+ except (OSError, subprocess.TimeoutExpired) as e:+ print(f"could not run the Modal CLI ({e}); nothing changed", file=sys.stderr)+ return 1+ if r.returncode != 0:+ print((r.stderr or r.stdout).strip(), file=sys.stderr)+ print('the Modal secret "freefield-demo" was not updated, so .env was left as it was', file=sys.stderr)+ return 1+ print(f'stored a new passcode in the Modal secret "freefield-demo" of profile "{active}"')++ text = read_env(env)+ line = f"{KEY}={passcode}"+ if re.search(rf"^{KEY}=.*$", text, flags=re.M):+ text = re.sub(rf"^{KEY}=.*$", line, text, count=1, flags=re.M)+ else:+ text = text.rstrip("\n") + "\n" + line + "\n"+ with open(env, "w", encoding="utf-8", newline="\n") as f:+ f.write(text)+ print(f"wrote it to .env as {KEY}")+ print("next: modal deploy infra/web_app.py then python tools/setup_demo.py --link")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/web/js/catalog.js b/web/js/catalog.jsindex 8bec165..081f9e4 100644--- a/web/js/catalog.js+++ b/web/js/catalog.js@@ -6,12 +6,14 @@ import { lang } from "./i18n.js";export let apps = [];export const byId = new Map();export let draftsAllowed = false;+export let hosted = false; // the server runs as a hosted demo (passcode, run cap): lab marks are read-onlyconst DEV = new URLSearchParams(location.search).has("dev"); // ?dev shows the smoke-test appsexport async function loadCatalog() {const d = await api("/api/apps");draftsAllowed = Boolean(d.drafts);+ hosted = Boolean(d.hosted);apps = d.apps.filter((a) => DEV || !a.id.startsWith("smoke"));byId.clear();for (const a of apps) byId.set(a.id, a);diff --git a/web/js/flags.js b/web/js/flags.jsindex 598dd24..2d4bd3f 100644--- a/web/js/flags.js+++ b/web/js/flags.js@@ -4,6 +4,7 @@// "<app>/<input>/<option>" for one option of a gallery select (the effects picker).import { api, el, icon, toast } from "./util.js";import { t } from "./i18n.js";+import { hosted } from "./catalog.js";let marks = {};const subs = new Set();@@ -43,6 +44,7 @@ function paint(b) {export function flagButton(key, { mini = false } = {}) {const b = el("button", { class: mini ? "mini flag" : "btn ghost flag", type: "button", "data-flag-key": key, ...(mini ? {} : { "data-flag-label": "1" }) },icon("thumbdown"), mini ? null : el("span", {}, ""));+ if (hosted) b.hidden = true; // marks are written to lab/flags.json, which a hosted demo does not keeppaint(b);b.addEventListener("click", async (ev) => {ev.stopPropagation();diff --git a/web/js/i18n.js b/web/js/i18n.jsindex cd6f7db..8e66a92 100644--- a/web/js/i18n.js+++ b/web/js/i18n.js@@ -13,6 +13,7 @@ const en = {"gpu.pop.wake": "Wake the GPU", "gpu.pop.waking": "Starting the container. Runs submitted now wait for it.","gpu.pop.ready": "Warm: runs start right away. It goes back to sleep 10 minutes after the last request.","gpu.pop.vram": "VRAM in use", "gpu.pop.loaded": "Loaded app", "gpu.pop.running": "{n} running", "gpu.pop.backend": "Backend",+ "gpu.pop.demo": "Hosted demo: {n} of {max} runs left today (UTC).","explore.lead.a": "An open studio for", "explore.lead.b": "images, video and sound","explore.lead.text": "Every app is a ComfyUI workflow with open weights, running on your own GPU. Nothing leaves your backend.","explore.start": "Start creating", "explore.browse": "Browse apps", "explore.apps": "{n} apps",@@ -92,6 +93,7 @@ const es = {"gpu.pop.wake": "Despertar la GPU", "gpu.pop.waking": "Arrancando el contenedor. Lo que envíes ahora lo espera.","gpu.pop.ready": "Caliente: las corridas empiezan de inmediato. Vuelve a dormir 10 minutos después de la última petición.","gpu.pop.vram": "VRAM en uso", "gpu.pop.loaded": "App cargada", "gpu.pop.running": "{n} en curso", "gpu.pop.backend": "Backend",+ "gpu.pop.demo": "Demo en línea: quedan {n} de {max} corridas hoy (UTC).","explore.lead.a": "Un estudio abierto para", "explore.lead.b": "imagen, video y sonido","explore.lead.text": "Cada app es un workflow de ComfyUI con pesos abiertos, en tu propia GPU. Nada sale de tu backend.","explore.start": "Empieza a crear", "explore.browse": "Ver las apps", "explore.apps": "{n} apps",diff --git a/web/js/nav.js b/web/js/nav.jsindex 58c0427..682439f 100644--- a/web/js/nav.js+++ b/web/js/nav.js@@ -62,6 +62,7 @@ function gpuPill() {if (g.device?.app) lines.push(el("p", { class: "help" }, `${t("gpu.pop.loaded")}: ${byId.get(g.device.app)?.name ?? g.device.app}`));} else lines.push(el("p", { class: "help" }, t("gpu.pop.asleep")), wake);if (g.running) lines.push(el("p", { class: "help" }, t("gpu.pop.running", { n: g.running })));+ if (g.demo?.max_runs_per_day) lines.push(el("p", { class: "help" }, t("gpu.pop.demo", { n: g.demo.runs_left, max: g.demo.max_runs_per_day })));}popover(pill, el("div", { class: "pad", style: { width: "300px" } }, ...lines), { align: "end" });};