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

Feature flags for apps: a flags file in the app template, values set from the app's settings, FORGE_FLAGS_URL and a one-file client #16707

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/1830-feature-flags-for-apps-a-flags-file-in-t → main 0 commits fork 5 threads · 5 unresolved

  • Merged. scout/1830-feature-flags-for-apps-a-flags-file-in-t was merged into main as c4232ca.

Review

Sign in to review this change.
32 files changed +861 −6
docs/features/app-flags.md added +43
@@ -0,0 +1,43 @@
1 ---
2 topic: Your apps
3 row: Feature flags for an app (`Settings → App → Feature flags`)
4 ---
5 # Feature flags for an app (`Settings → App → Feature flags`)
6
7 Ship two versions of a thing side by side and keep each viewer on the same
8 side. The app declares its flags in `flags.json` at the root of its
9 repository (the app template has an empty one):
10
11 ```json
12 { "flags": { "new-header": { "why": "the shorter header", "default": false } } }
13 ```
14
15 A repository's admin sets each flag's value on **Settings → App → Feature
16 flags** (page: `src/web/pages/app_flags.ts`), or in the terminal on the
17 repository's **Feature flags** screen (`src/tui/screens/appflags.ts`: `o` on,
18 `f` off, `c` clear; percentages and named viewers are set on the page), through
19 the API (`PUT /api/v1/repos/<owner>/<name>/flags/<flag>` with `forge`, `users`,
20 `roles`, `percent`; every field empty clears) or the MCP `app_flags` tool
21 (`list`, `set`): all four go through `setAppFlag` (`src/actions/app_flags.ts`).
22 The page lists each flag with its value; a row opens that flag's form. A
23 value is the forge's own shape: `everyone` on or off, listed viewer ids,
24 roles, and a percentage. A listed viewer or role is on, then the percentage,
25 then `everyone`, then the default. A percentage is a hash of the flag and the
26 viewer's id, so a viewer stays on one side as it grows.
27
28 The running app is told `FORGE_FLAGS_URL`
29 (`/api/v1/repos/<owner>/<name>/flags`), which answers `{ flags: [{ name, why,
30 default, value }] }` to whoever may read the repository, and sends the app's
31 `FORGE_TOKEN` along. The URL is the forge's own origin, which a cell always
32 reaches (`origins` in `src/apps/egress.ts`), so the app's `forge.json` `egress`
33 stays `[]`. A viewer's ids a flag lists are shown only to the repository's
34 admin; everyone else gets the percent, roles and forge fields, and a private
35 repository answers 404 to a viewer who cannot read it. The declarations are
36 parsed once per `flags.json` blob, not per request. The template's `src/flags.ts` is the whole client: no
37 dependencies, `createFlags().flag("new-header", { id: viewerId })` answers at
38 once from the last list fetched (refetched in the background every 30
39 seconds, the last good list kept when the forge is unreachable; off until the
40 first fetch). Copy that one file into any other app.
41
42 Not yet: the 7 and 30 day read-out the forge's own flags show. The app's
43 reads happen in the app, so counting them needs the client to report back.
scripts/doorless-allow.json +1
@@ -1,6 +1,7 @@
11 [
22 "src/web/pages/accounts.ts",
33 "src/web/pages/admin-limits.ts",
4 "src/web/pages/app_flag_edit.ts",
45 "src/web/pages/app_variants.ts",
56 "src/web/pages/apps-starters.ts",
67 "src/web/pages/apps.ts",
src/actions/app_flags.ts added +95
@@ -0,0 +1,95 @@
1 /**

The comment claims a gate for the API and the MCP, but neither writes through it. Add both doors, or correct the comment.

2 * An app's feature flags (#1830): the declarations read from `flags.json` in
3 * its repository, the values its admins set, one gate for the settings page,
4 * the API, the MCP and the terminal: each calls `setAppFlag`. Reading what the app is served
5 * (`servedFlags`) needs only read access; setting needs admin, and a
6 * non-admin is told `not_found` like every settings door.
7 */
8
9 import type { App } from "../app.ts";
10 import { FLAGS_FILE, parseDecls, type AppFlagDecl, readValues, rowsOf, writeValue, type AppFlagRow } from "../core/app_flags.ts";
11 import { checkInput, type FlagInput } from "../core/flags.ts";
12 import type { Repo } from "../core/repos.ts";
13 import type { User } from "../core/users.ts";
14 import { readerFor } from "../git/read.ts";
15 import type { FlagValue } from "../core/flags.ts";
16 import { repoDir } from "../git/repos.ts";
17 import { err, ok, type Result } from "../kernel/result.ts";
18 import { requireRepoAdmin } from "./access.ts";
19
20 const FILE_MAX = 65_536;
21
22 /**
23 * Parsed declarations by the flags file's blob id: a blob never changes, so no entry goes stale.
24 */
25 const declsByApp = new WeakMap<App, Map<string, Record<string, AppFlagDecl>>>();
26 const DECLS_KEPT = 500;
27
28 const declsOfApp = (app: App): Map<string, Record<string, AppFlagDecl>> => {
29 let held = declsByApp.get(app);
30 if (held === undefined) declsByApp.set(app, (held = new Map()));
31 return held;
32 };
33
34 async function declsOf(app: App, repo: Repo): Promise<Record<string, AppFlagDecl>> {
35 const reader = readerFor(repoDir(app.reposRoot, repo.ownerName, repo.name));
36 const stat = await reader.stat(`HEAD:${FLAGS_FILE}`);
37 if (!stat.ok || stat.value.type !== "blob") return {};
38 const byBlob = declsOfApp(app);
39 const kept = byBlob.get(stat.value.oid);
40 if (kept) return kept;
41 const file = await reader.object(`HEAD:${FLAGS_FILE}`);
42 const text = file.ok && file.value.type === "blob" ? new TextDecoder().decode(file.value.body.slice(0, FILE_MAX)) : undefined;
43 const decls = parseDecls(text);
44 if (byBlob.size >= DECLS_KEPT) byBlob.clear();
45 byBlob.set(stat.value.oid, decls);
46 return decls;
47 }
48
49 /** The declared flags with their values; the caller has checked who may see them. */
50 export async function servedFlags(app: App, repo: Repo): Promise<AppFlagRow[]> {
51 return rowsOf(await declsOf(app, repo), readValues(app.db, repo.id));
52 }
53
54 /**
55 * What a reader who is not the repository's admin is told: the viewer ids a flag lists are
56 * personal data, so they stay with the admin; the percent, roles and forge fields are rules.
57 */
58 export function withoutViewers(v: FlagValue | undefined): Omit<FlagValue, "users"> | null {
59 if (v === undefined) return null;
60 const { users: _users, ...rest } = v;
61 return rest;
62 }
63
64 /** The same rows for a repository's admin. */
65 export async function appFlagRows(app: App, actor: User | undefined, repo: Repo): Promise<Result<AppFlagRow[], "not_found">> {
66 const gate = requireRepoAdmin(app, actor, repo);
67 if (!gate.ok) return gate;
68 return ok(await servedFlags(app, repo));
69 }
70
71 export type SetFlagError = "not_found" | { message: string };
72
73 /** Set (or, with every field empty, clear) one declared flag's value. */
74 export async function setAppFlag(
75 app: App,
76 actor: User | undefined,
77 repo: Repo,
78 name: string,
79 input: FlagInput,
80 ): Promise<Result<AppFlagRow[], SetFlagError>> {
81 const gate = requireRepoAdmin(app, actor, repo);
82 if (!gate.ok) return gate;
83 const rows = await servedFlags(app, repo);
84 if (!rows.some((r) => r.name === name)) return err({ message: `"${name.slice(0, 48)}" is not declared in ${FLAGS_FILE}.` });
85 const checked = checkInput(input);
86 if (!checked.ok) return err({ message: checked.message });
87 writeValue(app.db, repo.id, name, checked.value, gate.value.id);
88 app.bus.append({
89 kind: "app.flag_set",
90 repoId: repo.id,
91 actorId: gate.value.id,
92 payload: { name, value: checked.value ?? null },
93 });
94 return ok(await servedFlags(app, repo));
95 }
src/apps/process.ts +2
@@ -235,6 +235,8 @@ export function appEnv(input: {
235235 : {}),
236236 FORGE_URL: input.forgeUrl,
237237 FORGE_API_URL: forgeApiUrl(input.forgeUrl),
238 // Where the app reads its feature flags (#1830): `src/flags.ts` in the template.
239 ...(input.repo === undefined ? {} : { FORGE_FLAGS_URL: `${forgeApiUrl(input.forgeUrl)}/repos/${input.repo}/flags` }),
238240 FORGE_APP_IDENTITY_KEY: input.identityKey,
239241 // Read-only, the owner's, gone when this process is: what a page
240242 // inside the app reads the forge with. Never sent to a browser.
src/contract/openapi/routes/getApiV1ReposOwnerNameFlags.ts added +3
@@ -0,0 +1,3 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = { method: "get", path: `${REPO}/flags`, summary: "Read the app's feature flags and their values", detail: "The flags the repository's flags.json declares, each with why, default and the value its admin set (or null); an app reads this at FORGE_FLAGS_URL; answers { flags }; the viewer ids a flag lists are shown to the repository admin only", auth: false, role: "anonymous", refuses: [404] };
src/contract/openapi/routes/index.ts +2
@@ -169,6 +169,7 @@ export { route as getApiV1ReposOwnerNameDropFile } from "./getApiV1ReposOwnerNam
169169 export { route as getApiV1ReposOwnerNameEgressGrants } from "./getApiV1ReposOwnerNameEgressGrants.ts";
170170 export { route as getApiV1ReposOwnerNameEvents } from "./getApiV1ReposOwnerNameEvents.ts";
171171 export { route as getApiV1ReposOwnerNameFamily } from "./getApiV1ReposOwnerNameFamily.ts";
172 export { route as getApiV1ReposOwnerNameFlags } from "./getApiV1ReposOwnerNameFlags.ts";
172173 export { route as getApiV1ReposOwnerNameFlow } from "./getApiV1ReposOwnerNameFlow.ts";
173174 export { route as getApiV1ReposOwnerNameFollowing } from "./getApiV1ReposOwnerNameFollowing.ts";
174175 export { route as getApiV1ReposOwnerNameFollowingProposals } from "./getApiV1ReposOwnerNameFollowingProposals.ts";
@@ -482,6 +483,7 @@ export { route as putApiV1ReposOwnerNameAppEnvVar } from "./putApiV1ReposOwnerNa
482483 export { route as putApiV1ReposOwnerNameAppMembers } from "./putApiV1ReposOwnerNameAppMembers.ts";
483484 export { route as putApiV1ReposOwnerNameCrewUsername } from "./putApiV1ReposOwnerNameCrewUsername.ts";
484485 export { route as putApiV1ReposOwnerNameDisplayBuilds } from "./putApiV1ReposOwnerNameDisplayBuilds.ts";
486 export { route as putApiV1ReposOwnerNameFlagsFlag } from "./putApiV1ReposOwnerNameFlagsFlag.ts";
485487 export { route as putApiV1ReposOwnerNameIssuesNumberAssignee } from "./putApiV1ReposOwnerNameIssuesNumberAssignee.ts";
486488 export { route as putApiV1ReposOwnerNameIssuesNumberLabels } from "./putApiV1ReposOwnerNameIssuesNumberLabels.ts";
487489 export { route as putApiV1ReposOwnerNameIssuesNumberPlan } from "./putApiV1ReposOwnerNameIssuesNumberPlan.ts";
src/contract/openapi/routes/putApiV1ReposOwnerNameFlagsFlag.ts added +12
@@ -0,0 +1,12 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "put",
5 path: `${REPO}/flags/{flag}`,
6 summary: "Set an app's feature flag",
7 detail: "Set one flag the repository's flags.json declares (admin scope); every field empty clears it; forge is on, off or empty, users and roles lists of names, percent 0 to 100; answers { flags }",
8 auth: true,
9 role: "member",
10 body: { forge: "string", users: "string", roles: "string", percent: "string" },
11 refuses: [401, 404],
12 };
src/core/account_purge.ts +1
@@ -60,6 +60,7 @@ export const COVERED: Readonly<Record<string, Coverage>> = {
6060 "admin_ask.answered_by": FORMER,
6161 "app_feature.absorbed_by": FORMER,
6262 "app_feature_setting.set_by": FORMER,
63 "app_flag.updated_by": FORMER,
6364 "bet.backed_by": FORMER,
6465 "check_proven.proven_by": FORMER,
6566 "check_runner.created_by": FORMER,
src/core/app_flags.ts added +76
@@ -0,0 +1,76 @@
1 /**
2 * An app's feature flags (#1830). The app declares them in `flags.json` at
3 * the root of its repository,
4 * { "flags": { "new-header": { "why": "the shorter header", "default": false } } }
5 * its owner sets values from the app's settings (rows in `app_flag`, the same
6 * `FlagValue` the forge's own flags use), and `GET …/flags` hands the app the
7 * declarations with the values; the one-file client in the template evaluates
8 * them with the same stable per-viewer bucket (`core/flags.ts`). Pure data: no
9 * authz, no events.
10 */
11
12 import type { Database } from "bun:sqlite";
13 import { parseValue, type FlagValue } from "./flags.ts";
14
15 export type AppFlagDecl = { why: string; default: boolean };
16
17 export const FLAGS_FILE = "flags.json";
18 export const MAX_FLAGS = 100;
19 /** A flag name: lower case, digits, dashes and underscores; it is a URL and a column. */
20 export const NAME = /^[a-z][a-z0-9_-]{0,47}$/;
21
22 /** Parse `flags.json`; what is not a valid declaration is left out, never a throw. */
23 export function parseDecls(text: string | undefined): Record<string, AppFlagDecl> {
24 const out: Record<string, AppFlagDecl> = {};
25 if (text === undefined) return out;
26 let data: unknown;
27 try {
28 data = JSON.parse(text);
29 } catch {
30 return out;
31 }
32 const flags = (data as { flags?: unknown } | null)?.flags;
33 if (typeof flags !== "object" || flags === null || Array.isArray(flags)) return out;
34 for (const [name, raw] of Object.entries(flags).slice(0, MAX_FLAGS)) {
35 if (!NAME.test(name) || typeof raw !== "object" || raw === null) continue;
36 const d = raw as Record<string, unknown>;
37 out[name] = {
38 why: typeof d["why"] === "string" ? d["why"].slice(0, 200) : "",
39 default: d["default"] === true,
40 };
41 }
42 return out;
43 }
44
45 /** The stored values of a repository's flags. */
46 export function readValues(db: Database, repoId: string): Map<string, FlagValue> {
47 const out = new Map<string, FlagValue>();
48 const rows = db
49 .query<{ name: string; value: string }, [string]>("SELECT name, value FROM app_flag WHERE repo_id = ?1")
50 .all(repoId);
51 for (const r of rows) {
52 const v = parseValue(r.value);
53 if (v !== undefined) out.set(r.name, v);
54 }
55 return out;
56 }
57
58 /** Store a value (`undefined` clears it). The caller has checked the name is declared. */
59 export function writeValue(db: Database, repoId: string, name: string, value: FlagValue | undefined, actorId: string): void {
60 if (value === undefined) {
61 db.query("DELETE FROM app_flag WHERE repo_id = ?1 AND name = ?2").run(repoId, name);
62 return;
63 }
64 db.query(
65 `INSERT INTO app_flag (repo_id, name, value, updated_by, updated_at) VALUES (?1, ?2, ?3, ?4, ?5)
66 ON CONFLICT (repo_id, name) DO UPDATE SET value = excluded.value,
67 updated_by = excluded.updated_by, updated_at = excluded.updated_at`,
68 ).run(repoId, name, JSON.stringify(value), actorId, new Date().toISOString());
69 }
70
71 export type AppFlagRow = AppFlagDecl & { name: string; value: FlagValue | undefined };
72
73 /** Every declared flag with its stored value, in declaration order. */
74 export function rowsOf(decls: Record<string, AppFlagDecl>, values: Map<string, FlagValue>): AppFlagRow[] {
75 return Object.entries(decls).map(([name, d]) => ({ name, ...d, value: values.get(name) }));
76 }
src/core/migration-pins/20261130100000-app-flag.pin added +1
@@ -0,0 +1,1 @@
1 a81087320a9a23ec2a2450761c7adba53598f0dad2d9bf944eddff341cc1d3f5
src/core/migrations/20261130100000-app-flag.ts added +12
@@ -0,0 +1,12 @@
1 // An app's feature flag values (#1830): one row per repository and declared flag,
2 // the JSON of a `FlagValue` (core/flags.ts). Additive.
3 export default `
4 CREATE TABLE app_flag (
5 repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE,
6 name TEXT NOT NULL,
7 value TEXT NOT NULL,
8 updated_by TEXT NOT NULL,
9 updated_at TEXT NOT NULL,
10 PRIMARY KEY (repo_id, name)
11 ) WITHOUT ROWID;
12 `;
src/http/api/app.ts +41 −1
@@ -8,12 +8,13 @@
88
99 import { readAppMembers, setAppMembersThrough, type AppMembersError } from "../../actions/app_members.ts";
1010 import { appView, appVisitors, deleteAppEnvVar, disableApp, enableApp, listAppEnv, openEnvUrl, redeployEnv, setAppEnvVar, stopEnv, updateAppSettings, type AppSettingsInput } from "../../actions/apps.ts";
11 import { servedFlags, setAppFlag, withoutViewers } from "../../actions/app_flags.ts";
1112 import { pullNow, PULL_NOW_REFUSALS } from "../../actions/app_pull.ts";
1213 import { addAppDomain, claimAppDomain, claimProofRecord, checkAppDomain, keepOldRecords, listAppDomains, removeAppDomain } from "../../actions/domains.ts";
1314 import { previewBuild, previewBuildRefusalText } from "../../actions/build_preview.ts";
1415 import { SETTING_WORDS } from "../../actions/setting_words.ts";
1516 import { appsRuntime } from "../../apps/runtime.ts";
16 import { canRead, getRepo } from "../../core/repos.ts";
17 import { canAdmin, canRead, getRepo } from "../../core/repos.ts";
1718 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
1819 import type { Result } from "../../kernel/result.ts";
1920 import { appJson, appLimitResponse, loadRepo } from "../api.ts";
@@ -26,6 +27,14 @@ import { getAppByRepo } from "../../core/apps.ts";
2627 import { normalizeHost } from "../../core/domains.ts";
2728 import type { Router } from "../router.ts";
2829
30 /** A flag field as the form's text: a string, a number, or a list of strings joined by commas. */
31 function flagText(v: unknown): string {
32 if (typeof v === "string") return v;
33 if (typeof v === "number") return String(v);
34 if (Array.isArray(v)) return v.filter((x): x is string => typeof x === "string").join(",");
35 return "";
36 }
37
2938 function appPatch(input: Record<string, unknown>): AppSettingsInput {
3039 return {
3140 ...(typeof input.slug === "string" ? { slug: input.slug } : {}),
@@ -67,6 +76,37 @@ function tagged(ctx: Ctx, data: unknown): Response {
6776 }
6877
6978 export function appRoutes(router: Router<Handler>): void {
79 // What `FORGE_FLAGS_URL` names (#1830): the flags `flags.json` declares with the values set for
80 // them, for whoever may read the repository; the client in the template does the evaluating.
81 router.add("GET", "/api/v1/repos/:owner/:name/flags", async (ctx) => {
82 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
83 const repo = loadRepo(ctx);
84 if (!repo) return notFound();
85 const rows = await servedFlags(ctx.app, repo);
86 // The viewer ids a flag lists are personal data: only the repository's admin is told them.
87 const admin = ctx.auth.user !== undefined && canAdmin(ctx.app.db, repo, ctx.auth.user);
88 return tagged(ctx, {
89 flags: rows.map((r) => ({ name: r.name, why: r.why, default: r.default, value: admin ? (r.value ?? null) : withoutViewers(r.value) })),
90 });
91 });
92
93 // Set (or, with every field empty, clear) one declared flag: the settings page's own gate.
94 router.add("PUT", "/api/v1/repos/:owner/:name/flags/:flag", async (ctx) => {
95 const denied = requireScope(ctx, "admin");
96 if (denied) return denied;
97 const repo = loadRepo(ctx);
98 if (!repo) return notFound();
99 const input = await body(ctx.request);
100 const set = await setAppFlag(ctx.app, ctx.auth.user, repo, ctx.params.flag ?? "", {
101 forge: flagText(input.forge),
102 users: flagText(input.users),
103 roles: flagText(input.roles),
104 percent: flagText(input.percent),
105 });
106 if (!set.ok) return set.error === "not_found" ? notFound() : apiError("invalid", 422, set.error.message);
107 return json({ flags: set.value.map((r) => ({ name: r.name, why: r.why, default: r.default, value: r.value ?? null })) });
108 });
109
70110 router.add("GET", "/api/v1/repos/:owner/:name/app", (ctx) => {
71111 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
72112 const repo = loadRepo(ctx);
src/http/mcp/tools/app_flags.ts added +51
@@ -0,0 +1,51 @@
1 import { appFlagRows, setAppFlag } from "../../../actions/app_flags.ts";
2 import { scopeAllows } from "../../../core/tokens.ts";
3 import { bad, good, isAnswer, REPO_ARG, repoArg, type Tool } from "../shared.ts";
4
5 const text = (v: unknown): string =>
6 typeof v === "string" ? v : typeof v === "number" ? String(v) : Array.isArray(v) ? v.filter((x) => typeof x === "string").join(",") : "";
7
8 export const tool: Tool = {
9 name: "app_flags",
10 doc: "`{ repo, action, name?, forge?, users?, roles?, percent? }`: `list` the feature flags an app's `flags.json` declares with their values, or `set` one (every field empty clears it); `forge` is `on`, `off` or empty, `users` and `roles` comma lists, `percent` 0 to 100; an admin of the repository with an admin-scope token",
11 description: "An app's feature flags: list the declared flags with their values, or set one. Admin.",
12 inputSchema: {
13 type: "object",
14 properties: {
15 repo: REPO_ARG,
16 action: { type: "string", enum: ["list", "set"] },
17 name: { type: "string" },
18 forge: { type: "string", enum: ["", "on", "off"] },
19 users: { type: "string" },
20 roles: { type: "string" },
21 percent: { type: "string" },
22 },
23 required: ["repo", "action"],
24 },
25 writes: true,
26 heldNotWhen: (args) => args["action"] === "list",
27 async run(ctx, user, args) {
28 if (!scopeAllows(ctx.auth.scope ?? "ro", "admin")) return bad("forbidden", "an app's flags need an admin-scope token");
29 const repo = repoArg(ctx, user, args);
30 if (isAnswer(repo)) return repo;
31 const action = args["action"];
32 const view = (rows: { name: string; why: string; default: boolean; value: unknown }[]) =>
33 good({ flags: rows.map((r) => ({ name: r.name, why: r.why, default: r.default, value: r.value ?? null })) });
34 if (action === "list") {
35 const rows = await appFlagRows(ctx.app, user, repo);
36 return rows.ok ? view(rows.value) : bad("not_found", "no such app or repository (owner/name)");
37 }
38 if (action === "set") {
39 const name = typeof args["name"] === "string" ? args["name"] : "";
40 const set = await setAppFlag(ctx.app, user, repo, name, {
41 forge: text(args["forge"]),
42 users: text(args["users"]),
43 roles: text(args["roles"]),
44 percent: text(args["percent"]),
45 });
46 if (set.ok) return view(set.value);
47 return set.error === "not_found" ? bad("not_found", "no such app or repository (owner/name)") : bad("invalid", set.error.message);
48 }
49 return bad("invalid", "`action` is list or set");
50 },
51 };
src/http/mcp/tools/index.ts +1
@@ -14,6 +14,7 @@ export { tool as app_data_import } from "./app_data_import.ts";
1414 export { tool as app_deploy } from "./app_deploy.ts";
1515 export { tool as app_domains } from "./app_domains.ts";
1616 export { tool as app_env } from "./app_env.ts";
17 export { tool as app_flags } from "./app_flags.ts";
1718 export { tool as app_members } from "./app_members.ts";
1819 export { tool as app_notes } from "./app_notes.ts";
1920 export { tool as apps } from "./apps.ts";
src/http/server.ts +4
@@ -16,6 +16,8 @@ import { answeringFor, ControlInput, controlRefusal, dirtyUrl, parseableRequest
1616 import { expireCookie } from "../auth/cookies.ts";
1717 import { checkText } from "./check_text.ts";
1818 import { noteOwnWrite } from "../flow/keep.ts";
19 import { appFlagSet } from "../web/pages/app_flags.ts";
20 import { appFlagEditPage } from "../web/pages/app_flag_edit.ts";
1921 import { appSecretGrant, appSecretRevoke } from "../web/pages/app_secrets.ts";
2022 import { apiRoot } from "./api_root.ts";
2123 import { isTokenScheme, tokenSecret } from "./token_header.ts";
@@ -1885,6 +1887,8 @@ export function buildRouter(): Router<Handler> {
18851887 router.add("POST", "/:owner/:name/settings/app/disable", appDisable);
18861888 router.add("POST", "/:owner/:name/settings/app/members", appMembersUpdate);
18871889 router.add("POST", "/:owner/:name/settings/app/env", appEnvSet);
1890 router.add("POST", "/:owner/:name/settings/app/flags", appFlagSet);
1891 router.add("GET", "/:owner/:name/settings/app/flags/:flag", appFlagEditPage);
18881892 router.add("POST", "/:owner/:name/settings/app/secrets/grant", appSecretGrant);
18891893 router.add("POST", "/:owner/:name/settings/app/secrets/revoke", appSecretRevoke);
18901894 router.add(
src/tui/screens/appflags.ts added +94
@@ -0,0 +1,94 @@
1 /**
2 * An app's feature flags in the terminal (#1830): each flag its `flags.json`
3 * declares and what is set for it. `o` turns one on for everyone, `f` off,
4 * `c` clears it, through `setAppFlag`, the same gate and the same words as
5 * the settings page. Percentages and named viewers are set on the page.
6 */
7
8 import { appFlagRows, setAppFlag } from "../../actions/app_flags.ts";
9 import type { AppFlagRow } from "../../core/app_flags.ts";
10 import { getAppByRepo } from "../../core/apps.ts";
11 import { canAdmin, type Repo } from "../../core/repos.ts";
12 import { flagSummary } from "../../web/pages/app_flags.ts";
13 import type { Ctx, Screen } from "../app/app.ts";
14 import { binding } from "../app/keys.ts";
15 import type { Command } from "../app/palette.ts";
16 import type { Session } from "../session.ts";
17 import { style } from "../term/style.ts";
18 import { wrap } from "../term/width.ts";
19 import { fill, len, split } from "../ui/layout.ts";
20 import { ListState, drawList, runAsync, type ListRow } from "./common.ts";
21
22 /** The palette's "Feature flags", for an admin of a repository that is an app. */
23 export function appFlagCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] {
24 if (repo === undefined || f.user === undefined) return [];
25 if (getAppByRepo(f.app.db, repo.id) === undefined || !canAdmin(f.app.db, repo, f.user)) return [];
26 return [
27 {
28 id: "app-flags",
29 title: `${repo.ownerName}/${repo.name} — Feature flags`,
30 hint: "o on, f off, c clear",
31 run: () => ctx.push(appFlagsScreen(f, ctx, repo)),
32 },
33 ];
34 }
35
36 export function appFlagsScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
37 const state = new ListState();
38 let rows: AppFlagRow[] = [];
39 let readable = false;
40 let note = "";
41 const load = (): void => {
42 runAsync(ctx, async () => {
43 const got = await appFlagRows(f.app, f.user, repo);
44 readable = got.ok;
45 rows = got.ok ? got.value : [];
46 state.clamp(rows.length);
47 ctx.invalidate();
48 });
49 };
50 load();
51 const put = (name: string, forge: string): void => {
52 runAsync(ctx, async () => {
53 const done = await setAppFlag(f.app, f.user, repo, name, { forge, users: "", roles: "", percent: "" });
54 note = done.ok ? `${name} is saved.` : done.error === "not_found" ? "An app's flags are its admin's." : done.error.message;
55 if (done.ok) rows = done.value;
56 ctx.invalidate();
57 });
58 };
59
60 const screen: Screen = {
61 title: "Feature flags",
62 get keys() {
63 return [binding(["o"], "on"), binding(["f"], "off"), binding(["c"], "clear"), binding(["j", "k"], "move cursor")];
64 },
65 render(area, s) {
66 const c = ctx.theme.c;
67 const text =
68 note !== ""
69 ? note
70 : !readable
71 ? "An app's flags are its admin's."
72 : rows.length === 0
73 ? "No flag is declared: add a flags.json to the repository."
74 : `${rows.length} for ${repo.ownerName}/${repo.name}.`;
75 const said = wrap(text, Math.max(1, area.w)).slice(0, 3);
76 const [head, list] = split(area, "v", [len(said.length), fill(1)]);
77 said.forEach((line, i) => s.text(head!.x, head!.y + i, line, style(c.mutedFg, c.bg), head!.x + head!.w));
78 const lines: ListRow[] = rows.map((r) => ({ title: r.name, meta: `default ${r.default ? "on" : "off"} · ${flagSummary(r.value)}` }));
79 drawList(s, list!, c, state, lines);
80 },
81 key(e) {
82 if (state.key(e, rows.length)) return true;
83 if (e.ctrl || e.alt || !readable) return false;
84 const row = rows[state.index];
85 if (row === undefined) return false;
86 if (e.key === "o" || e.key === "f" || e.key === "c") {
87 put(row.name, e.key === "o" ? "on" : e.key === "f" ? "off" : "");
88 return true;
89 }
90 return false;
91 },
92 };
93 return screen;
94 }
src/tui/screens/workspace.ts +2
@@ -208,6 +208,7 @@ import { iterationsCommands } from "./iterations.ts";
208208 import { labelsCommands } from "./labels.ts";
209209 import { appEnvCommands } from "./appenv.ts";
210210 import { appSecretCommands } from "./appsecrets.ts";
211 import { appFlagCommands } from "./appflags.ts";
211212 import { appBackupCommands } from "./appbackup.ts";
212213 import { variantsCommands } from "./variants.ts";
213214 import { autonomyCommands } from "./autonomy.ts";
@@ -2439,6 +2440,7 @@ export function workspaceScreen(
24392440 ...displayCommands(f, ctx, repo),
24402441 ...appEnvCommands(f, ctx, repo),
24412442 ...appSecretCommands(f, ctx, repo),
2443 ...appFlagCommands(f, ctx, repo),
24422444 ...appBackupCommands(f, ctx, repo),
24432445 ...variantsCommands(f, ctx, repo),
24442446 ...autonomyCommands(f, ctx, repo),
src/web/pages/app_flag_edit.ts added +40
@@ -0,0 +1,40 @@
1 /**
2 * GET /:owner/:name/settings/app/flags/:flag: one feature flag's value, edited (#1830). The
3 * form posts to the same door as the list (`app_flags.ts`); only the repository's admin sees it.
4 */
5
6 import { servedFlags } from "../../actions/app_flags.ts";
7 import type { Ctx } from "../../http/context.ts";
8 import { loadAdminRepo } from "../admin_form.ts";
9 import { repoBase, repoNotFound } from "../chrome.ts";
10 import { html } from "../html.ts";
11 import { btn } from "../ui.ts";
12 import { flagSummary } from "./app_flags.ts";
13 import { settingsPageResponse } from "./settings.ts";
14
15 export async function appFlagEditPage(ctx: Ctx): Promise<Response> {
16 const repo = loadAdminRepo(ctx);
17 if (!repo) return repoNotFound(ctx);
18 const f = (await servedFlags(ctx.app, repo)).find((r) => r.name === ctx.params.flag);
19 if (!f) return repoNotFound(ctx);
20 const base = repoBase(repo);
21 const v = f.value;
22 const body = html`<section class="settings-block">
23 <h2><span class="mono">${f.name}</span></h2>
24 <p class="muted small">${f.why === "" ? "" : `${f.why}. `}Default ${f.default ? "on" : "off"}; now ${flagSummary(v)}.</p>
25 <form class="row-fields" method="post" action="${base}/settings/app/flags">
26 <input type="hidden" name="name" value="${f.name}" />
27 <select class="input" name="forge" aria-label="Everyone">
28 <option value="" ${v?.forge === undefined ? "selected" : ""}>everyone: default</option>
29 <option value="on" ${v?.forge === true ? "selected" : ""}>everyone: on</option>
30 <option value="off" ${v?.forge === false ? "selected" : ""}>everyone: off</option>
31 </select>
32 <input class="input mono" name="users" placeholder="viewer ids" value="${(v?.users ?? []).join(", ")}" aria-label="Viewer ids" />
33 <input class="input mono" name="roles" placeholder="roles" value="${(v?.roles ?? []).join(", ")}" aria-label="Roles" />
34 <input class="input mono" name="percent" placeholder="%" size="3" value="${v?.percent === undefined ? "" : String(v.percent)}" aria-label="Percent" />
35 ${btn("Save", { size: "sm", label: `Save ${f.name}` })}
36 </form>
37 <p class="muted small mt">Empty fields and Save clear the value. <a href="${base}/settings/app#flags">Back to the flags</a></p>
38 </section>`;
39 return settingsPageResponse(ctx, repo, "app", f.name, body);
40 }
src/web/pages/app_flags.ts added +67
@@ -0,0 +1,67 @@
1 /**
2 * An app's feature flags, as its settings say them (#1830): each flag its
3 * `flags.json` declares, with the value its admin sets: the app's whole
4 * audience on or off, named people, a percentage that stays with a viewer.
5 */
6
7 import { setAppFlag } from "../../actions/app_flags.ts";
8 import { FLAGS_FILE, type AppFlagRow } from "../../core/app_flags.ts";
9 import type { Ctx } from "../../http/context.ts";
10 import { adminForm } from "../admin_form.ts";
11 import { repoBase } from "../chrome.ts";
12 import { field } from "../form.ts";
13 import { html, type Html } from "../html.ts";
14 import { flashTo } from "../layout.ts";
15 import { row, rowList } from "../ui.ts";
16
17 /** One line of what is set. */
18 export function flagSummary(v: AppFlagRow["value"]): string {
19 if (v === undefined) return "not set";
20 return [
21 v.forge === undefined ? "" : `everyone ${v.forge ? "on" : "off"}`,
22 v.users ? `${v.users.length} person(s)` : "",
23 v.roles ? `roles ${v.roles.join(", ")}` : "",
24 v.percent === undefined ? "" : `${v.percent}%`,
25 ]

Principle 2: the activity icon on each row says nothing and costs a column. Drop it, or let the live value be the visual. Run bun scripts/design-lint.ts and put its output in the pull.

26 .filter((x) => x !== "")
27 .join(" · ");
28 }
29
30 export function appFlagsView(base: string, rows: readonly AppFlagRow[]): Html {
31 const items = rows.map((f) =>
outdated

Principle 7 and Principle 3: every row carries a hand-rolled form with a select, three inputs and a button inside the row's trail, plus a <br /> in the meta. That is a form crammed into a row, not a row. Show name, default and live value as the row, and put the edit controls behind a link to a per-flag edit page, or use an existing named component. Check row-fields against docs/design/areas and docs/DESIGN.md, and move any new class into its area file.

32 row({
33 href: `${base}/settings/app/flags/${encodeURIComponent(f.name)}`,
34 title: html`<span class="mono">${f.name}</span>`,
35 meta: html`${f.why}`,
36 trail: html`<span class="small">${f.value === undefined ? `default ${f.default ? "on" : "off"}` : flagSummary(f.value)}</span>`,
37 }),
38 );
39 return html`<section class="settings-block" id="flags">
40 <h2>Feature flags</h2>
outdated

Principle 1 and Principle 8: the heading is followed by a sentence that explains the page twice (declared in flags.json, read at FORGE_FLAGS_URL, leave empty to clear). Cut it to one plain sentence. The how-to belongs in docs/features/app-flags.md.

41 <p class="muted small">Choose who sees each flag the app declares.</p>
42 ${items.length > 0
43 ? rowList(items, { bare: true })
44 : html`<p class="muted small">No flag is declared: add a <span class="mono">${FLAGS_FILE}</span> to the repository.</p>`}
45 </section>`;
46 }
47
48 /** POST /:owner/:name/settings/app/flags */
49 export async function appFlagSet(ctx: Ctx): Promise<Response> {
50 const gate = await adminForm(ctx);
51 if (gate instanceof Response) return gate;
52 const { repo, form } = gate;
53 const name = field(form, "name").trim();
54 const done = await setAppFlag(ctx.app, ctx.auth.user, repo, name, {
55 forge: field(form, "forge"),
56 users: field(form, "users"),
57 roles: field(form, "roles"),
58 percent: field(form, "percent"),
59 });
60 return flashTo(
61 ctx,
62 `${repoBase(repo)}/settings/app#flags`,
63 done.ok
64 ? { message: `${name} is saved: the app sees it at its next read.` }
65 : { tone: "danger", message: done.error === "not_found" ? "That app is not here." : done.error.message },
66 );
67 }
src/web/pages/settings.ts +6
@@ -99,6 +99,9 @@ import { settingsLead, teamJs } from "../studio/crew.ts";
9999 import { pageTitle } from "../studio/nouns.ts";
100100 import { appHref } from "./apps.ts";
101101 import { appSecretsView } from "./app_secrets.ts";
102 import { appFlagsView } from "./app_flags.ts";
103 import { servedFlags } from "../../actions/app_flags.ts";
104 import type { AppFlagRow } from "../../core/app_flags.ts";
102105 import { appSecretNeeds } from "../../actions/secrets.ts";
103106 import type { NeedRow } from "../../core/app_secrets.ts";
104107 import { field } from "../form.ts";
@@ -734,6 +737,7 @@ function appSettingsView(
734737 blocked?: BlockedView,
735738 needs?: { needs: readonly NeedRow[]; grantable: { name: string; scope: "forge" | "org" }[] },
736739 templateWhy?: string,
740 flags?: readonly AppFlagRow[],
737741 ): Html {
738742 const base = repoBase(repo);
739743 const runtime = appsRuntime(ctx.app);
@@ -852,6 +856,7 @@ function appSettingsView(
852856 <div class="mt">
853857 ${appEnvView(base, (() => { const l = listAppEnv(ctx.app, ctx.auth.user, repo); return l.ok ? l.value : []; })())}
854858 </div>
859 ${when(flags !== undefined, () => html`<div class="mt">${appFlagsView(base, flags!)}</div>`)}
855860 ${when(needs !== undefined, () => html`<div class="mt">${appSecretsView(base, needs!.needs, ctx.auth.user?.isAdmin === true, needs!.grantable)}</div>`)}
856861 <div class="mt">
857862 ${appDomainsView(base, domains.ok ? domains.value : undefined)}
@@ -1183,6 +1188,7 @@ export async function appSettingsPage(ctx: Ctx): Promise<Response> {
11831188 blocked?.ok ? blocked.value : undefined,
11841189 needs?.ok ? needs.value : undefined,
11851190 repo.template ? await templateProblem(ctx.app, repo) : undefined,
1191 record === undefined ? undefined : await servedFlags(ctx.app, repo),
11861192 );
11871193 const rendering = performance.now();
11881194 const response = settingsPageResponse(ctx, repo, "app", "App", view);
templates/app-template.json +3

Diff not shown — a line 25,347 characters wide (limit 2,000). +3

View file
test/app-flags.test.ts added +216
@@ -0,0 +1,216 @@
1 /**
2 * Feature flags for an app (#1830): flags.json declares, the settings page
3 * sets, `…/flags` (FORGE_FLAGS_URL) serves, the template's one-file client
4 * evaluates with the forge's own bucket, and a stranger sets nothing.
5 */
6
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm, writeFile } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { newApp } from "../src/actions/apps.ts";
13 import { commitToBranch } from "../src/actions/repos.ts";
14 import { appEnv } from "../src/apps/process.ts";
15 import { parseDecls } from "../src/core/app_flags.ts";
16 import { bucket } from "../src/core/flags.ts";
17 import { createToken } from "../src/core/tokens.ts";
18 import { createRepo } from "../src/actions/repos.ts";
19 import { createSession } from "../src/core/sessions.ts";
20 import { createUser, getUserById } from "../src/core/users.ts";
21 import { serve, type Servers } from "../src/http/server.ts";
22 import { quietLogs } from "./helpers/globals.ts";
23 import { seedAdmin } from "./helpers/admin.ts";
24
25 quietLogs();
26
27 test("a declaration keeps what is valid and drops the rest", () => {
28 const got = parseDecls(JSON.stringify({ flags: { "new-header": { why: "shorter", default: true }, "Bad Name": {}, ok: 3 } }));
29 expect(got).toEqual({ "new-header": { why: "shorter", default: true } });
30 expect(parseDecls("not json")).toEqual({});
31 expect(parseDecls(undefined)).toEqual({});
32 });
33
34 test("the app is told where its flags are", () => {
35 const env = appEnv({ port: 1, dataDir: "/d", env: "production", url: "http://a", commitOid: "abc", forgeUrl: "https://forge.test/", repo: "alice/budgeting", identityKey: "k" });
36 expect(env["FORGE_FLAGS_URL"]).toBe("https://forge.test/api/v1/repos/alice/budgeting/flags");
37 });
38
39 test("the template's client buckets exactly as the forge does", async () => {
40 const bundle = await Bun.file(join(import.meta.dir, "../templates/app-template.json")).json();
41 const dir = await mkdtemp(join(tmpdir(), "forge-flags-client-"));
42 try {
43 await writeFile(join(dir, "flags.ts"), bundle.files["src/flags.ts"]);
44 const client = await import(join(dir, "flags.ts"));
45 for (const id of ["u1", "u2", "alice", "z".repeat(40)]) expect(client.bucket("new-header", id)).toBe(bucket("new-header", id));
46 expect(bundle.files["flags.json"]).toContain('"flags"');
47 } finally {
48 await rm(dir, { recursive: true, force: true });
49 }
50 });
51
52 describe("flags on the app's settings page and over the API", () => {
53 let dataDir = "";
54 let app: App;
55 let servers: Servers;
56 let base = "";
57 let adminCookie = "";
58 let bobCookie = "";
59
60 const call = (cookie: string, path: string, form?: Record<string, string>): Promise<Response> =>
61 fetch(`${base}${path}`, {
62 method: form ? "POST" : "GET",
63 headers: { cookie, ...(form ? { origin: base } : {}) },
64 redirect: "manual",
65 ...(form ? { body: new URLSearchParams(form) } : {}),
66 });
67
68 beforeAll(async () => {
69 dataDir = await mkdtemp(join(tmpdir(), "forge-app-flags-"));
70 app = createApp({ dataDir, port: 0 });
71 servers = await serve(app);
72 base = servers.url;
73 const a = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "a-good-passphrase" });
74 if (!a.ok) throw new Error(a.error);
75 const o = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
76 if (!o.ok) throw new Error(o.error);
77 adminCookie = `forge_session=${createSession(app.db, a.value.id).token}`;
78 bobCookie = `forge_session=${createSession(app.db, o.value.id).token}`;
79 const made = await newApp(app, a.value, { name: "budgeting" });
80 if (!made.ok) throw new Error(made.error);
81 const files = await commitToBranch(app, a.value, made.value.repo, {
82 message: "Declare a flag",
83 files: [{ path: "flags.json", content: JSON.stringify({ flags: { "new-header": { why: "the shorter header", default: false } } }) }],
84 });
85 if (!files.ok) throw new Error(String(files.error));
86 });
87 afterAll(async () => {
88 servers.stop();
89 app.close();
90 await rm(dataDir, { recursive: true, force: true });
91 });
92
93 type Served = { flags: { name: string; why: string; default: boolean; value: unknown }[] };
94 const served = async (): Promise<Served> => {
95 const body = (await (await call(adminCookie, "/api/v1/repos/alice/budgeting/flags")).json()) as Served;
96 return body;
97 };
98
99 test("a declared flag is listed on the page and served with no value", async () => {
100 const page = await (await call(adminCookie, "/alice/budgeting/settings/app")).text();
101 expect(page).toContain("Feature flags");
102 expect(page).toContain("new-header");
103 expect(page).toContain("/alice/budgeting/settings/app/flags/new-header");
104 expect(page).not.toContain('name="percent"');
105 const edit = await call(adminCookie, "/alice/budgeting/settings/app/flags/new-header");
106 expect(edit.status).toBe(200);
107 expect(await edit.text()).toContain('name="percent"');
108 expect((await call(adminCookie, "/alice/budgeting/settings/app/flags/nope")).status).toBe(404);
109 expect((await call(bobCookie, "/alice/budgeting/settings/app/flags/new-header")).status).toBe(404);
110 expect((await served()).flags).toEqual([{ name: "new-header", why: "the shorter header", default: false, value: null }]);
111 });
112
113 test("an admin sets a value and the app is served it; a bad one is refused and changes nothing", async () => {
114 const set = await call(adminCookie, "/alice/budgeting/settings/app/flags", { name: "new-header", forge: "", users: "", roles: "", percent: "30" });
115 expect(set.status).toBe(303);
116 expect((await served()).flags[0]!.value).toEqual({ percent: 30 });
117 await call(adminCookie, "/alice/budgeting/settings/app/flags", { name: "new-header", forge: "on", users: "", roles: "", percent: "300" });
118 expect((await served()).flags[0]!.value).toEqual({ percent: 30 });
119 await call(adminCookie, "/alice/budgeting/settings/app/flags", { name: "undeclared", forge: "on", users: "", roles: "", percent: "" });
120 expect((await served()).flags.length).toBe(1);
121 await call(adminCookie, "/alice/budgeting/settings/app/flags", { name: "new-header", forge: "", users: "", roles: "", percent: "" });
122 expect((await served()).flags[0]!.value).toBeNull();
123 });
124
125 test("someone who does not administer the app sets nothing and is told nothing", async () => {
126 const refused = await call(bobCookie, "/alice/budgeting/settings/app/flags", { name: "new-header", forge: "on", users: "", roles: "", percent: "" });
127 expect(refused.status).toBe(404);
128 expect((await served()).flags[0]!.value).toBeNull();
129 const cross = await fetch(`${base}/alice/budgeting/settings/app/flags`, {
130 method: "POST",
131 headers: { cookie: adminCookie, origin: "https://evil.example" },
132 redirect: "manual",
133 body: new URLSearchParams({ name: "new-header", forge: "on", users: "", roles: "", percent: "" }),
134 });
135 expect(cross.status).not.toBe(303);
136 expect((await served()).flags[0]!.value).toBeNull();
137 });
138
139 const put = (cookie: string, path: string, body: unknown): Promise<Response> =>
140 fetch(`${base}${path}`, {
141 method: "PUT",
142 headers: { cookie, origin: base, "content-type": "application/json" },
143 body: JSON.stringify(body),
144 });
145
146 test("the API sets and clears a flag through the same gate; a stranger and a bad value change nothing", async () => {
147 const ok = await put(adminCookie, "/api/v1/repos/alice/budgeting/flags/new-header", { percent: 40, roles: ["author"] });
148 expect(ok.status).toBe(200);
149 expect(((await ok.json()) as Served).flags[0]!.value).toEqual({ roles: ["author"], percent: 40 });
150 expect((await put(adminCookie, "/api/v1/repos/alice/budgeting/flags/new-header", { percent: 400 })).status).toBe(422);
151 expect((await put(adminCookie, "/api/v1/repos/alice/budgeting/flags/nope", { forge: "on" })).status).toBe(422);
152 expect((await put(bobCookie, "/api/v1/repos/alice/budgeting/flags/new-header", { forge: "off" })).status).toBe(404);
153 expect((await served()).flags[0]!.value).toEqual({ roles: ["author"], percent: 40 });
154 await put(adminCookie, "/api/v1/repos/alice/budgeting/flags/new-header", {});
155 expect((await served()).flags[0]!.value).toBeNull();
156 });
157
158 /** A repository of alice's with one declared flag. */
159 const withFlag = async (name: string, visibility: "public" | "private"): Promise<void> => {
160 const row = app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'alice'").get()!;
161 const alice = getUserById(app.db, row.id)!;
162 const made = await createRepo(app, alice, { name, visibility });
163 if (!made.ok) throw new Error(String(made.error));
164 const files = await commitToBranch(app, alice, made.value, {
165 message: "Declare a flag",
166 files: [{ path: "flags.json", content: JSON.stringify({ flags: { hush: { why: "", default: true } } }) }],
167 });
168 if (!files.ok) throw new Error(String(files.error));
169 };
170
171 test("a reader who is not the admin is not told which viewers a flag lists", async () => {
172 await withFlag("open-app", "public");
173 const path = "/api/v1/repos/alice/open-app/flags";
174 expect((await put(adminCookie, `${path}/hush`, { users: "u-1, u-2", percent: 10 })).status).toBe(200);
175 const mine = (await (await call(adminCookie, path)).json()) as Served;
176 expect(mine.flags[0]!.value).toEqual({ users: ["u-1", "u-2"], percent: 10 });
177 const seen = (await (await call(bobCookie, path)).json()) as Served;
178 expect(seen.flags[0]!.value).toEqual({ percent: 10 });
179 expect(JSON.stringify(seen)).not.toContain("u-1");
180 expect(JSON.stringify(await (await fetch(`${base}${path}`)).json())).not.toContain("u-1");
181 });
182
183 test("the flags of a private repository answer 404 to a viewer who cannot read it", async () => {
184 await withFlag("secret-app", "private");
185 expect((await call(bobCookie, "/api/v1/repos/alice/secret-app/flags")).status).toBe(404);
186 expect((await fetch(`${base}/api/v1/repos/alice/secret-app/flags`)).status).toBe(404);
187 expect((await call(adminCookie, "/api/v1/repos/alice/secret-app/flags")).status).toBe(200);
188 });
189
190 test("the MCP tool lists and sets through the same gate and needs an admin-scope token", async () => {
191 const alice = app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'alice'").get()!;
192 const bob = app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'bob'").get()!;
193 const rpc = async (token: string, args: unknown) => {
194 const res = await fetch(`${base}/mcp`, {
195 method: "POST",
196 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
197 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "app_flags", arguments: args } }),
198 });
199 const body: any = await res.json();
200 return { error: body.result.isError === true, text: String(body.result.content[0].text) };
201 };
202 const admin = createToken(app.db, alice.id, "admin", "admin").token;
203 const rw = createToken(app.db, alice.id, "rw", "rw").token;
204 const bobAdmin = createToken(app.db, bob.id, "admin", "admin").token;
205 const set = await rpc(admin, { repo: "alice/budgeting", action: "set", name: "new-header", forge: "on" });
206 expect(set.error).toBe(false);
207 expect(JSON.parse(set.text).flags[0].value).toEqual({ forge: true });
208 expect(JSON.parse((await rpc(admin, { repo: "alice/budgeting", action: "list" })).text).flags[0].value).toEqual({ forge: true });
209 expect((await rpc(rw, { repo: "alice/budgeting", action: "set", name: "new-header", forge: "off" })).error).toBe(true);
210 expect((await rpc(bobAdmin, { repo: "alice/budgeting", action: "set", name: "new-header", forge: "off" })).error).toBe(true);
211 expect((await rpc(admin, { repo: "alice/budgeting", action: "set", name: "new-header", percent: "500" })).error).toBe(true);
212 expect((await served()).flags[0]!.value).toEqual({ forge: true });
213 await rpc(admin, { repo: "alice/budgeting", action: "set", name: "new-header" });
214 expect((await served()).flags[0]!.value).toBeNull();
215 });
216 });
test/conversation-confirm.test.ts +1 −1
@@ -123,7 +123,7 @@ describe("the one list of what asks first", () => {
123123 // settings and can be put back (`system` previews and does only on its own `confirm:true`). A new
124124 // `writes: true` tool is on neither list until someone decides.
125125 const NOT_ASKED = new Set([
126 "access", "account_requests", "apps", "account_verify", "app_members", "app_notes", "asks_act", "asks_decide", "asks_proposal", "asks_undecide", "atlas",
126 "access", "account_requests", "app_flags", "apps", "account_verify", "app_members", "app_notes", "asks_act", "asks_decide", "asks_proposal", "asks_undecide", "atlas",
127127 "asks", "assign", "attach_look", "bet", "board_pins", "board_write", "branches", "capacity", "valves", "cloud_accounts", "close", "confirm_wait",
128128 "crew", "decisions_by", "desk", "detach", "economics", "edit", "experiments", "email_verify", "estimate", "feed_chips", "feed_dismiss", "feed_like", "flag_set", "flag_winner",
129129 "follow_mode", "forge", "fork", "front_page", "hold", "issue_teams", "keep_plan", "knobs", "labels", "lift", "limb", "maintenance", "make_it_yours", "map", "merge", "new_app",
test/data-browser.test.ts +1
@@ -26,6 +26,7 @@ const AUDITED_CLEAR: string[] = [
2626 // A variable (not a secret) kept in the clear and shown; secrets are sealed in value_enc.
2727 "app_env.value_plain",
2828 "app_feature_setting.value",
29 "app_flag.value",
2930 "ask_filter.value",
3031 // Which hosted forge an ask or a grant is for (`core/child_reach.ts`): a spawn's body id, or `*`
3132 // for every one.
test/llms-budget.test.ts +3 −2
@@ -58,9 +58,10 @@ const get = async (token?: string): Promise<string> =>
5858 * bytes under 96,000, and four tools in flight (fetch_url, invite, bring, propose_upstream) each
5959 * add about 40 to 330 bytes to it. Only an agent with an admin token reads this text, and few do,
6060 * so the cost of the room is small. Raised to 98,500 for cut_wave (admin 98,345), then to 98,700
61 * for the allocation tool (#8718; admin 98,516).
61 * for the allocation tool (#8718; admin 98,516), then to 99,200 for the app_flags tool (#1830;
62 * admin 98,939).
6263 */
63 const BUDGET = { anonymous: 9_250, signedIn: 84_100, admin: 98_700 } as const;
64 const BUDGET = { anonymous: 9_250, signedIn: 84_100, admin: 99_200 } as const;
6465
6566 test("/llms.txt stays under its byte budget for each role", async () => {
6667 const sizes = {
test/mcp-forge-protocol.test.ts +1
@@ -287,6 +287,7 @@ describe("the forge over MCP: protocol", () => {
287287 "contribute",
288288 "limits",
289289 "app_env",
290 "app_flags",
290291 "agents", "app_data_import",
291292 "teams",
292293 "cloud_accounts",
test/mixed-actions-held.test.ts +1
@@ -51,6 +51,7 @@ const MIXED: Readonly<
5151 experiments: { key: "action", reads: [{ action: "list" }, { action: "show", id: "x" }] },
5252 pinned_forge: { key: "verb", reads: [{ verb: "list" }] },
5353 proposal_tokens: { key: "verb", reads: [{ verb: "list" }] },
54 app_flags: { key: "action", reads: [{ repo: "o/r", action: "list" }] },
5455 app_env: { key: "action", reads: [{ repo: "o/r", action: "list" }] },
5556 drop: { key: "action", reads: [{ repo: "o/r", action: "list" }] },
5657 origins: {
test/no-polling.test.ts +1
@@ -320,6 +320,7 @@ const NOT_WALKED: Record<string, string> = {
320320 "/:owner/:name/machines/:machine/shell": "needs a running machine to attach a terminal to",
321321 "/:owner/:name/milestones/:number/limb/:op": "needs a milestone with a limb",
322322 "/:owner/:name/runs/:id": "the seed creates no run",
323 "/:owner/:name/settings/app/flags/:flag": "needs an app whose flags.json declares a flag",
323324 "/:owner/:name/variants/:group": "needs a variant group of agent tries",
324325 "/:owner/:name/waves/:version": "needs a wave of a milestone",
325326 "/boards/:slug": "needs a board",
test/open-routes-floor.test.ts +1 −1
@@ -41,7 +41,7 @@ const FILL: Readonly<Record<string, string>> = {
4141 ref: "main", branch: "main", oid: "0".repeat(40), sha: "0".repeat(40), commit: "0".repeat(40),
4242 // Not seeded: each still has to answer its not-found with the floor.
4343 team: "core", env: "prod", file: "README.md", label: "v1", chapter: "1", kind: "desktop", machine: "web",
44 range: `${"0".repeat(40)}...${"1".repeat(40)}`, op: "x", step: "1", group: "a", version: "1", slug: "board", receipt: "r", token: "t", code: "c", spec: "16", stage: "build", walk: "1",
44 range: `${"0".repeat(40)}...${"1".repeat(40)}`, op: "x", step: "1", group: "a", version: "1", slug: "board", receipt: "r", token: "t", code: "c", spec: "16", stage: "build", walk: "1", flag: "x",
4545 };
4646
4747 /** Open GET routes that cannot be filled in from a seeded public repository, each with why. */
test/pages-budget.test.ts +1 −1
@@ -70,7 +70,7 @@ const HEAVIER: Record<string, { statements?: number; git?: number }> = {
7070 };
7171
7272 /** Patterns with no fixture today: lower this as fixtures are added, never raise it silently. */
73 const MAX_UNFIXTURED = 158; // +1: /:owner/:name/large/:oid, a redirect to a presigned URL with no large blob in the fixture (#4490) // +1: /:owner/:name/bets/:id/walk/:walk, a journey walk of a closed bet scope the fixture has not run (#8715) // +2: /status/:token and /api/v1/status/:token, an outsider status link the fixture has not been handed (#15768); // +1: /tell/share/:id, a receipt of a share the fixture has not sent; +1: /docs/features/:file, a static reference note with no fixture (#12069); +1: /:owner/:name/pulls/:number/check.txt, plain text with no page to fixture (#12165) // +1: /:owner/:name/data/:file, a CSV download with no app data in the fixture (#12684) // +1: /api/v1/repos/:owner/:name/drop/:file, a private file with no drop in the fixture (#645) // +1: /:owner/:name/stl/:ref/*path, an .stl download with no model file in the fixture (#15856) // +1: /api/v1/devices/:id/print/:job, a printer job the fixture has not sent (#16656)
73 const MAX_UNFIXTURED = 159; // +1: /:owner/:name/large/:oid, a redirect to a presigned URL with no large blob in the fixture (#4490) // +1: /:owner/:name/bets/:id/walk/:walk, a journey walk of a closed bet scope the fixture has not run (#8715) // +2: /status/:token and /api/v1/status/:token, an outsider status link the fixture has not been handed (#15768); // +1: /tell/share/:id, a receipt of a share the fixture has not sent; +1: /docs/features/:file, a static reference note with no fixture (#12069); +1: /:owner/:name/pulls/:number/check.txt, plain text with no page to fixture (#12165) // +1: /:owner/:name/data/:file, a CSV download with no app data in the fixture (#12684) // +1: /api/v1/repos/:owner/:name/drop/:file, a private file with no drop in the fixture (#645) // +1: /:owner/:name/stl/:ref/*path, an .stl download with no model file in the fixture (#15856) // +1: /api/v1/devices/:id/print/:job, a printer job the fixture has not sent (#16656) // +1: /:owner/:name/settings/app/flags/:flag, a flag the fixture app does not declare (#1830)
7474
7575 /** Streams and live fragments: no page. */
7676 const NOT_PAGES = new Set([
test/security-floor-routes.test.ts +1
@@ -100,6 +100,7 @@ const UNSEEDED: Record<string, string> = {
100100 "/:owner/:name/looks/:env/:commit/:kind.png": LOOK,
101101 "/:owner/:name/milestones/:number/limb/:op": LIMB,
102102 "/:owner/:name/pulls/:number/review/:step": "needs a pull with a review script, which the seed does not write (test/review-steps.test.ts covers it)",
103 "/:owner/:name/settings/app/flags/:flag": "needs an app whose flags.json declares a flag; the seed has none",
103104 "/:owner/:name/variants/:group": VARIANT,
104105 "/:owner/:name/waves/:version": WAVE,
105106 "/api/v1/boards/:slug/panels/:id": BOARD,
test/tui-appflags.test.ts added +77
@@ -0,0 +1,77 @@
1 /**
2 * The terminal's "Feature flags" (src/tui/screens/appflags.ts): the flags flags.json declares;
3 * `o` turns one on for everyone, `c` clears it, through the page's own action.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { newApp } from "../src/actions/apps.ts";
10 import { commitToBranch } from "../src/actions/repos.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { readValues } from "../src/core/app_flags.ts";
13 import { getRepo, type Repo } from "../src/core/repos.ts";
14 import { createUser, type User } from "../src/core/users.ts";
15 import { createForgeApp } from "../src/tui/forge.ts";
16 import { repoScreen } from "../src/tui/screens/repo.ts";
17 import { local } from "../src/tui/screens/where.ts";
18 import { headlessTerminal } from "../src/tui/term/terminal.ts";
19 import { settleApp } from "./helpers/tui.ts";
20 import { proveAll } from "./helpers/verified.ts";
21
22 let dir: string;
23 let app: App;
24 let admin: User;
25 let shop: Repo;
26
27 async function drive(keys: string[]): Promise<string> {
28 const terminal = headlessTerminal(120, 40);
29 const { app: tui, session } = createForgeApp(
30 app,
31 { sshUsername: admin.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: admin },
32 { terminal, exitHooks: false },
33 );
34 tui.start();
35 tui.ctx.push(repoScreen(session, tui.ctx, local(session, shop)));
36 await settleApp(tui);
37 for (const k of [":", "Feature flags", "\r", ...keys]) {
38 terminal.feed(k);
39 await settleApp(tui);
40 }
41 const text = tui.screen.toText();
42 tui.stop?.();
43 return text;
44 }
45
46 beforeAll(async () => {
47 dir = await mkdtemp(join(tmpdir(), "forge-tui-appflags-"));
48 app = createApp({ dataDir: dir, port: 0 });
49 const r = await createUser(app.db, {
50 origin: "seed", trusted: true, username: "alice", email: "[email protected]",
51 password: "a-good-passphrase", adminIfFirst: true,
52 });
53 if (!r.ok) throw new Error(r.error);
54 admin = r.value;
55 proveAll(app);
56 const made = await newApp(app, admin, { name: "shop", visibility: "public" });
57 if (!made.ok) throw new Error(String(made.error));
58 shop = getRepo(app.db, admin.username, "shop")!;
59 const c = await commitToBranch(app, admin, shop, {
60 message: "flags",
61 files: [{ path: "flags.json", content: JSON.stringify({ flags: { "new-header": { why: "w", default: false } } }) }],
62 });
63 if (!c.ok) throw new Error(JSON.stringify(c.error));
64 });
65 afterAll(async () => {
66 app.db.close();
67 await rm(dir, { recursive: true, force: true });
68 });
69
70 test("lists the declared flag; o sets it on for everyone and c clears it", async () => {
71 expect(await drive([])).toContain("new-header");
72 const on = await drive(["o"]);
73 expect(on).toContain("everyone on");
74 expect(readValues(app.db, shop.id).get("new-header")).toEqual({ forge: true });
75 await drive(["c"]);
76 expect(readValues(app.db, shop.id).has("new-header")).toBe(false);
77 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs