π OpenHands: AI-Driven Development
fix(library): preserve ESM peer imports in browser hosts (#18619)
πΎ smolpaws78beca15f1db
diff --git a/.pr/evidence/library-host/README.md b/.pr/evidence/library-host/README.mdnew file mode 100644index 0000000000..8360b13304--- /dev/null+++ b/.pr/evidence/library-host/README.md@@ -0,0 +1,11 @@+I am an AI agent helping Engel Nyst (@enyst) with project work.++# Normal library host proof++Build the selected package with `npm run build:lib`. The supplied host imports `@openhands/agent-canvas` by package name and mounts a button inside AgentServerUIRoot. In host/, install the exact listed dependencies (the package uses file:../../../..) and run `npx vite --host 127.0.0.1 --port PORT`. No import alias or global require shim is supplied. This run reused owned links to the existing exact-pinned modules instead of reinstalling them. The HTML error element only observes native window errors.++Write the host loopback URL to the owned control-openhands run workspace/library-host-url. Use `control-openhands bug run F26.lib-host-app --file .pr/evidence/library-host/recipe.md --attempts 2 --label LABEL --run RUN` on base and fix, then compare using `control-openhands bug proof F26.lib-host-app --file .pr/evidence/library-host/recipe.md --baseline BASE_RUN --fix FIX_RUN --baseline-label baseline-host --fix-label fix-host-final`.++paired-proof.json records two baseline xfails and two fixed xpasses with the identical recipe and backend/viewport. The fixed recording includes a real button click from 0 to 1. The build test separately runs native ESM and CJS consumers and checks React/Motion identity with the host dependencies.++A preliminary React-only fix exposed Motion's optional peer require being hoisted outside its guarded try/catch. That candidate was not counted as fixed. The final product commit also externalizes the existing framer-motion dependency. Only the final verified comparison is published here. Both external hosts and the fixed Canvas run were stopped; shared dependency data was preserved.diff --git a/.pr/evidence/library-host/after.gif b/.pr/evidence/library-host/after.gifnew file mode 100644index 0000000000..0b370acf6aBinary files /dev/null and b/.pr/evidence/library-host/after.gif differdiff --git a/.pr/evidence/library-host/after.mp4 b/.pr/evidence/library-host/after.mp4new file mode 100644index 0000000000..8dd60aef87Binary files /dev/null and b/.pr/evidence/library-host/after.mp4 differdiff --git a/.pr/evidence/library-host/after.png b/.pr/evidence/library-host/after.pngnew file mode 100644index 0000000000..415136a171Binary files /dev/null and b/.pr/evidence/library-host/after.png differdiff --git a/.pr/evidence/library-host/before.gif b/.pr/evidence/library-host/before.gifnew file mode 100644index 0000000000..65cee4c73cBinary files /dev/null and b/.pr/evidence/library-host/before.gif differdiff --git a/.pr/evidence/library-host/before.mp4 b/.pr/evidence/library-host/before.mp4new file mode 100644index 0000000000..4f60c6bb35Binary files /dev/null and b/.pr/evidence/library-host/before.mp4 differdiff --git a/.pr/evidence/library-host/before.png b/.pr/evidence/library-host/before.pngnew file mode 100644index 0000000000..93d0f7ee64Binary files /dev/null and b/.pr/evidence/library-host/before.png differdiff --git a/.pr/evidence/library-host/host/host.js b/.pr/evidence/library-host/host/host.jsnew file mode 100644index 0000000000..c64230564f--- /dev/null+++ b/.pr/evidence/library-host/host/host.js@@ -0,0 +1,8 @@+import React from "react";+import { createRoot } from "react-dom/client";+import { AgentServerUIRoot } from "@openhands/agent-canvas";+function App() {+ const [count, setCount] = React.useState(0);+ return React.createElement(AgentServerUIRoot, {}, React.createElement("button", { id: "inside", onClick: () => setCount((value) => value + 1) }, "Inside Canvas " + count));+}+createRoot(document.getElementById("root")).render(React.createElement(App));diff --git a/.pr/evidence/library-host/host/index.html b/.pr/evidence/library-host/host/index.htmlnew file mode 100644index 0000000000..cdba9cf7c2--- /dev/null+++ b/.pr/evidence/library-host/host/index.html@@ -0,0 +1 @@+<!doctype html><html lang="en"><head><meta charset="UTF-8"><title>Canvas package consumer</title></head><body><h1 id="outside">Normal Vite host β outside Canvas</h1><pre id="module-error" role="alert"></pre><div id="root"></div><script>window.addEventListener("error",(event)=>{document.getElementById("module-error").textContent=event.message;});</script><script type="module" src="/host.js"></script></body></html>diff --git a/.pr/evidence/library-host/host/package.json b/.pr/evidence/library-host/host/package.jsonnew file mode 100644index 0000000000..e0d6fd7035--- /dev/null+++ b/.pr/evidence/library-host/host/package.json@@ -0,0 +1,12 @@+{+ "name": "canvas-library-browser-proof",+ "private": true,+ "type": "module",+ "dependencies": {+ "@openhands/agent-canvas": "file:../../../..",+ "react": "19.3.0",+ "react-dom": "19.3.0",+ "react-router": "7.18.2",+ "vite": "8.0.16"+ }+}diff --git a/.pr/evidence/library-host/host/vite.config.mjs b/.pr/evidence/library-host/host/vite.config.mjsnew file mode 100644index 0000000000..36fe90bb92--- /dev/null+++ b/.pr/evidence/library-host/host/vite.config.mjs@@ -0,0 +1,9 @@+import { defineConfig } from "vite";+import { resolve } from "node:path";+import { realpathSync } from "node:fs";+const packageDirectory = resolve(process.env.QA_CANVAS_PACKAGE_DIR || "../../../..");+export default defineConfig({+ server: { host: "127.0.0.1", strictPort: true, fs: { allow: [process.cwd(), packageDirectory, realpathSync(resolve(packageDirectory, "node_modules"))] } },+ optimizeDeps: { include: ["@openhands/agent-canvas"] },+ resolve: { dedupe: ["react", "react-dom", "react-router"] },+});diff --git a/.pr/evidence/library-host/paired-proof.json b/.pr/evidence/library-host/paired-proof.jsonnew file mode 100644index 0000000000..3ab4a81167--- /dev/null+++ b/.pr/evidence/library-host/paired-proof.json@@ -0,0 +1,21 @@+{+ "ok": true,+ "id": "F26.lib-host-app",+ "verdict": "verified",+ "blocks": [+ {+ "name": "bare-package-mount",+ "sha": "8d623f948de5b335",+ "verdict": "verified",+ "reasons": [],+ "baseline": {+ "xfail": 2+ },+ "fix": {+ "xpass": 2+ },+ "ignored": 0+ }+ ],+ "hint": "Drop the Known failure note and the block's `# bug` marker in the fix's PR: the assertion now guards the corrected behavior as a normal recipe step."+}diff --git a/.pr/evidence/library-host/recipe.md b/.pr/evidence/library-host/recipe.mdnew file mode 100644index 0000000000..a3ce05c2f1--- /dev/null+++ b/.pr/evidence/library-host/recipe.md@@ -0,0 +1,15 @@+I am an AI agent helping Engel Nyst (@enyst) with project work.++Browser consumer proof for the normal bare package import. The host's error element observes native window error events; it supplies no require shim or mocked module response. Arrange the supplied host fixture against the selected package and write its loopback URL to the owned run workspace/library-host-url file. The same recipe is used on base and fix.++```sh known-bug F26.lib-host-app bare-package-mount+control-openhands browser viewport desktop+QA_LIBRARY_HOST_URL=$(cat "$OH_VERIFY_RUN/workspace/library-host-url")+control-openhands browser goto "$QA_LIBRARY_HOST_URL" --allow-external+control-openhands browser wait '#outside'+control-openhands browser wait '#inside, #module-error:not(:empty)' --timeout 30000+control-openhands browser screenshot --feature F26.lib-host-app --name bare-package-host+control-openhands assert --field value.mounted --equals true --bug 'value.mounted eq false && value.reactRequireError eq true' -- browser eval '(()=>({mounted:!!document.querySelector("#inside"),reactRequireError:document.querySelector("#module-error").textContent.includes("Calling `require` for \"react\"")}))()' # bug+control-openhands browser click '#inside'+control-openhands assert --field text --equals 'Inside Canvas 1' -- browser text '#inside'+```diff --git a/.pr/evidence/library-host/summary.json b/.pr/evidence/library-host/summary.jsonnew file mode 100644index 0000000000..d28265b122--- /dev/null+++ b/.pr/evidence/library-host/summary.json@@ -0,0 +1,76 @@+{+ "attribution": "I am an AI agent helping Engel Nyst (@enyst) with project work.",+ "issue": "https://github.com/enyst/playground/issues/126",+ "baseline": "61a3bd93e642a0ff4def73b29496a73245628209",+ "tested_product_revision": "8652dc8117e4c1d205d3f65cd60cd78e5081086a",+ "agent_server": "1.55.1",+ "automation": "1.20.1",+ "browser": "Chromium 151.0.7922.173",+ "playwright": "1.63.0",+ "node": "24.21.0",+ "model_response_requested": false,+ "cleanup": {+ "run": "/workspace/work/fix-weekly-four/runs/fix-126-final",+ "browser": {+ "stopped": true,+ "pid": 316916+ },+ "launcherStopped": true,+ "ports": {+ "ingress": "closed",+ "agentServer": "closed",+ "automation": "closed",+ "frontend": "closed",+ "vscode": "closed"+ },+ "evidenceFiles": 8,+ "privatePurged": true,+ "evidenceFilesAfterPurge": 8,+ "ok": true+ },+ "focused_tests_passed": 25,+ "library_build": "ESM, CJS, declarations completed",+ "live_assertions": [+ "bare package import mounts AgentServerUIRoot",+ "native window error has no React require failure",+ "Inside Canvas button changes from 0 to 1"+ ],+ "hosts": {+ "base_port": 21580,+ "fix_port": 21680,+ "peer_versions": {+ "react": "19.3.0",+ "react-dom": "19.3.0",+ "react-router": "7.18.2",+ "vite": "8.0.16"+ },+ "installation": "Owned node_modules links to the selected package and existing exact-pinned peer dependencies; ordinary bare package import. No aliases or require shim."+ },+ "host_cleanup": {+ "processes": [+ {+ "variant": "base",+ "pid": 310633,+ "port": 21580,+ "state": "owned-group-sigterm"+ },+ {+ "variant": "fix",+ "pid": 310635,+ "port": 21680,+ "state": "zombie-not-a-service"+ },+ {+ "variant": "fix",+ "pid": 316536,+ "port": 21680,+ "state": "owned-group-sigterm"+ }+ ],+ "ports_closed": [+ 21580,+ 21680+ ]+ },+ "scope": "Library peer interop and root mounting/click only; not full Canvas route or SSR coverage."+}diff --git a/.pr/evidence/library-host/task-cleanup.json b/.pr/evidence/library-host/task-cleanup.jsonnew file mode 100644index 0000000000..8ee80853dd--- /dev/null+++ b/.pr/evidence/library-host/task-cleanup.json@@ -0,0 +1,102 @@+{+ "checked_at": "2026-10-17T23:40:38.477040+00:00",+ "owned_runs": {+ "base": {+ "ports": {+ "ingress": "closed",+ "agentServer": "closed",+ "automation": "closed",+ "frontend": "closed",+ "vscode": "closed"+ },+ "private_purged": true,+ "evidence_files_retained": 46+ },+ "fix-124": {+ "ports": {+ "ingress": "closed",+ "agentServer": "closed",+ "automation": "closed",+ "frontend": "closed",+ "vscode": "closed"+ },+ "private_purged": true,+ "evidence_files_retained": 12+ },+ "fix-125": {+ "ports": {+ "ingress": "closed",+ "agentServer": "closed",+ "automation": "closed",+ "frontend": "closed",+ "vscode": "closed"+ },+ "private_purged": true,+ "evidence_files_retained": 15+ },+ "fix-126-preliminary": {+ "ports": {+ "ingress": "closed",+ "agentServer": "closed",+ "automation": "closed",+ "frontend": "closed",+ "vscode": "closed"+ },+ "private_purged": true,+ "evidence_files_retained": 8+ },+ "fix-126-final": {+ "ports": {+ "ingress": "closed",+ "agentServer": "closed",+ "automation": "closed",+ "frontend": "closed",+ "vscode": "closed"+ },+ "private_purged": true,+ "evidence_files_retained": 8+ },+ "fix-127": {+ "ports": {+ "ingress": "closed",+ "agentServer": "closed",+ "automation": "closed",+ "frontend": "closed",+ "vscode": "closed"+ },+ "private_purged": true,+ "evidence_files_retained": 14+ }+ },+ "external_hosts": {+ "processes": [+ {+ "variant": "base",+ "pid": 310633,+ "port": 21580,+ "state": "owned-group-sigterm"+ },+ {+ "variant": "fix",+ "pid": 310635,+ "port": 21680,+ "state": "zombie-not-a-service"+ },+ {+ "variant": "fix",+ "pid": 316536,+ "port": 21680,+ "state": "owned-group-sigterm"+ }+ ],+ "ports_closed": [+ 21580,+ 21680+ ]+ },+ "unique_port_count": 27,+ "evidence_files": 103,+ "scope": "Only this four-fix task resources were stopped; shared images/dependencies and original weekly evidence were preserved.",+ "all_owned_ports_closed": true,+ "count_definition": "Unique regular files beneath the six owned run evidence directories; current symlink aliases are excluded."+}diff --git a/__tests__/vite-config.test.ts b/__tests__/vite-config.test.tsindex 6aa10961ab..46b86001ee 100644--- a/__tests__/vite-config.test.ts+++ b/__tests__/vite-config.test.ts@@ -1,5 +1,10 @@// @vitest-environment nodeimport viteConfig from "../vite.config";+import { build } from "vite";+import { execFileSync } from "node:child_process";+import { mkdtemp, writeFile, symlink, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";import { afterEach, describe, expect, it } from "vitest";afterEach(() => {@@ -104,7 +109,9 @@ describe("vite app build", () => {};};- expect(appBuild.build?.rolldownOptions?.output?.codeSplitting?.groups).toEqual(+ expect(+ appBuild.build?.rolldownOptions?.output?.codeSplitting?.groups,+ ).toEqual(expect.arrayContaining([expect.objectContaining({name: "vendor",@@ -126,9 +133,6 @@ describe("vite library build", () => {expect(config.build?.lib).toMatchObject({formats: ["es"],});- expect(config.build?.rollupOptions?.external).toEqual(- expect.arrayContaining(["react", "react-dom", "react-router"]),- );expect(config.build?.rollupOptions?.output).toEqual(expect.arrayContaining([expect.objectContaining({@@ -146,3 +150,68 @@ describe("vite library build", () => {);});});++it("emits browser-compatible ESM when a bundled CommonJS dependency requires a React peer", async () => {+ process.env.BUILD_LIB = "true";+ const directory = await mkdtemp(join(tmpdir(), "canvas-esm-peer-"));+ try {+ await writeFile(+ join(directory, "package.json"),+ JSON.stringify({ type: "module" }),+ );+ await symlink(+ resolve("node_modules"),+ join(directory, "node_modules"),+ "dir",+ );+ await writeFile(+ join(directory, "entry.js"),+ 'export { useSyncExternalStore } from "use-sync-external-store/shim"; export { motion } from "framer-motion";',+ );+ const config = await viteConfig({ mode: "production", command: "build" });+ const built = await build({+ ...config,+ configFile: false,+ logLevel: "error",+ root: directory,+ build: {+ ...config.build,+ sourcemap: false,+ lib: { entry: join(directory, "entry.js"), formats: ["es"] },+ outDir: join(directory, "dist"),+ },+ });+ const outputs = Array.isArray(built) ? built : [built];+ const esm = outputs[0];+ if (!("output" in esm))+ throw new Error("Expected a completed library build");+ const entry = esm.output.find(+ (chunk) => chunk.type === "chunk" && chunk.isEntry,+ );+ if (!entry) throw new Error("Library entry was not emitted");+ await writeFile(+ join(directory, "consumer.mjs"),+ `import React from "react"; import { motion as hostMotion } from "framer-motion"; import { useSyncExternalStore, motion } from ${JSON.stringify("./dist/" + entry.fileName)}; if (useSyncExternalStore !== React.useSyncExternalStore) throw new Error("React peer hook was not preserved"); if (motion !== hostMotion) throw new Error("Motion dependency was not preserved");`,+ );++ // A native ESM consumer has no CommonJS require shim, like a browser host.+ execFileSync(process.execPath, [join(directory, "consumer.mjs")], {+ stdio: "pipe",+ });+ const cjs = outputs[1];+ if (!("output" in cjs)) throw new Error("Expected CommonJS library output");+ const commonEntry = cjs.output.find(+ (chunk) => chunk.type === "chunk" && chunk.isEntry,+ );+ if (!commonEntry) throw new Error("CommonJS entry was not emitted");+ await writeFile(+ join(directory, "consumer.cjs"),+ `const React = require("react"); const { motion: hostMotion } = require("framer-motion"); const { useSyncExternalStore, motion } = require(${JSON.stringify("./dist/" + commonEntry.fileName)}); if (useSyncExternalStore !== React.useSyncExternalStore) throw new Error("CommonJS React peer hook was not preserved"); if (motion !== hostMotion) throw new Error("CommonJS Motion dependency was not preserved");`,+ );+ execFileSync(process.execPath, [join(directory, "consumer.cjs")], {+ stdio: "pipe",+ });+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+}, 30000);diff --git a/vite.config.ts b/vite.config.tsindex 26241f541a..41bea69ee6 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -4,7 +4,7 @@ import { fileURLToPath } from "node:url";import { createRequire } from "node:module";import { readFile } from "node:fs/promises";import { resolve, dirname, relative, isAbsolute } from "node:path";-import { defineConfig, loadEnv } from "vite";+import { defineConfig, esmExternalRequirePlugin, loadEnv } from "vite";import svgr from "vite-plugin-svgr";import { reactRouter } from "@react-router/dev/vite";import { configDefaults } from "vitest/config";@@ -22,6 +22,8 @@ const LIB_EXTERNALS = ["react/jsx-runtime","react/jsx-dev-runtime","react-router",+ // Preserve Motion's guarded optional-peer require at runtime.+ "framer-motion",];const APP_CHUNK_MAX_BYTES = 450 * 1024;@@ -192,6 +194,9 @@ export default defineConfig(({ mode }) => {});},},+ // Let this plugin own externalization so CJS requires become ESM+ // imports. Top-level external entries bypass its resolve hook.+ isLibraryBuild && esmExternalRequirePlugin({ external: LIB_EXTERNALS }),!process.env.VITEST && !isLibraryBuild && reactRouter(),svgr(),tailwindcss(),@@ -229,7 +234,6 @@ export default defineConfig(({ mode }) => {formats: ["es"],},rollupOptions: {- external: LIB_EXTERNALS,output: [{format: "es",