The open-source agent harness - the runtime layer that turns an LLM into a working agent.
refactor: streamline agent search and model selection components (#102)
Govinda Vashishtha38af15764619
diff --git a/packages/frontend/src/App.tsx b/packages/frontend/src/App.tsxindex 4f1428ffd..12a8f2421 100644--- a/packages/frontend/src/App.tsx+++ b/packages/frontend/src/App.tsx@@ -1,12 +1,5 @@-import {- createTrueFoundryServer,- TrueforgeUI,- useShellMode,- WelcomeScreen,- type SlotOverrides,- type WelcomeScreenProps,-} from '@truefoundry/trueforge-ui';-import { useEffect, useMemo, useRef, useState } from 'react';+import { createTrueFoundryServer, TrueforgeUI, type SlotOverrides } from '@truefoundry/trueforge-ui';+import { useEffect, useMemo, useState } from 'react';import { AuthErrorScreen } from './AuthErrorScreen';import { isLoggedOutSearch, parseAuthErrorReason } from './authStatusSearch';import { getCapabilities, listModels } from './composerLists';@@ -19,20 +12,6 @@ import { createModelProviderCatalog } from './modelProviderCatalog';import { createSandboxProviderCatalog } from './sandboxProviderCatalog';import { createSkillCatalog } from './skillCatalog';-/** Opens settings once when the empty welcome screen mounts (no models configured). */-function OpenSettingsWelcomeScreen(props: WelcomeScreenProps) {- const { setSettingsOpen } = useShellMode();- const openedRef = useRef(false);- useEffect(() => {- if (openedRef.current) {- return;- }- openedRef.current = true;- setSettingsOpen(true);- }, [setSettingsOpen]);- return <WelcomeScreen {...props} />;-}-const chatServer = createHarnessChatServer();const server = createTrueFoundryServer<HarnessAgentSpec>({@@ -108,13 +87,7 @@ export function App() {};}, [skipBoot]);- const overrides: SlotOverrides = useMemo(- () => ({- ShellActionsActionSlot: LogoutButton,- ...(boot.status === 'ready' && boot.openSettings ? { WelcomeScreen: OpenSettingsWelcomeScreen } : {}),- }),- [boot],- );+ const overrides: SlotOverrides = useMemo(() => ({ ShellActionsActionSlot: LogoutButton }), []);if (loggedOut) {return <LoggedOutScreen />;@@ -150,6 +123,7 @@ export function App() {mode: 'AgentLibraryWithComposer',defaultAgentSpec: boot.defaultAgentSpec,}}+ initialSettingsOpen={boot.openSettings}overrides={overrides}className="app-assistant"/>diff --git a/packages/frontend/src/harnessBuilderServer.ts b/packages/frontend/src/harnessBuilderServer.tsindex 1e4c76cfb..3a323d403 100644--- a/packages/frontend/src/harnessBuilderServer.ts+++ b/packages/frontend/src/harnessBuilderServer.ts@@ -46,6 +46,7 @@ export function createHarnessBuilderServer(return {getCapabilities: () => client.server.getCapabilities(),getModels: async () => (await listModels()).map(toModelSelection),+ // Skills require a configured sandbox provider; keep the picker empty when skill capability is off.getSkills: async () => {const skills = await listSkills();return skills.map(skill => ({ id: skill.name, name: skill.name, description: skill.description }));diff --git a/packages/frontend/src/index.css b/packages/frontend/src/index.cssindex 87b0dc5a1..67725dc09 100644--- a/packages/frontend/src/index.css+++ b/packages/frontend/src/index.css@@ -10,16 +10,6 @@ body,height: 100%;}-/* Tokens for chrome outside the SDK shell (boot screen). The SDK sets its own- on `.aui-theme-root`, which wins for everything inside. */-:root {- color-scheme: dark;- --background: #161618;- --foreground: #ececee;- --muted-foreground: #9b9ba3;- --destructive: #f87171;-}-body {color: var(--foreground);background: var(--background);diff --git a/packages/trueforge-ui-sdk/package.json b/packages/trueforge-ui-sdk/package.jsonindex bd68c72c9..ad5389b22 100644--- a/packages/trueforge-ui-sdk/package.json+++ b/packages/trueforge-ui-sdk/package.json@@ -50,7 +50,9 @@],"scripts": {"build": "tsup && tailwindcss --input src/build-styles.css --output dist/styles.css --minify",- "dev:watch": "tsup --watch",+ "dev:watch": "pnpm run \"/^(dev:watch:js|dev:watch:css)$/\"",+ "dev:watch:js": "tsup --watch",+ "dev:watch:css": "tailwindcss --input src/build-styles.css --output dist/styles.css --watch","pack:tgz": "pnpm build && pnpm pack","test": "vitest run && pnpm test:package","test:package": "pnpm build && node test/packageExports.smoke.mjs",diff --git a/packages/trueforge-ui-sdk/src/atoms/AgentHistoryFilterButton.tsx b/packages/trueforge-ui-sdk/src/atoms/AgentHistoryFilterButton.tsxindex 93a50c575..b8ee851e7 100644--- a/packages/trueforge-ui-sdk/src/atoms/AgentHistoryFilterButton.tsx+++ b/packages/trueforge-ui-sdk/src/atoms/AgentHistoryFilterButton.tsx@@ -6,14 +6,20 @@ import { createPortal } from 'react-dom';import { Icon } from '../icons/Icon.js';import { useOptionalServer } from '../server/ServerContext.js';import { useOptionalShellMode } from '../server/ShellModeContext.js';-import type { AgentLibraryEntry } from '../server/types.js';import { auiButtonClass } from './lib/buttonClasses.js';import { cn } from './lib/cn.js';import { useCompactLayout } from './lib/CompactLayoutContext.js';import { useIsMobile } from './lib/useIsMobile.js';+import { useSearchAgentsList } from './lib/useSearchAgentsList.js';import { BottomSheet } from './primitives/BottomSheet.js';+import { DropdownMenuItem } from './primitives/DropdownMenu.js';import SearchInput from './primitives/SearchInput.js';+/** Keep portaled chrome under ThemeProvider so preset/custom CSS vars still apply. */+function themePortalRoot(from: HTMLElement | null): HTMLElement {+ return from?.closest('.aui-theme-root') ?? document.body;+}+/*** Funnel popover for filtering chat history by agent id.* Desktop: fixed menu to the right of the funnel. Mobile/compact: bottom sheet.@@ -27,8 +33,6 @@ export function AgentHistoryFilterButton() {const [open, setOpen] = useState(false);const [query, setQuery] = useState('');- const [agents, setAgents] = useState<AgentLibraryEntry[]>([]);- const [loading, setLoading] = useState(false);const [menuPos, setMenuPos] = useState<{ top: number; left: number } | null>(null);const buttonRef = useRef<HTMLButtonElement>(null);const menuRef = useRef<HTMLDivElement>(null);@@ -38,28 +42,13 @@ export function AgentHistoryFilterButton() {const selected = shell?.historyAgentFilter ?? null;useEffect(() => {- if (!open) {- setQuery('');- return;- }- if (!server) return;- let cancelled = false;- setLoading(true);- void server- .searchAgents({ query: query.trim() || undefined, limit: 50 })- .then(rows => {- if (!cancelled) setAgents(rows);- })- .catch(() => {- if (!cancelled) setAgents([]);- })- .finally(() => {- if (!cancelled) setLoading(false);- });- return () => {- cancelled = true;- };- }, [open, query, server]);+ if (!open) setQuery('');+ }, [open]);++ const { agents, isInitialLoading, isSearching, loadingMore, hasMore, listRef, sentinelRef } = useSearchAgentsList({+ enabled: open && enabled,+ query,+ });// Desktop only: anchor to the right of the funnel; portal escapes sidebar overflow.useLayoutEffect(() => {@@ -103,43 +92,47 @@ export function AgentHistoryFilterButton() {<><div className="p-1" onMouseDown={e => e.stopPropagation()}><SearchInput query={query} setQuery={setQuery} placeholder="Search agents" />+ {isSearching ? (+ <p className="text-muted-foreground px-1 pt-1 text-[11px]" role="status">+ Searching…+ </p>+ ) : null}</div>- <div className={cn('mt-1 overflow-y-auto', useSheet ? 'min-h-0 flex-1 px-1 pb-2' : 'max-h-64')}>- <button- type="button"- role="menuitem"- className={cn(- 'flex w-full cursor-pointer items-center justify-between rounded-sm px-2 py-1.5 text-sm outline-none',- 'hover:bg-accent hover:text-accent-foreground',- selected == null && 'bg-accent',- )}+ <div ref={listRef} className={cn('mt-1 overflow-y-auto', useSheet ? 'min-h-0 flex-1 px-1 pb-2' : 'max-h-64')}>+ <DropdownMenuItem+ className={cn('justify-between', selected == null && 'bg-accent text-accent-foreground')}onClick={() => pick(null)}>All chats{selected == null ? <Icon name="check" className="size-3.5 shrink-0" /> : null}- </button>- {loading ? (+ </DropdownMenuItem>+ {isInitialLoading ? (<p className="px-2 py-3 text-center text-xs text-muted-foreground">Loading…</p>) : (- agents.map(agent => {- const active = selected === agent.agentId;- return (- <button- key={agent.agentId}- type="button"- role="menuitem"- className={cn(- 'flex w-full cursor-pointer items-center justify-between gap-2 rounded-sm px-2 py-1.5 text-left text-sm outline-none',- 'hover:bg-accent hover:text-accent-foreground',- active && 'bg-accent',- )}- onClick={() => pick(agent.agentId)}- >- <span className="min-w-0 truncate">{agent.name}</span>- {active ? <Icon name="check" className="size-3.5 shrink-0" /> : null}- </button>- );- })+ <>+ {agents.map(agent => {+ const active = selected === agent.agentId;+ return (+ <DropdownMenuItem+ key={agent.agentId}+ className={cn('justify-between gap-2 text-left', active && 'bg-accent text-accent-foreground')}+ onClick={() => pick(agent.agentId)}+ >+ <span className="min-w-0 truncate">{agent.name}</span>+ {active ? <Icon name="check" className="size-3.5 shrink-0" /> : null}+ </DropdownMenuItem>+ );+ })}+ {hasMore ? (+ <div ref={sentinelRef} className="flex h-6 shrink-0 items-center justify-center" aria-hidden>+ {loadingMore ? (+ <span className="text-muted-foreground text-[11px]" role="status">+ Loading more…+ </span>+ ) : null}+ </div>+ ) : null}+ </>)}</div></>@@ -150,7 +143,7 @@ export function AgentHistoryFilterButton() {<buttonref={buttonRef}type="button"- aria-label="Filter chat history by agent"+ aria-label={selected != null ? `Filter chat history by agent (${selected})` : 'Filter chat history by agent'}aria-haspopup={useSheet ? 'dialog' : 'menu'}aria-expanded={open}aria-controls={open ? menuId : undefined}@@ -159,13 +152,20 @@ export function AgentHistoryFilterButton() {variant: 'ghost',size: 'icon',className: cn(- 'size-7 text-muted-foreground hover:bg-accent hover:text-foreground',+ 'relative size-7 shrink-0 text-muted-foreground hover:bg-accent hover:text-accent-foreground',selected != null && 'text-foreground',),})}onClick={() => setOpen(v => !v)}><Icon name="funnel" className="size-3.5" />+ {selected != null ? (+ <span+ className="bg-primary absolute top-1 right-1 size-1.5 rounded-full"+ aria-hidden+ data-testid="history-filter-active-dot"+ />+ ) : null}</button>{useSheet && open ? (<BottomSheet open onOpenChange={setOpen} id={menuId} aria-label="Filter agents">@@ -186,7 +186,7 @@ export function AgentHistoryFilterButton() {>{filterBody}</div>,- buttonRef.current?.closest('.aui-theme-root') ?? document.body,+ themePortalRoot(buttonRef.current),): null}</div>diff --git a/packages/trueforge-ui-sdk/src/atoms/AgentsLibrary.tsx b/packages/trueforge-ui-sdk/src/atoms/AgentsLibrary.tsxindex dbbdf55e7..817d5fcf5 100644--- a/packages/trueforge-ui-sdk/src/atoms/AgentsLibrary.tsx+++ b/packages/trueforge-ui-sdk/src/atoms/AgentsLibrary.tsx@@ -3,13 +3,14 @@import { useEffect, useState } from 'react';import { Icon } from '../icons/Icon.js';-import { useOptionalServer } from '../server/ServerContext.js';-import { useOptionalShellMode } from '../server/ShellModeContext.js';+import { libraryAgentId, useOptionalShellMode } from '../server/ShellModeContext.js';import type { AgentLibraryEntry, AgentSpec } from '../server/types.js';import { auiButtonClass } from './lib/buttonClasses.js';import { cn } from './lib/cn.js';import { useCompactLayout } from './lib/CompactLayoutContext.js';+import { useSearchAgentsList } from './lib/useSearchAgentsList.js';import { CenteredModal } from './primitives/CenteredModal.js';+import SearchInput from './primitives/SearchInput.js';import { Skeleton } from './primitives/Skeleton.js';export type AgentsLibraryProps = {@@ -63,6 +64,7 @@ function AgentLibraryRow({ agent, showEdit, onTry, onEdit }: AgentLibraryRowProp})}onClick={onEdit}>+ <Icon name="pencil" className="size-3.5" />Edit</button>) : null}@@ -76,7 +78,8 @@ function AgentLibraryRow({ agent, showEdit, onTry, onEdit }: AgentLibraryRowProp})}onClick={onTry}>- Try Agent+ <Icon name="play" className="size-3.5" />+ Try</button></span></div>@@ -84,43 +87,22 @@ function AgentLibraryRow({ agent, showEdit, onTry, onEdit }: AgentLibraryRowProp}export function AgentsLibrary({ open, onOpenChange, onSelectAgent }: AgentsLibraryProps) {- const server = useOptionalServer();const shell = useOptionalShellMode();const [query, setQuery] = useState('');- const [agents, setAgents] = useState<AgentLibraryEntry[]>([]);- const [loading, setLoading] = useState(false);- const [error, setError] = useState<string | null>(null);const canEdit = shell?.isComposerEnabled === true;const agentsListEpoch = shell?.agentsListEpoch ?? 0;useEffect(() => {- if (!open) {- setQuery('');- return;- }- if (!server) return;- let cancelled = false;- setLoading(true);- setError(null);- void server- .searchAgents({ query: query.trim() || undefined, limit: 50 })- .then(rows => {- if (!cancelled) setAgents(rows);- })- .catch((err: unknown) => {- if (!cancelled) {- setError(err instanceof Error ? err.message : 'Failed to load agents.');- setAgents([]);- }- })- .finally(() => {- if (!cancelled) setLoading(false);- });- return () => {- cancelled = true;- };- }, [open, query, server, agentsListEpoch]);+ if (!open) setQuery('');+ }, [open]);++ const { agents, isInitialLoading, isSearching, loadingMore, error, hasMore, listRef, sentinelRef } =+ useSearchAgentsList({+ enabled: open,+ query,+ refreshKey: agentsListEpoch,+ });const closeLibrary = () => {onOpenChange(false);@@ -152,23 +134,20 @@ export function AgentsLibrary({ open, onOpenChange, onSelectAgent }: AgentsLibra<CenteredModal open={open} onOpenChange={onOpenChange} title="Agents Library"><div className="bg-muted/40 flex min-h-0 flex-1 flex-col"><div className="shrink-0 border-b border-border px-4 py-3">- <label className="relative block">- <Icon- name="search"- className="text-muted-foreground pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2"- />- <input- type="search"- value={query}- onChange={e => setQuery(e.target.value)}- placeholder="Search agents"- className="border-input bg-background placeholder:text-muted-foreground h-9 w-full rounded-md border py-1 pr-3 pl-8 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring/40"- autoFocus- />- </label>+ <SearchInput query={query} setQuery={setQuery} placeholder="Search agents" />+ {isSearching ? (+ <p className="text-muted-foreground mt-1.5 text-xs" role="status">+ Searching…+ </p>+ ) : null}</div>- <div className="flex min-h-0 flex-1 flex-col gap-0.5 overflow-y-auto p-2" role="menu" aria-label="Agents">- {loading ? (+ <div+ ref={listRef}+ className="flex min-h-0 flex-1 flex-col gap-0.5 overflow-y-auto p-2"+ role="menu"+ aria-label="Agents"+ >+ {isInitialLoading ? (<div className="flex flex-col gap-2 p-1" role="status" aria-label="Loading agents">{Array.from({ length: 6 }, (_, i) => (<Skeleton key={i} className="h-11 w-full rounded-md" />@@ -183,21 +162,32 @@ export function AgentsLibrary({ open, onOpenChange, onSelectAgent }: AgentsLibra: 'No agents yet. Build one in a chat, then save it as an agent.'}</p>) : (- agents.map(agent => {- const agentSpec = agent.agentSpec;- const showEdit = canEdit && agentSpec != null;- return (- <AgentLibraryRow- key={agent.agentId}- agent={agent}- showEdit={showEdit}- onTry={() => handleTry(agent)}- onEdit={() => {- if (agentSpec != null) handleEdit(agent, agentSpec);- }}- />- );- })+ <>+ {agents.map(agent => {+ const agentSpec = agent.agentSpec;+ const showEdit = canEdit && agentSpec != null;+ return (+ <AgentLibraryRow+ key={libraryAgentId(agent)}+ agent={agent}+ showEdit={showEdit}+ onTry={() => handleTry(agent)}+ onEdit={() => {+ if (agentSpec != null) handleEdit(agent, agentSpec);+ }}+ />+ );+ })}+ {hasMore ? (+ <div ref={sentinelRef} className="flex h-8 shrink-0 items-center justify-center" aria-hidden>+ {loadingMore ? (+ <span className="text-muted-foreground text-xs" role="status">+ Loading more…+ </span>+ ) : null}+ </div>+ ) : null}+ </>)}</div></div>diff --git a/packages/trueforge-ui-sdk/src/atoms/AgentsLibraryButton.tsx b/packages/trueforge-ui-sdk/src/atoms/AgentsLibraryButton.tsxindex 29d73ba13..82992a353 100644--- a/packages/trueforge-ui-sdk/src/atoms/AgentsLibraryButton.tsx+++ b/packages/trueforge-ui-sdk/src/atoms/AgentsLibraryButton.tsx@@ -8,6 +8,7 @@ import { useOptionalShellMode } from '../server/ShellModeContext.js';import { useSlot } from '../theme/SlotsProvider.js';import { auiButtonClass } from './lib/buttonClasses.js';import { cn } from './lib/cn.js';+import { SEARCH_AGENTS_PAGE_SIZE } from './lib/useSearchAgentsList.js';export type AgentsLibraryButtonProps = {className?: string;@@ -20,7 +21,7 @@ export function AgentsLibraryButton({ className, compact = false, onSelectAgentconst server = useOptionalServer();const shell = useOptionalShellMode();const [open, setOpen] = useState(false);- const [count, setCount] = useState<number | null>(null);+ const [countLabel, setCountLabel] = useState<string | null>(null);const enabled = shell?.isLibraryEnabled === true && server != null;const agentsListEpoch = shell?.agentsListEpoch ?? 0;@@ -29,9 +30,11 @@ export function AgentsLibraryButton({ className, compact = false, onSelectAgentif (!enabled || !server) return;let cancelled = false;void server- .searchAgents({ limit: 50 })+ .searchAgents({ limit: SEARCH_AGENTS_PAGE_SIZE }).then(rows => {- if (!cancelled) setCount(rows.length);+ if (cancelled) return;+ // API has no total; a full page means there may be more.+ setCountLabel(rows.length >= SEARCH_AGENTS_PAGE_SIZE ? `${SEARCH_AGENTS_PAGE_SIZE}+` : String(rows.length));}).catch(() => undefined);return () => {@@ -65,7 +68,7 @@ export function AgentsLibraryButton({ className, compact = false, onSelectAgent<><span className="truncate">Agents Library- {count != null ? <span className="text-muted-foreground"> ({count})</span> : null}+ {countLabel != null ? <span className="text-muted-foreground"> ({countLabel})</span> : null}</span><Icon name="chevron-right" className="ml-auto size-3.5 shrink-0 opacity-60" /></>diff --git a/packages/trueforge-ui-sdk/src/atoms/ClearChatButton.tsx b/packages/trueforge-ui-sdk/src/atoms/ClearChatButton.tsxindex 373f99fe1..aa1c646f9 100644--- a/packages/trueforge-ui-sdk/src/atoms/ClearChatButton.tsx+++ b/packages/trueforge-ui-sdk/src/atoms/ClearChatButton.tsx@@ -17,7 +17,7 @@ export function ClearChatButton() {className={auiButtonClass({ variant: 'ghost', size: 'sm' })}onClick={() => shell.clearChat()}>- <Icon name="broom" size="0.875em" />+ <Icon name="broom" size="0.875rem" />Clear chat</button>);diff --git a/packages/trueforge-ui-sdk/src/atoms/NamedAgentHeaderLabel.tsx b/packages/trueforge-ui-sdk/src/atoms/NamedAgentHeaderLabel.tsxindex 02fffb309..0f52fa300 100644--- a/packages/trueforge-ui-sdk/src/atoms/NamedAgentHeaderLabel.tsx+++ b/packages/trueforge-ui-sdk/src/atoms/NamedAgentHeaderLabel.tsx@@ -1,5 +1,6 @@'use client';+import { Icon } from '../icons/Icon.js';import { useOptionalShellMode } from '../server/ShellModeContext.js';import { cn } from './lib/cn.js';@@ -12,8 +13,12 @@ export function NamedAgentHeaderLabel({ className }: { className?: string }) {if (name == null || name.length === 0) return null;return (- <h1 className={cn('min-w-0 truncate px-1 text-sm font-medium text-foreground', className)} title={name}>- {name}+ <h1+ className={cn('flex min-w-0 items-center gap-1.5 px-1 text-sm font-medium text-foreground', className)}+ title={name}+ >+ <Icon name="robot" className="size-3.5 shrink-0" />+ <span className="truncate">{name}</span></h1>);}diff --git a/packages/trueforge-ui-sdk/src/atoms/SyntaxHighlighter.tsx b/packages/trueforge-ui-sdk/src/atoms/SyntaxHighlighter.tsxindex 12e31112c..e0d7986f1 100644--- a/packages/trueforge-ui-sdk/src/atoms/SyntaxHighlighter.tsx+++ b/packages/trueforge-ui-sdk/src/atoms/SyntaxHighlighter.tsx@@ -1,9 +1,10 @@'use client';-import { Children, cloneElement, isValidElement, type ReactNode } from 'react';+import { Children, cloneElement, isValidElement, useCallback, useState, type ReactNode } from 'react';import { Prism as PrismHighlighter } from 'react-syntax-highlighter';import { oneDark, oneLight } from 'react-syntax-highlighter/dist/esm/styles/prism';+import { Icon } from '../icons/Icon.js';import { useOptionalContentClassNames } from '../theme/ThemeProvider.js';import { cn } from './lib/cn.js';@@ -33,27 +34,58 @@ function applyLineNumberClassName(children: ReactNode, className: string | undefexport function SyntaxHighlighter({ code, language, darkTheme, className, showLineNumbers }: SyntaxHighlighterProps) {const classNames = useOptionalContentClassNames();const style = darkTheme ? oneDark : oneLight;+ const [copied, setCopied] = useState(false);++ const handleCopy = useCallback(() => {+ void navigator.clipboard.writeText(code).then(() => {+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ });+ }, [code]);return (<divclassName={cn(- 'aui-syntax-highlighter my-2 max-w-full min-w-0 overflow-x-auto rounded-md',+ 'aui-syntax-highlighter relative my-2 max-w-full min-w-0 overflow-x-auto rounded-md',classNames.syntaxHighlighter?.root,className,)}>+ <button+ type="button"+ onClick={handleCopy}+ title={copied ? 'Copied!' : 'Copy'}+ aria-label={copied ? 'Copied!' : 'Copy'}+ className={cn(+ 'absolute top-2 right-2 z-10 flex cursor-pointer items-center justify-center rounded p-1.5 text-xs transition-colors',+ 'bg-background/80 text-muted-foreground hover:bg-muted hover:text-foreground',+ )}+ >+ <Icon name={copied ? 'check' : 'copy'} size="0.875em" />+ </button><PrismHighlighterlanguage={language}style={style}- customStyle={{ margin: 0, maxWidth: '100%' }}+ customStyle={{ margin: 0, maxWidth: '100%', whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}+ wrapLongLinesshowLineNumbers={showLineNumbers}PreTag={({ children, className: preClass, ...rest }) => (- <pre {...rest} className={cn('max-w-full overflow-x-auto', classNames.syntaxHighlighter?.pre, preClass)}>+ <pre+ {...rest}+ className={cn(+ 'max-w-full overflow-x-auto whitespace-pre-wrap break-words',+ classNames.syntaxHighlighter?.pre,+ preClass,+ )}+ >{children}</pre>)}CodeTag={({ children, className: codeClass, ...rest }) => (- <code {...rest} className={cn(classNames.syntaxHighlighter?.code, codeClass)}>+ <code+ {...rest}+ className={cn('whitespace-pre-wrap break-words', classNames.syntaxHighlighter?.code, codeClass)}+ >{applyLineNumberClassName(children, classNames.syntaxHighlighter?.lineNumber)}</code>)}diff --git a/packages/trueforge-ui-sdk/src/atoms/ThreadListMisc.tsx b/packages/trueforge-ui-sdk/src/atoms/ThreadListMisc.tsxindex 069e400ab..e8f10ec07 100644--- a/packages/trueforge-ui-sdk/src/atoms/ThreadListMisc.tsx+++ b/packages/trueforge-ui-sdk/src/atoms/ThreadListMisc.tsx@@ -24,7 +24,7 @@ export function ThreadListNewButton({ className, children, style, ...rest }: Thr>{children ?? (<>- <Icon name="pencil" />+ <Icon name="square-pen" />New Chat</>)}diff --git a/packages/trueforge-ui-sdk/src/atoms/draft/DraftCatalogProvider.tsx b/packages/trueforge-ui-sdk/src/atoms/draft/DraftCatalogProvider.tsxindex 00618fec6..a7dac302f 100644--- a/packages/trueforge-ui-sdk/src/atoms/draft/DraftCatalogProvider.tsx+++ b/packages/trueforge-ui-sdk/src/atoms/draft/DraftCatalogProvider.tsx@@ -1,6 +1,6 @@'use client';-import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';+import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';import { useOptionalServer } from '../../server/ServerContext.js';import type { AgentSkill, ConnectorState, ModelSelection } from '../../server/types.js';@@ -11,20 +11,29 @@ type DraftCatalogValue = {connectors: ConnectorState[];loading: boolean;error: string | null;+ /** Kick off catalog fetch (idempotent). Call when a picker opens. */+ ensureLoaded: () => void;};const DraftCatalogContext = createContext<DraftCatalogValue | null>(null);+const IDLE_ENSURE = () => undefined;+export function DraftCatalogProvider({ children }: { children: ReactNode }) {const server = useOptionalServer();+ const [requested, setRequested] = useState(false);const [models, setModels] = useState<ModelSelection[]>([]);const [skills, setSkills] = useState<AgentSkill[]>([]);const [connectors, setConnectors] = useState<ConnectorState[]>([]);const [loading, setLoading] = useState(false);const [error, setError] = useState<string | null>(null);+ const ensureLoaded = useCallback(() => {+ setRequested(true);+ }, []);+useEffect(() => {- if (!server) return;+ if (!requested || !server) return;let cancelled = false;setLoading(true);setError(null);@@ -46,11 +55,11 @@ export function DraftCatalogProvider({ children }: { children: ReactNode }) {return () => {cancelled = true;};- }, [server]);+ }, [requested, server]);const value = useMemo(- () => ({ models, skills, connectors, loading, error }),- [models, skills, connectors, loading, error],+ () => ({ models, skills, connectors, loading, error, ensureLoaded }),+ [models, skills, connectors, loading, error, ensureLoaded],);return <DraftCatalogContext.Provider value={value}>{children}</DraftCatalogContext.Provider>;@@ -59,7 +68,14 @@ export function DraftCatalogProvider({ children }: { children: ReactNode }) {export function useDraftCatalog(): DraftCatalogValue {const ctx = useContext(DraftCatalogContext);if (ctx == null) {- return { models: [], skills: [], connectors: [], loading: false, error: null };+ return {+ models: [],+ skills: [],+ connectors: [],+ loading: false,+ error: null,+ ensureLoaded: IDLE_ENSURE,+ };}return ctx;}diff --git a/packages/trueforge-ui-sdk/src/atoms/draft/DraftCompositeSelector.tsx b/packages/trueforge-ui-sdk/src/atoms/draft/DraftCompositeSelector.tsxindex 0f0f76901..487aa0609 100644--- a/packages/trueforge-ui-sdk/src/atoms/draft/DraftCompositeSelector.tsx+++ b/packages/trueforge-ui-sdk/src/atoms/draft/DraftCompositeSelector.tsx@@ -1,7 +1,7 @@'use client';import { useTrueFoundryAgentSpec, useTrueFoundryUpdateAgentSpec } from '@truefoundry/assistant-ui-runtime';-import { useEffect, useId, useMemo, useRef, useState } from 'react';+import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';import { Icon } from '../../icons/Icon.js';import { useServerCapabilities } from '../../server/ServerContext.js';@@ -21,6 +21,8 @@ const TABS: { id: AttachTab; label: string; icon: string }[] = [{ id: 'files', label: 'Attachment', icon: 'paperclip' },];+const SPEC_FLUSH_MS = 300;+function Checkbox({ checked }: { checked: boolean }) {return (<span@@ -110,7 +112,7 @@ function SectionHeading({ label, count }: { label: string; count: number }) {}export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftCompositeSelectorProps) {- const { skills, connectors } = useDraftCatalog();+ const { skills, connectors, ensureLoaded } = useDraftCatalog();const capabilities = useServerCapabilities();const { agentSpec } = useTrueFoundryAgentSpec();const updateAgentSpec = useTrueFoundryUpdateAgentSpec();@@ -120,6 +122,16 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftC// Section membership is snapped when the picker opens, so toggles don't jump rows mid-session.const [pinnedMcpIds, setPinnedMcpIds] = useState<Set<string>>(() => new Set());const [pinnedSkillIds, setPinnedSkillIds] = useState<Set<string>>(() => new Set());+ // Local working copy while open — flush to AgentSpec on debounce / close.+ const [localMcp, setLocalMcp] = useState<McpServerMount[]>([]);+ const [localSkills, setLocalSkills] = useState<SkillMount[]>([]);+ const dirtyRef = useRef(false);+ const flushTimerRef = useRef<number | null>(null);+ const localMcpRef = useRef(localMcp);+ const localSkillsRef = useRef(localSkills);+ localMcpRef.current = localMcp;+ localSkillsRef.current = localSkills;+const containerRef = useRef<HTMLDivElement>(null);const menuId = useId();const isMobile = useIsMobile();@@ -127,25 +139,63 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftCconst skillsDisabled = capabilities?.skill.enabled !== true;const skillsDisabledReason = capabilities?.skill.reason;- const selectedMcp = useMemo(- () => (agentSpec?.mcpServers as McpServerMount[] | undefined) ?? [],- [agentSpec?.mcpServers],- );- const selectedSkills = useMemo(() => (agentSpec?.skills as SkillMount[] | undefined) ?? [], [agentSpec?.skills]);+ const specMcp = useMemo(() => (agentSpec?.mcpServers as McpServerMount[] | undefined) ?? [], [agentSpec?.mcpServers]);+ const specSkills = useMemo(() => (agentSpec?.skills as SkillMount[] | undefined) ?? [], [agentSpec?.skills]);+ const selectedMcp = open ? localMcp : specMcp;+ const selectedSkills = open ? localSkills : specSkills;const selectedMcpIds = useMemo(() => new Set(selectedMcp.map(m => m.id)), [selectedMcp]);const selectedSkillIds = useMemo(() => new Set(selectedSkills.map(s => s.id)), [selectedSkills]);+ const clearFlushTimer = useCallback(() => {+ if (flushTimerRef.current != null) {+ window.clearTimeout(flushTimerRef.current);+ flushTimerRef.current = null;+ }+ }, []);++ const flushSpec = useCallback(() => {+ clearFlushTimer();+ if (!dirtyRef.current) return;+ dirtyRef.current = false;+ updateAgentSpec?.({+ mcpServers: localMcpRef.current,+ skills: localSkillsRef.current,+ });+ }, [clearFlushTimer, updateAgentSpec]);++ const scheduleFlush = useCallback(() => {+ clearFlushTimer();+ flushTimerRef.current = window.setTimeout(() => {+ flushTimerRef.current = null;+ flushSpec();+ }, SPEC_FLUSH_MS);+ }, [clearFlushTimer, flushSpec]);++ const setOpenAndFlush = useCallback(+ (next: boolean) => {+ if (!next) flushSpec();+ setOpen(next);+ },+ [flushSpec],+ );++ useEffect(() => {+ if (open) ensureLoaded();+ }, [open, ensureLoaded]);+useEffect(() => {if (!open) return;const handler = (e: MouseEvent) => {if (containerRef.current && !containerRef.current.contains(e.target as Node)) {- setOpen(false);+ setOpenAndFlush(false);}};document.addEventListener('mousedown', handler);return () => document.removeEventListener('mousedown', handler);- }, [open]);+ }, [open, setOpenAndFlush]);++ useEffect(() => () => clearFlushTimer(), [clearFlushTimer]);// Keep unavailable selections visible so users can remove them.// Hosts that omit auth info keep their connectors selectable.@@ -188,22 +238,32 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftC);const toggleConnector = (connector: ConnectorState) => {- const next = selectedMcpIds.has(connector.id)- ? selectedMcp.filter(m => m.id !== connector.id)- : [...selectedMcp, { id: connector.id, name: connector.name }];- updateAgentSpec?.({ mcpServers: next });+ setLocalMcp(prev =>+ prev.some(m => m.id === connector.id)+ ? prev.filter(m => m.id !== connector.id)+ : [...prev, { id: connector.id, name: connector.name }],+ );+ dirtyRef.current = true;+ scheduleFlush();};const toggleSkill = (skill: AgentSkill) => {- const next = selectedSkillIds.has(skill.id)- ? selectedSkills.filter(s => s.id !== skill.id)- : [...selectedSkills, { id: skill.id, name: skill.name }];- updateAgentSpec?.({ skills: next });+ setLocalSkills(prev =>+ prev.some(s => s.id === skill.id)+ ? prev.filter(s => s.id !== skill.id)+ : [...prev, { id: skill.id, name: skill.name }],+ );+ dirtyRef.current = true;+ scheduleFlush();};const openPicker = () => {- setPinnedMcpIds(new Set(selectedMcp.map(m => m.id)));- setPinnedSkillIds(new Set(selectedSkills.map(s => s.id)));+ setLocalMcp(specMcp);+ setLocalSkills(specSkills);+ dirtyRef.current = false;+ clearFlushTimer();+ setPinnedMcpIds(new Set(specMcp.map(m => m.id)));+ setPinnedSkillIds(new Set(specSkills.map(s => s.id)));setOpen(true);};@@ -240,7 +300,7 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftCdisabled={disabled}onClick={() => {onAttach?.();- setOpen(false);+ setOpenAndFlush(false);}}className={cn('m-3 flex min-h-48 flex-1 flex-col items-center justify-center gap-2 rounded-lg border border-dashed border-border px-4 py-8',@@ -352,7 +412,7 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftCclassName={auiButtonClass({ variant: 'ghost', size: 'icon' })}onClick={() => {if (open) {- setOpen(false);+ setOpenAndFlush(false);return;}openPicker();@@ -363,7 +423,7 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftC{open ? (isMobile || compactLayout ? (- <BottomSheet id={menuId} open onOpenChange={setOpen} aria-label="Add to composer">+ <BottomSheet id={menuId} open onOpenChange={setOpenAndFlush} aria-label="Add to composer">{content}</BottomSheet>) : (diff --git a/packages/trueforge-ui-sdk/src/atoms/draft/DraftModelSelector.tsx b/packages/trueforge-ui-sdk/src/atoms/draft/DraftModelSelector.tsxindex 8e303c47b..7b55376ae 100644--- a/packages/trueforge-ui-sdk/src/atoms/draft/DraftModelSelector.tsx+++ b/packages/trueforge-ui-sdk/src/atoms/draft/DraftModelSelector.tsx@@ -4,6 +4,8 @@ import { useTrueFoundryAgentSpec, useTrueFoundryUpdateAgentSpec } from '@truefouimport { useEffect, useId, useMemo, useRef, useState } from 'react';import { Icon } from '../../icons/Icon.js';+import { useOptionalCatalogServer } from '../../server/ServerContext.js';+import { useOptionalShellMode } from '../../server/ShellModeContext.js';import type { ModelSelection } from '../../server/types.js';import { auiButtonClass } from '../lib/buttonClasses.js';import { cn } from '../lib/cn.js';@@ -15,17 +17,26 @@ import { modelPatchWithReasoningEffort } from './reasoningEffort.js';type RichModel = ModelSelection & { apiModel?: string; modelId?: string };-const PROVIDER_COLORS = ['#ec4899', '#0ea5e9', '#f59e0b', '#10b981', '#6366f1', '#8b5cf6'] as const;-function monogram(value: string): string {const trimmed = value.trim();return trimmed ? trimmed.charAt(0).toUpperCase() : '?';}-function colorFor(value: string): string {- let hash = 0;- for (const ch of value) hash = (hash + ch.charCodeAt(0)) % PROVIDER_COLORS.length;- return PROVIDER_COLORS[hash] ?? PROVIDER_COLORS[0];+function ProviderMark({ logo, label, className }: { logo?: string; label: string; className?: string }) {+ if (logo) {+ return <img src={logo} alt="" className={cn('shrink-0 rounded object-contain', className)} aria-hidden />;+ }+ return (+ <span+ className={cn(+ 'bg-muted text-muted-foreground flex shrink-0 items-center justify-center rounded font-semibold',+ className,+ )}+ aria-hidden+ >+ {monogram(label)}+ </span>+ );}function displayModelLabel(modelName: string): string {@@ -43,16 +54,23 @@ export type DraftModelSelectorProps = {};export function DraftModelSelector({ disabled, isRunning }: DraftModelSelectorProps) {- const { models: rawModels, loading } = useDraftCatalog();+ const { models: rawModels, loading, ensureLoaded } = useDraftCatalog();const models = rawModels as RichModel[];const { agentSpec } = useTrueFoundryAgentSpec();const updateAgentSpec = useTrueFoundryUpdateAgentSpec();+ const catalog = useOptionalCatalogServer();+ const shell = useOptionalShellMode();const [open, setOpen] = useState(false);const [query, setQuery] = useState('');const containerRef = useRef<HTMLDivElement>(null);const menuId = useId();const isMobile = useIsMobile();const compactLayout = useCompactLayout();+ const showConfigureSettingsCta = !loading && models.length === 0 && catalog != null;++ useEffect(() => {+ ensureLoaded();+ }, [ensureLoaded]);const selectedName = agentSpec?.model?.name ?? (models[0] ? modelValue(models[0]) : '');const selected = models.find(m => modelValue(m) === selectedName || m.name === selectedName);@@ -88,7 +106,6 @@ export function DraftModelSelector({ disabled, isRunning }: DraftModelSelectorPr}, [open]);const account = selected?.provider ?? selectedName;- const iconBg = colorFor(account);const content = (<>@@ -116,7 +133,24 @@ export function DraftModelSelector({ disabled, isRunning }: DraftModelSelectorPrclassName="flex min-h-0 flex-1 flex-col overflow-y-auto p-1">{filtered.length === 0 ? (- <p className="text-muted-foreground px-2 py-4 text-center text-sm">No models</p>+ showConfigureSettingsCta ? (+ <button+ type="button"+ className="text-muted-foreground hover:text-foreground flex w-full items-center justify-center gap-1 px-2 py-4 text-center text-sm"+ onClick={() => {+ setOpen(false);+ setQuery('');+ shell?.setSettingsOpen(true);+ }}+ >+ <span>+ Please configure Models in the <span className="underline">settings</span>+ </span>+ <Icon name="chevron-right" className="size-3.5 shrink-0" />+ </button>+ ) : (+ <p className="text-muted-foreground px-2 py-4 text-center text-sm">No models</p>+ )) : (filtered.map(model => {const value = modelValue(model);@@ -139,13 +173,11 @@ export function DraftModelSelector({ disabled, isRunning }: DraftModelSelectorPrsetQuery('');}}>- <span- className="flex size-6 shrink-0 items-center justify-center rounded text-[11px] font-bold text-white"- style={{ backgroundColor: colorFor(model.provider || model.name) }}- aria-hidden- >- {monogram(model.provider || model.name)}- </span>+ <ProviderMark+ logo={model.providerLogo}+ label={model.provider || model.name}+ className="size-5 text-xs"+ /><span className="truncate font-medium">{displayModelLabel(value)}</span></button>);@@ -171,13 +203,7 @@ export function DraftModelSelector({ disabled, isRunning }: DraftModelSelectorPr})}onClick={() => setOpen(v => !v)}>- <span- className="flex size-5 shrink-0 items-center justify-center rounded text-[10px] font-bold text-white"- style={{ backgroundColor: iconBg }}- aria-hidden- >- {monogram(account)}- </span>+ <ProviderMark logo={selected?.providerLogo} label={account} className="size-5 text-[10px]" /><span className="truncate">{label}</span><Icon name="chevron-down" className="size-3.5 shrink-0 opacity-60" /></button>diff --git a/packages/trueforge-ui-sdk/src/atoms/draft/DraftReasoningEffortSelector.tsx b/packages/trueforge-ui-sdk/src/atoms/draft/DraftReasoningEffortSelector.tsxindex fce4aea3d..a1cff23e3 100644--- a/packages/trueforge-ui-sdk/src/atoms/draft/DraftReasoningEffortSelector.tsx+++ b/packages/trueforge-ui-sdk/src/atoms/draft/DraftReasoningEffortSelector.tsx@@ -25,7 +25,7 @@ export type DraftReasoningEffortSelectorProps = {};export function DraftReasoningEffortSelector({ disabled, isRunning }: DraftReasoningEffortSelectorProps) {- const { models: rawModels } = useDraftCatalog();+ const { models: rawModels, ensureLoaded } = useDraftCatalog();const models = rawModels as RichModel[];const { agentSpec } = useTrueFoundryAgentSpec();const updateAgentSpec = useTrueFoundryUpdateAgentSpec();@@ -42,6 +42,11 @@ export function DraftReasoningEffortSelector({ disabled, isRunning }: DraftReaso// Display fallback only — coerce into the spec on model change / explicit pick.const resolved = resolveReasoningEffort(efforts, currentEffort);+ useEffect(() => {+ // Need catalog to know whether this model exposes reasoning efforts.+ ensureLoaded();+ }, [ensureLoaded]);+useEffect(() => {if (!open) return;const handler = (e: MouseEvent) => {diff --git a/packages/trueforge-ui-sdk/src/atoms/lib/threadListMeta.ts b/packages/trueforge-ui-sdk/src/atoms/lib/threadListMeta.tsindex 67c7edfbe..50d8329ef 100644--- a/packages/trueforge-ui-sdk/src/atoms/lib/threadListMeta.ts+++ b/packages/trueforge-ui-sdk/src/atoms/lib/threadListMeta.ts@@ -14,6 +14,31 @@ export function formatRelativeShort(date: Date, now: Date = new Date()): stringreturn `${Math.floor(days / 365)}y`;}+/**+ * Indices into `threadIds` ordered newest-first by `lastMessageAt`.+ * Stabilizes UI when assistant-ui appends a switched-to thread at the end.+ * Missing `lastMessageAt` (empty local "New Chat") sorts as newest so it stays on top.+ */+export function threadListIndicesByRecency({+ threadIds,+ threadItems,+}: {+ threadIds: readonly string[];+ threadItems: readonly { id: string; remoteId?: string | null; lastMessageAt?: Date | null }[];+}): number[] {+ const timeByKey = new Map<string, number>();+ for (const item of threadItems) {+ // Empty / not-yet-messaged threads have no timestamp; treat as newest.+ const t = item.lastMessageAt?.getTime() ?? Number.POSITIVE_INFINITY;+ timeByKey.set(item.id, t);+ if (item.remoteId != null) timeByKey.set(item.remoteId, t);+ }+ return threadIds+ .map((id, index) => ({ index, t: timeByKey.get(id) ?? 0 }))+ .sort((a, b) => b.t - a.t || a.index - b.index)+ .map(row => row.index);+}+export function readThreadAgentName(custom: unknown): string | undefined {if (custom == null || typeof custom !== 'object') return undefined;if (!('agentName' in custom)) return undefined;diff --git a/packages/trueforge-ui-sdk/src/atoms/lib/useDebouncedValue.ts b/packages/trueforge-ui-sdk/src/atoms/lib/useDebouncedValue.tsnew file mode 100644index 000000000..5efc4df48--- /dev/null+++ b/packages/trueforge-ui-sdk/src/atoms/lib/useDebouncedValue.ts@@ -0,0 +1,15 @@+'use client';++import { useEffect, useState } from 'react';++/** Returns `value` immediately on first render; subsequent changes apply after `delayMs`. */+export function useDebouncedValue<T>(value: T, delayMs: number): T {+ const [debounced, setDebounced] = useState(value);++ useEffect(() => {+ const id = window.setTimeout(() => setDebounced(value), delayMs);+ return () => window.clearTimeout(id);+ }, [value, delayMs]);++ return debounced;+}diff --git a/packages/trueforge-ui-sdk/src/atoms/lib/useSearchAgentsList.ts b/packages/trueforge-ui-sdk/src/atoms/lib/useSearchAgentsList.tsnew file mode 100644index 000000000..ec91b9cf8--- /dev/null+++ b/packages/trueforge-ui-sdk/src/atoms/lib/useSearchAgentsList.ts@@ -0,0 +1,163 @@+'use client';++import { useCallback, useEffect, useRef, useState } from 'react';++import { useOptionalServer } from '../../server/ServerContext.js';+import type { AgentLibraryEntry } from '../../server/types.js';+import { useDebouncedValue } from './useDebouncedValue.js';++export const SEARCH_AGENTS_PAGE_SIZE = 50;+const DEFAULT_DEBOUNCE_MS = 300;+const LOAD_MORE_ROOT_MARGIN = '48px';++export type UseSearchAgentsListOptions = {+ /** When false, no fetches run. */+ enabled: boolean;+ query: string;+ /** Bump to force a replace fetch (e.g. agentsListEpoch). */+ refreshKey?: number;+ limit?: number;+ debounceMs?: number;+};++export type UseSearchAgentsListResult = {+ agents: AgentLibraryEntry[];+ /** True while the replace fetch is in flight and the list is still empty. */+ isInitialLoading: boolean;+ /** True while replacing results that are already on screen (softer than a skeleton wipe). */+ isSearching: boolean;+ loadingMore: boolean;+ error: string | null;+ hasMore: boolean;+ listRef: (node: HTMLElement | null) => void;+ sentinelRef: (node: HTMLElement | null) => void;+};++/**+ * Debounced `searchAgents` with offset pagination and an IntersectionObserver sentinel.+ * Attach `listRef` to the scroll container and `sentinelRef` to a footer element.+ */+export function useSearchAgentsList({+ enabled,+ query,+ refreshKey = 0,+ limit = SEARCH_AGENTS_PAGE_SIZE,+ debounceMs = DEFAULT_DEBOUNCE_MS,+}: UseSearchAgentsListOptions): UseSearchAgentsListResult {+ const server = useOptionalServer();+ // While closed, sync immediately so reopen never fetches a stale query.+ const debouncedQuery = useDebouncedValue(query, enabled ? debounceMs : 0);++ const [agents, setAgents] = useState<AgentLibraryEntry[]>([]);+ const [loading, setLoading] = useState(false);+ const [loadingMore, setLoadingMore] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [hasMore, setHasMore] = useState(false);++ const genRef = useRef(0);+ const loadMoreInflightRef = useRef(false);+ const hasMoreRef = useRef(false);+ const agentsLenRef = useRef(0);+ const listElRef = useRef<HTMLElement | null>(null);+ const sentinelElRef = useRef<HTMLElement | null>(null);+ const [listEl, setListEl] = useState<HTMLElement | null>(null);+ const [sentinelEl, setSentinelEl] = useState<HTMLElement | null>(null);++ hasMoreRef.current = hasMore;+ agentsLenRef.current = agents.length;++ const listRef = useCallback((node: HTMLElement | null) => {+ listElRef.current = node;+ setListEl(node);+ }, []);++ const sentinelRef = useCallback((node: HTMLElement | null) => {+ sentinelElRef.current = node;+ setSentinelEl(node);+ }, []);++ const searchQuery = debouncedQuery.trim() || undefined;++ useEffect(() => {+ if (!enabled || server == null) return;++ const gen = ++genRef.current;+ loadMoreInflightRef.current = false;+ setLoading(true);+ setError(null);++ void server+ .searchAgents({ query: searchQuery, limit, offset: 0 })+ .then(rows => {+ if (gen !== genRef.current) return;+ setAgents(rows);+ setHasMore(rows.length >= limit);+ })+ .catch((err: unknown) => {+ if (gen !== genRef.current) return;+ setAgents([]);+ setHasMore(false);+ setError(err instanceof Error ? err.message : 'Failed to load agents.');+ })+ .finally(() => {+ if (gen === genRef.current) setLoading(false);+ });++ return () => {+ genRef.current += 1;+ };+ }, [enabled, server, searchQuery, limit, refreshKey]);++ const loadMore = useCallback(() => {+ if (!enabled || server == null || !hasMoreRef.current || loadMoreInflightRef.current || loading) {+ return;+ }++ const gen = genRef.current;+ const offset = agentsLenRef.current;+ loadMoreInflightRef.current = true;+ setLoadingMore(true);++ void server+ .searchAgents({ query: searchQuery, limit, offset })+ .then(rows => {+ if (gen !== genRef.current) return;+ setAgents(prev => [...prev, ...rows]);+ setHasMore(rows.length >= limit);+ })+ .catch(() => {+ if (gen !== genRef.current) return;+ setHasMore(false);+ })+ .finally(() => {+ loadMoreInflightRef.current = false;+ if (gen === genRef.current) setLoadingMore(false);+ });+ }, [enabled, server, searchQuery, limit, loading]);++ useEffect(() => {+ if (!enabled || !hasMore || listEl == null || sentinelEl == null) return;++ const observer = new IntersectionObserver(+ entries => {+ if (entries.some(entry => entry.isIntersecting)) {+ loadMore();+ }+ },+ { root: listEl, rootMargin: LOAD_MORE_ROOT_MARGIN },+ );+ observer.observe(sentinelEl);+ return () => observer.disconnect();+ }, [enabled, hasMore, listEl, sentinelEl, loadMore, agents.length]);++ return {+ agents,+ isInitialLoading: loading && agents.length === 0,+ isSearching: loading && agents.length > 0,+ loadingMore,+ error,+ hasMore,+ listRef,+ sentinelRef,+ };+}diff --git a/packages/trueforge-ui-sdk/src/containers/ComposerContainer.tsx b/packages/trueforge-ui-sdk/src/containers/ComposerContainer.tsxindex 335622044..c83107c5c 100644--- a/packages/trueforge-ui-sdk/src/containers/ComposerContainer.tsx+++ b/packages/trueforge-ui-sdk/src/containers/ComposerContainer.tsx@@ -1,7 +1,7 @@'use client';import { ComposerPrimitive, useAui, useAuiState } from '@assistant-ui/react';-import { useTrueFoundryCancel } from '@truefoundry/assistant-ui-runtime';+import { useTrueFoundryAgentSpec, useTrueFoundryCancel } from '@truefoundry/assistant-ui-runtime';import { useRef } from 'react';import { DraftCatalogProvider } from '../atoms/draft/DraftCatalogProvider.js';@@ -20,11 +20,20 @@ export type ComposerContainerProps = {function ComposerBody({ placeholder }: { placeholder: string }) {const ComposerShell = useSlot('ComposerShell');const aui = useAui();+ const shell = useOptionalShellMode();const hasText = useAuiState(s => s.composer.text.trim().length > 0);+ const { agentSpec } = useTrueFoundryAgentSpec();+ // Named (immutable) agents use a server-side model; only draft/mutable composers pick one here.+ const requiresModel = shell == null || (shell.mode.status === 'active' && shell.mode.isMutable);+ const hasModel = Boolean(agentSpec?.model?.name?.trim());const { isBusy, send, resetBusy } = useComposerBusyState();const cancel = useTrueFoundryCancel();const fileInputRef = useRef<HTMLInputElement>(null);- const submit = () => send(() => aui.composer().send());+ const canSubmit = !isBusy && hasText && (!requiresModel || hasModel);+ const submit = () => {+ if (!canSubmit) return;+ send(() => aui.composer().send());+ };return (<>@@ -70,7 +79,7 @@ function ComposerBody({ placeholder }: { placeholder: string }) {/>}disabled={isBusy}- canSubmit={!isBusy && hasText}+ canSubmit={canSubmit}isRunning={isBusy}onSubmit={submit}onCancel={() => {diff --git a/packages/trueforge-ui-sdk/src/containers/ThreadListContainer.pagination.test.tsx b/packages/trueforge-ui-sdk/src/containers/ThreadListContainer.pagination.test.tsxindex ea8c955ec..af773811b 100644--- a/packages/trueforge-ui-sdk/src/containers/ThreadListContainer.pagination.test.tsx+++ b/packages/trueforge-ui-sdk/src/containers/ThreadListContainer.pagination.test.tsx@@ -20,6 +20,7 @@ vi.mock('@assistant-ui/react', () => ({isLoadingMore: false,hasMore: true,threadIds: ['t1'],+ threadItems: [{ id: 't1', remoteId: 's1', lastMessageAt: undefined }],mainThreadId: 't1',},threadListItem: {@@ -30,6 +31,7 @@ vi.mock('@assistant-ui/react', () => ({custom: undefined,},}),+ ThreadListItemByIndexProvider: ({ children }: { children?: ReactNode }) => <>{children}</>,ThreadListPrimitive: {Root: ({ children, className }: { children?: ReactNode; className?: string }) => (<div className={className}>{children}</div>diff --git a/packages/trueforge-ui-sdk/src/containers/ThreadListContainer.tsx b/packages/trueforge-ui-sdk/src/containers/ThreadListContainer.tsxindex 2b49ed006..78f12f101 100644--- a/packages/trueforge-ui-sdk/src/containers/ThreadListContainer.tsx+++ b/packages/trueforge-ui-sdk/src/containers/ThreadListContainer.tsx@@ -1,19 +1,25 @@'use client';import {+ ThreadListItemByIndexProvider,ThreadListItemMorePrimitive,ThreadListItemPrimitive,ThreadListPrimitive,useAui,useAuiState,} from '@assistant-ui/react';-import { useEffect, useRef, useState, type ReactNode, type Ref } from 'react';+import { useEffect, useMemo, useRef, useState, type ReactNode, type Ref } from 'react';import { AgentHistoryFilterButton } from '../atoms/AgentHistoryFilterButton.js';import { auiButtonClass } from '../atoms/lib/buttonClasses.js';import { cn } from '../atoms/lib/cn.js';import { useCompactLayout } from '../atoms/lib/CompactLayoutContext.js';-import { canReuseMutableShell, readThreadAgentName, threadListItemIsMutable } from '../atoms/lib/threadListMeta.js';+import {+ canReuseMutableShell,+ readThreadAgentName,+ threadListIndicesByRecency,+ threadListItemIsMutable,+} from '../atoms/lib/threadListMeta.js';import { useIsMobile } from '../atoms/lib/useIsMobile.js';import { BottomSheet } from '../atoms/primitives/BottomSheet.js';import { Icon } from '../icons/Icon.js';@@ -101,7 +107,13 @@ function ThreadListItemDeleteMenu() {);}-function ThreadListItemRow({ onThreadOpen, showDelete }: { onThreadOpen?: () => void; showDelete: boolean }) {+function ThreadListItemRow({+ onThreadOpen,+ canDeleteSession,+}: {+ onThreadOpen?: () => void;+ canDeleteSession: boolean;+}) {const aui = useAui();const shell = useOptionalShellMode();const ThreadListRow = useSlot('ThreadListRow');@@ -112,6 +124,7 @@ function ThreadListItemRow({ onThreadOpen, showDelete }: { onThreadOpen?: () =>const custom = useAuiState(s => s.threadListItem.custom);const mainThreadId = useAuiState(s => s.threads.mainThreadId);const agentName = readThreadAgentName(custom);+ const showDelete = canDeleteSession && remoteId != null;return (<ThreadListItemPrimitive.Root className="min-w-0">@@ -163,6 +176,38 @@ function ThreadListItemRow({ onThreadOpen, showDelete }: { onThreadOpen?: () =>);}+function useThreadListIndicesByRecency(): number[] {+ const threadIds = useAuiState(s => s.threads.threadIds);+ const threadItems = useAuiState(s => s.threads.threadItems);++ return useMemo(() => threadListIndicesByRecency({ threadIds, threadItems }), [threadIds, threadItems]);+}++function ThreadListItemsByRecency({+ onThreadOpen,+ canDeleteSession,+}: {+ onThreadOpen?: () => void;+ canDeleteSession: boolean;+}) {+ // Newest-first: remount/switchToThread can append the active session to threadIds.+ const indices = useThreadListIndicesByRecency();+ const threadIds = useAuiState(s => s.threads.threadIds);++ return (+ <>+ {indices.map(index => {+ const key = threadIds[index] ?? String(index);+ return (+ <ThreadListItemByIndexProvider key={key} index={index} archived={false}>+ <ThreadListItemRow onThreadOpen={onThreadOpen} canDeleteSession={canDeleteSession} />+ </ThreadListItemByIndexProvider>+ );+ })}+ </>+ );+}+const THREAD_LIST_VIEWPORT_SLOT = 'aui_thread-list-viewport';/** How close to the bottom (px) before the next sessions page is fetched. */const LOAD_MORE_BOTTOM_PX = 80;@@ -281,14 +326,7 @@ export function ThreadListContainer({ onThreadOpen }: ThreadListContainerProps =} else {listBody = (<ThreadListPrimitive.Root className="flex min-h-0 flex-col gap-0.5">- <ThreadListPrimitive.Items>- {({ threadListItem }) => (- <ThreadListItemRow- onThreadOpen={onThreadOpen}- showDelete={canDeleteSession && threadListItem.remoteId != null}- />- )}- </ThreadListPrimitive.Items>+ <ThreadListItemsByRecency onThreadOpen={onThreadOpen} canDeleteSession={canDeleteSession} /></ThreadListPrimitive.Root>);}diff --git a/packages/trueforge-ui-sdk/src/containers/TrueFoundryChatProvider.tsx b/packages/trueforge-ui-sdk/src/containers/TrueFoundryChatProvider.tsxindex cc542f38f..e0f73454d 100644--- a/packages/trueforge-ui-sdk/src/containers/TrueFoundryChatProvider.tsx+++ b/packages/trueforge-ui-sdk/src/containers/TrueFoundryChatProvider.tsx@@ -7,8 +7,9 @@ import {type TrueFoundryAgentConfig,type UseTrueFoundryAgentRuntimeOptions,} from '@truefoundry/assistant-ui-runtime';-import { useMemo, type ReactNode } from 'react';+import { useCallback, useMemo, type ReactNode } from 'react';+import { notifyComposerBusyFailure } from '../hooks/useComposerBusyState.js';import type { AgentUIServer } from '../server/types.js';import { ErrorToasterProvider, useErrorToaster } from './ErrorToasterContainer.js';@@ -48,7 +49,16 @@ function ChatRuntimeScope({children: ReactNode;}) {const { showError } = useErrorToaster();- const resolvedOnError = onError ?? showError;+ const reportError = onError ?? showError;+ // composer().send() is void and swallows onNew rejections; clear optimistic+ // busy when the runtime reports a pre-stream failure (e.g. createSession).+ const resolvedOnError = useCallback(+ (error: unknown) => {+ notifyComposerBusyFailure();+ reportError(error);+ },+ [reportError],+ );const runtime = useTrueFoundryAgentRuntime({server: server as never,diff --git a/packages/trueforge-ui-sdk/src/containers/TrueforgeUI.tsx b/packages/trueforge-ui-sdk/src/containers/TrueforgeUI.tsxindex d55551a8e..ef96a17c8 100644--- a/packages/trueforge-ui-sdk/src/containers/TrueforgeUI.tsx+++ b/packages/trueforge-ui-sdk/src/containers/TrueforgeUI.tsx@@ -40,6 +40,8 @@ export type TrueforgeUIProps = {* 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 }) {@@ -206,6 +208,7 @@ function TrueforgeUIShell(props: TrueforgeUIProps) {theme,className,agentConfig = DEFAULT_AGENT_CONFIG,+ initialSettingsOpen = false,server: serverConfig,onError,...providerRest@@ -235,7 +238,7 @@ function TrueforgeUIShell(props: TrueforgeUIProps) {return (<SlotsProvider overrides={overrides} theme={theme}><ServerProvider server={server}>- <ShellModeProvider agentConfig={agentConfig}>+ <ShellModeProvider agentConfig={agentConfig} initialSettingsOpen={initialSettingsOpen}><ChatProviderFromShell server={server} onError={onError} {...providerRest}>{layoutTree}</ChatProviderFromShell>diff --git a/packages/trueforge-ui-sdk/src/hooks/useComposerBusyState.ts b/packages/trueforge-ui-sdk/src/hooks/useComposerBusyState.tsindex 7e802fcc0..8de9cea13 100644--- a/packages/trueforge-ui-sdk/src/hooks/useComposerBusyState.ts+++ b/packages/trueforge-ui-sdk/src/hooks/useComposerBusyState.ts@@ -14,6 +14,20 @@ export type ComposerBusyState = {const ComposerBusyContext = createContext<ComposerBusyState | null>(null);+/**+ * `aui.composer().send()` returns void and swallows `onNew` rejections, so the+ * optimistic submitting flag cannot clear via Promise.catch. First-message+ * failures (e.g. createSession) also never flip `useThreadIsRunning()`. Chat+ * runtime `onError` calls this so the Cancel/spinner state does not stick.+ */+const busyFailureListeners = new Set<() => void>();++export function notifyComposerBusyFailure(): void {+ for (const listener of busyFailureListeners) {+ listener();+ }+}+function useComposerBusyStateValue(): ComposerBusyState {const isRunning = useThreadIsRunning();const [isSubmitting, setIsSubmitting] = useState(false);@@ -24,6 +38,16 @@ function useComposerBusyStateValue(): ComposerBusyState {}}, [isRunning]);+ useEffect(() => {+ const clearSubmitting = () => {+ setIsSubmitting(false);+ };+ busyFailureListeners.add(clearSubmitting);+ return () => {+ busyFailureListeners.delete(clearSubmitting);+ };+ }, []);+const isBusy = isRunning || isSubmitting;const resetBusy = useCallback(() => {diff --git a/packages/trueforge-ui-sdk/src/icons/IconRegistry.tsx b/packages/trueforge-ui-sdk/src/icons/IconRegistry.tsxindex 0b00ebc8f..04134f3d5 100644--- a/packages/trueforge-ui-sdk/src/icons/IconRegistry.tsx+++ b/packages/trueforge-ui-sdk/src/icons/IconRegistry.tsx@@ -1,4 +1,3 @@-import type { LucideIcon } from 'lucide-react';import {Archive,ArrowDown,@@ -7,7 +6,6 @@ import {Bot,Box,Brain,- BrushCleaning,Check,ChevronDown,ChevronLeft,@@ -40,21 +38,47 @@ import {PanelLeftOpen,Paperclip,Pencil,+ Play,Plug,Plus,RotateCw,Search,Settings,Sparkle,+ SquarePen,Sun,Terminal,Trash2,Wrench,X,} from 'lucide-react';+import type { SVGProps } from 'react';import type { IconEntry, IconMap } from '../theme/types.js';+/** Lucide `broom` (https://lucide.dev/icons/broom) — not in lucide-react 0.x. */+function Broom({ size = 24, ...props }: SVGProps<SVGSVGElement> & { size?: string | number }) {+ return (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width={size}+ height={size}+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ {...props}+ >+ <path d="M13.5 10.5 22 2" />+ <path d="M14.734 13.841a2 2 0 00-.314-2.42L12.58 9.58a2 2 0 00-2.421-.314l-7.657 4.461A1 1 0 002.3 15.3l6.403 6.403a1 1 0 001.571-.204z" />+ <path d="m5 18 2-2" />+ <path d="m7.699 10.7 5.602 5.601" />+ </svg>+ );+}+const registry = new Map<string, IconEntry>();export function registerIcon(name: string, icon: IconEntry): void {@@ -77,7 +101,7 @@ export function resolveIconName(icon: string | readonly string[]): string {return icon[icon.length - 1] ?? '';}-const defaults: Record<string, LucideIcon> = {+const defaults: Record<string, IconEntry> = {paperclip: Paperclip,'arrow-up': ArrowUp,'arrow-down': ArrowDown,@@ -85,8 +109,10 @@ const defaults: Record<string, LucideIcon> = {xmark: X,check: Check,pencil: Pencil,+ play: Play,+ 'square-pen': SquarePen,'rotate-right': RotateCw,- broom: BrushCleaning,+ broom: Broom,ellipsis: Ellipsis,trash: Trash2,'box-archive': Archive,diff --git a/packages/trueforge-ui-sdk/src/layouts/SidebarLayout.tsx b/packages/trueforge-ui-sdk/src/layouts/SidebarLayout.tsxindex c1e43848e..6fe6d6431 100644--- a/packages/trueforge-ui-sdk/src/layouts/SidebarLayout.tsx+++ b/packages/trueforge-ui-sdk/src/layouts/SidebarLayout.tsx@@ -116,7 +116,7 @@ export function SidebarLayout({ className }: { className?: string }) {className={auiButtonClass({ variant: 'ghost', size: 'icon' })}onClick={handleNewChat}>- <Icon name="pencil" />+ <Icon name="square-pen" /></button>) : null}<AgentsLibraryButton compact />diff --git a/packages/trueforge-ui-sdk/src/server/ShellModeContext.tsx b/packages/trueforge-ui-sdk/src/server/ShellModeContext.tsxindex 41f94887c..0b0d39726 100644--- a/packages/trueforge-ui-sdk/src/server/ShellModeContext.tsx+++ b/packages/trueforge-ui-sdk/src/server/ShellModeContext.tsx@@ -139,9 +139,12 @@ function libraryAgentId(agent: Pick<AgentLibraryEntry, 'agentId'>): string {export function ShellModeProvider({agentConfig = DEFAULT_AGENT_CONFIG,+ initialSettingsOpen = false,children,}: {agentConfig?: AgentConfig;+ /** Open settings on first paint (e.g. host boot with no models). Does not re-open later. */+ initialSettingsOpen?: boolean;children: ReactNode;}) {const capabilities = useServerCapabilities();@@ -163,7 +166,7 @@ export function ShellModeProvider({const [mutableEpoch, setMutableEpoch] = useState(0);const [clearEpoch, setClearEpoch] = useState(0);const [agentsListEpoch, setAgentsListEpoch] = useState(0);- const [settingsOpenState, setSettingsOpenState] = useState(false);+ const [settingsOpenState, setSettingsOpenState] = useState(initialSettingsOpen);const [historyAgentFilter, setHistoryAgentFilter] = useState<string | null>(null);const [pendingSessionId, setPendingSessionId] = useState<string | undefined>(undefined);const settingsEnabled = capabilities?.settings?.enabled !== false;diff --git a/packages/trueforge-ui-sdk/src/server/types.ts b/packages/trueforge-ui-sdk/src/server/types.tsindex 6fdb0ebb6..bc56b5134 100644--- a/packages/trueforge-ui-sdk/src/server/types.ts+++ b/packages/trueforge-ui-sdk/src/server/types.ts@@ -17,6 +17,8 @@ export interface ModelSelection {provider: string;/** When non-empty, UI shows a reasoning-effort picker beside the model selector. */reasoningEfforts?: string[];+ /** Provider logo URL from the model catalog; selector falls back to a monogram when omitted. */+ providerLogo?: string;}/** Skill picker row. Host extends for fqn, preload, etc. */diff --git a/packages/trueforge-ui-sdk/test/atoms/AgentHistoryFilterButton.test.tsx b/packages/trueforge-ui-sdk/test/atoms/AgentHistoryFilterButton.test.tsxindex 376d4a4b8..4ba682bd0 100644--- a/packages/trueforge-ui-sdk/test/atoms/AgentHistoryFilterButton.test.tsx+++ b/packages/trueforge-ui-sdk/test/atoms/AgentHistoryFilterButton.test.tsx@@ -98,18 +98,21 @@ describe('AgentHistoryFilterButton', () => {});expect(screen.getByTestId('filter-value')).toHaveTextContent('all');+ expect(screen.queryByTestId('history-filter-active-dot')).not.toBeInTheDocument();fireEvent.click(screen.getByRole('button', { name: /Filter chat history/i }));await waitFor(() => expect(screen.getByRole('menuitem', { name: /From SDK/i })).toBeInTheDocument());- const menu = screen.getByRole('menu', { name: 'Filter agents' });+ const menu = screen.getByRole('menu', { name: /Filter agents/i });expect(menu).toHaveClass('font-sans-flex');expect(menu.parentElement).toHaveClass('aui-theme-root');+ expect(menu.className).toContain('bg-popover');await act(async () => {fireEvent.click(screen.getByRole('menuitem', { name: /From SDK/i }));});expect(screen.getByTestId('filter-value')).toHaveTextContent('from-sdk');+ expect(screen.getByTestId('history-filter-active-dot')).toBeInTheDocument();expect(searchAgents).toHaveBeenCalled();});diff --git a/packages/trueforge-ui-sdk/test/atoms/AgentsLibrary.test.tsx b/packages/trueforge-ui-sdk/test/atoms/AgentsLibrary.test.tsxindex 19706ec44..cc94d357c 100644--- a/packages/trueforge-ui-sdk/test/atoms/AgentsLibrary.test.tsx+++ b/packages/trueforge-ui-sdk/test/atoms/AgentsLibrary.test.tsx@@ -245,4 +245,23 @@ describe('AgentsLibraryButton', () => {});expect(searchAgents).toHaveBeenCalledTimes(2);});++ it('shows 50+ when the first page is full', async () => {+ const agents = Array.from({ length: 50 }, (_, i) => ({ name: `agent-${i}` }));+ const server = mockServer(agents);++ render(+ <SlotsProvider>+ <ServerProvider server={server}>+ <ShellModeProvider>+ <AgentsLibraryButton />+ </ShellModeProvider>+ </ServerProvider>+ </SlotsProvider>,+ );++ await waitFor(() => {+ expect(screen.getByRole('button', { name: /Agents Library \(50\+\)/ })).toBeInTheDocument();+ });+ });});diff --git a/packages/trueforge-ui-sdk/test/atoms/SyntaxHighlighter.test.tsx b/packages/trueforge-ui-sdk/test/atoms/SyntaxHighlighter.test.tsxindex 2a9801917..ac66f1dd0 100644--- a/packages/trueforge-ui-sdk/test/atoms/SyntaxHighlighter.test.tsx+++ b/packages/trueforge-ui-sdk/test/atoms/SyntaxHighlighter.test.tsx@@ -1,7 +1,7 @@// @vitest-environment jsdom-import { render, screen } from '@testing-library/react';+import { act, fireEvent, render, screen } from '@testing-library/react';import type { ComponentType, ReactNode } from 'react';-import { describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { SyntaxHighlighter } from '@/atoms/SyntaxHighlighter.js';@@ -21,6 +21,7 @@ vi.mock('react-syntax-highlighter', () => ({language,style,showLineNumbers,+ wrapLongLines,PreTag,CodeTag,}: {@@ -28,6 +29,7 @@ vi.mock('react-syntax-highlighter', () => ({language?: string;style?: unknown;showLineNumbers?: boolean;+ wrapLongLines?: boolean;PreTag?: ComponentType<{ children?: ReactNode; className?: string }>;CodeTag?: ComponentType<{ children?: ReactNode; className?: string }>;}) => (@@ -36,6 +38,7 @@ vi.mock('react-syntax-highlighter', () => ({data-language={language}data-theme={style === syntaxMocks.dark ? 'dark' : 'light'}data-line-numbers={String(Boolean(showLineNumbers))}+ data-wrap-long-lines={String(Boolean(wrapLongLines))}>{PreTag ? (<PreTag className="engine-pre">@@ -48,17 +51,45 @@ vi.mock('react-syntax-highlighter', () => ({),}));+const clipboardDescriptor = Object.getOwnPropertyDescriptor(navigator, 'clipboard');+describe('SyntaxHighlighter', () => {+ const writeText = vi.fn(() => Promise.resolve());++ beforeEach(() => {+ writeText.mockClear();+ Object.defineProperty(navigator, 'clipboard', {+ configurable: true,+ value: { writeText },+ });+ });++ afterEach(() => {+ vi.useRealTimers();+ if (clipboardDescriptor === undefined) {+ Reflect.deleteProperty(navigator, 'clipboard');+ } else {+ Object.defineProperty(navigator, 'clipboard', clipboardDescriptor);+ }+ });+it('passes code, language, and line-number behavior to the highlighting engine', () => {render(<SyntaxHighlighter code={'const x = 1;\nconsole.log(x);'} language="typescript" showLineNumbers />);const highlighter = screen.getByTestId('syntax-engine');expect(highlighter).toHaveAttribute('data-language', 'typescript');expect(highlighter).toHaveAttribute('data-line-numbers', 'true');+ expect(highlighter).toHaveAttribute('data-wrap-long-lines', 'true');expect(highlighter).toHaveTextContent('const x = 1;');expect(highlighter).toHaveTextContent('console.log(x);');- expect(highlighter.querySelector('pre')).toHaveClass('engine-pre', 'max-w-full', 'overflow-x-auto');- expect(highlighter.querySelector('code')).toHaveClass('engine-code');+ expect(highlighter.querySelector('pre')).toHaveClass(+ 'engine-pre',+ 'max-w-full',+ 'overflow-x-auto',+ 'whitespace-pre-wrap',+ 'break-words',+ );+ expect(highlighter.querySelector('code')).toHaveClass('engine-code', 'whitespace-pre-wrap', 'break-words');});it('switches the highlighting theme and preserves consumer classes', () => {@@ -70,4 +101,23 @@ describe('SyntaxHighlighter', () => {rerender(<SyntaxHighlighter code="value" darkTheme className="consumer-class" />);expect(screen.getByTestId('syntax-engine')).toHaveAttribute('data-theme', 'dark');});++ it('copies the code and reports the copied state', async () => {+ vi.useFakeTimers();+ render(<SyntaxHighlighter code="copy me" />);++ await act(async () => {+ fireEvent.click(screen.getByRole('button', { name: 'Copy' }));+ await Promise.resolve();+ });++ expect(writeText).toHaveBeenCalledWith('copy me');+ expect(screen.getByRole('button', { name: 'Copied!' })).toBeInTheDocument();++ act(() => {+ vi.advanceTimersByTime(2000);+ });+ expect(screen.getByRole('button', { name: 'Copy' })).toBeInTheDocument();+ vi.useRealTimers();+ });});diff --git a/packages/trueforge-ui-sdk/test/atoms/draft/DraftCatalogProvider.test.tsx b/packages/trueforge-ui-sdk/test/atoms/draft/DraftCatalogProvider.test.tsxindex a1da58001..70aa7fadb 100644--- a/packages/trueforge-ui-sdk/test/atoms/draft/DraftCatalogProvider.test.tsx+++ b/packages/trueforge-ui-sdk/test/atoms/draft/DraftCatalogProvider.test.tsx@@ -1,5 +1,5 @@// @vitest-environment jsdom-import { act, render, screen, waitFor } from '@testing-library/react';+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';import { describe, expect, it, vi } from 'vitest';import { DraftCatalogProvider, useDraftCatalog } from '@/atoms/draft/DraftCatalogProvider.js';@@ -12,6 +12,9 @@ function CatalogProbe() {return (<div>+ <button type="button" onClick={() => catalog.ensureLoaded()}>+ Load catalog+ </button><output data-testid="models">{catalog.models.map(model => model.name).join(',')}</output><output data-testid="skills">{catalog.skills.map(skill => skill.name).join(',')}</output><output data-testid="connectors">{catalog.connectors.map(connector => connector.name).join(',')}</output>@@ -74,6 +77,11 @@ describe('DraftCatalogProvider', () => {</ServerProvider>,);+ expect(screen.getByTestId('loading')).toHaveTextContent('false');+ expect(getModels).not.toHaveBeenCalled();++ fireEvent.click(screen.getByRole('button', { name: 'Load catalog' }));+expect(screen.getByTestId('loading')).toHaveTextContent('true');expect(getModels).toHaveBeenCalledTimes(1);expect(getSkills).toHaveBeenCalledTimes(1);@@ -108,6 +116,8 @@ describe('DraftCatalogProvider', () => {</ServerProvider>,);+ fireEvent.click(screen.getByRole('button', { name: 'Load catalog' }));+await waitFor(() => expect(screen.getByTestId('error')).toHaveTextContent('Catalog unavailable'));expect(screen.getByTestId('loading')).toHaveTextContent('false');expect(screen.getByTestId('models')).toBeEmptyDOMElement();diff --git a/packages/trueforge-ui-sdk/test/atoms/draft/DraftCompositeSelector.test.tsx b/packages/trueforge-ui-sdk/test/atoms/draft/DraftCompositeSelector.test.tsxindex 14d76616a..308594664 100644--- a/packages/trueforge-ui-sdk/test/atoms/draft/DraftCompositeSelector.test.tsx+++ b/packages/trueforge-ui-sdk/test/atoms/draft/DraftCompositeSelector.test.tsx@@ -1,6 +1,6 @@// @vitest-environment jsdom-import { fireEvent, render, screen, within } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { act, fireEvent, render, screen, within } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { DraftCatalogProvider } from '@/atoms/draft/DraftCatalogProvider.js';import { DraftCompositeSelector, type DraftCompositeSelectorProps } from '@/atoms/draft/DraftCompositeSelector.js';@@ -45,6 +45,7 @@ function renderSelector({ props = {}, getCapabilities }: RenderSelectorOptions =describe('DraftCompositeSelector', () => {beforeEach(() => {+ vi.useFakeTimers({ shouldAdvanceTime: true });agentSpec = {model: { name: 'openai/gpt-4.1' },mcpServers: [{ id: 'slack', name: 'Slack' }],@@ -53,7 +54,11 @@ describe('DraftCompositeSelector', () => {updateAgentSpec.mockReset();});- it('adds an available connector to the draft spec', async () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ it('adds an available connector to the draft spec after debounce', async () => {renderSelector();fireEvent.click(screen.getByRole('button', { name: 'Add connectors, skills, or attachments' }));@@ -61,15 +66,21 @@ describe('DraftCompositeSelector', () => {expect(github).toHaveAttribute('aria-checked', 'false');fireEvent.click(github);+ expect(updateAgentSpec).not.toHaveBeenCalled();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(300);+ });+expect(updateAgentSpec).toHaveBeenCalledWith({mcpServers: [{ id: 'slack', name: 'Slack' },{ id: 'github', name: 'GitHub' },],+ skills: [{ id: 'research', name: 'Research' }],});});- it('switches tabs, resets search, and removes a selected skill', async () => {+ it('switches tabs, resets search, and removes a selected skill on close flush', async () => {renderSelector();fireEvent.click(screen.getByRole('button', { name: 'Add connectors, skills, or attachments' }));await screen.findByRole('menuitemcheckbox', { name: /GitHub/ });@@ -88,7 +99,13 @@ describe('DraftCompositeSelector', () => {expect(within(dialog).getByRole('menuitemcheckbox', { name: /Writer/ })).toBeInTheDocument();fireEvent.click(research);- expect(updateAgentSpec).toHaveBeenCalledWith({ skills: [] });+ // Close before debounce — flush pending local state.+ fireEvent.click(screen.getByRole('button', { name: 'Add connectors, skills, or attachments' }));++ expect(updateAgentSpec).toHaveBeenCalledWith({+ mcpServers: [{ id: 'slack', name: 'Slack' }],+ skills: [],+ });});it('forwards attachment requests and closes the picker', async () => {@@ -123,7 +140,13 @@ describe('DraftCompositeSelector', () => {expect(screen.getByRole('menuitemcheckbox', { name: /Writer/ })).toBeDisabled();fireEvent.click(research);- expect(updateAgentSpec).toHaveBeenCalledWith({ skills: [] });+ // Close before debounce — flush pending local state.+ fireEvent.click(screen.getByRole('button', { name: 'Add connectors, skills, or attachments' }));++ expect(updateAgentSpec).toHaveBeenCalledWith({+ mcpServers: [{ id: 'slack', name: 'Slack' }],+ skills: [],+ });});it('disables available skills until capabilities load', async () => {diff --git a/packages/trueforge-ui-sdk/test/atoms/draft/DraftModelSelector.test.tsx b/packages/trueforge-ui-sdk/test/atoms/draft/DraftModelSelector.test.tsxindex b94664935..50c213997 100644--- a/packages/trueforge-ui-sdk/test/atoms/draft/DraftModelSelector.test.tsx+++ b/packages/trueforge-ui-sdk/test/atoms/draft/DraftModelSelector.test.tsx@@ -5,8 +5,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { DraftCatalogProvider } from '@/atoms/draft/DraftCatalogProvider.js';import { DraftModelSelector, type DraftModelSelectorProps } from '@/atoms/draft/DraftModelSelector.js';import { ServerProvider } from '@/server/ServerContext.js';-import type { AgentSpec, ModelSelection } from '@/server/types.js';-import { createMockAgentUIServer } from '../../server/mockServer.js';+import { ShellModeProvider, useShellMode } from '@/server/ShellModeContext.js';+import type { AgentSpec, AgentUIServer, ModelSelection } from '@/server/types.js';+import { createMockAgentUIServer, createMockCatalog } from '../../server/mockServer.js';let agentSpec: AgentSpec | undefined;const updateAgentSpec = vi.fn();@@ -17,7 +18,7 @@ vi.mock('@truefoundry/assistant-ui-runtime', () => ({}));const models: ModelSelection[] = [- { name: 'openai/gpt-4.1', provider: 'OpenAI' },+ { name: 'openai/gpt-4.1', provider: 'OpenAI', providerLogo: 'https://assets.example/openai.svg' },{name: 'anthropic/claude-3.7-sonnet',provider: 'Anthropic',@@ -25,14 +26,25 @@ const models: ModelSelection[] = [},];-function renderSelector(props: DraftModelSelectorProps = {}) {- const server = createMockAgentUIServer({ getModels: async () => models });+function SettingsOpenProbe() {+ const { settingsOpen } = useShellMode();+ return <div data-testid="settings-open">{String(settingsOpen)}</div>;+}++function renderSelector(+ props: DraftModelSelectorProps = {},+ serverOverrides: Partial<AgentUIServer> = { getModels: async () => models },+) {+ const server = createMockAgentUIServer(serverOverrides);return render(<ServerProvider server={server}>- <DraftCatalogProvider>- <DraftModelSelector {...props} />- </DraftCatalogProvider>+ <ShellModeProvider>+ <DraftCatalogProvider>+ <DraftModelSelector {...props} />+ <SettingsOpenProbe />+ </DraftCatalogProvider>+ </ShellModeProvider></ServerProvider>,);}@@ -53,10 +65,22 @@ describe('DraftModelSelector', () => {const trigger = await screen.findByTitle('Select model');await waitFor(() => expect(trigger).toHaveTextContent('gpt-4.1'));+ expect(trigger.querySelector('img')?.getAttribute('src')).toBe('https://assets.example/openai.svg');fireEvent.click(trigger);const listbox = screen.getByRole('listbox', { name: 'Select model' });expect(within(listbox).getAllByRole('option')).toHaveLength(2);+ expect(+ within(listbox)+ .getByRole('option', { name: /gpt-4.1/i })+ .querySelector('img')+ ?.getAttribute('src'),+ ).toBe('https://assets.example/openai.svg');+ expect(+ within(listbox)+ .getByRole('option', { name: /claude-3.7-sonnet/i })+ .querySelector('img'),+ ).toBeNull();fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'anthropic' } });expect(within(listbox).getAllByRole('option')).toHaveLength(1);@@ -89,4 +113,30 @@ describe('DraftModelSelector', () => {rerender(<DraftModelSelector isRunning />);expect(screen.getByTitle('Select model')).toBeDisabled();});++ it('shows a settings CTA when the host has a catalog and no models', async () => {+ renderSelector(+ {},+ {+ getModels: async () => [],+ catalog: createMockCatalog(),+ },+ );++ fireEvent.click(await screen.findByTitle('Select model'));+ const cta = await screen.findByRole('button', { name: /Please configure Models in the settings/i });+ expect(cta.querySelector('.underline')).toHaveTextContent('settings');++ fireEvent.click(cta);+ expect(screen.queryByRole('listbox', { name: 'Select model' })).not.toBeInTheDocument();+ expect(screen.getByTestId('settings-open')).toHaveTextContent('true');+ });++ it('shows No models when the catalog is not configured', async () => {+ renderSelector({}, { getModels: async () => [] });++ fireEvent.click(await screen.findByTitle('Select model'));+ await waitFor(() => expect(screen.getByText('No models')).toBeInTheDocument());+ expect(screen.queryByRole('button', { name: /Please configure Models/i })).not.toBeInTheDocument();+ });});diff --git a/packages/trueforge-ui-sdk/src/atoms/lib/threadListMeta.test.ts b/packages/trueforge-ui-sdk/test/atoms/lib/threadListMeta.test.tssimilarity index 65%rename from packages/trueforge-ui-sdk/src/atoms/lib/threadListMeta.test.tsrename to packages/trueforge-ui-sdk/test/atoms/lib/threadListMeta.test.tsindex e7e584ef9..d346803ba 100644--- a/packages/trueforge-ui-sdk/src/atoms/lib/threadListMeta.test.ts+++ b/packages/trueforge-ui-sdk/test/atoms/lib/threadListMeta.test.ts@@ -5,8 +5,9 @@ import {formatRelativeShort,readThreadAgentName,readThreadIsMutable,+ threadListIndicesByRecency,threadListItemIsMutable,-} from './threadListMeta.js';+} from '@/atoms/lib/threadListMeta.js';describe('formatRelativeShort', () => {const now = new Date('2026-08-06T12:00:00.000Z');@@ -43,6 +44,39 @@ describe('threadListItemIsMutable', () => {});});+describe('threadListIndicesByRecency', () => {+ it('orders by lastMessageAt newest-first even when ids were appended', () => {+ const older = new Date('2026-08-06T11:00:00.000Z');+ const newer = new Date('2026-08-06T12:00:00.000Z');+ // Selected session appended at end (assistant-ui switchToThread fetch race).+ expect(+ threadListIndicesByRecency({+ threadIds: ['older', 'newer-appended'],+ threadItems: [+ { id: 'older', remoteId: 'older', lastMessageAt: older },+ { id: 'newer-appended', remoteId: 'newer-appended', lastMessageAt: newer },+ ],+ }),+ ).toEqual([1, 0]);+ });++ it('pins threads without lastMessageAt above dated history (empty New Chat)', () => {+ const older = new Date('2026-08-06T11:00:00.000Z');+ const newer = new Date('2026-08-06T12:00:00.000Z');+ // Local new thread appended at end with no timestamp.+ expect(+ threadListIndicesByRecency({+ threadIds: ['older', 'newer', 'new-chat'],+ threadItems: [+ { id: 'older', remoteId: 'older', lastMessageAt: older },+ { id: 'newer', remoteId: 'newer', lastMessageAt: newer },+ { id: 'new-chat', remoteId: null, lastMessageAt: undefined },+ ],+ }),+ ).toEqual([2, 1, 0]);+ });+});+describe('canReuseMutableShell', () => {it('allows blank drafts to share the mutable shell', () => {expect(diff --git a/packages/trueforge-ui-sdk/test/atoms/lib/useDebouncedValue.test.ts b/packages/trueforge-ui-sdk/test/atoms/lib/useDebouncedValue.test.tsnew file mode 100644index 000000000..62ccfea3f--- /dev/null+++ b/packages/trueforge-ui-sdk/test/atoms/lib/useDebouncedValue.test.ts@@ -0,0 +1,46 @@+// @vitest-environment jsdom+import { act, renderHook } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { useDebouncedValue } from '@/atoms/lib/useDebouncedValue.js';++describe('useDebouncedValue', () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ it('returns the initial value immediately and debounces subsequent updates', () => {+ vi.useFakeTimers();+ const { result, rerender } = renderHook(({ value, delay }) => useDebouncedValue(value, delay), {+ initialProps: { value: 'a', delay: 300 },+ });++ expect(result.current).toBe('a');++ rerender({ value: 'ab', delay: 300 });+ expect(result.current).toBe('a');++ act(() => {+ vi.advanceTimersByTime(299);+ });+ expect(result.current).toBe('a');++ act(() => {+ vi.advanceTimersByTime(1);+ });+ expect(result.current).toBe('ab');+ });++ it('syncs immediately when delay is 0', () => {+ vi.useFakeTimers();+ const { result, rerender } = renderHook(({ value, delay }) => useDebouncedValue(value, delay), {+ initialProps: { value: 'x', delay: 0 },+ });++ rerender({ value: 'y', delay: 0 });+ act(() => {+ vi.advanceTimersByTime(0);+ });+ expect(result.current).toBe('y');+ });+});diff --git a/packages/trueforge-ui-sdk/test/atoms/lib/useSearchAgentsList.test.tsx b/packages/trueforge-ui-sdk/test/atoms/lib/useSearchAgentsList.test.tsxnew file mode 100644index 000000000..956500a73--- /dev/null+++ b/packages/trueforge-ui-sdk/test/atoms/lib/useSearchAgentsList.test.tsx@@ -0,0 +1,110 @@+// @vitest-environment jsdom+import { act, renderHook, waitFor } from '@testing-library/react';+import type { ReactNode } from 'react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { SEARCH_AGENTS_PAGE_SIZE, useSearchAgentsList } from '@/atoms/lib/useSearchAgentsList.js';+import { ServerProvider } from '@/server/ServerContext.js';+import type { AgentLibraryEntry, AgentUIServer } from '@/server/types.js';+import { createMockAgentUIServer } from '../../server/mockServer.js';++function wrapperFor(server: AgentUIServer) {+ return function Wrapper({ children }: { children: ReactNode }) {+ return <ServerProvider server={server}>{children}</ServerProvider>;+ };+}++describe('useSearchAgentsList', () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ it('fetches the first page when enabled and paginates via loadMore sentinel', async () => {+ const page1 = Array.from({ length: SEARCH_AGENTS_PAGE_SIZE }, (_, i) => ({ name: `agent-${i}` }));+ const page2 = [{ name: 'agent-extra' }];+ const searchAgents = vi.fn().mockResolvedValueOnce(page1).mockResolvedValueOnce(page2);++ const server = createMockAgentUIServer({ searchAgents });+ const { result } = renderHook(() => useSearchAgentsList({ enabled: true, query: '' }), {+ wrapper: wrapperFor(server),+ });++ await waitFor(() => expect(result.current.agents).toHaveLength(SEARCH_AGENTS_PAGE_SIZE));+ expect(result.current.hasMore).toBe(true);+ expect(searchAgents).toHaveBeenCalledWith({ query: undefined, limit: SEARCH_AGENTS_PAGE_SIZE, offset: 0 });++ const observers: IntersectionObserverCallback[] = [];+ vi.stubGlobal(+ 'IntersectionObserver',+ class {+ constructor(cb: IntersectionObserverCallback) {+ observers.push(cb);+ }+ observe() {+ return undefined;+ }+ disconnect() {+ return undefined;+ }+ unobserve() {+ return undefined;+ }+ takeRecords() {+ return [];+ }+ root = null;+ rootMargin = '';+ thresholds = [];+ },+ );++ act(() => {+ result.current.listRef(document.createElement('div'));+ result.current.sentinelRef(document.createElement('div'));+ });++ await waitFor(() => expect(observers.length).toBeGreaterThan(0));++ act(() => {+ observers[0]?.([{ isIntersecting: true } as IntersectionObserverEntry], {} as IntersectionObserver);+ });++ await waitFor(() => expect(result.current.agents).toHaveLength(SEARCH_AGENTS_PAGE_SIZE + 1));+ expect(searchAgents).toHaveBeenCalledWith({+ query: undefined,+ limit: SEARCH_AGENTS_PAGE_SIZE,+ offset: SEARCH_AGENTS_PAGE_SIZE,+ });+ expect(result.current.hasMore).toBe(false);+ });++ it('debounces query changes before re-fetching', async () => {+ vi.useFakeTimers();+ const searchAgents = vi.fn(async ({ query }: { query?: string } = {}) => [{ name: query ?? 'all' }]);+ const server = createMockAgentUIServer({ searchAgents });++ const { result, rerender } = renderHook(+ ({ query }: { query: string }) => useSearchAgentsList({ enabled: true, query }),+ { wrapper: wrapperFor(server), initialProps: { query: '' } },+ );++ await act(async () => {+ await Promise.resolve();+ });+ expect(searchAgents).toHaveBeenCalledTimes(1);++ rerender({ query: 'alpha' });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(299);+ });+ expect(searchAgents).toHaveBeenCalledTimes(1);++ await act(async () => {+ await vi.advanceTimersByTimeAsync(1);+ await Promise.resolve();+ });+ expect(searchAgents).toHaveBeenCalledTimes(2);+ expect(searchAgents).toHaveBeenLastCalledWith({ query: 'alpha', limit: SEARCH_AGENTS_PAGE_SIZE, offset: 0 });+ expect(result.current.agents).toEqual([{ name: 'alpha' } satisfies AgentLibraryEntry]);+ });+});diff --git a/packages/trueforge-ui-sdk/test/containers/ComposerContainer.test.tsx b/packages/trueforge-ui-sdk/test/containers/ComposerContainer.test.tsxindex c54ba4c00..9288b4f10 100644--- a/packages/trueforge-ui-sdk/test/containers/ComposerContainer.test.tsx+++ b/packages/trueforge-ui-sdk/test/containers/ComposerContainer.test.tsx@@ -1,7 +1,7 @@// @vitest-environment jsdomimport type { AppendMessage } from '@assistant-ui/react';import { fireEvent, render, screen, waitFor } from '@testing-library/react';-import { describe, expect, it, vi } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';import { ComposerContainer } from '@/containers/ComposerContainer.js';import { ComposerBusyProvider } from '@/hooks/useComposerBusyState.js';@@ -9,9 +9,14 @@ import { ShellModeProvider } from '@/server/ShellModeContext.js';import { SlotsProvider } from '@/theme/SlotsProvider.js';import { RuntimeHarness } from './RuntimeHarness.js';+const agentSpecState: { agentSpec: { model: { name: string } } | undefined } = {+ agentSpec: { model: { name: 'test/model' } },+};+vi.mock('@truefoundry/assistant-ui-runtime', () => ({useTrueFoundryCancel: () => vi.fn(),useTrueFoundryToolResponses: () => ({ pending: [] }),+ useTrueFoundryAgentSpec: () => ({ agentSpec: agentSpecState.agentSpec }),}));function renderComposer(onNew?: (message: AppendMessage) => Promise<void>) {@@ -25,6 +30,9 @@ function renderComposer(onNew?: (message: AppendMessage) => Promise<void>) {}describe('ComposerContainer', () => {+ beforeEach(() => {+ agentSpecState.agentSpec = { model: { name: 'test/model' } };+ });it('wraps the composer in an attachment dropzone by default', () => {renderComposer();const dropzone = document.querySelector('[data-slot="aui_composer-attachment-dropzone"]');@@ -70,6 +78,43 @@ describe('ComposerContainer', () => {expect(onNew).toHaveBeenCalledTimes(1);});+ it('disables send when no model is selected in mutable draft', async () => {+ agentSpecState.agentSpec = { model: { name: '' } };+ const onNew = vi.fn(async () => {});+ // No ShellModeProvider → treated as requiring a client-side model (draft path).+ renderComposer(onNew);+ const input = screen.getByRole<HTMLTextAreaElement>('textbox', { name: 'Message input' });++ fireEvent.change(input, { target: { value: 'hi' } });+ expect(screen.getByRole('button', { name: 'Send message' })).toBeDisabled();++ fireEvent.keyDown(input, { key: 'Enter' });+ await waitFor(() => expect(input.value).toBe('hi'));+ expect(onNew).not.toHaveBeenCalled();+ });++ it('allows send on named agents without a client-side model', async () => {+ agentSpecState.agentSpec = undefined;+ const onNew = vi.fn(async () => {});+ render(+ <ShellModeProvider agentConfig={{ mode: 'SingleAgent', name: 'support' }}>+ <RuntimeHarness messages={[]} onNew={onNew}>+ <ComposerBusyProvider>+ <ComposerContainer />+ </ComposerBusyProvider>+ </RuntimeHarness>+ </ShellModeProvider>,+ );+ const input = screen.getByRole<HTMLTextAreaElement>('textbox', { name: 'Message input' });++ fireEvent.change(input, { target: { value: 'hi' } });+ expect(screen.getByRole('button', { name: 'Send message' })).toBeEnabled();++ fireEvent.keyDown(input, { key: 'Enter' });+ await waitFor(() => expect(input.value).toBe(''));+ expect(onNew).toHaveBeenCalledTimes(1);+ });+it('preserves consumer section overrides in draft mode', () => {render(<SlotsProviderdiff --git a/packages/trueforge-ui-sdk/test/containers/Thread.test.tsx b/packages/trueforge-ui-sdk/test/containers/Thread.test.tsxindex 2731028af..ebdd01907 100644--- a/packages/trueforge-ui-sdk/test/containers/Thread.test.tsx+++ b/packages/trueforge-ui-sdk/test/containers/Thread.test.tsx@@ -10,6 +10,7 @@ import { RuntimeHarness } from './RuntimeHarness.js';vi.mock('@truefoundry/assistant-ui-runtime', () => ({useTrueFoundryCancel: () => vi.fn(),useTrueFoundryToolResponses: () => ({ pending: [] }),+ useTrueFoundryAgentSpec: () => ({ agentSpec: { model: { name: 'test/model' } } }),}));function WelcomeOverride({ heading }: WelcomeScreenProps) {diff --git a/packages/trueforge-ui-sdk/test/containers/TrueFoundryChatProvider.test.tsx b/packages/trueforge-ui-sdk/test/containers/TrueFoundryChatProvider.test.tsxindex 6b719cfe4..afb1e588b 100644--- a/packages/trueforge-ui-sdk/test/containers/TrueFoundryChatProvider.test.tsx+++ b/packages/trueforge-ui-sdk/test/containers/TrueFoundryChatProvider.test.tsx@@ -49,10 +49,17 @@ describe('TrueFoundryChatProvider', () => {server,agentName: 'my-agent',initialSessionId: 'session-123',- onError,adapters: { attachments: defaultAttachmentAdapter },}),);+ const forwardedOnError = runtimeSpy.mock.calls[0]?.[0]?.onError;+ expect(typeof forwardedOnError).toBe('function');+ expect(forwardedOnError).not.toBe(onError);++ act(() => {+ forwardedOnError?.(new Error('createSession failed'));+ });+ expect(onError).toHaveBeenCalledWith(expect.any(Error));});it('forwards a discriminated agent configuration', () => {diff --git a/packages/trueforge-ui-sdk/test/hooks/useComposerBusyState.test.ts b/packages/trueforge-ui-sdk/test/hooks/useComposerBusyState.test.tsindex b7b3140aa..8f723388e 100644--- a/packages/trueforge-ui-sdk/test/hooks/useComposerBusyState.test.ts+++ b/packages/trueforge-ui-sdk/test/hooks/useComposerBusyState.test.ts@@ -9,7 +9,7 @@ vi.mock('@assistant-ui/core/react', () => ({useThreadIsRunning: () => useThreadIsRunning(),}));-import { ComposerBusyProvider, useComposerBusyState } from '@/hooks/useComposerBusyState.js';+import { ComposerBusyProvider, notifyComposerBusyFailure, useComposerBusyState } from '@/hooks/useComposerBusyState.js';function wrapper({ children }: { children: ReactNode }) {return createElement(ComposerBusyProvider, null, children);@@ -98,6 +98,24 @@ describe('useComposerBusyState', () => {expect(result.current.isBusy).toBe(false);});+ it('clears submitting on notifyComposerBusyFailure when send never starts a run', () => {+ const { result } = renderHook(() => useComposerBusyState(), { wrapper });++ act(() => {+ // Matches aui.composer().send(): void return, rejection swallowed upstream.+ result.current.send(() => undefined);+ });+ expect(result.current.isBusy).toBe(true);+ expect(result.current.isSubmitting).toBe(true);++ act(() => {+ notifyComposerBusyFailure();+ });++ expect(result.current.isBusy).toBe(false);+ expect(result.current.isSubmitting).toBe(false);+ });+it('requires ComposerBusyProvider', () => {expect(() => renderHook(() => useComposerBusyState())).toThrow('useComposerBusyState must be used within ComposerBusyProvider',diff --git a/packages/trueforge-ui-sdk/test/server/ShellModeContext.test.tsx b/packages/trueforge-ui-sdk/test/server/ShellModeContext.test.tsxindex 279f3353b..22a7cde1c 100644--- a/packages/trueforge-ui-sdk/test/server/ShellModeContext.test.tsx+++ b/packages/trueforge-ui-sdk/test/server/ShellModeContext.test.tsx@@ -5,9 +5,13 @@ import { describe, expect, it } from 'vitest';import { ShellModeProvider, useOptionalShellMode, useShellMode, type AgentConfig } from '@/server/ShellModeContext.js';-function wrap(agentConfig?: AgentConfig) {+function wrap(agentConfig?: AgentConfig, initialSettingsOpen?: boolean) {return function Wrapper({ children }: { children: ReactNode }) {- return <ShellModeProvider agentConfig={agentConfig}>{children}</ShellModeProvider>;+ return (+ <ShellModeProvider agentConfig={agentConfig} initialSettingsOpen={initialSettingsOpen}>+ {children}+ </ShellModeProvider>+ );};}@@ -22,6 +26,16 @@ describe('ShellModeProvider', () => {expect(result.current).toBeNull();});+ it('opens settings on first paint when initialSettingsOpen is true', () => {+ const { result } = renderHook(() => useShellMode(), { wrapper: wrap(undefined, true) });+ expect(result.current.settingsOpen).toBe(true);++ act(() => result.current.setSettingsOpen(false));+ expect(result.current.settingsOpen).toBe(false);+ act(() => result.current.openDraft());+ expect(result.current.settingsOpen).toBe(false);+ });+it('defaults to AgentLibraryWithComposer (mutable + library)', () => {const { result } = renderHook(() => useShellMode(), { wrapper: wrap() });expect(result.current.mode).toMatchObject({ status: 'active', isMutable: true, locked: false });diff --git a/packages/trueforge-ui-sdk/tsup.config.ts b/packages/trueforge-ui-sdk/tsup.config.tsindex 0b7e9f528..be7ecfa60 100644--- a/packages/trueforge-ui-sdk/tsup.config.ts+++ b/packages/trueforge-ui-sdk/tsup.config.ts@@ -11,7 +11,8 @@ export default defineConfig({format: ['esm'],dts: true,sourcemap: true,- clean: true,+ // Watch mode must not wipe dist/styles.css (built by a sibling tailwind watcher).+ clean: !process.argv.includes('--watch'),target: 'es2022',esbuildPlugins: [svgr({