mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 09:39:53 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The board UI is a React app, and the browser error monitor reports render failures from its route error boundary > - Some people read the board with browser page translation (Chrome or Google Translate) turned on > - Translation replaces React-owned text nodes, or moves them into `<font>` wrappers. React does not support this (facebook/react#11538) > - The next React commit that removes such a node, or inserts before it, gets `NotFoundError` from `removeChild` or `insertBefore`. The route error boundary then replaces the page > - Three production error reports show this exact shape. Each has the existing `translation_marker: true` diagnostic, so the cause is confirmed and not a guess > - This pull request adds a narrow DOM guard that does what React asked for only on a translated page > - The benefit is that translated pages stay usable, and real DOM errors still reach the error monitor ## Linked Issues or Issue Description Refs facebook/react#11538 **What happened?** A person used the board with browser page translation turned on (locale `es-419`). After the page changed, the route error boundary showed an error. The error monitor recorded `NotFoundError: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.` A second report from the same kind of session recorded the `insertBefore` form of the same error. **Steps to reproduce** 1. Open a board page that updates its text, for example a task whose status changes. 2. Use the browser to translate the page into another language. 3. Let the page update so that React removes or moves a translated text node. 4. The route error boundary replaces the page. **Expected behavior** The page keeps working while it is translated. **Environment** Hosted board, production build, Chrome page translation active (`translated-ltr` class on `<html>`). ## What Changed - Add `ui/src/lib/translation-dom-guard.ts`. It wraps `Node.prototype.removeChild` and `Node.prototype.insertBefore`. The wrapper acts only when both conditions are true: the page has the translation marker class, and the node is detached or is still inside the parent. In that case it removes the node from its real parent, or inserts before the translation wrapper. A `MutationObserver` records which `<font>` replaced each detached text node. For a `replaceChild`, that is the added `<font>`. For an insert followed by a remove, it is the `<font>` inserted next to that text node. The guard uses it only if it is still next to the removed text, so it never takes a neighbor's translation. When React removes a detached text node, the guard also removes that translated replacement, so the old text does not stay on the page. When React inserts before a detached node, the guard inserts before its replacement, or appends if there is none. All other calls go to the native method without change. - Install the guard in `ui/src/main.tsx` before the first render. Only the first call installs it, and its stop function restores the native methods. - Move the translation-marker check in `browser-error-context.ts` into an exported `hasPageTranslationMarker()` helper. The guard and the error diagnostic now read the same signal. The diagnostic output does not change. - Add `translation-dom-guard.test.tsx`. It renders real React in jsdom and does what translation does to a text node. This includes a replace in one step, an insert followed by a remove, and two adjacent text nodes translated right to left and left to right. ## Verification - Red: with a no-op guard, the new tests fail with the same `NotFoundError` that production recorded. Against the first version of this guard, the three replacement tests fail (the translated text stayed on the page). Against the second version, the right-to-left two-node test fails (the neighbor's translation was deleted). - Green: `cd ui && npx vitest run src/lib/translation-dom-guard.test.tsx src/lib/browser-error-context.test.ts src/lib/sentry.test.ts src/lib/sentry-package-version.test.ts` passes (4 files, 66 tests). - The tests also prove that the native errors stay on a page that is not translated, and for a node outside the parent on a translated page. - `tsc --noEmit -p ui/tsconfig.json` shows no errors in the changed files. The local run had only the UI dependencies installed, so unrelated packages that were not built (plugin SDK, runner protocol) showed errors that were already there. Required CI does the full typecheck, test, and build. - I did not run a real Chrome translation session. The jsdom test makes the same DOM change that translation makes. ## Risks - The guard changes two global DOM methods. Untranslated pages pay one extra property comparison per call. The translation check runs only when the parent does not match. - The `MutationObserver` watches child-list changes on the whole document. Its callback only checks records that remove one text node, and it keeps replacements in a `WeakMap`, so detached nodes can still be garbage collected. - On a translated page, a real bug that removes a detached node, or that inserts before a node inside a nested element, is no longer reported. This is limited to translated pages, which already showed this crash. - If translation detaches a node without a `<font>` replacement that the observer saw, removal leaves the page as it is, and an insert goes at the end of the parent. The page does not crash. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), with tool use and code execution in an agent workspace. ## 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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
227 lines
8.3 KiB
TypeScript
227 lines
8.3 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 {
|
|
browserState.translation_marker = readPageTranslationMarker();
|
|
} catch { /* diagnostic unavailable */ }
|
|
}
|
|
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;
|
|
}
|
|
|
|
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(),
|
|
},
|
|
};
|
|
}
|