Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix(library): ship a scoped stylesheet with the npm library (#18663)

Engel Nyst975441627b2c
diff --git a/.agents/skills/frontend-development/references/guide.md b/.agents/skills/frontend-development/references/guide.md
index dad9452417..9730125298 100644
--- a/.agents/skills/frontend-development/references/guide.md
+++ b/.agents/skills/frontend-development/references/guide.md
@@ -128,6 +128,7 @@ When adding code that needs a new string, decide up front which rule it falls un
- Route decoupling note: `src/components/` should stay free of direct `react-router` imports. Route state now flows through `src/context/navigation-context.tsx`, the standalone app bridges router state with `src/routes/react-router-navigation-provider.tsx`, and link-like UI should use `src/components/shared/navigation-link.tsx`.
- Test helper note: `test-utils.tsx` now wraps renders with a default `NavigationProvider` (`currentPath: "/"`, `conversationId: "test-conversation-id"`). Navigation-sensitive tests can override that via `renderWithProviders(..., { navigation: { ... } })`.
- CSS isolation for embeddable/hosted use now relies on a scoped wrapper attribute: all bundled CSS is prefixed under `[data-agent-server-ui]` via `postcss-prefix-selector` in `vite.config.ts`, with selector exceptions handled by `transformAgentServerUISelector()` in `src/styles/agent-server-ui-style-scope.ts`. That transform must remap global selectors like `:root`, `html`, and `body` directly onto the scoped shell instead of emitting impossible descendants such as `[data-agent-server-ui] :root`.
+- The library ships its CSS as `dist/styles.css`, exported as `@openhands/agent-canvas/styles.css`: `src/index.ts` imports the single entry `src/styles.css` (which `@import`s `index.css`, then `tailwind.css`), and `build.lib.cssFileName` names the extracted file. Keep it one CSS import: Vite's CJS output turns adjacent stripped CSS requires into a dangling comma. Hosts import it explicitly; the JS entries stay free of CSS imports. Do not add a `sideEffects` glob list to package.json: any list marks the unlisted JS side-effect free, and the library build then drops modules such as `dist/components/browser/index.js`. `__tests__/vite-config.test.ts` builds the library and checks that the stylesheet is scoped and `dist/index.cjs` parses; `__tests__/package-library.test.ts` checks the export.
- Public embedding entry points should use `AgentServerUIProviders` (scoped root on by default) or `AgentServerUIRoot` for manual control. The standalone app already renders its own scoped root in `src/root.tsx`, so `src/entry.client.tsx` must pass `withStyleRoot={false}` to avoid nesting duplicate shells. Keep `AgentServerUIRoot` and the scoping constants re-exported from `src/lib/index.ts` so library consumers can customize the host wrapper without reaching into private paths.
- `AgentServerUIRoot`'s themed inner wrapper must set a default `color: var(--foreground)` in addition to the `dark` / `data-theme` markers; otherwise inherited text and `currentColor` SVG icons fall back to dark browser defaults after CSS scoping, causing dark-on-dark regressions on pages like the home screen.
- Theme/customization tokens for the embedded shell are exposed as `--oh-*` CSS variables. Override them through `styleOverrides`, `style`, or host CSS targeting `[data-agent-server-ui]`; Tailwind theme tokens in `src/tailwind.css` should continue to reference those variables with `@theme inline` so host apps can restyle the UI without reworking component class names.
diff --git a/.pr/library-stylesheet/README.md b/.pr/library-stylesheet/README.md
new file mode 100644
index 0000000000..9e03b0ee0e
--- /dev/null
+++ b/.pr/library-stylesheet/README.md
@@ -0,0 +1,73 @@
+I'm an AI agent helping Engel Nyst (@enyst) with project work.
+
+# Library stylesheet: before and after (#18655)
+
+A plain Vite host imports `@openhands/agent-canvas` by package name. It renders
+`AgentServerUIProviders` with `analytics: false` and
+`styleOverrides: {"--oh-color-base": "#101820"}` around
+`div#probe.flex.flex-col.gap-4.p-6.bg-canvas-base.text-foreground.rounded-xl`,
+which holds two spans and `button#inside.px-4.py-2.rounded-md.bg-primary.text-on-primary`.
+The host `<h1 id="outside">` sits outside the Canvas root.
+
+- `host/host-before.js` (`before.html`): main (79abd32d8). It mounts the
+ library as docs/DEVELOPMENT.md described, with no stylesheet import, because
+ main exports none.
+- `host/host.js` (`index.html`): the fix. It adds
+ `import "@openhands/agent-canvas/styles.css";`.
+
+## Commands
+
+```sh
+# Canvas checkout (base = origin/main 79abd32d8; fix = this branch)
+npm ci --ignore-scripts && npm run build:lib
+find dist -name '*.css' # base: dist/assets/agent-canvas-T4IDBjWs.css (5055 B, xterm only)
+ # fix: dist/styles.css (443162 B)
+
+# Host: copy host/ to a scratch directory, set the dependency to file:<checkout>.
+# Base run serves before.html as index.html.
+npm install --ignore-scripts
+QA_CANVAS_PACKAGE_DIR=<checkout> npx vite --host 127.0.0.1 --port 5792
+
+# Browser (verify-openhands control-openhands, chromium)
+export OH_VERIFY_RUN=$(control-openhands launch --new --print-run)
+control-openhands browser viewport desktop # then 390x844
+control-openhands browser goto http://127.0.0.1:5792/ --allow-external
+control-openhands browser wait '#inside, #module-error:not(:empty)' --timeout 60000
+control-openhands browser eval "$(cat probe.js)"
+control-openhands browser screenshot --feature F26.lib-host-app --name after-desktop
+control-openhands stop
+```
+
+## Measurements (desktop and 390x844 gave the same values)
+
+| | base (main) | fix |
+|---|---|---|
+| `#probe` display / direction / gap | block / row / normal | flex / column / 16px |
+| `#probe` padding | 0px | 24px |
+| `#probe` background | rgba(0, 0, 0, 0) | rgb(16, 24, 32) (the `styleOverrides` value) |
+| `#probe` radius / color | 0px / rgb(0, 0, 0) | 12px / rgb(238, 242, 247) |
+| `#inside` padding / background / radius | 1px 6px / rgb(239, 239, 239) / 0px | 8px 16px / rgb(201, 185, 116) / 6px |
+| host `h1#outside` | Times New Roman, 32px, margin 21.44px 0px, rgb(0, 0, 0) | unchanged |
+| host `body` background | rgba(0, 0, 0, 0) | unchanged |
+| stylesheets in the document | react-hot-toast `_goober` only | `_goober` + `dist/styles.css` |
+| module error | none | none |
+
+Other checks on the fix:
+
+- `styleOverrides` drives the color. Removing the inline `--oh-color-base` from
+ the scope root changes `#probe` to the built-in rgb(11, 14, 20). Putting it
+ back restores rgb(16, 24, 32).
+- The library still mounts and reacts. Clicking `#inside` changed its label from
+ "Inside Canvas 0" to "Inside Canvas 1".
+- Production host build: `npx vite build` in the host bundles the stylesheet
+ into `assets/index-<hash>.css` (444 kB), and that file contains
+ `[data-agent-server-ui] .flex{display:flex}`. The same probe on the static
+ build returned the fix values above.
+
+## Screenshots
+
+- `before-desktop.png`, `before-phone.png`: main. The probe is unstyled inline
+ text and the button has the browser's default grey look.
+- `after-desktop.png`, `after-phone.png`: the fix. The probe is a padded column
+ on the `#101820` override, with a rounded accent button. The host heading
+ stays in the browser's default serif.
diff --git a/.pr/library-stylesheet/after-desktop.png b/.pr/library-stylesheet/after-desktop.png
new file mode 100644
index 0000000000..664e2dedf1
Binary files /dev/null and b/.pr/library-stylesheet/after-desktop.png differ
diff --git a/.pr/library-stylesheet/after-phone.png b/.pr/library-stylesheet/after-phone.png
new file mode 100644
index 0000000000..75443bb6b6
Binary files /dev/null and b/.pr/library-stylesheet/after-phone.png differ
diff --git a/.pr/library-stylesheet/before-desktop.png b/.pr/library-stylesheet/before-desktop.png
new file mode 100644
index 0000000000..8f061052c4
Binary files /dev/null and b/.pr/library-stylesheet/before-desktop.png differ
diff --git a/.pr/library-stylesheet/before-phone.png b/.pr/library-stylesheet/before-phone.png
new file mode 100644
index 0000000000..63807be8f5
Binary files /dev/null and b/.pr/library-stylesheet/before-phone.png differ
diff --git a/.pr/library-stylesheet/host/before.html b/.pr/library-stylesheet/host/before.html
new file mode 100644
index 0000000000..ffd1d588fb
--- /dev/null
+++ b/.pr/library-stylesheet/host/before.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-before.js"></script></body></html>
diff --git a/.pr/library-stylesheet/host/host-before.js b/.pr/library-stylesheet/host/host-before.js
new file mode 100644
index 0000000000..f6b955e876
--- /dev/null
+++ b/.pr/library-stylesheet/host/host-before.js
@@ -0,0 +1,15 @@
+// Baseline host: main documents no stylesheet import, so the host mounts the
+// library exactly as docs/DEVELOPMENT.md describes.
+import React from "react";
+import { createRoot } from "react-dom/client";
+import { AgentServerUIProviders } from "@openhands/agent-canvas";
+const h = React.createElement;
+function App() {
+ const [count, setCount] = React.useState(0);
+ return h(AgentServerUIProviders, { analytics: false, styleOverrides: { "--oh-color-base": "#101820" } },
+ h("div", { id: "probe", className: "flex flex-col gap-4 p-6 bg-canvas-base text-foreground rounded-xl" },
+ h("span", { id: "a" }, "Probe A (flex column, gap-4, p-6, bg-canvas-base)"),
+ h("span", { id: "b" }, "Probe B"),
+ h("button", { id: "inside", className: "px-4 py-2 rounded-md bg-primary text-on-primary", onClick: () => setCount((v) => v + 1) }, "Inside Canvas " + count)));
+}
+createRoot(document.getElementById("root")).render(h(App));
diff --git a/.pr/library-stylesheet/host/host.js b/.pr/library-stylesheet/host/host.js
new file mode 100644
index 0000000000..9052a90f61
--- /dev/null
+++ b/.pr/library-stylesheet/host/host.js
@@ -0,0 +1,14 @@
+import React from "react";
+import { createRoot } from "react-dom/client";
+import { AgentServerUIProviders } from "@openhands/agent-canvas";
+import "@openhands/agent-canvas/styles.css";
+const h = React.createElement;
+function App() {
+ const [count, setCount] = React.useState(0);
+ return h(AgentServerUIProviders, { analytics: false, styleOverrides: { "--oh-color-base": "#101820" } },
+ h("div", { id: "probe", className: "flex flex-col gap-4 p-6 bg-canvas-base text-foreground rounded-xl" },
+ h("span", { id: "a" }, "Probe A (flex column, gap-4, p-6, bg-canvas-base)"),
+ h("span", { id: "b" }, "Probe B"),
+ h("button", { id: "inside", className: "px-4 py-2 rounded-md bg-primary text-on-primary", onClick: () => setCount((v) => v + 1) }, "Inside Canvas " + count)));
+}
+createRoot(document.getElementById("root")).render(h(App));
diff --git a/.pr/library-stylesheet/host/index.html b/.pr/library-stylesheet/host/index.html
new file mode 100644
index 0000000000..cdba9cf7c2
--- /dev/null
+++ b/.pr/library-stylesheet/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/library-stylesheet/host/package.json b/.pr/library-stylesheet/host/package.json
new file mode 100644
index 0000000000..bcca82ec61
--- /dev/null
+++ b/.pr/library-stylesheet/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/library-stylesheet/host/vite.config.mjs b/.pr/library-stylesheet/host/vite.config.mjs
new file mode 100644
index 0000000000..35aa9f509c
--- /dev/null
+++ b/.pr/library-stylesheet/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/library-stylesheet/probe.js b/.pr/library-stylesheet/probe.js
new file mode 100644
index 0000000000..0c4e247f32
--- /dev/null
+++ b/.pr/library-stylesheet/probe.js
@@ -0,0 +1 @@
+(()=>{const p=document.getElementById('probe'),b=document.getElementById('inside'),o=document.getElementById('outside');if(!p)return JSON.stringify({error:document.getElementById('module-error').textContent||'no probe'});const s=getComputedStyle(p),bs=getComputedStyle(b),os=getComputedStyle(o);return JSON.stringify({probe:{display:s.display,flexDirection:s.flexDirection,gap:s.rowGap,padding:s.padding,background:s.backgroundColor,radius:s.borderRadius,color:s.color},button:{padding:bs.padding,background:bs.backgroundColor,radius:bs.borderRadius},outsideH1:{fontFamily:os.fontFamily,fontSize:os.fontSize,margin:os.margin,color:os.color},bodyBg:getComputedStyle(document.body).backgroundColor,scopeVar:getComputedStyle(document.querySelector('[data-agent-server-ui]')).getPropertyValue('--oh-color-base'),sheets:[...document.styleSheets].map(x=>x.href||(x.ownerNode&&(x.ownerNode.id||x.ownerNode.getAttribute('data-vite-dev-id')))||'inline'),moduleError:document.getElementById('module-error').textContent})})()
diff --git a/README.md b/README.md
index afd6c2ba0a..9416a236e0 100644
--- a/README.md
+++ b/README.md
@@ -175,5 +175,5 @@ The Agent Server API is implemented by the SDK and consumed through the TypeScri
- [Documentation index](./docs/README.md)
- [Architecture overview](./docs/architecture.md)
-- [Development guide](./docs/DEVELOPMENT.md)
+- [Development guide](./docs/DEVELOPMENT.md), including [embedding Canvas components in a host app](./docs/DEVELOPMENT.md#css-isolation-and-host-app-customization) (load `@openhands/agent-canvas/styles.css` once next to the component imports)
- [Self-hosting guide](./docs/SELF_HOSTING.md)
diff --git a/__tests__/package-library.test.ts b/__tests__/package-library.test.ts
index a4013e24e1..e2436777a9 100644
--- a/__tests__/package-library.test.ts
+++ b/__tests__/package-library.test.ts
@@ -12,6 +12,7 @@ const packageJson = JSON.parse(
module: string;
types: string;
exports: Record<string, unknown>;
+ sideEffects?: unknown;
scripts: Record<string, string>;
dependencies?: Record<string, string>;
devDependencies?: Record<string, string>;
@@ -57,7 +58,11 @@ describe("package library metadata", () => {
import: "./dist/i18n/index.js",
require: "./dist/i18n/index.cjs",
},
+ "./styles.css": "./dist/styles.css",
});
+ // A `sideEffects` list would let bundlers drop `import ".../styles.css"`
+ // unless it names the stylesheet.
+ expect(packageJson.sideEffects).toBeUndefined();
});
// Git dependencies break `npm install -g` because npm clones the repo and
diff --git a/__tests__/vite-config.test.ts b/__tests__/vite-config.test.ts
index 46b86001ee..84118a49fb 100644
--- a/__tests__/vite-config.test.ts
+++ b/__tests__/vite-config.test.ts
@@ -5,6 +5,7 @@ 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 { Script } from "node:vm";
import { afterEach, describe, expect, it } from "vitest";
afterEach(() => {
@@ -149,6 +150,46 @@ describe("vite library build", () => {
]),
);
});
+
+ it("emits the scoped Canvas stylesheet and a parseable CJS entry", async () => {
+ process.env.BUILD_LIB = "true";
+ const config = await viteConfig({ mode: "production", command: "build" });
+ const outputs = config.build?.rollupOptions?.output;
+ const cjsOutput = (Array.isArray(outputs) ? outputs : [outputs]).find(
+ (output) => output?.format === "cjs",
+ );
+ if (!cjsOutput) throw new Error("Expected a CJS library output");
+ const built = await build({
+ ...config,
+ configFile: false,
+ logLevel: "error",
+ build: {
+ ...config.build,
+ sourcemap: false,
+ write: false,
+ rollupOptions: { ...config.build?.rollupOptions, output: [cjsOutput] },
+ },
+ });
+ const [result] = Array.isArray(built) ? built : [built];
+ if (!("output" in result))
+ throw new Error("Expected a completed library build");
+ const file = (fileName: string) => {
+ const item = result.output.find((entry) => entry.fileName === fileName);
+ if (!item) throw new Error(`Missing ${fileName}`);
+ return String(item.type === "asset" ? item.source : item.code);
+ };
+
+ const css = file("styles.css");
+ // Scoped to the Canvas root so it never restyles the host page.
+ expect(css).toContain("[data-agent-server-ui] .flex{display:flex}");
+ expect(css).not.toMatch(/(^|[{},])\.flex\{/);
+ expect(css).toContain("[data-agent-server-ui] .xterm");
+ expect(css).toContain("fonts.googleapis.com");
+
+ // `package.json` routes `require` here; stripped CSS imports must not
+ // leave it unparseable.
+ expect(() => new Script(file("index.cjs"))).not.toThrow();
+ }, 180000);
});
it("emits browser-compatible ESM when a bundled CommonJS dependency requires a React peer", async () => {
diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md
index 656c247c30..1d8b8065a4 100644
--- a/docs/DEVELOPMENT.md
+++ b/docs/DEVELOPMENT.md
@@ -420,6 +420,15 @@ The standalone app and the exported provider/root wrapper now scope all bundled
### Embedding strategy
+- Load the Canvas stylesheet once in the host app, next to the component imports:
+
+ ```tsx
+ import "@openhands/agent-canvas/styles.css";
+ import { AgentServerUIProviders } from "@openhands/agent-canvas";
+ ```
+
+ `npm run build:lib` emits it as `dist/styles.css`. It holds the Tailwind, HeroUI, xterm, and app CSS for every exported component, scoped under `[data-agent-server-ui]`, and it `@import`s the Outfit and IBM Plex Mono fonts from Google Fonts. The JavaScript entries do not import it, so a host without a CSS loader (server rendering, tests) can still import the components. Without the stylesheet the components render unstyled and `styleOverrides` has no visible effect.
+
- Use `AgentServerUIProviders` in host apps. It renders a scoped style root by default.
- For direct wrapper control, use `AgentServerUIRoot`.
- The standalone app opts out of the provider wrapper because the router layout already renders the scoped root.
diff --git a/package.json b/package.json
index 794d6609e6..c457badde2 100644
--- a/package.json
+++ b/package.json
@@ -249,6 +249,7 @@
"import": "./dist/i18n/index.js",
"require": "./dist/i18n/index.cjs"
},
+ "./styles.css": "./dist/styles.css",
"./package.json": "./package.json"
},
"peerDependencies": {
diff --git a/src/index.ts b/src/index.ts
index 8cd5167d1c..204b6b7b8d 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -1 +1,5 @@
+// Keep this a single CSS import: Vite's CJS output turns adjacent stripped CSS
+// requires into a dangling comma (getEmptyChunkReplacer).
+import "./styles.css";
+
export * from "./lib";
diff --git a/src/styles.css b/src/styles.css
new file mode 100644
index 0000000000..d980eedffb
--- /dev/null
+++ b/src/styles.css
@@ -0,0 +1,4 @@
+/* The library stylesheet entry (dist/styles.css). index.css comes first so its
+ font @imports stay at the top of the bundled file. */
+@import "./index.css";
+@import "./tailwind.css";
diff --git a/vite.config.ts b/vite.config.ts
index 41bea69ee6..5f9c6cf589 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -232,6 +232,8 @@ export default defineConfig(({ mode }) => {
lib: {
entry: LIB_ENTRY,
formats: ["es"],
+ // Exported as @openhands/agent-canvas/styles.css.
+ cssFileName: "styles",
},
rollupOptions: {
output: [
@@ -241,7 +243,6 @@ export default defineConfig(({ mode }) => {
preserveModulesRoot: "src",
entryFileNames: "[name].js",
chunkFileNames: "chunks/[name]-[hash].js",
- assetFileNames: "assets/[name]-[hash][extname]",
},
{
format: "cjs",
@@ -249,7 +250,6 @@ export default defineConfig(({ mode }) => {
preserveModulesRoot: "src",
entryFileNames: "[name].cjs",
chunkFileNames: "chunks/[name]-[hash].cjs",
- assetFileNames: "assets/[name]-[hash][extname]",
exports: "named",
},
],