The open-source agent harness - the runtime layer that turns an LLM into a working agent.
Add customActionRenderers so hosts can pause on client-side tools with custom UI. (#442)
Govinda Vashishtha16feb2966fda
diff --git a/.changeset/custom-action-renderers.md b/.changeset/custom-action-renderers.mdnew file mode 100644index 000000000..a65d5696d--- /dev/null+++ b/.changeset/custom-action-renderers.md@@ -0,0 +1,5 @@+---+"@truefoundry/trueforge-ui": minor+---++Add `customActionRenderers` so hosts can pause the composer on client-side tools with their own UI and resume via `onSubmit(content)`.diff --git a/packages/frontend/src/App.tsx b/packages/frontend/src/App.tsxindex 8c1b348c4..ad298f723 100644--- a/packages/frontend/src/App.tsx+++ b/packages/frontend/src/App.tsx@@ -162,11 +162,6 @@ export function App() {<div className="app-root"><TrueForgeUIserver={{ type: 'trueforge', baseUrl: '/', fetch: authAwareFetch }}- theme={{- brand: {- name: 'TrueForge',- },- }}layout="sidebar"withRouteragentConfig={{diff --git a/packages/trueforge-ui/src/containers/ComposerContainer.tsx b/packages/trueforge-ui/src/containers/ComposerContainer.tsxindex 6a18bf005..009d1f1ae 100644--- a/packages/trueforge-ui/src/containers/ComposerContainer.tsx+++ b/packages/trueforge-ui/src/containers/ComposerContainer.tsx@@ -11,6 +11,7 @@ import { useOptionalShellMode } from '../server/ShellModeContext.js';import { SlotsProvider, useSlot, useSlotIsDefault } from '../theme/SlotsProvider.js';import { AskUserContainer } from './AskUserContainer.js';import { ComposerAttachmentsContainer } from './AttachmentsContainer.js';+import { CustomActionContainer } from './CustomActionContainer.js';import { McpAuthContainer } from './McpAuthContainer.js';export type ComposerContainerProps = {@@ -110,6 +111,9 @@ export function ComposerContainer({if (pauseView.kind === 'mcp') {return <McpAuthContainer />;}+ if (pauseView.kind === 'custom') {+ return <CustomActionContainer />;+ }if (pauseView.kind === 'ask-user') {return <AskUserContainer />;}diff --git a/packages/trueforge-ui/src/containers/CustomActionContainer.tsx b/packages/trueforge-ui/src/containers/CustomActionContainer.tsxnew file mode 100644index 000000000..a757eed3e--- /dev/null+++ b/packages/trueforge-ui/src/containers/CustomActionContainer.tsx@@ -0,0 +1,31 @@+'use client';++import { useThreadIsRunning } from '@assistant-ui/core/react';+import { useTrueFoundryToolResponses } from '@truefoundry/assistant-ui-runtime';+import { useCallback } from 'react';++import { useOptionalCustomActionRenderers } from '../server/CustomActionRenderersContext.js';++/** Host custom-action UI for a pending client-side tool response. */+export function CustomActionContainer() {+ const renderers = useOptionalCustomActionRenderers();+ const { pending, respond } = useTrueFoundryToolResponses();+ const isRunning = useThreadIsRunning();+ const item = pending[0];++ const onSubmit = useCallback(+ (content: string) => {+ if (item == null) return;+ const trimmed = content.trim();+ if (!trimmed) return;+ respond({ toolCallId: item.toolCallId, content: trimmed });+ },+ [item, respond],+ );++ if (item == null || item.toolName == null) return null;+ const Renderer = renderers?.[item.toolName];+ if (Renderer == null) return null;++ return <Renderer args={item.args ?? {}} disabled={isRunning} onSubmit={onSubmit} />;+}diff --git a/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsx b/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsxindex 02c537984..7bdb3d6a3 100644--- a/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsx+++ b/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsx@@ -9,6 +9,7 @@ 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 { CustomActionRenderersProvider, type CustomActionRenderers } from '../server/CustomActionRenderersContext.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';@@ -45,6 +46,11 @@ export type TrueForgeUIProps = {agentConfig?: AgentConfig;/** Open settings on first paint only (host boot with no models configured). */initialSettingsOpen?: boolean;+ /**+ * Host UI for pending client-side tools, keyed by tool name.+ * When a pending tool matches, the composer mounts that component instead of Ask User.+ */+ customActionRenderers?: CustomActionRenderers;/*** 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@@ -214,6 +220,7 @@ export function TrueForgeUIShell(props: TrueForgeUIShellProps) {initialSettingsOpen = false,server: serverConfig,onError,+ customActionRenderers,resolvedRoutes,routes: _routes,...providerRest@@ -244,27 +251,29 @@ export function TrueForgeUIShell(props: TrueForgeUIShellProps) {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>+ <CustomActionRenderersProvider renderers={customActionRenderers}>+ <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>+ </CustomActionRenderersProvider></SlotsProvider>);}diff --git a/packages/trueforge-ui/src/hooks/useComposerPauseView.ts b/packages/trueforge-ui/src/hooks/useComposerPauseView.tsindex 1b28f4114..884533e54 100644--- a/packages/trueforge-ui/src/hooks/useComposerPauseView.ts+++ b/packages/trueforge-ui/src/hooks/useComposerPauseView.ts@@ -3,6 +3,8 @@import { useAuiState } from '@assistant-ui/react';import { useTrueFoundryToolResponses } from '@truefoundry/assistant-ui-runtime';+import { useOptionalCustomActionRenderers } from '../server/CustomActionRenderersContext.js';+export type ThreadPauseState = {thread: {messages: readonly {@@ -22,18 +24,27 @@ export function threadHasPendingMcpAuth(s: ThreadPauseState): boolean {return (last.metadata?.custom as { pendingMcpAuth?: boolean } | undefined)?.pendingMcpAuth === true;}-export type ComposerPauseView = { kind: 'mcp' } | { kind: 'ask-user' } | { kind: 'compose' };+export type ComposerPauseView =+ { kind: 'mcp' } | { kind: 'custom'; toolName: string } | { kind: 'ask-user' } | { kind: 'compose' };/** Shared composer pause detection for default and custom composer containers. */export function useComposerPauseView(): ComposerPauseView {const mcpPending = useAuiState(threadHasPendingMcpAuth);const { pending: toolResponsesPending } = useTrueFoundryToolResponses();+ const customActionRenderers = useOptionalCustomActionRenderers();if (mcpPending) {return { kind: 'mcp' };}- if (toolResponsesPending.length > 0) {++ const firstPending = toolResponsesPending[0];+ if (firstPending != null) {+ const toolName = firstPending.toolName;+ if (toolName != null && customActionRenderers?.[toolName] != null) {+ return { kind: 'custom', toolName };+ }return { kind: 'ask-user' };}+return { kind: 'compose' };}diff --git a/packages/trueforge-ui/src/index.ts b/packages/trueforge-ui/src/index.tsindex 42f16c6b2..9cc5cbf9c 100644--- a/packages/trueforge-ui/src/index.ts+++ b/packages/trueforge-ui/src/index.ts@@ -158,6 +158,7 @@ export {} from './containers/AttachmentsContainer.js';export { ComposerContainer } from './containers/ComposerContainer.js';export type { ComposerContainerProps } from './containers/ComposerContainer.js';+export { CustomActionContainer } from './containers/CustomActionContainer.js';export { HistoryLoaderContainer } from './containers/HistoryLoaderContainer.js';export { McpAuthContainer } from './containers/McpAuthContainer.js';export { default as PostMcpOauthScreen } from './containers/McpOauthContainer/PostMcpOauthScreen.js';@@ -228,6 +229,11 @@ export { SelectAgentEmptyState } from './atoms/SelectAgentEmptyState.js';export { ShellActionsActionSlot } from './atoms/ShellActionsActionSlot.js';export { createTrueFoundryServer } from './server/createTrueFoundryServer.js';export type { CreateTrueFoundryServerOptions, TrueFoundryServer } from './server/createTrueFoundryServer.js';+export {+ CustomActionRenderersProvider,+ useOptionalCustomActionRenderers,+} from './server/CustomActionRenderersContext.js';+export type { CustomActionRendererProps, CustomActionRenderers } from './server/CustomActionRenderersContext.js';export {ServerProvider,useCatalogServer,diff --git a/packages/trueforge-ui/src/server/CustomActionRenderersContext.tsx b/packages/trueforge-ui/src/server/CustomActionRenderersContext.tsxnew file mode 100644index 000000000..9cc09e183--- /dev/null+++ b/packages/trueforge-ui/src/server/CustomActionRenderersContext.tsx@@ -0,0 +1,31 @@+'use client';++import { createContext, useContext, type ComponentType, type ReactNode } from 'react';++/** Props Trueforge passes to a host-registered custom action renderer. */+export type CustomActionRendererProps = {+ args: Record<string, unknown>;+ disabled: boolean;+ /** Resume the paused client-side tool with a non-empty string result. */+ onSubmit: (content: string) => void;+};++/** Map of client-side tool name → host UI for composer pause. */+export type CustomActionRenderers = Record<string, ComponentType<CustomActionRendererProps>>;++const CustomActionRenderersContext = createContext<CustomActionRenderers | undefined>(undefined);++export function CustomActionRenderersProvider({+ renderers,+ children,+}: {+ renderers?: CustomActionRenderers;+ children: ReactNode;+}) {+ return <CustomActionRenderersContext.Provider value={renderers}>{children}</CustomActionRenderersContext.Provider>;+}++/** Host-registered custom action renderers, or `undefined` when none were provided. */+export function useOptionalCustomActionRenderers(): CustomActionRenderers | undefined {+ return useContext(CustomActionRenderersContext);+}diff --git a/packages/trueforge-ui/test/containers/ComposerContainer.test.tsx b/packages/trueforge-ui/test/containers/ComposerContainer.test.tsxindex 9288b4f10..791cd7969 100644--- a/packages/trueforge-ui/test/containers/ComposerContainer.test.tsx+++ b/packages/trueforge-ui/test/containers/ComposerContainer.test.tsx@@ -5,6 +5,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { ComposerContainer } from '@/containers/ComposerContainer.js';import { ComposerBusyProvider } from '@/hooks/useComposerBusyState.js';+import {+ CustomActionRenderersProvider,+ type CustomActionRendererProps,+} from '@/server/CustomActionRenderersContext.js';import { ShellModeProvider } from '@/server/ShellModeContext.js';import { SlotsProvider } from '@/theme/SlotsProvider.js';import { RuntimeHarness } from './RuntimeHarness.js';@@ -13,12 +17,33 @@ const agentSpecState: { agentSpec: { model: { name: string } } | undefined } = {agentSpec: { model: { name: 'test/model' } },};+const toolResponsesState = vi.hoisted(() => ({+ pending: [] as Array<{ toolCallId: string; toolName?: string; args?: Record<string, unknown> }>,+ respond: vi.fn(),+}));+vi.mock('@truefoundry/assistant-ui-runtime', () => ({useTrueFoundryCancel: () => vi.fn(),- useTrueFoundryToolResponses: () => ({ pending: [] }),+ useTrueFoundryToolResponses: () => toolResponsesState,useTrueFoundryAgentSpec: () => ({ agentSpec: agentSpecState.agentSpec }),}));+vi.mock('@assistant-ui/core/react', async importOriginal => {+ const actual = await importOriginal<typeof import('@assistant-ui/core/react')>();+ return {+ ...actual,+ useThreadIsRunning: () => false,+ };+});++function SecretSelectProbe({ onSubmit }: CustomActionRendererProps) {+ return (+ <button type="button" onClick={() => onSubmit('chosen-secret')}>+ Secret selector+ </button>+ );+}+function renderComposer(onNew?: (message: AppendMessage) => Promise<void>) {return render(<RuntimeHarness messages={[]} onNew={onNew}>@@ -32,6 +57,8 @@ function renderComposer(onNew?: (message: AppendMessage) => Promise<void>) {describe('ComposerContainer', () => {beforeEach(() => {agentSpecState.agentSpec = { model: { name: 'test/model' } };+ toolResponsesState.pending = [];+ toolResponsesState.respond = vi.fn();});it('wraps the composer in an attachment dropzone by default', () => {renderComposer();@@ -141,4 +168,27 @@ describe('ComposerContainer', () => {expect(screen.getByText('Custom left')).toBeInTheDocument();expect(screen.getByText('Custom right')).toBeInTheDocument();});++ it('mounts a registered custom action renderer instead of the composer', () => {+ toolResponsesState.pending = [{ toolCallId: 'tc-1', toolName: 'secret_select', args: { secrets: ['a'] } }];++ render(+ <CustomActionRenderersProvider renderers={{ secret_select: SecretSelectProbe }}>+ <RuntimeHarness messages={[]}>+ <ComposerBusyProvider>+ <ComposerContainer />+ </ComposerBusyProvider>+ </RuntimeHarness>+ </CustomActionRenderersProvider>,+ );++ expect(screen.getByRole('button', { name: 'Secret selector' })).toBeInTheDocument();+ expect(screen.queryByRole('textbox', { name: 'Message input' })).not.toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: 'Secret selector' }));+ expect(toolResponsesState.respond).toHaveBeenCalledWith({+ toolCallId: 'tc-1',+ content: 'chosen-secret',+ });+ });});diff --git a/packages/trueforge-ui/test/containers/CustomActionContainer.test.tsx b/packages/trueforge-ui/test/containers/CustomActionContainer.test.tsxnew file mode 100644index 000000000..584dd13a8--- /dev/null+++ b/packages/trueforge-ui/test/containers/CustomActionContainer.test.tsx@@ -0,0 +1,104 @@+// @vitest-environment jsdom+import { fireEvent, render, screen } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { CustomActionContainer } from '@/containers/CustomActionContainer.js';+import {+ CustomActionRenderersProvider,+ type CustomActionRendererProps,+} from '@/server/CustomActionRenderersContext.js';++const useToolResponses = vi.hoisted(() => vi.fn());+const useThreadRunning = vi.hoisted(() => vi.fn());++vi.mock('@truefoundry/assistant-ui-runtime', () => ({+ useTrueFoundryToolResponses: () => useToolResponses(),+}));++vi.mock('@assistant-ui/core/react', () => ({+ useThreadIsRunning: () => useThreadRunning(),+}));++function SecretSelectProbe({ args, disabled, onSubmit }: CustomActionRendererProps) {+ const secrets = Array.isArray(args.secrets)+ ? args.secrets.filter((value): value is string => typeof value === 'string')+ : [];+ return (+ <section data-testid="secret-select-probe" data-disabled={String(disabled)}>+ <span data-testid="secret-count">{secrets.length}</span>+ <button type="button" disabled={disabled} onClick={() => onSubmit('prod-db')}>+ Choose prod-db+ </button>+ <button type="button" disabled={disabled} onClick={() => onSubmit(' ')}>+ Choose blank+ </button>+ </section>+ );+}++function renderSubject() {+ return render(+ <CustomActionRenderersProvider renderers={{ secret_select: SecretSelectProbe }}>+ <CustomActionContainer />+ </CustomActionRenderersProvider>,+ );+}++describe('CustomActionContainer', () => {+ const respond = vi.fn();++ beforeEach(() => {+ vi.clearAllMocks();+ useThreadRunning.mockReturnValue(false);+ useToolResponses.mockReturnValue({ pending: [], respond });+ });++ it('renders nothing while there is no pending tool response', () => {+ renderSubject();+ expect(screen.queryByTestId('secret-select-probe')).not.toBeInTheDocument();+ });++ it('renders nothing when the pending tool has no registered renderer', () => {+ useToolResponses.mockReturnValue({+ pending: [{ toolCallId: 'tc-1', toolName: 'ask_user_question', args: {} }],+ respond,+ });+ renderSubject();+ expect(screen.queryByTestId('secret-select-probe')).not.toBeInTheDocument();+ });++ it('renders the host component and resumes with trimmed content', () => {+ useToolResponses.mockReturnValue({+ pending: [+ {+ toolCallId: 'tc-secret',+ toolName: 'secret_select',+ args: { secrets: ['prod-db', 'staging-db'] },+ },+ ],+ respond,+ });+ renderSubject();++ expect(screen.getByTestId('secret-select-probe')).toBeInTheDocument();+ expect(screen.getByTestId('secret-count')).toHaveTextContent('2');++ fireEvent.click(screen.getByRole('button', { name: 'Choose blank' }));+ expect(respond).not.toHaveBeenCalled();++ fireEvent.click(screen.getByRole('button', { name: 'Choose prod-db' }));+ expect(respond).toHaveBeenCalledWith({ toolCallId: 'tc-secret', content: 'prod-db' });+ });++ it('disables the host component while the thread is running', () => {+ useThreadRunning.mockReturnValue(true);+ useToolResponses.mockReturnValue({+ pending: [{ toolCallId: 'tc-secret', toolName: 'secret_select', args: {} }],+ respond,+ });+ renderSubject();++ expect(screen.getByTestId('secret-select-probe')).toHaveAttribute('data-disabled', 'true');+ expect(screen.getByRole('button', { name: 'Choose prod-db' })).toBeDisabled();+ });+});diff --git a/packages/trueforge-ui/test/hooks/useComposerPauseView.test.ts b/packages/trueforge-ui/test/hooks/useComposerPauseView.test.tsxsimilarity index 58%rename from packages/trueforge-ui/test/hooks/useComposerPauseView.test.tsrename to packages/trueforge-ui/test/hooks/useComposerPauseView.test.tsxindex 917080501..cc10eb600 100644--- a/packages/trueforge-ui/test/hooks/useComposerPauseView.test.ts+++ b/packages/trueforge-ui/test/hooks/useComposerPauseView.test.tsx@@ -1,5 +1,6 @@// @vitest-environment jsdomimport { renderHook } from '@testing-library/react';+import type { ReactNode } from 'react';import { beforeEach, describe, expect, it, vi } from 'vitest';const useAuiState = vi.hoisted(() => vi.fn());@@ -14,6 +15,13 @@ vi.mock('@truefoundry/assistant-ui-runtime', () => ({}));import { threadHasPendingMcpAuth, type ThreadPauseState, useComposerPauseView } from '@/hooks/useComposerPauseView.js';+import { CustomActionRenderersProvider } from '@/server/CustomActionRenderersContext.js';++function withRenderers(renderers: Record<string, () => null>) {+ return ({ children }: { children: ReactNode }) => (+ <CustomActionRenderersProvider renderers={renderers}>{children}</CustomActionRenderersProvider>+ );+}describe('threadHasPendingMcpAuth', () => {it('recognizes MCP authorization only on the latest requiring-action assistant message', () => {@@ -85,20 +93,60 @@ describe('useComposerPauseView', () => {expect(useAuiState).toHaveBeenCalledWith(threadHasPendingMcpAuth);});- it('shows the ask-user view while tool responses are pending', () => {- useToolResponses.mockReturnValue({ pending: [{ toolCallId: 'question-1' }] });+ it('shows the ask-user view while tool responses are pending without a custom renderer', () => {+ useToolResponses.mockReturnValue({ pending: [{ toolCallId: 'question-1', toolName: 'ask_user_question' }] });const { result } = renderHook(() => useComposerPauseView());expect(result.current).toEqual({ kind: 'ask-user' });});+ it('shows the custom view when the pending tool name is registered', () => {+ useToolResponses.mockReturnValue({+ pending: [{ toolCallId: 'tc-1', toolName: 'secret_select', args: {} }],+ });++ const { result } = renderHook(() => useComposerPauseView(), {+ wrapper: withRenderers({ secret_select: () => null }),+ });++ expect(result.current).toEqual({ kind: 'custom', toolName: 'secret_select' });+ });++ it('falls back to ask-user when a pending tool is not in the custom map', () => {+ useToolResponses.mockReturnValue({+ pending: [{ toolCallId: 'tc-1', toolName: 'secret_select', args: {} }],+ });++ const { result } = renderHook(() => useComposerPauseView(), {+ wrapper: withRenderers({ other_tool: () => null }),+ });++ expect(result.current).toEqual({ kind: 'ask-user' });+ });+it('gives MCP authorization precedence over pending tool responses', () => {useAuiState.mockReturnValue(true);- useToolResponses.mockReturnValue({ pending: [{ toolCallId: 'question-1' }] });+ useToolResponses.mockReturnValue({+ pending: [{ toolCallId: 'question-1', toolName: 'secret_select' }],+ });- const { result } = renderHook(() => useComposerPauseView());+ const { result } = renderHook(() => useComposerPauseView(), {+ wrapper: withRenderers({ secret_select: () => null }),+ });expect(result.current).toEqual({ kind: 'mcp' });});++ it('gives custom renderers precedence over ask-user for the same pending tool', () => {+ useToolResponses.mockReturnValue({+ pending: [{ toolCallId: 'question-1', toolName: 'ask_user_question', question: 'Continue?' }],+ });++ const { result } = renderHook(() => useComposerPauseView(), {+ wrapper: withRenderers({ ask_user_question: () => null }),+ });++ expect(result.current).toEqual({ kind: 'custom', toolName: 'ask_user_question' });+ });});diff --git a/packages/trueforge-ui/test/publicUiExports.test.ts b/packages/trueforge-ui/test/publicUiExports.test.tsindex 8fd9d6952..249a0e2c7 100644--- a/packages/trueforge-ui/test/publicUiExports.test.ts+++ b/packages/trueforge-ui/test/publicUiExports.test.ts@@ -31,6 +31,8 @@ const expectedRuntimeExports: Array<keyof typeof sdk> = ['ComposerRightSection','ComposerSendButton','ComposerShell',+ 'CustomActionContainer',+ 'CustomActionRenderersProvider','DEFAULT_AGENT_CONFIG','DraftCatalogProvider','DraftComposerLeftSection',@@ -126,6 +128,7 @@ const expectedRuntimeExports: Array<keyof typeof sdk> = ['useMCPAuth','useOptionalCatalogServer','useOptionalContentClassNames',+ 'useOptionalCustomActionRenderers','useOptionalServer','useOptionalShellMode','useServer',