mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-02 10:44:52 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The board UI reports uncaught browser errors to Sentry when a deployment sets a DSN > - A React event handler that throws a string reaches Sentry through `window.onerror` with no stack of its own > - The event then shows only one frame: React's event dispatch (`processDispatchQueue`). It does not show the handler that threw the value, or the kind of the value > - Breadcrumbs and the user agent are not sent by design, so we cannot tell a scripted browser session from a person > - This pull request adds two bounded facts to these reports. It does not copy the thrown value > - The benefit is that the next occurrence tells us if a string or a stackless `Error` was thrown, and if a WebDriver-controlled browser threw it ## Linked Issues or Issue Description **What happened?** One browser event on a hosted Paperclip page reported `Error: 844g8`. The mechanism was `auto.browser.global_handlers.onerror` (unhandled). The only stack frame was React's event dispatch in the main bundle, at the `catch` that reports a listener's throw. The event had no breadcrumbs and no user agent. The source location was a cloud data center region. **Expected behavior** A report that lets a maintainer find what threw the value, or at least identify the class of the throw. **Steps to reproduce** 1. Enable browser Sentry monitoring. 2. Throw a string (for example `throw "844g8"`) from a React event handler, or call `window.onerror` with a string `error` argument. 3. Look at the Sentry event. It shows `Error: 844g8` with one synthetic frame at the reported location, and there is no other attribution. **Paperclip version or commit** The event came from release `506211b9176058ae06622b2bc1150d4bb2ea2e19` (hosted production bundle). This change is based on current `master`. No duplicate or related open pull request touches this path. I searched for the error text, for `onerror`, and for non-`Error` throws. ## What Changed - `ui/src/lib/browser-error-context.ts`: Add `classifyThrownValue()`. It returns `error`, `error_stackless`, or the primitive type. It checks only if an `Error` stack has frames. It does not coerce or copy the value. - `ui/src/lib/browser-error-context.ts`: Add `browser_state.automation` from `navigator.webdriver === true`. A failed read leaves out the field and keeps the other state. - `ui/src/lib/sentry.ts`: In `beforeSend`, tag `window.onerror` reports with `browser_thrown_kind`. Rejections and caught exceptions do not get this tag. - `doc/observability.md`: Document the new tag and field. - Tests use the real `@sentry/browser` SDK for the onerror path, and unit tests for the browser state. ## Verification - `cd ui && npx vitest run src/lib/sentry.test.ts src/lib/browser-error-context.test.ts`: 68 passed. - Red/green: with the source change removed, the two new `sentry.test.ts` tests fail (`browser_thrown_kind` is `undefined`, and `browser_state.automation` is missing). With the change, they pass. - The new real-SDK test throws the string `844g8` through `window.onerror`. The SDK produces the same shape as the production event: exception value `844g8`, mechanism `auto.browser.global_handlers.onerror`. The event now also has `browser_thrown_kind: string`. - `cd ui && node ../scripts/run-tsc.mjs -b`: pass. - `pnpm verify` exited 2 (broader verification required, from global CI inputs). Required CI supplies that coverage. ## Risks - Low risk. The change adds one tag and one boolean to browser Sentry events. It does not drop, group, or suppress any event. - Every read is in a `try` block, so a failed read cannot replace or discard the original error. - `navigator.webdriver` is a standard boolean. It does not identify a person or a tenant. - This is a diagnostic. It does not fix a defect. The root cause needs a future event with these facts. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use and shell execution. ## 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>
258 lines
9.0 KiB
TypeScript
258 lines
9.0 KiB
TypeScript
import { errorStatus } from "@/api/errors";
|
|
|
|
export interface BrowserErrorDetails {
|
|
boundary: "app" | "route";
|
|
componentStack?: string | null;
|
|
}
|
|
|
|
const MAX_STACK_LENGTH = 16_384;
|
|
const MAX_COMPONENT_FRAMES = 40;
|
|
|
|
/** Keep component names only: React stack locations can contain tenant URLs. */
|
|
export function sanitizeComponentStack(stack: string | null | undefined): string | undefined {
|
|
if (!stack) return undefined;
|
|
const frames: string[] = [];
|
|
for (const line of stack.slice(0, MAX_STACK_LENGTH).split("\n").slice(0, MAX_COMPONENT_FRAMES + 1)) {
|
|
// V8/React and Firefox/Safari component-frame formats. Never retain the
|
|
// location, arguments, or an unrecognized line as a fallback.
|
|
const name = /^\s*(?:at|in) ([A-Za-z_$][\w$.-]{0,99})(?:\s|$)/.exec(line)?.[1]
|
|
?? /^([A-Za-z_$][\w$.-]{0,99})@/.exec(line)?.[1];
|
|
if (name) frames.push(` at ${name}`);
|
|
if (frames.length === MAX_COMPONENT_FRAMES) break;
|
|
}
|
|
return frames.length ? `\n${frames.join("\n")}` : undefined;
|
|
}
|
|
|
|
/** Bounded document state; never read page content, locations, or identifiers. */
|
|
export function readBrowserErrorState() {
|
|
const browserState: {
|
|
ready_state?: "loading" | "interactive" | "complete";
|
|
visibility_state?: "visible" | "hidden";
|
|
translation_marker?: boolean;
|
|
automation?: boolean;
|
|
} = {};
|
|
if (typeof document !== "undefined") {
|
|
// Each read is optional. A DOM wrapper or extension must not prevent the
|
|
// original exception and component trace from reaching the error monitor.
|
|
try {
|
|
const state = document.readyState;
|
|
if (state === "loading" || state === "interactive" || state === "complete") {
|
|
browserState.ready_state = state;
|
|
}
|
|
} catch { /* diagnostic unavailable */ }
|
|
try {
|
|
const state = document.visibilityState;
|
|
if (state === "visible" || state === "hidden") browserState.visibility_state = state;
|
|
} catch { /* diagnostic unavailable */ }
|
|
try {
|
|
browserState.translation_marker = readPageTranslationMarker();
|
|
} catch { /* diagnostic unavailable */ }
|
|
try {
|
|
browserState.automation = navigator.webdriver === true;
|
|
} catch {}
|
|
}
|
|
return browserState;
|
|
}
|
|
|
|
function readPageTranslationMarker(): boolean {
|
|
const classes = document.documentElement.classList;
|
|
return classes.contains("translated-ltr") || classes.contains("translated-rtl");
|
|
}
|
|
|
|
export function hasPageTranslationMarker(): boolean {
|
|
try {
|
|
return typeof document !== "undefined" && readPageTranslationMarker();
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
type PageTransition = "visible" | "hidden" | "pagehide" | "pageshow" | "freeze" | "resume";
|
|
type ElapsedBucket = "<1s" | "1-10s" | "10-60s" | "1-10m" | ">10m";
|
|
type RejectionPromiseKind = "native" | "subclass" | "other" | "missing";
|
|
|
|
interface RejectionEventSnapshot {
|
|
at: number;
|
|
/** Same classification as the `browser_rejection_kind` tag, used to pair the event. */
|
|
kind: string;
|
|
trusted: boolean;
|
|
promise: RejectionPromiseKind;
|
|
}
|
|
|
|
/** A rejection report is paired with its DOM event only within this window. */
|
|
const REJECTION_PAIRING_WINDOW_MS = 5_000;
|
|
|
|
let lastTransition: { kind: PageTransition; at: number } | undefined;
|
|
let pagehideSeen = false;
|
|
let lastRejection: RejectionEventSnapshot | undefined;
|
|
let pageDiagnosticsStarted = false;
|
|
|
|
function now() {
|
|
return typeof performance !== "undefined" ? performance.now() : Date.now();
|
|
}
|
|
|
|
function bucketElapsed(ms: number): ElapsedBucket {
|
|
if (ms < 1_000) return "<1s";
|
|
if (ms < 10_000) return "1-10s";
|
|
if (ms < 60_000) return "10-60s";
|
|
if (ms < 600_000) return "1-10m";
|
|
return ">10m";
|
|
}
|
|
|
|
/** Classify without reading the rejected value or calling into the promise. */
|
|
export function classifyRejectionReason(reason: unknown) {
|
|
return reason === null ? "null" : typeof reason;
|
|
}
|
|
|
|
export type ThrownValueKind =
|
|
| "error"
|
|
| "error_stackless"
|
|
| "string"
|
|
| "number"
|
|
| "boolean"
|
|
| "bigint"
|
|
| "symbol"
|
|
| "undefined"
|
|
| "null"
|
|
| "object"
|
|
| "function";
|
|
|
|
const STACK_FRAME_LINE = /^\s+at \S|^[^@\n]*@\S+:\d+:\d+\r?$/m;
|
|
|
|
export function classifyThrownValue(value: unknown): ThrownValueKind {
|
|
try {
|
|
if (value instanceof Error) {
|
|
const stack: unknown = value.stack;
|
|
return typeof stack === "string" && STACK_FRAME_LINE.test(stack) ? "error" : "error_stackless";
|
|
}
|
|
} catch {
|
|
return "object";
|
|
}
|
|
return value === null ? "null" : typeof value;
|
|
}
|
|
|
|
function classifyRejectionPromise(event: PromiseRejectionEvent): RejectionPromiseKind {
|
|
try {
|
|
const promise: unknown = event.promise;
|
|
if (typeof promise !== "object" || promise === null) return "missing";
|
|
if (Object.getPrototypeOf(promise) === Promise.prototype) return "native";
|
|
return promise instanceof Promise ? "subclass" : "other";
|
|
} catch {
|
|
return "other";
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Record page lifecycle transitions and the shape of each unhandled rejection
|
|
* event. Only enum values and timestamps stay in memory; nothing is sent from
|
|
* here. Idempotent, and kept for the page lifetime so a later sign-in still
|
|
* registers before the error monitor's own rejection handler.
|
|
*/
|
|
export function startPageDiagnostics(target: Window = window, doc: Document = document): void {
|
|
if (pageDiagnosticsStarted) return;
|
|
pageDiagnosticsStarted = true;
|
|
const mark = (kind: PageTransition) => {
|
|
lastTransition = { kind, at: now() };
|
|
if (kind === "pagehide") pagehideSeen = true;
|
|
if (kind === "pageshow") pagehideSeen = false;
|
|
};
|
|
try {
|
|
doc.addEventListener("visibilitychange", () => {
|
|
try {
|
|
mark(doc.visibilityState === "hidden" ? "hidden" : "visible");
|
|
} catch { /* diagnostic unavailable */ }
|
|
});
|
|
doc.addEventListener("freeze", () => mark("freeze"));
|
|
doc.addEventListener("resume", () => mark("resume"));
|
|
target.addEventListener("pagehide", () => mark("pagehide"));
|
|
target.addEventListener("pageshow", () => mark("pageshow"));
|
|
// Capture phase, registered before the SDK assigns `onunhandledrejection`,
|
|
// so this snapshot exists before the SDK builds and filters its event.
|
|
target.addEventListener("unhandledrejection", (event) => {
|
|
try {
|
|
lastRejection = {
|
|
at: now(),
|
|
kind: classifyRejectionReason(event.reason),
|
|
trusted: event.isTrusted,
|
|
promise: classifyRejectionPromise(event),
|
|
};
|
|
} catch { /* diagnostic unavailable */ }
|
|
}, { capture: true });
|
|
} catch { /* diagnostic unavailable */ }
|
|
}
|
|
|
|
/** Coarse lifecycle timing; no page content, locations, or identifiers. */
|
|
export function readPageLifecycle() {
|
|
const at = now();
|
|
const lifecycle: {
|
|
since_load: ElapsedBucket;
|
|
pagehide_seen: boolean;
|
|
last_transition?: PageTransition;
|
|
since_transition?: ElapsedBucket;
|
|
} = { since_load: bucketElapsed(at), pagehide_seen: pagehideSeen };
|
|
if (lastTransition) {
|
|
lifecycle.last_transition = lastTransition.kind;
|
|
lifecycle.since_transition = bucketElapsed(at - lastTransition.at);
|
|
}
|
|
return lifecycle;
|
|
}
|
|
|
|
/** Consume the snapshot of the DOM event that produced this rejection report. */
|
|
export function takeRejectionEventSnapshot(kind: string) {
|
|
const snapshot = lastRejection;
|
|
lastRejection = undefined;
|
|
if (!snapshot || snapshot.kind !== kind || now() - snapshot.at > REJECTION_PAIRING_WINDOW_MS) return undefined;
|
|
return { trusted: snapshot.trusted, promise: snapshot.promise };
|
|
}
|
|
|
|
/** Test-only: forget recorded lifecycle state. Listeners stay attached. */
|
|
export function __resetPageDiagnostics() {
|
|
lastTransition = undefined;
|
|
pagehideSeen = false;
|
|
lastRejection = undefined;
|
|
}
|
|
|
|
const QUERY_KIND_PATTERN = /^[a-z]+(?:[-_][a-z]+)*$/;
|
|
const MAX_QUERY_KIND_LENGTH = 64;
|
|
|
|
/**
|
|
* The query key's static name, such as `issues`. Later key parts hold
|
|
* companies, refs and filters, and are never read. A head with a digit,
|
|
* uppercase letter or other character can be an ID or a typed value, so it
|
|
* becomes `other`.
|
|
*/
|
|
export function queryKindFor(queryKey: readonly unknown[]): string {
|
|
const head = queryKey[0];
|
|
return typeof head === "string" && head.length <= MAX_QUERY_KIND_LENGTH && QUERY_KIND_PATTERN.test(head)
|
|
? head
|
|
: "other";
|
|
}
|
|
|
|
/**
|
|
* Every failed request throws from the same `ApiError` frames, so default
|
|
* grouping puts all of them in one Sentry issue. Group an HTTP failure by its
|
|
* status and query name instead, so each failing endpoint has its own issue.
|
|
*/
|
|
export function buildQueryErrorContext(error: unknown, queryKey: readonly unknown[]) {
|
|
const queryKind = queryKindFor(queryKey);
|
|
const status = errorStatus(error);
|
|
if (status === null) return { tags: { query_kind: queryKind } };
|
|
return {
|
|
tags: { query_kind: queryKind, api_status: String(status) },
|
|
fingerprint: ["api-error", String(status), queryKind],
|
|
};
|
|
}
|
|
|
|
/** A bounded snapshot, taken at the error rather than when the capture queue runs. */
|
|
export function buildBrowserErrorContext(details: BrowserErrorDetails) {
|
|
const componentStack = sanitizeComponentStack(details.componentStack);
|
|
return {
|
|
tags: { react_error_boundary: details.boundary },
|
|
contexts: {
|
|
react: componentStack ? { componentStack } : {},
|
|
browser_state: readBrowserErrorState(),
|
|
page_lifecycle: readPageLifecycle(),
|
|
},
|
|
};
|
|
}
|