diff --git a/ui/src/lib/plugin-module-origins.test.ts b/ui/src/lib/plugin-module-origins.test.ts new file mode 100644 index 00000000000..fff3e9be1dd --- /dev/null +++ b/ui/src/lib/plugin-module-origins.test.ts @@ -0,0 +1,52 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { + __resetPluginModuleOrigins, + readPluginModuleOrigin, + rememberPluginModuleUrl, +} from "./plugin-module-origins"; + +const hostFrame = { filename: "/assets/index.js", abs_path: "https://app.example/assets/index.js" }; + +afterEach(() => __resetPluginModuleOrigins()); + +describe("readPluginModuleOrigin", () => { + it("names the plugin of the innermost blob frame", () => { + rememberPluginModuleUrl("blob:https://app.example/outer", "acme.outer"); + rememberPluginModuleUrl("blob:https://app.example/inner", "acme.inner"); + expect(readPluginModuleOrigin([{ + stacktrace: { frames: [ + { filename: "blob:https://app.example/outer" }, + hostFrame, + { abs_path: "blob:https://app.example/inner", filename: "blob:https://app.example/inner" }, + ] }, + }])).toBe("acme.inner"); + }); + + it("reports an unrecorded blob module as unmapped", () => { + expect(readPluginModuleOrigin([{ + stacktrace: { frames: [hostFrame, { filename: "blob:https://app.example/unknown" }] }, + }])).toBe("unmapped"); + }); + + it("adds nothing when no frame ran from a blob module", () => { + rememberPluginModuleUrl("blob:https://app.example/module", "acme.plugin"); + expect(readPluginModuleOrigin([{ stacktrace: { frames: [hostFrame] } }])).toBeUndefined(); + expect(readPluginModuleOrigin([{}])).toBeUndefined(); + expect(readPluginModuleOrigin(undefined)).toBeUndefined(); + }); + + it("keeps only the most recent modules", () => { + for (let index = 0; index <= 100; index += 1) { + rememberPluginModuleUrl(`blob:https://app.example/${index}`, `acme.plugin-${index}`); + } + const frameFor = (index: number) => [{ stacktrace: { frames: [{ filename: `blob:https://app.example/${index}` }] } }]; + expect(readPluginModuleOrigin(frameFor(0))).toBe("unmapped"); + expect(readPluginModuleOrigin(frameFor(100))).toBe("acme.plugin-100"); + }); + + it("bounds the tag to Sentry's value length", () => { + rememberPluginModuleUrl("blob:https://app.example/long", "a".repeat(300)); + expect(readPluginModuleOrigin([{ stacktrace: { frames: [{ filename: "blob:https://app.example/long" }] } }])) + .toHaveLength(200); + }); +}); diff --git a/ui/src/lib/plugin-module-origins.ts b/ui/src/lib/plugin-module-origins.ts new file mode 100644 index 00000000000..fbbf7516bb6 --- /dev/null +++ b/ui/src/lib/plugin-module-origins.ts @@ -0,0 +1,71 @@ +// Attribute a browser error to the plugin UI module that raised it. +// +// The host imports each plugin's UI module from a `blob:` URL (see +// `importPluginModule` in `plugins/slots.tsx`). A stack frame from that +// module names only the random blob URL, so a Sentry event cannot tell which +// plugin threw, or which plugin aborted a request during an unmount. +// +// The loader records each blob URL with its plugin key here. Sentry's +// `beforeSend` reads the innermost blob frame of an event back and tags the +// event with that plugin key. Blob URLs stay in this module and are never sent. + +/** At most this many recent plugin module URLs are remembered. */ +const MAX_REMEMBERED_MODULES = 100; +/** Sentry tag values are limited to 200 characters. */ +const MAX_TAG_LENGTH = 200; + +const pluginKeysByModuleUrl = new Map(); + +/** Record that `url` holds the UI module of plugin `pluginKey`. Never throws. */ +export function rememberPluginModuleUrl(url: string, pluginKey: string): void { + try { + pluginKeysByModuleUrl.delete(url); + pluginKeysByModuleUrl.set(url, pluginKey); + while (pluginKeysByModuleUrl.size > MAX_REMEMBERED_MODULES) { + const oldest = pluginKeysByModuleUrl.keys().next().value; + if (oldest === undefined) break; + pluginKeysByModuleUrl.delete(oldest); + } + } catch { /* diagnostic unavailable */ } +} + +interface StackFrameLike { + filename?: string; + abs_path?: string; +} + +interface ExceptionLike { + stacktrace?: { frames?: readonly StackFrameLike[] }; +} + +/** + * The plugin key of the innermost frame that ran from a `blob:` module, or + * `unmapped` when that blob module is not a recorded plugin module. + * `undefined` when no frame ran from a blob module. Sentry lists frames from + * outermost to innermost. + */ +export function readPluginModuleOrigin( + exceptions: readonly ExceptionLike[] | undefined, +): string | undefined { + try { + if (!exceptions) return undefined; + for (const exception of exceptions) { + const frames = exception.stacktrace?.frames ?? []; + for (let index = frames.length - 1; index >= 0; index -= 1) { + const frame = frames[index]; + const url = [frame.abs_path, frame.filename].find( + (value): value is string => typeof value === "string" && value.startsWith("blob:"), + ); + if (!url) continue; + const pluginKey = pluginKeysByModuleUrl.get(url); + return pluginKey ? pluginKey.slice(0, MAX_TAG_LENGTH) : "unmapped"; + } + } + } catch { /* diagnostic unavailable */ } + return undefined; +} + +/** Test-only: forget every recorded module URL. */ +export function __resetPluginModuleOrigins(): void { + pluginKeysByModuleUrl.clear(); +} diff --git a/ui/src/lib/sentry.test.ts b/ui/src/lib/sentry.test.ts index 105f62c5704..6adfbec318b 100644 --- a/ui/src/lib/sentry.test.ts +++ b/ui/src/lib/sentry.test.ts @@ -542,6 +542,32 @@ describe("buildBrowserSentryInitOptions", () => { expect(buildBrowserSentryInitOptions(DSN).ignoreErrors).toEqual(["__firefox__"]); }); + it("names the plugin whose blob module raised an error, without its URL", async () => { + const { buildBrowserSentryInitOptions } = await importFreshSentry(); + const origins = await import("./plugin-module-origins"); + const blobUrl = "blob:https://tenant.example/0b5f1f4e-module"; + origins.rememberPluginModuleUrl(blobUrl, "acme.dashboard"); + const beforeSend = buildBrowserSentryInitOptions(DSN).beforeSend!; + const eventFor = (filename: string) => ({ + exception: { values: [{ + type: "AbortError", + mechanism: { type: "auto.browser.global_handlers.onunhandledrejection", handled: false }, + stacktrace: { frames: [{ filename: "/assets/index.js" }, { filename, abs_path: filename }] }, + }] }, + }); + const reason = new DOMException("signal is aborted without reason", "AbortError"); + + const plugin = await beforeSend(eventFor(blobUrl) as never, { originalException: reason }); + expect(plugin?.tags).toMatchObject({ browser_plugin_module: "acme.dashboard" }); + expect(JSON.stringify(plugin?.tags)).not.toContain("blob:"); + + const unmapped = await beforeSend(eventFor("blob:https://tenant.example/other") as never, { originalException: reason }); + expect(unmapped?.tags).toMatchObject({ browser_plugin_module: "unmapped" }); + + const host = await beforeSend(eventFor("/assets/other.js") as never, { originalException: reason }); + expect(host?.tags).not.toHaveProperty("browser_plugin_module"); + }); + it("adds diagnostics without a transaction filter", async () => { const { buildBrowserSentryInitOptions } = await importFreshSentry(); diff --git a/ui/src/lib/sentry.ts b/ui/src/lib/sentry.ts index 4570d8eb577..7b62bb9188f 100644 --- a/ui/src/lib/sentry.ts +++ b/ui/src/lib/sentry.ts @@ -43,6 +43,9 @@ // starts monitoring, `fetch-rejection-origin.ts` wraps `fetch` itself and // tags an unhandled rejection with an enum for who started the request. It // sends no URL, path, or stack text. +// +// Plugin UI modules run from random `blob:` URLs. `plugin-module-origins.ts` +// maps such a frame back to its plugin key and tags the event with it. import { buildBrowserErrorContext, @@ -60,6 +63,7 @@ import { startFetchRejectionDiagnostics, } from "./fetch-rejection-origin"; import { isIntentionalAbortReason } from "./intentional-abort"; +import { readPluginModuleOrigin } from "./plugin-module-origins"; let queue: Promise = Promise.resolve(); @@ -263,6 +267,10 @@ export function buildBrowserSentryInitOptions( ...event.tags, browser_build_mode: import.meta.env.DEV ? "development" : "production", }; + // A plugin UI module runs from a random `blob:` URL. Name the plugin + // whose module holds the innermost such frame, never the URL. + const pluginModule = readPluginModuleOrigin(event.exception?.values); + if (pluginModule) event.tags.browser_plugin_module = pluginModule; if (isUnhandledRejection) { // The SDK supplies the rejected value directly. Classify without // reading object properties, coercing strings, or copying its value. diff --git a/ui/src/plugins/slots-loading.test.tsx b/ui/src/plugins/slots-loading.test.tsx index 6fa401f1830..bfdf25b8017 100644 --- a/ui/src/plugins/slots-loading.test.tsx +++ b/ui/src/plugins/slots-loading.test.tsx @@ -67,3 +67,21 @@ it("does not load agent tabs that have not opted into task side panels", async ( expect(container.textContent).toBe("0"); expect(fetch).not.toHaveBeenCalled(); }); + +it("records each plugin module's blob URL with its plugin key for error attribution", async () => { + const { readPluginModuleOrigin, __resetPluginModuleOrigins } = await import("@/lib/plugin-module-origins"); + __resetPluginModuleOrigins(); + vi.stubGlobal("fetch", vi.fn(async () => new Response("export const Switcher = () => null;"))); + vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:http://localhost/plugin-module"); + vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {}); + vi.spyOn(console, "error").mockImplementation(() => {}); + try { + // jsdom cannot import the blob URL; the loader logs that failure and settles. + await ensurePluginContributionLoaded(contribution); + expect(readPluginModuleOrigin([ + { stacktrace: { frames: [{ filename: "blob:http://localhost/plugin-module" }] } }, + ])).toBe("fixture.navigation"); + } finally { + __resetPluginModuleOrigins(); + } +}); diff --git a/ui/src/plugins/slots.tsx b/ui/src/plugins/slots.tsx index 6f0752b35ef..cb0aade0705 100644 --- a/ui/src/plugins/slots.tsx +++ b/ui/src/plugins/slots.tsx @@ -43,6 +43,7 @@ import { authApi } from "@/api/auth"; import { describeError, isTransientError } from "@/api/errors"; import { queryViewKind } from "@/components/QueryView"; import { queryKeys } from "@/lib/queryKeys"; +import { rememberPluginModuleUrl } from "@/lib/plugin-module-origins"; import { cn } from "@/lib/utils"; import { PluginBridgeContext, @@ -425,9 +426,10 @@ function rewriteBareSpecifiers(source: string): string { * Fetch, rewrite, and import a plugin UI module. * * @param url - The URL to the plugin's UI entry module + * @param pluginKey - The plugin's key, recorded for error attribution * @returns The module's exports */ -async function importPluginModule(url: string): Promise> { +async function importPluginModule(url: string, pluginKey: string): Promise> { // Check if the bridge registry is available. If not, fall back to direct // import (which will fail on bare specifiers but won't crash the loader). if (!globalThis.__paperclipPluginBridge__) { @@ -449,6 +451,9 @@ async function importPluginModule(url: string): Promise> // Create a blob URL from the rewritten source and import it const blob = new Blob([rewritten], { type: "application/javascript" }); const blobUrl = URL.createObjectURL(blob); + // Stack frames from this module name only the blob URL. Keep its plugin + // key so an error report from the module can say which plugin raised it. + rememberPluginModuleUrl(blobUrl, pluginKey); try { const mod = await import(/* @vite-ignore */ blobUrl); @@ -508,7 +513,7 @@ async function loadPluginModule(contribution: PluginUiContribution): Promise = await importPluginModule(url); + const mod: Record = await importPluginModule(url, pluginKey); // Collect the set of export names declared across all UI contributions so // we only register what the manifest advertises (ignore extra exports).