Skip to content

Open source CapCut alternative.

TypeScript

feat(site): runtime settings and experiment assignment

David Led202221a8536
diff --git a/site/prisma/Auth.prisma b/site/prisma/Auth.prisma
index 88fb5938..13f16380 100644
--- a/site/prisma/Auth.prisma
+++ b/site/prisma/Auth.prisma
@@ -27,6 +27,8 @@ model User {
onboarding UserOnboarding?
emailSettings UserEmailSettings?
outreach UserOutreach[]
+ experimentAssignments ExperimentAssignment[]
+ experimentHoldout ExperimentHoldout?
@@map("user")
}
diff --git a/site/prisma/Experiments.prisma b/site/prisma/Experiments.prisma
new file mode 100644
index 00000000..686da9e2
--- /dev/null
+++ b/site/prisma/Experiments.prisma
@@ -0,0 +1,68 @@
+// Runtime configuration and experiments. Every tunable is declared in code
+// (src/lib/config/registry.ts) with a default and a schema; a row here exists
+// only for a key a super user changed from su.donkeycut.com.
+
+model SettingOverride {
+ key String @id
+ value Json
+ actorUserId String?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+}
+
+// An experiment is a set of variants, each carrying a full value for every
+// setting it changes, drawn by the accounts in its audience.
+model Experiment {
+ id String @id @default(cuid())
+ key String @unique
+ name String
+ description String?
+ status String @default("draft") // draft | running | paused | ended
+ // [{ key, name, weight, config: { <settingKey>: <full value> } }]; the
+ // first variant is the control the others are measured against.
+ variants Json
+ // Who can be enrolled (src/lib/config/audience.ts). {} admits everyone.
+ audience Json @default("{}")
+ // Share of the audience enrolled, 0..100.
+ percent Int @default(100)
+ // What the results job measures (src/lib/config/experiment.ts); the first
+ // metric decides the verdict.
+ metrics Json @default("[]")
+ // The last computed results and when (src/lib/config/results.ts).
+ results Json?
+ resultsAt DateTime?
+ startedAt DateTime?
+ endedAt DateTime?
+ actorUserId String?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ assignments ExperimentAssignment[]
+}
+
+// Sticky: once a user is assigned, the row is what they read, whatever the
+// audience says later. A null variant holds the user out of this experiment.
+// A manual row was written from su and stands in place of the hash.
+model ExperimentAssignment {
+ id String @id @default(cuid())
+ experimentId String
+ experiment Experiment @relation(fields: [experimentId], references: [id], onDelete: Cascade)
+ userId String
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ variant String?
+ manual Boolean @default(false)
+ country String?
+ assignedAt DateTime @default(now())
+ exposedAt DateTime?
+
+ @@unique([experimentId, userId])
+ @@index([userId])
+}
+
+// Accounts kept out of every experiment: staff, testers, anyone who asked.
+model ExperimentHoldout {
+ userId String @id
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ note String?
+ actorUserId String?
+ createdAt DateTime @default(now())
+}
diff --git a/site/src/app/api/account/config/route.ts b/site/src/app/api/account/config/route.ts
new file mode 100644
index 00000000..981c25a3
--- /dev/null
+++ b/site/src/app/api/account/config/route.ts
@@ -0,0 +1,34 @@
+import { NextResponse } from "next/server";
+
+import { contextFromRequest, getEffectiveConfig } from "@/lib/config/effective";
+import { publicSubset } from "@/lib/config/resolve";
+import { withDonkeyAuth } from "@/lib/donkey-api-auth";
+import { prisma } from "@/lib/prisma";
+
+// The signed-in caller's configuration: the public settings after overrides
+// and experiments, and the variant they hold in each running experiment.
+// Reading is exposure — the app is about to act on these values — so the
+// unexposed assignments are stamped here and named back, and the browser
+// reports those first exposures to analytics.
+export const GET = withDonkeyAuth(async (request) => {
+ const ctx = await contextFromRequest(request);
+ const config = await getEffectiveConfig(ctx);
+
+ const unexposed = config.assignments.filter((a) => a.exposedAt === null);
+ if (unexposed.length > 0) {
+ await prisma.experimentAssignment.updateMany({
+ where: {
+ userId: ctx.userId,
+ experimentId: { in: unexposed.map((a) => a.experimentId) },
+ exposedAt: null,
+ },
+ data: { exposedAt: new Date() },
+ });
+ }
+
+ return NextResponse.json({
+ settings: publicSubset(config.settings),
+ experiments: config.experiments,
+ exposed: unexposed.map((a) => a.key),
+ });
+});
diff --git a/site/src/cut/components/RequireSession.tsx b/site/src/cut/components/RequireSession.tsx
index 0a769f4c..55c9c4de 100644
--- a/site/src/cut/components/RequireSession.tsx
+++ b/site/src/cut/components/RequireSession.tsx
@@ -8,8 +8,9 @@ import {
rememberedEngineUser,
setEngineUser,
} from "@/cut/lib/api";
-import { useAppLoaded } from "@/lib/analytics";
+import { reportExposures, useAppLoaded } from "@/lib/analytics";
import { authClient } from "@/lib/auth-client";
+import { useAccountConfig } from "@/queries/accountConfig";
// Session gate for the whole Cut app surface. The landing CTAs already route
// signed-out clicks through /sign-in (useAppEntryHref); this covers direct
@@ -26,6 +27,15 @@ export function RequireSession({ children }: { children: ReactNode }) {
useAppLoaded("cut", session?.user);
+ // The account's configuration — public settings after overrides and
+ // experiments — fetched behind the first paint, once the session is known.
+ // Reading it is exposure, reported after `identify` above has bound the id.
+ const config = useAccountConfig({ enabled: Boolean(userId) });
+ useEffect(() => {
+ if (!userId || !config.data) return;
+ reportExposures(config.data);
+ }, [userId, config.data]);
+
// Paint first, verify behind: the account remembered from the last visit
// opens the gate immediately, so a reload shows cached shelves while the
// session request is still in flight. The resolved session overrides it —
diff --git a/site/src/lib/analytics.ts b/site/src/lib/analytics.ts
index d865a871..8ca85168 100644
--- a/site/src/lib/analytics.ts
+++ b/site/src/lib/analytics.ts
@@ -33,6 +33,9 @@ export type AnalyticsEvents = {
cut_credits_pill_clicked: { dollars: number };
cut_storage_upgrade_shown: { source: "quota-413" | "pill" };
cut_grace_banner_shown: void;
+ // First exposure to an experiment variant; the same value rides every
+ // later event as a super property ($feature/<experiment>).
+ experiment_exposed: { experiment: string; variant: string; $set: Record<string, string> };
// Preview timing from an account that turned diagnostics on, one summary per
// half minute of playback. Numbers only — see `PerfSample` in the Cut
// preview's perfTrace for what each one means and why it is here.
@@ -79,6 +82,46 @@ export function useAppLoaded(
}, [app, id, email]);
}
+// Runs once per page load, after `identify`: every assignment becomes a super
+// property so any later event breaks down by variant, and a first exposure is
+// its own event with the variant pinned on the person. A property registered
+// on an earlier visit is dropped when the account no longer holds that
+// experiment, so an ended one stops tagging events.
+const REGISTERED_KEY = "dk-experiment-features";
+let exposuresReported = false;
+
+function readRegistered(): string[] {
+ try {
+ const raw = window.localStorage.getItem(REGISTERED_KEY);
+ const parsed: unknown = raw ? JSON.parse(raw) : [];
+ return Array.isArray(parsed) ? parsed.filter((k): k is string => typeof k === "string") : [];
+ } catch {
+ return [];
+ }
+}
+
+export function reportExposures(config: { experiments: Record<string, string>; exposed: string[] }): void {
+ if (exposuresReported) return;
+ exposuresReported = true;
+ const keys = Object.keys(config.experiments);
+ const features: Record<string, string> = {};
+ for (const [key, variant] of Object.entries(config.experiments)) features[`$feature/${key}`] = variant;
+ for (const stale of readRegistered()) {
+ if (!keys.includes(stale)) posthog.unregister(`$feature/${stale}`);
+ }
+ try {
+ window.localStorage.setItem(REGISTERED_KEY, JSON.stringify(keys));
+ } catch {
+ // A browser that refuses storage still reports this load correctly.
+ }
+ if (keys.length) posthog.register(features);
+ for (const key of config.exposed) {
+ const variant = config.experiments[key];
+ if (!variant) continue;
+ track("experiment_exposed", { experiment: key, variant, $set: { [`experiment_${key}`]: variant } });
+ }
+}
+
export function track<Name extends keyof AnalyticsEvents>(
name: Name,
...props: AnalyticsEvents[Name] extends void
diff --git a/site/src/lib/config/audienceFacts.ts b/site/src/lib/config/audienceFacts.ts
new file mode 100644
index 00000000..87e7b5d5
--- /dev/null
+++ b/site/src/lib/config/audienceFacts.ts
@@ -0,0 +1,64 @@
+import { cutLimitsForTier } from "@/cut/server/cloud/limits";
+import { usageBytes } from "@/cut/server/cloud/usage";
+import type { AudienceFact, AudienceFacts } from "@donkeycut/abexp";
+import { PURCHASE_SOURCES } from "@/lib/config/purchases";
+import { getActiveProSubscription } from "@/lib/billing/pro-subscription";
+import { prisma } from "@/lib/prisma";
+
+// Collects the facts an audience needs about one account, and only those: an
+// experiment over countries costs no billing query, and an account that
+// already holds every running experiment costs none at all.
+
+const clampPercent = (x: number) => Math.min(100, Math.max(0, x));
+
+export async function collectFacts(
+ userId: string,
+ known: { country: string | null; createdAt: Date },
+ needs: Set<AudienceFact>,
+): Promise<AudienceFacts> {
+ const facts: AudienceFacts = {
+ country: known.country,
+ createdAt: known.createdAt,
+ pro: false,
+ paid: false,
+ lastActiveAt: null,
+ storageUsedPercent: null,
+ creditsUsedPercent: null,
+ };
+ const wantsPro = needs.has("pro") || needs.has("storageUsedPercent");
+ const [pro, paid, session, storage, credits] = await Promise.all([
+ wantsPro ? getActiveProSubscription(userId) : null,
+ needs.has("paid")
+ ? prisma.userCreditGrant.count({ where: { userId, source: { in: [...PURCHASE_SOURCES] } } })
+ : 0,
+ needs.has("lastActiveAt")
+ ? prisma.session.findFirst({ where: { userId }, orderBy: { updatedAt: "desc" }, select: { updatedAt: true } })
+ : null,
+ needs.has("storageUsedPercent")
+ ? Promise.all([
+ usageBytes(userId),
+ prisma.user.findUnique({ where: { id: userId }, select: { superUser: true } }),
+ ])
+ : null,
+ needs.has("creditsUsedPercent")
+ ? prisma.userCreditAccount.findUnique({
+ where: { userId },
+ select: { lifetimeGrantedMicros: true, lifetimeChargedMicros: true },
+ })
+ : null,
+ ]);
+ facts.pro = pro !== null;
+ facts.paid = paid > 0;
+ facts.lastActiveAt = session?.updatedAt ?? null;
+ if (storage) {
+ const [bytes, user] = storage;
+ const quota = cutLimitsForTier({ superUser: user?.superUser ?? false, pro: facts.pro }).storageBytes;
+ facts.storageUsedPercent = quota === null ? null : clampPercent((100 * bytes) / quota);
+ }
+ if (credits) {
+ const granted = Number(credits.lifetimeGrantedMicros);
+ const charged = Number(credits.lifetimeChargedMicros);
+ facts.creditsUsedPercent = granted > 0 ? clampPercent((100 * charged) / granted) : null;
+ }
+ return facts;
+}
diff --git a/site/src/lib/config/effective.ts b/site/src/lib/config/effective.ts
new file mode 100644
index 00000000..b4f373ed
--- /dev/null
+++ b/site/src/lib/config/effective.ts
@@ -0,0 +1,177 @@
+import type { Prisma } from "@/generated/prisma/client";
+import { isEligible, pickVariant } from "@donkeycut/abexp";
+import { audienceNeeds, audienceSchema, type Audience, type AudienceFact } from "@donkeycut/abexp";
+import { collectFacts } from "@/lib/config/audienceFacts";
+import { variantSchema, type ExperimentVariant } from "@/lib/config/experiment";
+import type { SettingKey, Settings } from "@/lib/config/registry";
+import { resolveSettings } from "@/lib/config/resolve";
+import type { DonkeyAuthenticatedRequest } from "@/lib/donkey-api-auth";
+import { prisma } from "@/lib/prisma";
+
+// What one user's configuration is right now: overrides from su, plus the
+// variants of every running experiment they are assigned to. Assignment
+// happens here, on first read, and sticks.
+
+export type ConfigContext = {
+ userId: string;
+ country: string | null;
+ createdAt: Date;
+ // False for a caller with no account row (the dev bypass): settings still
+ // resolve, experiments never assign.
+ hasAccount: boolean;
+};
+
+export type Assignment = {
+ experimentId: string;
+ key: string;
+ variant: string;
+ exposedAt: Date | null;
+};
+
+export type EffectiveConfig = {
+ settings: Settings;
+ // experiment key → variant key, for every experiment applied.
+ experiments: Record<string, string>;
+ assignments: Assignment[];
+ invalid: { key: SettingKey; layer: "override" | "variant" }[];
+};
+
+const COUNTRY_HEADER = "x-vercel-ip-country";
+
+export function countryFromHeaders(headers: Headers): string | null {
+ const raw = headers.get(COUNTRY_HEADER)?.trim().toUpperCase();
+ return raw && /^[A-Z]{2}$/.test(raw) ? raw : null;
+}
+
+export async function contextFromRequest(request: DonkeyAuthenticatedRequest): Promise<ConfigContext> {
+ const user = await prisma.user.findUnique({
+ where: { id: request.donkey.userId },
+ select: { createdAt: true },
+ });
+ return {
+ userId: request.donkey.userId,
+ country: countryFromHeaders(request.headers),
+ createdAt: user?.createdAt ?? new Date(0),
+ hasAccount: user !== null,
+ };
+}
+
+export async function readOverrides(): Promise<Record<string, unknown>> {
+ const rows = await prisma.settingOverride.findMany({ select: { key: true, value: true } });
+ return Object.fromEntries(rows.map((row) => [row.key, row.value]));
+}
+
+export function parseVariants(raw: Prisma.JsonValue): ExperimentVariant[] {
+ const parsed = variantSchema.array().safeParse(raw);
+ return parsed.success ? parsed.data : [];
+}
+
+/** An audience that no longer parses admits nobody. */
+export function parseAudience(raw: Prisma.JsonValue): Audience | null {
+ const parsed = audienceSchema.safeParse(raw);
+ return parsed.success ? parsed.data : null;
+}
+
+export async function getEffectiveConfig(ctx: ConfigContext): Promise<EffectiveConfig> {
+ const [overrides, experiments, existing, holdout] = await Promise.all([
+ readOverrides(),
+ prisma.experiment.findMany({
+ where: { status: { in: ["running", "paused"] } },
+ // Fixed order, so two experiments that touch one setting resolve the
+ // same way on every request: the one started later wins.
+ orderBy: [{ createdAt: "asc" }, { id: "asc" }],
+ select: { id: true, key: true, status: true, variants: true, audience: true, percent: true },
+ }),
+ ctx.hasAccount
+ ? prisma.experimentAssignment.findMany({
+ where: { userId: ctx.userId },
+ select: { experimentId: true, variant: true, exposedAt: true },
+ })
+ : Promise.resolve([]),
+ ctx.hasAccount
+ ? prisma.experimentHoldout.findUnique({ where: { userId: ctx.userId }, select: { userId: true } })
+ : Promise.resolve(null),
+ ]);
+ const heldOut = holdout !== null;
+
+ const byExperiment = new Map(existing.map((a) => [a.experimentId, a]));
+ const candidates = experiments
+ .filter((e) => e.status === "running" && !byExperiment.has(e.id))
+ .map((e) => ({ ...e, variants: parseVariants(e.variants), audience: parseAudience(e.audience) }))
+ .filter((e): e is typeof e & { audience: Audience } => e.audience !== null);
+
+ if (ctx.hasAccount && !heldOut && candidates.length > 0) {
+ const needs = new Set<AudienceFact>();
+ for (const e of candidates) for (const fact of audienceNeeds(e.audience)) needs.add(fact);
+ const now = new Date();
+ const facts = await collectFacts(ctx.userId, { country: ctx.country, createdAt: ctx.createdAt }, needs);
+ const assign = { userId: ctx.userId, facts, now };
+ const fresh: Prisma.ExperimentAssignmentCreateManyInput[] = [];
+ for (const experiment of candidates) {
+ if (!isEligible(experiment, assign)) continue;
+ const variant = pickVariant(experiment, ctx.userId);
+ if (!variant) continue;
+ fresh.push({ experimentId: experiment.id, userId: ctx.userId, variant, country: ctx.country });
+ }
+ if (fresh.length > 0) {
+ await prisma.experimentAssignment.createMany({ data: fresh, skipDuplicates: true });
+ // Re-read so a concurrent first request's row wins over ours.
+ const rows = await prisma.experimentAssignment.findMany({
+ where: { userId: ctx.userId, experimentId: { in: fresh.map((f) => f.experimentId) } },
+ select: { experimentId: true, variant: true, exposedAt: true },
+ });
+ for (const row of rows) byExperiment.set(row.experimentId, row);
+ }
+ }
+
+ // A paused or ended experiment neither assigns nor applies; its rows stay so
+ // a resume picks up where it left off. A held-out account and a row with no
+ // variant read the plain configuration.
+ const assignments: Assignment[] = [];
+ const applied: Record<string, string> = {};
+ const variantConfigs: Record<string, unknown>[] = [];
+ // setting key → the experiment already varying it, to name a clash.
+ const carriedBy = new Map<string, string>();
+ for (const experiment of experiments) {
+ const row = byExperiment.get(experiment.id);
+ if (heldOut || !row || row.variant === null || experiment.status !== "running") continue;
+ const variant = parseVariants(experiment.variants).find((v) => v.key === row.variant);
+ if (!variant) continue;
+ assignments.push({
+ experimentId: experiment.id,
+ key: experiment.key,
+ variant: row.variant,
+ exposedAt: row.exposedAt,
+ });
+ applied[experiment.key] = row.variant;
+ for (const key of Object.keys(variant.config)) {
+ const other = carriedBy.get(key);
+ if (other) {
+ console.error(
+ `[config] experiments "${other}" and "${experiment.key}" both set "${key}"; the later one wins`,
+ );
+ }
+ carriedBy.set(key, experiment.key);
+ }
+ variantConfigs.push(variant.config);
+ }
+
+ const resolved = resolveSettings(overrides, variantConfigs);
+ for (const bad of resolved.invalid) {
+ console.error(`[config] ${bad.layer} for setting "${bad.key}" no longer parses; skipped`);
+ }
+ return { settings: resolved.settings, experiments: applied, assignments, invalid: resolved.invalid };
+}
+
+/** One setting for a signed-in caller, experiments included. */
+export async function getSetting<K extends SettingKey>(key: K, ctx: ConfigContext): Promise<Settings[K]> {
+ const config = await getEffectiveConfig(ctx);
+ return config.settings[key];
+}
+
+/** One setting with overrides only, for webhooks and jobs that act for no
+ * particular caller. */
+export async function getGlobalSetting<K extends SettingKey>(key: K): Promise<Settings[K]> {
+ const resolved = resolveSettings(await readOverrides(), []);
+ return resolved.settings[key];
+}
diff --git a/site/src/lib/config/experiment.ts b/site/src/lib/config/experiment.ts
new file mode 100644
index 00000000..c696087c
--- /dev/null
+++ b/site/src/lib/config/experiment.ts
@@ -0,0 +1,22 @@
+import { experimentSchemas } from "@donkeycut/abexp";
+
+import { SETTINGS } from "@/lib/config/registry";
+
+// The experiment schemas bound to this product's registry, so the su form and
+// the route validate variant settings against the same declarations.
+
+export {
+ EXPERIMENT_STATUSES,
+ METRIC_SOURCES,
+ STATUS_TRANSITIONS,
+ canTransition,
+ metricSchema,
+ removedAssignedVariants,
+ statusSchema,
+ type ExperimentInput,
+ type ExperimentMetric,
+ type ExperimentStatus,
+ type ExperimentVariant,
+} from "@donkeycut/abexp";
+
+export const { variantSchema, experimentSchema } = experimentSchemas(SETTINGS);
diff --git a/site/src/lib/config/experimentList.ts b/site/src/lib/config/experimentList.ts
new file mode 100644
index 00000000..6958e4ee
--- /dev/null
+++ b/site/src/lib/config/experimentList.ts
@@ -0,0 +1,131 @@
+import type { Prisma } from "@/generated/prisma/client";
+import { audienceSchema, EVERYONE, type Audience } from "@donkeycut/abexp";
+import { metricSchema, variantSchema, type ExperimentMetric } from "@/lib/config/experiment";
+import type { ExperimentResults } from "@donkeycut/abexp";
+import { prisma } from "@/lib/prisma";
+
+// The experiments list as su draws it: the definition, how many accounts each
+// variant holds and how many were shown it, the rows written by hand, and
+// the last computed results.
+
+const summarySelect = {
+ id: true,
+ key: true,
+ name: true,
+ description: true,
+ status: true,
+ variants: true,
+ audience: true,
+ percent: true,
+ metrics: true,
+ results: true,
+ resultsAt: true,
+ startedAt: true,
+ endedAt: true,
+ createdAt: true,
+ updatedAt: true,
+} satisfies Prisma.ExperimentSelect;
+
+type ExperimentRow = Prisma.ExperimentGetPayload<{ select: typeof summarySelect }>;
+
+export type VariantStats = { key: string; assigned: number; exposed: number };
+
+export type ManualAssignment = { userId: string; email: string; variant: string | null };
+
+export async function experimentSummary(row: ExperimentRow) {
+ // Counts come from the database, so an experiment with a hundred thousand
+ // accounts costs the same as one with ten; only the rows written by hand
+ // are listed, and there are never many.
+ const [assigned, exposed, manual] = await Promise.all([
+ prisma.experimentAssignment.groupBy({
+ by: ["variant"],
+ where: { experimentId: row.id, manual: false },
+ _count: { _all: true },
+ }),
+ prisma.experimentAssignment.groupBy({
+ by: ["variant"],
+ where: { experimentId: row.id, manual: false, exposedAt: { not: null } },
+ _count: { _all: true },
+ }),
+ prisma.experimentAssignment.findMany({
+ where: { experimentId: row.id, manual: true },
+ select: { userId: true, variant: true, user: { select: { email: true } } },
+ }),
+ ]);
+ const countBy = (rows: { variant: string | null; _count: { _all: number } }[]) =>
+ new Map(rows.map((r) => [r.variant, r._count._all]));
+ const assignedBy = countBy(assigned);
+ const exposedBy = countBy(exposed);
+ const variants = variantSchema.array().safeParse(row.variants);
+ const stats: VariantStats[] = (variants.success ? variants.data : []).map((variant) => ({
+ key: variant.key,
+ assigned: assignedBy.get(variant.key) ?? 0,
+ exposed: exposedBy.get(variant.key) ?? 0,
+ }));
+ const overrides: ManualAssignment[] = manual.map((a) => ({
+ userId: a.userId,
+ email: a.user.email,
+ variant: a.variant,
+ }));
+ const audience = audienceSchema.safeParse(row.audience);
+ const metrics = metricSchema.array().safeParse(row.metrics);
+ return {
+ id: row.id,
+ key: row.key,
+ name: row.name,
+ description: row.description,
+ status: row.status,
+ variants: variants.success ? variants.data : [],
+ audience: (audience.success ? audience.data : EVERYONE) as Audience,
+ percent: row.percent,
+ metrics: (metrics.success ? metrics.data : []) as ExperimentMetric[],
+ results: (row.results as ExperimentResults | null) ?? null,
+ resultsAt: row.resultsAt?.toISOString() ?? null,
+ startedAt: row.startedAt?.toISOString() ?? null,
+ endedAt: row.endedAt?.toISOString() ?? null,
+ createdAt: row.createdAt.toISOString(),
+ updatedAt: row.updatedAt.toISOString(),
+ stats,
+ overrides,
+ };
+}
+
+
+export type ExperimentSummary = Awaited<ReturnType<typeof experimentSummary>>;
+
+export async function listExperiments() {
+ const rows = await prisma.experiment.findMany({
+ orderBy: [{ createdAt: "desc" }],
+ select: summarySelect,
+ });
+ return Promise.all(rows.map(experimentSummary));
+}
+
+export async function findExperiment(id: string) {
+ return prisma.experiment.findUnique({ where: { id }, select: summarySelect });
+}
+
+export type HoldoutRow = { userId: string; email: string; note: string | null; createdAt: string };
+
+export async function listHoldout(): Promise<HoldoutRow[]> {
+ const rows = await prisma.experimentHoldout.findMany({
+ orderBy: { createdAt: "desc" },
+ select: { userId: true, note: true, createdAt: true, user: { select: { email: true } } },
+ });
+ return rows.map((r) => ({
+ userId: r.userId,
+ email: r.user.email,
+ note: r.note,
+ createdAt: r.createdAt.toISOString(),
+ }));
+}
+
+export function invalidResponse(issues: { path: PropertyKey[]; message: string }[]) {
+ return Response.json(
+ {
+ error: "Invalid request",
+ issues: issues.map((issue) => ({ message: issue.message, path: issue.path.join(".") })),
+ },
+ { status: 400 },
+ );
+}
diff --git a/site/src/lib/config/purchases.ts b/site/src/lib/config/purchases.ts
new file mode 100644
index 00000000..853bf5d1
--- /dev/null
+++ b/site/src/lib/config/purchases.ts
@@ -0,0 +1,3 @@
+// The credit-grant sources that mean money changed hands: a one-time top-up
+// and a Pro billing period. Audiences and the purchase metric both read them.
+export const PURCHASE_SOURCES = ["stripe_topup", "pro_subscription"] as const;
diff --git a/site/src/lib/config/registry.test.ts b/site/src/lib/config/registry.test.ts
new file mode 100644
index 00000000..f4d07e02
--- /dev/null
+++ b/site/src/lib/config/registry.test.ts
@@ -0,0 +1,37 @@
+import { DEFAULT_THRESHOLDS } from "@donkeycut/abexp";
+import { describe, expect, test } from "bun:test";
+
+import { PUBLIC_SETTING_KEYS, SETTINGS, SETTING_KEYS, defaultSettings } from "./registry";
+import { publicSubset, resolveSettings } from "./resolve";
+
+describe("the product's settings registry", () => {
+ test("every default parses against its schema", () => {
+ for (const key of SETTING_KEYS) {
+ expect(SETTINGS[key].schema.safeParse(SETTINGS[key].default).success).toBe(true);
+ }
+ });
+
+ test("the public subset carries only public keys", () => {
+ expect(Object.keys(publicSubset(defaultSettings())).sort()).toEqual([...PUBLIC_SETTING_KEYS].sort());
+ });
+
+ test("the verdict bars ship as the package's defaults", () => {
+ const shipped = defaultSettings().experimentResults;
+ expect(shipped.graceDays).toBe(30);
+ expect(shipped.shipPValue).toBe(DEFAULT_THRESHOLDS.shipPValue);
+ expect(shipped.minExposedPerVariant).toBe(DEFAULT_THRESHOLDS.minExposedPerVariant);
+ });
+
+ test("a bad override is reported and the default stands", () => {
+ const resolved = resolveSettings({ experimentResults: { graceDays: "soon" } }, []);
+ expect(resolved.settings.experimentResults).toEqual(SETTINGS.experimentResults.default);
+ expect(resolved.invalid).toEqual([{ key: "experimentResults", layer: "override" }]);
+ });
+
+ test("an override of one field replaces the whole value", () => {
+ const value = { ...SETTINGS.experimentResults.default, shipPValue: 0.1 };
+ const resolved = resolveSettings({ experimentResults: value }, []);
+ expect(resolved.settings.experimentResults.shipPValue).toBe(0.1);
+ expect(resolved.invalid).toEqual([]);
+ });
+});
diff --git a/site/src/lib/config/registry.ts b/site/src/lib/config/registry.ts
new file mode 100644
index 00000000..6c3aafd4
--- /dev/null
+++ b/site/src/lib/config/registry.ts
@@ -0,0 +1,68 @@
+import {
+ DEFAULT_THRESHOLDS,
+ defaultSettings as defaultsOf,
+ defineSettings,
+ publicSettingKeys,
+ settingKeys,
+ type PublicKeyOf,
+ type PublicSettingsOf,
+ type SettingsOf,
+} from "@donkeycut/abexp";
+import { z } from "zod";
+
+// The settings registry: every runtime tunable the product has, declared once
+// with a schema and a default. A value resolves default < override < variant
+// (src/lib/config/resolve.ts); su edits the override, an experiment supplies
+// the variant. Client-safe: zod only, so the su forms read the same
+// declarations the server validates against. A feature that people might
+// tune ships its setting here in the same change.
+
+export const SETTINGS = defineSettings({
+ experimentResults: {
+ schema: z
+ .object({
+ // An ended experiment keeps getting a fresh read for this long, so
+ // late conversions still land in it.
+ graceDays: z.number().int().min(0).max(365),
+ // The sample a positive result is believed on.
+ minExposedPerVariant: z.number().int().min(1),
+ minConversions: z.number().int().min(1),
+ // The smaller sample a loss can be called on.
+ earlyMinExposed: z.number().int().min(1),
+ earlyMinConversions: z.number().int().min(1),
+ shipPValue: z.number().min(0).max(1),
+ stopProbability: z.number().min(0).max(1),
+ // The lift the sample-size estimate plans for.
+ plannedRelativeLift: z.number().min(0.01).max(10),
+ })
+ .strict(),
+ default: {
+ graceDays: 30,
+ minExposedPerVariant: DEFAULT_THRESHOLDS.minExposedPerVariant,
+ minConversions: DEFAULT_THRESHOLDS.minConversions,
+ earlyMinExposed: DEFAULT_THRESHOLDS.earlyMinExposed,
+ earlyMinConversions: DEFAULT_THRESHOLDS.earlyMinConversions,
+ shipPValue: DEFAULT_THRESHOLDS.shipPValue,
+ stopProbability: DEFAULT_THRESHOLDS.stopProbability,
+ plannedRelativeLift: DEFAULT_THRESHOLDS.plannedRelativeLift,
+ },
+ public: false,
+ title: "Experiment results",
+ description:
+ "The bars a verdict is called against, and how long an ended experiment keeps being recomputed.",
+ },
+});
+
+export type SettingKey = keyof typeof SETTINGS;
+export type Settings = SettingsOf<typeof SETTINGS>;
+export type PublicSettingKey = PublicKeyOf<typeof SETTINGS>;
+export type PublicSettings = PublicSettingsOf<typeof SETTINGS>;
+
+export const SETTING_KEYS = settingKeys(SETTINGS);
+export const PUBLIC_SETTING_KEYS = publicSettingKeys(SETTINGS);
+
+export const isSettingKey = (key: string): key is SettingKey => key in SETTINGS;
+
+export function defaultSettings(): Settings {
+ return defaultsOf(SETTINGS);
+}
diff --git a/site/src/lib/config/resolve.ts b/site/src/lib/config/resolve.ts
new file mode 100644
index 00000000..4e64d25a
--- /dev/null
+++ b/site/src/lib/config/resolve.ts
@@ -0,0 +1,22 @@
+import {
+ publicSubset as publicSubsetOf,
+ resolveSettings as resolveOf,
+ type Resolved as ResolvedOf,
+} from "@donkeycut/abexp";
+
+import { SETTINGS, type PublicSettings, type Settings } from "@/lib/config/registry";
+
+// The package's resolution bound to this product's registry.
+
+export type Resolved = ResolvedOf<typeof SETTINGS>;
+
+export function resolveSettings(
+ overrides: Record<string, unknown>,
+ variantConfigs: Record<string, unknown>[],
+): Resolved {
+ return resolveOf(SETTINGS, overrides, variantConfigs);
+}
+
+export function publicSubset(settings: Settings): PublicSettings {
+ return publicSubsetOf(SETTINGS, settings);
+}
diff --git a/site/src/queries/accountConfig.ts b/site/src/queries/accountConfig.ts
new file mode 100644
index 00000000..bac5e50c
--- /dev/null
+++ b/site/src/queries/accountConfig.ts
@@ -0,0 +1,30 @@
+"use client";
+
+import { useQuery } from "@tanstack/react-query";
+
+import type { PublicSettings } from "@/lib/config/registry";
+import { apiFetch } from "@/queries/apiClient";
+
+export const accountConfigQueryKey = ["account", "config"] as const;
+
+export type AccountConfig = {
+ settings: PublicSettings;
+ // experiment key → the variant this account holds.
+ experiments: Record<string, string>;
+ // Experiment keys this read exposed for the first time.
+ exposed: string[];
+};
+
+// Fetched once per page load from the session gate. It never refetches on
+// focus: a variant switching under someone mid-session is the one thing an
+// experiment must not do.
+export function useAccountConfig({ enabled }: { enabled: boolean }) {
+ return useQuery({
+ enabled,
+ queryFn: () => apiFetch<AccountConfig>("/api/account/config"),
+ queryKey: accountConfigQueryKey,
+ refetchOnWindowFocus: false,
+ retry: false,
+ staleTime: Infinity,
+ });
+}