Open source CapCut alternative.
TypeScript
feat(site): always-on preview diagnostics, uploaded on trouble
David Le9d9e27628dc9
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsxindex 320a19b6..62ea5f75 100644--- a/site/src/cut/components/Editor.tsx+++ b/site/src/cut/components/Editor.tsx@@ -36,7 +36,9 @@ import { syncLinkedLibrary } from "@/cut/lib/linkedLibrary";import { reportActivity } from "@/cut/lib/tabActivity";import { TabStatus } from "./TabStatus";import { installDevHooks } from "@/cut/lib/devHooks";-import { meterPerf, stopMeter } from "@/cut/lib/perfTrace";+import { startPerfLog, stopPerfLog } from "@/cut/lib/perfLog";+import { meterMainThread, meterPerf, stopMainThreadMeter, stopMeter } from "@/cut/lib/perfTrace";+import { isDragActive } from "@/cut/lib/drag";import { track } from "@/lib/analytics";import { ensureCloudThreads } from "@/cut/lib/chatCloud";import { readProjectThreads, writeActiveChat } from "@/cut/lib/chatThreads";@@ -93,22 +95,33 @@ export function Editor({viewer?: boolean;}) {useEffect(() => installDevHooks(), []);- // Preview diagnostics, for accounts that turned them on in settings: the- // engine counts what its frames did and sends a summary every half minute of- // playback. Off — and costing a null check — for everyone else.+ // Diagnostics: the engine counts what its frames did, the main thread+ // reports the frames it was blocked in — with the script that ran them —+ // and a local log keeps those frames. All of it is a handful of counters+ // and a browser-side observer, so it runs from the first frame for every+ // account, which is what catches a freeze on open. What leaves the machine+ // is perfLog's decision: a session that saw trouble, and a small random+ // sample for the baseline.useEffect(() => {- let live = true;- void fetch("/api/account/feature-flags")- .then((r) => (r.ok ? (r.json() as Promise<{ flags: { id: string; enabled: boolean }[] }>) : null))- .then((body) => {- if (!live || !body) return;- const on = body.flags.some((f) => f.id === "preview_diagnostics" && f.enabled);- if (on) meterPerf((sample) => track("cut_preview_perf", sample));- })- .catch(() => {});+ startPerfLog((batch) => track("cut_perf_log", batch));+ meterPerf((sample) => track("cut_preview_perf", sample));+ meterMainThread(+ (sample) => track("cut_main_thread", sample),+ () => {+ const st = useEditor.getState();+ return {+ activity: st.playing ? "playing" : isDragActive() ? "dragging" : "idle",+ clips: st.clips.length,+ audioClips: st.audioClips.length,+ overlays: st.overlays.length,+ assets: st.assets.length,+ };+ }+ );return () => {- live = false;stopMeter();+ stopMainThreadMeter();+ stopPerfLog();};}, []);const back = backTarget(useCutBase(), from, folder);diff --git a/site/src/cut/lib/perfLog.ts b/site/src/cut/lib/perfLog.tsnew file mode 100644index 00000000..ec6d1356--- /dev/null+++ b/site/src/cut/lib/perfLog.ts@@ -0,0 +1,287 @@+"use client";++/**+ * A durable record of the frames the main thread was blocked in.+ *+ * The meter in perfTrace boils a half minute down to one summary, which is+ * the shape a chart wants and the wrong shape for a bug report: "the delete+ * at 10:19 took 1.7 seconds inside X" is one frame, and it is gone from the+ * summary the moment a longer one lands. This keeps the frames themselves —+ * the last few hundred, in fixed memory — and gets them to PostHog when the+ * machine has nothing better to do.+ *+ * Nothing here runs on the hot path. A frame is an object pushed onto an+ * array. The array reaches localStorage at idle, at most once every ten+ * seconds and only when something was added, so a tab that crashes still+ * leaves its log behind.+ *+ * Every machine records. Few send: with ten thousand accounts, a log from+ * each would be a flood of pages that were fine. A session sends when it has+ * seen trouble — a frame over a second, a half minute mostly blocked, a play+ * that hitched or whose sound ran late — so the frames that led up to it+ * arrive with it, and a small random share of sessions send regardless,+ * which is the baseline the trouble is measured against.+ * Batches go out at idle, on the page hiding (the analytics client beacons+ * what it holds), and on the next open for whatever the last page never got+ * to send — a session that crashed reads as trouble on the page after it.+ *+ * Every record is timings, a script's name in the page's own bundle, and+ * which control was pressed — see perfTrace's meter for what is kept out.+ */++export interface PerfLogRecord {+ /** Monotonic across page loads on this machine, so a batch sent twice —+ * once by a beacon that did land, once by the next open that could not+ * know — reads as one. */+ id: number;+ /** Epoch milliseconds the frame started, and when the page it happened on+ * was opened, so frames group by page load after the fact. */+ at: number;+ open: number;+ ms: number;+ blockedMs: number;+ scriptMs: number;+ layoutMs: number;+ invoker: string;+ fn: string;+ src: string;+ char: number;+ activity: string;+ input: string;+ inputAgoMs: number;+}++export interface PerfLogBatch {+ /** Which batch of the drain this is, out of how many, and why this session+ * is sending at all. */+ batch: number;+ of: number;+ reason: PerfUploadReason;+ records: PerfLogRecord[];+ cores: number;+ memoryGb: number;+}++/** Why a session uploads: it drew the sample, or it saw trouble. */+export type PerfUploadReason = "sampled" | "trouble";++const KEY = "cut-perf-log";+const VERSION = 1;+/** Frames kept. At ~150 bytes each this is a write of tens of kilobytes,+ * which is what the machines this runs on can afford to spend on being+ * measured. */+const CAP = 250;+/** Frames older than this are dropped at open: a stall last week is not the+ * context for a stall today. */+const KEEP_MS = 24 * 60 * 60_000;+/** Records per batch sent. */+const BATCH = 40;+/** Storage writes and in-session drains wait at least this long apart. A+ * struggling machine produces long frames without pause, so this is the+ * cadence of the write, and the page hiding flushes whatever it holds. */+const WRITE_MIN_MS = 30_000;+const DRAIN_MIN_MS = 5 * 60_000;+/** A drain right after open waits this long, so the open itself is not what+ * it competes with; one that trouble asked for waits only long enough for+ * the frames around it to land. */+const DRAIN_AFTER_OPEN_MS = 20_000;+const DRAIN_AFTER_TROUBLE_MS = 5_000;+/** Share of sessions that send without having seen trouble. One in a+ * hundred is a few dozen baselines a day at the current size, which is+ * enough to draw a percentile against. */+const SAMPLE_RATE = 0.01;+/** Drains one session will send, and batches each may hold: at most ten+ * events of frames from one session, however long it ran. */+const DRAIN_CAP = 2;+const BATCH_CAP = 5;++interface Stored {+ v: number;+ /** Records in order; `id` is monotonic across page loads. */+ records: PerfLogRecord[];+ nextId: number;+ sentThrough: number;+ /** Epoch milliseconds a session last saw trouble it has not drained, so a+ * page that ended before its drain hands the reason to the next one. */+ troubleAt: number;+}++let state: Stored | null = null;+let sink: ((batch: PerfLogBatch) => void) | null = null;+let sampled = false;+let rolled = false;+let trouble = false;+let drains = 0;+let dirty = false;+let writeTimer: ReturnType<typeof setTimeout> | null = null;+let drainTimer: ReturnType<typeof setTimeout> | null = null;+let openedAt = 0;+let removePageHide: (() => void) | null = null;++const idle = (fn: () => void): void => {+ if (typeof requestIdleCallback === "function") requestIdleCallback(() => fn(), { timeout: 5_000 });+ else setTimeout(fn, 0);+};++function load(): Stored {+ if (state) return state;+ let parsed: Stored | null = null;+ try {+ const raw = localStorage.getItem(KEY);+ if (raw) parsed = JSON.parse(raw) as Stored;+ } catch {+ parsed = null;+ }+ state =+ parsed && parsed.v === VERSION && Array.isArray(parsed.records)+ ? { ...parsed, troubleAt: parsed.troubleAt || 0 }+ : { v: VERSION, records: [], nextId: 1, sentThrough: 0, troubleAt: 0 };+ return state;+}++function persist(): void {+ if (!dirty || !state) return;+ dirty = false;+ try {+ localStorage.setItem(KEY, JSON.stringify(state));+ } catch {+ // Storage full or unavailable; the records stay in memory and send from+ // there.+ }+}++function scheduleWrite(): void {+ dirty = true;+ if (writeTimer) return;+ writeTimer = setTimeout(() => {+ writeTimer = null;+ idle(persist);+ }, WRITE_MIN_MS);+}++/** Keep one frame. Cheap enough to call from a performance observer. */+export function logPerfRecord(rec: Omit<PerfLogRecord, "id" | "open">): void {+ if (typeof window === "undefined") return;+ const s = load();+ s.records.push({ ...rec, open: openedAt, id: s.nextId++ });+ if (s.records.length > CAP) s.records.splice(0, s.records.length - CAP);+ scheduleWrite();+}++/** Why this session sends, or null while it has no reason to. The meters+ * ask before every summary. */+export function perfUploadReason(): PerfUploadReason | null {+ if (trouble) return "trouble";+ if (sampled) return "sampled";+ return null;+}++/** The session has seen something worth sending: the log drains shortly,+ * carrying the frames that led here, and summaries send from now on. */+export function notePerfTrouble(): void {+ if (trouble) return;+ trouble = true;+ if (state) {+ state.troubleAt = Date.now();+ scheduleWrite();+ }+ if (sink) scheduleDrain(DRAIN_AFTER_TROUBLE_MS);+}++/** Send everything not yet sent, in batches, and remember how far that got.+ * Sends nothing while the session has no reason to, and after its share of+ * drains is spent. */+export function drainPerfLog(): void {+ const s = state;+ const reason = perfUploadReason();+ if (!s || !sink || !reason || drains >= DRAIN_CAP) return;+ const pending = s.records.filter((r) => r.id > s.sentThrough).slice(-BATCH * BATCH_CAP);+ if (pending.length === 0) return;+ drains++;+ const of = Math.ceil(pending.length / BATCH);+ const cores = navigator.hardwareConcurrency || 0;+ const memoryGb = (navigator as unknown as { deviceMemory?: number }).deviceMemory ?? 0;+ for (let i = 0; i < of; i++) {+ sink({+ batch: i + 1,+ of,+ reason,+ records: pending.slice(i * BATCH, (i + 1) * BATCH),+ cores,+ memoryGb,+ });+ }+ s.sentThrough = pending[pending.length - 1].id;+ s.troubleAt = 0;+ dirty = true;+ persist();+}++function scheduleDrain(afterMs: number): void {+ if (drainTimer) clearTimeout(drainTimer);+ drainTimer = setTimeout(() => {+ drainTimer = null;+ idle(() => {+ // The editor may have closed while this waited for an idle moment, and+ // a timer armed after that is one nothing can clear.+ if (!sink) return;+ drainPerfLog();+ scheduleDrain(DRAIN_MIN_MS);+ });+ }, afterMs);+}++/**+ * Start keeping the log and sending it through `send`.+ *+ * The first drain, shortly after open, carries what the previous page left+ * behind — and a page that left unsent frames behind is one that never got to+ * send them, which is trouble in itself; later drains run a few minutes+ * apart. The page hiding writes and sends at once — the analytics client+ * beacons what it is handed there.+ */+export function startPerfLog(send: (batch: PerfLogBatch) => void): void {+ sink = send;+ if (typeof window === "undefined" || removePageHide) return;+ openedAt = openedAt || Date.now();+ // Rolled once for the page, not once per project opened in it: a dice throw+ // per editor mount would make the baseline a share of opens rather than a+ // share of sessions, and inflate the very population trouble is measured+ // against.+ if (!rolled) {+ rolled = true;+ sampled = Math.random() < SAMPLE_RATE;+ }+ const s = load();+ const stale = s.records.findIndex((r) => openedAt - r.at < KEEP_MS);+ if (stale !== 0) {+ s.records.splice(0, stale === -1 ? s.records.length : stale);+ dirty = true;+ }+ if (s.troubleAt && s.records.some((r) => r.id > s.sentThrough)) trouble = true;+ scheduleDrain(DRAIN_AFTER_OPEN_MS);+ const onHide = () => {+ if (document.visibilityState !== "hidden") return;+ persist();+ drainPerfLog();+ };+ document.addEventListener("visibilitychange", onHide);+ window.addEventListener("pagehide", onHide);+ removePageHide = () => {+ document.removeEventListener("visibilitychange", onHide);+ window.removeEventListener("pagehide", onHide);+ };+}++/** Stop keeping the log, sending what is in hand first. */+export function stopPerfLog(): void {+ if (writeTimer) clearTimeout(writeTimer);+ writeTimer = null;+ if (drainTimer) clearTimeout(drainTimer);+ drainTimer = null;+ persist();+ drainPerfLog();+ removePageHide?.();+ removePageHide = null;+ sink = null;+}diff --git a/site/src/cut/lib/perfMeter.test.ts b/site/src/cut/lib/perfMeter.test.tsindex ebbd5c1f..dcef9155 100644--- a/site/src/cut/lib/perfMeter.test.ts+++ b/site/src/cut/lib/perfMeter.test.ts@@ -1,7 +1,10 @@import { describe, expect, test } from "bun:test";+import { notePerfTrouble, perfUploadReason } from "./perfLog";import {flushMeter,meterAudioClock,+ meterAudioLate,+ meterClockJump,meterFrame,meterPerf,meterPull,@@ -14,7 +17,35 @@ import {} from "./perfTrace";describe("preview diagnostics meter", () => {+ test("a smooth play in a session with no reason to send sends nothing", () => {+ const out: PerfSample[] = [];+ meterPerf((s) => out.push(s));+ for (let i = 0; i < 300; i++) meterFrame(i < 30 ? 0.3 : 0, false);+ flushMeter();+ expect(out).toHaveLength(0);+ expect(perfUploadReason()).toBeNull();+ stopMeter();+ });++ test("sound starting late is trouble, and the summary says so", () => {+ const out: PerfSample[] = [];+ meterPerf((s) => out.push(s));+ for (let i = 0; i < 300; i++) meterFrame(0, false);+ meterAudioLate(0.4);+ meterAudioLate(1.2);+ meterAudioLate(0.3);+ meterClockJump();+ flushMeter();+ expect(out).toHaveLength(1);+ expect(out[0].reason).toBe("trouble");+ expect(out[0].audioLate).toBe(3);+ expect(out[0].audioLateMaxS).toBe(1.2);+ expect(out[0].clockJumps).toBe(1);+ stopMeter();+ });+test("a play's frames become one summary", () => {+ notePerfTrouble();const out: PerfSample[] = [];meterPerf((s) => out.push(s));expect(metering()).toBe(true);@@ -42,6 +73,7 @@ describe("preview diagnostics meter", () => {expect(out).toHaveLength(1);const s = out[0];+ expect(s.reason).toBe("trouble");expect(s.frames).toBe(300);expect(s.lateShare).toBe(0.1);expect(s.staleShare).toBe(0.033);@@ -74,6 +106,23 @@ describe("preview diagnostics meter", () => {stopMeter();});+ test("a hitching play is trouble, and sends from then on", () => {+ const out: PerfSample[] = [];+ meterPerf((s) => out.push(s));+ // A quarter of the frames a hitch behind.+ for (let i = 0; i < 300; i++) meterFrame(i < 75 ? 0.3 : 0, false);+ flushMeter();+ expect(out).toHaveLength(1);+ expect(out[0].reason).toBe("trouble");+ expect(out[0].hitchShare).toBe(0.25);+ // The next window is smooth and still sends: the session has its reason.+ for (let i = 0; i < 300; i++) meterFrame(0, false);+ flushMeter();+ expect(out).toHaveLength(2);+ expect(perfUploadReason()).toBe("trouble");+ stopMeter();+ });+test("counting costs nothing until it is armed", () => {expect(metering()).toBe(false);meterFrame(1, true);diff --git a/site/src/cut/lib/perfTrace.ts b/site/src/cut/lib/perfTrace.tsindex 52069982..bcc10df7 100644--- a/site/src/cut/lib/perfTrace.ts+++ b/site/src/cut/lib/perfTrace.ts@@ -1,5 +1,7 @@"use client";+import { logPerfRecord, notePerfTrouble, perfUploadReason, type PerfUploadReason } from "./perfLog";+/*** What the preview actually did, frame by frame.*@@ -328,6 +330,8 @@ export interface DecodeCaps {}export interface PerfSample {+ /** Why this session is sending — see perfLog. */+ reason: PerfUploadReason;/** Which summary this is in the session, and how long the editor had been* open when it closed — a preview that is smooth for a minute and choppy* after ten is two samples that say so. */@@ -353,6 +357,16 @@ export interface PerfSample {* second is a picture running that far ahead of its own audio. */audioLeadS: number;audioLatencyS: number;+ /**+ * Sound that missed its moment: windows the mixer had to start late, and+ * the worst by how much; and the times the clock re-anchored because the+ * audio graph fell away from the wall — an output that dropped out, a+ * device that stalled under load. A picture that keeps time while these+ * climb is the "audio cuts out" that no frame count shows.+ */+ audioLate: number;+ audioLateMaxS: number;+ clockJumps: number;/*** Walks the preview started while playing, and the worst one's cost.*@@ -411,9 +425,17 @@ const SAMPLE_FRAMES = 1800;const SAMPLE_MIN_FRAMES = 240;/** Summaries one editor session will send. A day-long session is interesting* for its first few, and this is not a firehose. */-const SAMPLE_CAP = 40;+const SAMPLE_CAP = 8;/** A frame this far behind is a hitch a person would name. */const HITCH_S = 0.25;+/** A play with this share of hitches, or a picture this far behind its sound,+ * is trouble the session sends about — see perfLog for what that starts. */+const TROUBLE_HITCH_SHARE = 0.2;+const TROUBLE_LAG_S = 1;+/** Sound starting late this many times in one window, or the clock+ * re-anchoring this many, is trouble too. */+const TROUBLE_AUDIO_LATE = 3;+const TROUBLE_CLOCK_JUMPS = 2;interface Meter {frames: number;@@ -433,6 +455,9 @@ interface Meter {srcCodec: string;audioLead: number;audioLatency: number;+ audioLate: number;+ audioLateMax: number;+ clockJumps: number;sources: number;held: number;warmMb: number;@@ -446,7 +471,6 @@ interface Meter {let meter: Meter | null = null;let sink: ((sample: PerfSample) => void) | null = null;-let meterObserver: PerformanceObserver | null = null;let sampleCount = 0;let openedAt = 0;let caps: DecodeCaps = { h264: false, hevc: false, vp9: false, av1: false };@@ -469,6 +493,9 @@ const emptyMeter = (): Meter => ({srcCodec: "",audioLead: 0,audioLatency: 0,+ audioLate: 0,+ audioLateMax: 0,+ clockJumps: 0,sources: 0,held: 0,warmMb: 0,@@ -495,25 +522,10 @@ export function meterPerf(report: (sample: PerfSample) => void): void {openedAt = performance.now();meter = emptyMeter();void probeDecodeCaps();- if (typeof PerformanceObserver === "undefined") return;- try {- meterObserver = new PerformanceObserver((list) => {- for (const entry of list.getEntries()) {- if (!meter) return;- meter.longTasks++;- meter.longTaskMs = Math.max(meter.longTaskMs, Math.round(entry.duration));- }- });- meterObserver.observe({ entryTypes: ["longtask"] });- } catch {- meterObserver = null;- }}/** Stop counting and forget the sink. */export function stopMeter(): void {- meterObserver?.disconnect();- meterObserver = null;meter = null;sink = null;}@@ -589,6 +601,20 @@ export function meterAudioClock(lead: number, reported: number): void {meter.audioLatency = Math.max(meter.audioLatency, reported);}+/** A window of sound started after the moment it was for, by `lateS`. */+export function meterAudioLate(lateS: number): void {+ if (!meter) return;+ meter.audioLate++;+ meter.audioLateMax = Math.max(meter.audioLateMax, lateS);+}++/** The mixer re-anchored its clock: the audio graph had fallen away from the+ * wall, and everything scheduled was torn down and refilled. */+export function meterClockJump(): void {+ if (!meter) return;+ meter.clockJumps++;+}+/*** Send what has been counted and start a fresh count.*@@ -600,10 +626,23 @@ export function flushMeter(): void {const m = meter;if (!m || !sink) return;meter = emptyMeter();- if (m.frames < SAMPLE_MIN_FRAMES || sampleCount >= SAMPLE_CAP) return;+ // Trouble is read before the window is judged too short to report. A play+ // that froze draws few frames — the thread was blocked — so the shortest+ // windows are the ones carrying the worst news.+ if (+ (m.frames > 0 && m.hitches / m.frames >= TROUBLE_HITCH_SHARE) ||+ m.lagMax >= TROUBLE_LAG_S ||+ m.audioLate >= TROUBLE_AUDIO_LATE ||+ m.clockJumps >= TROUBLE_CLOCK_JUMPS+ )+ notePerfTrouble();+ if (m.frames < SAMPLE_MIN_FRAMES) return;+ const reason = perfUploadReason();+ if (!reason || sampleCount >= SAMPLE_CAP) return;const seconds = (performance.now() - m.startedAt) / 1000;const round = (n: number, places = 3) => +n.toFixed(places);sink({+ reason,sample: ++sampleCount,openedForS: Math.round((performance.now() - openedAt) / 1000),seconds: round(seconds, 1),@@ -616,6 +655,9 @@ export function flushMeter(): void {lagMaxS: round(m.lagMax),audioLeadS: round(m.audioLead),audioLatencyS: round(m.audioLatency),+ audioLate: m.audioLate,+ audioLateMaxS: round(m.audioLateMax),+ clockJumps: m.clockJumps,walks: m.walks,walkMs: m.walkMs,pullMaxMs: Math.round(m.pullMax),@@ -674,3 +716,361 @@ async function probeDecodeCaps(): Promise<void> {]);caps = { h264, hevc, vp9, av1 };}++/**+ * The main thread's report card, for the freezes that happen between plays.+ *+ * The meter above counts what the preview did per played frame, so it says+ * nothing about a delete that took two seconds to land or an import that+ * froze the page. This watches the thread itself: every animation frame the+ * browser reports as long, with the script that ran it and what it was+ * invoked by — the one attribution a person's own machine can give, since the+ * profiler is never open when it happens.+ *+ * Long animation frames are Chromium's. Where the API is missing the long+ * task list stands in, which names the cost and nothing about its cause.+ *+ * Nothing here reads the project. The script names are the page's own+ * bundle; the "input" beside a frame is which control was pressed — a button's+ * label, a key's name — and a key pressed into a text field is reported as+ * text, never as the character.+ */+export interface MainThreadSample {+ /** Why this session is sending — see perfLog. */+ reason: PerfUploadReason;+ sample: number;+ openedForS: number;+ /** Wall seconds this summary covers. */+ seconds: number;+ /** Frames the thread was blocked in, milliseconds blocked across them, and+ * the longest of them. */+ longFrames: number;+ blockedMs: number;+ worstMs: number;+ /** The worst frame: how it split between script and layout, what invoked+ * the script, and where in the bundle it lives. */+ worstScriptMs: number;+ worstLayoutMs: number;+ worstInvoker: string;+ worstFn: string;+ worstSrc: string;+ worstChar: number;+ /** What the editor was doing when the worst frame hit, and what was pressed+ * last, how long before. */+ worstActivity: MainThreadActivity;+ worstInput: string;+ worstInputAgoMs: number;+ /** The three scripts that blocked longest across the window, as+ * "invoker>function:ms", pipe-separated. */+ top: string;+ /** The size of the cut at flush time. */+ clips: number;+ audioClips: number;+ overlays: number;+ assets: number;+ cores: number;+ memoryGb: number;+}++export type MainThreadActivity = "playing" | "dragging" | "idle";++/** What the editor tells the meter about itself when a frame lands. */+export interface MainThreadContext {+ activity: MainThreadActivity;+ clips: number;+ audioClips: number;+ overlays: number;+ assets: number;+}++/** A long-animation-frame entry, as Chromium reports it. The lib has no+ * type for it yet. */+interface LongFrameEntry extends PerformanceEntry {+ blockingDuration?: number;+ renderStart?: number;+ styleAndLayoutStart?: number;+ scripts?: LongFrameScript[];+}++interface LongFrameScript {+ duration: number;+ invoker?: string;+ sourceURL?: string;+ sourceFunctionName?: string;+ sourceCharPosition?: number;+}++interface WorstFrame {+ ms: number;+ scriptMs: number;+ layoutMs: number;+ invoker: string;+ fn: string;+ src: string;+ char: number;+ activity: MainThreadActivity;+ input: string;+ inputAgoMs: number;+}++interface ThreadMeter {+ longFrames: number;+ blockedMs: number;+ worst: WorstFrame | null;+ /** Blocked milliseconds per "invoker>function", for the top list. */+ byScript: Map<string, number>;+ startedAt: number;+}++/** A window this long is one summary. */+const THREAD_FLUSH_MS = 30_000;+/** A window whose worst frame is under this reports nothing, and a frame+ * under it is not kept in the log: a page that is merely busy is not the+ * complaint. */+const THREAD_REPORT_MS = 100;+/** Summaries one editor session will send. */+const THREAD_SAMPLE_CAP = 8;+/** A single frame this long, or a window blocked for this long in total, is+ * trouble the session sends about — see perfLog for what that starts. */+const TROUBLE_FRAME_MS = 1_000;+const TROUBLE_WINDOW_MS = 3_000;+/** An input older than this is not what a frame is answering. */+const INPUT_RECENT_MS = 5_000;++let threadMeter: ThreadMeter | null = null;+let threadSink: ((sample: MainThreadSample) => void) | null = null;+let threadContext: (() => MainThreadContext) | null = null;+let threadObserver: PerformanceObserver | null = null;+let threadTimer: ReturnType<typeof setInterval> | null = null;+let threadSamples = 0;+let threadOpenedAt = 0;+let lastInput: { at: number; what: string } | null = null;+let removeInputWatch: (() => void) | null = null;++const emptyThreadMeter = (): ThreadMeter => ({+ longFrames: 0,+ blockedMs: 0,+ worst: null,+ byScript: new Map(),+ startedAt: performance.now(),+});++/** The last path segment of a bundle URL — the chunk's name, which is what a+ * source map resolves against. */+const chunkName = (url: string | undefined): string => {+ if (!url) return "";+ const path = url.split(/[?#]/)[0];+ return path.slice(path.lastIndexOf("/") + 1);+};++/**+ * Which control an input landed on, read from the page's structure: a+ * timeline selection's kind, the component slots around it, the tag and an+ * input's type — every one of them a literal in this codebase.+ *+ * Nothing the page displays goes in. A label or a button's text carries what+ * the person named, wrote, or was shown — a file name, a project, another+ * user's email — and a performance record is no place for any of it.+ */+function describeTarget(target: EventTarget | null): string {+ const el = target instanceof Element ? target : null;+ if (!el) return "";+ const sel = el.closest<HTMLElement>("[data-tl-sel]");+ if (sel) return `timeline:${(sel.dataset.tlSel ?? "").split(":")[0]}`;+ const self = el instanceof HTMLInputElement ? `input:${el.type}` : el.tagName.toLowerCase();+ const slots: string[] = [];+ for (let node: Element | null = el; node && slots.length < 2; node = node.parentElement) {+ const slot = node instanceof HTMLElement ? node.dataset.slot : undefined;+ if (slot) slots.unshift(slot);+ }+ return slots.length ? `${slots.join(">")} ${self}` : self;+}++const isTextEntry = (target: EventTarget | null): boolean => {+ const el = target instanceof HTMLElement ? target : null;+ return (+ !!el &&+ (el.tagName === "TEXTAREA" ||+ el.isContentEditable ||+ (el.tagName === "INPUT" &&+ !["checkbox", "radio", "range", "button", "file"].includes((el as HTMLInputElement).type)))+ );+};++function watchInputs(): () => void {+ const onPointer = (e: PointerEvent) => {+ lastInput = { at: performance.now(), what: `press ${describeTarget(e.target)}` };+ };+ const onKey = (e: KeyboardEvent) => {+ const mods = [e.ctrlKey && "ctrl", e.metaKey && "cmd", e.altKey && "alt", e.shiftKey && "shift"]+ .filter(Boolean)+ .join("+");+ const key = isTextEntry(e.target) ? "text" : e.key.length === 1 ? e.key.toLowerCase() : e.key;+ lastInput = { at: performance.now(), what: `key ${mods ? `${mods}+` : ""}${key}` };+ };+ window.addEventListener("pointerdown", onPointer, true);+ window.addEventListener("keydown", onKey, true);+ return () => {+ window.removeEventListener("pointerdown", onPointer, true);+ window.removeEventListener("keydown", onKey, true);+ };+}++function noteLongFrame(entry: LongFrameEntry): void {+ const m = threadMeter;+ if (!m) return;+ const ms = entry.duration;+ const blocked = entry.blockingDuration ?? Math.max(0, ms - 50);+ m.longFrames++;+ m.blockedMs += blocked;+ if (meter) {+ meter.longTasks++;+ meter.longTaskMs = Math.max(meter.longTaskMs, Math.round(ms));+ }+ const scripts = entry.scripts ?? [];+ let scriptMs = 0;+ let lead: LongFrameScript | null = null;+ for (const s of scripts) {+ scriptMs += s.duration;+ if (!lead || s.duration > lead.duration) lead = s;+ const fn = s.sourceFunctionName || chunkName(s.sourceURL);+ const key = `${s.invoker ?? ""}>${fn}`;+ m.byScript.set(key, (m.byScript.get(key) ?? 0) + s.duration);+ }+ const end = entry.startTime + ms;+ const layoutMs =+ entry.styleAndLayoutStart && entry.styleAndLayoutStart > 0 ? end - entry.styleAndLayoutStart : 0;+ if (ms < THREAD_REPORT_MS && m.worst) return;+ const at = performance.now();+ const recent = lastInput && at - lastInput.at <= INPUT_RECENT_MS + ms ? lastInput : null;+ const frame: WorstFrame = {+ ms,+ scriptMs,+ layoutMs,+ invoker: lead?.invoker ?? "",+ fn: lead?.sourceFunctionName ?? "",+ src: chunkName(lead?.sourceURL),+ char: lead?.sourceCharPosition ?? -1,+ activity: threadContext?.().activity ?? "idle",+ input: recent?.what ?? "",+ inputAgoMs: recent ? Math.max(0, Math.round(entry.startTime - recent.at)) : -1,+ };+ if (ms >= TROUBLE_FRAME_MS) notePerfTrouble();+ if (ms >= THREAD_REPORT_MS) {+ logPerfRecord({+ at: Math.round(performance.timeOrigin + entry.startTime),+ ms: Math.round(ms),+ blockedMs: Math.round(blocked),+ scriptMs: Math.round(scriptMs),+ layoutMs: Math.round(layoutMs),+ invoker: frame.invoker,+ fn: frame.fn,+ src: frame.src,+ char: frame.char,+ activity: frame.activity,+ input: frame.input,+ inputAgoMs: frame.inputAgoMs,+ });+ }+ if (!m.worst || ms > m.worst.ms) m.worst = frame;+}++/** Whether the main thread is being watched. */+export const meteringMainThread = (): boolean => threadMeter !== null;++/**+ * Start watching the main thread, sending each summary to `report` with what+ * `context` says the editor was doing. Calling again replaces both and leaves+ * the counts alone.+ */+export function meterMainThread(+ report: (sample: MainThreadSample) => void,+ context: () => MainThreadContext+): void {+ threadSink = report;+ threadContext = context;+ if (threadMeter) return;+ if (typeof PerformanceObserver === "undefined") return;+ const types = PerformanceObserver.supportedEntryTypes ?? [];+ const type = types.includes("long-animation-frame")+ ? "long-animation-frame"+ : types.includes("longtask")+ ? "longtask"+ : null;+ if (!type) return;+ threadOpenedAt = performance.now();+ threadMeter = emptyThreadMeter();+ try {+ threadObserver = new PerformanceObserver((list) => {+ for (const entry of list.getEntries()) noteLongFrame(entry as LongFrameEntry);+ });+ threadObserver.observe({ type });+ } catch {+ threadObserver = null;+ threadMeter = null;+ return;+ }+ removeInputWatch = watchInputs();+ threadTimer = setInterval(flushMainThreadMeter, THREAD_FLUSH_MS);+}++/** Send what has been counted and start a fresh window. A window with no+ * frame worth naming sends nothing. */+export function flushMainThreadMeter(): void {+ const m = threadMeter;+ if (!m || !threadSink) return;+ threadMeter = emptyThreadMeter();+ // A window blocked for seconds is trouble however it got there: one long+ // frame, or a hundred medium ones that never reach the reporting bar.+ if (m.blockedMs >= TROUBLE_WINDOW_MS) notePerfTrouble();+ const worst = m.worst;+ if (!worst || worst.ms < THREAD_REPORT_MS) return;+ const reason = perfUploadReason();+ if (!reason || threadSamples >= THREAD_SAMPLE_CAP) return;+ const ctx = threadContext?.() ?? { activity: "idle", clips: 0, audioClips: 0, overlays: 0, assets: 0 };+ const top = [...m.byScript.entries()]+ .sort((a, b) => b[1] - a[1])+ .slice(0, 3)+ .map(([key, ms]) => `${key}:${Math.round(ms)}`)+ .join(" | ");+ threadSink({+ reason,+ sample: ++threadSamples,+ openedForS: Math.round((performance.now() - threadOpenedAt) / 1000),+ seconds: +((performance.now() - m.startedAt) / 1000).toFixed(1),+ longFrames: m.longFrames,+ blockedMs: Math.round(m.blockedMs),+ worstMs: Math.round(worst.ms),+ worstScriptMs: Math.round(worst.scriptMs),+ worstLayoutMs: Math.round(worst.layoutMs),+ worstInvoker: worst.invoker,+ worstFn: worst.fn,+ worstSrc: worst.src,+ worstChar: worst.char,+ worstActivity: worst.activity,+ worstInput: worst.input,+ worstInputAgoMs: worst.inputAgoMs,+ top,+ clips: ctx.clips,+ audioClips: ctx.audioClips,+ overlays: ctx.overlays,+ assets: ctx.assets,+ cores: navigator.hardwareConcurrency || 0,+ memoryGb: (navigator as unknown as { deviceMemory?: number }).deviceMemory ?? 0,+ });+}++/** Stop watching, sending the window in hand first. */+export function stopMainThreadMeter(): void {+ flushMainThreadMeter();+ if (threadTimer) clearInterval(threadTimer);+ threadTimer = null;+ threadObserver?.disconnect();+ threadObserver = null;+ removeInputWatch?.();+ removeInputWatch = null;+ threadMeter = null;+ threadSink = null;+ threadContext = null;+ lastInput = null;+}diff --git a/site/src/cut/lib/previewMixer.ts b/site/src/cut/lib/previewMixer.tsindex 86790327..2769604c 100644--- a/site/src/cut/lib/previewMixer.ts+++ b/site/src/cut/lib/previewMixer.ts@@ -44,6 +44,7 @@ import {} from "@donkeycut/effects-kit";import type { WrappedAudioBuffer } from "mediabunny";import { assembleAudio, decodeAudioSpan, openAudioWalk, type AudioWalk } from "./mediaRead";+import { meterAudioLate, meterClockJump } from "./perfTrace";import { timeStretch } from "./timeStretch";/** How much of a voice is pulled off its walk and scheduled at once, in source@@ -76,6 +77,13 @@ const AHEAD_S = 5;* device claims. Well past a Bluetooth headset, and short of anything that* would read as the playhead refusing to move. */const MAX_LATENCY_S = 0.4;+/** Sound late by more than this, mid-play, is a hole the listener hears: the+ * scheduling runs seconds ahead, so a window that misses its moment means the+ * thread was gone for that long. A voice's first window is a different thing+ * — it is read while the play is already running, by design — so only a long+ * one counts there. */+const LATE_GAP_S = 0.05;+const LATE_FIRST_S = 0.5;/** One audible thing on the timeline: a clip's own sound, or a soundtrack item. */export interface Voice {@@ -302,6 +310,7 @@ export class PreviewMixer {// moving would leave those windows playing the wrong moment for up to// their full length, so they stop here and the next update refills from// where the clock now stands.+ meterClockJump();this.restart(wall);return this.heard(wall);}@@ -599,6 +608,12 @@ export class PreviewMixer {}}+ /** A window that missed its moment. Reported to the diagnostics meter once+ * it is past what the first read of a voice costs by design. */+ private noteLate(live: LiveVoice, lateS: number): void {+ if (lateS > (live.windows.length ? LATE_GAP_S : LATE_FIRST_S)) meterAudioLate(lateS);+ }+/*** Get the sound ready for a play that has not started.*@@ -852,6 +867,7 @@ export class PreviewMixer {if (!current() || live.scheduled !== from) return;const until = from + buffer.duration;if (until <= tNow) {+ this.noteLate(live, tNow - from);// The read outlived the moment it was for — a long wait on bytes, a// tab in the background. Where it left the walk is behind the clock// now, so the voice re-aims at the clock and gives up the stretch in@@ -868,7 +884,8 @@ export class PreviewMixer {node.start(at);} else {// Late: start where the clock actually is, so the sound stays lined up- // with the picture instead of replaying what has already gone by.+ // with the picture and skips what has already gone by.+ this.noteLate(live, now - at);node.start(now, now - at);}live.windows.push({ node, until });diff --git a/site/src/lib/analytics.ts b/site/src/lib/analytics.tsindex 02a7ed75..7a4419b7 100644--- a/site/src/lib/analytics.ts+++ b/site/src/lib/analytics.ts@@ -1,7 +1,8 @@import posthog from "posthog-js";import { useEffect } from "react";-import type { PerfSample } from "@/cut/lib/perfTrace";+import type { PerfLogBatch } from "@/cut/lib/perfLog";+import type { MainThreadSample, PerfSample } from "@/cut/lib/perfTrace";import type {OnboardingRun,ReferralSource,@@ -35,6 +36,12 @@ export type AnalyticsEvents = {// half minute of playback. Numbers only — see `PerfSample` in the Cut// preview's perfTrace for what each one means and why it is here.cut_preview_perf: PerfSample;+ // Main-thread freezes from the same account, one summary per half minute+ // that held one — see `MainThreadSample` in perfTrace for the fields.+ cut_main_thread: MainThreadSample;+ // The blocked frames themselves, kept locally and sent at idle, on the page+ // hiding, and on the next open — see perfLog for the record.+ cut_perf_log: PerfLogBatch;// Billing (settings).pro_checkout_started: void;billing_portal_opened: void;diff --git a/site/src/lib/feature-flags.ts b/site/src/lib/feature-flags.tsindex 790265e3..eda67908 100644--- a/site/src/lib/feature-flags.ts+++ b/site/src/lib/feature-flags.ts@@ -23,14 +23,6 @@ export const ACCOUNT_FEATURE_FLAGS: AccountFeatureFlag[] = [group: "editor",defaultEnabled: true,},- {- id: "preview_diagnostics",- title: "Share diagnostics",- description:- "Help us diagnose playback issues. Your video, audio, and project stay in your browser.",- group: "early",- defaultEnabled: false,- },];export const isKnownFeatureFlag = (id: string) =>