Skip to content

Open source CapCut alternative.

TypeScript

refactor(site): make Cut tunables constants [rebuild]

David Lee0b91dc297f8
diff --git a/site/scripts/eval-cut-clip.ts b/site/scripts/eval-cut-clip.ts
index 7303269f..fac97692 100644
--- a/site/scripts/eval-cut-clip.ts
+++ b/site/scripts/eval-cut-clip.ts
@@ -11,7 +11,7 @@
* transcript whose good and flat stretches are known.
*
* The questions come from the tool's own module, so what is measured is what
- * ships. Thresholds come from the settings registry for the same reason.
+ * ships. Thresholds come from CUT_CLIP for the same reason.
*
* Runs against the judge adapter straight from the environment, so it needs
* no server and spends no credits:
@@ -22,7 +22,7 @@
* server up with DONKEY_DEV_AUTH_BYPASS=1 (scripts only — never the app).
*/
-import { SETTINGS } from "../src/lib/config/registry";
+import { CUT_CLIP } from "../src/cut/lib/chatRuntime";
import { typesafeJudge } from "../src/lib/inference/adapters/typesafe";
import type { Entry, JudgeQuestion } from "../src/lib/inference/judge";
import { CLIP_QUESTIONS, findHighlights, type SpeechSegment } from "../src/cut/lib/highlights";
@@ -34,7 +34,7 @@ const argValue = (flag: string) => {
};
const BASE = argValue("--base");
const ONLY = argValue("--only");
-const settings = SETTINGS.cutClip.default;
+const settings = CUT_CLIP;
const judge = typesafeJudge();
if (!BASE && !judge.configured) {
diff --git a/site/scripts/eval-cut-export-memory.ts b/site/scripts/eval-cut-export-memory.ts
index 2a66cc17..f44d549f 100644
--- a/site/scripts/eval-cut-export-memory.ts
+++ b/site/scripts/eval-cut-export-memory.ts
@@ -25,7 +25,7 @@ import { tmpdir } from "node:os";
import path from "node:path";
import { retimeOf } from "@donkeycut/effects-kit";
import { runExport, type ExportSpec, type RenderHandle } from "../src/cut/server/exportPipeline";
-import { SETTINGS } from "../src/lib/config/registry";
+import { CUT_EXPORT_PASSES } from "../src/cut/lib/exportPassSettings";
const SITE = path.resolve(import.meta.dir, "..");
const REPORT = path.resolve(SITE, "..", "evals", "cut-export-memory.latest-report.json");
@@ -54,7 +54,7 @@ const CUT_COUNTS = [60, 180] as const;
const GROWTH_MAX = 1.5;
/** The most any export may peak at: the pass budget, which a reordered edit
* spends on frames waiting for their turn, plus the process around it. */
-const PEAK_MAX_MB = SETTINGS.cutExportPasses.default.holdMB + 512;
+const PEAK_MAX_MB = CUT_EXPORT_PASSES.holdMB + 512;
type Order = "in order" | "reordered";
diff --git a/site/scripts/eval-cut-instant.ts b/site/scripts/eval-cut-instant.ts
index 1477b992..883bbba0 100644
--- a/site/scripts/eval-cut-instant.ts
+++ b/site/scripts/eval-cut-instant.ts
@@ -6,7 +6,7 @@
*
* Every case is judged once and the composition is replayed under a grid of
* floors in code, so the sweep costs no extra calls. The report names the
- * best set; the `cutJudge` registry defaults are set from it.
+ * best set; the CUT_JUDGE floors are set from it.
*
* Two kinds of mistake, and they do not cost the same. A WRONG call edits
* the project without asking, so it is the one to drive to zero; a MISS
@@ -23,7 +23,7 @@
* dev-server-only and spend no credits.
*/
-import { SETTINGS } from "../src/lib/config/registry";
+import { CUT_JUDGE } from "../src/cut/lib/chatRuntime";
import {
availableActions,
instantAction,
@@ -45,7 +45,7 @@ const BASE = argValue("--base") ?? "http://localhost:3000";
const ONLY = argValue("--only");
const SWEEP = !args.includes("--no-sweep");
-const defaults = SETTINGS.cutJudge.default;
+const defaults = CUT_JUDGE;
type Settings = typeof defaults;
async function judge(state: unknown, questions: Record<string, unknown>) {
diff --git a/site/scripts/eval-cut-routing.ts b/site/scripts/eval-cut-routing.ts
index da19f290..9622cfad 100644
--- a/site/scripts/eval-cut-routing.ts
+++ b/site/scripts/eval-cut-routing.ts
@@ -2,7 +2,7 @@
/**
* The Cut routing eval: what the turn judge decides for a labelled set of
* asks — the skill it attaches, the tool areas it declares, the gate side —
- * and how the thresholds in the `cutJudge` setting trade suggestion
+ * and how the CUT_JUDGE thresholds trade suggestion
* accuracy against declared tool count.
*
* Every case is judged once (the answers are cached for the run), then the
@@ -21,7 +21,7 @@
* dev-server-only and spend no credits.
*/
-import { SETTINGS } from "../src/lib/config/registry";
+import { CUT_JUDGE } from "../src/cut/lib/chatRuntime";
import { noul } from "../src/lib/inference/judge";
import { AI_SKILL_INDEX, areaTools, CORE_TOOLS, TOOL_AREA_NAMES } from "../src/cut/server/ai/catalog";
import { judgeTurnState, pickSkill, routeTurn, TURN_JUDGE_QUESTIONS, type TurnJudgeAnswers } from "../src/cut/lib/turnJudge";
@@ -73,7 +73,7 @@ interface Summary {
meanTools: number;
}
-function summarize(judged: Judged[], settings: typeof SETTINGS.cutJudge.default): Summary {
+function summarize(judged: Judged[], settings: typeof CUT_JUDGE): Summary {
let skillWrong = 0;
let skillNeedless = 0;
let skillMissed = 0;
@@ -109,7 +109,7 @@ const pct = (n: number, d: number) => `${Math.round((100 * n) / Math.max(1, d))}
async function main() {
const selected = routingCases.filter((c) => !ONLY || c.request.includes(ONLY));
if (selected.length === 0) throw new Error(`No case matching "${ONLY}".`);
- const defaults = SETTINGS.cutJudge.default;
+ const defaults = CUT_JUDGE;
console.log(`== routing cases=${selected.length} skills=${AI_SKILL_INDEX.length} areas=${TOOL_AREA_NAMES.length}`);
const judged: Judged[] = [];
diff --git a/site/src/clients/chatgpt/server/mcp.ts b/site/src/clients/chatgpt/server/mcp.ts
index e8d53318..24777625 100644
--- a/site/src/clients/chatgpt/server/mcp.ts
+++ b/site/src/clients/chatgpt/server/mcp.ts
@@ -18,8 +18,7 @@ import {
} from "@/clients/chatgpt/server/catalog";
import { MAX_COMMANDS_PER_BATCH } from "@/cut/server/cloud/commands";
import { DOC_EXPORT_PRESETS } from "@/cut/lib/exportPresets";
-import { bindCutLoudness, cutLoudness, LOUDNESS_CHOICES, LOUDNESS_IDS } from "@/cut/lib/loudnessSettings";
-import { getGlobalSetting } from "@/lib/config/effective";
+import { CUT_LOUDNESS, LOUDNESS_CHOICES, LOUDNESS_IDS } from "@/cut/lib/loudnessSettings";
import { formatCredits } from "@/lib/credits/format-credits";
import {
chatgptConfig,
@@ -430,7 +429,7 @@ export function createChatgptServer(
{
title: "Export a project",
description:
- `Render the saved project to an MP4 the user downloads from the Donkey Cut card. preset: ${DOC_EXPORT_PRESETS.join(" | ")} (original matches the footage; tiktok is best quality 1080p; fast is a smaller 1080p; light is a 720p draft). loudness masters the mix to an integrated target under a true-peak ceiling: ${LOUDNESS_CHOICES.map((c) => (c.id === "off" ? "off (the mix as it plays)" : `${c.id} ${cutLoudness().targets[c.id]} LUFS (${c.detail})`)).join(", ")}; the true-peak ceiling is ${cutLoudness().truePeakCeiling} dBTP; omitted masters to ${cutLoudness().defaultTarget}. stems: true also writes one 24-bit WAV per lane (dialogue from the video clips, then each soundtrack lane), full length and unmastered, zipped as "<name> stems.zip" beside the video in the project's exports. Free; the files count against the account's cloud storage and are listed in the project's exports. A render can outlast this call — finish it with get_export_status.`,
+ `Render the saved project to an MP4 the user downloads from the Donkey Cut card. preset: ${DOC_EXPORT_PRESETS.join(" | ")} (original matches the footage; tiktok is best quality 1080p; fast is a smaller 1080p; light is a 720p draft). loudness masters the mix to an integrated target under a true-peak ceiling: ${LOUDNESS_CHOICES.map((c) => (c.id === "off" ? "off (the mix as it plays)" : `${c.id} ${CUT_LOUDNESS.targets[c.id]} LUFS (${c.detail})`)).join(", ")}; the true-peak ceiling is ${CUT_LOUDNESS.truePeakCeiling} dBTP; omitted masters to ${CUT_LOUDNESS.defaultTarget}. stems: true also writes one 24-bit WAV per lane (dialogue from the video clips, then each soundtrack lane), full length and unmastered, zipped as "<name> stems.zip" beside the video in the project's exports. Free; the files count against the account's cloud storage and are listed in the project's exports. A render can outlast this call — finish it with get_export_status.`,
inputSchema: z.object({
projectId: idSchema,
preset: z.enum(DOC_EXPORT_PRESETS).optional(),
@@ -611,8 +610,6 @@ export async function mcpEndpoint(request: Request) {
return rateLimitResponse(rateLimit.retryAfterSeconds);
}
- // export_video teaches the loudness targets the worker will master to.
- bindCutLoudness(await getGlobalSetting("cutLoudness"));
const handler = chatgptHttpHandler(identity, config);
try {
const response = await handler.fetch(request);
diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsx
index d7e00719..2aab71f1 100644
--- a/site/src/cut/components/AiPanel.tsx
+++ b/site/src/cut/components/AiPanel.tsx
@@ -4,7 +4,7 @@ import { useQueryClient, type QueryClient } from "@tanstack/react-query";
import { notesKey } from "@/cut/lib/queries";
import { ChatStatusBadge, type ChatStatus } from "./ChatStatusBadge";
-import { chatRuntime, cutJudge } from "@/cut/lib/chatRuntime";
+import { CHAT_RUNTIME, CUT_JUDGE } from "@/cut/lib/chatRuntime";
import { ChatRequests } from "@/cut/lib/chatRequests";
import { Fragment, memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type ReactNode } from "react";
import { Chat, useChat } from "@ai-sdk/react";
@@ -610,9 +610,9 @@ export function AiPanel({
const refresh = async () => {
if (!document.hidden && useEditor.getState().projectId === projectId)
await ensureCloudThreads(projectId, true);
- if (!stopped) timer = setTimeout(() => void refresh(), chatRuntime().syncIntervalMs);
+ if (!stopped) timer = setTimeout(() => void refresh(), CHAT_RUNTIME.syncIntervalMs);
};
- timer = setTimeout(() => void refresh(), chatRuntime().syncIntervalMs);
+ timer = setTimeout(() => void refresh(), CHAT_RUNTIME.syncIntervalMs);
return () => { stopped = true; clearTimeout(timer); };
}, [projectId]);
@@ -1213,7 +1213,7 @@ function ChatSession({
api: localBackend.url("/api/cut/ai/chat"),
body: {
threadId,
- runtime: chatRuntime(),
+ runtime: CHAT_RUNTIME,
messages,
model: currentModel(),
context,
@@ -1762,7 +1762,7 @@ function ChatSession({
// second; the cadence and the in-flight count keep it to one call at a time.
useEffect(() => {
if (!busy || queuePaused || readOnly) return;
- const { queueRetriageMs } = cutJudge();
+ const { queueRetriageMs } = CUT_JUDGE;
if (queueRetriageMs <= 0) return;
const rows = () => queueRef.current.filter((m) => m.status === "queued" && m.id !== queueEditingRef.current);
let timer: ReturnType<typeof setTimeout>;
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsx
index 4d611d5c..9c0ea56e 100644
--- a/site/src/cut/components/Editor.tsx
+++ b/site/src/cut/components/Editor.tsx
@@ -1,6 +1,6 @@
"use client";
-import { chatRuntime } from "@/cut/lib/chatRuntime";
+import { CHAT_RUNTIME } from "@/cut/lib/chatRuntime";
import { useHostBridge, useHostReady } from "@/cut/lib/hostBridge";
import { useCutMode } from "@/cut/lib/backend/hooks";
import { usePhoneInbox } from "@/cut/hooks/usePhoneInbox";
@@ -355,7 +355,7 @@ export function Editor({
const tick = async () => {
if (stopped || polling) return;
polling = true;
- let nextIn = document.hidden ? VIEWER_POLL_MAX_MS : (viewer ? VIEWER_POLL_MIN_MS : chatRuntime().syncIntervalMs);
+ let nextIn = document.hidden ? VIEWER_POLL_MAX_MS : (viewer ? VIEWER_POLL_MIN_MS : CHAT_RUNTIME.syncIntervalMs);
try {
const current = useEditor.getState();
if (!document.hidden && current.projectId === projectId && current.loaded &&
@@ -400,7 +400,7 @@ export function Editor({
};
document.addEventListener("visibilitychange", focus);
window.addEventListener("focus", focus);
- timer = setTimeout(() => void tick(), viewer ? VIEWER_POLL_MIN_MS : chatRuntime().syncIntervalMs);
+ timer = setTimeout(() => void tick(), viewer ? VIEWER_POLL_MIN_MS : CHAT_RUNTIME.syncIntervalMs);
return () => {
stopped = true;
document.removeEventListener("visibilitychange", focus);
diff --git a/site/src/cut/components/ExportDialog.tsx b/site/src/cut/components/ExportDialog.tsx
index ae1b1db8..470975ba 100644
--- a/site/src/cut/components/ExportDialog.tsx
+++ b/site/src/cut/components/ExportDialog.tsx
@@ -46,7 +46,7 @@ import { useExports } from "@/cut/lib/exportStore";
import { projectDuration, useEditor } from "@/cut/lib/store";
import { subtitleFiles } from "@/cut/lib/subtitleFile";
import { formatTime } from "@/cut/lib/time";
-import { cutLoudness, LOUDNESS_CHOICES, loudnessLabel, loudnessSettings, type LoudnessId } from "@/cut/lib/loudnessSettings";
+import { CUT_LOUDNESS, LOUDNESS_CHOICES, loudnessLabel, loudnessSettings, type LoudnessId } from "@/cut/lib/loudnessSettings";
import { planStems } from "@/cut/lib/stems";
import { cn } from "@/lib/utils";
@@ -109,7 +109,7 @@ export function ExportDialog() {
// A captions file beside the video.
const [withCaptions, setWithCaptions] = useState(false);
// The loudness the mix is mastered to, starting on the account's default.
- const [loudness, setLoudness] = useState<LoudnessId>(() => cutLoudness().defaultTarget);
+ const [loudness, setLoudness] = useState<LoudnessId>(() => CUT_LOUDNESS.defaultTarget);
// A zip of one WAV per lane beside the video.
const [withStems, setWithStems] = useState(false);
const canStem = useMemo(() => planStems({ clips, audioClips, assets }).length > 0, [clips, audioClips, assets]);
@@ -413,7 +413,7 @@ export function ExportDialog() {
hint={
loudness === "off"
? undefined
- : `Sets the whole mix to its target and holds true peaks under ${String(cutLoudness().truePeakCeiling).replace("-", "−")} dBTP.`
+ : `Sets the whole mix to its target and holds true peaks under ${String(CUT_LOUDNESS.truePeakCeiling).replace("-", "−")} dBTP.`
}
>
<Select value={loudness} onValueChange={(v) => setLoudness(v as LoudnessId)}>
diff --git a/site/src/cut/components/MotionControls.tsx b/site/src/cut/components/MotionControls.tsx
index 55824acd..e459afbc 100644
--- a/site/src/cut/components/MotionControls.tsx
+++ b/site/src/cut/components/MotionControls.tsx
@@ -27,7 +27,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@
import { Switch } from "@/components/ui/switch";
import { groupCameraOf, groupCameraPoseAt } from "@/cut/lib/groupCamera";
import { sharedNumber, sharedValue } from "@/cut/lib/groupEdit";
-import { cutMotion } from "@/cut/lib/motionSettings";
+import { CUT_MOTION } from "@/cut/lib/motionSettings";
import { usePreviewTime } from "@/cut/lib/playhead";
import { useEditor } from "@/cut/lib/store";
import { clipPoseAt, isEffectOverlay, type Overlay, type VideoClip } from "@/cut/lib/types";
@@ -81,7 +81,7 @@ function MotionBlurRows({
{shutter?.mixed && <Value className="text-muted-foreground italic">Mixed</Value>}
<Switch
checked={!!shutter && !shutter.mixed}
- onCheckedChange={(on) => onChange(on ? cutMotion().motionBlur : undefined, "once")}
+ onCheckedChange={(on) => onChange(on ? CUT_MOTION.motionBlur : undefined, "once")}
aria-label="Motion blur"
/>
</Row>
diff --git a/site/src/cut/components/NotesView.tsx b/site/src/cut/components/NotesView.tsx
index dd2465e6..ff054f08 100644
--- a/site/src/cut/components/NotesView.tsx
+++ b/site/src/cut/components/NotesView.tsx
@@ -26,7 +26,7 @@ import {
type CutNoteFolder,
} from "@/cut/lib/notes";
import { homeHref, useCutBase } from "@/cut/lib/nav";
-import { cutNotes } from "@/cut/lib/chatRuntime";
+import { CUT_NOTES } from "@/cut/lib/chatRuntime";
import { notesKey, patchNotes, useNotes } from "@/cut/lib/queries";
import { cn } from "@/lib/utils";
import { setObjectDragImage } from "@/cut/lib/assetDrag";
@@ -416,7 +416,7 @@ export function NotesView({ library, ref }: Props = {}) {
autosave.current = setTimeout(() => {
autosave.current = null;
if (buffer.current) void save(buffer.current);
- }, cutNotes().autosaveMs);
+ }, CUT_NOTES.autosaveMs);
};
/** Save whatever the composer holds one last time and let go of it. */
diff --git a/site/src/cut/components/RequireSession.tsx b/site/src/cut/components/RequireSession.tsx
index d06662a4..ee658a08 100644
--- a/site/src/cut/components/RequireSession.tsx
+++ b/site/src/cut/components/RequireSession.tsx
@@ -1,12 +1,4 @@
"use client";
-import { bindChatRuntime, bindChatgptPolling, bindCutClip, bindCutJudge, bindCutNotes, bindCutTracking, bindCutUploads } from "@/cut/lib/chatRuntime";
-import { bindCutColor } from "@/cut/lib/colorSettings";
-import { bindCutExportPasses } from "@/cut/lib/exportPassSettings";
-import { bindCutSound } from "@/cut/lib/soundSettings";
-import { bindCutMotion } from "@/cut/lib/motionSettings";
-import { bindCutFontMatch } from "@/cut/lib/fontMatchSettings";
-import { bindCutLoudness } from "@/cut/lib/loudnessSettings";
-import { bindCutMediaCache } from "@/cut/lib/chunkCache";
import { useEffect, type ReactNode } from "react";
import { useEnvironment } from "@/cut/lib/environment";
@@ -64,20 +56,6 @@ export function RequireSession({ children }: { children: ReactNode }) {
const config = useAccountConfig({ enabled: Boolean(userId) });
useEffect(() => {
if (!userId || !config.data) return;
- bindChatRuntime(config.data.settings.chatRuntime);
- bindChatgptPolling(config.data.settings.chatgptPolling);
- bindCutJudge(config.data.settings.cutJudge);
- bindCutClip(config.data.settings.cutClip);
- bindCutNotes(config.data.settings.cutNotes);
- bindCutTracking(config.data.settings.cutTracking);
- bindCutUploads(config.data.settings.cutUploads);
- bindCutColor(config.data.settings.cutColor);
- bindCutSound(config.data.settings.cutSound);
- bindCutMotion(config.data.settings.cutMotion);
- bindCutFontMatch(config.data.settings.cutFontMatch);
- bindCutLoudness(config.data.settings.cutLoudness);
- bindCutExportPasses(config.data.settings.cutExportPasses);
- bindCutMediaCache(config.data.settings.cutMediaCache);
reportExposures(config.data);
}, [userId, config.data]);
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index 83393865..42d0ec1d 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -138,7 +138,7 @@ import type { GroupPanelToolName } from "@/cut/components/GroupPanel.tools";
import { CAMERA_SCALE_MAX, CAMERA_SCALE_MIN, CAMERA_WORLD_MAX, CAMERA_WORLD_MIN, ELEMENT_BLUR_MAX, SHUTTER_MAX, SHUTTER_MIN, TILT_MAX, isEaseId, upsertKey as upsertCameraKey, type CameraKey } from "@donkeycut/effects-kit";
import { cleanInks, LETTER_SPACING_MAX, LETTER_SPACING_MIN, PATTERN_KINDS, SHADOW_BLUR_MAX, SHADOW_OFFSET_MAX, STRIPE_GAP_MAX, STRIPE_LINE_MAX, STRIPE_LINE_MIN, STRIPES_DEFAULT, type PatternSpec, type ShadowSpec } from "@donkeycut/effects-kit";
import { groupCameraOf, groupCameraPoseAt } from "@/cut/lib/groupCamera";
-import { cutMotion } from "@/cut/lib/motionSettings";
+import { CUT_MOTION } from "@/cut/lib/motionSettings";
import type { LibraryToolName } from "@/cut/components/LibraryView.tools";
import type { PreviewToolName } from "@/cut/components/Preview.tools";
import type { RemovalToolName } from "@/cut/components/RemovalPanel.tools";
@@ -239,7 +239,7 @@ import { renderMix } from "./audioMix";
import { measureLoudnessSliced, roundedLoudness, type LoudnessMeasure } from "./loudness";
import { frameAt, framesAt, readMediaFileSize } from "./mediaRead";
import { bundledFaces, inkMaskOf, rankFaces } from "./fontMatch";
-import { cutFontMatch } from "./fontMatchSettings";
+import { CUT_FONT_MATCH } from "./fontMatchSettings";
import { COMPARE_MODES, MAX_COMPARE, SWEEP_TARGET } from "./frameDiff";
import { compareMoments, sweepSource } from "./sourceCompare";
import { findPicture, sampleColors, scanCuts, trackElement, type FrameBox } from "./measure/sourceMeasure";
@@ -295,7 +295,7 @@ import { readHostedError } from "./hostedError";
import { creditPriceQuote, type CreditPriceSheet } from "@/lib/credits/price-sheet";
import { creditsFromDollars } from "@/lib/credits/format-credits";
import { BLOCK_MAX_SECONDS, BLOCK_MIN_SECONDS, BLOCKOUT_MAX, blockAsset } from "./blockSource";
-import { cutClip, cutJudge } from "./chatRuntime";
+import { CUT_CLIP, CUT_JUDGE } from "./chatRuntime";
import { FOLLOW_MODES } from "./trackKeys";
import { trackMotion } from "./trackMotion";
import { TRACK_TARGET_IDS, TRACK_USES } from "./trackTargets";
@@ -2093,7 +2093,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
} catch (e) {
throw new ToolError(`Filler detection is unavailable: ${e instanceof Error ? e.message : String(e)}`);
}
- const floor = cutJudge().fillerCut;
+ const floor = CUT_JUDGE.fillerCut;
const toSource = clip ? (t: number) => roundT(retimeOf(clip).srcAt(clamp(t - clip.start, 0, Infinity))) : null;
// Neighbouring filler words are one span: "you know" is a single cut,
// and every span the caller gets is a cut it can make in one call.
@@ -2205,7 +2205,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
size: m.typePx > 0 ? Math.round((m.typePx / k / Math.min(fw * area.w, fh * area.h)) * DESIGN_SHORT_SIDE) : null,
tracking: m.tracking,
}));
- const good = cutFontMatch().goodScore;
+ const good = CUT_FONT_MATCH.goodScore;
const best = matches[0];
const round3 = (v: number) => Math.round(v * 1000) / 1000;
return {
@@ -2477,7 +2477,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
const hits = sweepPicks(
answers as Record<string, { type: "noul"; noul: number } | undefined>,
items,
- cutJudge().sweepFit
+ CUT_JUDGE.sweepFit
).sort((a, b) => b.fit - a.fit);
const kept = isNum(input.limit) ? hits.slice(0, Math.max(1, Math.floor(input.limit))) : hits;
return {
@@ -2710,10 +2710,10 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
const count = isNum(input.count) ? clamp(Math.round(input.count), 1, 20) : 5;
const post = (payload: Record<string, unknown>, signal?: AbortSignal) =>
hostedPost("/api/inference/judge", payload, signal);
- const clips = await findHighlights(post, said, cutClip(), count).catch((e) => {
+ const clips = await findHighlights(post, said, CUT_CLIP, count).catch((e) => {
throw new ToolError(`Finding the moments is unavailable: ${e instanceof Error ? e.message : String(e)}`);
});
- const settings = cutClip();
+ const settings = CUT_CLIP;
return {
source: sourceRef(asset),
searched: { from: roundT(from), to: roundT(to ?? asset.duration) },
@@ -6243,7 +6243,7 @@ async function rankStock<T extends { id: string; kind: string; category: string;
} catch (e) {
throw new ToolError(`Stock search is unavailable: ${e instanceof Error ? e.message : String(e)}`);
}
- const floor = cutJudge().stockFit;
+ const floor = CUT_JUDGE.stockFit;
return candidates
.map((c, i) => ({ c, p: answers[`fit::${i}`]?.noul ?? 0 }))
.filter((x) => x.p >= floor)
@@ -7765,7 +7765,7 @@ async function launchVideoJob(
* neither keeps `current`. */
function shutterInput(input: Record<string, unknown>, current: number | undefined): number | undefined {
if (isNum(input.shutter)) return input.shutter > 0 ? clamp(input.shutter, SHUTTER_MIN, SHUTTER_MAX) : undefined;
- if (input.motion_blur === true) return current ?? cutMotion().motionBlur;
+ if (input.motion_blur === true) return current ?? CUT_MOTION.motionBlur;
if (input.motion_blur === false) return undefined;
return current;
}
diff --git a/site/src/cut/lib/chatRuntime.ts b/site/src/cut/lib/chatRuntime.ts
index 63c92b1a..05b8e36b 100644
--- a/site/src/cut/lib/chatRuntime.ts
+++ b/site/src/cut/lib/chatRuntime.ts
@@ -1,50 +1,159 @@
-import { SETTINGS, type Settings } from "@/lib/config/registry";
-
-let runtime: Settings["chatRuntime"] = SETTINGS.chatRuntime.default;
-export function bindChatRuntime(value: unknown): void {
- const parsed = SETTINGS.chatRuntime.schema.safeParse(value);
- if (parsed.success) runtime = parsed.data;
-}
-export function chatRuntime(): Settings["chatRuntime"] { return runtime; }
-
-let polling: Settings["chatgptPolling"] = SETTINGS.chatgptPolling.default;
-export function bindChatgptPolling(value: unknown): void {
- const parsed = SETTINGS.chatgptPolling.schema.safeParse(value);
- if (parsed.success) polling = parsed.data;
-}
-export function chatgptPolling(): Settings["chatgptPolling"] { return polling; }
-
-let judge: Settings["cutJudge"] = SETTINGS.cutJudge.default;
-export function bindCutJudge(value: unknown): void {
- const parsed = SETTINGS.cutJudge.schema.safeParse(value);
- if (parsed.success) judge = parsed.data;
-}
-export function cutJudge(): Settings["cutJudge"] { return judge; }
-
-let clip: Settings["cutClip"] = SETTINGS.cutClip.default;
-export function bindCutClip(value: unknown): void {
- const parsed = SETTINGS.cutClip.schema.safeParse(value);
- if (parsed.success) clip = parsed.data;
-}
-export function cutClip(): Settings["cutClip"] { return clip; }
-
-let tracking: Settings["cutTracking"] = SETTINGS.cutTracking.default;
-export function bindCutTracking(value: unknown): void {
- const parsed = SETTINGS.cutTracking.schema.safeParse(value);
- if (parsed.success) tracking = parsed.data;
-}
-export function cutTracking(): Settings["cutTracking"] { return tracking; }
-
-let notes: Settings["cutNotes"] = SETTINGS.cutNotes.default;
-export function bindCutNotes(value: unknown): void {
- const parsed = SETTINGS.cutNotes.schema.safeParse(value);
- if (parsed.success) notes = parsed.data;
-}
-export function cutNotes(): Settings["cutNotes"] { return notes; }
-
-let uploads: Settings["cutUploads"] = SETTINGS.cutUploads.default;
-export function bindCutUploads(value: unknown): void {
- const parsed = SETTINGS.cutUploads.schema.safeParse(value);
- if (parsed.success) uploads = parsed.data;
-}
-export function cutUploads(): Settings["cutUploads"] { return uploads; }
+import { z } from "zod";
+
+// Chat continuity: project and conversation refresh cadence, scene ownership
+// expiry, and the saved engine transcript size.
+export const CHAT_RUNTIME = { syncIntervalMs: 5000, sceneLeaseMs: 30000, journalBytes: 8388608 };
+
+// The tab sends its chat runtime with every engine turn and scene lease, and
+// engines already installed require it, so the wire keeps carrying it.
+export const chatRuntimeSchema = z.object({
+ syncIntervalMs: z.number().int().min(1000).max(30000),
+ sceneLeaseMs: z.number().int().min(15000).max(120000),
+ journalBytes: z.number().int().min(1048576).max(33554432),
+}).strict();
+
+// ChatGPT editor command polling cadence and maximum failure backoff.
+export const CHATGPT_POLLING = { pollMs: 1000, hiddenPollMs: 3000, maxBackoffMs: 60000 };
+
+// Thresholds for the typed judgments that route a chat turn, run a one-action
+// turn with no model round, hold a turn back until its work is finished and
+// its reply true to it, re-place the messages waiting in the tray, pick the
+// items a sweep touches, rank stock, find filler words, and resolve voices.
+export const CUT_JUDGE = {
+ // Preload the skill the judge picks for the turn; off leaves the model to
+ // read skills on its own.
+ skillSuggestion: true,
+ // The reference-need probability below which no skill is attached.
+ skillGate: 0.4,
+ // The winning skill's own fit below which it is dropped.
+ skillFits: 0.3,
+ // Declare only the tool areas the judge routes to; off declares the whole
+ // catalog on every turn.
+ toolRouting: true,
+ // An area's probability at or above which its tools are declared.
+ toolArea: 0.2,
+ // How long the first model round waits for the judge before going out with
+ // the full catalog and no skill. Set above the judgment's slowest turns: a
+ // round that goes out early is the one a chat or complex verdict then
+ // throws away.
+ judgeWaitMs: 1000,
+ // A stock candidate's fit below which it is left out of a search.
+ stockFit: 0.5,
+ // A transcript word's disfluency probability at or above which find_filler
+ // reports it.
+ fillerCut: 0.5,
+ // The confidence below which a described voice falls back to the default.
+ voicePick: 0.4,
+ // How often a running turn re-places the messages waiting in the tray
+ // against the work it has done since; 0 places them once, at send.
+ queueRetriageMs: 4000,
+ // Run a turn the judgment settles to one known action with no model round
+ // at all; off sends every turn through the chat loop.
+ instantAction: true,
+ // The chosen action's own probability below which the turn takes the loop
+ // instead. The floors below do the same for each argument.
+ instantFloor: 0.5,
+ instantTarget: 0.5,
+ instantEnum: 0.5,
+ // A style, look or direction the request left open: several good answers
+ // split the probability, so the winner clears less.
+ instantPick: 0.15,
+ instantLevel: 0.3,
+ // A yes/no argument has to be this decisive in one direction.
+ instantBool: 0.7,
+ // An ask that names an exact figure, acts on more than one item, leaves a
+ // second edit undone, or wants the shot itself remade goes to the model at
+ // or above these.
+ instantExact: 0.4,
+ instantMulti: 0.4,
+ instantLeftover: 0.5,
+ instantRemake: 0.3,
+ // A candidate's fit below which a described sweep leaves it out.
+ sweepFit: 0.5,
+ // Judge the turn's own work before it closes; off lets a turn sign off on
+ // whatever it did.
+ qualityGate: true,
+ // The probabilities below which the work is judged unfinished, the footage
+ // under-watched, and the reply wider than the record.
+ qualityFinished: 0.5,
+ qualitySeen: 0.5,
+ qualityHonest: 0.5,
+ // The probability above which the ask is taken to want the project changed,
+ // which lets a turn that changed nothing be sent to build.
+ qualityWantsChange: 0.5,
+ // The probability above which the reply is taken to ask the one question an
+ // ambiguous ask needs answered, which closes the turn on that question.
+ qualityAsksBack: 0.5,
+ // The probability above which the ask is taken to turn on how the source
+ // sounds, which makes unplayed seconds a gap worth a round.
+ qualityHears: 0.6,
+ // The probability above which on-screen text is taken to be the source's
+ // own narration, which puts its words in the transcript and leaves only
+ // their treatment to be read off the frames.
+ qualityCaptionsSpeak: 0.7,
+ // Seconds of close reading that settle how a spoken caption track is set,
+ // once the words are known from the transcript.
+ qualityTreatmentSeconds: 8,
+ // How many times one turn may be sent back to work by the gate.
+ qualityRounds: 3,
+};
+
+// How a talk or an interview is read for the moments worth cutting a short
+// from.
+export const CUT_CLIP = {
+ // A pause this long ends a sentence when the punctuation does not.
+ pauseBreakSeconds: 0.6,
+ // What a clip may run. The sweep aims at the target and accepts anything
+ // between the bounds, ending on a sentence.
+ minSeconds: 18,
+ targetSeconds: 45,
+ maxSeconds: 75,
+ // How far apart the wide sweep's candidate starts sit. Smaller reads more
+ // of the source and costs more questions.
+ strideSeconds: 12,
+ // How many of the sweep's best earn the close read.
+ shortlist: 14,
+ // Standing alone and landing are requirements: a stretch that needs what
+ // came before it, or that trails off into the next thing, is not a clip
+ // however well it opens. Below either floor it is not offered.
+ standaloneFloor: 0.35,
+ payoffFloor: 0.5,
+ // What orders the ones that qualify.
+ standaloneWeight: 0.4,
+ hookWeight: 0.35,
+ payoffWeight: 0.25,
+ // The composite below which a moment is not offered at all.
+ rankFloor: 0.45,
+ // Second beats considered per clip, and the probability one has to reach
+ // to be cut in behind the first.
+ pairsPerClip: 3,
+ followsFloor: 0.6,
+};
+
+// How hands, heads and people are tracked through a clip.
+export const CUT_TRACKING = {
+ // Tracked frames per second of the span, and the most frames one track
+ // reads; a longer span samples more sparsely.
+ sampleFps: 30,
+ maxFrames: 1200,
+ // The decoded frame's long side the landmarkers read.
+ longSide: 1280,
+ // Detection, presence and tracking confidence floors.
+ minConfidence: 0.5,
+ // One-euro smoothing: the cutoff (Hz) a still target settles at, and how
+ // fast the cutoff rises with speed.
+ smoothCutoff: 1.5,
+ smoothBeta: 20,
+ // A dropout this short is bridged; a longer one hides the shape.
+ bridgeSeconds: 0.25,
+ // How far, in frame fractions, a dropped key may sit from the line its
+ // neighbors draw.
+ keyTolerance: 0.0015,
+};
+
+// How long a note sits still after the last keystroke before it saves.
+export const CUT_NOTES = { autosaveMs: 800 };
+
+// The pause before each automatic retry of an upload the connection dropped;
+// the browser's reconnect retries it too.
+export const CUT_UPLOADS = { resumeDelaysMs: [5000, 20000, 60000] as readonly number[] };
diff --git a/site/src/cut/lib/chunkCache.ts b/site/src/cut/lib/chunkCache.ts
index 020defe5..a2be9de9 100644
--- a/site/src/cut/lib/chunkCache.ts
+++ b/site/src/cut/lib/chunkCache.ts
@@ -54,7 +54,6 @@ import {
import { CUT_MEDIA_ORIGIN } from "./hosts";
import { allowance, holdMemory } from "./memoryBudget";
import { observeOperationResponse } from "./operationFailure";
-import { SETTINGS, type Settings } from "@/lib/config/registry";
export const CHUNK_SIZE = 2 * 1024 * 1024;
/** Longest single ranged request, in chunks, when a read needs a missing run. */
@@ -787,14 +786,7 @@ let lastEstimate: { at: number; usage: number; quota: number } | null = null;
// The browser grants an origin most of the disk, so the quota alone would let
// cached media fill the Mac. The cache keeps to its own ceiling, counted over
// the chunks here and the whole-file copies mediaSync reports.
-let cacheSetting: Settings["cutMediaCache"] = SETTINGS.cutMediaCache.default;
-export function bindCutMediaCache(value: unknown): void {
- const parsed = SETTINGS.cutMediaCache.schema.safeParse(value);
- if (parsed.success) cacheSetting = parsed.data;
-}
-export function cutMediaCache(): Settings["cutMediaCache"] {
- return cacheSetting;
-}
+export const CUT_MEDIA_CACHE = { maxBytes: 10 * 1024 ** 3 };
let tally: { at: number; bytes: number } | null = null;
let copyBytes = 0;
@@ -832,7 +824,7 @@ async function roomFor(bytes: number, keepKeyHash: string): Promise<boolean> {
const stored = await chunkStoreBytes();
let deficit = Math.max(
lastEstimate.usage + bytes + margin - lastEstimate.quota,
- stored + copyBytes + bytes - cacheSetting.maxBytes,
+ stored + copyBytes + bytes - CUT_MEDIA_CACHE.maxBytes,
);
if (deficit > 0) {
const freed = await evictChunkBytes(deficit, keepKeyHash);
diff --git a/site/src/cut/lib/colorSettings.ts b/site/src/cut/lib/colorSettings.ts
index 3c92bf6d..fa81cc45 100644
--- a/site/src/cut/lib/colorSettings.ts
+++ b/site/src/cut/lib/colorSettings.ts
@@ -1,16 +1,16 @@
-import { SETTINGS, type Settings } from "@/lib/config/registry";
-
-// The color pipeline's tunables — LUT sizes, the proxy's size and quality, the
-// LUT file cap — bound once at session start from account config (the tab) or
-// the global setting (a worker job), and read wherever a LUT is sized.
-
-let color: Settings["cutColor"] = SETTINGS.cutColor.default;
-
-export function bindCutColor(value: unknown): void {
- const parsed = SETTINGS.cutColor.schema.safeParse(value);
- if (parsed.success) color = parsed.data;
-}
-
-export function cutColor(): Settings["cutColor"] {
- return color;
-}
+// The color pipeline's constants, read wherever a LUT is sized.
+export const CUT_COLOR = {
+ // Lattice nodes per axis of a clip's color LUT: Rec.709 and sRGB sources
+ // take the smaller cube, log and HDR sources the wider one.
+ lutSize: 33,
+ lutSizeWide: 65,
+ // The cube drawn while a slider is moving; the full cube follows.
+ draftLutSize: 17,
+ // The preview proxy's largest height, and its HEVC quality (x265 crf; the
+ // VideoToolbox quality maps from it). 18 is visually lossless for 10-bit
+ // footage that is only ever previewed.
+ proxyMaxHeight: 2160,
+ proxyCrf: 18,
+ // A LUT file past this is something else.
+ lutFileMaxBytes: 64 * 1024 ** 2,
+};
diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.ts
index 46e8b721..29ae1417 100644
--- a/site/src/cut/lib/exportClient.ts
+++ b/site/src/cut/lib/exportClient.ts
@@ -9,8 +9,8 @@ import { projectOperation } from "./projectOperation";
import { apiFetch, apiJson, getBackend, type CutBackend } from "./backend";
import { engineFeatures } from "./api";
import type { EngineFeature } from "./engineFeatures";
-import { cutColor } from "./colorSettings";
-import { cutExportPasses } from "./exportPassSettings";
+import { CUT_COLOR } from "./colorSettings";
+import { CUT_EXPORT_PASSES } from "./exportPassSettings";
import { loadLibraryLutFile, lutIdOf } from "./linkedLibrary/luts";
import {
removeBrowserExportJob,
@@ -1522,9 +1522,9 @@ export async function buildExportPayload(
// The hover proxy, the share card and the streaming ladder are SDR web
// pictures whatever the project delivers.
colorSpace: target === "export" ? doc.colorSpace ?? "sdr" : "sdr",
- lutSize: cutColor().lutSize,
- lutSizeWide: cutColor().lutSizeWide,
- passes: cutExportPasses(),
+ lutSize: CUT_COLOR.lutSize,
+ lutSizeWide: CUT_COLOR.lutSizeWide,
+ passes: CUT_EXPORT_PASSES,
duration,
background: projectBackground(doc.background),
clips,
diff --git a/site/src/cut/lib/exportPassSettings.ts b/site/src/cut/lib/exportPassSettings.ts
index affeac11..c800b3d6 100644
--- a/site/src/cut/lib/exportPassSettings.ts
+++ b/site/src/cut/lib/exportPassSettings.ts
@@ -1,16 +1,10 @@
-import { SETTINGS, type Settings } from "@/lib/config/registry";
-
-// The export pass budget — the memory one ffmpeg pass may hold and the pieces
-// it opens — bound once at session start from account config (the tab) or the
-// global setting (a worker job), and sent with every export spec.
-
-let passes: Settings["cutExportPasses"] = SETTINGS.cutExportPasses.default;
-
-export function bindCutExportPasses(value: unknown): void {
- const parsed = SETTINGS.cutExportPasses.schema.safeParse(value);
- if (parsed.success) passes = parsed.data;
-}
-
-export function cutExportPasses(): Settings["cutExportPasses"] {
- return passes;
-}
+// The export pass budget, sent with every export spec.
+export const CUT_EXPORT_PASSES = {
+ // The frames one ffmpeg pass may hold, MB. A long timeline renders in
+ // passes held under it; a larger budget means fewer passes, each decoding
+ // the stretch of file its cuts span.
+ holdMB: 2048,
+ // The most pieces one pass opens, whatever their size: each brings a
+ // decoder and its threads.
+ pieces: 48,
+};
diff --git a/site/src/cut/lib/fontMatch.test.ts b/site/src/cut/lib/fontMatch.test.ts
index dbfdfd3e..8193eac1 100644
--- a/site/src/cut/lib/fontMatch.test.ts
+++ b/site/src/cut/lib/fontMatch.test.ts
@@ -5,7 +5,7 @@ import { Canvas, FontLibrary, loadImage } from "skia-canvas";
/** skia's font registry, under a name the hook lint leaves alone. */
const fontLibrary = FontLibrary;
-import { SETTINGS } from "@/lib/config/registry";
+import { CUT_FONT_MATCH } from "./fontMatchSettings";
import { setRasterFactory, type RasterFactory, type RasterSurface } from "./raster";
import { GOOGLE_FONTS } from "./fontCatalog";
import { bundledFaces, inkMaskOf, rankFaces, type TitleFace } from "./fontMatch";
@@ -72,7 +72,7 @@ function reference(text: string, css: string, opts: { tracking?: number; ink?: s
return inkMaskOf(data.data, data.width, data.height);
}
-const good = SETTINGS.cutFontMatch.default.goodScore;
+const good = CUT_FONT_MATCH.goodScore;
describe("font suggestions", () => {
test("the face the words are set in ranks first, with its tracking", async () => {
diff --git a/site/src/cut/lib/fontMatchSettings.ts b/site/src/cut/lib/fontMatchSettings.ts
index 5d698832..280bab14 100644
--- a/site/src/cut/lib/fontMatchSettings.ts
+++ b/site/src/cut/lib/fontMatchSettings.ts
@@ -1,16 +1,3 @@
-import { SETTINGS, type Settings } from "@/lib/config/registry";
-
-// Font-suggestion tunables — the score a bundled face has to reach to count as
-// the reference's face — bound once at session start from account config (the
-// tab) or the global setting (a worker job).
-
-let fontMatch: Settings["cutFontMatch"] = SETTINGS.cutFontMatch.default;
-
-export function bindCutFontMatch(value: unknown): void {
- const parsed = SETTINGS.cutFontMatch.schema.safeParse(value);
- if (parsed.success) fontMatch = parsed.data;
-}
-
-export function cutFontMatch(): Settings["cutFontMatch"] {
- return fontMatch;
-}
+// The score (0..1, glyph overlap times width agreement) a bundled face has to
+// reach before suggest_font calls it the reference's face.
+export const CUT_FONT_MATCH = { goodScore: 0.72 };
diff --git a/site/src/cut/lib/genScene.ts b/site/src/cut/lib/genScene.ts
index 9141792e..b3a6a1ee 100644
--- a/site/src/cut/lib/genScene.ts
+++ b/site/src/cut/lib/genScene.ts
@@ -1,6 +1,6 @@
"use client";
-import { chatRuntime } from "./chatRuntime";
+import { CHAT_RUNTIME } from "./chatRuntime";
import { create } from "zustand";
import { apiFetch, apiJson } from "./backend";
import { useGenerate } from "./generate";
@@ -592,7 +592,7 @@ function failed(projectId: string, orch: SceneOrchestrator): (e: unknown) => voi
const s = useEditor.getState();
if (s.projectId === projectId && s.loaded && s.genvideo && !s.readOnly && !orchestrators.has(projectId))
useGenScene.getState().hydrate(projectId, s.genvideo);
- }, chatRuntime().syncIntervalMs);
+ }, CHAT_RUNTIME.syncIntervalMs);
return;
}
if (orchestrators.get(projectId) === orch && !orch.isAborted) {
diff --git a/site/src/cut/lib/genvideo/sceneOwnership.ts b/site/src/cut/lib/genvideo/sceneOwnership.ts
index a510a447..3b4092cf 100644
--- a/site/src/cut/lib/genvideo/sceneOwnership.ts
+++ b/site/src/cut/lib/genvideo/sceneOwnership.ts
@@ -1,5 +1,5 @@
import { flushEditorSave } from "../editorWork";
-import { chatRuntime } from "../chatRuntime";
+import { CHAT_RUNTIME } from "../chatRuntime";
import { projectBackend } from "../residency";
import { useEditor } from "../store";
import { projectRevision } from "../projectRevision";
@@ -19,9 +19,9 @@ export function ownScene(projectId: string, scene: VideoOrchestrator, fresh = fa
const backend = await projectBackend(projectId);
const owner = crypto.randomUUID();
const route = `/api/cut/projects/${encodeURIComponent(projectId)}/scene-lease`;
- let leaseMs = chatRuntime().sceneLeaseMs;
+ let leaseMs = CHAT_RUNTIME.sceneLeaseMs;
const lease = async (release = false) => {
- const res = await backend.fetch(route, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ owner, release, leaseMs: chatRuntime().sceneLeaseMs }) });
+ const res = await backend.fetch(route, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ owner, release, leaseMs: CHAT_RUNTIME.sceneLeaseMs }) });
if (!res.ok) throw new Error("Could not reserve the video run.");
const result = await res.json() as { acquired: boolean; leaseMs?: number };
if (result.leaseMs) leaseMs = result.leaseMs;
diff --git a/site/src/cut/lib/highlights.test.ts b/site/src/cut/lib/highlights.test.ts
index 6409b8a5..fb821b78 100644
--- a/site/src/cut/lib/highlights.test.ts
+++ b/site/src/cut/lib/highlights.test.ts
@@ -1,9 +1,9 @@
import { describe, expect, test } from "bun:test";
-import { SETTINGS } from "@/lib/config/registry";
+import { CUT_CLIP } from "./chatRuntime";
import { highlightCandidates, rankOf, sentences } from "./highlights";
-const settings = SETTINGS.cutClip.default;
+const settings = CUT_CLIP;
const seg = (start: number, end: number, text: string) => ({ start, end, text });
describe("sentences", () => {
diff --git a/site/src/cut/lib/highlights.ts b/site/src/cut/lib/highlights.ts
index b2cb9982..c4e543b9 100644
--- a/site/src/cut/lib/highlights.ts
+++ b/site/src/cut/lib/highlights.ts
@@ -1,9 +1,9 @@
import { askJudgeChunked, noul, score } from "./judge";
import type { Entry, NoulAnswer, ScoreAnswer } from "./judge";
import type { PostFn } from "./pi/donkeyStream";
-import type { Settings } from "@/lib/config/registry";
+import type { CUT_CLIP } from "./chatRuntime";
-export type CutClipSettings = Settings["cutClip"];
+export type CutClipSettings = typeof CUT_CLIP;
/** Finding the moments in a long source worth cutting a short from.
*
@@ -18,7 +18,7 @@ export type CutClipSettings = Settings["cutClip"];
* then the shortlist earns the expensive questions (does it stand alone, does
* the opening hold, does it land) and a few boundary variants each. Code
* composes the weights and picks the non-overlapping winners, so changing what
- * "best" means is a settings change, not another round of inference.
+ * "best" means is a change to CUT_CLIP, not another round of inference.
*
* A clip does not have to be one stretch. Two moments that belong together
* cut together, and the judge says which pairs those are; the spans come back
@@ -335,7 +335,7 @@ async function judgeVariants(
}));
}
-/** The composite. Weights live in settings, so what "best" means is tuned
+/** The composite. Weights live in CUT_CLIP, so what "best" means is tuned
* without asking anything again. */
export function rankOf(h: Omit<ScoredHighlight, "rank">, settings: CutClipSettings): number {
const w = settings.standaloneWeight + settings.hookWeight + settings.payoffWeight;
diff --git a/site/src/cut/lib/hostCommandPolling.test.ts b/site/src/cut/lib/hostCommandPolling.test.ts
index c80224d3..5c09a7d9 100644
--- a/site/src/cut/lib/hostCommandPolling.test.ts
+++ b/site/src/cut/lib/hostCommandPolling.test.ts
@@ -1,8 +1,8 @@
import { expect, test } from "bun:test";
import { hostCommandPoller } from "./hostCommandPolling";
-import { SETTINGS } from "@/lib/config/registry";
+import { CHATGPT_POLLING } from "./chatRuntime";
-const settings = () => SETTINGS.chatgptPolling.default;
+const settings = () => CHATGPT_POLLING;
test("failed polls back off, remain bounded, and reset after recovery", async () => {
let status = 500;
diff --git a/site/src/cut/lib/hostCommandPolling.ts b/site/src/cut/lib/hostCommandPolling.ts
index ee554693..6b2cb70d 100644
--- a/site/src/cut/lib/hostCommandPolling.ts
+++ b/site/src/cut/lib/hostCommandPolling.ts
@@ -1,4 +1,4 @@
-import type { Settings } from "@/lib/config/registry";
+import type { CHATGPT_POLLING } from "./chatRuntime";
import type { CommandJobSpec } from "@/cut/lib/commandBatch";
type Claimed = { id: string; spec: CommandJobSpec };
@@ -7,7 +7,7 @@ type Claimed = { id: string; spec: CommandJobSpec };
export function hostCommandPoller(options: {
claim: () => Promise<Response>;
run: (job: Claimed) => Promise<void>;
- settings: () => Settings["chatgptPolling"];
+ settings: () => typeof CHATGPT_POLLING;
hidden: () => boolean;
}) {
let backoff = 0;
diff --git a/site/src/cut/lib/hostCommands.ts b/site/src/cut/lib/hostCommands.ts
index e1393a2b..9b49678c 100644
--- a/site/src/cut/lib/hostCommands.ts
+++ b/site/src/cut/lib/hostCommands.ts
@@ -1,7 +1,7 @@
"use client";
import { useEffect } from "react";
-import { chatgptPolling } from "@/cut/lib/chatRuntime";
+import { CHATGPT_POLLING } from "@/cut/lib/chatRuntime";
import { hostCommandPoller } from "@/cut/lib/hostCommandPolling";
import { runAiTool } from "./aiTools";
import { apiFetch } from "./backend";
@@ -117,7 +117,7 @@ export function useHostCommands(projectId: string, enabled: boolean): void {
const poll = hostCommandPoller({
claim: () => apiFetch(`/api/cut/projects/${projectId}/commands/claim`, { method: "POST", signal }),
run: (job) => runClaimed(projectId, job.id, job.spec, signal),
- settings: chatgptPolling,
+ settings: () => CHATGPT_POLLING,
hidden: () => document.hidden,
});
const tick = async () => {
diff --git a/site/src/cut/lib/importQueue.ts b/site/src/cut/lib/importQueue.ts
index 7b38e206..d96911fa 100644
--- a/site/src/cut/lib/importQueue.ts
+++ b/site/src/cut/lib/importQueue.ts
@@ -22,7 +22,7 @@ import { getBackend, type CutBackend } from "./backend";
import { resolveRegisteredBlob } from "./backend/browser/registry";
import type { PendingImport } from "./media";
import { storedMediaUrl } from "./mediaSync";
-import { cutUploads } from "./chatRuntime";
+import { CUT_UPLOADS } from "./chatRuntime";
import { connectionLost, isOffline, onReconnect } from "./network";
import { useEditor } from "./store";
@@ -65,7 +65,7 @@ type Job = {
const jobs = new Map<string, Job>();
// An upload the connection dropped, the way a phone hotspot does, picks back
-// up by itself: after each pause the cutUploads setting lists, and the moment
+// up by itself: after each pause CUT_UPLOADS lists, and the moment
// the browser reports the connection back, which also restarts the pauses. A
// refusal from the server waits for the user's retry.
const resumes = new Map<string, { attempt: number; timer: ReturnType<typeof setTimeout> | null }>();
@@ -104,7 +104,7 @@ export function retryFailedUploads() {
* waits per asset: a later failure replaces the booked one. */
function scheduleResume(job: Job) {
const id = job.pending.asset.id;
- const delays = cutUploads().resumeDelaysMs;
+ const delays = CUT_UPLOADS.resumeDelaysMs;
const prior = resumes.get(id);
if (prior?.timer) {
clearTimeout(prior.timer);
diff --git a/site/src/cut/lib/instantAction.test.ts b/site/src/cut/lib/instantAction.test.ts
index 3d8d47d2..08fe016f 100644
--- a/site/src/cut/lib/instantAction.test.ts
+++ b/site/src/cut/lib/instantAction.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test";
import { JUDGE_MAX_QUESTIONS } from "@/lib/inference/judge";
-import { SETTINGS } from "@/lib/config/registry";
+import { CUT_JUDGE } from "./chatRuntime";
import {
availableActions,
instantAction,
@@ -12,7 +12,7 @@ import {
type TargetKind,
} from "./instantAction";
-const settings = SETTINGS.cutJudge.default;
+const settings = CUT_JUDGE;
/** An editor snapshot in the shape buildAiContext returns, with enough on it
* for every tier of the registry to be offered. */
diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.ts
index fec5ef7a..591e0a01 100644
--- a/site/src/cut/lib/library.ts
+++ b/site/src/cut/lib/library.ts
@@ -3,7 +3,7 @@
import { uploadCloudLibraryMedia, withCloudPreparedMedia } from "@/cut/lib/cloudLibraryUpload";
import type { LibraryUploadStage, LibraryUploadState } from "@/cut/lib/libraryUpload";
import { assetTypeOf } from "@/cut/lib/media";
-import { cutColor } from "@/cut/lib/colorSettings";
+import { CUT_COLOR } from "@/cut/lib/colorSettings";
import { lutFacts, parseLutFile } from "@donkeycut/effects-kit";
import { apiJson, getBackend } from "./backend";
import { cloudBackend } from "./backend/cloud";
@@ -644,7 +644,7 @@ async function checkFont(
async function checkLut(
file: File,
): Promise<{ label: string; meta: LinkedUploadMeta }> {
- const maxBytes = cutColor().lutFileMaxBytes;
+ const maxBytes = CUT_COLOR.lutFileMaxBytes;
if (file.size > maxBytes) {
throw new Error(
`LUT files are limited to ${Math.round(maxBytes / 1024 ** 2)}MB.`,
diff --git a/site/src/cut/lib/libraryProxy.ts b/site/src/cut/lib/libraryProxy.ts
index 506dceb7..3dfa12b6 100644
--- a/site/src/cut/lib/libraryProxy.ts
+++ b/site/src/cut/lib/libraryProxy.ts
@@ -18,7 +18,7 @@ import { engineFeatures } from "./api";
import { apiJson } from "./backend";
import { pollCloudJob } from "./cloudJob";
import { browserCodecs } from "./codecSupport";
-import { cutColor } from "./colorSettings";
+import { CUT_COLOR } from "./colorSettings";
import { compatCovers } from "./proxyNames";
import type { LibraryAsset, LibraryData } from "./library";
import { useLightbox, lightboxItemFromLibrary } from "./lightbox";
@@ -81,7 +81,7 @@ export async function ensureLibraryProxy(
throw new Error("Update the Donkey app to play this video here.");
}
const backend = backendFor(a.residency);
- const { proxyMaxHeight, proxyCrf } = cutColor();
+ const { proxyMaxHeight, proxyCrf } = CUT_COLOR;
const res = await backend.fetch(`/api/cut/library/${encodeURIComponent(a.id)}/proxy`, {
method: "POST",
headers: { "Content-Type": "application/json" },
diff --git a/site/src/cut/lib/loudnessSettings.ts b/site/src/cut/lib/loudnessSettings.ts
index 9a1b6a9f..d88ae8b1 100644
--- a/site/src/cut/lib/loudnessSettings.ts
+++ b/site/src/cut/lib/loudnessSettings.ts
@@ -1,25 +1,20 @@
-import { SETTINGS, type Settings } from "@/lib/config/registry";
-
// Export loudness: the LUFS each named target masters to, the target an
-// export starts on, and the true-peak ceiling — bound once at session start
-// from account config (the tab) or the global setting (a worker job), and read
-// wherever an export's settings are made.
-
-let loudness: Settings["cutLoudness"] = SETTINGS.cutLoudness.default;
-
-export function bindCutLoudness(value: unknown): void {
- const parsed = SETTINGS.cutLoudness.schema.safeParse(value);
- if (parsed.success) loudness = parsed.data;
-}
-
-export function cutLoudness(): Settings["cutLoudness"] {
- return loudness;
-}
+// export starts on ("off" leaves the mix as mixed), and the true-peak ceiling
+// a mastered mix is held under, dBTP.
+export const CUT_LOUDNESS: {
+ targets: { social: number; podcast: number; broadcast: number };
+ defaultTarget: LoudnessId;
+ truePeakCeiling: number;
+} = {
+ targets: { social: -14, podcast: -16, broadcast: -23 },
+ defaultTarget: "off",
+ truePeakCeiling: -1,
+};
/** A loudness choice: off, or one of the named targets. */
-export type LoudnessId = Settings["cutLoudness"]["defaultTarget"];
+export type LoudnessId = "off" | "social" | "podcast" | "broadcast";
-/** The choices in menu order. The numbers come from the setting. */
+/** The choices in menu order. The numbers come from CUT_LOUDNESS. */
export const LOUDNESS_CHOICES = [
{ id: "off", label: "Off", detail: "the mix as it plays" },
{ id: "social", label: "Social", detail: "streaming and social platforms" },
@@ -32,7 +27,7 @@ export const LOUDNESS_IDS = LOUDNESS_CHOICES.map((c) => c.id) as [LoudnessId, ..
/** The settings fields a choice adds to an export: the target and the
* ceiling, or nothing for off. */
export function loudnessSettings(id: LoudnessId | undefined): { loudness?: number; truePeakCeiling?: number } {
- const s = cutLoudness();
+ const s = CUT_LOUDNESS;
const choice = id ?? s.defaultTarget;
if (choice === "off") return {};
return { loudness: s.targets[choice], truePeakCeiling: s.truePeakCeiling };
@@ -42,5 +37,5 @@ export function loudnessSettings(id: LoudnessId | undefined): { loudness?: numbe
export function loudnessLabel(id: LoudnessId): string {
const c = LOUDNESS_CHOICES.find((x) => x.id === id)!;
if (id === "off") return c.label;
- return `${c.label} · ${String(cutLoudness().targets[id]).replace("-", "−")} LUFS`;
+ return `${c.label} · ${String(CUT_LOUDNESS.targets[id]).replace("-", "−")} LUFS`;
}
diff --git a/site/src/cut/lib/lutBuild.ts b/site/src/cut/lib/lutBuild.ts
index ce0197e0..cec84cfc 100644
--- a/site/src/cut/lib/lutBuild.ts
+++ b/site/src/cut/lib/lutBuild.ts
@@ -10,7 +10,7 @@
* (the headless runner, tests) builds inline, and a caller that needs the
* exact picture now (an export) asks for it inline in the tab too.
*
- * Sizes come from the color setting: the standard cube for Rec.709 and sRGB
+ * Sizes come from CUT_COLOR: the standard cube for Rec.709 and sRGB
* sources, the wide cube for log and HDR, and a draft cube while a slider is
* moving — the full cube follows when the drag settles. The built LUTs are a
* cache bounded in bytes through the memory budget.
@@ -26,7 +26,7 @@ import {
type ParsedLut,
type SourceProfile,
} from "@donkeycut/effects-kit";
-import { cutColor } from "./colorSettings";
+import { CUT_COLOR } from "./colorSettings";
import { cachedLut, loadLibraryLut, lutIdOf } from "./linkedLibrary/luts";
import { allowance, holdMemory } from "./memoryBudget";
import { colorRead, type ReadFile } from "./sourceColor";
@@ -70,7 +70,7 @@ const isSdrSource = (profile: SourceProfile) => profile === "rec709" || profile
/** Lattice nodes per axis for a source, at draft or full quality. */
export function lutSizeFor(profile: SourceProfile, draft = false): number {
- const c = cutColor();
+ const c = CUT_COLOR;
return draft ? c.draftLutSize : isSdrSource(profile) ? c.lutSize : c.lutSizeWide;
}
diff --git a/site/src/cut/lib/mediaProxy.ts b/site/src/cut/lib/mediaProxy.ts
index e57e7dd3..51eb8dcd 100644
--- a/site/src/cut/lib/mediaProxy.ts
+++ b/site/src/cut/lib/mediaProxy.ts
@@ -38,7 +38,7 @@ import { resolveRegisteredBlob } from "./backend/browser/registry";
import { pollCloudJob } from "./cloudJob";
import { compatInTheCloud } from "./cloudLibraryUpload";
import { compatNeedOf } from "./codecSupport";
-import { cutColor } from "./colorSettings";
+import { CUT_COLOR } from "./colorSettings";
import { enrichAsset, uploadProjectMediaTo } from "./media";
import { frameSinkIsCustom, hasUndecodableVideo, probeMediaFile, setStreamCovers, withMedia } from "./mediaRead";
import { forgetLocalMediaUrl, storedMediaUrl } from "./mediaSync";
@@ -331,7 +331,7 @@ async function buildCompat(
ask: Extract<ProxyAsk, { kind: "compat" }>,
onProgress: (p: number) => void
): Promise<Landed | null> {
- const { proxyMaxHeight, proxyCrf } = cutColor();
+ const { proxyMaxHeight, proxyCrf } = CUT_COLOR;
if (backend.kind === "local" && ask.cover === "audio") {
if (!(await engineFeatures()).has("media.compat")) return null;
return requestProxy(projectId, backend, { file: asset.fileName, maxHeight: proxyMaxHeight, crf: proxyCrf, compat: ask.cover }, onProgress);
@@ -353,7 +353,7 @@ async function buildProxy(
backend: CutBackend,
onProgress: (p: number) => void
): Promise<Landed | null> {
- const { proxyMaxHeight, proxyCrf } = cutColor();
+ const { proxyMaxHeight, proxyCrf } = CUT_COLOR;
if (backend.kind === "local") {
if (!(await engineFeatures()).has("media.proxy")) return null;
return requestProxy(projectId, backend, { file: asset.fileName, maxHeight: proxyMaxHeight, crf: proxyCrf }, onProgress);
diff --git a/site/src/cut/lib/mediaSync.ts b/site/src/cut/lib/mediaSync.ts
index 934650b3..a86448cb 100644
--- a/site/src/cut/lib/mediaSync.ts
+++ b/site/src/cut/lib/mediaSync.ts
@@ -46,7 +46,7 @@ import {
import { getBackend, type CutBackend } from "./backend";
import {
chunkStoreBytes,
- cutMediaCache,
+ CUT_MEDIA_CACHE,
dropChunksMatching,
evictChunkBytes,
noteCachedCopyBytes,
@@ -361,7 +361,7 @@ const QUOTA_MARGIN = 512 * 1024 * 1024;
/** Make room for `bytes` of new media, evicting least-recently-opened cloud
* projects' cached copies until the write fits under quota and the cache
- * under its ceiling (cutMediaCache). Pinned files and browser-resident
+ * under its ceiling (CUT_MEDIA_CACHE). Pinned files and browser-resident
* projects are exempt; `keepId` (the project being written) is never a
* candidate. A pinned write (`cached` false) needs quota room only; it is no
* cache. */
@@ -387,7 +387,7 @@ async function makeRoom(keepId: string, bytes: number, cached = true): Promise<v
if (id !== keepId) candidates.push({ id, openedAt: idx.opens[id] ?? 0 });
}
noteCachedCopyBytes(copies);
- let deficit = Math.max(quotaDeficit, (await chunkStoreBytes()) + copies + (cached ? bytes : 0) - cutMediaCache().maxBytes);
+ let deficit = Math.max(quotaDeficit, (await chunkStoreBytes()) + copies + (cached ? bytes : 0) - CUT_MEDIA_CACHE.maxBytes);
if (deficit <= 0) return;
// The chunk cache is the cheapest byte to lose — losing one costs a ranged
// re-fetch, where losing a whole-file copy costs the file — so it goes first.
diff --git a/site/src/cut/lib/motionSettings.ts b/site/src/cut/lib/motionSettings.ts
index 2c34092c..f433f6d4 100644
--- a/site/src/cut/lib/motionSettings.ts
+++ b/site/src/cut/lib/motionSettings.ts
@@ -1,17 +1,5 @@
-import { SETTINGS, type Settings } from "@/lib/config/registry";
-
-// Motion tunables — the shutter a newly switched-on motion blur starts at —
-// bound once at session start from account config (the tab) or the global
-// setting (a worker job). The value is written onto the item when the blur is
-// switched on, so every renderer draws from the item alone.
-
-let motion: Settings["cutMotion"] = SETTINGS.cutMotion.default;
-
-export function bindCutMotion(value: unknown): void {
- const parsed = SETTINGS.cutMotion.schema.safeParse(value);
- if (parsed.success) motion = parsed.data;
-}
-
-export function cutMotion(): Settings["cutMotion"] {
- return motion;
-}
+// The shutter a newly switched-on motion blur starts at, as a share of a 30fps
+// frame: 0.5 is the half-open shutter of most filmed footage. The value is
+// written onto the item when the blur is switched on, so every renderer draws
+// from the item alone.
+export const CUT_MOTION = { motionBlur: 0.5 };
diff --git a/site/src/cut/lib/pi/cutAgent.test.ts b/site/src/cut/lib/pi/cutAgent.test.ts
index d485cd58..623cf65b 100644
--- a/site/src/cut/lib/pi/cutAgent.test.ts
+++ b/site/src/cut/lib/pi/cutAgent.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test";
import type { UIMessage } from "ai";
-import { SETTINGS } from "@/lib/config/registry";
+import { CUT_JUDGE } from "../chatRuntime";
import { TOOL_AREA_NAMES } from "@/cut/server/ai/catalog";
import { QUALITY_STEER_PREFIX } from "../turnQuality";
import { dropPiSession, readPiSession, streamCutChat, type CutAgentDeps } from "./cutAgent";
@@ -114,7 +114,7 @@ function harness(opts: { gateVerdicts: number[]; call?: { name: string; args: Re
headers: { "Content-Type": "application/json" },
});
},
- judgeSettings: { ...SETTINGS.cutJudge.default, instantAction: false, judgeWaitMs: 2000 },
+ judgeSettings: { ...CUT_JUDGE, instantAction: false, judgeWaitMs: 2000 },
execTool: async () => WATCH_RESULT,
models: { simple: "chatSimple", complex: "chat" },
buildContext: () => ({ project: { aspect: "9:16" }, videoTrack: [], media: [] }),
@@ -200,7 +200,7 @@ describe("the quality gate in the turn loop", () => {
const threadId = "gate-off";
dropPiSession(threadId);
const h = harness({ gateVerdicts: [0.01] });
- h.deps.judgeSettings = { ...SETTINGS.cutJudge.default, instantAction: false, qualityGate: false };
+ h.deps.judgeSettings = { ...CUT_JUDGE, instantAction: false, qualityGate: false };
await drain(
streamCutChat({ threadId, model: "chat", messages: ask("what happens in this video?"), deps: h.deps })
);
diff --git a/site/src/cut/lib/pi/cutAgent.ts b/site/src/cut/lib/pi/cutAgent.ts
index 4d3dfd46..e12a9556 100644
--- a/site/src/cut/lib/pi/cutAgent.ts
+++ b/site/src/cut/lib/pi/cutAgent.ts
@@ -19,7 +19,7 @@ import {
STEP_BUDGET,
turnClose,
} from "../turnBudget";
-import { cutJudge } from "../chatRuntime";
+import { CUT_JUDGE } from "../chatRuntime";
import {
instantAction,
instantQuestions,
@@ -76,9 +76,7 @@ export interface CutAgentDeps {
/** The judge route: typed questions over a state, answered as
* probabilities. Routes the turn and triages the queue. */
judge: PostFn;
- /** The judgment thresholds. The page binds them from the account config;
- * the worker reads them from the global settings; unset falls back to the
- * bound value (the registry default when nothing bound one). */
+ /** The judgment thresholds; unset reads CUT_JUDGE. */
judgeSettings?: CutJudgeSettings;
execTool: ExecTool;
models: { simple: string; complex: string };
@@ -519,7 +517,7 @@ export async function judgeTurnAndAction(
deps: CutAgentDeps,
abortSignal?: AbortSignal
): Promise<{ verdict: TurnVerdict; instant: ResolvedAction | null }> {
- const settings = deps.judgeSettings ?? cutJudge();
+ const settings = deps.judgeSettings ?? CUT_JUDGE;
const lastUser = messages.findLast((m) => m.role === "user");
const onSight = complexOnSight(lastUser);
if (onSight && !settings.skillSuggestion && !settings.toolRouting)
@@ -699,7 +697,7 @@ export function streamCutChat({
const askText = lastUser ? messageText(lastUser) : "";
const context = deps.buildContext();
const promptPromise = buildPrompt(lastUser, deps, context);
- const settings = deps.judgeSettings ?? cutJudge();
+ const settings = deps.judgeSettings ?? CUT_JUDGE;
// One judgment settles both: how the turn is routed, and whether it
// is a single known action the editor can carry out on its own.
const decision = judgeTurnAndAction(messages, context, deps, abortSignal);
diff --git a/site/src/cut/lib/pi/engineTurn.test.ts b/site/src/cut/lib/pi/engineTurn.test.ts
index 3af8bd49..95d45f30 100644
--- a/site/src/cut/lib/pi/engineTurn.test.ts
+++ b/site/src/cut/lib/pi/engineTurn.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test";
import type { UIMessage } from "ai";
-import { SETTINGS } from "@/lib/config/registry";
+import { CUT_JUDGE } from "../chatRuntime";
import { TOOL_AREA_NAMES } from "@/cut/server/ai/catalog";
import type { CutAgentDeps } from "./cutAgent";
import { EngineGate, engineInstant, handledSince, judgeEngineTurn } from "./engineTurn";
@@ -67,7 +67,7 @@ function deps(
headers: { "Content-Type": "application/json" },
});
},
- judgeSettings: { ...SETTINGS.cutJudge.default, instantAction: false, judgeWaitMs: 500, ...opts.settings },
+ judgeSettings: { ...CUT_JUDGE, instantAction: false, judgeWaitMs: 500, ...opts.settings },
execTool: async () => ({ ok: true }),
models: { simple: "chatSimple", complex: "chat" },
buildContext: () => ({ project: { aspect: "9:16" }, videoTrack: [], media: [] }),
diff --git a/site/src/cut/lib/pi/engineTurn.ts b/site/src/cut/lib/pi/engineTurn.ts
index f7d69ce5..346051c6 100644
--- a/site/src/cut/lib/pi/engineTurn.ts
+++ b/site/src/cut/lib/pi/engineTurn.ts
@@ -1,6 +1,6 @@
import type { UIMessage, UIMessageChunk } from "ai";
import type { EngineRoute, HandledAsk } from "@/cut/server/ai/turnCatalog";
-import { cutJudge } from "../chatRuntime";
+import { CUT_JUDGE } from "../chatRuntime";
import type { ResolvedAction } from "../instantAction";
import { messageText } from "../messageText";
import { judgeTurnAndAction, playInstant, type CutAgentDeps } from "./cutAgent";
@@ -30,7 +30,7 @@ export async function judgeEngineTurn(
deps: CutAgentDeps,
signal?: AbortSignal
): Promise<EngineDecision | null> {
- const settings = deps.judgeSettings ?? cutJudge();
+ const settings = deps.judgeSettings ?? CUT_JUDGE;
const decision = judgeTurnAndAction(messages, deps.buildContext(), deps, signal);
const landed = await Promise.race([decision, sleep(settings.judgeWaitMs).then(() => null)]);
if (!landed) {
@@ -125,7 +125,7 @@ export class EngineGate {
}
this.answered.add(gateId);
- const verdict = await this.gate.hold(reply, deps, deps.judgeSettings ?? cutJudge(), signal);
+ const verdict = await this.gate.hold(reply, deps, deps.judgeSettings ?? CUT_JUDGE, signal);
return verdict?.steer ?? null;
}
}
diff --git a/site/src/cut/lib/soundBind.ts b/site/src/cut/lib/soundBind.ts
index 22a005a5..f11466b0 100644
--- a/site/src/cut/lib/soundBind.ts
+++ b/site/src/cut/lib/soundBind.ts
@@ -7,7 +7,7 @@
*/
import { syncSourceSound } from "./media";
-import { cutSound } from "./soundSettings";
+import { CUT_SOUND } from "./soundSettings";
import { useEditor } from "./store";
import { assetIsSilent, type MediaAsset } from "./types";
import { queueWatchSweep } from "./watch/sweep";
@@ -45,7 +45,7 @@ export async function bindRecording(
if (assetIsSilent(video))
throw new Error(`"${video.name}" has no sound of its own to line the recording up against.`);
if (!(video.duration > 0) || !(rec.duration > 0)) throw new Error("Both files must finish importing first.");
- const { syncProbeSeconds, syncMaxSeconds, syncMinConfidence } = cutSound();
+ const { syncProbeSeconds, syncMaxSeconds, syncMinConfidence } = CUT_SOUND;
const [cameraFrom, cameraTo] = probeWindow(video, syncProbeSeconds, near);
const answer = await syncSourceSound(video.url, rec.url, {
cameraFrom,
diff --git a/site/src/cut/lib/soundSettings.ts b/site/src/cut/lib/soundSettings.ts
index 0b85cd45..6f6ab67b 100644
--- a/site/src/cut/lib/soundSettings.ts
+++ b/site/src/cut/lib/soundSettings.ts
@@ -1,17 +1,13 @@
-import { SETTINGS, type Settings } from "@/lib/config/registry";
-
-// The sound editing tunables — the split edit's ramp and how a separate
-// recording is lined up — bound once at session start from account config (the
-// tab) or the global setting (a worker job), and read where a clip's sound is
-// laid out.
-
-let sound: Settings["cutSound"] = SETTINGS.cutSound.default;
-
-export function bindCutSound(value: unknown): void {
- const parsed = SETTINGS.cutSound.schema.safeParse(value);
- if (parsed.success) sound = parsed.data;
-}
-
-export function cutSound(): Settings["cutSound"] {
- return sound;
-}
+// The sound editing constants, read where a clip's sound is laid out.
+export const CUT_SOUND = {
+ // The ramp at the outer end of a split edit's sound, so the sound that
+ // leads or trails the picture never starts or stops on a click.
+ splitFadeSeconds: 0.03,
+ // How much clearer the best alignment of a separate recording has to be
+ // than the runner-up before it is bound.
+ syncMinConfidence: 1.4,
+ // How much of the camera's own sound the alignment listens to.
+ syncProbeSeconds: 90,
+ // The longest recording searched end to end.
+ syncMaxSeconds: 2 * 3600,
+};
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index 001ba6cf..67718be6 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -102,7 +102,7 @@ import { ANIM_STYLE_IDS, animStyleOfTransition, assetIsSilent, CLIP_MIN_SECONDS,
import { clampBand, clampFeather, takesBand, takesFeather } from "./transitionShape";
import { liftMoveTracks } from "./textMotion";
import { OWN_SOUND, soundRoom, soundSourceOf, soundWindow, SPLIT_EDIT_MAX_S } from "./soundSource";
-import { cutSound } from "./soundSettings";
+import { CUT_SOUND } from "./soundSettings";
import { readTextStyle } from "./textStyle";
import { loadUiState, saveUiState, type ProjectUiState } from "./uiState";
import { captureTimelineFrames } from "./visualFrames";
@@ -6292,7 +6292,7 @@ function buildClipSpans(clips: VideoClip[], assets: MediaAsset[], track: number)
soundAhead: Math.max(tail, handleSeconds(soundOut, room.tail, clip, "tail")),
soundBack: Math.max(lead, handleSeconds(prevSound, room.head, clip, "head")),
...(lead > 0 || tail > 0
- ? { soundLead: lead, soundTail: tail, splitFade: cutSound().splitFadeSeconds }
+ ? { soundLead: lead, soundTail: tail, splitFade: CUT_SOUND.splitFadeSeconds }
: {}),
...(src.bound ? { sound: { asset: src.asset, offset: src.offset, limit: src.limit } } : {}),
});
diff --git a/site/src/cut/lib/suggestFontTool.test.ts b/site/src/cut/lib/suggestFontTool.test.ts
index 1be98af4..9247307e 100644
--- a/site/src/cut/lib/suggestFontTool.test.ts
+++ b/site/src/cut/lib/suggestFontTool.test.ts
@@ -3,7 +3,7 @@ import { Canvas, FontLibrary } from "skia-canvas";
/** skia's font registry, under a name the hook lint leaves alone. */
const fontLibrary = FontLibrary;
-import { SETTINGS } from "@/lib/config/registry";
+import { CUT_FONT_MATCH } from "./fontMatchSettings";
import { stubModule } from "@/lib/testing/stubModule";
import { setRasterFactory, type RasterFactory, type RasterSurface } from "./raster";
import { registerFonts } from "./types";
@@ -99,7 +99,7 @@ test("type in a face Donkey does not bundle is reported as that", async () => {
shows = { text: "Travel Destination", css: '400 110px "Great Vibes"' };
const out = (await runAiTool("suggest_font", { asset_id: "ref", t: 3, region: REGION, text: "Travel Destination" })) as Out;
expect(out.verdict).toBe("no_match");
- expect(out.matches[0].score).toBeLessThan(SETTINGS.cutFontMatch.default.goodScore);
+ expect(out.matches[0].score).toBeLessThan(CUT_FONT_MATCH.goodScore);
expect(out.note).toContain("does not bundle");
});
diff --git a/site/src/cut/lib/trackKeys.ts b/site/src/cut/lib/trackKeys.ts
index 48b66ade..4d5bfb78 100644
--- a/site/src/cut/lib/trackKeys.ts
+++ b/site/src/cut/lib/trackKeys.ts
@@ -15,7 +15,7 @@
*/
import { evalOverlayFrame, type Mask, type MaskKey, type MaskPoint, type OverlayKey, type OverlayPose } from "@donkeycut/effects-kit";
-import type { Settings } from "@/lib/config/registry";
+import type { CUT_TRACKING } from "./chatRuntime";
import { clipCovers, clipZoom, contentRect, frameOf, rectOf, type Aspect, type Overlay, type VideoClip } from "./types";
/** One moment of a target: its outline, its center, and two points along
@@ -26,7 +26,7 @@ export interface TrackSample {
axis: [MaskPoint, MaskPoint];
}
-type TrackTuning = Pick<Settings["cutTracking"], "smoothCutoff" | "smoothBeta" | "bridgeSeconds">;
+type TrackTuning = Pick<typeof CUT_TRACKING, "smoothCutoff" | "smoothBeta" | "bridgeSeconds">;
/** The derivative's own smoothing cutoff, Hz — the one-euro default. */
const DERIVATIVE_CUTOFF = 1;
diff --git a/site/src/cut/lib/trackMotion.ts b/site/src/cut/lib/trackMotion.ts
index 09d127a8..77bd223b 100644
--- a/site/src/cut/lib/trackMotion.ts
+++ b/site/src/cut/lib/trackMotion.ts
@@ -12,7 +12,7 @@
*/
import { MASK_FEATHER_MAX, poseAt, retimeOf, type MaskPoint } from "@donkeycut/effects-kit";
-import { cutTracking } from "./chatRuntime";
+import { CUT_TRACKING } from "./chatRuntime";
import { clipLen, useEditor } from "./store";
import { trackFootage } from "./tracking";
import {
@@ -72,7 +72,7 @@ export async function trackMotion(req: TrackRequest) {
const b = Math.min(span.end, srcEnd, req.to ?? Infinity);
if (b - a < MIN_TRACK_SECONDS)
throw new Error(`The item and the source clip share no stretch to track (${round2(source.start)}–${round2(srcEnd)}s holds the footage).`);
- const tune = cutTracking();
+ const tune = CUT_TRACKING;
const fps = Math.min(tune.sampleFps, tune.maxFrames / (b - a));
const n = Math.max(2, Math.floor((b - a) * fps) + 1);
const last = b - 1 / (2 * tune.sampleFps);
diff --git a/site/src/cut/lib/tracking.ts b/site/src/cut/lib/tracking.ts
index e48cdbd8..85bc31bc 100644
--- a/site/src/cut/lib/tracking.ts
+++ b/site/src/cut/lib/tracking.ts
@@ -14,7 +14,7 @@
*/
import type { FaceLandmarker, HandLandmarker, NormalizedLandmark, PoseLandmarker } from "@mediapipe/tasks-vision";
-import { cutTracking } from "./chatRuntime";
+import { CUT_TRACKING } from "./chatRuntime";
import { framesAt } from "./mediaRead";
import { visionFileset, withQuietWasmLogs } from "./mediapipe";
import { trackTargetOf, type TrackTarget } from "./trackTargets";
@@ -58,7 +58,7 @@ export async function trackFootage(
times: number[],
onFrame?: (done: number, total: number) => void
): Promise<(TrackSample | null)[]> {
- const settings = cutTracking();
+ const settings = CUT_TRACKING;
// Decode at the configured long side, keeping the picture's own aspect.
const long = Math.max(size.width, size.height);
diff --git a/site/src/cut/lib/tts.ts b/site/src/cut/lib/tts.ts
index 920d1c10..506c2a16 100644
--- a/site/src/cut/lib/tts.ts
+++ b/site/src/cut/lib/tts.ts
@@ -5,7 +5,7 @@ import { bytesFromBase64 } from "./bytes";
import { wavHeader } from "./wav";
import { readHostedError } from "./hostedError";
import { hostedPost } from "./hosted";
-import { cutJudge } from "./chatRuntime";
+import { CUT_JUDGE } from "./chatRuntime";
import { askJudge, choice } from "./judge";
import { importFileToProject } from "./media";
import { mediaSlug, type MediaAsset } from "./types";
@@ -48,7 +48,7 @@ export async function resolveVoiceAsk(wanted?: string): Promise<string> {
// twenty voices every plausible match takes a share, so a correct pick
// reads as low confidence.
const p = pick.probabilities[pick.choice] ?? 0;
- return p >= cutJudge().voicePick && SPEECH_VOICES.some((v) => v.id === pick.choice)
+ return p >= CUT_JUDGE.voicePick && SPEECH_VOICES.some((v) => v.id === pick.choice)
? pick.choice
: DEFAULT_VOICE;
} catch {
diff --git a/site/src/cut/lib/turnJudge.test.ts b/site/src/cut/lib/turnJudge.test.ts
index a36f4b54..6e22c7d6 100644
--- a/site/src/cut/lib/turnJudge.test.ts
+++ b/site/src/cut/lib/turnJudge.test.ts
@@ -1,9 +1,9 @@
import { describe, expect, test } from "bun:test";
-import { SETTINGS } from "@/lib/config/registry";
+import { CUT_JUDGE } from "./chatRuntime";
import { AI_SKILL_INDEX, TOOL_AREA_NAMES } from "@/cut/server/ai/catalog";
import { judgeTurnState, pickSkill, routeTurn, TURN_JUDGE_QUESTIONS, type TurnJudgeAnswers } from "./turnJudge";
-const settings = SETTINGS.cutJudge.default;
+const settings = CUT_JUDGE;
function answers(over: {
intent?: { chat: number; simple: number; complex: number };
diff --git a/site/src/cut/lib/turnJudge.ts b/site/src/cut/lib/turnJudge.ts
index a7330926..7bb2486b 100644
--- a/site/src/cut/lib/turnJudge.ts
+++ b/site/src/cut/lib/turnJudge.ts
@@ -1,5 +1,5 @@
import type { UIMessage } from "ai";
-import type { Settings } from "@/lib/config/registry";
+import type { CUT_JUDGE } from "./chatRuntime";
import {
AI_SKILL_AREAS,
AI_SKILL_BLURBS,
@@ -16,7 +16,7 @@ import { messageText } from "./messageText";
// editor answers three things at once — how big the ask is (chat / simple /
// complex), which skill document the model should read first, and which tool
// areas the turn needs — and the harness routes deterministically on the
-// probabilities under the thresholds in the `cutJudge` setting. A "chat" turn
+// probabilities under the CUT_JUDGE thresholds. A "chat" turn
// runs with no tool declarations at all, so unsolicited edits are impossible
// by construction; a "simple" turn keeps the light chat model; a "complex"
// turn runs on the full model. The route is composed here, in code, from the
@@ -32,7 +32,7 @@ export interface TurnRoute {
areas: string[];
}
-export type CutJudgeSettings = Settings["cutJudge"];
+export type CutJudgeSettings = typeof CUT_JUDGE;
/** The judge's questions, built once: the roster of skills and areas is the
* catalog's, so a new skill or tool module joins the judgment on its own. */
diff --git a/site/src/cut/lib/turnQuality.test.ts b/site/src/cut/lib/turnQuality.test.ts
index 4d4f7f65..ec469743 100644
--- a/site/src/cut/lib/turnQuality.test.ts
+++ b/site/src/cut/lib/turnQuality.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
-import { SETTINGS } from "@/lib/config/registry";
+import { CUT_JUDGE } from "./chatRuntime";
import {
QUALITY_QUESTIONS,
QUALITY_STEER_PREFIX,
@@ -11,7 +11,7 @@ import {
type WatchedSource,
} from "./turnQuality";
-const settings = SETTINGS.cutJudge.default;
+const settings = CUT_JUDGE;
const source = (over: Partial<WatchedSource> = {}): WatchedSource => ({
name: "reference.mp4",
diff --git a/site/src/cut/lib/turnQuality.ts b/site/src/cut/lib/turnQuality.ts
index 4280e64f..cefcbef1 100644
--- a/site/src/cut/lib/turnQuality.ts
+++ b/site/src/cut/lib/turnQuality.ts
@@ -1,11 +1,11 @@
import type { Entry, NoulAnswer, ChoiceAnswer } from "./judge";
import { choice, noul } from "./judge";
-import type { Settings } from "@/lib/config/registry";
+import type { CUT_JUDGE } from "./chatRuntime";
// The quality gate: a turn built on footage, judged before it is allowed to
// close. One typed judgment reads the ask, what the turn watched and wrote
// down, what it ran, and the line it is about to sign off with; code composes
-// the verdict under the `cutJudge` thresholds and hands the turn its next
+// the verdict under the CUT_JUDGE thresholds and hands the turn its next
// step. A turn that watched a slice of a source and is about to describe the
// whole of it, or that read a reference and left the cut it promised
// unbuilt, goes back to work before it replies.
@@ -16,9 +16,9 @@ import type { Settings } from "@/lib/config/registry";
//
// The judgment reads the record in fields, never the user's words for intent
// — the request is state to judge against, and every threshold and cap lives
-// in the settings registry.
+// in CUT_JUDGE.
-export type CutJudgeSettings = Settings["cutJudge"];
+export type CutJudgeSettings = typeof CUT_JUDGE;
/** What one source has given up so far, harvested off this turn's own watch
* and note results. */
diff --git a/site/src/cut/server/ai/headlessRuntime.ts b/site/src/cut/server/ai/headlessRuntime.ts
index 7306d558..eb5ae946 100644
--- a/site/src/cut/server/ai/headlessRuntime.ts
+++ b/site/src/cut/server/ai/headlessRuntime.ts
@@ -1,6 +1,6 @@
import { spawn } from "node:child_process";
import path from "node:path";
-import { chatRuntime } from "../../lib/chatRuntime";
+import { CHAT_RUNTIME } from "../../lib/chatRuntime";
type ToolResult = { output?: unknown; errorText?: string };
let idle: Promise<unknown> = Promise.resolve();
@@ -19,7 +19,7 @@ export function callDetachedTool(projectId: string, toolName: string, input: unk
if (!channel || !("on" in channel)) { child.kill(); reject(new Error("Could not open the editor tool channel.")); return; }
channel.on("data", (data: Buffer) => {
bytes += data.length;
- if (bytes > chatRuntime().journalBytes) { child.kill(); reject(new Error("The editor tool result is too large.")); return; }
+ if (bytes > CHAT_RUNTIME.journalBytes) { child.kill(); reject(new Error("The editor tool result is too large.")); return; }
output.push(data);
});
child.on("error", reject);
diff --git a/site/src/cut/server/ai/sceneLease.ts b/site/src/cut/server/ai/sceneLease.ts
index 018d728f..ef7dc2b0 100644
--- a/site/src/cut/server/ai/sceneLease.ts
+++ b/site/src/cut/server/ai/sceneLease.ts
@@ -1,10 +1,10 @@
-import { SETTINGS } from "@/lib/config/registry";
+import { chatRuntimeSchema } from "../../lib/chatRuntime";
import { z } from "zod";
import { projectFileRevision } from "../projects";
const globalLeases = globalThis as unknown as { __cutSceneLeases?: Map<string, { owner: string; until: number }> };
const leases = (globalLeases.__cutSceneLeases ??= new Map<string, { owner: string; until: number }>());
-const schema = z.object({ owner: z.string().uuid(), release: z.boolean().optional(), leaseMs: SETTINGS.chatRuntime.schema.shape.sceneLeaseMs });
+const schema = z.object({ owner: z.string().uuid(), release: z.boolean().optional(), leaseMs: chatRuntimeSchema.shape.sceneLeaseMs });
export async function localSceneLease(projectId: string, req: Request): Promise<Response> {
if (!(await projectFileRevision(projectId))) return new Response(null, { status: 404 });
diff --git a/site/src/cut/server/ai/turnStreams.ts b/site/src/cut/server/ai/turnStreams.ts
index 0c1b9dcd..d4e0565c 100644
--- a/site/src/cut/server/ai/turnStreams.ts
+++ b/site/src/cut/server/ai/turnStreams.ts
@@ -1,4 +1,4 @@
-import { chatRuntime } from "../../lib/chatRuntime";
+import { CHAT_RUNTIME } from "../../lib/chatRuntime";
import { mkdir, open, readFile, rm, stat, writeFile } from "node:fs/promises";
import { createHash } from "node:crypto";
import path from "node:path";
@@ -28,7 +28,7 @@ export async function startTurnStream(
source: (signal: AbortSignal) => ReadableStream<UIMessageChunk>,
attached: () => void,
detached: () => void,
- journalBytes = chatRuntime().journalBytes,
+ journalBytes = CHAT_RUNTIME.journalBytes,
readerSignal?: AbortSignal,
): Promise<Response> {
const key = keyFor(projectId, threadId);
@@ -122,7 +122,7 @@ export async function followTurnStream(projectId: string, threadId: string, sign
}
if (!turn || turn.finished) { await close(); controller.close(); return; }
// A heartbeat also lets the HTTP adapter observe a vanished reader while a tool waits.
- if (Date.now() - lastWrite >= chatRuntime().syncIntervalMs) {
+ if (Date.now() - lastWrite >= CHAT_RUNTIME.syncIntervalMs) {
lastWrite = Date.now();
controller.enqueue(new TextEncoder().encode(": keepalive\n\n"));
return;
diff --git a/site/src/cut/server/cloud/sceneLease.ts b/site/src/cut/server/cloud/sceneLease.ts
index 35873187..a917e23b 100644
--- a/site/src/cut/server/cloud/sceneLease.ts
+++ b/site/src/cut/server/cloud/sceneLease.ts
@@ -1,6 +1,6 @@
import { z } from "zod";
import { prisma } from "@/lib/prisma";
-import { getGlobalSetting } from "@/lib/config/effective";
+import { CHAT_RUNTIME } from "../../lib/chatRuntime";
export const sceneLeaseSchema = z.object({ owner: z.string().uuid(), release: z.boolean().optional() });
@@ -9,7 +9,7 @@ export async function cloudSceneLease(userId: string, projectId: string, req: Re
const parsed = sceneLeaseSchema.safeParse(await req.json().catch(() => null));
if (!parsed.success) return new Response(null, { status: 400 });
const { owner, release } = parsed.data;
- const { sceneLeaseMs } = await getGlobalSetting("chatRuntime");
+ const { sceneLeaseMs } = CHAT_RUNTIME;
const id = `scene-lease-${projectId}`;
if (release) {
await prisma.cutRenderJob.deleteMany({ where: { id, userId, outName: owner, state: "held" } });
diff --git a/site/src/cut/server/exportPipeline.ts b/site/src/cut/server/exportPipeline.ts
index e946762d..f081a387 100644
--- a/site/src/cut/server/exportPipeline.ts
+++ b/site/src/cut/server/exportPipeline.ts
@@ -7,7 +7,7 @@ export type { SpecClipColor };
import { readFile, stat, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
import { atempoChain, audioChannels, hasStream, mediaDuration, num, videoDecodeCost, videoDimensions, videoPicture } from "./util";
-import { SETTINGS, type Settings } from "@/lib/config/registry";
+import { CUT_EXPORT_PASSES } from "../lib/exportPassSettings";
import { xfadeTransition } from "./transitionExpr";
import { assertGraphSafe, fanOutInputs, fexpr } from "./filterGraph";
import { bakeRetimedAudio, setptsExpr, type BakedAudio } from "./retimeAudio";
@@ -86,7 +86,7 @@ export interface ExportSpec {
lutSizeWide?: number;
/** The memory one encode pass may hold and the most pieces it opens;
* absent = the setting's default. */
- passes?: Settings["cutExportPasses"];
+ passes?: typeof CUT_EXPORT_PASSES;
/** Where the render lands instead of a stamped file in exports/: "hls" is the
* share's streaming ladder, "preview"
* writes the project's low-res hover proxy, "card" the opening seconds the
@@ -785,7 +785,7 @@ function clipReach(spec: ExportSpec): { before: number; after: number }[] {
* graph opens and its chain keeps frames through the encode, about this many
* of its source's size or the delivery's, whichever is larger. Cuts played
* out of file order add the frames their decoder holds until their turn. The
- * pass budget (the cutExportPasses setting) caps their sum and the count.
+ * pass budget (CUT_EXPORT_PASSES) caps their sum and the count.
*/
const PIECE_FRAMES = 16;
@@ -827,7 +827,7 @@ function heldSeconds(cuts: PassSpan[]): number {
* are the delivery.
*/
export function passWindows(spec: ExportSpec, sourceOf: (file: string) => SourcePicture): ExportRange[] {
- const budget = spec.passes ?? SETTINGS.cutExportPasses.default;
+ const budget = spec.passes ?? CUT_EXPORT_PASSES;
const from = Math.max(0, spec.range?.start ?? 0);
const to = Math.min(spec.duration, spec.range?.end ?? spec.duration);
const frameBytes = (file: string) => 1.5 * Math.max(sourceOf(file).pixels, spec.width * spec.height);
diff --git a/site/src/cut/server/http/ai.ts b/site/src/cut/server/http/ai.ts
index 5d7e5a2f..827cff7a 100644
--- a/site/src/cut/server/http/ai.ts
+++ b/site/src/cut/server/http/ai.ts
@@ -1,7 +1,7 @@
import { spawn, execFile } from "node:child_process";
import os from "node:os";
import { z } from "zod";
-import { SETTINGS } from "@/lib/config/registry";
+import { chatRuntimeSchema } from "../../lib/chatRuntime";
import { startTurnStream, followTurnStream, cancelTurnStream, peekTurnStream } from "../ai/turnStreams";
import { foldIntoTurn, openFoldInbox, type Fold, type FoldInbox } from "../ai/turnFolds";
import path from "node:path";
@@ -596,7 +596,7 @@ export const aiApi = {
threadId: z.string().min(1).max(200),
model: z.string().min(1).max(200),
messages: z.array(z.object({ id: z.string(), role: z.enum(["user", "assistant", "system"]), parts: z.array(z.object({ type: z.string() })) })),
- runtime: SETTINGS.chatRuntime.schema,
+ runtime: chatRuntimeSchema,
context: z.object({ project: z.object({ id: z.string().min(1).max(200) }) }),
route: routeSchema.optional(),
handled: handledSchema.optional(),
diff --git a/site/src/cut/worker/exportJob.ts b/site/src/cut/worker/exportJob.ts
index 258ea70a..4b9f2a26 100644
--- a/site/src/cut/worker/exportJob.ts
+++ b/site/src/cut/worker/exportJob.ts
@@ -11,12 +11,7 @@ import { overlayKey } from "../server/cloud/r2";
import { STORAGE_FULL } from "../lib/operationFailure";
import { isTabExport, specMediaFiles, STEMS_MIME, stemsArchiveName } from "../lib/exportDelivery";
import { runnerSession } from "./session";
-import { bindCutColor } from "../lib/colorSettings";
-import { bindCutExportPasses } from "../lib/exportPassSettings";
-import { bindCutSound } from "../lib/soundSettings";
-import { bindCutLoudness } from "../lib/loudnessSettings";
import type { DocExportAudio } from "../lib/exportPresets";
-import { getGlobalSetting } from "@/lib/config/effective";
/** The stored spec of an export/preview CutRenderJob: the engine export spec
* plus the R2 keys of the browser-rendered overlay PNGs (title/caption stills
@@ -144,14 +139,6 @@ export async function runExportJob(
// own straight into it, so it exists before the spec does.
handle.tmpDir = path.join(work, "overlays");
await mkdir(handle.tmpDir, { recursive: true });
- // A doc-built spec sizes its LUTs from the same setting the tab binds.
- if (stored.fromDoc) {
- bindCutColor(await getGlobalSetting("cutColor"));
- bindCutSound(await getGlobalSetting("cutSound"));
- // Its loudness target and ceiling come from the setting the tab binds.
- bindCutLoudness(await getGlobalSetting("cutLoudness"));
- bindCutExportPasses(await getGlobalSetting("cutExportPasses"));
- }
const body: ExportJobSpec = stored.fromDoc
? {
...stored,
diff --git a/site/src/cut/worker/libraryProxyJob.ts b/site/src/cut/worker/libraryProxyJob.ts
index cf594ebc..9ff8215a 100644
--- a/site/src/cut/worker/libraryProxyJob.ts
+++ b/site/src/cut/worker/libraryProxyJob.ts
@@ -2,7 +2,7 @@ import { mkdtemp, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import type { Prisma } from "@/generated/prisma/client";
-import { getGlobalSetting } from "@/lib/config/effective";
+import { CUT_COLOR } from "@/cut/lib/colorSettings";
import type { RenderHandle } from "../server/exportPipeline";
import { makeCompatProxy, makeProxy, proxyNameFor } from "../server/proxy";
import { compatCoverIn, compatCovers, compatProxyNameFor } from "../lib/proxyNames";
@@ -35,7 +35,7 @@ const defaultIO: LibraryProxyIO = {
make: makeProxy,
makeCompat: makeCompatProxy,
duration: probeDuration,
- settings: () => getGlobalSetting("cutColor"),
+ settings: async () => CUT_COLOR,
transact: storageTransaction,
register: registerObjectIn,
};
diff --git a/site/src/cut/worker/proxyJob.ts b/site/src/cut/worker/proxyJob.ts
index 0f546a8d..5510c32f 100644
--- a/site/src/cut/worker/proxyJob.ts
+++ b/site/src/cut/worker/proxyJob.ts
@@ -2,6 +2,7 @@ import { mkdtemp, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { getGlobalSetting } from "@/lib/config/effective";
+import { CUT_COLOR } from "../lib/colorSettings";
import type { RenderHandle } from "../server/exportPipeline";
import { makeCompatProxy, makeProxy, proxyNameFor } from "../server/proxy";
import { compatCoverIn, compatProxyNameFor, lightProxyNameFor, PROXY_SOURCE_FAULT } from "../lib/proxyNames";
@@ -47,8 +48,8 @@ const defaultIO: ProxyJobIO = {
makeCompat: makeCompatProxy,
duration: probeDuration,
settings: async () => {
- const [color, proxy] = await Promise.all([getGlobalSetting("cutColor"), getGlobalSetting("cutProxy")]);
- return { ...color, lightKbps: proxy.lightKbps };
+ const proxy = await getGlobalSetting("cutProxy");
+ return { ...CUT_COLOR, lightKbps: proxy.lightKbps };
},
};
diff --git a/site/src/cut/worker/turnJob.ts b/site/src/cut/worker/turnJob.ts
index b32399dd..95d6d443 100644
--- a/site/src/cut/worker/turnJob.ts
+++ b/site/src/cut/worker/turnJob.ts
@@ -1,10 +1,4 @@
import type { UIMessage } from "ai";
-import { getGlobalSetting } from "@/lib/config/effective";
-import { bindCutClip, bindCutJudge } from "@/cut/lib/chatRuntime";
-import { bindCutColor } from "@/cut/lib/colorSettings";
-import { bindCutSound } from "@/cut/lib/soundSettings";
-import { bindCutMotion } from "@/cut/lib/motionSettings";
-import { bindCutFontMatch } from "@/cut/lib/fontMatchSettings";
import { geminiModelRoleNames } from "@/lib/inference/gemini-models";
import { openCloudProject, pushCloudProject } from "../lib/headless/docSession";
import { dropPiSession, streamCutChat } from "../lib/pi/cutAgent";
@@ -108,16 +102,6 @@ export async function runTurnJob(
const doc = await openCloudProject(session, job.projectId);
const deps = headlessDeps(session);
- // The same thresholds the tab binds from account config, so a judged tool
- // behaves the same way in a job.
- const judgeSettings = await getGlobalSetting("cutJudge");
- bindCutJudge(judgeSettings);
- bindCutClip(await getGlobalSetting("cutClip"));
- bindCutColor(await getGlobalSetting("cutColor"));
- bindCutSound(await getGlobalSetting("cutSound"));
- bindCutMotion(await getGlobalSetting("cutMotion"));
- bindCutFontMatch(await getGlobalSetting("cutFontMatch"));
- deps.judgeSettings = judgeSettings;
const toolCalls: string[] = [];
const exec = deps.execTool;
deps.execTool = async (name, args) => {
diff --git a/site/src/lib/config/registry.ts b/site/src/lib/config/registry.ts
index 11c870dd..73a3e8f6 100644
--- a/site/src/lib/config/registry.ts
+++ b/site/src/lib/config/registry.ts
@@ -11,12 +11,12 @@ import { z } from "zod";
import { maxCreditGrantDollars, maxCreditGrantExpiryDays } from "@/lib/credits/top-up";
-// The settings registry: every runtime tunable the product has, declared once
+// The settings registry: every lever su runs, declared once
// with a schema and a default. A value resolves default < override < variant
// (src/lib/config/resolve.ts); a database row holds the override, an
// experiment supplies the variant. Client-safe: zod only, so a form reads the
-// same declarations the server validates against. A feature that people might
-// tune ships its setting here in the same change.
+// same declarations the server validates against. An engineering threshold is a
+// constant beside its code.
export const SETTINGS = defineSettings({
databasePool: {
@@ -53,17 +53,6 @@ export const SETTINGS = defineSettings({
title: "ChatGPT app",
description: "Account linking, allowed OAuth callbacks, token lifetimes, preview polling, how long an edit call waits and how long the card's editor has to claim it, and how long the editor stays signed in inside the card. Enable after the OAuth tables are deployed.",
},
- chatgptPolling: {
- schema: z.object({
- pollMs: z.number().int().min(500).max(3000),
- hiddenPollMs: z.number().int().min(1000).max(3000),
- maxBackoffMs: z.number().int().min(10000).max(300000),
- }).strict(),
- default: { pollMs: 1000, hiddenPollMs: 3000, maxBackoffMs: 60000 },
- public: true,
- title: "ChatGPT editor polling",
- description: "Command polling cadence and maximum failure backoff. Expired sessions stop polling until the editor opens again.",
- },
cutPreviewJobs: {
schema: z.object({ maxAttempts: z.number().int().min(1).max(10) }).strict(),
default: { maxAttempts: 5 },
@@ -85,259 +74,6 @@ export const SETTINGS = defineSettings({
title: "Shared library",
description: "Folders, assets, and templates returned per shared library page.",
},
- chatRuntime: {
- schema: z.object({
- syncIntervalMs: z.number().int().min(1000).max(30000),
- sceneLeaseMs: z.number().int().min(15000).max(120000),
- journalBytes: z.number().int().min(1048576).max(33554432),
- }).strict(),
- default: { syncIntervalMs: 5000, sceneLeaseMs: 30000, journalBytes: 8388608 },
- public: true,
- title: "Chat continuity",
- description: "Project and conversation refresh cadence, scene ownership expiry, and saved engine transcript size.",
- },
- cutJudge: {
- schema: z
- .object({
- // Preload the skill the judge picks for the turn; off leaves the model
- // to read skills on its own.
- skillSuggestion: z.boolean(),
- // The reference-need probability below which no skill is attached.
- skillGate: z.number().min(0).max(1),
- // The winning skill's own fit below which it is dropped.
- skillFits: z.number().min(0).max(1),
- // Declare only the tool areas the judge routes to; off declares the
- // whole catalog on every turn.
- toolRouting: z.boolean(),
- // An area's probability at or above which its tools are declared.
- toolArea: z.number().min(0).max(1),
- // How long the first model round waits for the judge before going out
- // with the full catalog and no skill. Set above the judgment's slowest
- // turns: a round that goes out early is the one a chat or complex
- // verdict then throws away.
- judgeWaitMs: z.number().int().min(0).max(4000),
- // A stock candidate's fit below which it is left out of a search.
- stockFit: z.number().min(0).max(1),
- // A transcript word's disfluency probability at or above which
- // find_filler reports it.
- fillerCut: z.number().min(0).max(1),
- // The confidence below which a described voice falls back to the default.
- voicePick: z.number().min(0).max(1),
- // How often a running turn re-places the messages waiting in the tray
- // against the work it has done since; 0 places them once, at send.
- queueRetriageMs: z.number().int().min(0).max(60000),
- // Run a turn the judgment settles to one known action with no model
- // round at all; off sends every turn through the chat loop.
- instantAction: z.boolean(),
- // The chosen action's own probability below which the turn takes the
- // loop instead. The floors below do the same for each argument.
- instantFloor: z.number().min(0).max(1),
- instantTarget: z.number().min(0).max(1),
- instantEnum: z.number().min(0).max(1),
- // A style, look or direction the request left open: several good
- // answers split the probability, so the winner clears less.
- instantPick: z.number().min(0).max(1),
- instantLevel: z.number().min(0).max(1),
- // A yes/no argument has to be this decisive in one direction.
- instantBool: z.number().min(0.5).max(1),
- // An ask that names an exact figure, acts on more than one item,
- // leaves a second edit undone, or wants the shot itself remade goes
- // to the model at or above these.
- instantExact: z.number().min(0).max(1),
- instantMulti: z.number().min(0).max(1),
- instantLeftover: z.number().min(0).max(1),
- instantRemake: z.number().min(0).max(1),
- // A candidate's fit below which a described sweep leaves it out.
- sweepFit: z.number().min(0).max(1),
- // Judge the turn's own work before it closes; off lets a turn sign
- // off on whatever it did.
- qualityGate: z.boolean(),
- // The probabilities below which the work is judged unfinished, the
- // footage under-watched, and the reply wider than the record.
- qualityFinished: z.number().min(0).max(1),
- qualitySeen: z.number().min(0).max(1),
- qualityHonest: z.number().min(0).max(1),
- // The probability above which the ask is taken to want the project
- // changed, which lets a turn that changed nothing be sent to build.
- qualityWantsChange: z.number().min(0).max(1),
- // The probability above which the reply is taken to ask the one
- // question an ambiguous ask needs answered, which closes the turn on
- // that question.
- qualityAsksBack: z.number().min(0).max(1),
- // The probability above which the ask is taken to turn on how the
- // source sounds, which makes unplayed seconds a gap worth a round.
- qualityHears: z.number().min(0).max(1),
- // The probability above which on-screen text is taken to be the
- // source's own narration, which puts its words in the transcript and
- // leaves only their treatment to be read off the frames.
- qualityCaptionsSpeak: z.number().min(0).max(1),
- // Seconds of close reading that settle how a spoken caption track is
- // set, once the words are known from the transcript.
- qualityTreatmentSeconds: z.number().min(0).max(120),
- // How many times one turn may be sent back to work by the gate.
- qualityRounds: z.number().int().min(0).max(6),
- })
- // A stored override is parsed as one whole object, so a key added here
- // without `.default(...)` makes every row written before it fail and
- // silently drops that row's other values back to the defaults below.
- .strict(),
- default: {
- skillSuggestion: true,
- skillGate: 0.4,
- skillFits: 0.3,
- toolRouting: true,
- toolArea: 0.2,
- judgeWaitMs: 1000,
- stockFit: 0.5,
- fillerCut: 0.5,
- voicePick: 0.4,
- queueRetriageMs: 4000,
- instantAction: true,
- instantFloor: 0.5,
- instantTarget: 0.5,
- instantEnum: 0.5,
- instantPick: 0.15,
- instantLevel: 0.3,
- instantBool: 0.7,
- instantExact: 0.4,
- instantMulti: 0.4,
- instantLeftover: 0.5,
- instantRemake: 0.3,
- sweepFit: 0.5,
- qualityGate: true,
- qualityFinished: 0.5,
- qualitySeen: 0.5,
- qualityHonest: 0.5,
- qualityWantsChange: 0.5,
- qualityAsksBack: 0.5,
- qualityHears: 0.6,
- qualityCaptionsSpeak: 0.7,
- qualityTreatmentSeconds: 8,
- qualityRounds: 3,
- },
- public: true,
- title: "Chat judgments",
- description:
- "Thresholds for the typed judgments that route a chat turn (skill, tool areas), run a one-action turn with no model round, hold a turn back until its work is finished and its reply true to it, re-place the messages waiting in the tray, pick the items a sweep touches, rank stock, find filler words, and resolve described voices.",
- },
- cutClip: {
- schema: z
- .object({
- // A pause this long ends a sentence when the punctuation does not.
- pauseBreakSeconds: z.number().min(0.1).max(5),
- // What a clip may run. The sweep aims at the target and accepts
- // anything between the bounds, ending on a sentence.
- minSeconds: z.number().min(3).max(600),
- targetSeconds: z.number().min(3).max(600),
- maxSeconds: z.number().min(3).max(600),
- // How far apart the wide sweep's candidate starts sit. Smaller reads
- // more of the source and costs more questions.
- strideSeconds: z.number().min(1).max(120),
- // How many of the sweep's best earn the close read.
- shortlist: z.number().int().min(1).max(60),
- // Standing alone and landing are requirements: a stretch that needs
- // what came before it, or that trails off into the next thing, is not
- // a clip however well it opens. Below either floor it is not offered.
- standaloneFloor: z.number().min(0).max(1),
- payoffFloor: z.number().min(0).max(1),
- // What orders the ones that qualify.
- standaloneWeight: z.number().min(0).max(1),
- hookWeight: z.number().min(0).max(1),
- payoffWeight: z.number().min(0).max(1),
- // The composite below which a moment is not offered at all.
- rankFloor: z.number().min(0).max(1),
- // Second beats considered per clip, and the probability one has to
- // reach to be cut in behind the first.
- pairsPerClip: z.number().int().min(0).max(10),
- followsFloor: z.number().min(0).max(1),
- })
- .strict(),
- default: {
- pauseBreakSeconds: 0.6,
- minSeconds: 18,
- targetSeconds: 45,
- maxSeconds: 75,
- strideSeconds: 12,
- shortlist: 14,
- standaloneFloor: 0.35,
- payoffFloor: 0.5,
- standaloneWeight: 0.4,
- hookWeight: 0.35,
- payoffWeight: 0.25,
- rankFloor: 0.45,
- pairsPerClip: 3,
- followsFloor: 0.6,
- },
- public: true,
- title: "Clipping a long source",
- description:
- "How a talk or an interview is read for the moments worth cutting a short from: what a clip may run, how widely the first sweep looks, how many moments earn the close read, and what the ranking weighs.",
- },
- cutUploads: {
- schema: z
- .object({
- // The pause before each automatic retry of an upload the connection
- // dropped; the browser's reconnect retries it too.
- resumeDelaysMs: z.array(z.number().int().min(1000).max(600000)).max(10).readonly(),
- })
- .strict(),
- default: { resumeDelaysMs: [5000, 20000, 60000] },
- public: true,
- title: "Upload resume",
- description: "How an upload the connection dropped picks back up on its own: the pauses before each automatic retry.",
- },
- cutTracking: {
- schema: z
- .object({
- // Tracked frames per second of the span, and the most frames one
- // track reads; a longer span samples more sparsely.
- sampleFps: z.number().int().min(5).max(60),
- maxFrames: z.number().int().min(60).max(3600),
- // The decoded frame's long side the landmarkers read.
- longSide: z.number().int().min(320).max(1920),
- // Detection, presence and tracking confidence floors.
- minConfidence: z.number().min(0.1).max(0.95),
- // One-euro smoothing: the cutoff (Hz) a still target settles at, and
- // how fast the cutoff rises with speed.
- smoothCutoff: z.number().min(0.1).max(30),
- smoothBeta: z.number().min(0).max(200),
- // A dropout this short is bridged; a longer one hides the shape.
- bridgeSeconds: z.number().min(0).max(2),
- // How far, in frame fractions, a dropped key may sit from the line
- // its neighbors draw.
- keyTolerance: z.number().min(0).max(0.02),
- })
- .strict(),
- default: {
- sampleFps: 30,
- maxFrames: 1200,
- longSide: 1280,
- minConfidence: 0.5,
- smoothCutoff: 1.5,
- smoothBeta: 20,
- bridgeSeconds: 0.25,
- keyTolerance: 0.0015,
- },
- public: true,
- title: "Motion tracking",
- description:
- "How hands, heads and people are tracked through a clip: frames read per second, the frame size and confidence the landmarkers use, how hard the path is smoothed, and how closely the written keys follow it.",
- },
- cutNotes: {
- schema: z.object({ autosaveMs: z.number().int().min(200).max(10000) }).strict(),
- default: { autosaveMs: 800 },
- public: true,
- title: "Notes",
- description: "How long a note sits still after the last keystroke before it saves.",
- },
- cutMediaCache: {
- schema: z.object({ maxBytes: z.number().int().min(1024 ** 3).max(1024 ** 4) }).strict(),
- default: { maxBytes: 10 * 1024 ** 3 },
- public: true,
- title: "Cloud media cache",
- description:
- "The most disk a browser spends on cached copies of cloud media. Past it, the least recently used copies go first.",
- },
factCheck: {
schema: z
.object({
@@ -354,81 +90,6 @@ export const SETTINGS = defineSettings({
description:
"How claims are checked against the web: how many searches run at once, how many sources a verdict needs, and how many sources each claim reports.",
},
- cutColor: {
- schema: z
- .object({
- // Lattice nodes per axis of a clip's color LUT: Rec.709 and sRGB
- // sources take the smaller cube, log and HDR sources the wider one.
- lutSize: z.number().int().min(9).max(129),
- lutSizeWide: z.number().int().min(9).max(129),
- // The cube drawn while a slider is moving; the full cube follows.
- draftLutSize: z.number().int().min(5).max(65),
- // The preview proxy's largest height, and its HEVC quality (x265 crf;
- // the VideoToolbox quality maps from it). 18 is visually lossless for
- // 10-bit footage that is only ever previewed.
- proxyMaxHeight: z.number().int().min(360).max(4320),
- proxyCrf: z.number().int().min(0).max(51),
- // A LUT file past this is something else.
- lutFileMaxBytes: z.number().int().min(1024).max(1024 ** 3),
- })
- .strict(),
- default: {
- lutSize: 33,
- lutSizeWide: 65,
- draftLutSize: 17,
- proxyMaxHeight: 2160,
- proxyCrf: 18,
- lutFileMaxBytes: 64 * 1024 ** 2,
- },
- public: true,
- title: "Color pipeline",
- description:
- "The color LUT sizes a clip is rendered through (standard, wide-gamut and the draft drawn mid-drag), the preview proxy's size and quality, and the largest LUT file the library takes.",
- },
- cutExportPasses: {
- schema: z
- .object({
- // The frames one ffmpeg pass may hold, MB. A long timeline renders in
- // passes held under it; a larger budget means fewer passes, each
- // decoding the stretch of file its cuts span.
- holdMB: z.number().int().min(256).max(65536),
- // The most pieces one pass opens, whatever their size: each brings a
- // decoder and its threads.
- pieces: z.number().int().min(2).max(512),
- })
- .strict(),
- default: { holdMB: 2048, pieces: 48 },
- public: true,
- title: "Export passes",
- description:
- "The memory one export pass may hold and the most pieces it opens; a longer timeline renders in more passes.",
- },
- cutSound: {
- schema: z
- .object({
- // The ramp at the outer end of a split edit's sound, so the sound
- // that leads or trails the picture never starts or stops on a click.
- splitFadeSeconds: z.number().min(0).max(1),
- // How much clearer the best alignment of a separate recording has to
- // be than the runner-up before it is bound.
- syncMinConfidence: z.number().min(1).max(10),
- // How much of the camera's own sound the alignment listens to.
- syncProbeSeconds: z.number().min(5).max(600),
- // The longest recording searched end to end.
- syncMaxSeconds: z.number().min(60).max(4 * 3600),
- })
- .strict(),
- default: {
- splitFadeSeconds: 0.03,
- syncMinConfidence: 1.4,
- syncProbeSeconds: 90,
- syncMaxSeconds: 2 * 3600,
- },
- public: true,
- title: "Sound editing",
- description:
- "The ramp on the sound a split edit carries past its picture, and how lining up a separately recorded sound listens, how sure it must be, and how long a recording it searches.",
- },
cutProxy: {
schema: z
.object({
@@ -446,49 +107,6 @@ export const SETTINGS = defineSettings({
description:
"The light proxy's bitrate ceiling for heavy cloud videos, and how long a master that could not be proxied waits before the cloud tries it again.",
},
- cutMotion: {
- schema: z.object({ motionBlur: z.number().min(0.05).max(1) }).strict(),
- default: { motionBlur: 0.5 },
- public: true,
- title: "Motion blur",
- description:
- "The shutter a newly switched-on motion blur starts at, as a share of a 30fps frame. 0.5 is the half-open shutter of most filmed footage; higher streaks harder.",
- },
- cutFontMatch: {
- schema: z.object({ goodScore: z.number().min(0).max(1) }).strict(),
- default: { goodScore: 0.72 },
- public: true,
- title: "Font suggestions",
- description:
- "The score (0..1, glyph overlap times width agreement) a bundled face has to reach before suggest_font calls it a match; under it the reference is reported as set in a face Donkey does not bundle.",
- },
- cutLoudness: {
- schema: z
- .object({
- // The integrated loudness each named target masters to, LUFS.
- targets: z
- .object({
- social: z.number().min(-36).max(-5),
- podcast: z.number().min(-36).max(-5),
- broadcast: z.number().min(-36).max(-5),
- })
- .strict(),
- // The target an export starts on; "off" leaves the mix as mixed.
- defaultTarget: z.enum(["off", "social", "podcast", "broadcast"]),
- // What a mastered mix's true peak is held under, dBTP.
- truePeakCeiling: z.number().min(-9).max(0),
- })
- .strict(),
- default: {
- targets: { social: -14, podcast: -16, broadcast: -23 },
- defaultTarget: "off",
- truePeakCeiling: -1,
- },
- public: true,
- title: "Export loudness",
- description:
- "The loudness each export target masters to (social, podcast, broadcast), the target an export starts on, and the true-peak ceiling a mastered mix is limited under.",
- },
signupCredits: {
schema: z
.object({