The open-source agent harness - the runtime layer that turns an LLM into a working agent.
Refactor SDK styling and theming integration (#142)
Govinda Vashishtha0d71e2c4647f
diff --git a/packages/frontend/src/index.css b/packages/frontend/src/index.cssindex 67725dc09..66e570b18 100644--- a/packages/frontend/src/index.css+++ b/packages/frontend/src/index.css@@ -1,8 +1,5 @@-/* The SDK ships utilities and theme tokens but no reset. Preflight goes in its- own layer: unlayered it would outrank `tfy-agent-ui-utilities` and strip the- SDK's own margin, padding and border. */+/* Host Tailwind for this app's chrome. SDK styles inject via ThemeProvider. */@import 'tailwindcss';-@import '@truefoundry/trueforge-ui/styles.css';html,body,@@ -11,8 +8,8 @@ body,}body {- color: var(--foreground);- background: var(--background);+ color: #09090b;+ background: #fff;}.app-root {@@ -29,11 +26,11 @@ body {display: grid;place-items: center;padding: 2rem;- color: var(--muted-foreground);+ color: #71717a;}.boot-screen[data-error='true'] {- color: var(--destructive);+ color: #ef4444;}.harness-logout {diff --git a/packages/trueforge-ui-sdk/CHANGELOG.md b/packages/trueforge-ui-sdk/CHANGELOG.mdindex f8617846f..7ef51be19 100644--- a/packages/trueforge-ui-sdk/CHANGELOG.md+++ b/packages/trueforge-ui-sdk/CHANGELOG.md@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Changed++- **Styles auto-inject** — `ThemeProvider` injects the SDK stylesheet at runtime.+ Hosts no longer need `@import '@truefoundry/trueforge-ui/styles.css'` (export+ kept for SSR). Semantic tokens and dark mode are scoped to `.aui-theme-root`+ (no `html.dark` / `:root` retheme of the host page).+### Fixed- **History row mutability** — prefer `custom.isMutable` from the session (runtimediff --git a/packages/trueforge-ui-sdk/README.md b/packages/trueforge-ui-sdk/README.mdindex 1aa58d1f3..a9cbfbb59 100644--- a/packages/trueforge-ui-sdk/README.md+++ b/packages/trueforge-ui-sdk/README.md@@ -51,7 +51,19 @@ pnpm add @truefoundry/trueforge-uiyarn add @truefoundry/trueforge-ui```-`react` / `react-dom` are required peers. Import the stylesheet after Tailwind in the host:+`react` / `react-dom` are required peers. The **host app must have+[Tailwind CSS](https://tailwindcss.com/) set up** (v4 recommended) so preflight+and your app chrome work alongside the SDK. In the host stylesheet:++```css+@import 'tailwindcss';+```++SDK styles (tokens, utilities, OpenUI) load automatically when `TrueforgeUI` /+`ThemeProvider` mounts — you do **not** need to import the SDK stylesheet for+client-only apps.++Optional (SSR / explicit load order):```css@import 'tailwindcss';@@ -460,7 +472,7 @@ See [docs/server.md](./docs/server.md) for the full method list and BYO guidance| `SlotsProvider`, `useSlot`, `useTheme` | API | Overrides + theme mode || `AgentUIServer`, `AgentChatServer`, `AgentBuilderServer` | Types | Resolved server contract || `ThemeConfig`, `LayoutProp`, `SlotOverrides`, `AgentSpec`, … | Types | Configuration contracts |-| `@truefoundry/trueforge-ui/styles.css` | CSS | Tokens, utilities, OpenUI |+| `@truefoundry/trueforge-ui/styles.css` | CSS | Optional; auto-injected by `ThemeProvider` || `@truefoundry/trueforge-ui/assistant-ui` | Entry | Shared `useAui` / `useAuiState` (single instance) |Curated public API: [docs/api.md](./docs/api.md).diff --git a/packages/trueforge-ui-sdk/docs/api.md b/packages/trueforge-ui-sdk/docs/api.mdindex 83c2cc452..5ce2e81d7 100644--- a/packages/trueforge-ui-sdk/docs/api.md+++ b/packages/trueforge-ui-sdk/docs/api.md@@ -48,6 +48,6 @@ re-exports override **types** only where needed.## Styles-| Export path | Notes |-| -------------------------------------- | --------------------------- |-| `@truefoundry/trueforge-ui/styles.css` | Tokens + utilities + OpenUI |+| Export path | Notes |+| -------------------------------------- | ----------------------------------------------------- |+| `@truefoundry/trueforge-ui/styles.css` | Tokens + utilities + OpenUI (optional; auto-injected) |diff --git a/packages/trueforge-ui-sdk/docs/architecture.md b/packages/trueforge-ui-sdk/docs/architecture.mdindex 5a27825af..a410c9caa 100644--- a/packages/trueforge-ui-sdk/docs/architecture.md+++ b/packages/trueforge-ui-sdk/docs/architecture.md@@ -45,8 +45,9 @@ provider. See [customization.md](./customization.md) for the keep-list.## Theming-Default atoms use CSS variables from `styles.css`. Override colours in host-`:root` / `.dark` after importing the SDK stylesheet, or via `theme.tokens`.+Default atoms use CSS variables from the auto-injected stylesheet (scoped to+`.aui-theme-root`). Override colours via `theme.tokens` or host CSS on+`.aui-theme-root` / `.aui-theme-root.dark`.## Errorsdiff --git a/packages/trueforge-ui-sdk/docs/theming.md b/packages/trueforge-ui-sdk/docs/theming.mdindex de6cf4981..0b11fc3bc 100644--- a/packages/trueforge-ui-sdk/docs/theming.md+++ b/packages/trueforge-ui-sdk/docs/theming.md@@ -493,8 +493,9 @@ no longer depends on tfy.## Migration notes (for consumers)- Remove `@import "tfy-web-components/theme.css"`.-- Only `@import "@truefoundry/trueforge-ui/styles.css"` (+ host Tailwind- preflight as today).+- Styles auto-inject from `ThemeProvider` (optional+ `@import "@truefoundry/trueforge-ui/styles.css"` for SSR). Tokens are scoped+ to `.aui-theme-root` — the host document is not rethemed.- Revisit `overrides` for `Button` / `IconButton` / bubbles (new props).- Prefer`theme={{ preset, tokens, brand, icons, className, classNames }}`diff --git a/packages/trueforge-ui-sdk/embedCssPlugin.mjs b/packages/trueforge-ui-sdk/embedCssPlugin.mjsnew file mode 100644index 000000000..f74688d9d--- /dev/null+++ b/packages/trueforge-ui-sdk/embedCssPlugin.mjs@@ -0,0 +1,26 @@+import { existsSync, readFileSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const packageRoot = path.dirname(fileURLToPath(import.meta.url));+const stylesPath = path.join(packageRoot, 'dist', 'styles.css');+const embeddedStylesFile = path.join(packageRoot, 'src', 'theme', 'embeddedStyles.ts');++/** esbuild/tsup plugin: replace `embeddedStyles.ts` with minified `dist/styles.css`. */+export function embedCssPlugin() {+ return {+ name: 'trueforge-ui-embed-css',+ setup(build) {+ build.onLoad({ filter: /[/\\]embeddedStyles\.ts$/ }, args => {+ if (path.resolve(args.path) !== embeddedStylesFile) {+ return null;+ }+ const css = existsSync(stylesPath) ? readFileSync(stylesPath, 'utf8') : '';+ return {+ contents: `export const EMBEDDED_STYLES = ${JSON.stringify(css)};\n`,+ loader: 'ts',+ };+ });+ },+ };+}diff --git a/packages/trueforge-ui-sdk/example/README.md b/packages/trueforge-ui-sdk/example/README.mdindex 61e7a4aa7..f5067b638 100644--- a/packages/trueforge-ui-sdk/example/README.md+++ b/packages/trueforge-ui-sdk/example/README.md@@ -15,7 +15,8 @@ yarn build`link:..` symlinks the SDK so example picks up a fresh `dist/` after each`yarn build`. Re-run `yarn` in `example/` if the link is missing. The exampleimports Tailwind via `@tailwindcss/vite` (`@import "tailwindcss"` in-`src/index.css`) for preflight, since the SDK does not ship it.+`src/index.css`) for host preflight and chrome utilities; SDK styles inject+from `ThemeProvider`.2. Configure env:diff --git a/packages/trueforge-ui-sdk/example/src/index.css b/packages/trueforge-ui-sdk/example/src/index.cssindex af77353c8..57e283a2c 100644--- a/packages/trueforge-ui-sdk/example/src/index.css+++ b/packages/trueforge-ui-sdk/example/src/index.css@@ -1,6 +1,4 @@@import 'tailwindcss';-@import '@truefoundry/trueforge-ui/styles.css';-*,*::before,*::after {@@ -15,12 +13,9 @@ body,}body {- font-family: var(--font-agent-ui, ui-sans-serif, system-ui, sans-serif);- background: var(--background, #fff);-}--.dark body {- background: var(--background, #0a0a0a);+ font-family: ui-sans-serif, system-ui, sans-serif;+ background: #fff;+ color: #111827;}.missing-env {@@ -70,8 +65,8 @@ body {justify-content: space-between;gap: 0.5rem;padding: 0.5rem 0.75rem;- border-bottom: 1px solid var(--border, #e5e7eb);- background: var(--background, #fff);+ border-bottom: 1px solid #e5e7eb;+ background: #fff;flex-shrink: 0;}@@ -86,7 +81,7 @@ body {border: 1px solid transparent;border-radius: 0.375rem;background: transparent;- color: var(--muted-foreground, #6b7280);+ color: #6b7280;cursor: pointer;font: inherit;font-size: 0.8125rem;@@ -96,15 +91,15 @@ body {.layout-switcher__btn:hover,.theme-toggle:hover {- background: var(--muted, #f3f4f6);- color: var(--foreground, #111827);+ background: #f3f4f6;+ color: #111827;}.layout-switcher__btn.is-active,.theme-toggle[aria-pressed='true'] {- background: var(--muted, #f3f4f6);- border-color: var(--border, #e5e7eb);- color: var(--foreground, #111827);+ background: #f3f4f6;+ border-color: #e5e7eb;+ color: #111827;}.fake-host {@@ -113,12 +108,7 @@ body {height: 100%;padding: 2.5rem 2rem;background:- radial-gradient(- ellipse 80% 50% at 20% 0%,- color-mix(in oklab, var(--primary, #4f46e5) 12%, transparent),- transparent- ),- var(--muted, #f3f4f6);+ radial-gradient(ellipse 80% 50% at 20% 0%, color-mix(in oklab, #4f46e5 12%, transparent), transparent), #f3f4f6;}.fake-host__eyebrow {@@ -127,7 +117,7 @@ body {font-weight: 600;letter-spacing: 0.06em;text-transform: uppercase;- color: var(--muted-foreground, #6b7280);+ color: #6b7280;}.fake-host__title {@@ -135,7 +125,7 @@ body {font-size: 1.75rem;font-weight: 650;letter-spacing: -0.02em;- color: var(--foreground, #111827);+ color: #111827;}.fake-host__body {@@ -143,7 +133,7 @@ body {max-width: 28rem;font-size: 0.9375rem;line-height: 1.55;- color: var(--muted-foreground, #6b7280);+ color: #6b7280;}.embed-host {diff --git a/packages/trueforge-ui-sdk/package.json b/packages/trueforge-ui-sdk/package.jsonindex ad5389b22..45a63d641 100644--- a/packages/trueforge-ui-sdk/package.json+++ b/packages/trueforge-ui-sdk/package.json@@ -49,7 +49,7 @@"src/icons/registerAgentIcons.ts"],"scripts": {- "build": "tsup && tailwindcss --input src/build-styles.css --output dist/styles.css --minify",+ "build": "rm -rf dist && tailwindcss --input src/build-styles.css --output dist/styles.css --minify && tsup","dev:watch": "pnpm run \"/^(dev:watch:js|dev:watch:css)$/\"","dev:watch:js": "tsup --watch","dev:watch:css": "tailwindcss --input src/build-styles.css --output dist/styles.css --watch",diff --git a/packages/trueforge-ui-sdk/src/build-styles.css b/packages/trueforge-ui-sdk/src/build-styles.cssindex 8e66f913e..090d103ee 100644--- a/packages/trueforge-ui-sdk/src/build-styles.css+++ b/packages/trueforge-ui-sdk/src/build-styles.css@@ -9,4 +9,5 @@@import 'tailwindcss/utilities' layer(tfy-agent-ui-utilities);@import './styles.css';-@custom-variant dark (&:is(.dark *));+/* Match `.dark` on `.aui-theme-root` (not `html`) and its descendants. */+@custom-variant dark (&:is(.dark, .dark *));diff --git a/packages/trueforge-ui-sdk/src/containers/useResolvedServer.ts b/packages/trueforge-ui-sdk/src/containers/useResolvedServer.tsindex 16048e7f9..7d6372f7f 100644--- a/packages/trueforge-ui-sdk/src/containers/useResolvedServer.ts+++ b/packages/trueforge-ui-sdk/src/containers/useResolvedServer.ts@@ -4,13 +4,22 @@ import { createTrueFoundryAgentUIServer } from '@truefoundry/assistant-ui-runtimimport { useEffect, useState } from 'react';import type { TrueforgeBuiltInServerConfig, TrueforgeServerConfig } from '../server/TrueforgeServerConfig.js';-import type { AgentUIServer } from '../server/types.js';+import type { AgentBuilderCapabilitiesResponse, AgentUIServer, CatalogServer } from '../server/types.js';export type ResolvedServerState =| { status: 'loading'; server: null; error: null }| { status: 'ready'; server: AgentUIServer; error: null }| { status: 'error'; server: null; error: unknown };+/** Used when the runtime adapter has not shipped `getCapabilities` yet. */+const DEFAULT_CAPABILITIES = {+ data: {+ sandbox: { enabled: true },+ skill: { enabled: true },+ settings: { enabled: true },+ },+} satisfies AgentBuilderCapabilitiesResponse;+function isBuiltInConfig(config: TrueforgeServerConfig): config is TrueforgeBuiltInServerConfig {return (typeof config === 'object' &&@@ -20,6 +29,48 @@ function isBuiltInConfig(config: TrueforgeServerConfig): config is TrueforgeBuil);}+function hasGetCapabilities(+ server: object,+): server is { getCapabilities: () => Promise<AgentBuilderCapabilitiesResponse> } {+ return typeof Reflect.get(server, 'getCapabilities') === 'function';+}++/**+ * Runtime chat/builder objects are structurally an AgentUIServer once+ * `getCapabilities` is present. Catalog is optional host overlay.+ */+function toAgentUIServer(server: object, catalog: CatalogServer | undefined): AgentUIServer {+ const getCapabilities = hasGetCapabilities(server)+ ? () => server.getCapabilities()+ : async () => DEFAULT_CAPABILITIES;+ const withCapabilities = { ...server, getCapabilities };+ const withCatalog = catalog != null ? { ...withCapabilities, catalog } : withCapabilities;+ if (!isAgentUIServer(withCatalog)) {+ throw new Error('TrueforgeUI: runtime adapter returned an incomplete AgentUIServer');+ }+ return withCatalog;+}++function isAgentUIServer(value: object): value is AgentUIServer {+ return (+ typeof Reflect.get(value, 'createSession') === 'function' &&+ typeof Reflect.get(value, 'listSessions') === 'function' &&+ typeof Reflect.get(value, 'getSession') === 'function' &&+ typeof Reflect.get(value, 'updateSession') === 'function' &&+ typeof Reflect.get(value, 'createTurn') === 'function' &&+ typeof Reflect.get(value, 'cancelSession') === 'function' &&+ typeof Reflect.get(value, 'listTurns') === 'function' &&+ typeof Reflect.get(value, 'getTurn') === 'function' &&+ typeof Reflect.get(value, 'listEvents') === 'function' &&+ typeof Reflect.get(value, 'getCapabilities') === 'function' &&+ typeof Reflect.get(value, 'getModels') === 'function' &&+ typeof Reflect.get(value, 'getSkills') === 'function' &&+ typeof Reflect.get(value, 'getMcp') === 'function' &&+ typeof Reflect.get(value, 'searchAgents') === 'function' &&+ typeof Reflect.get(value, 'saveAgent') === 'function'+ );+}+/*** Resolves a {@link TrueforgeServerConfig} to an {@link AgentUIServer}.* - `AgentUIServer` — sync passthrough@@ -73,14 +124,18 @@ export function useResolvedServer(cpURL: controlPlaneURL,...(gatewayPlaneURL ? { gatewayURL: gatewayPlaneURL } : {}),})- .then(server => {+ .then(runtimeServer => {if (cancelled) return;- const resolved = server as unknown as AgentUIServer;- setState({- status: 'ready',- server: catalog != null ? ({ ...resolved, catalog } as AgentUIServer) : resolved,- error: null,- });+ try {+ setState({+ status: 'ready',+ server: toAgentUIServer(runtimeServer, catalog),+ error: null,+ });+ } catch (error: unknown) {+ onError?.(error);+ setState({ status: 'error', server: null, error });+ }}).catch((error: unknown) => {if (cancelled) return;diff --git a/packages/trueforge-ui-sdk/src/github-markdown-bridge.css b/packages/trueforge-ui-sdk/src/github-markdown-bridge.cssindex c25dff4cc..5996ee06a 100644--- a/packages/trueforge-ui-sdk/src/github-markdown-bridge.css+++ b/packages/trueforge-ui-sdk/src/github-markdown-bridge.css@@ -6,8 +6,8 @@** Source: github-markdown-css (auto theme variable blocks).*/-.dark .markdown-body,-[data-theme='dark'] .markdown-body {+.aui-theme-root.dark .markdown-body,+.aui-theme-root[data-theme='dark'] .markdown-body {/*dark */color-scheme: dark;--fgColor-accent: #4493f8;@@ -62,8 +62,8 @@--borderColor-neutral-muted: var(--borderColor-muted);}-:root:not(.dark) .markdown-body,-[data-theme='light'] .markdown-body {+.aui-theme-root:not(.dark) .markdown-body,+.aui-theme-root[data-theme='light'] .markdown-body {/*light */color-scheme: light;--fgColor-danger: #d1242f;diff --git a/packages/trueforge-ui-sdk/src/styles.css b/packages/trueforge-ui-sdk/src/styles.cssindex 9f470a225..7105981d1 100644--- a/packages/trueforge-ui-sdk/src/styles.css+++ b/packages/trueforge-ui-sdk/src/styles.css@@ -2,39 +2,13 @@* Tailwind authoring source for @truefoundry/trueforge-ui.** The package build compiles this file through `build-styles.css` into the- * public `dist/styles.css` artifact. Consumers must import that artifact,- * rather than compiling this source in their own Tailwind pipeline.+ * public `dist/styles.css` artifact. `ThemeProvider` injects that stylesheet+ * at runtime — hosts do not need a CSS import. The `styles.css` export remains+ * for SSR / explicit control.*- * ── Quick start ──────────────────────────────────────────────────────- *- * @import "@truefoundry/trueforge-ui/styles.css";- *- * That's the entire styling setup. Everything below is pulled in for you:- *- * 1. OpenUI stylesheet + Tailwind `@source` scanning for this SDK's own- * compiled components.- *- * 2. GitHub Markdown styles (`github-markdown-css`) for `.markdown-body`.- *- * 3. Owned palette + shadcn-style semantic tokens (`--background`,- * `--muted`, `--primary`, …) in light and dark.- *- * ── Overriding colours ───────────────────────────────────────────────- *- * Palette colours:- *- * :root { --color-indigo-500: #000; }- *- * Semantic tokens (used by this SDK's atoms):- *- * :root { --background: #fff; --primary: #e11d48; }- *- * Or via the theme object: `theme={{ tokens: { primary: "#e11d48" } }}`.- * Scrollbar thumb: `theme={{ tokens: { scrollbarThumb: "#a1a1aa" } }}` or- * `--scrollbar-thumb` in host CSS. Track stays transparent; thumb is the plug.- *- * Both work because the `@layer` block below has the lowest precedence —- * any plain `:root` / `.aui-root` declaration in the consumer's CSS wins.+ * Tokens live on `.aui-theme-root` (light) and `.aui-theme-root.dark` so the+ * host document is not rethemed. Override via host CSS on `.aui-theme-root` or+ * `theme={{ tokens: { primary: "#e11d48" } }}`.*/@import './openui.css';@@ -47,12 +21,12 @@@import './github-markdown-bridge.css';/* ──────────────────────────────────────────────────────────────────────- * Owned palette (minimal set used by semantic tokens + gray utilities).- * Light values on :root; dark mode flips the same var names under .dark- * (matches prior tfy ThemeProvider injectThemes behaviour).+ * Owned palette scoped to `.aui-theme-root` so host `:root` / `html.dark`+ * are untouched. ThemeProvider toggles `.dark` on this root.* ──────────────────────────────────────────────────────────────────── */@layer tfy-agent-ui-base {- :root {+ .aui-theme-root {+ box-sizing: border-box;--color-white: #ffffff;--color-black: #09090b;--color-gray-100: #f4f4f5;@@ -105,7 +79,13 @@--assistant-bubble-foreground: var(--foreground);}- .dark {+ .aui-theme-root *,+ .aui-theme-root *::before,+ .aui-theme-root *::after {+ box-sizing: border-box;+ }++ .aui-theme-root.dark {--color-gray-100: #101013;--color-gray-125: #141417;--color-gray-150: #18181b;diff --git a/packages/trueforge-ui-sdk/src/theme/ThemeProvider.tsx b/packages/trueforge-ui-sdk/src/theme/ThemeProvider.tsxindex 32e0e9db7..758817c52 100644--- a/packages/trueforge-ui-sdk/src/theme/ThemeProvider.tsx+++ b/packages/trueforge-ui-sdk/src/theme/ThemeProvider.tsx@@ -13,6 +13,7 @@ import {} from 'react';import { cn } from '../atoms/lib/cn.js';+import { ensureStyles } from './ensureStyles.js';import { resolvePresetTokens } from './presets/index.js';import {TOKEN_CSS_VARS,@@ -69,11 +70,6 @@ function readStoredPreference(): ThemeMode {return 'system';}-function applyDarkClass(mode: 'light' | 'dark') {- if (typeof document === 'undefined') return;- document.documentElement.classList.toggle('dark', mode === 'dark');-}-function tokensToStyle(tokens: Partial<SemanticTokens> | undefined): CSSProperties {if (!tokens) return {};const style: Record<string, string> = {};@@ -89,19 +85,19 @@ export function ThemeProvider({ theme, children }: { theme?: ThemeConfig; childrconst [preference, setPreference] = useState<ThemeMode>(() => theme?.mode ?? readStoredPreference());const [mode, setMode] = useState<'light' | 'dark'>(() => resolveMode(theme?.mode ?? readStoredPreference()));+ useLayoutEffect(() => {+ ensureStyles();+ }, []);+useLayoutEffect(() => {if (theme?.mode !== undefined) {setPreference(theme.mode);- const resolved = resolveMode(theme.mode);- setMode(resolved);- applyDarkClass(resolved);+ setMode(resolveMode(theme.mode));return;}const stored = readStoredPreference();- const resolved = resolveMode(stored);setPreference(stored);- setMode(resolved);- applyDarkClass(resolved);+ setMode(resolveMode(stored));}, [theme?.mode]);useEffect(() => {@@ -111,9 +107,7 @@ export function ThemeProvider({ theme, children }: { theme?: ThemeConfig; childrconst mq = window.matchMedia('(prefers-color-scheme: dark)');const onChange = () => {if (preference !== 'system') return;- const resolved = getSystemTheme();- setMode(resolved);- applyDarkClass(resolved);+ setMode(getSystemTheme());};mq.addEventListener('change', onChange);return () => mq.removeEventListener('change', onChange);@@ -122,10 +116,8 @@ export function ThemeProvider({ theme, children }: { theme?: ThemeConfig; childrconst setTheme = useCallback((next: ThemeMode) => {if (isControlled) return;- const resolved = resolveMode(next);setPreference(next);- setMode(resolved);- applyDarkClass(resolved);+ setMode(resolveMode(next));try {localStorage.setItem(STORAGE_KEY, next);} catch {@@ -158,7 +150,7 @@ export function ThemeProvider({ theme, children }: { theme?: ThemeConfig; childrreturn (<ThemeContext.Provider value={value}><div- className={cn('aui-theme-root h-full min-h-0', theme?.className)}+ className={cn('aui-theme-root h-full min-h-0', mode === 'dark' && 'dark', theme?.className)}data-theme={mode}data-preset={theme?.preset ?? 'truefoundry'}style={rootStyle}diff --git a/packages/trueforge-ui-sdk/src/theme/embeddedStyles.ts b/packages/trueforge-ui-sdk/src/theme/embeddedStyles.tsnew file mode 100644index 000000000..c4df27b50--- /dev/null+++ b/packages/trueforge-ui-sdk/src/theme/embeddedStyles.ts@@ -0,0 +1,6 @@+/**+ * Build-time placeholder. The tsup `embed-css` plugin replaces this module with+ * the contents of `dist/styles.css` so `ensureStyles` can inject without a host+ * CSS import. Source/tests see an empty string until CSS has been built.+ */+export const EMBEDDED_STYLES = '';diff --git a/packages/trueforge-ui-sdk/src/theme/ensureStyles.ts b/packages/trueforge-ui-sdk/src/theme/ensureStyles.tsnew file mode 100644index 000000000..cedcf1aa3--- /dev/null+++ b/packages/trueforge-ui-sdk/src/theme/ensureStyles.ts@@ -0,0 +1,20 @@+import { EMBEDDED_STYLES } from './embeddedStyles.js';++export const TRUEFORGE_UI_STYLE_ID = 'trueforge-ui-styles';++/**+ * Injects the published SDK stylesheet once into `document.head`.+ * No-ops when a host already loaded styles (same id) or when CSS was not+ * embedded (dev without a prior CSS build).+ */+export function ensureStyles(css: string = EMBEDDED_STYLES): void {+ if (typeof document === 'undefined') return;+ if (document.getElementById(TRUEFORGE_UI_STYLE_ID) != null) return;+ if (css.length === 0) return;++ const el = document.createElement('style');+ el.id = TRUEFORGE_UI_STYLE_ID;+ el.setAttribute('data-trueforge-ui', '');+ el.textContent = css;+ document.head.appendChild(el);+}diff --git a/packages/trueforge-ui-sdk/test/containers/useResolvedServer.test.tsx b/packages/trueforge-ui-sdk/test/containers/useResolvedServer.test.tsxindex f02ab694c..661af023a 100644--- a/packages/trueforge-ui-sdk/test/containers/useResolvedServer.test.tsx+++ b/packages/trueforge-ui-sdk/test/containers/useResolvedServer.test.tsx@@ -8,7 +8,19 @@ import { createMockAgentUIServer, createMockCatalog } from '../server/mockServervi.mock('@truefoundry/assistant-ui-runtime/plugins/truefoundry-agent-server-adapter', () => ({createTrueFoundryAgentUIServer: vi.fn(async () => ({createSession: vi.fn(),+ listSessions: vi.fn(),+ getSession: vi.fn(),+ updateSession: vi.fn(),+ createTurn: vi.fn(),+ cancelSession: vi.fn(),+ listTurns: vi.fn(),+ getTurn: vi.fn(),+ listEvents: vi.fn(),getModels: vi.fn(async () => []),+ getSkills: vi.fn(async () => []),+ getMcp: vi.fn(async () => []),+ searchAgents: vi.fn(async () => []),+ saveAgent: vi.fn(async () => ({})),})),}));@@ -54,6 +66,14 @@ describe('useResolvedServer', () => {cpURL: 'https://cp.example',gatewayURL: 'https://gw.example',});+ expect(result.current.server?.getCapabilities).toEqual(expect.any(Function));+ await expect(result.current.server?.getCapabilities()).resolves.toEqual({+ data: {+ sandbox: { enabled: true },+ skill: { enabled: true },+ settings: { enabled: true },+ },+ });});it('attaches an optional catalog onto the truefoundry server', async () => {@@ -71,5 +91,6 @@ describe('useResolvedServer', () => {expect(result.current.status).toBe('ready');});expect(result.current.server?.catalog).toBe(catalog);+ expect(result.current.server?.getCapabilities).toEqual(expect.any(Function));});});diff --git a/packages/trueforge-ui-sdk/test/packageExports.smoke.mjs b/packages/trueforge-ui-sdk/test/packageExports.smoke.mjsindex 1e0b03506..235c8fd81 100644--- a/packages/trueforge-ui-sdk/test/packageExports.smoke.mjs+++ b/packages/trueforge-ui-sdk/test/packageExports.smoke.mjs@@ -51,6 +51,16 @@ assert.equal(typeof assistantUi.useAuiState, 'function');const stylesPath = fileURLToPath(import.meta.resolve('@truefoundry/trueforge-ui/styles.css'));await access(stylesPath);++const { readdir, readFile } = await import('node:fs/promises');+const { dirname, join } = await import('node:path');+const packageDist = dirname(fileURLToPath(import.meta.resolve('@truefoundry/trueforge-ui')));+const jsFiles = (await readdir(packageDist)).filter(name => name.endsWith('.js'));+const embedded = await Promise.all(jsFiles.map(name => readFile(join(packageDist, name), 'utf8')));+assert.ok(+ embedded.some(source => source.includes('trueforge-ui-styles') && source.includes('--color-indigo-500')),+ 'Expected bundled JS to embed SDK stylesheet',+);`,);diff --git a/packages/trueforge-ui-sdk/test/theme/ThemeProvider.test.tsx b/packages/trueforge-ui-sdk/test/theme/ThemeProvider.test.tsxindex 107d5e14f..067d5e16e 100644--- a/packages/trueforge-ui-sdk/test/theme/ThemeProvider.test.tsx+++ b/packages/trueforge-ui-sdk/test/theme/ThemeProvider.test.tsx@@ -39,11 +39,25 @@ describe('ThemeProvider', () => {beforeEach(() => {localStorage.clear();document.documentElement.classList.remove('dark');+ document.getElementById('trueforge-ui-styles')?.remove();});afterEach(() => {vi.unstubAllGlobals();document.documentElement.classList.remove('dark');+ document.getElementById('trueforge-ui-styles')?.remove();+ });++ it('applies controlled dark mode on the theme root only', () => {+ const { container } = render(+ <ThemeProvider theme={{ mode: 'dark' }}>+ <ModeProbe />+ </ThemeProvider>,+ );+ expect(screen.getByTestId('mode')).toHaveTextContent('dark');+ expect(getThemeRoot(container)).toHaveClass('dark');+ expect(getThemeRoot(container)).toHaveAttribute('data-theme', 'dark');+ expect(document.documentElement).not.toHaveClass('dark');});it('requires a provider for useTheme', () => {@@ -73,7 +87,8 @@ describe('ThemeProvider', () => {screen.getByRole('button', { name: 'dark' }).click();});expect(screen.getByTestId('mode')).toHaveTextContent('dark');- expect(document.documentElement.classList.contains('dark')).toBe(true);+ expect(document.documentElement.classList.contains('dark')).toBe(false);+ expect(getThemeRoot(document.body).classList.contains('dark')).toBe(true);expect(localStorage.getItem('aui-theme-preference')).toBe('dark');});@@ -98,7 +113,7 @@ describe('ThemeProvider', () => {);localStorage.setItem('aui-theme-preference', 'system');- const { unmount } = render(+ const { unmount, container } = render(<ThemeProvider><ModeProbe /></ThemeProvider>,@@ -106,6 +121,7 @@ describe('ThemeProvider', () => {expect(screen.getByTestId('preference')).toHaveTextContent('system');expect(screen.getByTestId('mode')).toHaveTextContent('light');+ expect(getThemeRoot(container).classList.contains('dark')).toBe(false);systemDark = true;act(() => {@@ -113,7 +129,8 @@ describe('ThemeProvider', () => {});expect(screen.getByTestId('mode')).toHaveTextContent('dark');- expect(document.documentElement).toHaveClass('dark');+ expect(document.documentElement).not.toHaveClass('dark');+ expect(getThemeRoot(container).classList.contains('dark')).toBe(true);unmount();expect(removeEventListener).toHaveBeenCalledWith('change', expect.any(Function));diff --git a/packages/trueforge-ui-sdk/test/theme/ensureStyles.test.ts b/packages/trueforge-ui-sdk/test/theme/ensureStyles.test.tsnew file mode 100644index 000000000..3a6b074f0--- /dev/null+++ b/packages/trueforge-ui-sdk/test/theme/ensureStyles.test.ts@@ -0,0 +1,24 @@+// @vitest-environment jsdom+import { afterEach, describe, expect, it } from 'vitest';++import { ensureStyles, TRUEFORGE_UI_STYLE_ID } from '@/theme/ensureStyles.js';++describe('ensureStyles', () => {+ afterEach(() => {+ document.getElementById(TRUEFORGE_UI_STYLE_ID)?.remove();+ });++ it('injects a style tag once', () => {+ ensureStyles('.aui-theme-root{color:red}');+ ensureStyles('.aui-theme-root{color:blue}');++ const nodes = document.querySelectorAll(`#${TRUEFORGE_UI_STYLE_ID}`);+ expect(nodes).toHaveLength(1);+ expect(nodes[0]?.textContent).toBe('.aui-theme-root{color:red}');+ });++ it('no-ops when css is empty', () => {+ ensureStyles('');+ expect(document.getElementById(TRUEFORGE_UI_STYLE_ID)).toBeNull();+ });+});diff --git a/packages/trueforge-ui-sdk/tsup.config.ts b/packages/trueforge-ui-sdk/tsup.config.tsindex be7ecfa60..c1d41b039 100644--- a/packages/trueforge-ui-sdk/tsup.config.ts+++ b/packages/trueforge-ui-sdk/tsup.config.ts@@ -2,19 +2,24 @@* tsup build configuration for @truefoundry/trueforge-ui.** Produces an ESM-only bundle at `dist/index.js` (+ `.d.ts` + sourcemap).+ * CSS must be built first (`dist/styles.css`) so `embedCssPlugin` can inline it.*/import svgr from 'esbuild-plugin-svgr';import { defineConfig } from 'tsup';+import { embedCssPlugin } from './embedCssPlugin.mjs';+export default defineConfig({entry: ['src/index.ts', 'src/assistant-ui.ts'],format: ['esm'],dts: true,sourcemap: true,- // Watch mode must not wipe dist/styles.css (built by a sibling tailwind watcher).- clean: !process.argv.includes('--watch'),+ // `package.json` `build` clears dist then writes styles.css before tsup; do not+ // wipe that stylesheet here. Watch mode also keeps dist/styles.css from the CSS watcher.+ clean: false,target: 'es2022',esbuildPlugins: [+ embedCssPlugin(),svgr({icon: true,replaceAttrValues: {