Skip to content

The open-source agent harness - the runtime layer that turns an LLM into a working agent.

Update dependencies and enhance routing in TrueForge UI (#300)

Govinda Vashishtha9a4d1a752b1c
diff --git a/.changeset/20260817113112-trueforge-ui-with-router.md b/.changeset/20260817113112-trueforge-ui-with-router.md
new file mode 100644
index 000000000..3b3726608
--- /dev/null
+++ b/.changeset/20260817113112-trueforge-ui-with-router.md
@@ -0,0 +1,6 @@
+---
+'@truefoundry/trueforge-ui': minor
+'@truefoundry/trueforge': patch
+---
+
+Add opt-in `withRouter` URL sync for shell places (`/`, `/agents/:agentName`, `/sessions/:sessionId`, `/settings`), with path customization via `routes` and `react-router-dom` as an optional peer. Serve the app shell for client-side deep links from the TrueForge server.
diff --git a/packages/frontend/package.json b/packages/frontend/package.json
index ae3a3cfde..f88499702 100644
--- a/packages/frontend/package.json
+++ b/packages/frontend/package.json
@@ -31,8 +31,9 @@
"@truefoundry/trueforge-sdk": "workspace:*",
"@truefoundry/trueforge-ui": "workspace:*",
"monaco-editor": "^0.52.0",
+ "react": "^19.2.4",
"react-dom": "^19.2.4",
- "react": "^19.2.4"
+ "react-router-dom": "^7.18.2"
},
"devDependencies": {
"@types/react": "^19.2.17",
diff --git a/packages/frontend/src/App.tsx b/packages/frontend/src/App.tsx
index 1e417d9eb..41db8fbbc 100644
--- a/packages/frontend/src/App.tsx
+++ b/packages/frontend/src/App.tsx
@@ -150,6 +150,7 @@ export function App() {
},
}}
layout="sidebar"
+ withRouter
agentConfig={{
mode: 'AgentLibraryWithComposer',
defaultAgentSpec: boot.defaultAgentSpec,
diff --git a/packages/trueforge-ui/docs/customization.md b/packages/trueforge-ui/docs/customization.md
index 326a9b393..1b24229ba 100644
--- a/packages/trueforge-ui/docs/customization.md
+++ b/packages/trueforge-ui/docs/customization.md
@@ -73,6 +73,58 @@ Public override surface (primitives stay theme/CSS — not slots):
`AgentStepsCard`, `ReasoningCard`, `AskUserPrompt`, `McpAuthPrompt`,
`ResumeUnavailable`
+## URL routing (`withRouter`)
+
+Opt in to browser-URL sync for shell navigation. Requires `react-router-dom`
+(v6 or v7) in the host; it is an optional peer and stays out of the bundle
+unless `withRouter` is set, so dock/widget embeds and hosts that own their own
+router should leave it off (the default).
+
+```tsx
+<TrueForgeUI server={server} layout="sidebar" withRouter />
+```
+
+Places mirrored to the URL:
+
+- `/` — new chat / library landing (mode-dependent)
+- `/agents/:agentName` — immutable "Try" of a library agent
+- `/sessions/:sessionId` — a specific chat session
+- `/settings` — settings overlay (closing navigates to the chat place below it)
+
+Customize the paths (only honored when `withRouter`). Set any entry to `false`
+to keep that place overlay-only with no URL:
+
+```tsx
+<TrueForgeUI
+ server={server}
+ withRouter
+ routes={{
+ basename: '/app',
+ paths: { session: '/chats/:sessionId', settings: false },
+ }}
+/>
+```
+
+Custom `agent` / `session` templates must keep their `:param` segment, or the
+place can be written to the URL but not read back.
+
+Shell state stays the source of truth; the router mirrors it. Combining
+`withRouter` with `initialSessionId` is not supported — the URL wins.
+
+Notes on behaviour:
+
+- Only the pathname is owned; query string and hash are preserved across
+ navigation, so host state in `?…` survives switching sessions.
+- A `/sessions/:sessionId` link is resolved through `getSession` so the chat
+ opens with its own agent binding and mutability rather than as a new draft.
+- Unrecognized paths (and malformed escapes) normalize to the root place.
+- A URL naming a place the host cannot honor (e.g. `/agents/x` without the
+ agent library, or `/settings` when the settings capability is disabled) is
+ left in the address bar until the next navigation corrects it.
+
+Hosts serving the SDK must send the app shell for unknown paths (SPA
+fallback), otherwise deep links 404 before React boots.
+
## Custom layout
Pass a React component as `layout` to own chrome; compose exported
diff --git a/packages/trueforge-ui/package.json b/packages/trueforge-ui/package.json
index b04b2d05d..606dc59a6 100644
--- a/packages/trueforge-ui/package.json
+++ b/packages/trueforge-ui/package.json
@@ -78,7 +78,8 @@
"@assistant-ui/react": "^0.14.24",
"@types/react": "*",
"react": "^18 || ^19",
- "react-dom": "^18 || ^19"
+ "react-dom": "^18 || ^19",
+ "react-router-dom": "^6 || ^7"
},
"peerDependenciesMeta": {
"@assistant-ui/core": {
@@ -89,6 +90,9 @@
},
"@types/react": {
"optional": true
+ },
+ "react-router-dom": {
+ "optional": true
}
},
"dependencies": {
@@ -98,6 +102,7 @@
"@openuidev/react-lang": "^0.2.9",
"@openuidev/react-ui": "^0.13.2",
"@truefoundry/assistant-ui-runtime": "0.1.18",
+ "@truefoundry/trueforge-sdk": "workspace:*",
"clsx": "^2.1.1",
"lucide-react": "^0.562.0",
"monaco-editor": "^0.56.0",
@@ -106,7 +111,6 @@
"react-syntax-highlighter": "^16.1.1",
"remark-gfm": "^4.0.1",
"tailwind-merge": "^3.6.0",
- "@truefoundry/trueforge-sdk": "workspace:*",
"truefoundry-gateway-sdk": "^0.4.0",
"zod": "^4.4.3"
},
@@ -130,6 +134,7 @@
"prettier": "^3.6.2",
"react": "^19.2.4",
"react-dom": "^19.2.4",
+ "react-router-dom": "^7.18.2",
"tailwindcss": "^4.3.2",
"tsup": "^8.5.0",
"typescript": "^5.9.3",
diff --git a/packages/trueforge-ui/src/containers/TrueForgeUI.tsx b/packages/trueforge-ui/src/containers/TrueForgeUI.tsx
index fd868697e..dd43e7c84 100644
--- a/packages/trueforge-ui/src/containers/TrueForgeUI.tsx
+++ b/packages/trueforge-ui/src/containers/TrueForgeUI.tsx
@@ -1,194 +1,21 @@
'use client';
-import type { TrueFoundryAgentConfig, UseTrueFoundryAgentRuntimeOptions } from '@truefoundry/assistant-ui-runtime';
-import { lazy, Suspense, useMemo, type ReactNode } from 'react';
+import { lazy, Suspense, type ComponentType } from 'react';
-import { DraftCatalogProvider } from '../atoms/draft/DraftCatalogProvider.js';
-import { DraftSpecPreferenceBridge } from '../atoms/draft/DraftSpecPreferenceBridge.js';
-import { cn } from '../atoms/lib/cn.js';
-import { Spinner } from '../atoms/primitives/Spinner.js';
-import { ServerProvider } from '../server/ServerContext.js';
-import { DEFAULT_AGENT_CONFIG, ShellModeProvider, useShellMode, type AgentConfig } from '../server/ShellModeContext.js';
-import type { TrueForgeServerConfig } from '../server/TrueForgeServerConfig.js';
-import { SlotsProvider, type SlotOverrides } from '../theme/SlotsProvider.js';
-import type { LayoutProp, ThemeConfig } from '../theme/types.js';
-import { getErrorMessage } from '../utils/getErrorMessage.js';
+import { SlotsProvider } from '../theme/SlotsProvider.js';
import PostMcpOauthScreen from './McpOauthContainer/PostMcpOauthScreen.js';
-import { TrueFoundryChatProvider, type TrueFoundryChatProviderProps } from './TrueFoundryChatProvider.js';
-import { useResolvedServer } from './useResolvedServer.js';
+import { ServerInitLoader, TrueForgeUIShell, type TrueForgeUIProps } from './TrueForgeUIShell.js';
-const SidebarLayout = lazy(() => import('../layouts/SidebarLayout.js').then(m => ({ default: m.SidebarLayout })));
-const DrawerLayout = lazy(() => import('../layouts/DrawerLayout.js').then(m => ({ default: m.DrawerLayout })));
-const DockLayout = lazy(() => import('../layouts/DockLayout.js').then(m => ({ default: m.DockLayout })));
-const WidgetLayout = lazy(() => import('../layouts/WidgetLayout.js').then(m => ({ default: m.WidgetLayout })));
-
-export type ChatLayout = 'sidebar' | 'drawer' | 'dock' | 'widget';
+export type { RoutePlace, RoutesConfig } from '../routing/types.js';
export type { AgentConfig } from '../server/ShellModeContext.js';
export type { TrueForgeBuiltInServerConfig, TrueForgeServerConfig } from '../server/TrueForgeServerConfig.js';
export type { LayoutProp } from '../theme/types.js';
+export type { ChatLayout, TrueForgeUIProps } from './TrueForgeUIShell.js';
-type RuntimeAdapters = NonNullable<UseTrueFoundryAgentRuntimeOptions['adapters']>;
-
-export type TrueForgeUIProps = {
- server: TrueForgeServerConfig;
- /** Built-in layout string or a custom layout component. Defaults to `"sidebar"`. */
- layout?: LayoutProp;
- overrides?: SlotOverrides;
- theme?: ThemeConfig;
- className?: string;
- initialSessionId?: string;
- adapters?: RuntimeAdapters;
- onError?: (error: unknown) => void;
- /**
- * Agent / library / composer shell mode.
- * Defaults to `{ mode: "AgentLibraryWithComposer" }`.
- */
- agentConfig?: AgentConfig;
- /** Open settings on first paint only (host boot with no models configured). */
- initialSettingsOpen?: boolean;
-};
-
-function LayoutFallback({ className }: { className?: string }) {
- return (
- <div
- className={className}
- style={{
- height: '100%',
- minHeight: '12rem',
- background:
- 'linear-gradient(90deg, color-mix(in oklab, var(--secondary-bg) 55%, transparent) 25%, color-mix(in oklab, var(--secondary-bg) 25%, transparent) 50%, color-mix(in oklab, var(--secondary-bg) 55%, transparent) 75%)',
- backgroundSize: '200% 100%',
- animation: 'tfy-aui-pulse 1.2s ease-in-out infinite',
- }}
- aria-hidden
- />
- );
-}
-
-/** Shown while `type: "truefoundry"` resolves the agent UI server. */
-function ServerInitLoader({ className }: { className?: string }) {
- return (
- <div
- role="status"
- aria-live="polite"
- aria-busy="true"
- className={cn(
- 'flex h-full min-h-48 w-full flex-1 items-center justify-center bg-primary-bg text-text-secondary',
- className,
- )}
- >
- <Spinner size={28} className="text-text-primary" />
- <span className="sr-only">Loading</span>
- </div>
- );
-}
-
-function ServerInitError({ error, className }: { error: unknown; className?: string }) {
- const message = getErrorMessage(error, 'Failed to initialize server');
- return (
- <div
- role="alert"
- className={cn(
- 'flex h-full min-h-48 items-center justify-center bg-primary-bg px-6 text-center text-sm text-failure-bg',
- className,
- )}
- >
- {message}
- </div>
- );
-}
-
-function isBuiltInLayout(layout: LayoutProp): layout is ChatLayout {
- return layout === 'sidebar' || layout === 'drawer' || layout === 'dock' || layout === 'widget';
-}
-
-function BuiltInLayoutView({ layout, className }: { layout: ChatLayout; className?: string }) {
- switch (layout) {
- case 'sidebar':
- return <SidebarLayout className={className} />;
- case 'drawer':
- return <DrawerLayout className={className} />;
- case 'dock':
- return <DockLayout className={className} />;
- case 'widget':
- return <WidgetLayout className={className} />;
- }
-}
-
-function LayoutChildren({ layout, className }: { layout: LayoutProp; className?: string }) {
- if (isBuiltInLayout(layout)) {
- return (
- <Suspense fallback={<LayoutFallback className={className} />}>
- <BuiltInLayoutView layout={layout} className={className} />
- </Suspense>
- );
- }
- const HostLayout = layout;
- return <HostLayout className={className} />;
-}
-
-function ChatProviderFromShell({
- children,
- initialSessionId: hostInitialSessionId,
- ...providerRest
-}: {
- children: ReactNode;
-} & Omit<TrueFoundryChatProviderProps, 'agent' | 'agentName' | 'listSessionsAgentId' | 'children'>) {
- const { mode, runtimeKey, listSessionsAgentId, pendingSessionId } = useShellMode();
-
- // Freeze draft seed for the life of this runtimeKey so bindMutableAgent (identity /
- // instructions on shell) does not push a new defaultAgentSpec into the runtime.
- const draftDefaultAgentSpec = useMemo(() => {
- if (mode.status === 'active' && mode.isMutable) {
- return mode.agentSpec ?? { model: { name: 'openai-main/gpt-4.1' } };
- }
- return { model: { name: 'openai-main/gpt-4.1' } };
- // runtimeKey is the remount boundary for mutable chats.
- // eslint-disable-next-line react-hooks/exhaustive-deps -- intentionally keyed on runtimeKey only
- }, [runtimeKey]);
-
- const agent: TrueFoundryAgentConfig = useMemo(() => {
- // idle uses a placeholder draft so layout chrome (useAui) still mounts;
- // layouts render an empty CTA instead of the thread.
- if (mode.status === 'idle') {
- return {
- mode: 'draft',
- defaultAgentSpec: { model: { name: 'openai-main/gpt-4.1' } },
- };
- }
- // Runtime still uses named|draft; shell mutability maps onto that adapter.
- if (!mode.isMutable) {
- const agentName = mode.agentName ?? mode.agentId ?? pendingSessionId;
- if (agentName == null) {
- // Active immutable without identity should not happen; keep chrome mounted.
- return {
- mode: 'draft',
- defaultAgentSpec: { model: { name: 'openai-main/gpt-4.1' } },
- };
- }
- return { mode: 'named', agentName };
- }
- return {
- mode: 'draft',
- defaultAgentSpec: draftDefaultAgentSpec,
- };
- }, [mode, draftDefaultAgentSpec, pendingSessionId]);
-
- return (
- <TrueFoundryChatProvider
- key={runtimeKey}
- {...providerRest}
- agent={agent}
- listSessionsAgentId={listSessionsAgentId}
- initialSessionId={pendingSessionId ?? hostInitialSessionId}
- >
- <DraftCatalogProvider>
- <DraftSpecPreferenceBridge />
- {children}
- </DraftCatalogProvider>
- </TrueFoundryChatProvider>
- );
-}
+// Lazy so `react-router` stays out of the base bundle unless `withRouter` is set.
+const TrueForgeUIWithRouter = lazy<ComponentType<Omit<TrueForgeUIProps, 'withRouter'>>>(() =>
+ import('./TrueForgeUIWithRouter.js').then(m => ({ default: m.TrueForgeUIWithRouter })),
+);
/**
* Quick-start assistant UI: slots + runtime + a built-in or custom layout.
@@ -199,58 +26,21 @@ export function TrueForgeUI(props: TrueForgeUIProps) {
typeof window !== 'undefined' && new URLSearchParams(window.location.search).get('screenType') === 'mcp-auth';
// The callback skips server resolution but still inherits host theme and slots.
- return isMcpAuthScreen ? (
- <SlotsProvider overrides={props.overrides} theme={props.theme}>
- <PostMcpOauthScreen />
- </SlotsProvider>
- ) : (
- <TrueForgeUIShell {...props} />
- );
-}
-
-function TrueForgeUIShell(props: TrueForgeUIProps) {
- const {
- layout = 'sidebar',
- overrides,
- theme,
- className,
- agentConfig = DEFAULT_AGENT_CONFIG,
- initialSettingsOpen = false,
- server: serverConfig,
- onError,
- ...providerRest
- } = props;
-
- const resolved = useResolvedServer(serverConfig, onError);
-
- if (resolved.status === 'loading') {
+ if (isMcpAuthScreen) {
return (
- <SlotsProvider overrides={overrides} theme={theme}>
- <ServerInitLoader className={className} />
+ <SlotsProvider overrides={props.overrides} theme={props.theme}>
+ <PostMcpOauthScreen />
</SlotsProvider>
);
}
- if (resolved.status === 'error') {
+ const { withRouter, ...rest } = props;
+ if (withRouter) {
return (
- <SlotsProvider overrides={overrides} theme={theme}>
- <ServerInitError error={resolved.error} className={className} />
- </SlotsProvider>
+ <Suspense fallback={<ServerInitLoader className={props.className} />}>
+ <TrueForgeUIWithRouter {...rest} />
+ </Suspense>
);
}
-
- const server = resolved.server;
- const layoutTree = <LayoutChildren layout={layout} className={className} />;
-
- return (
- <SlotsProvider overrides={overrides} theme={theme}>
- <ServerProvider server={server}>
- <ShellModeProvider agentConfig={agentConfig} initialSettingsOpen={initialSettingsOpen}>
- <ChatProviderFromShell server={server} onError={onError} {...providerRest}>
- {layoutTree}
- </ChatProviderFromShell>
- </ShellModeProvider>
- </ServerProvider>
- </SlotsProvider>
- );
+ return <TrueForgeUIShell {...rest} />;
}
diff --git a/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsx b/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsx
new file mode 100644
index 000000000..02c537984
--- /dev/null
+++ b/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsx
@@ -0,0 +1,270 @@
+'use client';
+
+import type { TrueFoundryAgentConfig, UseTrueFoundryAgentRuntimeOptions } from '@truefoundry/assistant-ui-runtime';
+import { lazy, Suspense, useCallback, useMemo, useState, type ReactNode } from 'react';
+
+import { DraftCatalogProvider } from '../atoms/draft/DraftCatalogProvider.js';
+import { DraftSpecPreferenceBridge } from '../atoms/draft/DraftSpecPreferenceBridge.js';
+import { cn } from '../atoms/lib/cn.js';
+import { Spinner } from '../atoms/primitives/Spinner.js';
+import { RemoteIdRouteBridge } from '../routing/RemoteIdRouteBridge.js';
+import type { ResolvedRoutes, RoutesConfig } from '../routing/types.js';
+import { ServerProvider } from '../server/ServerContext.js';
+import { DEFAULT_AGENT_CONFIG, ShellModeProvider, useShellMode, type AgentConfig } from '../server/ShellModeContext.js';
+import type { TrueForgeServerConfig } from '../server/TrueForgeServerConfig.js';
+import { SlotsProvider, type SlotOverrides } from '../theme/SlotsProvider.js';
+import type { LayoutProp, ThemeConfig } from '../theme/types.js';
+import { getErrorMessage } from '../utils/getErrorMessage.js';
+import { TrueFoundryChatProvider, type TrueFoundryChatProviderProps } from './TrueFoundryChatProvider.js';
+import { useResolvedServer } from './useResolvedServer.js';
+
+const SidebarLayout = lazy(() => import('../layouts/SidebarLayout.js').then(m => ({ default: m.SidebarLayout })));
+const DrawerLayout = lazy(() => import('../layouts/DrawerLayout.js').then(m => ({ default: m.DrawerLayout })));
+const DockLayout = lazy(() => import('../layouts/DockLayout.js').then(m => ({ default: m.DockLayout })));
+const WidgetLayout = lazy(() => import('../layouts/WidgetLayout.js').then(m => ({ default: m.WidgetLayout })));
+const ShellRouteSync = lazy(() => import('../routing/ShellRouteSync.js').then(m => ({ default: m.ShellRouteSync })));
+
+export type ChatLayout = 'sidebar' | 'drawer' | 'dock' | 'widget';
+
+type RuntimeAdapters = NonNullable<UseTrueFoundryAgentRuntimeOptions['adapters']>;
+
+export type TrueForgeUIProps = {
+ server: TrueForgeServerConfig;
+ /** Built-in layout string or a custom layout component. Defaults to `"sidebar"`. */
+ layout?: LayoutProp;
+ overrides?: SlotOverrides;
+ theme?: ThemeConfig;
+ className?: string;
+ initialSessionId?: string;
+ adapters?: RuntimeAdapters;
+ onError?: (error: unknown) => void;
+ /**
+ * Agent / library / composer shell mode.
+ * Defaults to `{ mode: "AgentLibraryWithComposer" }`.
+ */
+ agentConfig?: AgentConfig;
+ /** Open settings on first paint only (host boot with no models configured). */
+ initialSettingsOpen?: boolean;
+ /**
+ * Sync shell navigation to the browser URL via react-router (opt-in).
+ * Requires `react-router-dom` in the host. Leave off for dock/widget embeds
+ * and hosts that own their own router. Defaults to `false`.
+ */
+ withRouter?: boolean;
+ /** URL path customization; only honored when `withRouter`. */
+ routes?: RoutesConfig;
+};
+
+export type TrueForgeUIShellProps = Omit<TrueForgeUIProps, 'withRouter'> & { resolvedRoutes?: ResolvedRoutes };
+
+function LayoutFallback({ className }: { className?: string }) {
+ return (
+ <div
+ className={className}
+ style={{
+ height: '100%',
+ minHeight: '12rem',
+ background:
+ 'linear-gradient(90deg, color-mix(in oklab, var(--secondary-bg) 55%, transparent) 25%, color-mix(in oklab, var(--secondary-bg) 25%, transparent) 50%, color-mix(in oklab, var(--secondary-bg) 55%, transparent) 75%)',
+ backgroundSize: '200% 100%',
+ animation: 'tfy-aui-pulse 1.2s ease-in-out infinite',
+ }}
+ aria-hidden
+ />
+ );
+}
+
+/** Shown while `type: "truefoundry"` resolves the agent UI server. */
+export function ServerInitLoader({ className }: { className?: string }) {
+ return (
+ <div
+ role="status"
+ aria-live="polite"
+ aria-busy="true"
+ className={cn(
+ 'flex h-full min-h-48 w-full flex-1 items-center justify-center bg-primary-bg text-text-secondary',
+ className,
+ )}
+ >
+ <Spinner size={28} className="text-text-primary" />
+ <span className="sr-only">Loading</span>
+ </div>
+ );
+}
+
+function ServerInitError({ error, className }: { error: unknown; className?: string }) {
+ const message = getErrorMessage(error, 'Failed to initialize server');
+ return (
+ <div
+ role="alert"
+ className={cn(
+ 'flex h-full min-h-48 items-center justify-center bg-primary-bg px-6 text-center text-sm text-failure-bg',
+ className,
+ )}
+ >
+ {message}
+ </div>
+ );
+}
+
+function isBuiltInLayout(layout: LayoutProp): layout is ChatLayout {
+ return layout === 'sidebar' || layout === 'drawer' || layout === 'dock' || layout === 'widget';
+}
+
+function BuiltInLayoutView({ layout, className }: { layout: ChatLayout; className?: string }) {
+ switch (layout) {
+ case 'sidebar':
+ return <SidebarLayout className={className} />;
+ case 'drawer':
+ return <DrawerLayout className={className} />;
+ case 'dock':
+ return <DockLayout className={className} />;
+ case 'widget':
+ return <WidgetLayout className={className} />;
+ }
+}
+
+function LayoutChildren({ layout, className }: { layout: LayoutProp; className?: string }) {
+ if (isBuiltInLayout(layout)) {
+ return (
+ <Suspense fallback={<LayoutFallback className={className} />}>
+ <BuiltInLayoutView layout={layout} className={className} />
+ </Suspense>
+ );
+ }
+ const HostLayout = layout;
+ return <HostLayout className={className} />;
+}
+
+function ChatProviderFromShell({
+ children,
+ initialSessionId: hostInitialSessionId,
+ onRemoteIdChange,
+ ...providerRest
+}: {
+ children: ReactNode;
+ /** When routing, reports the active thread's remote id up to `ShellRouteSync`. */
+ onRemoteIdChange?: (id: string | undefined) => void;
+} & Omit<TrueFoundryChatProviderProps, 'agent' | 'agentName' | 'listSessionsAgentId' | 'children'>) {
+ const { mode, runtimeKey, listSessionsAgentId, pendingSessionId } = useShellMode();
+
+ // Freeze draft seed for the life of this runtimeKey so bindMutableAgent (identity /
+ // instructions on shell) does not push a new defaultAgentSpec into the runtime.
+ const draftDefaultAgentSpec = useMemo(() => {
+ if (mode.status === 'active' && mode.isMutable) {
+ return mode.agentSpec ?? { model: { name: 'openai-main/gpt-4.1' } };
+ }
+ return { model: { name: 'openai-main/gpt-4.1' } };
+ // runtimeKey is the remount boundary for mutable chats.
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- intentionally keyed on runtimeKey only
+ }, [runtimeKey]);
+
+ const agent: TrueFoundryAgentConfig = useMemo(() => {
+ // idle uses a placeholder draft so layout chrome (useAui) still mounts;
+ // layouts render an empty CTA instead of the thread.
+ if (mode.status === 'idle') {
+ return {
+ mode: 'draft',
+ defaultAgentSpec: { model: { name: 'openai-main/gpt-4.1' } },
+ };
+ }
+ // Runtime still uses named|draft; shell mutability maps onto that adapter.
+ if (!mode.isMutable) {
+ const agentName = mode.agentName ?? mode.agentId ?? pendingSessionId;
+ if (agentName == null) {
+ // Active immutable without identity should not happen; keep chrome mounted.
+ return {
+ mode: 'draft',
+ defaultAgentSpec: { model: { name: 'openai-main/gpt-4.1' } },
+ };
+ }
+ return { mode: 'named', agentName };
+ }
+ return {
+ mode: 'draft',
+ defaultAgentSpec: draftDefaultAgentSpec,
+ };
+ }, [mode, draftDefaultAgentSpec, pendingSessionId]);
+
+ return (
+ <TrueFoundryChatProvider
+ key={runtimeKey}
+ {...providerRest}
+ agent={agent}
+ listSessionsAgentId={listSessionsAgentId}
+ initialSessionId={pendingSessionId ?? hostInitialSessionId}
+ >
+ <DraftCatalogProvider>
+ <DraftSpecPreferenceBridge />
+ {onRemoteIdChange != null ? <RemoteIdRouteBridge onRemoteIdChange={onRemoteIdChange} /> : null}
+ {children}
+ </DraftCatalogProvider>
+ </TrueFoundryChatProvider>
+ );
+}
+
+/** Internal shell. `resolvedRoutes` present iff mounted under `TrueForgeUIWithRouter`. */
+export function TrueForgeUIShell(props: TrueForgeUIShellProps) {
+ const {
+ layout = 'sidebar',
+ overrides,
+ theme,
+ className,
+ agentConfig = DEFAULT_AGENT_CONFIG,
+ initialSettingsOpen = false,
+ server: serverConfig,
+ onError,
+ resolvedRoutes,
+ routes: _routes,
+ ...providerRest
+ } = props;
+
+ const resolved = useResolvedServer(serverConfig, onError);
+ const [activeRemoteId, setActiveRemoteId] = useState<string | undefined>(undefined);
+ const handleRemoteIdChange = useCallback((id: string | undefined) => setActiveRemoteId(id), []);
+
+ if (resolved.status === 'loading') {
+ return (
+ <SlotsProvider overrides={overrides} theme={theme}>
+ <ServerInitLoader className={className} />
+ </SlotsProvider>
+ );
+ }
+
+ if (resolved.status === 'error') {
+ return (
+ <SlotsProvider overrides={overrides} theme={theme}>
+ <ServerInitError error={resolved.error} className={className} />
+ </SlotsProvider>
+ );
+ }
+
+ const server = resolved.server;
+ const layoutTree = <LayoutChildren layout={layout} className={className} />;
+
+ return (
+ <SlotsProvider overrides={overrides} theme={theme}>
+ <ServerProvider server={server}>
+ <ShellModeProvider agentConfig={agentConfig} initialSettingsOpen={initialSettingsOpen}>
+ {resolvedRoutes != null ? (
+ <Suspense fallback={null}>
+ <ShellRouteSync
+ routes={resolvedRoutes}
+ activeRemoteId={activeRemoteId}
+ initialSettingsOpen={initialSettingsOpen}
+ />
+ </Suspense>
+ ) : null}
+ <ChatProviderFromShell
+ server={server}
+ onError={onError}
+ onRemoteIdChange={resolvedRoutes != null ? handleRemoteIdChange : undefined}
+ {...providerRest}
+ >
+ {layoutTree}
+ </ChatProviderFromShell>
+ </ShellModeProvider>
+ </ServerProvider>
+ </SlotsProvider>
+ );
+}
diff --git a/packages/trueforge-ui/src/containers/TrueForgeUIWithRouter.tsx b/packages/trueforge-ui/src/containers/TrueForgeUIWithRouter.tsx
new file mode 100644
index 000000000..bb6860f22
--- /dev/null
+++ b/packages/trueforge-ui/src/containers/TrueForgeUIWithRouter.tsx
@@ -0,0 +1,24 @@
+'use client';
+
+import { useMemo, type ComponentProps } from 'react';
+import { BrowserRouter } from 'react-router-dom';
+
+import { resolveRoutesConfig } from '../routing/paths.js';
+import { TrueForgeUIShell } from './TrueForgeUIShell.js';
+
+/**
+ * `withRouter` entry point. Owns a `BrowserRouter` and hands the resolved route
+ * templates to the shell, which mounts `ShellRouteSync`. This module statically
+ * imports react-router and is only loaded lazily from `TrueForgeUI`.
+ */
+export function TrueForgeUIWithRouter({
+ routes,
+ ...rest
+}: Omit<ComponentProps<typeof TrueForgeUIShell>, 'resolvedRoutes'>) {
+ const resolved = useMemo(() => resolveRoutesConfig(routes), [routes]);
+ return (
+ <BrowserRouter basename={resolved.basename || undefined}>
+ <TrueForgeUIShell {...rest} resolvedRoutes={resolved} />
+ </BrowserRouter>
+ );
+}
diff --git a/packages/trueforge-ui/src/index.ts b/packages/trueforge-ui/src/index.ts
index f982c5620..42f16c6b2 100644
--- a/packages/trueforge-ui/src/index.ts
+++ b/packages/trueforge-ui/src/index.ts
@@ -178,6 +178,8 @@ export type { ThreadGroupPart } from './containers/ToolGroupContainer.js';
export { TrueForgeUI } from './containers/TrueForgeUI.js';
export type {
ChatLayout,
+ RoutePlace,
+ RoutesConfig,
TrueForgeBuiltInServerConfig,
TrueForgeServerConfig,
TrueForgeUIProps,
diff --git a/packages/trueforge-ui/src/routing/RemoteIdRouteBridge.tsx b/packages/trueforge-ui/src/routing/RemoteIdRouteBridge.tsx
new file mode 100644
index 000000000..3ff6eafd1
--- /dev/null
+++ b/packages/trueforge-ui/src/routing/RemoteIdRouteBridge.tsx
@@ -0,0 +1,19 @@
+'use client';
+
+import { useEffect } from 'react';
+
+import { useAuiState } from '../assistant-ui.js';
+
+/**
+ * Observes the active thread's remote id (assigned once a fresh chat persists)
+ * and lifts it to the parent so `ShellRouteSync` can mirror it to `/sessions/:id`.
+ * Lives inside the chat runtime, so it remounts with `runtimeKey`; reporting is
+ * idempotent, so that is harmless. Carries no react-router dependency.
+ */
+export function RemoteIdRouteBridge({ onRemoteIdChange }: { onRemoteIdChange: (id: string | undefined) => void }) {
+ const remoteId = useAuiState(s => s.threadListItem.remoteId);
+ useEffect(() => {
+ onRemoteIdChange(remoteId ?? undefined);
+ }, [remoteId, onRemoteIdChange]);
+ return null;
+}
diff --git a/packages/trueforge-ui/src/routing/ShellRouteSync.tsx b/packages/trueforge-ui/src/routing/ShellRouteSync.tsx
new file mode 100644
index 000000000..7cac209fb
--- /dev/null
+++ b/packages/trueforge-ui/src/routing/ShellRouteSync.tsx
@@ -0,0 +1,199 @@
+'use client';
+
+import { useCallback, useEffect, useRef } from 'react';
+import { useLocation, useNavigate } from 'react-router-dom';
+
+import { useOptionalServer } from '../server/ServerContext.js';
+import { useShellMode } from '../server/ShellModeContext.js';
+import { deriveChatPlace, derivePlace } from './derivePlace.js';
+import { buildPath, matchPath, placesEqual } from './paths.js';
+import type { ResolvedRoutes, RoutePlace, ShellSnapshot } from './types.js';
+
+/**
+ * Single bidirectional bridge between shell state and the URL. Mounted under
+ * `ShellModeProvider` but outside the keyed chat runtime so boot applies once.
+ */
+export function ShellRouteSync({
+ routes,
+ activeRemoteId,
+ initialSettingsOpen,
+}: {
+ routes: ResolvedRoutes;
+ activeRemoteId: string | undefined;
+ initialSettingsOpen: boolean;
+}) {
+ const shell = useShellMode();
+ const server = useOptionalServer();
+ const navigate = useNavigate();
+ const location = useLocation();
+
+ const snapshot: ShellSnapshot = {
+ settingsOpen: shell.settingsOpen,
+ pendingSessionId: shell.pendingSessionId,
+ activeRemoteId,
+ mode: shell.mode,
+ agentConfigMode: shell.agentConfigMode,
+ };
+
+ const place = derivePlace(snapshot);
+ const placeKey = JSON.stringify(place);
+
+ // Guards. `selfNavPathRef` marks a path we navigated to ourselves so the
+ // URL->shell effect does not re-apply it. `prevPlaceRef` powers push/replace.
+ const selfNavPathRef = useRef<string | null>(null);
+ const prevPlaceRef = useRef<RoutePlace | null>(null);
+ const bootedRef = useRef(false);
+ // Latest session id the URL asked for, so slower lookups cannot bind over it.
+ const requestedSessionRef = useRef<string | null>(null);
+ // Boot owns the first URL; the ongoing effects skip their initial commit so
+ // they do not fight boot with the stale first-render place.
+ const shellSyncStartedRef = useRef(false);
+ const urlSyncStartedRef = useRef(false);
+
+ /**
+ * A URL carries only the id, so ask the server whether it names a mutable
+ * draft or an agent chat; guessing "mutable" opens an agent session as a
+ * blank draft. `requestedSessionRef` drops replies a later place superseded.
+ */
+ const openSession = useCallback(
+ (sessionId: string) => {
+ requestedSessionRef.current = sessionId;
+ if (server == null) {
+ shell.openHistorySession({ sessionId });
+ return;
+ }
+ void server
+ .getSession({ sessionId })
+ .then(session => {
+ if (requestedSessionRef.current !== sessionId) return;
+ shell.openHistorySession({
+ sessionId,
+ isMutable: session.isMutable,
+ ...(session.agentName != null ? { agentName: session.agentName } : {}),
+ });
+ })
+ .catch(() => {
+ if (requestedSessionRef.current !== sessionId) return;
+ // Unreachable session: bind by id alone rather than stranding the shell.
+ shell.openHistorySession({ sessionId });
+ });
+ },
+ [server, shell],
+ );
+
+ const applyPlace = useCallback(
+ (target: RoutePlace) => {
+ switch (target.type) {
+ case 'settings':
+ shell.setSettingsOpen(true);
+ return;
+ case 'session':
+ if (shell.pendingSessionId === target.sessionId || activeRemoteId === target.sessionId) return;
+ openSession(target.sessionId);
+ return;
+ case 'agent':
+ shell.selectLibraryAgent({ isMutable: false, agentName: target.agentName });
+ return;
+ case 'root':
+ shell.setSettingsOpen(false);
+ switch (shell.agentConfigMode) {
+ case 'AgentLibrary':
+ shell.openLibraryHome();
+ return;
+ case 'AgentComposer':
+ case 'AgentLibraryWithComposer':
+ shell.openDraft();
+ return;
+ case 'SingleAgent':
+ shell.clearChat();
+ return;
+ }
+ }
+ },
+ [shell, activeRemoteId, openSession],
+ );
+
+ // Boot: URL wins, except an explicit `initialSettingsOpen` overlay. Boot is the
+ // sole authority for the first commit and sets the final URL + `prevPlaceRef`.
+ useEffect(() => {
+ if (bootedRef.current) return;
+ bootedRef.current = true;
+
+ const urlPlace = matchPath(location.pathname, routes) ?? { type: 'root' };
+ const settingsOnBoot = initialSettingsOpen || urlPlace.type === 'settings';
+
+ if (urlPlace.type === 'settings') {
+ shell.setSettingsOpen(true);
+ } else {
+ const chatPlace = deriveChatPlace(snapshot);
+ if (!placesEqual(chatPlace, urlPlace)) applyPlace(urlPlace);
+ if (initialSettingsOpen) shell.setSettingsOpen(true);
+ }
+
+ const desiredPlace: RoutePlace = settingsOnBoot ? { type: 'settings' } : urlPlace;
+ const desiredPath = buildPath(desiredPlace, routes);
+ prevPlaceRef.current = desiredPlace;
+ if (desiredPath != null && desiredPath !== location.pathname) {
+ selfNavPathRef.current = desiredPath;
+ navigate({ pathname: desiredPath, search: location.search, hash: location.hash }, { replace: true });
+ }
+ // Boot runs once; snapshot is read imperatively here.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ // Shell -> URL: mirror the derived place. Skip the first commit (boot owns it).
+ useEffect(() => {
+ if (!bootedRef.current) return;
+ if (!shellSyncStartedRef.current) {
+ shellSyncStartedRef.current = true;
+ return;
+ }
+ const target = buildPath(place, routes);
+ if (target == null) return; // place has no configured URL (e.g. settings disabled)
+
+ const prev = prevPlaceRef.current;
+ prevPlaceRef.current = place;
+
+ if (target === location.pathname) return;
+
+ // Replace when a fresh chat just acquired its session id (same place, new id).
+ const replace =
+ place.type === 'session' && shell.pendingSessionId == null && prev != null && prev.type !== 'session';
+
+ selfNavPathRef.current = target;
+ // Only the pathname is ours; host query/hash state rides along unchanged.
+ navigate({ pathname: target, search: location.search, hash: location.hash }, { replace });
+ // location.pathname intentionally excluded: only react to shell-derived place changes.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [placeKey]);
+
+ // URL -> shell: apply on genuine location changes (Back/Forward, manual edits).
+ useEffect(() => {
+ if (!bootedRef.current) return;
+ if (!urlSyncStartedRef.current) {
+ urlSyncStartedRef.current = true;
+ return;
+ }
+ if (selfNavPathRef.current === location.pathname) {
+ selfNavPathRef.current = null;
+ return;
+ }
+ const urlPlace = matchPath(location.pathname, routes);
+ if (urlPlace == null) {
+ // Unknown path: normalize to root.
+ const rootPath = routes.root;
+ selfNavPathRef.current = rootPath;
+ navigate({ pathname: rootPath, search: location.search, hash: location.hash }, { replace: true });
+ applyPlace({ type: 'root' });
+ return;
+ }
+ if (urlPlace.type !== 'settings' && shell.settingsOpen) {
+ // Leaving settings via Back to a chat place.
+ shell.setSettingsOpen(false);
+ }
+ applyPlace(urlPlace);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [location.pathname]);
+
+ return null;
+}
diff --git a/packages/trueforge-ui/src/routing/derivePlace.ts b/packages/trueforge-ui/src/routing/derivePlace.ts
new file mode 100644
index 000000000..0f0cddccb
--- /dev/null
+++ b/packages/trueforge-ui/src/routing/derivePlace.ts
@@ -0,0 +1,26 @@
+import type { RoutePlace, ShellSnapshot } from './types.js';
+
+/**
+ * The chat place implied by shell state, ignoring the settings overlay.
+ * SingleAgent canonicalizes to `root` so `/` and `/agents/{name}` alias.
+ */
+export function deriveChatPlace(snapshot: ShellSnapshot): RoutePlace {
+ // The live thread wins: reusing a mutable shell switches thread without a
+ // remount, leaving `pendingSessionId` on the session the shell last opened.
+ // It only leads while a requested session has not reported its thread yet.
+ const sessionId = snapshot.activeRemoteId ?? snapshot.pendingSessionId;
+ if (sessionId != null) return { type: 'session', sessionId };
+
+ const { mode, agentConfigMode } = snapshot;
+ if (mode.status === 'active' && !mode.isMutable && agentConfigMode !== 'SingleAgent') {
+ const agentName = mode.agentName ?? mode.agentId;
+ if (agentName != null) return { type: 'agent', agentName };
+ }
+ return { type: 'root' };
+}
+
+/** Full place including the settings overlay, which wins over the chat place. */
+export function derivePlace(snapshot: ShellSnapshot): RoutePlace {
+ if (snapshot.settingsOpen) return { type: 'settings' };
+ return deriveChatPlace(snapshot);
+}
diff --git a/packages/trueforge-ui/src/routing/paths.ts b/packages/trueforge-ui/src/routing/paths.ts
new file mode 100644
index 000000000..90604bff2
--- /dev/null
+++ b/packages/trueforge-ui/src/routing/paths.ts
@@ -0,0 +1,117 @@
+import type { ResolvedRoutes, RoutePlace, RoutesConfig } from './types.js';
+
+const DEFAULTS = {
+ root: '/',
+ settings: '/settings',
+ agent: '/agents/:agentName',
+ session: '/sessions/:sessionId',
+} as const;
+
+function normalizePath(path: string): string {
+ const trimmed = path.trim();
+ const withLead = trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
+ // Drop a trailing slash except for the root itself.
+ return withLead.length > 1 && withLead.endsWith('/') ? withLead.slice(0, -1) : withLead;
+}
+
+function resolveOptional(value: string | false | undefined, fallback: string): string | null {
+ if (value === false) return null;
+ return normalizePath(value ?? fallback);
+}
+
+export function resolveRoutesConfig(routes?: RoutesConfig): ResolvedRoutes {
+ const paths = routes?.paths;
+ return {
+ basename: routes?.basename ?? '',
+ root: normalizePath(paths?.root ?? DEFAULTS.root),
+ settings: resolveOptional(paths?.settings, DEFAULTS.settings),
+ agent: resolveOptional(paths?.agent, DEFAULTS.agent),
+ session: resolveOptional(paths?.session, DEFAULTS.session),
+ };
+}
+
+function splitSegments(path: string): string[] {
+ return path.split('/').filter(segment => segment.length > 0);
+}
+
+/** Fill a single-param template (`/agents/:agentName`) with an encoded value. */
+function fillTemplate(template: string, value: string): string {
+ return (
+ '/' +
+ splitSegments(template)
+ .map(segment => (segment.startsWith(':') ? encodeURIComponent(value) : segment))
+ .join('/')
+ );
+}
+
+/** Build the URL path for a place, or `null` when that place has no configured route. */
+export function buildPath(place: RoutePlace, routes: ResolvedRoutes): string | null {
+ switch (place.type) {
+ case 'root':
+ return routes.root;
+ case 'settings':
+ return routes.settings;
+ case 'agent':
+ return routes.agent == null ? null : fillTemplate(routes.agent, place.agentName);
+ case 'session':
+ return routes.session == null ? null : fillTemplate(routes.session, place.sessionId);
+ }
+}
+
+/** Percent-decode a segment; `null` when the URL carries a malformed escape. */
+function decodeSegment(segment: string): string | null {
+ try {
+ return decodeURIComponent(segment);
+ } catch {
+ return null;
+ }
+}
+
+/** Match a single-param template against concrete segments; returns the decoded param or null. */
+function matchTemplate(template: string, segments: string[]): string | null {
+ const templateSegments = splitSegments(template);
+ if (templateSegments.length !== segments.length) return null;
+ let param: string | null = null;
+ for (const [i, tpl] of templateSegments.entries()) {
+ const seg = segments[i];
+ if (seg === undefined) return null;
+ if (tpl.startsWith(':')) {
+ // A malformed escape is an unusable id, so the path simply does not match.
+ const decoded = decodeSegment(seg);
+ if (decoded == null) return null;
+ param = decoded;
+ } else if (tpl !== seg) {
+ return null;
+ }
+ }
+ return param;
+}
+
+/** Parse a (basename-relative) pathname into a place, or `null` when unrecognized. */
+export function matchPath(pathname: string, routes: ResolvedRoutes): RoutePlace | null {
+ const normalized = normalizePath(pathname);
+ const segments = splitSegments(normalized);
+
+ if (routes.settings != null && normalized === routes.settings) {
+ return { type: 'settings' };
+ }
+ if (routes.agent != null) {
+ const agentName = matchTemplate(routes.agent, segments);
+ if (agentName != null) return { type: 'agent', agentName };
+ }
+ if (routes.session != null) {
+ const sessionId = matchTemplate(routes.session, segments);
+ if (sessionId != null) return { type: 'session', sessionId };
+ }
+ if (normalized === routes.root) {
+ return { type: 'root' };
+ }
+ return null;
+}
+
+export function placesEqual(a: RoutePlace, b: RoutePlace): boolean {
+ if (a.type !== b.type) return false;
+ if (a.type === 'agent' && b.type === 'agent') return a.agentName === b.agentName;
+ if (a.type === 'session' && b.type === 'session') return a.sessionId === b.sessionId;
+ return true;
+}
diff --git a/packages/trueforge-ui/src/routing/types.ts b/packages/trueforge-ui/src/routing/types.ts
new file mode 100644
index 000000000..d2c1b9235
--- /dev/null
+++ b/packages/trueforge-ui/src/routing/types.ts
@@ -0,0 +1,50 @@
+import type { AgentConfig, ShellMode } from '../server/ShellModeContext.js';
+
+/**
+ * A navigable place in the chat shell. The router mirrors these to the URL;
+ * shell state stays the source of truth.
+ */
+export type RoutePlace =
+ | { type: 'root' }
+ | { type: 'agent'; agentName: string }
+ | { type: 'session'; sessionId: string }
+ | { type: 'settings' };
+
+/**
+ * Host-facing route path customization. Only honored when `withRouter`.
+ * The shell owns the pathname only; query string and hash are left untouched.
+ */
+export type RoutesConfig = {
+ /** Passed to the router; not used for our own match/build (router strips it). */
+ basename?: string;
+ /** `agent` and `session` templates MUST keep their `:param` segment to stay addressable. */
+ paths?: {
+ /** New-chat / landing. Default `'/'`. */
+ root?: string;
+ /** Settings overlay. `false` keeps settings overlay-only (no URL). Default `'/settings'`. */
+ settings?: string | false;
+ /** Immutable "Try" agent. `false` disables. Default `'/agents/:agentName'`. */
+ agent?: string | false;
+ /** Session deep link. `false` disables. Default `'/sessions/:sessionId'`. */
+ session?: string | false;
+ };
+};
+
+/** Fully-resolved templates with defaults applied. `null` = that place has no URL. */
+export type ResolvedRoutes = {
+ basename: string;
+ root: string;
+ settings: string | null;
+ agent: string | null;
+ session: string | null;
+};
+
+/** Inputs for deriving the current place from shell + runtime state. */
+export type ShellSnapshot = {
+ settingsOpen: boolean;
+ pendingSessionId?: string;
+ /** Remote id of the active thread once a fresh chat is persisted. */
+ activeRemoteId?: string;
+ mode: ShellMode;
+ agentConfigMode: AgentConfig['mode'];
+};
diff --git a/packages/trueforge-ui/src/server/ShellModeContext.tsx b/packages/trueforge-ui/src/server/ShellModeContext.tsx
index a7da3c6a0..1d9ff0a35 100644
--- a/packages/trueforge-ui/src/server/ShellModeContext.tsx
+++ b/packages/trueforge-ui/src/server/ShellModeContext.tsx
@@ -87,6 +87,8 @@ type ShellModeContextValue = {
openHistorySession: (req: { sessionId: string; agentName?: string; isMutable?: boolean }) => void;
/** Reset current chat; no-op when idle. */
clearChat: () => void;
+ /** Return pure Agents Library to its idle landing; no-op in other modes. */
+ openLibraryHome: () => void;
/** Remount key for the chat runtime when binding changes. */
runtimeKey: string;
/**
@@ -360,6 +362,15 @@ export function ShellModeProvider({
bumpEpoch(false);
}, [effectiveMode, bumpEpoch]);
+ const openLibraryHome = useCallback(() => {
+ // Only pure Agents Library has an idle landing; other modes root via openDraft / clearChat.
+ if (!isLibraryEnabled || isComposerEnabled) return;
+ setPendingSessionId(undefined);
+ setSettingsOpen(false);
+ setMode({ status: 'idle' });
+ bumpEpoch(false);
+ }, [isLibraryEnabled, isComposerEnabled, setSettingsOpen, bumpEpoch]);
+
// Mutable remounts are driven only by mutableEpoch (library Edit / New Chat / Clear).
// Agent id and model must not be in the key — saveAgent binds those onto the same draft.
const runtimeKey = useMemo(() => {
@@ -388,6 +399,7 @@ export function ShellModeProvider({
rememberDraftSpec,
openHistorySession,
clearChat,
+ openLibraryHome,
runtimeKey,
historyAgentFilter,
setHistoryAgentFilter,
@@ -412,6 +424,7 @@ export function ShellModeProvider({
rememberDraftSpec,
openHistorySession,
clearChat,
+ openLibraryHome,
runtimeKey,
historyAgentFilter,
listSessionsAgentId,
diff --git a/packages/trueforge-ui/test/routing/ShellRouteSync.test.tsx b/packages/trueforge-ui/test/routing/ShellRouteSync.test.tsx
new file mode 100644
index 000000000..c36623c42
--- /dev/null
+++ b/packages/trueforge-ui/test/routing/ShellRouteSync.test.tsx
@@ -0,0 +1,118 @@
+// @vitest-environment jsdom
+import { act, render } from '@testing-library/react';
+import { useEffect, useState } from 'react';
+import { MemoryRouter, useLocation } from 'react-router-dom';
+import { describe, expect, it } from 'vitest';
+
+import { resolveRoutesConfig } from '@/routing/paths.js';
+import { ShellRouteSync } from '@/routing/ShellRouteSync.js';
+import { ShellModeProvider, useShellMode, type AgentConfig } from '@/server/ShellModeContext.js';
+
+const routes = resolveRoutesConfig();
+
+type Shell = ReturnType<typeof useShellMode>;
+
+let shell: Shell;
+let pathname = '';
+let setRemoteId: (id: string | undefined) => void = () => undefined;
+
+function CaptureShell() {
+ shell = useShellMode();
+ return null;
+}
+
+function CaptureLocation() {
+ const location = useLocation();
+ pathname = location.pathname;
+ useEffect(() => {
+ pathname = location.pathname;
+ }, [location.pathname]);
+ return null;
+}
+
+function Harness({
+ agentConfig,
+ initialRemoteId,
+ initialSettingsOpen = false,
+}: {
+ agentConfig?: AgentConfig;
+ initialRemoteId?: string;
+ initialSettingsOpen?: boolean;
+}) {
+ const [remoteId, setId] = useState<string | undefined>(initialRemoteId);
+ setRemoteId = setId;
+ return (
+ <ShellModeProvider agentConfig={agentConfig} initialSettingsOpen={initialSettingsOpen}>
+ <CaptureShell />
+ <CaptureLocation />
+ <ShellRouteSync routes={routes} activeRemoteId={remoteId} initialSettingsOpen={initialSettingsOpen} />
+ </ShellModeProvider>
+ );
+}
+
+function renderSync(opts: { initialEntries?: string[]; agentConfig?: AgentConfig; initialSettingsOpen?: boolean }) {
+ return render(
+ <MemoryRouter initialEntries={opts.initialEntries ?? ['/']}>
+ <Harness agentConfig={opts.agentConfig} initialSettingsOpen={opts.initialSettingsOpen} />
+ </MemoryRouter>,
+ );
+}
+
+describe('ShellRouteSync', () => {
+ it('applies a session deep link on boot', () => {
+ renderSync({ initialEntries: ['/sessions/abc'] });
+ expect(shell.pendingSessionId).toBe('abc');
+ expect(pathname).toBe('/sessions/abc');
+ });
+
+ it('applies an agent deep link on boot', () => {
+ renderSync({ initialEntries: ['/agents/helper'], agentConfig: { mode: 'AgentLibrary' } });
+ expect(shell.mode).toMatchObject({ status: 'active', isMutable: false, agentName: 'helper' });
+ });
+
+ it('pushes the URL when the shell selects an immutable agent', () => {
+ renderSync({ initialEntries: ['/'], agentConfig: { mode: 'AgentLibrary' } });
+ expect(pathname).toBe('/');
+ act(() => shell.selectLibraryAgent({ isMutable: false, agentName: 'foo' }));
+ expect(pathname).toBe('/agents/foo');
+ });
+
+ it('mirrors settings open/close through history', () => {
+ renderSync({ initialEntries: ['/'] });
+ act(() => shell.setSettingsOpen(true));
+ expect(pathname).toBe('/settings');
+ act(() => shell.setSettingsOpen(false));
+ expect(pathname).toBe('/');
+ });
+
+ it('replaces to the session path when a fresh chat acquires a remote id', () => {
+ render(
+ <MemoryRouter initialEntries={['/']}>
+ <Harness agentConfig={{ mode: 'AgentComposer' }} />
+ </MemoryRouter>,
+ );
+ expect(pathname).toBe('/');
+ act(() => setRemoteId('new-session'));
+ expect(pathname).toBe('/sessions/new-session');
+ });
+
+ it('opens settings on boot when initialSettingsOpen is set and pushes the URL', () => {
+ renderSync({ initialEntries: ['/'], initialSettingsOpen: true });
+ expect(shell.settingsOpen).toBe(true);
+ expect(pathname).toBe('/settings');
+ });
+
+ // Boot replaces into /settings, so Back would leave the app instead of closing it.
+ it('returns to the chat place when settings opened on boot is closed', () => {
+ renderSync({ initialEntries: ['/'], initialSettingsOpen: true });
+ act(() => shell.setSettingsOpen(false));
+ expect(pathname).toBe('/');
+ });
+
+ it('returns to the chat place when a /settings deep link is closed', () => {
+ renderSync({ initialEntries: ['/settings'] });
+ expect(shell.settingsOpen).toBe(true);
+ act(() => shell.setSettingsOpen(false));
+ expect(pathname).toBe('/');
+ });
+});
diff --git a/packages/trueforge-ui/test/routing/derivePlace.test.ts b/packages/trueforge-ui/test/routing/derivePlace.test.ts
new file mode 100644
index 000000000..5d4dfb757
--- /dev/null
+++ b/packages/trueforge-ui/test/routing/derivePlace.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it } from 'vitest';
+
+import { deriveChatPlace, derivePlace } from '@/routing/derivePlace.js';
+import type { ShellSnapshot } from '@/routing/types.js';
+
+function snap(partial: Partial<ShellSnapshot>): ShellSnapshot {
+ return {
+ settingsOpen: false,
+ mode: { status: 'idle' },
+ agentConfigMode: 'AgentLibraryWithComposer',
+ ...partial,
+ };
+}
+
+describe('derivePlace', () => {
+ it('settings overlay wins over the chat place', () => {
+ expect(derivePlace(snap({ settingsOpen: true, pendingSessionId: 'abc' }))).toEqual({ type: 'settings' });
+ });
+
+ it('pendingSessionId maps to a session while no thread has reported yet', () => {
+ expect(derivePlace(snap({ pendingSessionId: 'abc' }))).toEqual({ type: 'session', sessionId: 'abc' });
+ });
+
+ it('activeRemoteId maps to a session when no pending id', () => {
+ expect(derivePlace(snap({ activeRemoteId: 'remote-1' }))).toEqual({ type: 'session', sessionId: 'remote-1' });
+ });
+
+ it('activeRemoteId takes precedence over a stale pendingSessionId', () => {
+ expect(derivePlace(snap({ pendingSessionId: 'p', activeRemoteId: 'r' }))).toEqual({
+ type: 'session',
+ sessionId: 'r',
+ });
+ });
+
+ it('active immutable agent maps to an agent place', () => {
+ expect(
+ deriveChatPlace(snap({ mode: { status: 'active', isMutable: false, agentName: 'helper', locked: false } })),
+ ).toEqual({ type: 'agent', agentName: 'helper' });
+ });
+
+ it('SingleAgent canonicalizes the immutable agent to root', () => {
+ expect(
+ deriveChatPlace(
+ snap({
+ agentConfigMode: 'SingleAgent',
+ mode: { status: 'active', isMutable: false, agentName: 'locked', locked: true },
+ }),
+ ),
+ ).toEqual({ type: 'root' });
+ });
+
+ it('mutable draft and idle map to root', () => {
+ expect(deriveChatPlace(snap({ mode: { status: 'idle' } }))).toEqual({ type: 'root' });
+ expect(deriveChatPlace(snap({ mode: { status: 'active', isMutable: true, locked: false } }))).toEqual({
+ type: 'root',
+ });
+ });
+});
diff --git a/packages/trueforge-ui/test/routing/paths.test.ts b/packages/trueforge-ui/test/routing/paths.test.ts
new file mode 100644
index 000000000..d68e15471
--- /dev/null
+++ b/packages/trueforge-ui/test/routing/paths.test.ts
@@ -0,0 +1,104 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildPath, matchPath, placesEqual, resolveRoutesConfig } from '@/routing/paths.js';
+
+describe('resolveRoutesConfig', () => {
+ it('applies defaults', () => {
+ expect(resolveRoutesConfig()).toEqual({
+ basename: '',
+ root: '/',
+ settings: '/settings',
+ agent: '/agents/:agentName',
+ session: '/sessions/:sessionId',
+ });
+ });
+
+ it('honors overrides and disabled places', () => {
+ const resolved = resolveRoutesConfig({
+ basename: '/app',
+ paths: { root: '/home', settings: false, agent: '/a/:agentName' },
+ });
+ expect(resolved.basename).toBe('/app');
+ expect(resolved.root).toBe('/home');
+ expect(resolved.settings).toBeNull();
+ expect(resolved.agent).toBe('/a/:agentName');
+ expect(resolved.session).toBe('/sessions/:sessionId');
+ });
+
+ it('normalizes trailing slashes but keeps root', () => {
+ const resolved = resolveRoutesConfig({ paths: { root: '/', session: '/s/:sessionId/' } });
+ expect(resolved.root).toBe('/');
+ expect(resolved.session).toBe('/s/:sessionId');
+ });
+});
+
+describe('buildPath', () => {
+ const routes = resolveRoutesConfig();
+
+ it('builds each place', () => {
+ expect(buildPath({ type: 'root' }, routes)).toBe('/');
+ expect(buildPath({ type: 'settings' }, routes)).toBe('/settings');
+ expect(buildPath({ type: 'agent', agentName: 'code-helper' }, routes)).toBe('/agents/code-helper');
+ expect(buildPath({ type: 'session', sessionId: 'abc123' }, routes)).toBe('/sessions/abc123');
+ });
+
+ it('encodes param values', () => {
+ expect(buildPath({ type: 'agent', agentName: 'a/b c' }, routes)).toBe('/agents/a%2Fb%20c');
+ });
+
+ it('returns null for disabled places', () => {
+ const disabled = resolveRoutesConfig({ paths: { settings: false, agent: false } });
+ expect(buildPath({ type: 'settings' }, disabled)).toBeNull();
+ expect(buildPath({ type: 'agent', agentName: 'x' }, disabled)).toBeNull();
+ });
+});
+
+describe('matchPath', () => {
+ const routes = resolveRoutesConfig();
+
+ it('matches each place and decodes params', () => {
+ expect(matchPath('/', routes)).toEqual({ type: 'root' });
+ expect(matchPath('/settings', routes)).toEqual({ type: 'settings' });
+ expect(matchPath('/agents/a%2Fb', routes)).toEqual({ type: 'agent', agentName: 'a/b' });
+ expect(matchPath('/sessions/xyz', routes)).toEqual({ type: 'session', sessionId: 'xyz' });
+ });
+
+ it('returns null for unknown paths', () => {
+ expect(matchPath('/nope/here', routes)).toBeNull();
+ expect(matchPath('/agents', routes)).toBeNull();
+ });
+
+ // A pasted URL is untrusted input; a bad escape must not throw out of the router.
+ it('treats malformed percent-escapes as no match', () => {
+ expect(matchPath('/sessions/%', routes)).toBeNull();
+ expect(matchPath('/sessions/%E0%A4%A', routes)).toBeNull();
+ expect(matchPath('/agents/100%', routes)).toBeNull();
+ });
+
+ it('does not match disabled places', () => {
+ const disabled = resolveRoutesConfig({ paths: { session: false } });
+ expect(matchPath('/sessions/xyz', disabled)).toBeNull();
+ });
+
+ it('round-trips build and match', () => {
+ for (const place of [
+ { type: 'root' as const },
+ { type: 'settings' as const },
+ { type: 'agent' as const, agentName: 'weird name/1' },
+ { type: 'session' as const, sessionId: 'sess 9' },
+ ]) {
+ const path = buildPath(place, routes);
+ if (path == null) throw new Error(`Expected a path for ${place.type}`);
+ expect(matchPath(path, routes)).toEqual(place);
+ }
+ });
+});
+
+describe('placesEqual', () => {
+ it('compares type and params', () => {
+ expect(placesEqual({ type: 'root' }, { type: 'root' })).toBe(true);
+ expect(placesEqual({ type: 'agent', agentName: 'a' }, { type: 'agent', agentName: 'a' })).toBe(true);
+ expect(placesEqual({ type: 'agent', agentName: 'a' }, { type: 'agent', agentName: 'b' })).toBe(false);
+ expect(placesEqual({ type: 'session', sessionId: '1' }, { type: 'root' })).toBe(false);
+ });
+});
diff --git a/packages/trueforge-ui/test/routing/sessionRouting.test.tsx b/packages/trueforge-ui/test/routing/sessionRouting.test.tsx
new file mode 100644
index 000000000..bf5a7d9c9
--- /dev/null
+++ b/packages/trueforge-ui/test/routing/sessionRouting.test.tsx
@@ -0,0 +1,223 @@
+// @vitest-environment jsdom
+import {
+ AssistantRuntimeProvider,
+ useExternalStoreRuntime,
+ type ExternalStoreThreadListAdapter,
+ type ThreadMessageLike,
+} from '@assistant-ui/react';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { useState, type ReactNode } from 'react';
+import { MemoryRouter, useLocation, useNavigate } from 'react-router-dom';
+import { describe, expect, it, vi } from 'vitest';
+
+import { CompactLayoutProvider } from '@/atoms/lib/CompactLayoutContext.js';
+import type { ThreadListRowProps } from '@/atoms/ThreadListRow.js';
+import { ThreadListContainer } from '@/containers/ThreadListContainer.js';
+import { resolveRoutesConfig } from '@/routing/paths.js';
+import { RemoteIdRouteBridge } from '@/routing/RemoteIdRouteBridge.js';
+import { ShellRouteSync } from '@/routing/ShellRouteSync.js';
+import { ShellModeProvider } from '@/server/ShellModeContext.js';
+import { SlotsProvider } from '@/theme/SlotsProvider.js';
+
+const routes = resolveRoutesConfig();
+
+let pathname = '';
+let search = '';
+let hash = '';
+
+function CaptureLocation() {
+ const location = useLocation();
+ pathname = location.pathname;
+ search = location.search;
+ hash = location.hash;
+ return null;
+}
+
+function BackButton() {
+ const navigate = useNavigate();
+ return (
+ <button type="button" onClick={() => navigate(-1)}>
+ Go back
+ </button>
+ );
+}
+
+function ThreadListRowOverride({ title, onSelect }: ThreadListRowProps) {
+ return (
+ <button type="button" onClick={onSelect}>
+ {title}
+ </button>
+ );
+}
+
+function RuntimeHarness({ threadList, children }: { threadList: ExternalStoreThreadListAdapter; children: ReactNode }) {
+ const runtime = useExternalStoreRuntime<ThreadMessageLike>({
+ messages: [],
+ convertMessage: message => message,
+ onNew: async () => {},
+ adapters: { threadList },
+ });
+ return <AssistantRuntimeProvider runtime={runtime}>{children}</AssistantRuntimeProvider>;
+}
+
+/** Mirrors production: sync outside the chat runtime, remote-id bridge inside it. */
+function Harness({
+ threads,
+ onSwitchToThread,
+}: {
+ threads: NonNullable<ExternalStoreThreadListAdapter['threads']>;
+ onSwitchToThread?: (id: string) => void;
+}) {
+ const [activeRemoteId, setActiveRemoteId] = useState<string | undefined>(undefined);
+ const [threadId, setThreadId] = useState('thread-draft');
+ return (
+ <SlotsProvider overrides={{ ThreadListRow: ThreadListRowOverride }}>
+ <ShellModeProvider agentConfig={{ mode: 'AgentLibraryWithComposer' }}>
+ <ShellRouteSync routes={routes} activeRemoteId={activeRemoteId} initialSettingsOpen={false} />
+ <RuntimeHarness
+ threadList={{
+ threadId,
+ threads,
+ onSwitchToThread: async id => {
+ onSwitchToThread?.(id);
+ setThreadId(id);
+ },
+ }}
+ >
+ <RemoteIdRouteBridge onRemoteIdChange={setActiveRemoteId} />
+ <CompactLayoutProvider>
+ <ThreadListContainer />
+ </CompactLayoutProvider>
+ </RuntimeHarness>
+ </ShellModeProvider>
+ </SlotsProvider>
+ );
+}
+
+describe('selecting a session updates the URL', () => {
+ it('routes to /sessions/:id when picking a history row', async () => {
+ const onSwitchToThread = vi.fn(async () => {});
+ render(
+ <MemoryRouter initialEntries={['/']}>
+ <CaptureLocation />
+ <Harness
+ threads={[
+ { status: 'regular', id: 'thread-draft', title: 'New Chat' },
+ { status: 'regular', id: 'thread-2', remoteId: 'session-2', title: 'Second' },
+ ]}
+ onSwitchToThread={onSwitchToThread}
+ />
+ </MemoryRouter>,
+ );
+
+ expect(pathname).toBe('/');
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: 'Second' }));
+ });
+
+ await waitFor(() => {
+ expect(onSwitchToThread).toHaveBeenCalledWith('thread-2');
+ });
+ await waitFor(() => {
+ expect(pathname).toBe('/sessions/session-2');
+ });
+ });
+
+ // Reuse via switchToThread never clears pendingSessionId, so a session opened
+ // through the shell (deep link, agent row) must not pin the URL afterwards.
+ it('follows a pick made after the shell already holds a pending session', async () => {
+ render(
+ <MemoryRouter initialEntries={['/sessions/session-1']}>
+ <CaptureLocation />
+ <Harness
+ threads={[
+ { status: 'regular', id: 'thread-draft', title: 'New Chat' },
+ { status: 'regular', id: 'thread-1', remoteId: 'session-1', title: 'First' },
+ { status: 'regular', id: 'thread-2', remoteId: 'session-2', title: 'Second' },
+ ]}
+ />
+ </MemoryRouter>,
+ );
+
+ await waitFor(() => {
+ expect(pathname).toBe('/sessions/session-1');
+ });
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: 'Second' }));
+ });
+ await waitFor(() => {
+ expect(pathname).toBe('/sessions/session-2');
+ });
+ });
+
+ // The live thread leads the derived place, so Back must not be dragged forward
+ // again by the thread the runtime still has mounted.
+ it('stays put when Back moves between two sessions', async () => {
+ render(
+ <MemoryRouter initialEntries={['/']}>
+ <CaptureLocation />
+ <BackButton />
+ <Harness
+ threads={[
+ { status: 'regular', id: 'thread-draft', title: 'New Chat' },
+ { status: 'regular', id: 'thread-1', remoteId: 'session-1', title: 'First' },
+ { status: 'regular', id: 'thread-2', remoteId: 'session-2', title: 'Second' },
+ ]}
+ />
+ </MemoryRouter>,
+ );
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: 'First' }));
+ });
+ await waitFor(() => {
+ expect(pathname).toBe('/sessions/session-1');
+ });
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: 'Second' }));
+ });
+ await waitFor(() => {
+ expect(pathname).toBe('/sessions/session-2');
+ });
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: 'Go back' }));
+ });
+ expect(pathname).toBe('/sessions/session-1');
+
+ // Let every follow-up effect settle: the URL must not bounce forward.
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(pathname).toBe('/sessions/session-1');
+ });
+
+ // The shell owns the pathname only; host query state must survive navigation.
+ it('keeps query string and hash when the place changes', async () => {
+ render(
+ <MemoryRouter initialEntries={['/sessions/session-1?tenant=acme#top']}>
+ <CaptureLocation />
+ <Harness
+ threads={[
+ { status: 'regular', id: 'thread-draft', title: 'New Chat' },
+ { status: 'regular', id: 'thread-1', remoteId: 'session-1', title: 'First' },
+ { status: 'regular', id: 'thread-2', remoteId: 'session-2', title: 'Second' },
+ ]}
+ />
+ </MemoryRouter>,
+ );
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: 'Second' }));
+ });
+
+ await waitFor(() => {
+ expect(pathname).toBe('/sessions/session-2');
+ });
+ expect(search).toBe('?tenant=acme');
+ expect(hash).toBe('#top');
+ });
+});
diff --git a/packages/trueforge-ui/test/routing/withRouter.integration.test.tsx b/packages/trueforge-ui/test/routing/withRouter.integration.test.tsx
new file mode 100644
index 000000000..8441653fb
--- /dev/null
+++ b/packages/trueforge-ui/test/routing/withRouter.integration.test.tsx
@@ -0,0 +1,186 @@
+// @vitest-environment jsdom
+import { useExternalStoreRuntime, type ThreadMessageLike } from '@assistant-ui/react';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { useState } from 'react';
+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
+
+import { createMockAgentUIServer } from '../server/mockServer.js';
+
+/** Thread list driven by the test: a local draft plus one remote session row. */
+const threadState = {
+ threadId: 'thread-draft',
+ setThreadId: (_id: string) => {},
+};
+
+vi.mock('@truefoundry/assistant-ui-runtime', () => ({
+ trueFoundryAttachmentAdapter: {},
+ useTrueFoundryAgentRuntime: () => {
+ const [threadId, setThreadId] = useState(threadState.threadId);
+ threadState.setThreadId = setThreadId;
+ return useExternalStoreRuntime<ThreadMessageLike>({
+ messages: [],
+ isRunning: false,
+ convertMessage: (message: ThreadMessageLike) => message,
+ onNew: async () => {},
+ adapters: {
+ threadList: {
+ threadId,
+ threads: [
+ { status: 'regular', id: 'thread-draft', title: 'New Chat' },
+ { status: 'regular', id: 'thread-2', remoteId: 'session-2', title: 'Second' },
+ ],
+ onSwitchToThread: async id => {
+ setThreadId(id);
+ },
+ },
+ },
+ });
+ },
+ useTrueFoundryCancel: () => vi.fn(),
+ useTrueFoundryToolResponses: () => ({ pending: [] }),
+ useTrueFoundryRespondToToolApproval: () => vi.fn(),
+ useTrueFoundryMcpAuth: () => ({ pending: [], connect: vi.fn(), continue: vi.fn() }),
+ useTrueFoundryHistoryPagination: () => ({
+ isLoadingMore: false,
+ hasMore: false,
+ loadMore: vi.fn(),
+ }),
+ useTrueFoundryAgentSpec: () => ({
+ agentSpec: { model: { name: 'openai-main/gpt-4.1' } },
+ }),
+ useTrueFoundryFlushAgentSpec: () => async () => {},
+ useTrueFoundryAdoptAgentSpec: () => vi.fn(),
+ useTrueFoundryUpdateAgentSpec: () => vi.fn(),
+}));
+
+import { CompactLayoutProvider } from '@/atoms/lib/CompactLayoutContext.js';
+import type { ThreadListRowProps } from '@/atoms/ThreadListRow.js';
+import { ThreadListContainer } from '@/containers/ThreadListContainer.js';
+import { TrueForgeUI } from '@/containers/TrueForgeUI.js';
+import { useShellMode } from '@/server/ShellModeContext.js';
+
+beforeAll(() => {
+ HTMLDialogElement.prototype.showModal = function showModal() {
+ this.setAttribute('open', '');
+ };
+ HTMLDialogElement.prototype.close = function close() {
+ this.removeAttribute('open');
+ this.dispatchEvent(new Event('close'));
+ };
+});
+
+afterEach(() => {
+ window.history.replaceState(null, '', '/');
+});
+
+function ThreadListRowOverride({ title, onSelect }: ThreadListRowProps) {
+ return (
+ <button type="button" onClick={onSelect}>
+ {title}
+ </button>
+ );
+}
+
+/** Exposes shell state so boot behaviour is observable from the DOM. */
+function ShellProbe() {
+ const shell = useShellMode();
+ const mode = shell.mode;
+ return (
+ <>
+ <div data-testid="pending">{shell.pendingSessionId ?? 'none'}</div>
+ <div data-testid="binding">
+ {mode.status === 'idle' ? 'idle' : `${mode.isMutable ? 'mutable' : 'immutable'}:${mode.agentName ?? '-'}`}
+ </div>
+ </>
+ );
+}
+
+function ThreadListHost() {
+ return (
+ <CompactLayoutProvider>
+ <ThreadListContainer />
+ </CompactLayoutProvider>
+ );
+}
+
+function renderApp() {
+ return render(
+ <TrueForgeUI
+ server={createMockAgentUIServer({})}
+ agentConfig={{ mode: 'AgentLibraryWithComposer' }}
+ withRouter
+ layout={() => <ShellProbe />}
+ overrides={{ ThreadListRow: ThreadListRowOverride }}
+ />,
+ );
+}
+
+describe('withRouter end to end', () => {
+ it('applies a /sessions/:id deep link on boot', async () => {
+ window.history.replaceState(null, '', '/sessions/session-2');
+ renderApp();
+
+ await waitFor(() => {
+ expect(screen.getByTestId('pending')).toHaveTextContent('session-2');
+ });
+ expect(window.location.pathname).toBe('/sessions/session-2');
+ });
+
+ // A URL carries only an id, so the session's own identity must decide the
+ // chrome; assuming "mutable draft" turns an agent chat into a blank one.
+ it('binds a deep-linked agent session to that agent', async () => {
+ window.history.replaceState(null, '', '/sessions/session-agent');
+ render(
+ <TrueForgeUI
+ server={createMockAgentUIServer({
+ getSession: async () => ({
+ id: 'session-agent',
+ title: 'Agent chat',
+ agentName: 'my-agent',
+ isMutable: false,
+ createdAt: '2026-01-01T00:00:00Z',
+ updatedAt: '2026-01-01T00:00:00Z',
+ }),
+ })}
+ agentConfig={{ mode: 'AgentLibraryWithComposer' }}
+ withRouter
+ layout={() => <ShellProbe />}
+ overrides={{ ThreadListRow: ThreadListRowOverride }}
+ />,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByTestId('binding')).toHaveTextContent('immutable:my-agent');
+ });
+ expect(screen.getByTestId('pending')).toHaveTextContent('session-agent');
+ expect(window.location.pathname).toBe('/sessions/session-agent');
+ });
+
+ it('pushes /sessions/:id when a history row is picked', async () => {
+ render(
+ <TrueForgeUI
+ server={createMockAgentUIServer({})}
+ agentConfig={{ mode: 'AgentLibraryWithComposer' }}
+ withRouter
+ layout={() => (
+ <>
+ <ShellProbe />
+ <ThreadListHost />
+ </>
+ )}
+ overrides={{ ThreadListRow: ThreadListRowOverride }}
+ />,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'Second' })).toBeInTheDocument();
+ });
+ expect(window.location.pathname).toBe('/');
+
+ fireEvent.click(screen.getByRole('button', { name: 'Second' }));
+
+ await waitFor(() => {
+ expect(window.location.pathname).toBe('/sessions/session-2');
+ });
+ });
+});
diff --git a/packages/trueforge-ui/tsup.config.ts b/packages/trueforge-ui/tsup.config.ts
index 34d053219..53ed3bf30 100644
--- a/packages/trueforge-ui/tsup.config.ts
+++ b/packages/trueforge-ui/tsup.config.ts
@@ -32,6 +32,8 @@ export default defineConfig({
external: [
'react',
'react-dom',
+ 'react-router',
+ 'react-router-dom',
'@assistant-ui/react',
'@assistant-ui/core',
'@openuidev/react-headless',
diff --git a/packages/trueforge/src/frontend.ts b/packages/trueforge/src/frontend.ts
index e2d30e283..547e63197 100644
--- a/packages/trueforge/src/frontend.ts
+++ b/packages/trueforge/src/frontend.ts
@@ -58,7 +58,29 @@ export function mountFrontend(app: OpenAPIHono, dir: string): boolean {
return serveCompressed(c, next);
};
+ const serveAppShell = serveStatic({ root: dir, rewriteRequestPath: () => '/index.html', precompressed: true });
+
+ /**
+ * Client routes (`/sessions/{id}`, `/settings`) have no file on disk, so a
+ * deep link only reaches the app when the shell answers the navigation.
+ * Runs after `serveBuild`, so real files still win; requests that do not
+ * accept HTML keep their 404 rather than getting the shell as a fake asset.
+ */
+ const serveSpaFallback: MiddlewareHandler = async (c, next) => {
+ if (isServerPath(c.req.path)) return next();
+ if (c.req.method !== 'GET' && c.req.method !== 'HEAD') return next();
+ if (c.req.header('accept')?.includes('text/html') !== true) return next();
+
+ const response = await serveAppShell(c, next);
+ if (response instanceof Response) {
+ response.headers.set('Cache-Control', REVALIDATE_CACHE_CONTROL);
+ response.headers.set('Vary', 'Accept-Encoding');
+ }
+ return response;
+ };
+
app.use('/*', serveBuild);
+ app.use('/*', serveSpaFallback);
return true;
}
diff --git a/packages/trueforge/tests/unit/frontend.test.ts b/packages/trueforge/tests/unit/frontend.test.ts
new file mode 100644
index 000000000..211758559
--- /dev/null
+++ b/packages/trueforge/tests/unit/frontend.test.ts
@@ -0,0 +1,58 @@
+import { OpenAPIHono } from '@hono/zod-openapi';
+import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { mountFrontend } from '../../src/frontend';
+
+function buildDir(): string {
+ const dir = mkdtempSync(path.join(tmpdir(), 'trueforge-frontend-'));
+ writeFileSync(path.join(dir, 'index.html'), '<html><body><div id="root"></div></body></html>');
+ mkdirSync(path.join(dir, 'assets'));
+ writeFileSync(path.join(dir, 'assets', 'app-abc123.js'), 'console.log("app");');
+ return dir;
+}
+
+function appWithFrontend(dir: string): OpenAPIHono {
+ const app = new OpenAPIHono();
+ app.get('/api/v1/health', c => c.json({ ok: true }));
+ mountFrontend(app, dir);
+ return app;
+}
+
+const HTML_ACCEPT = { accept: 'text/html,application/xhtml+xml' };
+
+describe('mountFrontend', () => {
+ it('reports whether the directory holds a build', () => {
+ expect(mountFrontend(new OpenAPIHono(), path.join(tmpdir(), 'trueforge-missing-build'))).toBe(false);
+ expect(mountFrontend(new OpenAPIHono(), buildDir())).toBe(true);
+ });
+
+ it('serves the app shell for client-only deep links', async () => {
+ const app = appWithFrontend(buildDir());
+
+ for (const clientPath of ['/', '/settings', '/sessions/abc123', '/agents/my-agent']) {
+ const response = await app.request(clientPath, { headers: HTML_ACCEPT });
+ expect(response.status).toBe(200);
+ await expect(response.text()).resolves.toContain('id="root"');
+ }
+ });
+
+ it('keeps real files, API routes, and missing assets intact', async () => {
+ const app = appWithFrontend(buildDir());
+
+ const asset = await app.request('/assets/app-abc123.js');
+ expect(asset.status).toBe(200);
+ await expect(asset.text()).resolves.toContain('console.log');
+
+ const api = await app.request('/api/v1/health', { headers: HTML_ACCEPT });
+ expect(api.status).toBe(200);
+ await expect(api.json()).resolves.toEqual({ ok: true });
+
+ // A missing asset must 404 rather than receive HTML under a JS content type.
+ expect((await app.request('/assets/gone-000000.js')).status).toBe(404);
+
+ // Navigations are the only thing the shell answers.
+ expect((await app.request('/sessions/abc123', { method: 'POST', headers: HTML_ACCEPT })).status).toBe(404);
+ });
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 55f0119db..56b55690d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -78,6 +78,9 @@ importers:
react-dom:
specifier: ^19.2.4
version: 19.2.8([email protected])
+ react-router-dom:
+ specifier: ^7.18.2
devDependencies:
'@types/react':
specifier: ^19.2.17
@@ -461,6 +464,9 @@ importers:
react-dom:
specifier: ^19.2.4
version: 19.2.8([email protected])
+ react-router-dom:
+ specifier: ^7.18.2
tailwindcss:
specifier: ^4.3.2
version: 4.3.3
@@ -4366,6 +4372,10 @@ packages:
resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==}
engines: {node: '>= 0.6'}
+ resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==}
+ engines: {node: '>=18'}
+
resolution: {integrity: sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==}
engines: {node: '>= 0.10'}
@@ -6450,6 +6460,23 @@ packages:
'@types/react':
optional: true
+ resolution: {integrity: sha512-AIKJ/jgGlFb3EbfCXk5Gzshiwt+l3mqbCrNjmEWMMjqQxNJ3svBa6bgzFyCC2Sw3RA0VWF1kg3uQf2OFhxb8hw==}
+ engines: {node: '>=20.0.0'}
+ peerDependencies:
+ react: '>=18'
+ react-dom: '>=18'
+
+ resolution: {integrity: sha512-aUVMjFm3GAPTTZL7oYr5E7ETiqfQCHRLH+B+5afnICvf0r7kkK4eR6SMuwbSTJw/7t+12khT/Kahij49fqOCIg==}
+ engines: {node: '>=20.0.0'}
+ peerDependencies:
+ react: '>=18'
+ react-dom: '>=18'
+ peerDependenciesMeta:
+ react-dom:
+ optional: true
+
resolution: {integrity: sha512-gnGKTpYwqL0Iii09gHobNolvX4Kiq4PKx6eWBCYYix+8cdw+cGo3do906l1NBPKkSWx1DghC1dlWG9L2uGd61Q==}
peerDependencies:
@@ -6655,6 +6682,9 @@ packages:
resolution: {integrity: sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==}
engines: {node: '>= 18'}
+ resolution: {integrity: sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==}
+
resolution: {integrity: sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==}
@@ -11543,6 +11573,8 @@ snapshots:
+
dependencies:
object-assign: 4.1.1
@@ -14227,6 +14259,20 @@ snapshots:
optionalDependencies:
'@types/react': 19.2.17
+ dependencies:
+ react: 19.2.8
+ react-dom: 19.2.8([email protected])
+
+ dependencies:
+ cookie: 1.1.1
+ react: 19.2.8
+ set-cookie-parser: 2.7.2
+ optionalDependencies:
+ react-dom: 19.2.8([email protected])
+
dependencies:
fast-equals: 5.4.1
@@ -14529,6 +14575,8 @@ snapshots:
transitivePeerDependencies:
- supports-color
+