Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/20260817113112-trueforge-ui-with-router.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@truefoundry/trueforge-ui': minor
---

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.
Comment thread
govindavashishtha marked this conversation as resolved.
Resolved
3 changes: 2 additions & 1 deletion packages/frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions packages/frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ export function App() {
},
}}
layout="sidebar"
withRouter
agentConfig={{
mode: 'AgentLibraryWithComposer',
defaultAgentSpec: boot.defaultAgentSpec,
Expand Down
52 changes: 52 additions & 0 deletions packages/trueforge-ui/docs/customization.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 7 additions & 2 deletions packages/trueforge-ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand All @@ -89,6 +90,9 @@
},
"@types/react": {
"optional": true
},
"react-router-dom": {
"optional": true
Comment thread
govindavashishtha marked this conversation as resolved.
Resolved
}
},
"dependencies": {
Expand All @@ -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",
Expand All @@ -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"
},
Expand All @@ -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",
Expand Down
246 changes: 18 additions & 228 deletions packages/trueforge-ui/src/containers/TrueForgeUI.tsx
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -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} />;
}
Loading
Loading