Skip to content

Open source CapCut alternative.

TypeScript

fix(site): report errors once per cause, without noise [rebuild]

David Le2f3f5bfca9e5
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsx
index daa86b95..c3ae41b5 100644
--- a/site/src/cut/components/Editor.tsx
+++ b/site/src/cut/components/Editor.tsx
@@ -741,7 +741,7 @@ export function Editor({
void uploadLinkedFile(file)
.then(() => opts?.onOutcome?.({ file, assetId: "" }))
.catch((err) => {
- reportSwallowed(`[cut] shelving failed for ${file.name}`, err);
+ reportSwallowed("[cut] shelving failed", err, file.name);
opts?.onOutcome?.({ file, failed: true });
});
}
@@ -835,7 +835,7 @@ export function Editor({
if (pending) startUpload(projectId, pending);
opts?.onOutcome?.({ file, assetId: asset.id });
} catch (err) {
- reportSwallowed(`[cut] import failed for ${file.name}`, err);
+ reportSwallowed("[cut] import failed", err, file.name);
opts?.onOutcome?.({ file, failed: true });
} finally {
setImporting((n) => n - 1);
@@ -1001,7 +1001,7 @@ export function Editor({
e.preventDefault();
for (const file of linked) {
void uploadLinkedFile(file).catch((err) =>
- reportSwallowed(`[cut] paste failed for ${file.name}`, err)
+ reportSwallowed("[cut] paste failed", err, file.name)
);
}
}
@@ -1039,7 +1039,7 @@ export function Editor({
try {
await placeRefAtPlayhead(ref, { projectId, library, at });
} catch (err) {
- reportSwallowed(`[cut] paste failed for ${ref.name}`, err);
+ reportSwallowed("[cut] paste failed", err, ref.name);
}
}
})();
diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsx
index 4124b676..d6a311c1 100644
--- a/site/src/cut/components/Inspector.tsx
+++ b/site/src/cut/components/Inspector.tsx
@@ -1890,7 +1890,7 @@ function BeatsControl({ asset }: { asset: MediaAsset }) {
disabled={busy || !!asset.upload}
onClick={() => {
void detectAssetBeats(asset).catch((err) => {
- reportSwallowed(`[cut] beat scan failed for ${asset.fileName}`, err);
+ reportSwallowed("[cut] beat scan failed", err, asset.fileName);
});
}}
>
diff --git a/site/src/cut/components/desktopFolders.tsx b/site/src/cut/components/desktopFolders.tsx
index 30be316c..270ddb0d 100644
--- a/site/src/cut/components/desktopFolders.tsx
+++ b/site/src/cut/components/desktopFolders.tsx
@@ -529,7 +529,7 @@ export function FolderShelf<F extends DeskFolder>({
(err: unknown) => {
release();
setFailed(err instanceof Error && err.message ? err.message : "Could not create folder.");
- reportSwallowed(`[cut] folder create failed for ${name}`, err);
+ reportSwallowed("[cut] folder create failed", err, name);
},
);
closeCreate();
diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.ts
index 09e512f0..fec5ef7a 100644
--- a/site/src/cut/lib/library.ts
+++ b/site/src/cut/lib/library.ts
@@ -871,7 +871,7 @@ export async function importLibraryAsset(
height = probe.height;
}
repairLibraryAssetMeta(lib, { duration, width, height }).catch((err: unknown) =>
- reportSwallowed(`[cut] library meta repair failed for ${lib.fileName}`, err),
+ reportSwallowed("[cut] library meta repair failed", err, lib.fileName),
);
}
// On this Mac the engine lands the file with a clone, and it is landed
diff --git a/site/src/cut/lib/mediabunnyLog.test.ts b/site/src/cut/lib/mediabunnyLog.test.ts
new file mode 100644
index 00000000..bc4614e1
--- /dev/null
+++ b/site/src/cut/lib/mediabunnyLog.test.ts
@@ -0,0 +1,37 @@
+import { afterAll, describe, expect, spyOn, test } from "bun:test";
+import { Logging } from "mediabunny";
+
+import "./mediabunnyLog";
+import { bindFailureSink } from "./report";
+
+// Logging._error is how mediabunny itself logs; it is internal, so reach it
+// through a cast.
+const logError = (...args: unknown[]) => (Logging as unknown as { _error(...a: unknown[]): void })._error(...args);
+
+const reports: string[] = [];
+bindFailureSink((error) => reports.push(error.message));
+const warn = spyOn(console, "warn").mockImplementation(() => {});
+const error = spyOn(console, "error").mockImplementation(() => {});
+
+afterAll(() => {
+ bindFailureSink((e) => console.error(e));
+ warn.mockRestore();
+ error.mockRestore();
+});
+
+describe("mediabunny's error log", () => {
+ test("a fetch it retries is a warning", () => {
+ logError("Retrying failed fetch. Error:", new TypeError("Load failed"));
+
+ expect(reports).toEqual([]);
+ expect(error).not.toHaveBeenCalled();
+ expect(warn).toHaveBeenCalled();
+ });
+
+ test("anything else is reported in its own words", () => {
+ logError("Error parsing AVC SPS:", new Error("Invalid exponential-Golomb code."));
+
+ expect(reports).toEqual(["[mediabunny] Error parsing AVC SPS:"]);
+ expect(error).not.toHaveBeenCalled();
+ });
+});
diff --git a/site/src/cut/lib/mediabunnyLog.ts b/site/src/cut/lib/mediabunnyLog.ts
new file mode 100644
index 00000000..45b8cf02
--- /dev/null
+++ b/site/src/cut/lib/mediabunnyLog.ts
@@ -0,0 +1,18 @@
+import { Logging, LogLevel } from "mediabunny";
+
+import { reportSwallowed } from "./report";
+
+/**
+ * mediabunny's error log, routed through Cut's failure reporting.
+ *
+ * mediabunny prints its errors with console.error, which error tracking
+ * captures as a bare exception with the sentence dropped — and most of them
+ * are failures it already handles: a fetch it retries, a response stream it
+ * resumes. Silencing its console and reporting each error with its own words
+ * sends the transient ones to console.warn and names the rest. Warnings and
+ * info stay off the console, as they were at the default level.
+ */
+Logging.level = LogLevel.Silent;
+Logging.on("error", ([what, err]) => {
+ reportSwallowed(`[mediabunny] ${String(what).trim()}`, err);
+});
diff --git a/site/src/cut/lib/network.test.ts b/site/src/cut/lib/network.test.ts
new file mode 100644
index 00000000..58fbc364
--- /dev/null
+++ b/site/src/cut/lib/network.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, test } from "bun:test";
+
+import { fetchDropped } from "./network";
+
+describe("fetchDropped", () => {
+ test("reads each browser's wording for a dropped request", () => {
+ // Chrome, Safari, and Firefox when the connection goes mid-body.
+ for (const message of ["Failed to fetch", "Load failed", "Error in input stream"]) {
+ expect(fetchDropped(new TypeError(message))).toBe(true);
+ }
+ });
+
+ test("leaves a server's answer alone", () => {
+ expect(fetchDropped(new Error("Cut couldn't read this media (404)."))).toBe(false);
+ });
+});
diff --git a/site/src/cut/lib/network.ts b/site/src/cut/lib/network.ts
index c74c11ae..4818054b 100644
--- a/site/src/cut/lib/network.ts
+++ b/site/src/cut/lib/network.ts
@@ -16,9 +16,10 @@ export function onReconnect(work: () => void): void {
export class ConnectionLostError extends Error {}
/** Whether `err` is fetch giving up on the network, by the TypeError every
- * browser throws for it, e.g. Chrome's "Failed to fetch". */
+ * browser throws for it, e.g. Chrome's "Failed to fetch", or Firefox's "Error
+ * in input stream" for a body cut off mid-read. */
export function fetchDropped(err: unknown): boolean {
- return err instanceof TypeError && /failed to fetch|network\s*error|load failed|connection/i.test(err.message);
+ return err instanceof TypeError && /failed to fetch|network\s*error|load failed|connection|input stream/i.test(err.message);
}
/** Whether `err` is the connection failing rather than a server answering:
diff --git a/site/src/cut/lib/refMedia.ts b/site/src/cut/lib/refMedia.ts
index 81e43b6a..73c45361 100644
--- a/site/src/cut/lib/refMedia.ts
+++ b/site/src/cut/lib/refMedia.ts
@@ -330,7 +330,7 @@ export async function refsFromDroppedFiles(
if (pending) startUpload(projectId, pending);
refs.push(refFromAsset(asset));
} catch (err) {
- reportSwallowed(`[cut] attach failed for ${file.name}`, err);
+ reportSwallowed("[cut] attach failed", err, file.name);
}
}
return refs;
diff --git a/site/src/cut/lib/report.test.ts b/site/src/cut/lib/report.test.ts
new file mode 100644
index 00000000..9116d831
--- /dev/null
+++ b/site/src/cut/lib/report.test.ts
@@ -0,0 +1,53 @@
+import { afterAll, describe, expect, spyOn, test } from "bun:test";
+
+import { bindFailureSink, reportSwallowed } from "./report";
+
+type Sent = { error: Error; fingerprint: string };
+
+const sent: Sent[] = [];
+bindFailureSink((error, fingerprint) => sent.push({ error, fingerprint }));
+
+const warn = spyOn(console, "warn").mockImplementation(() => {});
+afterAll(() => warn.mockRestore());
+
+/** Report one failure and hand back what reached the sink. */
+const report = (what: string, err: unknown, subject?: string): Sent | undefined => {
+ sent.length = 0;
+ reportSwallowed(what, err, subject);
+ return sent[0];
+};
+
+describe("reportSwallowed", () => {
+ test("names the file in the message and keeps it out of the grouping", () => {
+ const a = report("[cut] peaks failed", new Error("Decoding error."), "IMG_7087.MOV");
+ const b = report("[cut] peaks failed", new Error("Decoding error."), "IMG_7091.MOV");
+
+ expect(a?.error.message).toBe("[cut] peaks failed for IMG_7087.MOV");
+ expect(b?.error.message).toBe("[cut] peaks failed for IMG_7091.MOV");
+ expect(a?.fingerprint).toBe(b!.fingerprint);
+ });
+
+ test("keeps different causes of one failure apart", () => {
+ const decode = report("[cut] enrich failed", new DOMException("Decoding error.", "EncodingError"), "a.mp4");
+ const read = report("[cut] enrich failed", new Error("Cloud media read failed (404)."), "a.mp4");
+
+ expect(decode?.fingerprint).not.toBe(read!.fingerprint);
+ });
+
+ test("carries the cause behind the report", () => {
+ const cause = new Error("Decoding error.");
+
+ expect(report("[cut] paste failed", cause)?.error.cause).toBe(cause);
+ });
+
+ test("leaves signed URLs out of the grouping", () => {
+ const one = report("[cut] drop failed", new Error("Error fetching https://media.donkeycut.com/a?s=1"), "a");
+ const two = report("[cut] drop failed", new Error("Error fetching https://media.donkeycut.com/b?s=2"), "b");
+
+ expect(one?.fingerprint).toBe(two!.fingerprint);
+ });
+
+ test("sends a dropped connection to the console only", () => {
+ expect(report("[cut] peaks failed", new TypeError("Failed to fetch"), "a.mp4")).toBeUndefined();
+ });
+});
diff --git a/site/src/cut/lib/report.ts b/site/src/cut/lib/report.ts
index 87acb4d7..755e1139 100644
--- a/site/src/cut/lib/report.ts
+++ b/site/src/cut/lib/report.ts
@@ -7,9 +7,9 @@ import { fetchDropped } from "./network";
*
* 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.
+ * has to be visible. Error tracking is that channel (see instrumentation-client.ts),
+ * and `console.error` reaches it too, through PostHog's autocapture. Handing
+ * that 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
@@ -59,15 +59,48 @@ function shape(err: unknown): boolean {
return fetchDropped(err);
}
+/** Where a report goes: the error and the key error tracking groups it by. */
+type FailureSink = (error: Error, fingerprint: string) => void;
+
+// Unbound — a headless process, a test — a report is a console error. The page
+// binds error tracking here (instrumentation-client.ts).
+let sink: FailureSink = (error) => console.error(error);
+
+/** Send every report to `next` from here on. */
+export function bindFailureSink(next: FailureSink): void {
+ sink = next;
+}
+
+/**
+ * The key one kind of failure is grouped under: the step that failed and the
+ * chain of causes behind it, with the file it failed on left out. Error
+ * tracking groups by message otherwise, so a filename in the sentence opened
+ * one issue per file — "peaks failed for IMG_7087.MOV" and "… IMG_7091.MOV"
+ * apart. Signed URLs are masked, since each carries its own signature.
+ */
+function fingerprintOf(what: string, err: unknown): string {
+ const parts = [what];
+ for (let at = err, depth = 0; at != null && depth < 4; depth++) {
+ if (!(at instanceof Error)) {
+ parts.push(String(at));
+ break;
+ }
+ parts.push(`${at.name}: ${at.message.replace(/https?:\/\/\S+/g, "<url>")}`);
+ at = at.cause;
+ }
+ return parts.join(" | ");
+}
+
/**
- * 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.
+ * Record a failure the feature already handled. `what` names the step that
+ * failed, and `subject` the file or item it failed on: the message carries
+ * both, and the grouping only the first.
*/
-export function reportSwallowed(what: string, err: unknown): void {
+export function reportSwallowed(what: string, err: unknown, subject?: string): void {
+ const message = subject ? `${what} for ${subject}` : what;
if (transient(err)) {
- console.warn(what, err);
+ console.warn(message, err);
return;
}
- console.error(new Error(what, { cause: err }));
+ sink(new Error(message, { cause: err }), fingerprintOf(what, err));
}
diff --git a/site/src/instrumentation-client.test.ts b/site/src/instrumentation-client.test.ts
new file mode 100644
index 00000000..cfcbdeee
--- /dev/null
+++ b/site/src/instrumentation-client.test.ts
@@ -0,0 +1,126 @@
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
+
+import { bindFailureSink } from "./cut/lib/report";
+import { stubModule } from "./lib/testing/stubModule";
+
+type Event = { event: string; properties: { $exception_list: unknown[] } };
+type BeforeSend = (event: Event) => Event | null;
+
+let beforeSend: BeforeSend;
+const saved = {
+ env: { ...process.env },
+ window: (globalThis as { window?: unknown }).window,
+ document: (globalThis as { document?: unknown }).document,
+};
+
+// Load the client with production settings and keep the before_send it hands
+// to posthog.init, so each case runs the real filter.
+beforeAll(async () => {
+ await stubModule("posthog-js", import.meta.url, {
+ default: { init: (_key: string, config: { before_send: BeforeSend }) => (beforeSend = config.before_send) },
+ } as never);
+ Object.assign(process.env, { NEXT_PUBLIC_POSTHOG_KEY: "test", NODE_ENV: "production" });
+ Object.assign(globalThis, { window: { location: { pathname: "/" }, addEventListener: () => {} } });
+ await import("./instrumentation-client");
+});
+
+// Bun runs every test file in one process; put the environment back for the rest.
+afterAll(() => {
+ process.env = saved.env;
+ Object.assign(globalThis, { window: saved.window, document: saved.document });
+ // Loading the client bound Cut's failure reports to the stubbed PostHog.
+ bindFailureSink((error) => console.error(error));
+});
+
+const translatedDocument = (lang: string, classes: string[]) => ({
+ documentElement: { lang, classList: { contains: (c: string) => classes.includes(c) } },
+});
+
+const exception = (...list: unknown[]): Event => ({ event: "$exception", properties: { $exception_list: list } });
+
+describe("before_send", () => {
+ test("drops an opaque cross-origin script error", () => {
+ const opaque = { type: "Error", value: "Script error.", mechanism: { synthetic: true } };
+
+ expect(beforeSend(exception(opaque))).toBeNull();
+ });
+
+ test("drops the browser's ResizeObserver loop notice", () => {
+ const notice = { type: "Error", value: "ResizeObserver loop completed with undelivered notifications." };
+
+ expect(beforeSend(exception(notice))).toBeNull();
+ });
+
+ test("drops a wallet extension's injected script", () => {
+ const wallet = {
+ type: "TypeError",
+ value: "undefined is not an object (evaluating 'window.ethereum.selectedAddress = undefined')",
+ stacktrace: { frames: [{ filename: "https://donkeycut.com/", function: "global code" }] },
+ };
+
+ expect(beforeSend(exception(wallet))).toBeNull();
+ });
+
+ test("drops a hydration error on a page the browser translated", () => {
+ // Chrome's translator tags <html> and relabels its language.
+ Object.assign(globalThis, { document: translatedDocument("pt", ["translated-ltr"]) });
+ const hydration = { type: "Error", value: "Minified React error #418; visit <url> for the full message" };
+ const moved = { type: "DOMException", value: "NotFoundError: Failed to execute 'insertBefore' on 'Node': x" };
+
+ expect(beforeSend(exception(hydration))).toBeNull();
+ expect(beforeSend(exception(moved))).toBeNull();
+ });
+
+ test("keeps a hydration error on the page as served", () => {
+ Object.assign(globalThis, { document: translatedDocument("en", []) });
+ const hydration = { type: "Error", value: "Minified React error #418; visit <url> for the full message" };
+
+ expect(beforeSend(exception(hydration))).not.toBeNull();
+ });
+
+ test("drops a script the browser evaluated into the page", () => {
+ // Chrome on iOS runs its translator inline; this one recursed until the
+ // stack ran out, with every frame in the document itself.
+ const translator = {
+ type: "RangeError",
+ value: "Maximum call stack size exceeded.",
+ stacktrace: { frames: [{ filename: "/", lineno: 225 }, { filename: "/", lineno: 196 }, { filename: "[native code]" }] },
+ };
+
+ expect(beforeSend(exception(translator))).toBeNull();
+ });
+
+ test("keeps an error thrown through a native call in our code", () => {
+ const ours = {
+ type: "URIError",
+ value: "URI malformed",
+ stacktrace: { frames: [{ filename: "<anonymous>" }, { filename: "https://donkeycut.com/_next/static/chunks/a.js?dpl=1" }] },
+ };
+
+ expect(beforeSend(exception(ours))).not.toBeNull();
+ });
+
+ test("drops a bare dropped fetch", () => {
+ // The router logs its own failed RSC fetch, then navigates the browser.
+ const dropped = { type: "TypeError", value: "Failed to fetch" };
+
+ expect(beforeSend(exception(dropped))).toBeNull();
+ });
+
+ test("keeps a worded report whose cause is a dropped fetch", () => {
+ const report = { type: "Error", value: "[cut] export upload failed" };
+ const cause = { type: "TypeError", value: "Failed to fetch" };
+
+ expect(beforeSend(exception(report, cause))).not.toBeNull();
+ });
+
+ test("keeps an error our own code threw", () => {
+ const ours = {
+ type: "TypeError",
+ value: "Cannot read properties of undefined (reading 'clips')",
+ stacktrace: { frames: [{ filename: "https://donkeycut.com/_next/static/chunks/a.js" }] },
+ };
+
+ expect(beforeSend(exception(ours))).not.toBeNull();
+ });
+});
diff --git a/site/src/instrumentation-client.ts b/site/src/instrumentation-client.ts
index 36b7de67..78a4eb5b 100644
--- a/site/src/instrumentation-client.ts
+++ b/site/src/instrumentation-client.ts
@@ -1,5 +1,9 @@
import posthog from "posthog-js";
+import { fetchDropped } from "./cut/lib/network";
+import { bindFailureSink } from "./cut/lib/report";
+import { reloadOnChunkError } from "./lib/chunkReload";
+
// Surfaces that composite video onto a canvas every frame never record session
// replay (see app/_components/NoSessionReplay.tsx): the Cut app and the shared
// player, at their public paths and at the /cut/… routes the proxy serves them
@@ -43,6 +47,88 @@ const fromInjectedScript = (item: { stacktrace?: { frames?: { filename?: string
*/
const recoveredMediaRead = (item: { type?: string }) => item?.type === "MediaFetchError";
+// The message a browser substitutes for an error thrown by a script from
+// another origin loaded without CORS.
+const OPAQUE_SCRIPT_ERROR = "Script error.";
+
+/**
+ * Whether this exception is an error the browser hid from the page.
+ *
+ * Every script this page ships is same-origin, and posthog-js loads its own
+ * with crossorigin set, so their errors arrive with a message and a stack. A
+ * script with neither — "Script error.", no frames — comes from somewhere
+ * else, in practice a Safari extension's click listener, which fires one on
+ * every click of a session and names nothing we could fix.
+ */
+const opaqueScriptError = (item: { value?: string; stacktrace?: { frames?: unknown[] } }) =>
+ item?.value === OPAQUE_SCRIPT_ERROR && !item.stacktrace?.frames?.length;
+
+// Notices a browser raises when a ResizeObserver callback resizes what it
+// observes; the observers get the change on the next frame.
+const RESIZE_OBSERVER_NOTICES = new Set([
+ "ResizeObserver loop completed with undelivered notifications.",
+ "ResizeObserver loop limit exceeded",
+]);
+
+/** Whether this exception is the browser's ResizeObserver loop notice. */
+const browserNoise = (item: { value?: string }) =>
+ typeof item?.value === "string" && RESIZE_OBSERVER_NOTICES.has(item.value);
+
+// A frame in a script file: what this site ships is all .js files, from its
+// own chunks or posthog-js's asset host.
+const SCRIPT_FILE = /\.js(\?|#|$)/;
+
+/**
+ * Whether this exception was thrown by code evaluated into the page itself.
+ *
+ * Every script this page runs is a file, and the only inline scripts it
+ * serves are data. A stack whose located frames all name the document ("/",
+ * or the page's address) comes from code a browser feature or an extension
+ * put there: Chrome's translator on iOS, a crypto wallet's provider. Native
+ * frames ("[native code]", "<anonymous>") locate nothing either way.
+ */
+const fromDocumentScript = (item: { stacktrace?: { frames?: { filename?: string }[] } }) => {
+ const located = (item?.stacktrace?.frames ?? []).filter((f) => /^(\/|https?:)/.test(f?.filename ?? ""));
+ return located.length > 0 && located.every((f) => !SCRIPT_FILE.test(f.filename!));
+};
+
+// The language every page is served in, and the classes Chrome's and Edge's
+// translators put on <html> once they rewrite a page.
+const SERVED_LANG = "en";
+const TRANSLATED_CLASSES = ["translated-ltr", "translated-rtl"];
+
+// React's hydration mismatch errors (#418, #423, #425) and the DOM error a
+// commit throws when a node it moves is no longer where React left it.
+const RECONCILE_ERROR = /Minified React error #(418|423|425)\b|NotFoundError: Failed to execute '(insertBefore|removeChild)'/;
+
+/**
+ * Whether this exception is the browser's translator rewriting text React
+ * owns on a page that leaves translation on (the marketing pages). React
+ * recovers by rendering the page again, and the translator translates it
+ * again; the error names nothing in our render.
+ */
+const translatorArtifact = (item: { value?: string }) => {
+ const html = typeof document === "undefined" ? null : document.documentElement;
+ const translated =
+ !!html && (html.lang !== SERVED_LANG || TRANSLATED_CLASSES.some((c) => html.classList.contains(c)));
+ return translated && typeof item?.value === "string" && RECONCILE_ERROR.test(item.value);
+};
+
+/**
+ * Whether this exception is a fetch the network dropped, reported bare: the
+ * router logging its own failed page fetch before it navigates the browser
+ * there instead, or a library logging a read it retries. A failure that
+ * outlived its retries reaches here worded by report.ts, with the dropped
+ * fetch only as its cause.
+ */
+const droppedFetch = (item: { type?: string; value?: string }) =>
+ item?.type === "TypeError" && typeof item.value === "string" && fetchDropped(new TypeError(item.value));
+
+// A tab left open across a deploy recovers from the old build's missing chunks.
+if (process.env.NODE_ENV === "production") {
+ reloadOnChunkError(window);
+}
+
// 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") {
@@ -68,7 +154,17 @@ if (process.env.NEXT_PUBLIC_POSTHOG_KEY && process.env.NODE_ENV === "production"
if (Array.isArray(list)) {
// Only as the exception itself: a report worded around one (its
// cause, further down the list) is a failure that outlived retries.
- if (list.some(fromInjectedScript) || recoveredMediaRead(list[0])) return null;
+ if (
+ list.some(fromInjectedScript) ||
+ list.some(fromDocumentScript) ||
+ recoveredMediaRead(list[0]) ||
+ opaqueScriptError(list[0]) ||
+ browserNoise(list[0]) ||
+ translatorArtifact(list[0]) ||
+ droppedFetch(list[0])
+ ) {
+ return null;
+ }
for (const item of list) {
if (typeof item?.value === "string") item.value = scrubUrls(item.value);
}
@@ -77,4 +173,11 @@ if (process.env.NEXT_PUBLIC_POSTHOG_KEY && process.env.NODE_ENV === "production"
return event;
},
});
+
+ // Failures Cut carried on past go straight to error tracking under the key
+ // report.ts groups them by, and to the console for whoever has it open.
+ bindFailureSink((error, fingerprint) => {
+ console.warn(error);
+ posthog.captureException(error, { $exception_fingerprint: fingerprint });
+ });
}
diff --git a/site/src/lib/chunkReload.test.ts b/site/src/lib/chunkReload.test.ts
new file mode 100644
index 00000000..e56df099
--- /dev/null
+++ b/site/src/lib/chunkReload.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, test } from "bun:test";
+
+import { reloadOnChunkError } from "./chunkReload";
+
+type Listener = (e: unknown) => void;
+
+// A window with just what the recovery touches: listeners, reload, a clock and
+// session storage.
+const fakeWindow = (now = 1_000_000) => {
+ const listeners = new Map<string, Listener>();
+ const store = new Map<string, string>();
+ const win = {
+ reloads: 0,
+ now,
+ addEventListener(type: string, fn: (e: never) => void) {
+ listeners.set(type, fn as Listener);
+ },
+ location: { reload: () => (win.reloads += 1) },
+ sessionStorage: {
+ getItem: (k: string) => store.get(k) ?? null,
+ setItem: (k: string, v: string) => store.set(k, v),
+ },
+ fire: (type: string, e: unknown) => listeners.get(type)?.(e),
+ };
+ return win;
+};
+
+const chunkError = () => Object.assign(new Error("Failed to load chunk /_next/static/chunks/a.js"), { name: "ChunkLoadError" });
+
+describe("reloadOnChunkError", () => {
+ test("reloads when a lazy chunk fails to load", () => {
+ const win = fakeWindow();
+ reloadOnChunkError(win, () => win.now);
+
+ win.fire("unhandledrejection", { reason: chunkError() });
+
+ expect(win.reloads).toBe(1);
+ });
+
+ test("reloads on an uncaught chunk error too", () => {
+ const win = fakeWindow();
+ reloadOnChunkError(win, () => win.now);
+
+ win.fire("error", { error: chunkError() });
+
+ expect(win.reloads).toBe(1);
+ });
+
+ test("does not loop when the chunk fails again right after the reload", () => {
+ const win = fakeWindow();
+ reloadOnChunkError(win, () => win.now);
+ win.fire("error", { error: chunkError() });
+
+ win.now += 2_000;
+ win.fire("error", { error: chunkError() });
+
+ expect(win.reloads).toBe(1);
+ });
+
+ test("leaves every other error alone", () => {
+ const win = fakeWindow();
+ reloadOnChunkError(win, () => win.now);
+
+ win.fire("error", { error: new TypeError("x is undefined") });
+
+ expect(win.reloads).toBe(0);
+ });
+});
diff --git a/site/src/lib/chunkReload.ts b/site/src/lib/chunkReload.ts
new file mode 100644
index 00000000..2fa0c1b6
--- /dev/null
+++ b/site/src/lib/chunkReload.ts
@@ -0,0 +1,48 @@
+// The error name the bundler's runtime gives a lazy chunk that failed to load.
+const CHUNK_LOAD_ERROR = "ChunkLoadError";
+
+// Where the tab remembers its last recovery reload, and how long one counts:
+// a chunk that fails again inside the window is genuinely unreachable (the
+// network is down), and reloading again would loop.
+const RELOADED_AT_KEY = "donkey-chunk-reload-at";
+const RELOAD_WINDOW_MS = 30_000;
+
+interface ReloadWindow {
+ addEventListener(type: "error", fn: (e: ErrorEvent) => void): void;
+ addEventListener(type: "unhandledrejection", fn: (e: PromiseRejectionEvent) => void): void;
+ location: { reload(): void };
+ sessionStorage: { getItem(key: string): string | null; setItem(key: string, value: string): void };
+}
+
+/**
+ * Reload the page when a lazy chunk fails to load.
+ *
+ * A tab open across a deploy still asks for the old build's chunks, and once
+ * those are gone the import rejects and the tree it was loading dies. A
+ * reload fetches the current build, at most once per window; a tab whose
+ * storage throws keeps the failure.
+ */
+export function reloadOnChunkError(win: ReloadWindow, now: () => number = Date.now): void {
+ const recover = (error: unknown) => {
+ if ((error as { name?: string } | null)?.name !== CHUNK_LOAD_ERROR) {
+ return;
+ }
+
+ // Skip when this tab already reloaded for a chunk moments ago.
+ try {
+ const last = Number(win.sessionStorage.getItem(RELOADED_AT_KEY));
+ if (last && now() - last < RELOAD_WINDOW_MS) {
+ return;
+ }
+ win.sessionStorage.setItem(RELOADED_AT_KEY, String(now()));
+ } catch {
+ // Storage unavailable: no way to tell a first failure from a loop.
+ return;
+ }
+
+ win.location.reload();
+ };
+
+ win.addEventListener("error", (e) => recover(e.error));
+ win.addEventListener("unhandledrejection", (e) => recover(e.reason));
+}