mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-16 11:59:26 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The browser app can report errors to Sentry. A final query error goes to Sentry when it is not an outage, a denial, or a missing item. > - Every failed API request throws an `ApiError` from the same frames in `api/client.ts`. > - Sentry groups errors by stack. Thus all unrelated server failures go into one issue, titled "ApiError: Internal server error". > - The report has no route, no query name, and no status. Breadcrumbs and URLs are removed for privacy. A person cannot find which endpoint failed. > - This pull request tags each failed-query report with its HTTP status and the static name of its query key. It also sets the Sentry fingerprint from these two values. > - The benefit: each failing endpoint gets its own Sentry issue, and a person can connect it to the server error. ## Linked Issues or Issue Description **What happened?** One browser Sentry issue collected unrelated server 500 errors from different pages and environments. The events had no route or query name. A person could not connect an event to a server error. **Steps to reproduce** 1. Turn on browser error monitoring with a Sentry DSN. 2. Make two different queries fail with a 500 response, for example the issues list and the agents list. 3. Look at Sentry. Both events are in one issue with the title "ApiError: Internal server error". Neither event shows which query failed. **Expected behavior** Each failing query has its own Sentry issue. The event shows the HTTP status and the static query name. It shows no IDs, refs, or filters. **Environment** The hosted browser app, staging and production builds. I searched open pull requests for duplicates. I found no pull request that changes browser query-error grouping. ## What Changed - `ui/src/lib/browser-error-context.ts`: add `queryKindFor`. It keeps only the first query-key part, and only when it is a lowercase word list such as `issues` or `agent-commentary`. Other values become `other`, so an ID, a ref, an email, or a typed value is never sent. - `ui/src/lib/browser-error-context.ts`: add `buildQueryErrorContext`. For an error with an HTTP status, it sets the `query_kind` and `api_status` tags and the fingerprint `["api-error", status, queryKind]`. For an error without a status, it sets only the `query_kind` tag and keeps default stack grouping. - `ui/src/lib/sentry.ts`: add `captureQueryException`. It uses the same serialized queue as `captureBrowserException`. Both functions now share one private capture step. - `ui/src/lib/query-client.ts`: `reportError` now also receives the query key. - `ui/src/main.tsx`: the query client reports through `captureQueryException`. - Tests for key sanitizing, the fingerprint, the reporter argument, and the gate call. ## Verification - Red before the fix: the 6 new assertions fail on the old source (`queryKindFor`, `buildQueryErrorContext` and `captureQueryException` do not exist, and `reportError` gets no key). - Green after the fix: `cd ui && npx vitest run src/lib/sentry.test.ts src/lib/browser-error-context.test.ts src/lib/query-client.test.ts` passes 3 files and 78 tests. - The privacy test makes sure that `company-uuid` and `PAP-1` from later key parts do not go into the Sentry call. It also makes sure that UUID, ref, email, and long heads become `other`. - `ui` typecheck: no errors in the changed files. The local install was filtered to the UI package, so unrelated packages (`plugin-sdk` build output, runner dependencies) could not resolve. Required CI supplies the full typecheck. - I did not run browser e2e suites. This change does not touch them. ## Risks - Low risk. Only the grouping and tags of browser query-error reports change. The app does not change what it shows to users. - Sentry opens new issues for future query errors, one for each status and query name. The old catch-all issue gets no new events. - A query key with a dynamic first part becomes `other`. Those errors still group together, but they keep the status tag. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), in Claude Code with tool use, repository inspection, and shell code 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: Claude Opus 5.5 <noreply@anthropic.com>
215 lines
8.1 KiB
TypeScript
215 lines
8.1 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;
|
|
} = {};
|
|
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 {
|
|
const classes = document.documentElement.classList;
|
|
browserState.translation_marker = classes.contains("translated-ltr") || classes.contains("translated-rtl");
|
|
} catch { /* diagnostic unavailable */ }
|
|
}
|
|
return browserState;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
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(),
|
|
},
|
|
};
|
|
}
|