mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-22 11:54:35 +01:00
fix(ui): keep translated pages from crashing on React DOM updates (#22463)
## 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>
This commit is contained in:
4 files changed
+324
-2
No files matched your search
@@ -44,13 +44,25 @@ export function readBrowserErrorState() {
|
||||
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");
|
||||
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";
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { startTranslationDomGuard } from "./translation-dom-guard";
|
||||
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
|
||||
|
||||
function translateTextNode(textNode: Text, translated: string) {
|
||||
document.documentElement.classList.add("translated-ltr");
|
||||
const font = document.createElement("font");
|
||||
font.appendChild(document.createTextNode(translated));
|
||||
textNode.parentNode!.replaceChild(font, textNode);
|
||||
return font;
|
||||
}
|
||||
|
||||
function translateTextNodeInTwoSteps(textNode: Text, translated: string) {
|
||||
document.documentElement.classList.add("translated-ltr");
|
||||
const font = document.createElement("font");
|
||||
font.appendChild(document.createTextNode(translated));
|
||||
textNode.parentNode!.insertBefore(font, textNode);
|
||||
textNode.parentNode!.removeChild(textNode);
|
||||
return font;
|
||||
}
|
||||
|
||||
function wrapTextNode(textNode: Text) {
|
||||
document.documentElement.classList.add("translated-ltr");
|
||||
const font = document.createElement("font");
|
||||
textNode.parentNode!.replaceChild(font, textNode);
|
||||
font.appendChild(textNode);
|
||||
return font;
|
||||
}
|
||||
|
||||
function expectNotFound(action: () => unknown) {
|
||||
expect(action).toThrow(expect.objectContaining({ name: "NotFoundError" }));
|
||||
}
|
||||
|
||||
function firstTextNode(element: Element): Text {
|
||||
for (const node of Array.from(element.childNodes)) {
|
||||
if (node.nodeType === Node.TEXT_NODE) return node as Text;
|
||||
}
|
||||
throw new Error("no text node");
|
||||
}
|
||||
|
||||
function Status({ done }: { done: boolean }) {
|
||||
return <p>{done ? null : "Running"}<b>end</b></p>;
|
||||
}
|
||||
|
||||
function Pair({ showLeft }: { showLeft: boolean }) {
|
||||
return <p>{showLeft ? "Left" : null}{"Right"}</p>;
|
||||
}
|
||||
|
||||
function textNodes(element: Element): Text[] {
|
||||
return Array.from(element.childNodes).filter((node): node is Text => node.nodeType === Node.TEXT_NODE);
|
||||
}
|
||||
|
||||
function Toggle({ show }: { show: boolean }) {
|
||||
return <p>{show ? <i>new</i> : null}{"Running"}</p>;
|
||||
}
|
||||
|
||||
describe("startTranslationDomGuard", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
let stop: (() => void) | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
stop?.();
|
||||
stop = undefined;
|
||||
document.documentElement.classList.remove("translated-ltr", "translated-rtl");
|
||||
});
|
||||
|
||||
it("reproduces the translated-page removeChild crash without the guard", () => {
|
||||
act(() => root.render(<Status done={false} />));
|
||||
translateTextNode(firstTextNode(container.querySelector("p")!), "En curso");
|
||||
expect(() => act(() => root.render(<Status done />))).toThrow(/not a child of this node/);
|
||||
});
|
||||
|
||||
it("removes the translated replacement when React removes a detached text node", () => {
|
||||
stop = startTranslationDomGuard();
|
||||
act(() => root.render(<Status done={false} />));
|
||||
const font = translateTextNode(firstTextNode(container.querySelector("p")!), "En curso");
|
||||
expect(() => act(() => root.render(<Status done />))).not.toThrow();
|
||||
expect(font.isConnected).toBe(false);
|
||||
expect(container.textContent).toBe("end");
|
||||
act(() => root.render(<Status done={false} />));
|
||||
expect(container.textContent).toBe("Runningend");
|
||||
});
|
||||
|
||||
it("removes a replacement that translation inserted and detached in separate steps", () => {
|
||||
stop = startTranslationDomGuard();
|
||||
act(() => root.render(<Status done={false} />));
|
||||
const font = translateTextNodeInTwoSteps(firstTextNode(container.querySelector("p")!), "En curso");
|
||||
act(() => root.render(<Status done />));
|
||||
expect(font.isConnected).toBe(false);
|
||||
expect(container.textContent).toBe("end");
|
||||
});
|
||||
|
||||
it("keeps a neighbor's translation when adjacent text nodes are translated right to left", () => {
|
||||
stop = startTranslationDomGuard();
|
||||
act(() => root.render(<Pair showLeft />));
|
||||
const [left, right] = textNodes(container.querySelector("p")!);
|
||||
const rightFont = translateTextNodeInTwoSteps(right, "Derecha");
|
||||
const leftFont = translateTextNodeInTwoSteps(left, "Izquierda");
|
||||
act(() => root.render(<Pair showLeft={false} />));
|
||||
expect(leftFont.isConnected).toBe(false);
|
||||
expect(rightFont.isConnected).toBe(true);
|
||||
expect(container.textContent).toBe("Derecha");
|
||||
});
|
||||
|
||||
it("keeps a neighbor's translation when adjacent text nodes are translated left to right", () => {
|
||||
stop = startTranslationDomGuard();
|
||||
act(() => root.render(<Pair showLeft />));
|
||||
const [left, right] = textNodes(container.querySelector("p")!);
|
||||
const leftFont = translateTextNodeInTwoSteps(left, "Izquierda");
|
||||
const rightFont = translateTextNodeInTwoSteps(right, "Derecha");
|
||||
act(() => root.render(<Pair showLeft={false} />));
|
||||
expect(leftFont.isConnected).toBe(false);
|
||||
expect(rightFont.isConnected).toBe(true);
|
||||
expect(container.textContent).toBe("Derecha");
|
||||
});
|
||||
|
||||
it("removes a text node that translation moved into its wrapper", () => {
|
||||
stop = startTranslationDomGuard();
|
||||
act(() => root.render(<Status done={false} />));
|
||||
const font = wrapTextNode(firstTextNode(container.querySelector("p")!));
|
||||
act(() => root.render(<Status done />));
|
||||
expect(font.textContent).toBe("");
|
||||
expect(container.textContent).toBe("end");
|
||||
});
|
||||
|
||||
it("inserts before a reference node that translation moved into its wrapper", () => {
|
||||
stop = startTranslationDomGuard();
|
||||
act(() => root.render(<Toggle show={false} />));
|
||||
const paragraph = container.querySelector("p")!;
|
||||
const font = wrapTextNode(firstTextNode(paragraph));
|
||||
act(() => root.render(<Toggle show />));
|
||||
expect(paragraph.firstChild).toBe(container.querySelector("i"));
|
||||
expect(paragraph.lastChild).toBe(font);
|
||||
});
|
||||
|
||||
it("inserts before the translated replacement of a detached reference node", () => {
|
||||
stop = startTranslationDomGuard();
|
||||
act(() => root.render(<Toggle show={false} />));
|
||||
const paragraph = container.querySelector("p")!;
|
||||
const font = translateTextNode(firstTextNode(paragraph), "En curso");
|
||||
expect(() => act(() => root.render(<Toggle show />))).not.toThrow();
|
||||
expect(paragraph.firstChild).toBe(container.querySelector("i"));
|
||||
expect(paragraph.lastChild).toBe(font);
|
||||
});
|
||||
|
||||
it("appends when a detached reference node has no translated replacement", () => {
|
||||
stop = startTranslationDomGuard();
|
||||
document.documentElement.classList.add("translated-ltr");
|
||||
const parent = document.createElement("div");
|
||||
parent.appendChild(document.createElement("span"));
|
||||
const detached = document.createTextNode("gone");
|
||||
const added = document.createElement("i");
|
||||
expect(parent.insertBefore(added, detached)).toBe(added);
|
||||
expect(parent.lastChild).toBe(added);
|
||||
});
|
||||
|
||||
it("keeps the native errors when the page is not translated", () => {
|
||||
stop = startTranslationDomGuard();
|
||||
const parent = document.createElement("div");
|
||||
const stray = document.createElement("span");
|
||||
expectNotFound(() => parent.removeChild(stray));
|
||||
expectNotFound(() => parent.insertBefore(document.createElement("i"), stray));
|
||||
});
|
||||
|
||||
it("keeps the native errors for nodes outside the parent on a translated page", () => {
|
||||
stop = startTranslationDomGuard();
|
||||
document.documentElement.classList.add("translated-rtl");
|
||||
const parent = document.createElement("div");
|
||||
const elsewhere = document.createElement("section");
|
||||
const stray = elsewhere.appendChild(document.createElement("span"));
|
||||
expectNotFound(() => parent.removeChild(stray));
|
||||
expectNotFound(() => parent.insertBefore(document.createElement("i"), stray));
|
||||
expect(stray.parentNode).toBe(elsewhere);
|
||||
});
|
||||
|
||||
it("installs once and restores the native methods when stopped", () => {
|
||||
const nativeRemove = Node.prototype.removeChild;
|
||||
const nativeInsert = Node.prototype.insertBefore;
|
||||
const first = startTranslationDomGuard();
|
||||
const second = startTranslationDomGuard();
|
||||
const guardedRemove = Node.prototype.removeChild;
|
||||
expect(guardedRemove).not.toBe(nativeRemove);
|
||||
second();
|
||||
expect(Node.prototype.removeChild).toBe(guardedRemove);
|
||||
first();
|
||||
expect(Node.prototype.removeChild).toBe(nativeRemove);
|
||||
expect(Node.prototype.insertBefore).toBe(nativeInsert);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import { hasPageTranslationMarker } from "./browser-error-context";
|
||||
|
||||
interface GuardedMethods {
|
||||
removeChild: Node["removeChild"];
|
||||
insertBefore: Node["insertBefore"];
|
||||
}
|
||||
|
||||
let installed: GuardedMethods | undefined;
|
||||
|
||||
function childOfParentContaining(parent: Node, node: Node): Node | null {
|
||||
let current: Node | null = node;
|
||||
while (current && current.parentNode !== parent) current = current.parentNode;
|
||||
return current;
|
||||
}
|
||||
|
||||
function isTranslationWrapper(node: Node | null | undefined): node is Element {
|
||||
return !!node && node.nodeType === Node.ELEMENT_NODE && (node as Element).localName === "font";
|
||||
}
|
||||
|
||||
interface ReplacementTracker {
|
||||
inserted: WeakMap<Node, Element>;
|
||||
replacements: WeakMap<Node, Element>;
|
||||
}
|
||||
|
||||
function isTextNode(node: Node | null | undefined): node is Text {
|
||||
return !!node && node.nodeType === Node.TEXT_NODE;
|
||||
}
|
||||
|
||||
function recordReplacements(records: MutationRecord[], tracker: ReplacementTracker) {
|
||||
for (const record of records) {
|
||||
if (record.type !== "childList") continue;
|
||||
const added = record.addedNodes.length === 1 ? record.addedNodes[0] : null;
|
||||
const wrapper = isTranslationWrapper(added) ? added : null;
|
||||
if (record.removedNodes.length === 0) {
|
||||
if (!wrapper) continue;
|
||||
if (isTextNode(record.previousSibling)) tracker.inserted.set(record.previousSibling, wrapper);
|
||||
if (isTextNode(record.nextSibling)) tracker.inserted.set(record.nextSibling, wrapper);
|
||||
continue;
|
||||
}
|
||||
if (record.removedNodes.length !== 1) continue;
|
||||
const removed = record.removedNodes[0];
|
||||
if (!isTextNode(removed)) continue;
|
||||
if (wrapper) {
|
||||
tracker.replacements.set(removed, wrapper);
|
||||
continue;
|
||||
}
|
||||
if (record.addedNodes.length > 0) continue;
|
||||
const insertedWrapper = tracker.inserted.get(removed);
|
||||
if (insertedWrapper && (record.previousSibling === insertedWrapper || record.nextSibling === insertedWrapper)) {
|
||||
tracker.replacements.set(removed, insertedWrapper);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function startTranslationDomGuard(): () => void {
|
||||
if (installed || typeof Node !== "function" || !Node.prototype) return () => {};
|
||||
const proto = Node.prototype;
|
||||
const native: GuardedMethods = { removeChild: proto.removeChild, insertBefore: proto.insertBefore };
|
||||
installed = native;
|
||||
|
||||
const tracker: ReplacementTracker = { inserted: new WeakMap(), replacements: new WeakMap() };
|
||||
let observer: MutationObserver | undefined;
|
||||
if (typeof MutationObserver === "function" && typeof document !== "undefined" && document.documentElement) {
|
||||
observer = new MutationObserver((records) => recordReplacements(records, tracker));
|
||||
observer.observe(document.documentElement, { childList: true, subtree: true });
|
||||
}
|
||||
|
||||
const replacementInside = (parent: Node, node: Node): Element | null => {
|
||||
if (observer) recordReplacements(observer.takeRecords(), tracker);
|
||||
const replacement = tracker.replacements.get(node);
|
||||
return replacement && replacement.parentNode === parent ? replacement : null;
|
||||
};
|
||||
|
||||
proto.removeChild = function removeChild<T extends Node>(this: Node, child: T): T {
|
||||
if (child && child.parentNode !== this && hasPageTranslationMarker()) {
|
||||
if (child.parentNode === null) {
|
||||
const replacement = replacementInside(this, child);
|
||||
if (replacement) native.removeChild.call(this, replacement);
|
||||
return child;
|
||||
}
|
||||
if (this.contains(child)) return native.removeChild.call(child.parentNode, child) as T;
|
||||
}
|
||||
return native.removeChild.call(this, child) as T;
|
||||
};
|
||||
|
||||
proto.insertBefore = function insertBefore<T extends Node>(this: Node, node: T, child: Node | null): T {
|
||||
if (child && child.parentNode !== this && hasPageTranslationMarker()) {
|
||||
if (child.parentNode === null) {
|
||||
return native.insertBefore.call(this, node, replacementInside(this, child)) as T;
|
||||
}
|
||||
const wrapper = this.contains(child) ? childOfParentContaining(this, child) : null;
|
||||
if (wrapper) return native.insertBefore.call(this, node, wrapper) as T;
|
||||
}
|
||||
return native.insertBefore.call(this, node, child) as T;
|
||||
};
|
||||
|
||||
return () => {
|
||||
if (installed !== native) return;
|
||||
observer?.disconnect();
|
||||
proto.removeChild = native.removeChild;
|
||||
proto.insertBefore = native.insertBefore;
|
||||
installed = undefined;
|
||||
};
|
||||
}
|
||||
@@ -28,6 +28,7 @@ import { initPluginBridge } from "./plugins/bridge-init";
|
||||
import { PluginLauncherProvider } from "./plugins/launchers";
|
||||
import { startChunkLoadRecovery } from "./lib/chunk-load-recovery";
|
||||
import { startPerfMeasureReaper } from "./lib/perf-measure-reaper";
|
||||
import { startTranslationDomGuard } from "./lib/translation-dom-guard";
|
||||
import { getOrCreatePaperclipReactRoot } from "./lib/react-root";
|
||||
import { startServiceWorkerUpdates } from "./lib/service-worker-updates";
|
||||
import { connectivity } from "./lib/connectivity";
|
||||
@@ -48,6 +49,8 @@ startPerfMeasureReaper();
|
||||
|
||||
startChunkLoadRecovery();
|
||||
|
||||
startTranslationDomGuard();
|
||||
|
||||
// The global mutation error toast is raised from the MutationCache, outside
|
||||
// React; the bridge below hands it the ToastProvider's pushToast.
|
||||
let pushMutationErrorToast: ((input: ToastInput) => void) | null = null;
|
||||
|
||||
Reference in new issue
Block a user