fix(app): keep uncaught plugin errors from crashing the native app (#11412)

React Native reports an error thrown out of a press handler, timer,
animation frame, or microtask to ErrorUtils as fatal, so one bad plugin
callback terminated a release app. The plugin error boundary only covers
render and effects.

Client bundles now evaluate with a paseo-plugin://<server>/<plugin>
source URL, and a wrapped global handler logs errors whose stack has a
plugin frame instead of forwarding them. Errors without a plugin frame
reach the previous handler unchanged.

Hermes prints an empty source for new Function code and records no
creation site, so the bundle receives a Function that appends a source
URL to code it compiles. Code compiled through eval, globalThis.Function,
or from already compiled code stays unattributed and fatal.

Refs #10978
This commit is contained in:
Mohamed Boudra
2026-11-30 15:45:16 +07:00
committed by GitHub
parent 9d994aca9b
commit 01aced8cd2
8 changed files with 382 additions and 11 deletions
@@ -58,7 +58,11 @@ function installProbe(
return function() {};
} };
})`;
const evaluated = runPluginClientBundle("probe-plugin", clientBundle, runtime);
const evaluated = runPluginClientBundle(
{ serverId: "test-host", pluginId: "probe-plugin" },
clientBundle,
runtime,
);
return {
...evaluated,
serverId: "host-1",
+13 -5
View File
@@ -27,7 +27,7 @@ const runtime = {
} as unknown as PluginClientRuntime;
function evaluatePluginClientBundle(id: string, source: string) {
return runPluginClientBundle(id, source, runtime);
return runPluginClientBundle({ serverId: "test-host", pluginId: id }, source, runtime);
}
function bundle(body: string): string {
@@ -52,7 +52,7 @@ describe("evaluatePluginClientBundle", () => {
}
expect(() =>
runPluginClientBundle(
"failed-buttons",
{ serverId: "test-host", pluginId: "failed-buttons" },
bundle(`
plugin.addHeaderButton({ id: "header", workspaceId: "workspace", button: { title: "Header", icon: "Scan", behavior: { kind: "action", onPress() {} } } });
plugin.addComposerPill({ id: "pill", workspaceId: "workspace", agentId: "agent", button: { title: "Pill", icon: "Scan", behavior: { kind: "action", onPress() {} } } });
@@ -101,7 +101,7 @@ describe("evaluatePluginClientBundle", () => {
it("returns idempotent removers for every client registration", () => {
let pillCount = 0;
const plugin = runPluginClientBundle(
"removals",
{ serverId: "test-host", pluginId: "removals" },
bundle(`
function Component() { return null; }
const schema = { safeParse(value) { return { success: true, data: value }; } };
@@ -1052,8 +1052,16 @@ it("binds imported getters to each originating installation across delayed callb
onSelect: async () => { await Promise.resolve(); getPaseoClient("target-host"); },
});
`);
const first = runPluginClientBundle("same-id", source, hostRuntime("first"));
const second = runPluginClientBundle("same-id", source, hostRuntime("second"));
const first = runPluginClientBundle(
{ serverId: "first", pluginId: "same-id" },
source,
hostRuntime("first"),
);
const second = runPluginClientBundle(
{ serverId: "second", pluginId: "same-id" },
source,
hostRuntime("second"),
);
// Both callbacks run after the second bundle has evaluated.
await first.commandCenterItems[0].onSelect({} as never);
await second.commandCenterItems[0].onSelect({} as never);
+4 -3
View File
@@ -43,6 +43,7 @@ import type {
import type { ComponentType } from "react";
import { parsePluginIcon, parseSerializablePluginIcon } from "./icons";
import { parsePluginThemeContribution } from "./themes";
import { evaluatePluginSource } from "./uncaught-errors";
const CONTRIBUTION_ID = /^[a-z][a-z0-9-]*$/;
const PANEL_LOCATIONS = ["workspace", "explorer"] as const;
@@ -147,11 +148,12 @@ const pluginReactNativeRuntime = createPluginReactNativeRuntime(
);
export function runPluginClientBundle(
id: string,
installation: { serverId: string; pluginId: string },
bundle: string,
runtime: PluginClientRuntime,
onChange: () => void = () => undefined,
): EvaluatedPlugin {
const id = installation.pluginId;
const collector: Omit<EvaluatedPlugin, "id" | "cleanup"> = {
surfaces: [],
settingsScreens: [],
@@ -631,8 +633,7 @@ export function runPluginClientBundle(
if (name === "zod") return Zod;
throw new Error(`Module "${name}" is not available in plugin client code`);
};
const evaluate: (source: string) => unknown = globalThis.eval;
const factory = evaluate(bundle);
const factory = evaluatePluginSource(bundle, installation);
if (typeof factory !== "function")
throw new Error(`Plugin ${id} client bundle is not executable`);
const exports = factory(runtimeRequire);
+5 -2
View File
@@ -143,8 +143,11 @@ export class PluginRegistry {
once: true,
});
const runtime = this.dependencies.createRuntime(installation, options.audio);
const evaluated = runPluginClientBundle(entry.id, entry.clientBundle, runtime, () =>
this.publish(),
const evaluated = runPluginClientBundle(
{ serverId, pluginId: entry.id },
entry.clientBundle,
runtime,
() => this.publish(),
);
Object.assign(installation, evaluated);
const paseo = installation.paseo;
@@ -0,0 +1,224 @@
import { describe, expect, it } from "vitest";
import { runPluginClientBundle, type PluginClientRuntime } from "./evaluate";
import { containUncaughtPluginErrors } from "./uncaught-errors";
type GlobalHandler = (error: unknown, isFatal?: boolean) => void;
const runtime = {} as PluginClientRuntime;
/** The React Native `ErrorUtils` global: one replaceable handler for uncaught errors. */
function createErrorUtils() {
const received: Array<{ error: unknown; isFatal: boolean | undefined }> = [];
let handler: GlobalHandler = (error, isFatal) => received.push({ error, isFatal });
return {
received,
getGlobalHandler: () => handler,
setGlobalHandler: (next: GlobalHandler) => {
handler = next;
},
/** What React Native does with an error thrown out of a timer, press handler, or microtask. */
reportFatal(run: () => void) {
try {
run();
} catch (error) {
handler(error, true);
}
},
};
}
function createReports() {
const reports: Array<{ plugin: string; error: unknown }> = [];
return { reports, report: (plugin: string, error: unknown) => reports.push({ plugin, error }) };
}
/** A client bundle whose entry exposes `handlers` built from `body` to the test. */
function evaluateHandlers(
installation: { serverId: string; pluginId: string },
body: string,
): Record<string, () => void> {
const source = `(function(require) {
const module = { exports: {} };
module.exports.default = function(plugin) {
globalThis.__pluginHandlers = (function() { ${body} })();
return function() {};
};
return module.exports;
})`;
runPluginClientBundle(installation, source, runtime);
const handlers = Reflect.get(globalThis, "__pluginHandlers") as Record<string, () => void>;
Reflect.deleteProperty(globalThis, "__pluginHandlers");
return handlers;
}
function errorWithStack(stack: string): Error {
const error = new Error(stack.split("\n")[0]);
error.stack = stack;
return error;
}
const demo = { serverId: "srv_local", pluginId: "demo" };
function stackOf(run: () => void): string {
try {
run();
} catch (error) {
return String((error as Error).stack);
}
throw new Error("expected a throw");
}
describe("plugin source URLs", () => {
it("name the installation in the stack frames of plugin code", () => {
const handlers = evaluateHandlers(
demo,
`return { boom: function pluginBoom() { throw new Error("plugin failed"); } };`,
);
expect(stackOf(handlers.boom)).toMatch(
/at pluginBoom \(paseo-plugin:\/\/srv_local\/demo\/index\.client\.js:\d+:\d+\)/,
);
});
it("name code the plugin compiles with new Function", () => {
const handlers = evaluateHandlers(
demo,
`return { inner: new Function("throw new Error('inner failed');") };`,
);
expect(stackOf(handlers.inner)).toMatch(
/^ {4}at (eval|anonymous) \(paseo-plugin:\/\/srv_local\/demo\/function\.js:\d+:\d+\)$/m,
);
});
it("percent-encode installation names so each stays one URL", () => {
const handlers = evaluateHandlers(
{ serverId: "srv (a):b", pluginId: "x/y\n//# sourceURL=evil" },
`return { boom: function pluginBoom() { throw new Error("plugin failed"); } };`,
);
expect(stackOf(handlers.boom)).toContain(
"paseo-plugin://srv%20%28a%29%3Ab/x%2Fy%0A%2F%2F%23%20sourceURL%3Devil/index.client.js:",
);
});
});
describe("containUncaughtPluginErrors", () => {
it("keeps a fatal error thrown by plugin code from reaching the previous handler", () => {
const errorUtils = createErrorUtils();
const { reports, report } = createReports();
containUncaughtPluginErrors(errorUtils, report);
const handlers = evaluateHandlers(
demo,
`return {
press: function onPress() { throw new Error("press failed"); },
timer: function onTimer() { JSON.parse("{not json"); },
};`,
);
errorUtils.reportFatal(handlers.press);
errorUtils.reportFatal(handlers.timer);
expect(errorUtils.received).toEqual([]);
expect(reports.map(({ plugin }) => plugin)).toEqual(["srv_local/demo", "srv_local/demo"]);
expect(reports.map(({ error }) => (error as Error).message)).toEqual([
"press failed",
expect.stringContaining("JSON"),
]);
});
it("passes errors without a plugin frame to the previous handler unchanged", () => {
const errorUtils = createErrorUtils();
const { reports, report } = createReports();
containUncaughtPluginErrors(errorUtils, report);
const hostError = new Error("host failed");
errorUtils.reportFatal(() => {
throw hostError;
});
errorUtils.getGlobalHandler()("not an error", false);
expect(errorUtils.received).toEqual([
{ error: hostError, isFatal: true },
{ error: "not an error", isFatal: false },
]);
expect(reports).toEqual([]);
});
// Stacks captured on the iOS 27.2 simulator (Hermes) from the QA plugin in the pull request.
const HOST_FRAME =
" at _performTransitionSideEffects (http://127.0.0.1:8113/packages/app/index.ts.bundle//&platform=ios&dev=true:61087:20)";
it("attributes Hermes frames of plugin code and of code a plugin tags itself", () => {
const errorUtils = createErrorUtils();
const { reports, report } = createReports();
containUncaughtPluginErrors(errorUtils, report);
for (const stack of [
[
"Error: timer",
" at anonymous (paseo-plugin://srv_RDy5H9w4QGF9/crash-qa/index.client.js:8:90)",
],
[
"Error: inner only",
" at anonymous (paseo-plugin://srv_RDy5H9w4QGF9/crash-qa/function.js:1:38)",
" at anonymous (paseo-plugin://srv_RDy5H9w4QGF9/crash-qa/index.client.js:7:1239)",
HOST_FRAME,
],
[
"SyntaxError: JSON Parse error: Unexpected character: b",
" at parse (native)",
" at anonymous (paseo-plugin://srv_RDy5H9w4QGF9/crash-qa/index.client.js:8:169)",
HOST_FRAME,
],
[
"Error: inner tagged",
" at anonymous (paseo-plugin://crash-qa/inner.js:1:38)",
HOST_FRAME,
],
]) {
errorUtils.getGlobalHandler()(errorWithStack(stack.join("\n")), true);
}
expect(errorUtils.received).toEqual([]);
expect(reports.map(({ plugin }) => plugin)).toEqual([
"srv_RDy5H9w4QGF9/crash-qa",
"srv_RDy5H9w4QGF9/crash-qa",
"srv_RDy5H9w4QGF9/crash-qa",
"crash-qa",
]);
});
it("passes through Hermes code that has no plugin source URL", () => {
const errorUtils = createErrorUtils();
containUncaughtPluginErrors(errorUtils, createReports().report);
// Hermes prints an empty source for code evaluated without a source URL.
const untagged = errorWithStack(
[
"Error: inner only",
" at anonymous (:1:38)",
" at anonymous (:6:1239)",
HOST_FRAME,
].join("\n"),
);
errorUtils.getGlobalHandler()(untagged, true);
expect(errorUtils.received).toEqual([{ error: untagged, isFatal: true }]);
});
it("wraps the global handler once", () => {
const errorUtils = createErrorUtils();
const { reports, report } = createReports();
containUncaughtPluginErrors(errorUtils, report);
const installed = errorUtils.getGlobalHandler();
containUncaughtPluginErrors(errorUtils, report);
expect(errorUtils.getGlobalHandler()).toBe(installed);
const handlers = evaluateHandlers(demo, `return { press() { throw new Error("once"); } };`);
errorUtils.reportFatal(handlers.press);
expect(reports).toHaveLength(1);
});
it("does nothing where React Native has no global error handler", () => {
expect(() => containUncaughtPluginErrors(undefined)).not.toThrow();
});
});
+112
View File
@@ -0,0 +1,112 @@
/**
* Keeps an uncaught error from plugin code from terminating the native app.
*
* React Native reports an error thrown out of a press handler, timer, animation frame, or
* microtask to its global handler as fatal: debug builds show a red screen and release builds
* terminate. Browsers only log the same error. Paseo names every frame of plugin code with a
* `paseo-plugin://` source URL, and the global handler logs errors whose stack has such a frame
* instead of forwarding them as fatal.
*/
type GlobalErrorHandler = (error: unknown, isFatal?: boolean) => void;
/** React Native's `ErrorUtils` global. */
interface GlobalErrorUtils {
getGlobalHandler(): GlobalErrorHandler;
setGlobalHandler(handler: GlobalErrorHandler): void;
}
interface PluginInstallation {
serverId: string;
pluginId: string;
}
const PLUGIN_SOURCE_SCHEME = "paseo-plugin://";
const PLUGIN_FRAME = /paseo-plugin:\/\/([^\s():]+)/;
// Shared across module instances, so a reloaded module does not wrap the handler again.
const CONTAINING_HANDLER = Symbol.for("paseo.plugins.containingErrorHandler");
const NativeFunction = globalThis.Function;
/**
* Evaluates a plugin client bundle, an expression that yields its factory.
*
* Hermes prints an empty source for code without a source URL, and it does not record where
* `new Function` code was created. The bundle therefore gets a source URL, and so does code
* that the bundle compiles with `new Function`, because the bundle sees a `Function` that tags it.
*/
export function evaluatePluginSource(source: string, installation: PluginInstallation): unknown {
containUncaughtPluginErrors();
const scope = NativeFunction(
"Function",
`return (\n${source}\n);\n//# sourceURL=${pluginSourceUrl(installation, "index.client.js")}`,
);
return scope(createTaggingFunction(pluginSourceUrl(installation, "function.js")));
}
/** Wraps React Native's global error handler once. Errors without a plugin frame pass through. */
export function containUncaughtPluginErrors(
errorUtils: GlobalErrorUtils | undefined = Reflect.get(globalThis, "ErrorUtils"),
report: (plugin: string, error: unknown) => void = logUncaughtPluginError,
): void {
if (!errorUtils) return;
const previous = errorUtils.getGlobalHandler();
if (Reflect.get(previous, CONTAINING_HANDLER) === true) return;
const containing: GlobalErrorHandler = (error, isFatal) => {
const plugin = findPluginInStack(error);
if (plugin === null) {
previous(error, isFatal);
return;
}
report(plugin, error);
};
Reflect.set(containing, CONTAINING_HANDLER, true);
errorUtils.setGlobalHandler(containing);
}
function logUncaughtPluginError(plugin: string, error: unknown): void {
console.error(`[Plugins] Uncaught error in ${plugin}`, error);
}
function pluginSourceUrl(installation: PluginInstallation, file: string): string {
return `${PLUGIN_SOURCE_SCHEME}${encodeSegment(installation.serverId)}/${encodeSegment(installation.pluginId)}/${file}`;
}
/** Percent-encodes everything that could end a URL inside a stack frame or a source comment. */
function encodeSegment(value: string): string {
return encodeURIComponent(value).replace(
/[!'()*~]/g,
(character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,
);
}
function createTaggingFunction(sourceUrl: string): FunctionConstructor {
function PluginFunction(...parameters: string[]) {
const body = parameters.length > 0 ? String(parameters.pop()) : "";
return NativeFunction(...parameters, `${body}\n//# sourceURL=${sourceUrl}`);
}
PluginFunction.prototype = NativeFunction.prototype;
return PluginFunction as unknown as FunctionConstructor;
}
/**
* The plugin of the innermost `paseo-plugin://` frame: `<server>/<plugin>` for code Paseo
* evaluated, or the host part of a URL the plugin wrote itself.
*/
function findPluginInStack(error: unknown): string | null {
if (typeof error !== "object" || error === null) return null;
const stack: unknown = Reflect.get(error, "stack");
if (typeof stack !== "string") return null;
const location = PLUGIN_FRAME.exec(stack)?.[1];
if (!location) return null;
const segments = location.split("/");
if (segments.length > 1) segments.pop();
return segments.map(decodeSegment).join("/");
}
function decodeSegment(segment: string): string {
try {
return decodeURIComponent(segment);
} catch {
return segment;
}
}
+13
View File
@@ -280,6 +280,19 @@ The scaffold's `tsconfig.json` omits the DOM library. Keep DOM globals out of cr
components; do not add `/// <reference lib="dom" />` or `"DOM"` to `lib`.
`layout.platform` carries the same value as React Native's `Platform.OS` for rendering decisions.
### Uncaught errors
On iOS and Android, React Native treats an error thrown out of a press handler, timer, animation
frame, or microtask as fatal: a release app terminates. Paseo catches such an error when its stack
has a frame of plugin code. The app logs `[Plugins] Uncaught error in <host>/<plugin>` and keeps
running. Render and effect errors stay inside the plugin error boundary.
Paseo finds plugin code by its source URL, `paseo-plugin://<host>/<plugin>/index.client.js`. Code
that your client bundle compiles with `new Function` gets a source URL too. Other compiled code has
no source URL on Hermes, so its errors stay fatal. This includes code from `eval`, from
`globalThis.Function`, and from a `new Function` call inside code that was itself compiled. If you
compile code that way, end the source with `//# sourceURL=paseo-plugin://<plugin-id>/<file>.js`.
### Play audio
Call `client.playAudio({ base64, mimeType }): Promise<void>` to play an audio file on the
+6
View File
@@ -243,6 +243,12 @@ Paseo 为客户端代码提供以下模块:
脚手架的 `tsconfig.json` 省略了 DOM 库。请让跨平台组件远离 DOM 全局对象;不要添加 `/// <reference lib="dom" />`,也不要在 `lib` 中加入 `"DOM"`。`layout.platform` 携带与 React Native 的 `Platform.OS` 相同的值,用于渲染决策。
### 未捕获的错误 {#uncaught-errors}
在 iOS 和 Android 上,React Native 把从按压处理函数、定时器、动画帧或微任务中抛出的错误视为致命错误:release 版应用会直接退出。当错误的调用栈中有插件代码的帧时,Paseo 会捕获这个错误。应用记录 `[Plugins] Uncaught error in <host>/<plugin>` 并继续运行。渲染和 effect 中的错误仍由插件的错误边界处理。
Paseo 通过源 URL `paseo-plugin://<host>/<plugin>/index.client.js` 识别插件代码。客户端包用 `new Function` 编译的代码也会获得源 URL。其他编译出的代码在 Hermes 上没有源 URL,所以它的错误仍然是致命的。这包括 `eval`、`globalThis.Function`,以及在已编译代码内部调用 `new Function` 生成的代码。如果你用这些方式编译代码,请在源码末尾加上 `//# sourceURL=paseo-plugin://<plugin-id>/<file>.js`。
### 播放音频 {#play-audio}
调用 `client.playAudio({ base64, mimeType }): Promise<void>` 在当前客户端(浏览器、Electron、iOS 或 Android)上播放音频文件。传入插件 RPC 返回的 base64 文件即可;不需要浏览器全局对象或平台检查。