Files
PaperClipAI/ui/src/lib/browser-error-context.test.ts
T
285db75d87 fix(ui): name the kind of value an uncaught browser error threw (#23346)
## 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>
2026-12-01 09:12:57 +00:00

219 lines
9.5 KiB
TypeScript

// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from "vitest";
import {
__resetPageDiagnostics,
buildBrowserErrorContext,
buildQueryErrorContext,
classifyThrownValue,
queryKindFor,
readPageLifecycle,
sanitizeComponentStack,
startPageDiagnostics,
takeRejectionEventSnapshot,
} from "./browser-error-context";
afterEach(() => {
__resetPageDiagnostics();
vi.restoreAllMocks();
vi.unstubAllGlobals();
document.documentElement.className = "";
});
describe("query error context", () => {
it("keeps only a static query key name", () => {
expect(queryKindFor(["issues", "company-uuid", "detail", "PAP-1"])).toBe("issues");
expect(queryKindFor(["agent-commentary", "company-uuid"])).toBe("agent-commentary");
expect(queryKindFor(["266ff1d0-6be9-47cb-b2ed-300fce5fbcd3"])).toBe("other");
expect(queryKindFor(["abcdefab-abcd-4bcd-abcd-abcdefabcdef"])).toBe("other");
expect(queryKindFor(["PAP-1"])).toBe("other");
expect(queryKindFor(["person@example.com"])).toBe("other");
expect(queryKindFor(["a".repeat(65)])).toBe("other");
expect(queryKindFor([{ companyId: "company-uuid" }])).toBe("other");
expect(queryKindFor([])).toBe("other");
});
it("fingerprints an HTTP failure by status and query name", () => {
const error = Object.assign(new Error("Internal server error"), { status: 500 });
expect(buildQueryErrorContext(error, ["issues", "company-uuid"])).toEqual({
tags: { query_kind: "issues", api_status: "500" },
fingerprint: ["api-error", "500", "issues"],
});
});
it("keeps default stack grouping for an error without an HTTP status", () => {
expect(buildQueryErrorContext(new TypeError("x is undefined"), ["issues"])).toEqual({
tags: { query_kind: "issues" },
});
});
});
describe("browser error context", () => {
it("keeps React component names without locations or unrecognized content", () => {
const stack = `
at TaskDetail (https://tenant.example/assets/app.js?token=private-value:42:7)
at div (<anonymous>)
in AppShell (created by Router)
TaskPanel@https://tenant.example/tasks/private-task:12:3
at ErrorBoundary (/workspace/private/src/Boundary.tsx:15:9)
at https://tenant.example/private-page:17:3
unrecognized private content`;
expect(sanitizeComponentStack(stack)).toBe(
"\n at TaskDetail\n at div\n at AppShell\n at TaskPanel\n at ErrorBoundary",
);
});
it("bounds malformed and oversized component stacks", () => {
expect(sanitizeComponentStack(` at ${"a".repeat(101)} (private)`)).toBeUndefined();
expect(sanitizeComponentStack("x".repeat(16_384) + "\n at SecretSuffix")).toBeUndefined();
expect(sanitizeComponentStack("\n at TaskDetail (private)".repeat(100))?.match(/at TaskDetail/g)).toHaveLength(40);
});
it.each([undefined, null, "", "private unrecognized data"])("omits absent or unrecognized stacks: %s", (stack) => {
expect(sanitizeComponentStack(stack)).toBeUndefined();
});
it.each(["translated-ltr", "translated-rtl"])("records only a translation-marker boolean for %s", (marker) => {
document.documentElement.className = `${marker} private-customer-class`;
const result = buildBrowserErrorContext({ boundary: "route", componentStack: "\n at TaskDetail" });
expect(result).toMatchObject({
tags: { react_error_boundary: "route" },
contexts: { react: { componentStack: "\n at TaskDetail" }, browser_state: { translation_marker: true } },
});
expect(JSON.stringify(result)).not.toContain("private-customer-class");
});
it("captures a snapshot rather than reading changed DOM state later", () => {
vi.spyOn(document, "visibilityState", "get").mockReturnValue("hidden");
vi.spyOn(document, "readyState", "get").mockReturnValue("interactive");
const result = buildBrowserErrorContext({ boundary: "app" });
document.documentElement.classList.add("translated-ltr");
expect(result.contexts.browser_state).toEqual({
ready_state: "interactive", visibility_state: "hidden", translation_marker: false, automation: false,
});
});
it("keeps the component trace when browser-state reads throw", () => {
vi.spyOn(document, "readyState", "get").mockImplementation(() => { throw new Error("unavailable"); });
vi.spyOn(document.documentElement, "classList", "get").mockImplementation(() => { throw new Error("unavailable"); });
expect(buildBrowserErrorContext({ boundary: "app", componentStack: "\n at TaskDetail" })).toEqual({
tags: { react_error_boundary: "app" },
contexts: {
react: { componentStack: "\n at TaskDetail" },
browser_state: { visibility_state: document.visibilityState, automation: false },
page_lifecycle: expect.objectContaining({ pagehide_seen: false }),
},
});
});
function withWebdriver(get: () => unknown, run: () => void) {
Object.defineProperty(navigator, "webdriver", { configurable: true, get });
try {
run();
} finally {
delete (navigator as unknown as Record<string, unknown>).webdriver;
}
}
it("records whether a WebDriver session controls the browser", () => {
withWebdriver(() => true, () => {
expect(buildBrowserErrorContext({ boundary: "app" }).contexts.browser_state).toHaveProperty("automation", true);
});
});
it("keeps other browser state when the automation flag cannot be read", () => {
withWebdriver(() => { throw new Error("unavailable"); }, () => {
const state = buildBrowserErrorContext({ boundary: "app" }).contexts.browser_state;
expect(state).not.toHaveProperty("automation");
expect(state).toHaveProperty("translation_marker", false);
});
});
it("classifies a thrown value by its kind and whether its stack has frames", () => {
const withStack = (stack: string) => Object.assign(new Error("failure"), { stack });
expect(classifyThrownValue("844g8")).toBe("string");
expect(classifyThrownValue(null)).toBe("null");
expect(classifyThrownValue(undefined)).toBe("undefined");
expect(classifyThrownValue(withStack("Error: failure\n at handler (https://tenant.example/a.js:1:2)"))).toBe("error");
expect(classifyThrownValue(withStack("handler@https://tenant.example/a.js:1:2"))).toBe("error");
expect(classifyThrownValue(withStack("global code@https://tenant.example/a.js:3:4\n"))).toBe("error");
expect(classifyThrownValue(withStack("Error: failure"))).toBe("error_stackless");
expect(classifyThrownValue(withStack("Error: failed at 12:34:56"))).toBe("error_stackless");
expect(classifyThrownValue(withStack(""))).toBe("error_stackless");
});
it("does not require a browser document", () => {
vi.stubGlobal("document", undefined);
expect(buildBrowserErrorContext({ boundary: "app" }).contexts.browser_state).toEqual({});
});
});
/** A dispatched (untrusted) rejection event; jsdom has no PromiseRejectionEvent. */
function dispatchRejection(reason: unknown, promise?: unknown) {
const event = new Event("unhandledrejection");
Object.defineProperty(event, "reason", { value: reason });
Object.defineProperty(event, "promise", { value: promise });
window.dispatchEvent(event);
}
describe("page diagnostics", () => {
startPageDiagnostics();
function setNow(ms: number) {
vi.spyOn(performance, "now").mockReturnValue(ms);
}
it("records only the latest lifecycle transition with coarse timing", () => {
setNow(5_000);
expect(readPageLifecycle()).toEqual({ since_load: "1-10s", pagehide_seen: false });
vi.spyOn(document, "visibilityState", "get").mockReturnValue("hidden");
document.dispatchEvent(new Event("visibilitychange"));
setNow(65_000);
expect(readPageLifecycle()).toEqual({
since_load: "1-10m", pagehide_seen: false, last_transition: "hidden", since_transition: "1-10m",
});
document.dispatchEvent(new Event("freeze"));
document.dispatchEvent(new Event("resume"));
setNow(65_500);
expect(readPageLifecycle()).toMatchObject({ last_transition: "resume", since_transition: "<1s" });
});
it("keeps a pagehide marker until the page is shown again", () => {
setNow(1_000_000);
window.dispatchEvent(new Event("pagehide"));
expect(readPageLifecycle()).toEqual({
since_load: ">10m", pagehide_seen: true, last_transition: "pagehide", since_transition: "<1s",
});
window.dispatchEvent(new Event("pageshow"));
expect(readPageLifecycle()).toMatchObject({ pagehide_seen: false, last_transition: "pageshow" });
});
it.each([
["native", Promise.resolve()],
["subclass", new (class Custom<T> extends Promise<T> {})(() => {})],
["other", { then() {} }],
["missing", undefined],
])("classifies a %s rejection promise without reading the reason", (kind, promise) => {
setNow(100);
const reason = { get secret() { throw new Error("must not be read"); } };
dispatchRejection(reason, promise);
expect(takeRejectionEventSnapshot("object")).toEqual({ trusted: false, promise: kind });
});
it("pairs a snapshot once, with the same rejection kind, inside the pairing window", () => {
setNow(100);
dispatchRejection(undefined, Promise.resolve());
expect(takeRejectionEventSnapshot("undefined")).toEqual({ trusted: false, promise: "native" });
expect(takeRejectionEventSnapshot("undefined")).toBeUndefined();
dispatchRejection(undefined, Promise.resolve());
expect(takeRejectionEventSnapshot("string")).toBeUndefined();
dispatchRejection(undefined, Promise.resolve());
setNow(5_101);
expect(takeRejectionEventSnapshot("undefined")).toBeUndefined();
});
});