mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-02 18:58:33 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The browser UI sends unhandled errors to Sentry through `ui/src/lib/sentry.ts` > - Browser extensions run their own scripts in the page. The Sentry SDK wraps their event listeners, so an extension error is reported as a Paperclip error > - The Jam bug-capture extension listens for the Navigation API `navigate` event. When its recorded network events become too large, its listener throws `RangeError: Invalid string length` from `JSON.stringify` > - No Paperclip code is at fault. These reports are noise and hide real errors > - This pull request drops errors that extension code threw, with the built-in Sentry `denyUrls` option > - The benefit is fewer false error reports. Errors that Paperclip code throws are still sent, also when an extension frame is lower on the stack ## Linked Issues or Issue Description **What happened?** Hosted staging browser Sentry recorded one unhandled `RangeError: Invalid string length`. A Paperclip link click called React Router's `History.pushState`. The browser then fired the Navigation API `navigate` event. The Sentry `BrowserApiErrors` wrapper caught the error from a listener that the Jam extension added. The top frames are `JSON.stringify (<anonymous>)`, then `re.addMany`, `t2.persistEphemeral` and `t2.beforeNavigation` in `webpack://jam-extension/injected-scripts/host-network-events.js`. A second Sentry group with the same title and the same trace is already ignored by hand. **Steps to reproduce** 1. Install the Jam bug-capture extension and let it record network events on a Paperclip page for a long time. 2. Click a Paperclip link that navigates in the app. 3. See `RangeError: Invalid string length` in the browser Sentry project. **Expected behavior** Sentry does not record errors that a browser extension's own script throws. **Actual behavior** Sentry records them as unhandled Paperclip errors. Related: #22378 (the same kind of filter for Firefox for iOS injected scripts). No duplicate PR was found (searched for `denyUrls`, `jam-extension`, and "browser extension sentry"). ## What Changed - `ui/src/lib/sentry.ts`: add the exported `BROWSER_EXTENSION_SCRIPT_URLS` list and pass it to `Sentry.init` as `denyUrls`. The list holds the `chrome-`, `moz-`, `safari-`, `safari-web-` and `ms-browser-extension://` URL schemes and Jam's `webpack://jam-extension/` script URL. A comment tells why. - `ui/src/lib/sentry.test.ts`: add a test with the real Sentry SDK. It sends the reported Jam stack and a `chrome-extension://` stack, and makes sure that Sentry drops them. It also sends an app error with a Jam frame lower on the stack and a plain app error, and makes sure that Sentry keeps them. Add an options test for which URLs are denied and which are not. - `doc/observability.md`: describe the filter next to the `__firefox__` note. ## Verification - `cd ui && pnpm exec vitest run src/lib/sentry.test.ts src/lib/browser-error-context.test.ts`: 66 passed. - Without the `ui/src/lib/sentry.ts` change (tests kept), the 2 new tests fail. With the change, all 45 tests in `sentry.test.ts` pass. - `@sentry/core` 10.71.0 `eventFilters` reads the innermost frame whose file name is not `<anonymous>` or `[native code]`. For the reported event, that is the Jam script URL. - `cd ui && pnpm exec tsc --noEmit -p .`: no errors in the changed files. The local tree has only errors from an unbuilt plugin SDK and missing generated Storybook files. CI covers the full typecheck. ## Risks - Low risk. The filter matches only the frame that threw. An extension that throws from its own script while it runs Paperclip code would also be dropped, but such an error is not a Paperclip bug. - A Paperclip error is not dropped when an extension frame is lower on the stack. A test covers this. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
323 lines
14 KiB
TypeScript
323 lines
14 KiB
TypeScript
// Optional Sentry error monitoring for the browser.
|
|
//
|
|
// Activated only when the signed-in session carries a Sentry DSN. `SentryGate`
|
|
// reads the DSN off `GET /api/auth/get-session` and calls
|
|
// `initBrowserErrorMonitoring` once. A signed-out browser, or a browser with
|
|
// no DSN, calls this module never — see `SentryGate.tsx`.
|
|
//
|
|
// Sign-out must stop monitoring, not just stop starting it: `SentryGate`
|
|
// calls `teardownBrowserErrorMonitoring` when the session's DSN goes away.
|
|
// The function detaches the client from the current scope first
|
|
// (`Sentry.getCurrentScope().setClient(undefined)`), then closes that same
|
|
// client (`client.close()`), so a signed-out page's global handlers find no
|
|
// attached client at any point. Detach runs first because a client stays
|
|
// attached, and stays enabled, for the whole close call — closing first
|
|
// would leave the signed-out page able to send one more event to Sentry for
|
|
// as long as the close call takes. Both calls are built-in Sentry client
|
|
// calls — no custom filter code.
|
|
//
|
|
// `initBrowserErrorMonitoring`, `teardownBrowserErrorMonitoring`,
|
|
// `captureBrowserException`, and `captureQueryException` each queue their
|
|
// work on one shared promise chain (`enqueue`) instead of running at once.
|
|
// One operation runs at a time, in call order, so no operation can ever
|
|
// observe another one part-finished — a sign-out always closes the client a
|
|
// sign-in already finished starting, never one still starting.
|
|
//
|
|
// `@sentry/browser` loads through a dynamic import, so Vite puts it in a
|
|
// separate chunk that a browser with no DSN never fetches.
|
|
//
|
|
// Default-integration privacy note: two default integrations copy values
|
|
// this app does not want inside a Sentry event, so the initializer removes
|
|
// them with a built-in Sentry option — no custom filter code:
|
|
// - `Breadcrumbs` turns a console call, a click, and a fetch call into a
|
|
// breadcrumb with the raw arguments and the raw request URL.
|
|
// - `HttpContext` copies the page URL, the query string, and the referrer
|
|
// onto every event.
|
|
// The initializer keeps every other default integration, so the browser
|
|
// still captures `window.onerror` and `window.onunhandledrejection`
|
|
// (`GlobalHandlers`), the two React error boundaries, deduplicates a repeat
|
|
// event (`Dedupe`), and links a caused-by chain (`LinkedErrors`).
|
|
//
|
|
// Without `Breadcrumbs`, nothing in the SDK wraps `fetch`, so a browser's
|
|
// stackless `TypeError: Failed to fetch` arrives with no caller. Once a DSN
|
|
// 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,
|
|
buildQueryErrorContext,
|
|
classifyRejectionReason,
|
|
classifyThrownValue,
|
|
readBrowserErrorState,
|
|
readPageLifecycle,
|
|
startPageDiagnostics,
|
|
takeRejectionEventSnapshot,
|
|
type BrowserErrorDetails,
|
|
} from "./browser-error-context";
|
|
import {
|
|
readFetchInitiator,
|
|
readFetchWrapperState,
|
|
startFetchRejectionDiagnostics,
|
|
} from "./fetch-rejection-origin";
|
|
import { isIntentionalAbortReason } from "./intentional-abort";
|
|
import { readPluginModuleOrigin } from "./plugin-module-origins";
|
|
|
|
let queue: Promise<void> = Promise.resolve();
|
|
|
|
/** Run gate operations one at a time, in call order. */
|
|
function enqueue(op: () => Promise<void>): Promise<void> {
|
|
const next = queue.then(op);
|
|
queue = next.catch(() => {});
|
|
return next;
|
|
}
|
|
|
|
/** The `@sentry/browser` module shape, resolved once. */
|
|
type SentryBrowserModule = typeof import("@sentry/browser");
|
|
|
|
/**
|
|
* The `Sentry.init` options this gate builds. `Sentry.init`'s parameter is
|
|
* optional, so `Parameters<...>[0]` alone carries an `| undefined` arm this
|
|
* gate never returns. `NonNullable` removes only that arm — the object shape
|
|
* underneath stays the true `@sentry/browser` option type.
|
|
*/
|
|
type BrowserSentryInitOptions = NonNullable<Parameters<SentryBrowserModule["init"]>[0]>;
|
|
|
|
let sentry: SentryBrowserModule | null = null;
|
|
|
|
/**
|
|
* Load `@sentry/browser` and start the client with the given DSN. Idempotent
|
|
* — the session query can refetch and call this again, and a second call is
|
|
* a no-op because a client is already started.
|
|
*/
|
|
export function initBrowserErrorMonitoring(dsn: string, environment?: string | null): Promise<void> {
|
|
return enqueue(async () => {
|
|
if (sentry) return;
|
|
try {
|
|
const Sentry = await import("@sentry/browser");
|
|
// Before init: the rejection snapshot listener must precede the SDK's
|
|
// `onunhandledrejection` handler. Diagnostics never block monitoring.
|
|
try {
|
|
startPageDiagnostics();
|
|
} catch { /* diagnostic unavailable */ }
|
|
try {
|
|
startFetchRejectionDiagnostics();
|
|
} catch { /* diagnostic unavailable */ }
|
|
Sentry.init(buildBrowserSentryInitOptions(dsn, environment));
|
|
sentry = Sentry;
|
|
} catch (err) {
|
|
// The dynamic import or the init call failed. Fall through with a
|
|
// single diagnostic. The gate fails open — the app keeps running
|
|
// without error monitoring rather than crashing on an opt-in feature.
|
|
// eslint-disable-next-line no-console
|
|
console.error("[paperclip] Sentry browser bootstrap failed", err);
|
|
}
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Stop browser error monitoring and forget the started client. Call this on
|
|
* sign-out, so the browser sends Sentry no more events and no more
|
|
* breadcrumbs after the session ends. A no-op when monitoring never started.
|
|
*
|
|
* Detaches the client from the current scope, then closes that same client.
|
|
* A client stays attached, and stays enabled, for the whole close call — a
|
|
* signed-out page's `window.onerror` or `window.onunhandledrejection`
|
|
* handler would still reach it for as long as the close call takes.
|
|
* Detaching first removes that window instead of leaving it open.
|
|
*/
|
|
export function teardownBrowserErrorMonitoring(): Promise<void> {
|
|
return enqueue(async () => {
|
|
const Sentry = sentry;
|
|
sentry = null;
|
|
if (!Sentry) return;
|
|
// Read the client before detaching it. The scope holds no client after
|
|
// detach, so the close step below needs this reference to flush and
|
|
// close the right client.
|
|
const client = Sentry.getClient();
|
|
// Detach first, close second — the opposite order from a plain
|
|
// `Sentry.close()` call, which reads the client off the current scope
|
|
// and would find nothing to close if detach ran first. A separate
|
|
// guarded try keeps this step unable to reject, unlike a bare finally
|
|
// block: a thrown error here would still reach the caller, and
|
|
// `SentryGate.tsx` discards this function's returned promise with a
|
|
// bare `void` call, so a rejection would surface as an unhandled
|
|
// promise rejection in the browser.
|
|
try {
|
|
Sentry.getCurrentScope().setClient(undefined);
|
|
} catch (err) {
|
|
// eslint-disable-next-line no-console
|
|
console.error("[paperclip] Sentry client detach failed", err);
|
|
}
|
|
// A second, separate guarded try, for the same reason as the one
|
|
// above: this step must never reject the returned promise.
|
|
try {
|
|
// Awaiting matters: the client flushes buffered events to Sentry
|
|
// during close; a caller that does not wait may navigate away, or
|
|
// the page may unload, before the flush finishes.
|
|
await client?.close(2_000);
|
|
} catch (err) {
|
|
// eslint-disable-next-line no-console
|
|
console.error("[paperclip] Sentry teardownBrowserErrorMonitoring failed", err);
|
|
}
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Report an error to Sentry. Never throws — observability must not change
|
|
* control flow. A no-op before the gate opens, when the gate never opens (no
|
|
* DSN on the session), or when bootstrap failed.
|
|
*/
|
|
export function captureBrowserException(error: unknown, details?: BrowserErrorDetails): void {
|
|
let context: ReturnType<typeof buildBrowserErrorContext> | undefined;
|
|
try {
|
|
if (details) context = buildBrowserErrorContext(details);
|
|
} catch {
|
|
// Diagnostics must never replace the original exception or its recovery UI.
|
|
}
|
|
enqueueCapture(error, context);
|
|
}
|
|
|
|
/**
|
|
* Report a failed query, grouped by its HTTP status and the static name of
|
|
* its query key. Never throws, and is a no-op until the gate opens.
|
|
*/
|
|
export function captureQueryException(error: unknown, queryKey: readonly unknown[]): void {
|
|
let context: ReturnType<typeof buildQueryErrorContext> | undefined;
|
|
try {
|
|
context = buildQueryErrorContext(error, queryKey);
|
|
} catch {
|
|
// Diagnostics must never replace the original exception.
|
|
}
|
|
enqueueCapture(error, context);
|
|
}
|
|
|
|
function enqueueCapture(
|
|
error: unknown,
|
|
context: ReturnType<typeof buildBrowserErrorContext> | ReturnType<typeof buildQueryErrorContext> | undefined,
|
|
): void {
|
|
void enqueue(async () => {
|
|
try {
|
|
if (context) sentry?.captureException(error, context);
|
|
else sentry?.captureException(error);
|
|
} catch (err) {
|
|
// eslint-disable-next-line no-console
|
|
console.error("[paperclip] Sentry captureException failed", err);
|
|
}
|
|
});
|
|
}
|
|
|
|
export const BROWSER_EXTENSION_SCRIPT_URLS: readonly RegExp[] = [
|
|
/^(?:chrome|moz|safari|safari-web|ms-browser)-extension:\/\//i,
|
|
/^webpack:\/\/jam-extension\//,
|
|
];
|
|
|
|
const POSTHOG_REQUEST_TIMEOUT_MESSAGE = /^PostHog request timed out(?: after \d+ms)?$/;
|
|
|
|
export function isPostHogRequestTimeout(reason: unknown): boolean {
|
|
try {
|
|
return reason instanceof Error
|
|
&& reason.name === "AbortError"
|
|
&& POSTHOG_REQUEST_TIMEOUT_MESSAGE.test(reason.message);
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function isGlobalOnError(event: { exception?: { values?: Array<{ mechanism?: { type?: string } }> } }) {
|
|
return event.exception?.values?.some((value) =>
|
|
value.mechanism?.type === "onerror"
|
|
|| value.mechanism?.type === "auto.browser.global_handlers.onerror",
|
|
) ?? false;
|
|
}
|
|
|
|
/**
|
|
* Build the `Sentry.init` options object. A pure function, split out from
|
|
* `initBrowserErrorMonitoring` so a test can call it with the real
|
|
* `@sentry/browser` module and assert the resolved integration list and the
|
|
* captured-event shape against the true SDK, not a stand-in.
|
|
*/
|
|
export function buildBrowserSentryInitOptions(
|
|
dsn: string,
|
|
environment?: string | null,
|
|
): BrowserSentryInitOptions {
|
|
return {
|
|
dsn,
|
|
environment: environment ?? undefined,
|
|
// Use the loaded bundle's build, even when the server has since deployed.
|
|
release:
|
|
typeof __PAPERCLIP_BUILD_COMMIT__ === "string"
|
|
? __PAPERCLIP_BUILD_COMMIT__
|
|
: undefined,
|
|
tracesSampleRate: 0,
|
|
sendDefaultPii: false,
|
|
ignoreErrors: ["__firefox__"],
|
|
denyUrls: [...BROWSER_EXTENSION_SCRIPT_URLS],
|
|
beforeSend: (event, hint) => {
|
|
const isUnhandledRejection = event.exception?.values?.some((value) =>
|
|
value.mechanism?.type === "onunhandledrejection"
|
|
|| value.mechanism?.type === "auto.browser.global_handlers.onunhandledrejection",
|
|
) ?? false;
|
|
if (
|
|
isUnhandledRejection
|
|
&& (isIntentionalAbortReason(hint.originalException) || isPostHogRequestTimeout(hint.originalException))
|
|
) {
|
|
takeRejectionEventSnapshot(classifyRejectionReason(hint.originalException));
|
|
return null;
|
|
}
|
|
// Global handlers do not pass through our React boundaries. Give their
|
|
// reports the same bounded document state, without URLs or breadcrumbs.
|
|
// Preserve a boundary's earlier snapshot across the asynchronous queue.
|
|
try {
|
|
event.contexts = {
|
|
...event.contexts,
|
|
browser_state: event.contexts?.browser_state ?? readBrowserErrorState(),
|
|
page_lifecycle: event.contexts?.page_lifecycle ?? readPageLifecycle(),
|
|
};
|
|
event.tags = {
|
|
...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 (isGlobalOnError(event)) {
|
|
event.tags.browser_thrown_kind = classifyThrownValue(hint.originalException);
|
|
}
|
|
if (isUnhandledRejection) {
|
|
// The SDK supplies the rejected value directly. Classify without
|
|
// reading object properties, coercing strings, or copying its value.
|
|
const kind = classifyRejectionReason(hint.originalException);
|
|
event.tags.browser_rejection_kind = kind;
|
|
if (kind === "object") {
|
|
// A stackless network error carries no caller. Record who started
|
|
// the request, as an enum, and whether another script wraps fetch.
|
|
event.tags.browser_fetch_initiator = readFetchInitiator(hint.originalException);
|
|
const wrapper = readFetchWrapperState();
|
|
if (wrapper) event.tags.browser_fetch_wrapper = wrapper;
|
|
}
|
|
// Whether the browser or a script dispatched the event, and which
|
|
// promise implementation carried it. Without a stack these are the
|
|
// remaining attribution facts for an `undefined` rejection.
|
|
const rejection = takeRejectionEventSnapshot(kind);
|
|
if (rejection) {
|
|
event.tags.browser_rejection_event = rejection.trusted ? "trusted" : "synthetic";
|
|
event.contexts.rejection_event = rejection;
|
|
}
|
|
}
|
|
} catch {
|
|
// Diagnostics must not replace or discard the original error.
|
|
}
|
|
return event;
|
|
},
|
|
integrations: (defaults) =>
|
|
defaults.filter(
|
|
(integration) => integration.name !== "HttpContext" && integration.name !== "Breadcrumbs",
|
|
),
|
|
};
|
|
}
|