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

Feature flags with live A/B baked in: code-declared flags, per-forge, per-user and percentage values, each variant's use measured, flag debt in the gate #1447

Closed opened this in answer to
Closed without merging

scout/forge:scout/1137-feature-flags-with-live-a-b-baked-in-cod → main 8 commits fork 6 threads · 6 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
15 files changed +1016 −1
README.md +2
@@ -113,6 +113,8 @@ Unset, only this machine may say so, and the named header is never read. Everyth
113113 instance _is_ lives under the data directory — the SQLite index, the bare
114114 repos, and the SSH host key, in plain layout. Tar it up and it moves.
115115
116 Feature flags live in code (`src/core/flag_decls.ts`); an admin sets their values and reads each variant's use under **Settings → Flags**, or with `Flags` in the terminal's palette (`s` set a rule, `c` remove one, `w` make the winner, `esc` close). See `docs/FLAGS.md`.
117
116118 ## Origins
117119
118120 Your forge is the index of everything you work on, wherever it actually lives.
docs/FLAGS.md added +21
@@ -0,0 +1,21 @@
1 # Feature flags with live A/B (#1137)
2
3 A flag is declared in code, set by an admin, and measured by use.
4
5 - **Declare** in `src/core/flag_decls.ts`: name (`area.thing`), a one-line why,
6 the variants, the default, the owner issue.
7 - **Read** with `flag(ctx, "area.thing")` (`src/core/flags.ts`); the literal name
8 is how `scripts/flag-debt.ts` finds the read. Counted once per request.
9 - **Set** at Settings → Flags (admin): for the whole forge, a role
10 (`admin`/`agent`/`member`), a user, or a percentage. Precedence: user, role,
11 percentage, forge, default. A percentage hashes flag + viewer id, so a person
12 always sees the same side; percentages for one flag total at most 100.
13 Signed-out viewers see forge rules or the default.
14 - **Read out**: the same page shows requests per variant for 7 and 30 days
15 (`flag_use`, flushed every few seconds; values refresh in-process every 3 s).
16 - **Retire**: "Make the winner" sets the forge-wide value and drops other rules;
17 then a pull makes it the default in `flag_decls.ts`, deletes the losing path
18 and the declaration. `bun scripts/flag-debt.ts` (and `test/flags.test.ts` in
19 the gate) fails on a declared flag nothing reads, and on a read nothing declares.
20
21 Not yet: flags for apps (`FORGE_FLAGS_URL`, a template flags file and client), tracked in #1572.
outdated

This is an unchecked item in #1137's done list. Open a linked follow-up issue for it and reference it here, so the work isn't silently dropped.

