Open source CapCut alternative.
TypeScript
fix(site): a swallowed read failure reports what failed
David Led283300f7e98
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsxindex 23769efb..62c8aa8c 100644--- a/site/src/cut/components/Editor.tsx+++ b/site/src/cut/components/Editor.tsx@@ -42,6 +42,7 @@ import { useOnboardingCover } from "@/cut/lib/onboarding";import { requestSidePanel } from "@/cut/lib/panelRequest";import { resolveProjectPlacement } from "@/cut/lib/residency";import {+import { reportSwallowed } from "@/cut/lib/report";docAudioClips,docClips,docOverlays,@@ -666,7 +667,7 @@ export function Editor({void enrichAsset(asset, pending?.localUrl);if (pending) startUpload(projectId, pending);} catch (err) {- console.error(`Import failed for ${file.name}:`, err);+ reportSwallowed(`[cut] import failed for ${file.name}`, err);} finally {setImporting((n) => n - 1);}@@ -875,7 +876,7 @@ export function Editor({if (s.paste()) e.preventDefault();else if (hasCopiedFrame()) {e.preventDefault();- void pasteCopiedFrame().catch((err) => console.error("Paste frame failed:", err));+ void pasteCopiedFrame().catch((err) => reportSwallowed("[cut] paste frame failed", err));}} else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "g") {// ⌘G groups the multi-selected elements, ⇧⌘G dissolves the primary'sdiff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.tsindex d3f687ea..14e3e65a 100644--- a/site/src/cut/lib/media.ts+++ b/site/src/cut/lib/media.ts@@ -42,6 +42,7 @@ import {type RasterSurface,} from "./raster";import { pickThumbTimes, type ThumbProbe } from "./filmstrip";+import { reportSwallowed } from "./report";import { useEditor } from "./store";import type { AssetType, AudioClip, MediaAsset, ProjectSummary, StoredAsset, VideoClip, WatchKeepReason } from "./types";import { contentRect, IMAGE_CLIP_SECONDS, mediaUrl } from "./types";@@ -1516,7 +1517,7 @@ export async function enrichAsset(asset: MediaAsset, src = asset.url) {if (live && stripComplete(live) && live.sceneCuts === undefined) {void refineSceneCuts(asset.id, src, asset.duration).catch((err) => {// Scene cuts only sharpen the strip; the tiles already painted.- console.error(`[cut] scene probe failed for ${asset.fileName}`, err);+ reportSwallowed(`[cut] scene probe failed for ${asset.fileName}`, err);});}// The clip box draws the sound under the picture, so a video enriches@@ -1529,7 +1530,7 @@ export async function enrichAsset(asset: MediaAsset, src = asset.url) {} catch (err) {// The strip above already painted; a peaks failure (an expired// signed URL, an undecodable track) never marks it failed.- console.error(`[cut] peaks failed for ${asset.fileName}`, err);+ reportSwallowed(`[cut] peaks failed for ${asset.fileName}`, err);}}enrichRetries.delete(asset.id);@@ -1541,13 +1542,12 @@ export async function enrichAsset(asset: MediaAsset, src = asset.url) {} catch (err) {// Thumbnails and waveforms are decorative; editing works without them.// The failure still gets recorded — clips stop their loading pulse — and- // logged at error level, which carries it into PostHog error tracking- // (console.error autocapture) with the file's shape beside the cause.+ // reported, which carries it into PostHog error tracking with the file's+ // shape beside the cause (lib/report.ts).if (asset.type === "video") setStripFailed(asset.id, true);if (asset.type !== "image") scheduleEnrichRetry(asset.id);- console.error(- `[cut] enrich failed for ${asset.fileName}`,- { type: asset.type, durationSec: Math.round(asset.duration) },+ reportSwallowed(+ `[cut] enrich failed for ${asset.fileName} (${asset.type}, ${Math.round(asset.duration)}s)`,err);} finally {@@ -1564,9 +1564,8 @@ export async function ensurePeaks(asset: MediaAsset) {if (peaks?.length) useEditor.getState().updateAsset(asset.id, { peaks });}} catch (err) {- // Waveforms are decorative; editing works without them. Error level- // carries the failure into PostHog error tracking.- console.error(`[cut] peaks failed for ${asset.fileName}`, err);+ // Waveforms are decorative; editing works without them.+ reportSwallowed(`[cut] peaks failed for ${asset.fileName}`, err);}}diff --git a/site/src/cut/lib/refMedia.ts b/site/src/cut/lib/refMedia.tsindex 726770f3..aef039cb 100644--- a/site/src/cut/lib/refMedia.ts+++ b/site/src/cut/lib/refMedia.ts@@ -12,6 +12,7 @@ import {renderAudioSpanWav,} from "./media";import { frameSink, openMedia, videoTrackOf } from "./mediaRead";+import { reportSwallowed } from "./report";import { createRasterCanvas, rasterCanvasToDataUrl } from "./raster";import { useEditor } from "./store";import { formatTime } from "./time";@@ -331,7 +332,7 @@ export async function refsFromDroppedFiles(if (pending) startUpload(projectId, pending);refs.push(refFromAsset(asset));} catch (err) {- console.error(`Attach failed for ${file.name}:`, err);+ reportSwallowed(`[cut] attach failed for ${file.name}`, err);}}return refs;diff --git a/site/src/cut/lib/report.ts b/site/src/cut/lib/report.tsnew file mode 100644index 00000000..d8a0a0a8--- /dev/null+++ b/site/src/cut/lib/report.ts@@ -0,0 +1,67 @@+"use client";++/**+ * Reporting a failure a feature carried on past.+ *+ * Cut's read paths — filmstrips, waveforms, the chunk cache, an import that+ * only lost one file — keep working when a read fails, and the failure still+ * has to be visible. `console.error` is that channel: PostHog's autocapture+ * turns one into an `$exception` (see instrumentation-client.ts). Handing it+ * the cause directly goes wrong twice.+ *+ * The sentence the call site wrote is dropped. Autocapture picks the `Error`+ * out of the arguments and reports that alone, so a filmstrip that failed on a+ * signed URL arrives in error tracking as a bare "TypeError: Failed to fetch"+ * with nothing saying what was being read.+ *+ * And weather arrives looking like a crash. A read fails because the network+ * blinked, the tab tore the read down, or the store evicted the bytes under+ * it — cases the retry beside the call site already covers, filed as unhandled+ * exceptions against the browser they happened in.+ *+ * So: the transient shapes go to `console.warn`, which autocapture leaves+ * alone, and everything else is reported as one `Error` that says what failed,+ * carrying the cause behind it.+ */++/**+ * Whether this failure is the kind every caller here already handles.+ *+ * Storage and teardown name themselves, so those are read off `name`. `fetch`+ * is the awkward one: every network-level failure — offline, DNS, a connection+ * cut mid-body, a local engine that went away between two range requests —+ * rejects with a bare `TypeError` whose wording is the only mark, and each+ * browser words it differently.+ */+function transient(err: unknown): boolean {+ if (err instanceof DOMException) {+ return (+ // The read was torn down: a scrub superseded it, a clip closed, the tab+ // navigated.+ err.name === "AbortError" ||+ // The cached file was evicted between the handle and the read, or its+ // directory was swept. Reads fall back to the network.+ err.name === "NotFoundError" ||+ err.name === "NotReadableError" ||+ // The origin's store is full. Caching is optional everywhere it runs.+ err.name === "QuotaExceededError"+ );+ }+ return (+ err instanceof TypeError &&+ /failed to fetch|network\s*error|load failed|connection/i.test(err.message)+ );+}++/**+ * Record a failure the feature already handled. `what` is the sentence that+ * ends up in error tracking, so it names the thing that failed and the file it+ * failed on.+ */+export function reportSwallowed(what: string, err: unknown): void {+ if (transient(err)) {+ console.warn(what, err);+ return;+ }+ console.error(new Error(what, { cause: err }));+}diff --git a/site/src/instrumentation-client.ts b/site/src/instrumentation-client.tsindex b0156fe7..cd7a4cb3 100644--- a/site/src/instrumentation-client.ts+++ b/site/src/instrumentation-client.ts@@ -12,6 +12,22 @@ const REPLAY_FREE = /^\/(?:cut\/)?(?:app|s)(?:\/|$)/;// embed one get it masked before the event leaves the browser.const scrubUrls = (s: string) => s.replace(/https?:\/\/\S+/g, "<url>");+/**+ * Whether this exception was thrown by script the page never served.+ *+ * An in-app browser — the web view inside a social or messaging app — injects+ * its own bridge into every page it opens, and that bridge throws when its+ * host tears the native side down mid-page ("Java object is gone"). The frames+ * come from no file, because there is no file: the code was evaluated into the+ * document. Anything this page shipped, minified or not, has a filename on+ * every frame, and an exception carrying no stack at all (a DOMException, say)+ * is ours to keep — so the test is a stack that exists and names nothing.+ */+const fromInjectedScript = (item: { stacktrace?: { frames?: { filename?: string }[] } }) => {+ const frames = item?.stacktrace?.frames;+ return Array.isArray(frames) && frames.length > 0 && frames.every((f) => !f?.filename);+};+// Production builds only: a dev server on localhost sends HMR build overlays// and half-saved-file errors straight into production error tracking.if (process.env.NEXT_PUBLIC_POSTHOG_KEY && process.env.NODE_ENV === "production") {@@ -20,10 +36,11 @@ if (process.env.NEXT_PUBLIC_POSTHOG_KEY && process.env.NODE_ENV === "production"defaults: "2026-05-30",disable_session_recording: REPLAY_FREE.test(window.location.pathname),// Error tracking: unhandled errors, unhandled rejections, and every- // console.error become $exception events. Failures a feature swallows on- // purpose reach it by logging with console.error. Event capture is- // memory-queued batches — none of session replay's canvas readback cost,- // so it runs on the Cut surfaces too.+ // console.error become $exception events. Failures a feature carries on+ // past reach it through cut/lib/report.ts, which words the report and+ // holds back the transient shapes — console.warn is not captured. Event+ // capture is memory-queued batches — none of session replay's canvas+ // readback cost, so it runs on the Cut surfaces too.capture_exceptions: {capture_unhandled_errors: true,capture_unhandled_rejections: true,@@ -33,6 +50,7 @@ if (process.env.NEXT_PUBLIC_POSTHOG_KEY && process.env.NODE_ENV === "production"if (event?.event === "$exception") {const list = event.properties?.$exception_list;if (Array.isArray(list)) {+ if (list.some(fromInjectedScript)) return null;for (const item of list) {if (typeof item?.value === "string") item.value = scrubUrls(item.value);}