scripts/flag-debt.ts added +50
@@ -0,0 +1,50 @@
1 /**
2 * Flag debt (#1137): every flag the code declares is read, and every flag the
3 * code reads is declared. `flag(ctx, "name")` is the only read; this finds
4 * each one in `src/` by spelling. A declared flag nothing reads is debt —
5 * delete the declaration and the path it guarded — and a read of a name not
6 * declared would be a defect at runtime, so it fails here first.
7 *
8 * bun scripts/flag-debt.ts
9 */
10
11 import { Glob } from "bun";
12 import { FLAGS, FLAG_NAME } from "../src/core/flag_decls.ts";
13
14 const READ = /\bflag\(\s*[A-Za-z_.]+\s*,\s*["']([^"']+)["']/g;
15 const SKIP = new Set(["src/core/flags.ts", "src/core/flag_decls.ts"]);
16
17 export interface Debt {
18 readonly undeclared: string[];
19 readonly unread: string[];
20 readonly malformed: string[];
21 }
22
23 export async function flagDebt(
24 root = new URL("..", import.meta.url).pathname,
25 declared: readonly string[] = FLAGS.map((f) => f.name),
26 files?: ReadonlyMap<string, string>,
27 ): Promise<Debt> {
28 const read = new Set<string>();
29 const sources = files ?? new Map<string, string>();
30 if (files === undefined)
31 for await (const path of new Glob("src/**/*.ts").scan({ cwd: root }))
32 if (!SKIP.has(path)) (sources as Map<string, string>).set(path, await Bun.file(`${root}${path}`).text());
33 for (const [path, text] of sources) {
34 if (SKIP.has(path)) continue;
35 for (const m of text.matchAll(READ)) read.add(m[1]!);
36 }
37 return {
38 undeclared: [...read].filter((n) => !declared.includes(n)).sort(),
39 unread: declared.filter((n) => !read.has(n)).sort(),
40 malformed: declared.filter((n) => !FLAG_NAME.test(n)),
41 };
42 }
43
44 if (import.meta.main) {
45 const d = await flagDebt();
46 for (const n of d.undeclared) console.error(`read but not declared: ${n}`);
47 for (const n of d.unread) console.error(`declared but never read (flag debt): ${n}`);
48 for (const n of d.malformed) console.error(`malformed name: ${n}`);
49 process.exit(d.undeclared.length + d.unread.length + d.malformed.length ? 1 : 0);
50 }
scripts/gate.ts +1
@@ -210,6 +210,7 @@ export const GATE: readonly string[] = [
210210 "test/check-list.test.ts",
211211 "test/check-tiers.test.ts",
212212 "test/holds.test.ts",
213 "test/flags.test.ts",
213214 "test/hollow.test.ts",
214215 "test/home-feed.test.ts",
215216 "test/oauth-discovery.test.ts",
src/core/flag_decls.ts added +35
@@ -0,0 +1,35 @@
1 /**
2 * Every feature flag the forge's code reads, declared in this one file: a
3 * name, a one-line why, the variants it can take, the default (what everyone
4 * sees until an admin sets a value), and the issue that owns it.
5 *
6 * A flag the code no longer reads is flag debt and fails the gate
7 * (`scripts/flag-debt.ts`, run by `test/flags.test.ts`); a read of a name not
8 * declared here fails it too. Retiring a flag means deleting the losing path,
9 * then its line here.
10 */
11
12 export interface FlagDecl {
13 /** Lowercase dotted name: `area.thing`. */
14 readonly name: string;
15 /** One line: what the flag decides and why it is a flag. */
16 readonly why: string;
17 /** The values it can take; the first is conventionally the control. */
18 readonly variants: readonly string[];
19 /** What a viewer with no rule sees. One of `variants`. */
20 readonly default: string;
21 /** The issue that owns the experiment and its retirement. */
22 readonly owner: number;
23 }
24
25 export const FLAGS: readonly FlagDecl[] = [
26 {
27 name: "ui.density",
28 why: "Compact tables against comfortable ones: which do people read the settings pages in?",
29 variants: ["comfortable", "compact"],
30 default: "comfortable",
31 owner: 1137,
32 },
33 ];
34
35 export const FLAG_NAME = /^[a-z][a-z0-9]*(\.[a-z][a-z0-9_]*)+$/;
src/core/flags.ts added +279
@@ -0,0 +1,279 @@
1 /**
2 * Feature flags with live A/B: values an admin sets (`flag_rule`), read in
3 * process from a snapshot that refreshes in seconds, and a count of every
4 * variant that ran (`flag_use`), so the use of each side can be read.
5 *
6 * A viewer's variant, first match wins: a rule for that user, a rule for
7 * their role (`admin`, `agent`, `member`), a percentage split, a rule for the
8 * whole forge, the declared default. A percentage rule hashes flag + viewer
9 * (no randomness, no cookie), so the same person always lands on the same
10 * side; percentages for one flag fill buckets in order and may total at most
11 * 100.
12 *
13 * Counting is batched in memory and written every few seconds: a request
14 * pays a map increment, not a write.
15 */
16
17 import type { Database } from "bun:sqlite";
18 import { defect } from "../kernel/error.ts";
19 import { sha256 } from "../kernel/hash.ts";
20 import { FLAGS, type FlagDecl } from "./flag_decls.ts";
21
22 export type RuleScope = "forge" | "user" | "role" | "percent";
23 export const RULE_SCOPES: readonly RuleScope[] = ["forge", "user", "role", "percent"];
24 export const ROLES: readonly string[] = ["admin", "agent", "member"];
25
26 export interface Rule {
27 readonly flag: string;
28 readonly scope: RuleScope;
29 /** user id, role name, or "" for forge/percent. */
30 readonly subject: string;
31 readonly value: string;
32 /** 1–100 for `percent`, else 0. */
33 readonly pct: number;
34 }
35
36 export interface Viewer {
37 readonly id: string;
38 readonly role: string;
39 }
40
41 export const declared = (name: string): FlagDecl | undefined =>
42 FLAGS.find((f) => f.name === name);
43
44 export function viewerOf(
45 user: { id: string; isAdmin: boolean; kind: string } | undefined,
46 ): Viewer | undefined {
47 if (user === undefined) return undefined;
48 return {
49 id: user.id,
50 role: user.isAdmin ? "admin" : user.kind === "agent" ? "agent" : "member",
51 };
52 }
53
54 /** 0–99, stable for one flag and one viewer. */
55 export function bucket(flag: string, viewerId: string): number {
56 const h = sha256(`${flag}\0${viewerId}`);
57 return Number.parseInt(h.slice(0, 8), 16) % 100;
58 }
59
60 /** Pure: which variant `viewer` sees under `rules`. No viewer sees only forge rules. */
61 export function resolve(
62 decl: FlagDecl,
63 rules: readonly Rule[],
64 viewer: Viewer | undefined,
65 ): string {
66 if (viewer !== undefined) {
67 const user = rules.find((r) => r.scope === "user" && r.subject === viewer.id);
68 if (user) return user.value;
69 const role = rules.find((r) => r.scope === "role" && r.subject === viewer.role);
70 if (role) return role.value;
71 const b = bucket(decl.name, viewer.id);
72 let from = 0;
73 for (const r of rules) {
74 if (r.scope !== "percent") continue;
75 if (b >= from && b < from + r.pct) return r.value;
76 from += r.pct;
77 }
78 }
79 return rules.find((r) => r.scope === "forge")?.value ?? decl.default;
80 }
81
82 // ---- the snapshot ------------------------------------------------------
83
84 const REFRESH_MS = 3_000;
85 const FLUSH_MS = 5_000;
86
87 interface Cache {
88 at: number;
89 rules: Map<string, Rule[]>;
90 }
91 const caches = new WeakMap<Database, Cache>();
92
93 function snapshot(db: Database, now = Date.now()): Map<string, Rule[]> {
94 const hit = caches.get(db);
95 if (hit && now - hit.at < REFRESH_MS) return hit.rules;
96 const rules = new Map<string, Rule[]>();
97 const rows = db
98 .query<
99 { flag: string; scope: RuleScope; subject: string; value: string; pct: number },
100 []
101 >("SELECT flag, scope, subject, value, pct FROM flag_rule ORDER BY rowid")
102 .all();
103 for (const r of rows) {
104 const list = rules.get(r.flag) ?? [];
105 list.push(r);
106 rules.set(r.flag, list);
107 }
108 caches.set(db, { at: now, rules });
109 return rules;
110 }
111
112 const forgetSnapshot = (db: Database): void => void caches.delete(db);
113
114 export function rulesOf(db: Database, flag: string): readonly Rule[] {
115 return snapshot(db).get(flag) ?? [];
116 }
117
118 // ---- reading -----------------------------------------------------------
119
120 interface Reader {
121 readonly app: { readonly db: Database };
122 readonly auth: {
123 readonly user: { id: string; isAdmin: boolean; kind: string } | undefined;
124 };
125 readonly request?: Request;
126 }
127
128 const pending = new WeakMap<Database, Map<string, number>>();
129 const timers = new WeakMap<Database, ReturnType<typeof setTimeout>>();
130 const seen = new WeakMap<Request, Set<string>>();
131
132 const day = (at: number): string => new Date(at).toISOString().slice(0, 10);
133
134 /**
135 * The variant this request runs under, counted once per request per flag.
136 * An undeclared name is a defect — and the gate finds it before it ships.
137 */
138 export function flag(ctx: Reader, name: string): string {
139 const decl = declared(name);
140 if (decl === undefined) defect("flag.undeclared", `flag "${name}" is not declared in core/flag_decls.ts`);
141 const db = ctx.app.db;
142 const variant = resolve(decl, rulesOf(db, name), viewerOf(ctx.auth.user));
143 const req = ctx.request;
144 if (req !== undefined) {
145 const s = seen.get(req) ?? new Set<string>();
146 seen.set(req, s);
147 if (s.has(name)) return variant;
148 s.add(name);
149 }
150 countUse(db, name, variant);
151 return variant;
152 }
153
154 export function countUse(db: Database, name: string, variant: string, now = Date.now()): void {
155 const map = pending.get(db) ?? new Map<string, number>();
156 pending.set(db, map);
157 const key = `${name}\0${variant}\0${day(now)}`;
158 map.set(key, (map.get(key) ?? 0) + 1);
159 if (!timers.has(db)) {
160 const t = setTimeout(() => flushUse(db), FLUSH_MS);
161 (t as { unref?: () => void }).unref?.();
162 timers.set(db, t);
163 }
164 }
165
166 export function flushUse(db: Database): void {
167 const t = timers.get(db);
168 if (t) clearTimeout(t);
169 timers.delete(db);
170 const map = pending.get(db);
171 if (!map || map.size === 0) return;
172 pending.delete(db);
173 try {
174 const up = db.query(
175 `INSERT INTO flag_use (flag, variant, day, n) VALUES (?1, ?2, ?3, ?4)
176 ON CONFLICT (flag, variant, day) DO UPDATE SET n = n + excluded.n`,
177 );
178 db.transaction(() => {
179 for (const [key, n] of map) {
180 const [f, v, d] = key.split("\0");
181 up.run(f!, v!, d!, n);
182 }
183 })();
184 } catch {
185 // The database closed under a pending batch (shutdown): a lost count,
186 // never a failed request.
187 }
188 }
189
190 // ---- writing -----------------------------------------------------------
191
192 export type RuleInput = {
193 flag: string;
194 scope: string;
195 subject: string;
196 value: string;
197 pct: number;
198 };
199
200 /** Validate and store a rule; one per (flag, scope, subject), the latest wins. */
201 export function setRule(db: Database, input: RuleInput): string | undefined {
202 const decl = declared(input.flag);
203 if (decl === undefined) return "That flag is not declared in the code.";
204 if (!decl.variants.includes(input.value)) return "That is not one of the flag's variants.";
205 const scope = input.scope as RuleScope;
206 if (!RULE_SCOPES.includes(scope)) return "Unknown scope.";
207 let subject = input.subject.trim();
208 let pct = 0;
209 if (scope === "user") {
210 if (!/^[A-Za-z0-9_-]{1,64}$/.test(subject)) return "A user rule needs a user id.";
211 const row = db.query<{ id: string }, [string]>("SELECT id FROM user WHERE id = ?1 OR username = ?1").get(subject);
212 if (!row) return "No such user.";
213 subject = row.id;
214 } else if (scope === "role") {
215 if (!ROLES.includes(subject)) return "Role must be admin, agent or member.";
216 } else {
217 subject = "";
218 }
219 if (scope === "percent") {
220 if (!Number.isInteger(input.pct) || input.pct < 1 || input.pct > 100)
221 return "A percentage is a whole number from 1 to 100.";
222 pct = input.pct;
223 const others = rulesOf(db, input.flag)
224 .filter((r) => r.scope === "percent" && r.value !== input.value)
225 .reduce((a, r) => a + r.pct, 0);
226 if (others + pct > 100) return "Percentages for one flag may total at most 100.";
227 }
228 db.query(
229 `INSERT INTO flag_rule (flag, scope, subject, value, pct) VALUES (?1, ?2, ?3, ?4, ?5)
230 ON CONFLICT (flag, scope, subject) DO UPDATE SET value = excluded.value, pct = excluded.pct`,
outdated

High: the upsert key includes value, so a second forge, user or role rule with a different value is inserted next to the first instead of replacing it, and resolve keeps returning the older one. Upsert on (flag, scope, subject) and set value, pct.

231 ).run(input.flag, scope, scope === "percent" ? input.value : subject, input.value, pct);
232 forgetSnapshot(db);
233 return undefined;
234 }
235
236 export function clearRule(db: Database, flag: string, scope: string, subject: string): void {
237 db.query("DELETE FROM flag_rule WHERE flag = ?1 AND scope = ?2 AND subject = ?3").run(flag, scope, subject);
238 forgetSnapshot(db);
239 }
240
241 /** The winner becomes everyone's value: every other rule goes, one forge rule stays. */
242 export function crownWinner(db: Database, flagName: string, winner: string): string | undefined {
243 const decl = declared(flagName);
244 if (decl === undefined) return "That flag is not declared in the code.";
245 if (!decl.variants.includes(winner)) return "That is not one of the flag's variants.";
246 db.transaction(() => {
247 db.query("DELETE FROM flag_rule WHERE flag = ?1").run(flagName);
248 db.query(
249 "INSERT INTO flag_rule (flag, scope, subject, value, pct) VALUES (?1, 'forge', '', ?2, 0)",
250 ).run(flagName, winner);
251 })();
252 forgetSnapshot(db);
253 return undefined;
254 }
255
256 // ---- the read-out ------------------------------------------------------
257
258 export interface Readout {
259 readonly variant: string;
260 readonly d7: number;
261 readonly d30: number;
262 }
263
264 export function readout(db: Database, name: string, now = Date.now()): Readout[] {
265 flushUse(db);
266 const decl = declared(name);
267 const since = (days: number): string => day(now - (days - 1) * 86_400_000);
268 const sum = (variant: string, days: number): number =>
269 db
270 .query<{ n: number | null }, [string, string, string]>(
271 "SELECT SUM(n) AS n FROM flag_use WHERE flag = ?1 AND variant = ?2 AND day >= ?3",
272 )
273 .get(name, variant, since(days))?.n ?? 0;
274 return (decl?.variants ?? []).map((variant) => ({
275 variant,
276 d7: sum(variant, 7),
277 d30: sum(variant, 30),
278 }));
279 }
src/core/schema.ts +20
@@ -1595,6 +1595,26 @@ export const migrations: readonly string[] = [
15951595 PRIMARY KEY (repo_id, parent_id, issue_id)
15961596 );
15971597 `,
1598 // 76 — feature flags with live A/B (#1137): the values an admin sets, and
1599 // a count of each variant that ran, per day. Config and measurement, not
1600 // truth: losing the tables returns every flag to its declared default.
1601 `
1602 CREATE TABLE flag_rule (
1603 flag TEXT NOT NULL,
1604 scope TEXT NOT NULL CHECK (scope IN ('forge','user','role','percent')),
1605 subject TEXT NOT NULL DEFAULT '',
1606 value TEXT NOT NULL,
1607 pct INTEGER NOT NULL DEFAULT 0,
1608 PRIMARY KEY (flag, scope, subject)
outdated

This PK is what lets a stale forge/user/role value outlive a newer one. (flag, scope, subject) is enough, because a percent rule already uses the value as its subject. Fix it here while 76 is unreleased.

1609 );
1610 CREATE TABLE flag_use (
1611 flag TEXT NOT NULL,
1612 variant TEXT NOT NULL,
1613 day TEXT NOT NULL,
1614 n INTEGER NOT NULL DEFAULT 0,
1615 PRIMARY KEY (flag, variant, day)
1616 );
1617 `,
15981618 ];
15991619
16001620 /**
src/http/server.ts +10
@@ -98,6 +98,12 @@ import {
9898 backupsPage,
9999 backupsTest,
100100 } from "../web/pages/backups.ts";
101 import {
102 flagsClear,
103 flagsPage,
104 flagsSet,
105 flagsWinner,
106 } from "../web/pages/flags.ts";
101107 import {
102108 cloudAdd,
103109 cloudAudit,
@@ -663,6 +669,10 @@ export function buildRouter(): Router<Handler> {
663669 router.add("POST", "/settings/cloud/remove", cloudRemove);
664670 router.add("GET", "/settings/capacity", capacityPage);
665671 router.add("POST", "/settings/capacity", capacitySet);
672 router.add("GET", "/settings/flags", flagsPage);
673 router.add("POST", "/settings/flags/set", flagsSet);
674 router.add("POST", "/settings/flags/clear", flagsClear);
675 router.add("POST", "/settings/flags/winner", flagsWinner);
666676 router.add("GET", "/settings/backups", backupsPage);
667677 router.add("POST", "/settings/backups/now", backupsNow);
668678 router.add("POST", "/settings/backups/destination", backupsDestination);
src/tui/forge.ts +8
@@ -35,6 +35,7 @@ import { newPullScreen } from "./screens/newpull.ts";
3535 import { newRepoScreen } from "./screens/newrepo.ts";
3636 import { repoScreen } from "./screens/repo.ts";
3737 import { signInScreen } from "./screens/signin.ts";
38 import { flagsScreen } from "./screens/flags.ts";
3839 import { local } from "./screens/where.ts";
3940
4041 export { Session, type TuiIdentity };
@@ -161,6 +162,13 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
161162 run: () => openOnWeb(session, ctx, "/settings", "Account settings"),
162163 },
163164 );
165 if (session.user?.isAdmin === true)
166 commands.push({
167 id: "flags",
168 title: "Flags",
169 hint: "read-out, set a rule",
170 run: () => ctx.push(flagsScreen(session, ctx, blank("Flags"))),
171 });
164172 commands.push({
165173 id: "quit",
166174 title: "Quit",
src/tui/screens/flags.ts added +127
@@ -0,0 +1,127 @@
1 /**
2 * Feature flags in the terminal (admins): the read-out, setting a rule, clearing one, and making a winner.
3 * The same `core/flags.ts` the Settings → Flags page calls, behind the same
4 * admin check; a member never gets the command.
5 */
6
7 import { FLAGS } from "../../core/flag_decls.ts";
8 import { clearRule, crownWinner, readout, rulesOf, setRule } from "../../core/flags.ts";
9 import type { Ctx, Screen } from "../app/app.ts";
10 import { binding } from "../app/keys.ts";
11 import { style } from "../term/style.ts";
12 import { truncate } from "../term/width.ts";
13 import { card } from "../ui/widgets.ts";
14 import type { Session } from "../session.ts";
15 import { promptScreen } from "./common.ts";
16
17 /** The lines of the read-out: each flag, its rules, each variant's use. */
18 export function flagLines(f: Session): string[] {
19 const lines: string[] = [];
20 for (const decl of FLAGS) {
21 lines.push(`${decl.name} (default ${decl.default}, #${decl.owner})`);
22 for (const r of rulesOf(f.db, decl.name))
23 lines.push(` rule ${r.scope}${r.subject === "" || r.scope === "percent" ? "" : ` ${r.subject}`} → ${r.value}${r.scope === "percent" ? ` ${r.pct}%` : ""}`);
24 for (const row of readout(f.db, decl.name))
25 lines.push(` ${row.variant.padEnd(14)} 7d ${row.d7} 30d ${row.d30}`);
26 }
27 return lines;
28 }
29
30 export function flagsScreen(f: Session, ctx: Ctx, parent: Screen): Screen {
31 if (f.user?.isAdmin !== true) throw new Error("not found");
32 return {
33 title: "Flags",
34 keys: [binding(["s"], "set a rule"), binding(["c"], "clear a rule"), binding(["w"], "make the winner"), binding(["esc"], "close")],
outdated

The page has set, remove, and make-the-winner. The terminal only has s. Add c (call clearRule) and w (call crownWinner) behind the same admin check, and test the submit path of each.

35 render(area, s) {
36 parent.render(area, s);
37 const c = ctx.theme.c;
38 const lines = flagLines(f);
39 const w = Math.min(76, Math.max(30, area.w - 6));
40 const h = Math.min(area.h, lines.length + 4);
41 const inner = card(
42 s,
43 { x: area.x + ((area.w - w) >> 1), y: area.y + ((area.h - h) >> 1), w, h },
44 c,
45 { title: "Flags", footer: "s set c clear w winner", focused: true },
46 );
47 lines.slice(0, inner.h).forEach((line, i) => {
48 s.text(inner.x + 1, inner.y + i, truncate(line, Math.max(0, inner.w - 2)), style(c.fg, c.card), inner.x + inner.w);
49 });
50 },
51 key(e) {
52 if (e.key === "s") {
53 ctx.push(setFlagScreen(f, ctx, parent));
54 return true;
55 }
56 if (e.key === "c") {
57 ctx.push(clearFlagScreen(f, ctx, parent));
58 return true;
59 }
60 if (e.key === "w") {
61 ctx.push(winnerFlagScreen(f, ctx, parent));
62 return true;
63 }
64 if (e.key === "esc" || e.key === "q") ctx.pop();
65 return true;
66 },
67 };
68 }
69
70 /** `flag value [scope [subject|pct]]`; the scope defaults to the whole forge. */
71 export function setFlagScreen(f: Session, ctx: Ctx, parent: Screen): Screen {
72 return promptScreen(ctx, parent, {
73 title: "Set a flag",
74 label: "flag value [forge | user NAME | role ROLE | percent N]",
75 onSubmit(text) {
76 if (f.user?.isAdmin !== true) return "not found";
77 const [flagName = "", value = "", scope = "forge", arg = ""] = text.trim().split(/\s+/);
78 const percent = scope === "percent";
79 const error = setRule(f.db, {
80 flag: flagName,
81 value,
82 scope,
83 subject: percent ? "" : arg,
84 pct: percent ? Number(arg) : 0,
85 });
86 if (error === undefined) ctx.toast(`${flagName} → ${value}`, "success");
87 return error;
88 },
89 });
90 }
91
92 /** `flag [scope [subject|variant]]`: remove one rule; a percent rule is named by its variant. */
93 export function clearFlagScreen(f: Session, ctx: Ctx, parent: Screen): Screen {
94 return promptScreen(ctx, parent, {
95 title: "Remove a rule",
96 label: "flag [forge | user NAME | role ROLE | percent VARIANT]",
97 onSubmit(text) {
98 if (f.user?.isAdmin !== true) return "not found";
99 const [flagName = "", scope = "forge", arg = ""] = text.trim().split(/\s+/);
100 if (!FLAGS.some((d) => d.name === flagName)) return "That flag is not declared in the code.";
101 let subject = scope === "forge" ? "" : arg;
102 if (scope === "user") {
103 const row = f.db.query<{ id: string }, [string]>("SELECT id FROM user WHERE id = ?1 OR username = ?1").get(arg);
104 if (!row) return "No such user.";
105 subject = row.id;
106 } else if (!["forge", "role", "percent"].includes(scope)) return "Unknown scope.";
107 clearRule(f.db, flagName, scope, subject);
108 ctx.toast(`${flagName}: rule removed`, "success");
109 return undefined;
110 },
111 });
112 }
113
114 /** `flag variant`: the variant becomes everyone's value and the other rules go. */
115 export function winnerFlagScreen(f: Session, ctx: Ctx, parent: Screen): Screen {
116 return promptScreen(ctx, parent, {
117 title: "Make the winner",
118 label: "flag variant",
119 onSubmit(text) {
120 if (f.user?.isAdmin !== true) return "not found";
121 const [flagName = "", winner = ""] = text.trim().split(/\s+/);
122 const error = crownWinner(f.db, flagName, winner);
123 if (error === undefined) ctx.toast(`${flagName} → ${winner} for everyone`, "success");
124 return error;
125 },
126 });
127 }
src/web/layout.ts +3 −1
@@ -14,6 +14,7 @@ import type { User } from "../core/users.ts";
1414 import type { Ctx } from "../http/context.ts";
1515 import { edgeLoginUrl, edgeLogoutUrl } from "../http/edge.ts";
1616 import { json } from "../http/respond.ts";
17 import { flag } from "../core/flags.ts";
1718 import { sha256 } from "../kernel/hash.ts";
1819 import { secret } from "../kernel/id.ts";
1920 import { runningLine } from "../kernel/version.ts";
@@ -532,6 +533,7 @@ export function page(options: PageOptions, status = 200): Response {
532533 const nonce = secret();
533534 const { ctx } = options;
534535 const theme = ctx.theme ?? options.theme;
536 const density = flag(ctx, "ui.density");
535537 const flash = readFlash(ctx.request);
536538 const links = pageLinks(ctx);
537539
@@ -633,7 +635,7 @@ export function page(options: PageOptions, status = 200): Response {
633635 ? raw(`<style nonce="${nonce}">${options.styleCss}</style>`)
634636 : null}
635637 </head>
636 <body>
638 <body data-density="${density}">
637639 ${shell}${iconSprite(shell.text)}
638640 <script nonce="${nonce}" src="${shellAsset().path}"></script>
639641 ${options.scriptJs
src/web/pages/flags.ts added +212
@@ -0,0 +1,212 @@
1 /**
2 * Settings → Flags, for a forge admin: every flag the code declares, its
3 * default and live values, and beside each the use of every variant over the
4 * last 7 and 30 days — the A/B read-out. One form adds a value (the whole
5 * forge, a user, a role, or a percentage of viewers), one button per variant
6 * makes it everyone's and ends the experiment.
7 *
8 * The default lives in code, so crowning a winner cannot edit it: it sets the
9 * forge-wide value, drops every other rule, and says what the retiring pull
10 * must delete.
11 */
12
13 import {
14 FLAGS,
15 type FlagDecl,
16 } from "../../core/flag_decls.ts";
17 import {
18 clearRule,
19 crownWinner,
20 readout,
21 ROLES,
22 rulesOf,
23 setRule,
24 type Rule,
25 } from "../../core/flags.ts";
26 import type { Ctx } from "../../http/context.ts";
27 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
28 import { field, readForm } from "../form.ts";
29 import { html, type Html } from "../html.ts";
30 import { flashTo, page } from "../layout.ts";
31 import { btn, card, icon } from "../ui.ts";
32 import { accountSections } from "./origins.ts";
33
34 function requireAdmin(ctx: Ctx): Response | undefined {
35 if (!ctx.auth.user) return signInFirst(ctx);
36 if (!ctx.auth.user.isAdmin) return notFoundPage(ctx);
37 return undefined;
38 }
39
40 const describe = (r: Rule): string =>
41 r.scope === "percent"
42 ? `${r.pct}% of viewers`
43 : r.scope === "forge"
44 ? "everyone"
45 : `${r.scope} ${r.subject}`;
46
47 function flagCard(ctx: Ctx, f: FlagDecl): Html {
48 const rules = rulesOf(ctx.app.db, f.name);
49 const out = readout(ctx.app.db, f.name);
50 const hidden = (extra: Html | null = null): Html =>
51 html`<input type="hidden" name="flag" value="${f.name}" />${extra}`;
52 return card(
53 html`<p>${f.why}</p>
54 <p class="muted small">
55 Default <code>${f.default}</code> · owner
56 <span class="mono">#${String(f.owner)}</span>
57 </p>
58 <table class="table" data-flag="${f.name}">
59 <thead>
60 <tr>
61 <th scope="col">Variant</th>
62 <th scope="col" class="num">7 days</th>
63 <th scope="col" class="num">30 days</th>
64 <th scope="col"></th>
65 </tr>
66 </thead>
67 <tbody>
68 ${out.map(
69 (o) =>
70 html`<tr data-variant="${o.variant}">
71 <th scope="row">${o.variant}</th>
72 <td class="num">${String(o.d7)}</td>
73 <td class="num">${String(o.d30)}</td>
74 <td>
75 <form method="post" action="/settings/flags/winner">
76 ${hidden(
77 html`<input type="hidden" name="winner" value="${o.variant}" />`,
78 )}
79 ${btn("Make the winner", {
80 size: "sm",
81 label: `Make ${o.variant} the winner of ${f.name}`,
82 })}
83 </form>
84 </td>
85 </tr>`,
86 )}
87 </tbody>
88 </table>
89 <p class="muted small">
90 Requests that ran under each variant, counted once per request.
91 </p>
92 ${rules.length === 0
93 ? html`<p class="muted">No values set: everyone sees the default.</p>`
94 : html`<ul>
95 ${rules.map(
96 (r) =>
97 html`<li>
98 <code>${r.value}</code> for ${describe(r)}
99 <form method="post" action="/settings/flags/clear" class="inline">
100 ${hidden(
101 html`<input type="hidden" name="scope" value="${r.scope}" /><input
102 type="hidden"
103 name="subject"
104 value="${r.scope === "percent" ? r.value : r.subject}"
105 />`,
106 )}
107 ${btn("Remove", { size: "sm", label: `Remove ${describe(r)}` })}
108 </form>
109 </li>`,
110 )}
111 </ul>`}
112 <form method="post" action="/settings/flags/set" class="row-actions">
113 ${hidden()}
114 <select class="input" name="value" aria-label="Value">
115 ${f.variants.map((v) => html`<option value="${v}">${v}</option>`)}
116 </select>
117 <select class="input" name="scope" aria-label="For">
118 <option value="forge">the whole forge</option>
119 <option value="percent">a percentage of viewers</option>
120 <option value="role">a role</option>
121 <option value="user">a user</option>
122 </select>
123 <input
124 class="input"
125 name="subject"
126 placeholder="username, or ${ROLES.join(" / ")}"
127 aria-label="User or role"
128 maxlength="64"
129 />
130 <input
131 class="input"
132 name="pct"
133 type="number"
134 min="1"
135 max="100"
136 placeholder="%"
137 aria-label="Percent"
138 />
139 ${btn("Set", { variant: "primary", label: `Set a value for ${f.name}` })}
140 </form>`,
141 { head: html`${icon("activity")} <b class="mono">${f.name}</b>` },
142 );
143 }
144
145 export function flagsPage(ctx: Ctx): Response {
146 const denied = requireAdmin(ctx);
147 if (denied) return denied;
148 return page({
149 ctx,
150 title: "Flags",
151 body: html`<div class="page-head"><h1>Flags</h1></div>
152 ${settingsLayout(
153 accountSections("flags", { admin: true }),
154 html`${FLAGS.length === 0
155 ? html`<p class="muted">The code declares no flags.</p>`
156 : FLAGS.map((f) => flagCard(ctx, f))}
157 <p class="muted small">
158 A person always sees the same side: a percentage hashes the flag and
159 the viewer. Order of precedence: user, role, percentage, whole forge,
160 default.
161 </p>`,
162 "Account settings",
163 )}`,
164 });
165 }
166
167 async function admin(ctx: Ctx): Promise<Response | Awaited<ReturnType<typeof readForm>>> {
168 const denied = requireAdmin(ctx);
169 if (denied) return denied;
170 return readForm(ctx, "admin");
171 }
172
173 const back = (ctx: Ctx, message: string, bad = false): Response =>
174 flashTo(ctx, "/settings/flags", bad ? { tone: "danger", message } : { message });
175
176 export async function flagsSet(ctx: Ctx): Promise<Response> {
177 const form = await admin(ctx);
178 if (form instanceof Response) return form;
179 const flag = field(form, "flag");
180 const scope = field(form, "scope");
181 const pct = Number(field(form, "pct"));
182 const error = setRule(ctx.app.db, {
183 flag,
184 scope,
185 subject: field(form, "subject"),
186 value: field(form, "value"),
187 pct: scope === "percent" ? pct : 0,
188 });
189 return error ? back(ctx, error, true) : back(ctx, `${flag} updated.`);
190 }
191
192 export async function flagsClear(ctx: Ctx): Promise<Response> {
193 const form = await admin(ctx);
194 if (form instanceof Response) return form;
195 const flag = field(form, "flag");
196 clearRule(ctx.app.db, flag, field(form, "scope"), field(form, "subject"));
197 return back(ctx, `${flag}: value removed.`);
198 }
199
200 export async function flagsWinner(ctx: Ctx): Promise<Response> {
201 const form = await admin(ctx);
202 if (form instanceof Response) return form;
203 const flag = field(form, "flag");
204 const winner = field(form, "winner");
205 const error = crownWinner(ctx.app.db, flag, winner);
206 return error
207 ? back(ctx, error, true)
208 : back(
209 ctx,
210 `${winner} is now everyone's ${flag}. To retire it, open a pull that makes "${winner}" the default in core/flag_decls.ts, deletes the losing path and removes the flag's declaration.`,
211 );
212 }
src/web/pages/origins.ts +7
@@ -80,6 +80,7 @@ export type AccountSection =
8080 | "backups"
8181 | "secrets"
8282 | "capacity"
83 | "flags"
8384 | "cloud";
8485
8586 /**
@@ -131,6 +132,12 @@ export function accountSections(
131132 icon: "activity" as const,
132133 current: current === "capacity",
133134 },
135 {
136 label: "Flags",
137 href: "/settings/flags",
138 icon: "activity" as const,
139 current: current === "flags",
140 },
134141 {
135142 label: "Backups",
136143 href: "/settings/backups",
src/web/style/components.ts +3
@@ -734,4 +734,7 @@ a.row:hover .row-title { color: var(--accent); }
734734 input, textarea, select, .input, .input[data-size="sm"], .topbar-search input,
735735 .palette .palette-input { font-size: 16px; }
736736 }
737
738 /* ui.density (#1137): the compact side of the experiment. */
739 body[data-density="compact"] .table th, body[data-density="compact"] .table td { padding-block: 4px; }
737740 `;
test/flags.test.ts added +238
@@ -0,0 +1,238 @@
1 /**
2 * Feature flags with live A/B (#1137): the code's declarations are the set
3 * (no debt, no undeclared read), a percentage splits viewers evenly and
4 * stably, and the read-out is the use table.
5 */
6
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { flagDebt } from "../scripts/flag-debt.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import { FLAGS, type FlagDecl } from "../src/core/flag_decls.ts";
14 import {
15 bucket,
16 clearRule,
17 countUse,
18 crownWinner,
19 flag,
20 flushUse,
21 readout,
22 resolve,
23 setRule,
24 type Rule,
25 } from "../src/core/flags.ts";
26 import { createUser } from "../src/core/users.ts";
27 import { flagLines, flagsScreen, setFlagScreen, clearFlagScreen, winnerFlagScreen } from "../src/tui/screens/flags.ts";
28 import { serve, type Servers } from "../src/http/server.ts";
29
30 const decl: FlagDecl = {
31 name: "t.split",
32 why: "test",
33 variants: ["a", "b"],
34 default: "a",
35 owner: 1,
36 };
37 const pct = (value: string, n: number): Rule => ({
38 flag: "t.split",
39 scope: "percent",
40 subject: value,
41 value,
42 pct: n,
43 });
44
45 describe("flag debt", () => {
46 test("the repository declares what it reads and reads what it declares", async () => {
47 expect(await flagDebt()).toEqual({ undeclared: [], unread: [], malformed: [] });
48 });
49 test("an undeclared read and an unread declaration both fail", async () => {
50 const src = new Map([["src/x.ts", `const v = flag(ctx, "nope.nothing");`]]);
51 const d = await flagDebt("", ["old.thing"], src);
52 expect(d.undeclared).toEqual(["nope.nothing"]);
53 expect(d.unread).toEqual(["old.thing"]);
54 });
55 test("reading an undeclared flag at runtime is a defect", () => {
56 const ctx = { app: { db: null as never }, auth: { user: undefined } };
57 expect(() => flag(ctx, "nope.nothing")).toThrow();
58 });
59 });
60
61 describe("percentage", () => {
62 const viewers = Array.from({ length: 1000 }, (_, i) => ({ id: `u${i}`, role: "member" }));
63 test("splits a thousand viewers within tolerance and is stable per viewer", () => {
64 const rules = [pct("b", 30)];
65 const first = viewers.map((v) => resolve(decl, rules, v));
66 const b = first.filter((x) => x === "b").length;
67 expect(b).toBeGreaterThan(300 - 50);
68 expect(b).toBeLessThan(300 + 50);
69 expect(viewers.map((v) => resolve(decl, rules, v))).toEqual(first);
70 expect(bucket("t.split", "u1")).toBe(bucket("t.split", "u1"));
71 });
72 test("user beats role beats percent beats forge beats default", () => {
73 const v = { id: "u1", role: "admin" };
74 const forge: Rule = { flag: "t.split", scope: "forge", subject: "", value: "b", pct: 0 };
75 expect(resolve(decl, [], v)).toBe("a");
76 expect(resolve(decl, [forge], v)).toBe("b");
77 expect(resolve(decl, [forge, pct("a", 100)], v)).toBe("a");
78 const role: Rule = { flag: "t.split", scope: "role", subject: "admin", value: "b", pct: 0 };
79 expect(resolve(decl, [pct("a", 100), role], v)).toBe("b");
80 const user: Rule = { flag: "t.split", scope: "user", subject: "u1", value: "a", pct: 0 };
81 expect(resolve(decl, [role, user], v)).toBe("a");
82 expect(resolve(decl, [forge], undefined)).toBe("b");
83 });
84 });
85
86 describe("the forge", () => {
87 let dir: string;
88 let app: App;
89 let servers: Servers;
90 const name = FLAGS[0]!.name;
91
92 beforeAll(async () => {
93 dir = await mkdtemp(join(tmpdir(), "flags-"));
94 app = createApp({ dataDir: dir, port: 0 });
95 servers = await serve(app);
96 for (const [username, adminIfFirst] of [["alice", true], ["bob", false]] as const) {
97 const made = await createUser(app.db, {
98 trusted: true,
99 username,
100 email: `${username}@forge.local`,
101 password: "correct horse battery",
102 adminIfFirst,
103 });
104 if (!made.ok) throw new Error(made.error);
105 }
106 });
107 afterAll(async () => {
108 servers.stop();
109 app.close();
110 await rm(dir, { recursive: true, force: true });
111 });
112
113 const login = async (username: string): Promise<string> => {
114 const res = await fetch(`${servers.url}/signin`, {
115 method: "POST",
116 redirect: "manual",
117 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url },
118 body: new URLSearchParams({ username, password: "correct horse battery" }),
119 });
120 return (res.headers.get("set-cookie") ?? "").split(";")[0]!;
121 };
122
123 test("rules are validated at the boundary", () => {
124 const base = { flag: name, scope: "forge", subject: "", value: "compact", pct: 0 };
125 expect(setRule(app.db, { ...base, flag: "no.such" })).toBeString();
126 expect(setRule(app.db, { ...base, value: "huge" })).toBeString();
127 expect(setRule(app.db, { ...base, scope: "galaxy" })).toBeString();
128 expect(setRule(app.db, { ...base, scope: "percent", pct: 101 })).toBeString();
129 expect(setRule(app.db, { ...base, scope: "role", subject: "king" })).toBeString();
130 expect(setRule(app.db, { ...base, scope: "user", subject: "nobody" })).toBeString();
131 });
132
133 test("the read-out counts match the use table, once per request", async () => {
134 const admin = await login("alice");
135 clearRule(app.db, name, "forge", "");
136 expect(setRule(app.db, { flag: name, scope: "role", subject: "admin", value: "compact", pct: 0 })).toBeUndefined();
137 const before = readout(app.db, name);
138 for (let i = 0; i < 3; i++) {
139 const res = await fetch(`${servers.url}/settings/flags`, { headers: { cookie: admin } });
140 expect(res.status).toBe(200);
141 expect(await res.text()).toContain('data-density="compact"');
142 }
143 const anon = await fetch(`${servers.url}/signin`);
144 expect(await anon.text()).toContain('data-density="comfortable"');
145 const after = readout(app.db, name);
146 const n = (r: typeof after, v: string) => r.find((x) => x.variant === v)!;
147 expect(n(after, "compact").d7 - n(before, "compact").d7).toBe(3);
148 expect(n(after, "comfortable").d7 - n(before, "comfortable").d7).toBe(1);
149 // the table itself says the same
150 flushUse(app.db);
151 const row = app.db
152 .query<{ n: number }, [string]>("SELECT SUM(n) AS n FROM flag_use WHERE flag = ?1 AND variant = 'compact'")
153 .get(name)!;
154 expect(row.n).toBe(n(after, "compact").d30);
155 });
156
outdated

This test never calls readout, so the 7/30-day window isn't checked. Assert readout(app.db, name, now) with rows at now-10d (in d30, not d7) and now-40d (in neither).

157 test("old days fall out of the 7-day window but stay in the 30", () => {
158 const now = Date.parse("2026-10-13T12:00:00Z");
159 const base = readout(app.db, name, now).find((x) => x.variant === "compact")!;
160 countUse(app.db, name, "compact", now - 10 * 86_400_000);
161 countUse(app.db, name, "compact", now - 40 * 86_400_000);
162 const r = readout(app.db, name, now).find((x) => x.variant === "compact")!;
163 expect(r.d7 - base.d7).toBe(0);
164 expect(r.d30 - base.d30).toBe(1);
165 });
166
167 test("a newer value replaces the older one in the same scope", () => {
168 clearRule(app.db, name, "forge", "");
169 expect(setRule(app.db, { flag: name, scope: "forge", subject: "", value: "compact", pct: 0 })).toBeUndefined();
170 expect(setRule(app.db, { flag: name, scope: "forge", subject: "", value: "comfortable", pct: 0 })).toBeUndefined();
171 const rows = app.db.query("SELECT value FROM flag_rule WHERE flag = ?1 AND scope = 'forge'").all(name);
172 expect(rows).toEqual([{ value: "comfortable" }]);
173 });
174
175 test("the page is for admins; every mutation is same-origin; a winner replaces all rules", async () => {
176 const admin = await login("alice");
177 const bob = await login("bob");
178 expect((await fetch(`${servers.url}/settings/flags`, { headers: { cookie: bob } })).status).toBe(404);
179 expect((await fetch(`${servers.url}/settings/flags`, { redirect: "manual" })).status).not.toBe(200);
180 const post = (path: string, body: Record<string, string>, cookie = admin, origin = servers.url) =>
181 fetch(`${servers.url}${path}`, {
182 method: "POST",
183 redirect: "manual",
184 headers: { cookie, origin, "content-type": "application/x-www-form-urlencoded" },
185 body: new URLSearchParams(body),
186 });
187 const cross = await post("/settings/flags/winner", { flag: name, winner: "compact" }, admin, "https://evil.example");
188 expect(cross.status).toBeGreaterThanOrEqual(400);
189 const forbidden = await post("/settings/flags/winner", { flag: name, winner: "compact" }, bob);
190 expect(forbidden.status).not.toBe(303);
191 const set = await post("/settings/flags/set", { flag: name, value: "compact", scope: "percent", pct: "40", subject: "" });
192 expect(set.status).toBe(303);
193 const won = await post("/settings/flags/winner", { flag: name, winner: "comfortable" });
194 expect(won.status).toBe(303);
195 const rules = app.db.query("SELECT scope, value FROM flag_rule WHERE flag = ?1").all(name);
196 expect(rules).toEqual([{ scope: "forge", value: "comfortable" }]);
197 expect(crownWinner(app.db, name, "bogus")).toBeString();
198 });
199
200 test("the terminal lists flags for an admin and refuses everyone else", () => {
201 clearRule(app.db, name, "forge", "");
202 setRule(app.db, { flag: name, scope: "forge", subject: "", value: "compact", pct: 0 });
203 const admin = { db: app.db, user: { isAdmin: true } } as never;
204 const lines = flagLines(admin);
205 expect(lines[0]).toContain(name);
206 expect(lines.join("\n")).toContain("rule forge → compact");
207 const member = { db: app.db, user: { isAdmin: false } } as never;
208 expect(() => flagsScreen(member, {} as never, {} as never)).toThrow();
209 });
210
211 test("the terminal's set, remove and winner prompts write through the core, admins only", () => {
212 const toasts: string[] = [];
213 const ctx = { toast: (m: string) => toasts.push(m), pop() {}, push() {}, setCursor() {} } as never;
214 const submit = (screen: { key(e: never): boolean }, text: string) => {
215 for (const ch of text) screen.key({ key: ch } as never);
216 screen.key({ key: "enter" } as never);
217 };
218 const admin = { db: app.db, user: { isAdmin: true } } as never;
219 const member = { db: app.db, user: { isAdmin: false } } as never;
220 const count = () => app.db.query("SELECT COUNT(*) AS n FROM flag_rule WHERE flag = ?1").get(name) as { n: number };
221 const parent = {} as never;
222 clearRule(app.db, name, "forge", "");
223 submit(setFlagScreen(admin, ctx, parent) as never, `${name} compact role member`);
224 expect(app.db.query("SELECT value FROM flag_rule WHERE flag = ?1 AND scope = 'role'").all(name)).toEqual([{ value: "compact" }]);
225 submit(setFlagScreen(member, ctx, parent) as never, `${name} compact`);
226 expect(count().n).toBe(1);
227 submit(clearFlagScreen(member, ctx, parent) as never, `${name} role member`);
228 expect(count().n).toBe(1);
229 submit(clearFlagScreen(admin, ctx, parent) as never, `${name} role member`);
230 expect(count().n).toBe(0);
231 setRule(app.db, { flag: name, scope: "forge", subject: "", value: "compact", pct: 0 });
232 submit(winnerFlagScreen(member, ctx, parent) as never, `${name} comfortable`);
233 expect(app.db.query("SELECT value FROM flag_rule WHERE flag = ?1").all(name)).toEqual([{ value: "compact" }]);
234 submit(winnerFlagScreen(admin, ctx, parent) as never, `${name} comfortable`);
235 expect(app.db.query("SELECT value FROM flag_rule WHERE flag = ?1").all(name)).toEqual([{ value: "comfortable" }]);
236 expect(toasts.length).toBe(3);
237 });
238 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs