The open-source agent harness - the runtime layer that turns an LLM into a working agent.
feat: enhance agent capabilities and UI components (#221)
Vinitd202bb4a8f39
diff --git a/packages/trueforge-ui-sdk/example/yarn.lock b/packages/trueforge-ui-sdk/example/yarn.lockindex 323841010..f7f5903b9 100644--- a/packages/trueforge-ui-sdk/example/yarn.lock+++ b/packages/trueforge-ui-sdk/example/yarn.lock@@ -1425,10 +1425,10 @@"@tailwindcss/oxide" "4.3.3"tailwindcss "4.3.3"-"@truefoundry/[email protected]":- version "0.1.13"- resolved "https://registry.yarnpkg.com/@truefoundry/assistant-ui-runtime/-/assistant-ui-runtime-0.1.13.tgz#64191bf904a31c5a32f45c3314ebe86117f2e57a"- integrity sha512-pmY4Fvm5tZmX+uhsr3RegTeY3yYrdQdqaqYV5QzPZyrOPloboVPO07jbcZ2/D7S33622Ug0drhKGvWHpYTMTDw==+"@truefoundry/[email protected]":+ version "0.1.14"+ resolved "https://registry.yarnpkg.com/@truefoundry/assistant-ui-runtime/-/assistant-ui-runtime-0.1.14.tgz#c77b2f41ae260b965c16d72dc1b9f73ddde66813"+ integrity sha512-xdFob3v6KdhUVFrDuw1OAcX6o8lsnT+kQAo82gzCgXbg3YvdIs4cDWRswZdCI83FriRieYtMc8kZPjrRysJSkQ==dependencies:"@assistant-ui/core" "^0.2.22""@assistant-ui/store" "^0.2.21"@@ -2859,6 +2859,11 @@ parse5@^7.0.0:dependencies:entities "^6.0.0"+partial-json@^0.1.7:+ version "0.1.7"+ resolved "https://registry.yarnpkg.com/partial-json/-/partial-json-0.1.7.tgz#b735a89edb3e25f231a3c4caeaae71dc9f578605"+ integrity sha512-Njv/59hHaokb/hRUjce3Hdv12wd60MtM9Z5Olmn+nehe0QDAsRtRbJPvJ0Z91TusF0SuZRIvnM+S4l6EIP8leA==+picocolors@^1.1.1:version "1.1.1"resolved "https://registry.yarnpkg.com/picocolors/-/picocolors-1.1.1.tgz#3d321af3eab939b083c8f929a1d12cda81c26b6b"diff --git a/packages/trueforge-ui-sdk/src/atoms/NamedAgentHeaderLabel.tsx b/packages/trueforge-ui-sdk/src/atoms/NamedAgentHeaderLabel.tsxindex 1266905b4..4b297fd47 100644--- a/packages/trueforge-ui-sdk/src/atoms/NamedAgentHeaderLabel.tsx+++ b/packages/trueforge-ui-sdk/src/atoms/NamedAgentHeaderLabel.tsx@@ -1,26 +1,27 @@'use client';-import { useNamedAgentHeaderVisible } from '../hooks/useChatChromeActionsVisible.js';+import { useNamedAgentHeaderState } from '../hooks/useChatChromeActionsVisible.js';import { Icon } from '../icons/Icon.js';-import { useOptionalShellMode } from '../server/ShellModeContext.js';import { cn } from './lib/cn.js';-/** Left-of-header title for an immutable (named) agent chat. Hidden for idle / draft. */+/** Left-of-header title for a named agent, including its mutable edit state. */export function NamedAgentHeaderLabel({ className }: { className?: string }) {- const shell = useOptionalShellMode();- const visible = useNamedAgentHeaderVisible();- if (!visible || shell == null || shell.mode.status !== 'active') return null;-- const name = shell.mode.agentName ?? shell.mode.agentId;- if (name == null || name.length === 0) return null;+ const state = useNamedAgentHeaderState();+ if (state === null) return null;return (<h1className={cn('flex min-w-0 items-center gap-1.5 px-1 text-sm font-medium text-text-primary', className)}- title={name}+ title={state.name}><Icon name="robot" className="size-3.5 shrink-0" />- <span className="truncate">{name}</span>+ <span className="truncate">{state.name}</span>+ {state.isEditing ? (+ <span className="bg-secondary-bg text-text-secondary inline-flex shrink-0 items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium">+ <Icon name="pencil" className="size-3" />+ Editing+ </span>+ ) : null}</h1>);}diff --git a/packages/trueforge-ui-sdk/src/atoms/SaveAgentButton.tsx b/packages/trueforge-ui-sdk/src/atoms/SaveAgentButton.tsxindex 61ca6ad0d..bd4ba7c07 100644--- a/packages/trueforge-ui-sdk/src/atoms/SaveAgentButton.tsx+++ b/packages/trueforge-ui-sdk/src/atoms/SaveAgentButton.tsx@@ -1,154 +1,450 @@'use client';-import { useTrueFoundryAgentSpec } from '@truefoundry/assistant-ui-runtime';-import { useId, useState, type FormEvent } from 'react';-+import {+ useTrueFoundryAdoptAgentSpec,+ useTrueFoundryAgentSpec,+ useTrueFoundryFlushAgentSpec,+} from '@truefoundry/assistant-ui-runtime';+import { useId, useMemo, useRef, useState } from 'react';import { useSaveAgentVisible } from '../hooks/useChatChromeActionsVisible.js';-import { useOptionalServer } from '../server/ServerContext.js';+import { Icon } from '../icons/Icon.js';+import { useOptionalServer, useServerCapabilities } from '../server/ServerContext.js';import { useOptionalShellMode } from '../server/ShellModeContext.js';import type { AgentSpec } from '../server/types.js';import { getErrorMessage } from '../utils/getErrorMessage.js';+import { readAgentCapabilities, withAgentCapabilities } from './draft/agentCapabilities.js';+import { DraftCapabilitiesPanel } from './draft/DraftCapabilitiesPanel.js';+import { DraftCatalogProvider, useDraftCatalog } from './draft/DraftCatalogProvider.js';+import { CatalogRow, ConnectorConnectButton, isUnauthenticatedDcrConnector } from './draft/DraftCompositeSelector.js';+import { displayModelLabel, DraftModelCatalogPanel } from './draft/DraftModelCatalogPanel.js';+import { modelPatchWithReasoningEffort } from './draft/reasoningEffort.js';import { auiButtonClass } from './lib/buttonClasses.js';import { auiInputClass } from './lib/inputClasses.js';import { CenteredModal } from './primitives/CenteredModal.js';-const inputClassName = auiInputClass('disabled:opacity-50');+type SaveIntent = 'create' | 'update';+type Editor = 'model' | 'mcp' | 'skills';+type EditableMount = { id: string; name: string; value: object };++function editableMountsFromSpec(value: unknown): EditableMount[] {+ if (!Array.isArray(value)) return [];+ const mounts: EditableMount[] = [];+ for (const item of value) {+ if (typeof item !== 'object' || item === null) continue;+ const name = Reflect.get(item, 'name');+ if (typeof name !== 'string') continue;+ const id = Reflect.get(item, 'id');+ mounts.push({ id: typeof id === 'string' ? id : name, name, value: item });+ }+ return mounts;+}++function SummarySection({+ icon,+ title,+ value,+ onEdit,+ disabled,+}: {+ icon: string;+ title: string;+ value: string;+ onEdit: () => void;+ disabled: boolean;+}) {+ return (+ <div className="flex items-center gap-3 border-b border-border px-5 py-3.5 last:border-b-0">+ <Icon name={icon} className="text-text-secondary size-4 shrink-0" />+ <div className="min-w-0 flex-1">+ <p className="text-text-primary text-sm font-medium">{title}</p>+ <p className="text-text-secondary mt-0.5 truncate text-xs">{value}</p>+ </div>+ <button+ type="button"+ aria-label={`Edit ${title}`}+ disabled={disabled}+ className={auiButtonClass({ variant: 'ghost', size: 'icon', className: 'size-8' })}+ onClick={onEdit}+ >+ <Icon name="pencil" className="size-3.5" />+ </button>+ </div>+ );+}++export type SaveAgentButtonProps = {+ disabled?: boolean;+ className?: string;+ children?: string;+};-export function SaveAgentButton() {+export function SaveAgentButton({ disabled = false, className, children = 'Save Agent' }: SaveAgentButtonProps) {+ return (+ <DraftCatalogProvider>+ <SaveAgentButtonContent disabled={disabled} className={className}>+ {children}+ </SaveAgentButtonContent>+ </DraftCatalogProvider>+ );+}++function SaveAgentButtonContent({+ disabled,+ className,+ children,+}: {+ disabled: boolean;+ className?: string;+ children: string;+}) {+ const { agentSpec, draftSessionId } = useTrueFoundryAgentSpec();+ const agentSpecRef = useRef(agentSpec);+ agentSpecRef.current = agentSpec;+ const flushAgentSpec = useTrueFoundryFlushAgentSpec();+ const adoptAgentSpec = useTrueFoundryAdoptAgentSpec();+ const builder = useOptionalServer();const shell = useOptionalShellMode();- const server = useOptionalServer();- const { agentSpec } = useTrueFoundryAgentSpec();+ const catalog = useDraftCatalog();+ const serverCapabilities = useServerCapabilities();+ const modelListId = useId();const visible = useSaveAgentVisible();const [open, setOpen] = useState(false);+ const [editor, setEditor] = useState<Editor | null>(null);+ const [intent, setIntent] = useState<SaveIntent>('create');const [name, setName] = useState('');- const [instructions, setInstructions] = useState('');+ const [draftSpec, setDraftSpec] = useState<AgentSpec | null>(null);+ const [modelQuery, setModelQuery] = useState('');+ const [search, setSearch] = useState('');const [saving, setSaving] = useState(false);const [error, setError] = useState<string | null>(null);- const nameId = useId();- const instructionsId = useId();-- if (!visible || shell?.mode.status !== 'active' || !shell.mode.isMutable || server == null) return null;- const editingAgentName = shell.mode.agentName ?? shell.mode.agentId;- const isUpdate = editingAgentName != null && editingAgentName !== '';- const draftSpec = shell.mode.agentSpec ?? { model: { name: 'openai-main/gpt-4.1' } };- // Runtime AgentSpec is structurally compatible; cast across package boundary.- const specToSave: AgentSpec = (agentSpec as AgentSpec | undefined) ?? draftSpec;+ const mcpMounts = useMemo(() => editableMountsFromSpec(draftSpec?.mcpServers), [draftSpec?.mcpServers]);+ const skillMounts = useMemo(() => editableMountsFromSpec(draftSpec?.skills), [draftSpec?.skills]);- const reset = () => {- setName('');- setInstructions('');+ const close = () => {+ if (saving) return;+ setEditor(null);+ setOpen(false);+ setDraftSpec(null);setError(null);- setSaving(false);};- const handleOpenChange = (next: boolean) => {- if (next) {- setName(editingAgentName ?? '');- setInstructions(specToSave.instructions ?? draftSpec.instructions ?? '');- } else {- reset();- }- setOpen(next);+ const show = async () => {+ if (agentSpecRef.current === null || builder === null) return;+ setError(null);+ catalog.ensureLoaded();+ await flushAgentSpec();+ const latestAgentSpec = agentSpecRef.current;+ if (latestAgentSpec === null) return;+ const currentName = shell?.mode.status === 'active' ? (shell.mode.agentName ?? shell.mode.agentId ?? '') : '';+ setIntent(currentName ? 'update' : 'create');+ setName(currentName);+ setDraftSpec({+ ...latestAgentSpec,+ model: {+ ...latestAgentSpec.model,+ params: latestAgentSpec.model.params ? { ...latestAgentSpec.model.params } : undefined,+ },+ mcpServers: latestAgentSpec.mcpServers?.map(item => ({ ...item })),+ skills: latestAgentSpec.skills?.map(item => ({ ...item })),+ config: latestAgentSpec.config ? { ...latestAgentSpec.config } : undefined,+ });+ setOpen(true);};- const handleSubmit = async (event: FormEvent) => {- event.preventDefault();- const agentName = name.trim();- if (!agentName || saving) return;-+ const save = async () => {+ if (builder === null || draftSpec === null) return;+ const normalizedName = name.trim();+ if (!normalizedName || !draftSpec.model.name.trim()) return;setSaving(true);setError(null);- const trimmedInstructions = instructions.trim();- const savedSpec: AgentSpec = {- ...specToSave,- instructions: trimmedInstructions || undefined,- };try {- await server.saveAgent({- agentName,- agentSpec: savedSpec,- intent: isUpdate ? 'update' : 'create',+ const result = await builder.saveAgent({+ agentName: normalizedName,+ agentSpec: draftSpec,+ intent,+ sessionId: draftSessionId,});- // Same draft chat continues as editable agent — do not remount via selectLibraryAgent.- shell.bindMutableAgent({- agentId: agentName,- agentName,- agentSpec: savedSpec,+ adoptAgentSpec({ agentSpec: draftSpec, updatedAt: result.sessionUpdatedAt });+ shell?.bindMutableAgent({+ agentId: result.agentId ?? normalizedName,+ agentName: normalizedName,+ agentSpec: draftSpec,});- shell.invalidateAgentsList();- handleOpenChange(false);- } catch (err: unknown) {- setError(getErrorMessage(err, isUpdate ? 'Failed to update agent.' : 'Failed to save agent.'));+ shell?.invalidateAgentsList();+ setOpen(false);+ setDraftSpec(null);+ setEditor(null);+ } catch (caught) {+ setError(getErrorMessage(caught, 'Could not save agent'));+ } finally {setSaving(false);}};- const triggerLabel = isUpdate ? 'Update Agent' : 'Save agent';- const modalTitle = isUpdate ? 'Update Agent' : 'Save agent';- const modalDescription = isUpdate- ? 'Save changes to this agent in the Agents library'- : 'Reuse this setup later from the Agents library';- const submitLabel = saving ? (isUpdate ? 'Updating…' : 'Saving…') : isUpdate ? 'Update' : 'Save';+ const filteredConnectors = catalog.connectors.filter(item =>+ `${item.name} ${item.description ?? ''}`.toLowerCase().includes(search.trim().toLowerCase()),+ );+ const filteredSkills = catalog.skills.filter(item =>+ `${item.name} ${item.description ?? ''}`.toLowerCase().includes(search.trim().toLowerCase()),+ );+ const isUpdateMode =+ shell?.mode.status === 'active' &&+ shell.mode.isMutable &&+ (shell.mode.agentName !== undefined || shell.mode.agentId !== undefined);+ const triggerLabel = isUpdateMode && children === 'Save Agent' ? 'Update Agent' : children;++ if (!visible) return null;return (<><buttontype="button"- className={auiButtonClass({ variant: 'outline', size: 'sm' })}- onClick={() => handleOpenChange(true)}+ disabled={disabled || builder === null || agentSpec === null}+ className={auiButtonClass({ variant: 'outline', size: 'sm', className })}+ onClick={() => void show()}>{triggerLabel}</button><CenteredModalopen={open}- onOpenChange={handleOpenChange}- title={modalTitle}- description={modalDescription}- contentSized+ onOpenChange={next => !next && close()}+ title={intent === 'create' ? 'Save agent' : 'Update agent'}+ description="Review the configuration before saving."+ className="md:max-w-lg"+ aria-label={intent === 'create' ? 'Save agent' : 'Update agent'}>- <form className="flex flex-col gap-4 p-5" onSubmit={e => void handleSubmit(e)}>- <div className="flex flex-col gap-1.5">- <label htmlFor={nameId} className="text-text-primary text-sm font-medium">- Name- </label>- <input- id={nameId}- type="text"- value={name}- onChange={e => setName(e.target.value)}- placeholder="release-notes-writer"- autoFocus={!isUpdate}- autoComplete="off"- disabled={saving || isUpdate}- className={`${inputClassName} h-9`}- />+ {draftSpec ? (+ <div className="flex min-h-0 w-[min(32rem,calc(100vw-2rem))] flex-1 flex-col">+ <div className="min-h-0 flex-1 overflow-y-auto px-5 py-4">+ <label className="mb-4 block">+ <span className="mb-1.5 block text-sm font-medium">Agent name</span>+ <input+ value={name}+ disabled={saving || intent === 'update'}+ onChange={event => setName(event.target.value)}+ placeholder="my-agent"+ className={auiInputClass('h-9 disabled:opacity-60')}+ />+ </label>++ <label className="mb-4 block">+ <span className="mb-1.5 block text-sm font-medium">Instructions</span>+ <textarea+ value={draftSpec.instructions ?? ''}+ disabled={saving}+ onChange={event => setDraftSpec({ ...draftSpec, instructions: event.target.value })}+ rows={4}+ className={auiInputClass('resize-y py-2 disabled:opacity-60')}+ />+ </label>++ <div className="mb-4 overflow-hidden rounded-xl border border-border">+ <SummarySection+ icon="cpu"+ title="Model"+ value={draftSpec.model.name ? displayModelLabel(draftSpec.model.name) : 'Not selected'}+ disabled={saving}+ onEdit={() => setEditor('model')}+ />+ <SummarySection+ icon="plug"+ title="MCP servers"+ value={`${mcpMounts.length} selected`}+ disabled={saving}+ onEdit={() => setEditor('mcp')}+ />+ <SummarySection+ icon="lightbulb"+ title="Skills"+ value={`${skillMounts.length} selected`}+ disabled={saving}+ onEdit={() => setEditor('skills')}+ />+ </div>++ <div>+ <h3 className="mb-2 text-sm font-medium">Capabilities</h3>+ <DraftCapabilitiesPanel+ divided+ value={readAgentCapabilities(draftSpec.config)}+ disabled={saving}+ onChange={values =>+ setDraftSpec({+ ...draftSpec,+ config: withAgentCapabilities({ config: draftSpec.config, values }),+ })+ }+ />+ </div>++ {error ? (+ <p role="alert" className="text-failure-bg mt-3 text-sm">+ {error}+ </p>+ ) : null}+ </div>++ <div className="bg-card-bg sticky bottom-0 z-10 flex shrink-0 justify-end gap-2 border-t border-border px-5 py-4">+ <button+ type="button"+ disabled={saving}+ className={auiButtonClass({ variant: 'secondary' })}+ onClick={close}+ >+ Cancel+ </button>+ <button+ type="button"+ disabled={saving || !name.trim() || !draftSpec.model.name.trim()}+ className={auiButtonClass({ variant: 'default' })}+ onClick={() => void save()}+ >+ {saving ? 'Saving…' : 'Save changes'}+ </button>+ </div></div>- <div className="flex flex-col gap-1.5">- <label htmlFor={instructionsId} className="text-text-primary text-sm font-medium">- System instructions- </label>- <textarea- id={instructionsId}- value={instructions}- onChange={e => setInstructions(e.target.value)}- placeholder="You are a release notes writer for the platform team..."- rows={4}- autoFocus={isUpdate}- disabled={saving}- className={`${inputClassName} min-h-24 resize-y py-2`}- />+ ) : null}+ </CenteredModal>++ <CenteredModal+ open={editor !== null}+ onOpenChange={next => {+ if (!next) {+ setEditor(null);+ setSearch('');+ setModelQuery('');+ }+ }}+ title={editor === 'model' ? 'Select model' : editor === 'mcp' ? 'MCP servers' : 'Skills'}+ className="md:max-w-md"+ contentSized+ aria-label={editor === 'model' ? 'Edit model' : editor === 'mcp' ? 'Edit MCP servers' : 'Edit skills'}+ >+ {draftSpec && editor ? (+ <div className="flex h-[min(28rem,calc(100dvh-10rem))] w-[min(28rem,calc(100vw-2rem))] flex-col">+ {editor === 'model' ? (+ <>+ {catalog.error ? (+ <p role="alert" className="text-failure-bg px-3 pt-3 text-sm">+ {catalog.error}+ </p>+ ) : null}+ <DraftModelCatalogPanel+ models={catalog.models}+ loading={catalog.loading}+ selectedName={draftSpec.model.name}+ query={modelQuery}+ onQueryChange={setModelQuery}+ listboxId={modelListId}+ onSelect={nextModel => {+ setDraftSpec({+ ...draftSpec,+ model: modelPatchWithReasoningEffort(+ nextModel.name,+ draftSpec.model.params,+ nextModel.properties.reasoningEfforts,+ ),+ });+ setEditor(null);+ }}+ />+ </>+ ) : (+ <>+ {catalog.error ? (+ <p role="alert" className="text-failure-bg px-3 pt-3 text-sm">+ {catalog.error}+ </p>+ ) : null}+ <div className="border-b border-border p-3">+ <label className="relative block">+ <Icon+ name="search"+ className="text-text-secondary pointer-events-none absolute top-1/2 left-2 size-3.5 -translate-y-1/2"+ />+ <input+ value={search}+ onChange={event => setSearch(event.target.value)}+ placeholder={editor === 'mcp' ? 'Search MCP servers' : 'Search skills'}+ className={auiInputClass('h-8 pr-2 pl-7')}+ autoFocus+ />+ </label>+ </div>+ <div className="min-h-0 flex-1 overflow-y-auto p-2">+ {editor === 'mcp'+ ? filteredConnectors.map(connector => {+ const checked = mcpMounts.some(item => item.id === connector.id);+ const needsConnect = isUnauthenticatedDcrConnector(connector);+ return (+ <CatalogRow+ key={connector.id}+ title={connector.name}+ description={connector.description}+ checked={checked}+ disabled={!connector.authenticated && !checked}+ action={+ needsConnect ? (+ <ConnectorConnectButton connector={connector} onConnected={catalog.refreshConnectors} />+ ) : undefined+ }+ onToggle={() => {+ if (!connector.authenticated && !checked) return;+ const next = checked+ ? mcpMounts.filter(item => item.id !== connector.id)+ : [+ ...mcpMounts,+ {+ id: connector.id,+ name: connector.name,+ value: { id: connector.id, name: connector.name },+ },+ ];+ setDraftSpec({+ ...draftSpec,+ mcpServers: next.map(item => item.value),+ });+ }}+ />+ );+ })+ : filteredSkills.map(skill => {+ const checked = skillMounts.some(item => item.id === skill.id);+ const disabledSkill = serverCapabilities?.skill.enabled !== true;+ return (+ <CatalogRow+ key={skill.id}+ title={skill.name}+ description={skill.description}+ checked={checked}+ disabled={disabledSkill && !checked}+ onToggle={() => {+ if (disabledSkill && !checked) return;+ const next = checked+ ? skillMounts.filter(item => item.id !== skill.id)+ : [+ ...skillMounts,+ {+ id: skill.id,+ name: skill.name,+ value: { id: skill.id, name: skill.name },+ },+ ];+ setDraftSpec({+ ...draftSpec,+ skills: next.map(item => item.value),+ });+ }}+ />+ );+ })}+ </div>+ </>+ )}</div>- {error ? <p className="text-failure-bg text-sm">{error}</p> : null}- <button- type="submit"- disabled={saving || name.trim().length === 0}- className={auiButtonClass({ variant: 'default', className: 'w-full' })}- >- {submitLabel}- </button>- </form>+ ) : null}</CenteredModal></>);diff --git a/packages/trueforge-ui-sdk/src/atoms/draft/DraftCapabilitiesPanel.tsx b/packages/trueforge-ui-sdk/src/atoms/draft/DraftCapabilitiesPanel.tsxnew file mode 100644index 000000000..57364ebb2--- /dev/null+++ b/packages/trueforge-ui-sdk/src/atoms/draft/DraftCapabilitiesPanel.tsx@@ -0,0 +1,65 @@+'use client';++import { cn } from '../lib/cn.js';+import { Switch } from '../primitives/Switch.js';+import type { AgentCapabilityValues } from './agentCapabilities.js';++const CAPABILITIES: Array<{+ id: keyof AgentCapabilityValues;+ label: string;+ description: string;+}> = [+ {+ id: 'generativeUi',+ label: 'Generative UI',+ description: 'Let the agent render interactive UI in its replies.',+ },+ {+ id: 'dynamicSubAgents',+ label: 'Dynamic sub-agents',+ description: 'Let the agent spin up sub-agents for complex tasks.',+ },+ {+ id: 'askUserQuestions',+ label: 'Ask clarifying questions',+ description: 'Let the agent ask before acting when unsure.',+ },+];++export function DraftCapabilitiesPanel({+ value,+ onChange,+ disabled = false,+ divided = false,+}: {+ value: AgentCapabilityValues;+ onChange: (value: AgentCapabilityValues) => void;+ disabled?: boolean;+ divided?: boolean;+}) {+ return (+ <div className={cn('flex flex-col', divided && 'overflow-hidden rounded-xl border border-border')}>+ {CAPABILITIES.map((capability, index) => {+ const checked = value[capability.id];+ return (+ <div+ key={capability.id}+ className={cn('flex items-start gap-3 px-3 py-3', divided && index > 0 && 'border-t border-border')}+ >+ <div className="min-w-0 flex-1">+ <p className="text-text-primary text-sm font-medium">{capability.label}</p>+ <p className="text-text-secondary mt-0.5 text-xs leading-snug">{capability.description}</p>+ </div>+ <Switch+ checked={checked}+ aria-label={capability.label}+ disabled={disabled}+ className="mt-0.5"+ onCheckedChange={nextChecked => onChange({ ...value, [capability.id]: nextChecked })}+ />+ </div>+ );+ })}+ </div>+ );+}diff --git a/packages/trueforge-ui-sdk/src/atoms/draft/DraftCatalogProvider.tsx b/packages/trueforge-ui-sdk/src/atoms/draft/DraftCatalogProvider.tsxindex de8204008..f0fcfe30f 100644--- a/packages/trueforge-ui-sdk/src/atoms/draft/DraftCatalogProvider.tsx+++ b/packages/trueforge-ui-sdk/src/atoms/draft/DraftCatalogProvider.tsx@@ -3,7 +3,7 @@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';+import type { AgentSkill, AgentUIServer, ConnectorState, ModelSelection } from '../../server/types.js';import { getErrorMessage } from '../../utils/getErrorMessage.js';type DraftCatalogValue = {@@ -18,13 +18,25 @@ type DraftCatalogValue = {refreshConnectors: () => Promise<void>;};-const DraftCatalogContext = createContext<DraftCatalogValue | null>(null);+type DraftCatalogContextValue = DraftCatalogValue & {+ server: AgentUIServer | null;+};++const DraftCatalogContext = createContext<DraftCatalogContextValue | null>(null);const IDLE_ENSURE = () => undefined;const IDLE_REFRESH = async () => undefined;export function DraftCatalogProvider({ children }: { children: ReactNode }) {const server = useOptionalServer();+ const existing = useContext(DraftCatalogContext);+ if (existing?.server === server) {+ return children;+ }+ return <DraftCatalogStore server={server}>{children}</DraftCatalogStore>;+}++function DraftCatalogStore({ server, children }: { server: AgentUIServer | null; children: ReactNode }) {const [requested, setRequested] = useState(false);const [models, setModels] = useState<ModelSelection[]>([]);const [skills, setSkills] = useState<AgentSkill[]>([]);@@ -86,8 +98,8 @@ export function DraftCatalogProvider({ children }: { children: ReactNode }) {}, [requested, server]);const value = useMemo(- () => ({ models, skills, connectors, loading, error, ensureLoaded, refreshConnectors }),- [models, skills, connectors, loading, error, ensureLoaded, refreshConnectors],+ () => ({ server, models, skills, connectors, loading, error, ensureLoaded, refreshConnectors }),+ [server, models, skills, connectors, loading, error, ensureLoaded, refreshConnectors],);return <DraftCatalogContext.Provider value={value}>{children}</DraftCatalogContext.Provider>;diff --git a/packages/trueforge-ui-sdk/src/atoms/draft/DraftCompositeSelector.tsx b/packages/trueforge-ui-sdk/src/atoms/draft/DraftCompositeSelector.tsxindex 2d1c04867..4350a8f65 100644--- a/packages/trueforge-ui-sdk/src/atoms/draft/DraftCompositeSelector.tsx+++ b/packages/trueforge-ui-sdk/src/atoms/draft/DraftCompositeSelector.tsx@@ -13,17 +13,19 @@ import { useCompactLayout } from '../lib/CompactLayoutContext.js';import { useIsMobile } from '../lib/useIsMobile.js';import { BottomSheet } from '../primitives/BottomSheet.js';import { Tooltip } from '../primitives/Tooltip.js';+import { readAgentCapabilities, withAgentCapabilities } from './agentCapabilities.js';+import { DraftCapabilitiesPanel } from './DraftCapabilitiesPanel.js';import { useDraftCatalog } from './DraftCatalogProvider.js';/** Catalog-backed mount shape used by the draft picker (runtime mounts stay opaque). */-type DraftMount = { id: string; name: string };+export type DraftMount = { id: string; name: string };/*** Harness wire mounts are name-keyed (`{ name }` only). Catalog rows use* `id === name`, so missing ids hydrate from name — otherwise save/load drops* mounts from the picker and the next flush can wipe them from the spec.*/-function draftMountsFromSpec(value: unknown): DraftMount[] {+export function draftMountsFromSpec(value: unknown): DraftMount[] {if (!Array.isArray(value)) return [];const mounts: DraftMount[] = [];for (const item of value) {@@ -35,12 +37,12 @@ function draftMountsFromSpec(value: unknown): DraftMount[] {}return mounts;}-type AttachTab = 'connectors' | 'skills' | 'files';+type AttachTab = 'connectors' | 'skills' | 'capabilities';const TABS: { id: AttachTab; label: string; icon: string }[] = [{ id: 'connectors', label: 'Connectors', icon: 'plug' },{ id: 'skills', label: 'Skills', icon: 'lightbulb' },- { id: 'files', label: 'Attachment', icon: 'paperclip' },+ { id: 'capabilities', label: 'Capabilities', icon: 'wrench' },];const SPEC_FLUSH_MS = 300;@@ -61,7 +63,7 @@ function Checkbox({ checked }: { checked: boolean }) {);}-function CatalogRow({+export function CatalogRow({title,description,checked,@@ -124,7 +126,7 @@ function CatalogRow({);}-function isUnauthenticatedDcrConnector(connector: ConnectorState): boolean {+export function isUnauthenticatedDcrConnector(connector: ConnectorState): boolean {const auth = Reflect.get(connector, 'auth');return (connector.authenticated === false &&@@ -134,7 +136,7 @@ function isUnauthenticatedDcrConnector(connector: ConnectorState): boolean {);}-function ConnectorConnectButton({+export function ConnectorConnectButton({connector,onConnected,}: {@@ -239,6 +241,8 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftCconst 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 hasValidModel = Boolean(agentSpec?.model?.name.trim());+ const toolsCount = selectedMcp.length + selectedSkills.length;const clearFlushTimer = useCallback(() => {if (flushTimerRef.current != null) {@@ -277,15 +281,27 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftCif (open) ensureLoaded();}, [open, ensureLoaded]);+ useEffect(() => {+ if (open && !hasValidModel) {+ setOpenAndFlush(false);+ }+ }, [hasValidModel, open, setOpenAndFlush]);+useEffect(() => {if (!open) return;- const handler = (e: MouseEvent) => {+ // Flush on pointer or keyboard focus leaving the picker so Save Agent (and+ // other outside actions) see the latest local connector/skill toggles.+ const handler = (e: Event) => {if (containerRef.current && !containerRef.current.contains(e.target as Node)) {setOpenAndFlush(false);}};document.addEventListener('mousedown', handler);- return () => document.removeEventListener('mousedown', handler);+ document.addEventListener('focusin', handler);+ return () => {+ document.removeEventListener('mousedown', handler);+ document.removeEventListener('focusin', handler);+ };}, [open, setOpenAndFlush]);useEffect(() => () => clearFlushTimer(), [clearFlushTimer]);@@ -391,24 +407,27 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftC})}</div>- {tab === 'files' ? (- <button- type="button"- disabled={disabled}- onClick={() => {- onAttach?.();- 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',- 'text-center outline-none transition-colors hover:bg-ghost-button-hover',- 'disabled:cursor-not-allowed disabled:opacity-50',- )}- >- <Icon name="paperclip" className="text-primary-button-bg size-6" />- <span className="text-sm font-medium">Add files or photos</span>- <span className="text-text-secondary text-xs">Upto 5 attachments | 10 MB each</span>- </button>+ {tab === 'capabilities' ? (+ <div className="min-h-0 flex-1 overflow-y-auto p-2">+ <DraftCapabilitiesPanel+ value={readAgentCapabilities(agentSpec?.config)}+ disabled={disabled || isRunning}+ onChange={values => {+ // Capability writes bypass the mount debounce. Fold in any dirty+ // local mounts in the same update so a pending connector/skill+ // toggle is not overwritten by a config-only sync.+ clearFlushTimer();+ const includeLocalMounts = dirtyRef.current;+ if (includeLocalMounts) {+ dirtyRef.current = false;+ }+ updateAgentSpec?.({+ ...(includeLocalMounts ? { mcpServers: localMcpRef.current, skills: localSkillsRef.current } : {}),+ config: withAgentCapabilities({ config: agentSpec?.config, values }),+ });+ }}+ />+ </div>) : (<><SearchField@@ -509,33 +528,50 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftCreturn (<div ref={containerRef} className="relative flex flex-wrap items-center gap-1.5">- <button- type="button"- disabled={disabled || isRunning}- aria-label="Add connectors, skills, or attachments"- aria-haspopup="dialog"- aria-expanded={open}- aria-controls={open ? menuId : undefined}- className={auiButtonClass({ variant: 'ghost', size: 'icon' })}- onClick={() => {- if (open) {- setOpenAndFlush(false);- return;- }- openPicker();- }}- >- <Icon name="plus" className="text-primary-button-bg" />- </button>+ {hasValidModel ? (+ <button+ type="button"+ disabled={disabled || isRunning}+ aria-label={`Tools (${toolsCount})`}+ aria-haspopup="dialog"+ aria-expanded={open}+ aria-controls={open ? menuId : undefined}+ className={auiButtonClass({+ variant: 'ghost',+ size: 'sm',+ className: 'h-8 gap-1.5 rounded-md px-2 text-xs',+ })}+ onClick={() => {+ if (open) {+ setOpenAndFlush(false);+ return;+ }+ openPicker();+ }}+ >+ <Icon name="wrench" className="size-3.5" />+ <span>Tools</span>+ <span className="bg-primary-button-bg/10 text-primary-button-bg rounded px-1.5 py-0.5 text-[10px] font-semibold">+ {toolsCount}+ </span>+ </button>+ ) : null}- <DraftSelectionChips- disabled={disabled || isRunning}- onOpenTab={tabId => {- openPicker(tabId);- }}- />+ {onAttach ? (+ <Tooltip content="Attach a file">+ <button+ type="button"+ disabled={disabled || isRunning}+ aria-label="Attach a file"+ className={auiButtonClass({ variant: 'ghost', size: 'icon' })}+ onClick={onAttach}+ >+ <Icon name="paperclip" />+ </button>+ </Tooltip>+ ) : null}- {open ? (+ {open && hasValidModel ? (isMobile || compactLayout ? (<BottomSheet id={menuId} open onOpenChange={setOpenAndFlush} aria-label="Add to composer">{content}@@ -555,70 +591,6 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftC);}-export type DraftSelectionChipsProps = {- disabled?: boolean;- onOpenTab?: (tab: 'connectors' | 'skills') => void;-};--function SelectionChipTooltipList({ mounts }: { mounts: DraftMount[] }) {- return (- <ul className="m-0 flex max-w-48 list-none flex-col gap-0.5 p-0 text-left">- {mounts.map(mount => (- <li key={mount.id} className="truncate" title={mount.name}>- {mount.name}- </li>- ))}- </ul>- );-}--export function DraftSelectionChips({ disabled, onOpenTab }: DraftSelectionChipsProps = {}) {- const { agentSpec } = useTrueFoundryAgentSpec();- const mcpMounts = useMemo(() => draftMountsFromSpec(agentSpec?.mcpServers), [agentSpec?.mcpServers]);- const skillMounts = useMemo(() => draftMountsFromSpec(agentSpec?.skills), [agentSpec?.skills]);-- if (mcpMounts.length === 0 && skillMounts.length === 0) return null;-- const chipClassName = cn(- 'bg-secondary-bg text-text-secondary inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs outline-none',- 'focus-visible:ring-1 focus-visible:ring-focus-ring',- disabled ? 'cursor-not-allowed opacity-50' : 'hover:bg-ghost-button-hover cursor-pointer',- );-- return (- <div className="flex flex-wrap items-center gap-1.5">- {mcpMounts.length > 0 ? (- <Tooltip content={<SelectionChipTooltipList mounts={mcpMounts} />} className="max-w-48 whitespace-normal">- <button- type="button"- disabled={disabled}- aria-label={`View ${mcpMounts.length} selected connector${mcpMounts.length === 1 ? '' : 's'}`}- className={chipClassName}- onClick={() => onOpenTab?.('connectors')}- >- <Icon name="plug" className="size-3" />- {mcpMounts.length} Connector{mcpMounts.length === 1 ? '' : 's'}- </button>- </Tooltip>- ) : null}- {skillMounts.length > 0 ? (- <Tooltip content={<SelectionChipTooltipList mounts={skillMounts} />} className="max-w-48 whitespace-normal">- <button- type="button"- disabled={disabled}- aria-label={`View ${skillMounts.length} selected skill${skillMounts.length === 1 ? '' : 's'}`}- className={chipClassName}- onClick={() => onOpenTab?.('skills')}- >- <Icon name="lightbulb" className="size-3" />- {skillMounts.length} Skill{skillMounts.length === 1 ? '' : 's'}- </button>- </Tooltip>- ) : null}- </div>- );-}-declare module '../../theme/SlotsProvider.js' {interface AtomSlots {DraftCompositeSelector: typeof DraftCompositeSelector;diff --git a/packages/trueforge-ui-sdk/src/atoms/draft/DraftModelCatalogPanel.tsx b/packages/trueforge-ui-sdk/src/atoms/draft/DraftModelCatalogPanel.tsxnew file mode 100644index 000000000..2fea8e9ca--- /dev/null+++ b/packages/trueforge-ui-sdk/src/atoms/draft/DraftModelCatalogPanel.tsx@@ -0,0 +1,173 @@+'use client';++import { Icon } from '../../icons/Icon.js';+import type { ModelSelection } from '../../server/types.js';+import { auiButtonClass } from '../lib/buttonClasses.js';+import { cn } from '../lib/cn.js';+import { auiInputClass } from '../lib/inputClasses.js';+import { CatalogLogo } from '../primitives/CatalogLogo.js';++function monogram(value: string): string {+ const trimmed = value.trim();+ return trimmed ? trimmed.charAt(0).toUpperCase() : '?';+}++export function displayModelLabel(modelName: string): string {+ const slash = modelName.lastIndexOf('/');+ return slash >= 0 ? modelName.slice(slash + 1) : modelName;+}++export function ProviderMark({ logo, label, className }: { logo?: string; label: string; className?: string }) {+ if (logo) {+ return <CatalogLogo src={logo} alt="" className={cn('shrink-0 rounded object-contain', className)} aria-hidden />;+ }+ return (+ <span+ className={cn(+ 'bg-secondary-bg text-text-secondary flex shrink-0 items-center justify-center rounded font-semibold',+ className,+ )}+ aria-hidden+ >+ {monogram(label)}+ </span>+ );+}++type ProviderSection = { name: string; logo?: string; models: ModelSelection[] };++function groupModelsByProvider(models: ModelSelection[]): ProviderSection[] {+ const sections: ProviderSection[] = [];+ const byProvider = new Map<string, ProviderSection>();+ for (const model of models) {+ const name = model.provider.name.trim() || 'Other';+ const existing = byProvider.get(name);+ if (existing) {+ existing.models.push(model);+ if (!existing.logo && model.provider.logo) existing.logo = model.provider.logo;+ } else {+ const section: ProviderSection = { name, logo: model.provider.logo, models: [model] };+ byProvider.set(name, section);+ sections.push(section);+ }+ }+ return sections;+}++export function DraftModelCatalogPanel({+ models,+ loading,+ selectedName,+ query,+ onQueryChange,+ onSelect,+ onOpenSettings,+ listboxId,+}: {+ models: ModelSelection[];+ loading: boolean;+ selectedName: string;+ query: string;+ onQueryChange: (query: string) => void;+ onSelect: (model: ModelSelection) => void;+ onOpenSettings?: () => void;+ listboxId: string;+}) {+ const needle = query.trim().toLowerCase();+ const filtered = needle+ ? models.filter(+ model =>+ model.name.toLowerCase().includes(needle) ||+ model.id.toLowerCase().includes(needle) ||+ model.provider.name.toLowerCase().includes(needle),+ )+ : models;+ const sections = groupModelsByProvider(filtered);++ return (+ <>+ <div className="border-b border-border px-3 py-2">+ <p className="text-text-primary mb-2 text-sm font-semibold">Select model</p>+ <label className="relative block">+ <Icon+ name="search"+ className="text-text-secondary pointer-events-none absolute top-1/2 left-2 size-3.5 -translate-y-1/2"+ />+ <input+ type="search"+ value={query}+ onChange={event => onQueryChange(event.target.value)}+ placeholder="Search"+ className={auiInputClass('h-8 py-1 pr-2 pl-7')}+ autoFocus+ />+ </label>+ </div>+ <div+ id={listboxId}+ role="listbox"+ aria-label="Select model"+ className="flex min-h-0 flex-1 flex-col overflow-y-auto p-1"+ >+ {filtered.length === 0 ? (+ !loading && onOpenSettings ? (+ <button+ type="button"+ className={auiButtonClass({+ variant: 'ghost',+ className: 'text-text-secondary w-full justify-center py-4 text-sm',+ })}+ onClick={onOpenSettings}+ >+ Please configure Models in the <span className="underline">settings</span>+ <Icon name="chevron-right" className="size-3.5" />+ </button>+ ) : (+ <p className="text-text-secondary px-2 py-4 text-center text-sm">{loading ? 'Loading…' : 'No models'}</p>+ )+ ) : (+ sections.map((section, sectionIndex) => {+ const headingId = `${listboxId}-provider-${sectionIndex}`;+ return (+ <div+ key={section.name}+ role="group"+ aria-labelledby={headingId}+ className={cn(sectionIndex > 0 && 'mt-2')}+ >+ <div+ id={headingId}+ className="text-text-secondary flex items-center gap-1.5 px-2 py-1.5 text-[11px] font-medium tracking-wide uppercase"+ >+ <ProviderMark logo={section.logo} label={section.name} className="size-3.5 text-[9px]" />+ <span className="truncate">{section.name}</span>+ </div>+ {section.models.map(model => {+ const active = selectedName ? model.name === selectedName : filtered[0] === model;+ return (+ <button+ key={model.id || model.name}+ type="button"+ role="option"+ aria-selected={active}+ className={cn(+ 'flex w-full items-center rounded-md px-2 py-2 text-left text-sm',+ active+ ? 'bg-dropdown-selected-item-bg text-dropdown-selected-item-text'+ : 'hover:bg-ghost-button-hover',+ )}+ onClick={() => onSelect(model)}+ >+ <span className="truncate font-medium">{displayModelLabel(model.name)}</span>+ {active ? <Icon name="check" className="ml-auto size-3.5" /> : null}+ </button>+ );+ })}+ </div>+ );+ })+ )}+ </div>+ </>+ );+}diff --git a/packages/trueforge-ui-sdk/src/atoms/draft/DraftModelSelector.tsx b/packages/trueforge-ui-sdk/src/atoms/draft/DraftModelSelector.tsxindex 423fa1e6e..4004ab006 100644--- a/packages/trueforge-ui-sdk/src/atoms/draft/DraftModelSelector.tsx+++ b/packages/trueforge-ui-sdk/src/atoms/draft/DraftModelSelector.tsx@@ -1,72 +1,20 @@'use client';import { useTrueFoundryAgentSpec, useTrueFoundryUpdateAgentSpec } from '@truefoundry/assistant-ui-runtime';-import { useEffect, useId, useMemo, useRef, useState } from 'react';+import { useEffect, useId, 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';import { useCompactLayout } from '../lib/CompactLayoutContext.js';import { useIsMobile } from '../lib/useIsMobile.js';import { BottomSheet } from '../primitives/BottomSheet.js';-import { CatalogLogo } from '../primitives/CatalogLogo.js';import { useDraftCatalog } from './DraftCatalogProvider.js';+import { displayModelLabel, DraftModelCatalogPanel, ProviderMark } from './DraftModelCatalogPanel.js';import { modelPatchWithReasoningEffort } from './reasoningEffort.js';-function monogram(value: string): string {- const trimmed = value.trim();- return trimmed ? trimmed.charAt(0).toUpperCase() : '?';-}--function ProviderMark({ logo, label, className }: { logo?: string; label: string; className?: string }) {- if (logo) {- return <CatalogLogo src={logo} alt="" className={cn('shrink-0 rounded object-contain', className)} aria-hidden />;- }- return (- <span- className={cn(- 'bg-secondary-bg text-text-secondary flex shrink-0 items-center justify-center rounded font-semibold',- className,- )}- aria-hidden- >- {monogram(label)}- </span>- );-}--function displayModelLabel(modelName: string): string {- const slash = modelName.lastIndexOf('/');- return slash >= 0 ? modelName.slice(slash + 1) : modelName;-}--type ProviderSection = {- name: string;- logo?: string;- models: ModelSelection[];-};--function groupModelsByProvider(models: ModelSelection[]): ProviderSection[] {- const sections: ProviderSection[] = [];- const byProvider = new Map<string, ProviderSection>();- for (const model of models) {- const name = model.provider.name.trim() || 'Other';- const existing = byProvider.get(name);- if (existing) {- existing.models.push(model);- if (!existing.logo && model.provider.logo) existing.logo = model.provider.logo;- continue;- }- const section: ProviderSection = { name, logo: model.provider.logo, models: [model] };- byProvider.set(name, section);- sections.push(section);- }- return sections;-}-export type DraftModelSelectorProps = {disabled?: boolean;isRunning?: boolean;@@ -123,19 +71,6 @@ export function DraftModelSelector({ disabled, isRunning }: DraftModelSelectorPr? 'Loading…': 'Select model';- const filtered = useMemo(() => {- const needle = query.trim().toLowerCase();- if (!needle) return models;- return models.filter(- m =>- m.name.toLowerCase().includes(needle) ||- m.id.toLowerCase().includes(needle) ||- m.provider.name.toLowerCase().includes(needle),- );- }, [models, query]);-- const sections = useMemo(() => groupModelsByProvider(filtered), [filtered]);-useEffect(() => {if (!open) return;const handler = (e: MouseEvent) => {@@ -150,103 +85,30 @@ export function DraftModelSelector({ disabled, isRunning }: DraftModelSelectorPrconst account = selected?.provider.name ?? selectedName;const content = (- <>- <div className="border-b border-border px-3 py-2">- <p className="text-text-primary mb-2 text-sm font-semibold">Select model</p>- <label className="relative block">- <Icon- name="search"- className="text-text-secondary pointer-events-none absolute top-1/2 left-2 size-3.5 -translate-y-1/2"- />- <input- type="search"- value={query}- onChange={e => setQuery(e.target.value)}- placeholder="Search"- className="border-input-border bg-input-box-bg text-text-primary placeholder:text-text-secondary h-8 w-full rounded-md border py-1 pr-2 pl-7 text-sm outline-none focus-visible:ring-2 focus-visible:ring-focus-ring/40"- autoFocus- />- </label>- </div>- <div- id={menuId}- role="listbox"- aria-label="Select model"- className="flex min-h-0 flex-1 flex-col overflow-y-auto p-1"- >- {filtered.length === 0 ? (- showConfigureSettingsCta ? (- <button- type="button"- className="text-text-secondary hover:text-text-primary 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-text-secondary px-2 py-4 text-center text-sm">No models</p>- )- ) : (- sections.map((section, sectionIndex) => {- const headingId = `${menuId}-provider-${sectionIndex}`;- return (- <div- key={section.name}- role="group"- aria-labelledby={headingId}- className={cn(sectionIndex > 0 && 'mt-2')}- >- <div- id={headingId}- className="text-text-secondary flex items-center gap-1.5 px-2 py-1.5 text-[11px] font-medium tracking-wide uppercase"- >- <ProviderMark logo={section.logo} label={section.name} className="size-3.5 text-[9px]" />- <span className="truncate">{section.name}</span>- </div>- {section.models.map(model => {- // If there is no selected model, consider the first in the filtered list as active- const active = selectedName ? model.name === selectedName : filtered[0] === model;- return (- <button- key={model.id || model.name}- type="button"- role="option"- aria-selected={active}- className={cn(- 'flex w-full items-center rounded-md px-2 py-2 text-left text-sm',- active- ? 'bg-dropdown-selected-item-bg text-dropdown-selected-item-text'- : 'hover:bg-ghost-button-hover',- )}- onClick={() => {- updateAgentSpec?.({- model: modelPatchWithReasoningEffort(- model.name,- agentSpec?.model?.params,- model.properties.reasoningEfforts,- ),- });- setOpen(false);- setQuery('');- }}- >- <span className="truncate font-medium">{displayModelLabel(model.name)}</span>- </button>- );- })}- </div>- );- })- )}- </div>- </>+ <DraftModelCatalogPanel+ models={models}+ loading={loading}+ selectedName={selectedName}+ query={query}+ onQueryChange={setQuery}+ listboxId={menuId}+ onOpenSettings={+ showConfigureSettingsCta+ ? () => {+ setOpen(false);+ setQuery('');+ shell?.setSettingsOpen(true);+ }+ : undefined+ }+ onSelect={model => {+ updateAgentSpec?.({+ model: modelPatchWithReasoningEffort(model.name, agentSpec?.model?.params, model.properties.reasoningEfforts),+ });+ setOpen(false);+ setQuery('');+ }}+ />);return (diff --git a/packages/trueforge-ui-sdk/src/atoms/draft/agentCapabilities.ts b/packages/trueforge-ui-sdk/src/atoms/draft/agentCapabilities.tsnew file mode 100644index 000000000..a00458360--- /dev/null+++ b/packages/trueforge-ui-sdk/src/atoms/draft/agentCapabilities.ts@@ -0,0 +1,36 @@+import type { AgentRuntimeConfig } from '../../server/types.js';++export type AgentCapabilityValues = {+ generativeUi: boolean;+ dynamicSubAgents: boolean;+ askUserQuestions: boolean;+};++export const DEFAULT_AGENT_CAPABILITIES: AgentCapabilityValues = {+ generativeUi: true,+ dynamicSubAgents: true,+ askUserQuestions: true,+};++export function readAgentCapabilities(config?: AgentRuntimeConfig): AgentCapabilityValues {+ return {+ generativeUi: config?.generativeUi?.enabled ?? DEFAULT_AGENT_CAPABILITIES.generativeUi,+ dynamicSubAgents: config?.dynamicSubAgents?.enabled ?? DEFAULT_AGENT_CAPABILITIES.dynamicSubAgents,+ askUserQuestions: config?.askUserQuestions?.enabled ?? DEFAULT_AGENT_CAPABILITIES.askUserQuestions,+ };+}++export function withAgentCapabilities({+ config,+ values,+}: {+ config?: AgentRuntimeConfig;+ values: AgentCapabilityValues;+}): AgentRuntimeConfig {+ return {+ ...config,+ generativeUi: { ...config?.generativeUi, enabled: values.generativeUi },+ dynamicSubAgents: { ...config?.dynamicSubAgents, enabled: values.dynamicSubAgents },+ askUserQuestions: { ...config?.askUserQuestions, enabled: values.askUserQuestions },+ };+}diff --git a/packages/trueforge-ui-sdk/src/atoms/primitives/CenteredModal.tsx b/packages/trueforge-ui-sdk/src/atoms/primitives/CenteredModal.tsxindex 79dcf774c..f2e33424a 100644--- a/packages/trueforge-ui-sdk/src/atoms/primitives/CenteredModal.tsx+++ b/packages/trueforge-ui-sdk/src/atoms/primitives/CenteredModal.tsx@@ -73,6 +73,7 @@ export function CenteredModal({style={compactStyle ?? (contentSized ? { height: 'fit-content', maxHeight: '85dvh' } : undefined)}className={cn('bg-card-bg text-text-primary border-border open:flex open:flex-col overflow-hidden p-0 shadow-xl',+ 'backdrop:bg-black/50 backdrop:backdrop-blur-[2px] dark:backdrop:bg-black/70',compact? 'm-0 mt-auto max-w-none rounded-t-xl rounded-b-none border-t pb-[env(safe-area-inset-bottom)]': contentSized@@ -108,7 +109,7 @@ export function CenteredModal({<Icon name="xmark" /></button></header>- <div className="flex min-h-0 flex-1 flex-col overflow-y-auto">{children}</div>+ <div className="flex min-h-0 flex-1 flex-col overflow-x-hidden overflow-y-auto">{children}</div></dialog>);}diff --git a/packages/trueforge-ui-sdk/src/atoms/primitives/Switch.tsx b/packages/trueforge-ui-sdk/src/atoms/primitives/Switch.tsxnew file mode 100644index 000000000..ba64763d8--- /dev/null+++ b/packages/trueforge-ui-sdk/src/atoms/primitives/Switch.tsx@@ -0,0 +1,60 @@+'use client';++import type { ComponentPropsWithoutRef } from 'react';++import { cn } from '../lib/cn.js';++export type SwitchSize = 'sm' | 'md';++export type SwitchProps = Omit<ComponentPropsWithoutRef<'button'>, 'aria-checked' | 'children' | 'onClick' | 'role'> & {+ checked: boolean;+ onCheckedChange: (checked: boolean) => void;+ size?: SwitchSize;+};++const sizeClasses: Record<SwitchSize, { track: string; thumb: string; checkedThumb: string }> = {+ sm: {+ track: 'h-5 w-9 p-0.5',+ thumb: 'size-4',+ checkedThumb: 'translate-x-4',+ },+ md: {+ track: 'h-6 w-11 p-0.5',+ thumb: 'size-5',+ checkedThumb: 'translate-x-5',+ },+};++export function Switch({ checked, onCheckedChange, size = 'sm', disabled, className, ...props }: SwitchProps) {+ const classes = sizeClasses[size];++ return (+ <button+ {...props}+ type="button"+ role="switch"+ aria-checked={checked}+ data-state={checked ? 'checked' : 'unchecked'}+ disabled={disabled}+ className={cn(+ 'flex shrink-0 cursor-pointer items-center overflow-hidden rounded-full transition-colors',+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring/40',+ 'disabled:cursor-not-allowed disabled:opacity-50',+ classes.track,+ checked ? 'bg-primary-button-bg' : 'bg-text-secondary/35 dark:bg-text-secondary/50',+ className,+ )}+ onClick={() => onCheckedChange(!checked)}+ >+ <span+ aria-hidden+ className={cn(+ 'shrink-0 translate-x-0 rounded-full shadow-sm transition-[transform,background-color]',+ checked ? 'bg-primary-button-text' : 'bg-primary-bg',+ classes.thumb,+ checked && classes.checkedThumb,+ )}+ />+ </button>+ );+}diff --git a/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/CustomModelProviderForm.tsx b/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/CustomModelProviderForm.tsxindex faeff5106..a49cc3676 100644--- a/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/CustomModelProviderForm.tsx+++ b/packages/trueforge-ui-sdk/src/containers/SettingsBuilder/CustomModelProviderForm.tsx@@ -5,6 +5,7 @@ import { useState, type ReactNode } from 'react';import { cn } from '../../atoms/lib/cn.js';import { Button } from '../../atoms/primitives/Button.js';import { CenteredModal } from '../../atoms/primitives/CenteredModal.js';+import { Switch } from '../../atoms/primitives/Switch.js';import { Icon } from '../../icons/Icon.js';export type CustomProviderDraft = {@@ -476,32 +477,18 @@ const CustomModelProviderForm = ({{reasoningEffortOptions && reasoningEffortOptions.length > 0 ? (<div><div className="flex items-center justify-between gap-3">- <span className="text-xs font-medium text-text-secondary">Reasoning effort</span>- <button- type="button"- role="switch"- aria-checked={model.reasoningEfforts !== undefined}+ <span className="text-text-secondary text-xs font-medium">Reasoning effort</span>+ <Switch+ checked={model.reasoningEfforts !== undefined}aria-label={`Enable reasoning effort for model ${index + 1}`}disabled={busy}- className={cn(- 'relative h-6 w-11 shrink-0 rounded-full transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring/40 disabled:opacity-50',- model.reasoningEfforts !== undefined- ? 'bg-primary-button-bg'- : 'bg-text-secondary/30 dark:bg-text-secondary/50',- )}- onClick={() =>+ size="md"+ onCheckedChange={nextChecked =>updateModel(index, {- reasoningEfforts: model.reasoningEfforts === undefined ? [] : undefined,+ reasoningEfforts: nextChecked ? [] : undefined,})}- >- <span- className={cn(- 'absolute top-0.5 left-0 size-5 rounded-full bg-white shadow-sm transition-transform',- model.reasoningEfforts !== undefined ? 'translate-x-5' : 'translate-x-0.5',- )}- />- </button>+ /></div>{model.reasoningEfforts !== undefined ? (<divdiff --git a/packages/trueforge-ui-sdk/src/containers/TrueforgeUI.tsx b/packages/trueforge-ui-sdk/src/containers/TrueforgeUI.tsxindex 679102305..7826477e1 100644--- a/packages/trueforge-ui-sdk/src/containers/TrueforgeUI.tsx+++ b/packages/trueforge-ui-sdk/src/containers/TrueforgeUI.tsx@@ -3,6 +3,7 @@import type { TrueFoundryAgentConfig, UseTrueFoundryAgentRuntimeOptions } from '@truefoundry/assistant-ui-runtime';import { lazy, Suspense, useMemo, type ReactNode } from 'react';+import { DraftCatalogProvider } from '../atoms/draft/DraftCatalogProvider.js';import { cn } from '../atoms/lib/cn.js';import { Spinner } from '../atoms/primitives/Spinner.js';import { ServerProvider } from '../server/ServerContext.js';@@ -179,7 +180,7 @@ function ChatProviderFromShell({listSessionsAgentId={listSessionsAgentId}initialSessionId={pendingSessionId ?? hostInitialSessionId}>- {children}+ <DraftCatalogProvider>{children}</DraftCatalogProvider></TrueFoundryChatProvider>);}diff --git a/packages/trueforge-ui-sdk/src/hooks/useChatChromeActionsVisible.ts b/packages/trueforge-ui-sdk/src/hooks/useChatChromeActionsVisible.tsindex a86ed3e1c..b92c711ef 100644--- a/packages/trueforge-ui-sdk/src/hooks/useChatChromeActionsVisible.ts+++ b/packages/trueforge-ui-sdk/src/hooks/useChatChromeActionsVisible.ts@@ -4,12 +4,23 @@ import { useTrueFoundryAgentSpec } from '@truefoundry/assistant-ui-runtime';import { useOptionalShellMode } from '../server/ShellModeContext.js';-// Immutable named-agent title in the thread header.-export function useNamedAgentHeaderVisible(): boolean {+export type NamedAgentHeaderState = {+ name: string;+ isEditing: boolean;+};++// Canonical named-agent header state, including mutable edit mode.+export function useNamedAgentHeaderState(): NamedAgentHeaderState | null {const shell = useOptionalShellMode();- if (shell == null || shell.mode.status !== 'active' || shell.mode.isMutable) return false;+ if (shell == null || shell.mode.status !== 'active') return null;const name = shell.mode.agentName ?? shell.mode.agentId;- return name != null && name.length > 0;+ if (name == null || name.length === 0) return null;+ return { name, isEditing: shell.mode.isMutable };+}++export function useNamedAgentHeaderVisible(): boolean {+ const state = useNamedAgentHeaderState();+ return state !== null;}// Mutable draft/edit with a selected model — drives Save Agent + header chrome.diff --git a/packages/trueforge-ui-sdk/src/index.ts b/packages/trueforge-ui-sdk/src/index.tsindex 1c568244d..1754114e0 100644--- a/packages/trueforge-ui-sdk/src/index.ts+++ b/packages/trueforge-ui-sdk/src/index.ts@@ -33,6 +33,8 @@ export type { ButtonProps, ButtonSize, ButtonVariant } from './atoms/primitives/export { CenteredModal } from './atoms/primitives/CenteredModal.js';export type { CenteredModalProps } from './atoms/primitives/CenteredModal.js';export type { IconButtonProps } from './atoms/primitives/IconButton.js';+export { Switch } from './atoms/primitives/Switch.js';+export type { SwitchProps, SwitchSize } from './atoms/primitives/Switch.js';export { Icon } from './icons/Icon.js';export type { IconProps } from './icons/Icon.js';diff --git a/packages/trueforge-ui-sdk/src/server/createTrueFoundryServer.ts b/packages/trueforge-ui-sdk/src/server/createTrueFoundryServer.tsindex 472e64a09..96d192f32 100644--- a/packages/trueforge-ui-sdk/src/server/createTrueFoundryServer.ts+++ b/packages/trueforge-ui-sdk/src/server/createTrueFoundryServer.ts@@ -19,7 +19,7 @@ export type CreateTrueFoundryServerOptions<TSkill extends AgentSkill = AgentSkill,TMcp extends ConnectorState = ConnectorState,TAgent extends AgentLibraryEntry = AgentLibraryEntry,- TSave = SaveAgentResult,+ TSave extends SaveAgentResult = SaveAgentResult,TCatalog extends CatalogServer = CatalogServer,TCapabilities extends AgentBuilderCapabilitiesResponse = AgentBuilderCapabilitiesResponse,> = {@@ -42,7 +42,7 @@ export type TrueFoundryServer<TSkill extends AgentSkill = AgentSkill,TMcp extends ConnectorState = ConnectorState,TAgent extends AgentLibraryEntry = AgentLibraryEntry,- TSave = SaveAgentResult,+ TSave extends SaveAgentResult = SaveAgentResult,TCatalog extends CatalogServer = CatalogServer,TCapabilities extends AgentBuilderCapabilitiesResponse = AgentBuilderCapabilitiesResponse,> = AgentChatServer<TSpec> &@@ -61,7 +61,7 @@ export function createTrueFoundryServer<TSkill extends AgentSkill = AgentSkill,TMcp extends ConnectorState = ConnectorState,TAgent extends AgentLibraryEntry = AgentLibraryEntry,- TSave = SaveAgentResult,+ TSave extends SaveAgentResult = SaveAgentResult,TCatalog extends CatalogServer = CatalogServer,TCapabilities extends AgentBuilderCapabilitiesResponse = AgentBuilderCapabilitiesResponse,>(diff --git a/packages/trueforge-ui-sdk/src/server/types.ts b/packages/trueforge-ui-sdk/src/server/types.tsindex 62755eed2..207a25d24 100644--- a/packages/trueforge-ui-sdk/src/server/types.ts+++ b/packages/trueforge-ui-sdk/src/server/types.ts@@ -10,8 +10,10 @@export type {AgentBuilderCapabilitiesResponse,AgentBuilderServer,+ AgentCapabilityConfig,AgentChatServer,AgentLibraryEntry,+ AgentRuntimeConfig,AgentSkill,AgentSpec,AgentUIServer,diff --git a/packages/trueforge-ui-sdk/test/atoms/NamedAgentHeaderLabel.test.tsx b/packages/trueforge-ui-sdk/test/atoms/NamedAgentHeaderLabel.test.tsxindex 5f0bbbadb..d4ff3895c 100644--- a/packages/trueforge-ui-sdk/test/atoms/NamedAgentHeaderLabel.test.tsx+++ b/packages/trueforge-ui-sdk/test/atoms/NamedAgentHeaderLabel.test.tsx@@ -14,6 +14,25 @@ function SelectNamed() {);}+function SelectEditable() {+ const shell = useShellMode();+ return (+ <button+ type="button"+ onClick={() =>+ shell.selectLibraryAgent({+ isMutable: true,+ agentId: 'reviewer',+ agentName: 'reviewer',+ agentSpec: { model: { name: 'openai/gpt-4.1' } },+ })+ }+ >+ edit+ </button>+ );+}+describe('NamedAgentHeaderLabel', () => {it('shows the agent name for a named (immutable) chat', () => {render(@@ -24,7 +43,7 @@ describe('NamedAgentHeaderLabel', () => {expect(screen.getByRole('heading', { name: 'support' })).toBeInTheDocument();});- it('is hidden for draft / mutable chats', () => {+ it('is hidden for unnamed draft chats', () => {render(<ShellModeProvider agentConfig={{ mode: 'AgentComposer' }}><NamedAgentHeaderLabel />@@ -33,6 +52,21 @@ describe('NamedAgentHeaderLabel', () => {expect(screen.queryByRole('heading')).not.toBeInTheDocument();});+ it('shows an Editing label for a saved agent opened in mutable mode', () => {+ render(+ <ShellModeProvider agentConfig={{ mode: 'AgentComposer' }}>+ <SelectEditable />+ <NamedAgentHeaderLabel />+ </ShellModeProvider>,+ );++ act(() => {+ screen.getByRole('button', { name: 'edit' }).click();+ });++ expect(screen.getByRole('heading', { name: 'reviewer Editing' })).toBeInTheDocument();+ });+it('is hidden while idle, then appears after selecting a named agent', () => {render(<ShellModeProvider agentConfig={{ mode: 'AgentLibrary' }}>diff --git a/packages/trueforge-ui-sdk/test/atoms/SaveAgentButton.test.tsx b/packages/trueforge-ui-sdk/test/atoms/SaveAgentButton.test.tsxindex 07bb5c60b..401ccdb74 100644--- a/packages/trueforge-ui-sdk/test/atoms/SaveAgentButton.test.tsx+++ b/packages/trueforge-ui-sdk/test/atoms/SaveAgentButton.test.tsx@@ -1,33 +1,23 @@// @vitest-environment jsdom-import { fireEvent, render, screen, waitFor } from '@testing-library/react';-import { useEffect, useRef, type ReactNode } from 'react';-import { beforeAll, describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';+import { cloneElement, isValidElement, useEffect, type ReactNode } from 'react';+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';import { SaveAgentButton } from '@/atoms/SaveAgentButton.js';import { ServerProvider } from '@/server/ServerContext.js';-import { ShellModeProvider, useShellMode } from '@/server/ShellModeContext.js';-import type { SaveAgentResult } from '@/server/types.js';+import { ShellModeProvider, useShellMode, type AgentConfig } from '@/server/ShellModeContext.js';+import type { AgentSpec, AgentUIServer, SaveAgentRequest, SaveAgentResult } from '@/server/types.js';import { SlotsProvider } from '@/theme/SlotsProvider.js';-import { RuntimeHarness } from '../containers/RuntimeHarness.js';import { createMockAgentUIServer } from '../server/mockServer.js';-type MockAgentSpec = {- model?: { name?: string };- skills?: { id: string; name: string }[];- instructions?: string;-};--const agentSpecState: { agentSpec: MockAgentSpec } = {- agentSpec: {- model: { name: 'openai-main/gpt-4.1' },- skills: [{ id: 's1', name: 'Skill One' }],- },-};+let agentSpec: AgentSpec;+const flushAgentSpec = vi.fn(async () => undefined);+const adoptAgentSpec = vi.fn();vi.mock('@truefoundry/assistant-ui-runtime', () => ({- useTrueFoundryAgentSpec: () => ({- agentSpec: agentSpecState.agentSpec,- }),+ useTrueFoundryAgentSpec: () => ({ agentSpec, draftSessionId: 'draft-1' }),+ useTrueFoundryFlushAgentSpec: () => flushAgentSpec,+ useTrueFoundryAdoptAgentSpec: () => adoptAgentSpec,}));beforeAll(() => {@@ -40,222 +30,383 @@ beforeAll(() => {};});-const startedMessages = [{ role: 'user' as const, content: 'hello', id: 'm1' }];--type SaveAgentMock = ReturnType<typeof vi.fn<(...args: never[]) => Promise<SaveAgentResult>>>;--function mockServer(saveAgent: SaveAgentMock = vi.fn(async () => ({ agentId: 'agt_1' }))) {- return createMockAgentUIServer({ saveAgent });-}--function getSubmitButton(dialog: HTMLElement): HTMLButtonElement {- const button = dialog.querySelector<HTMLButtonElement>('button[type="submit"]');- if (button === null) {- throw new Error('Expected submit button');- }- return button;-}--function renderSaveAgent({- children,- messages = startedMessages,- agentConfig,- saveAgent,+function renderButton({+ saveAgent = vi.fn(async (): Promise<SaveAgentResult> => ({ agentId: 'agent-1' })),+ agentConfig = { mode: 'AgentComposer' as const },+ serverOverrides = {},+ children = <SaveAgentButton />,}: {- children: ReactNode;- messages?: typeof startedMessages | [];- agentConfig?: Parameters<typeof ShellModeProvider>[0]['agentConfig'];- saveAgent?: SaveAgentMock;-}) {- return render(+ saveAgent?: (request: SaveAgentRequest) => Promise<SaveAgentResult>;+ agentConfig?: AgentConfig;+ serverOverrides?: Partial<AgentUIServer>;+ children?: ReactNode;+} = {}) {+ const server = createMockAgentUIServer({+ getModels: async () => [+ {+ id: 'openai/gpt-4.1',+ name: 'openai/gpt-4.1',+ provider: { name: 'OpenAI' },+ properties: {},+ },+ {+ id: 'anthropic/claude-sonnet-4-6',+ name: 'anthropic/claude-sonnet-4-6',+ provider: { name: 'Anthropic' },+ properties: {},+ },+ ],+ getMcp: async () => [+ { id: 'github', name: 'GitHub', authenticated: true },+ { id: 'slack', name: 'Slack', authenticated: true },+ ],+ getSkills: async () => [+ { id: 'research', name: 'Research' },+ { id: 'writing', name: 'Writing' },+ ],+ ...serverOverrides,+ saveAgent,+ });+ const tree = () => (<SlotsProvider>- <ServerProvider server={mockServer(saveAgent)}>+ <ServerProvider server={server}><ShellModeProvider agentConfig={agentConfig}>- <RuntimeHarness messages={messages}>{children}</RuntimeHarness>+ {isValidElement(children) ? cloneElement(children) : children}</ShellModeProvider></ServerProvider>- </SlotsProvider>,+ </SlotsProvider>);+ const rendered = render(tree());+ return {+ saveAgent,+ ...rendered,+ rerenderButton: () => rendered.rerender(tree()),+ };}-describe('SaveAgentButton', () => {- it('is hidden when the shell is locked to a named agent', () => {- renderSaveAgent({- agentConfig: { mode: 'SingleAgent', name: 'locked-agent' },- children: <SaveAgentButton />,+function BoundMutableSaveButton({ agentId, agentName }: { agentId: string; agentName?: string }) {+ const { selectLibraryAgent } = useShellMode();+ useEffect(() => {+ selectLibraryAgent({+ isMutable: true,+ agentId,+ agentName,+ agentSpec,});+ }, [agentId, agentName, selectLibraryAgent]);+ return <SaveAgentButton />;+}- expect(screen.queryByRole('button', { name: 'Save agent' })).not.toBeInTheDocument();+function deferred<T>() {+ let resolvePromise: ((value: T) => void) | undefined;+ const promise = new Promise<T>(resolve => {+ resolvePromise = resolve;});+ return {+ promise,+ resolve(value: T) {+ if (resolvePromise === undefined) throw new Error('Deferred promise was not initialized');+ resolvePromise(value);+ },+ };+}- it('shows on an empty new chat when a model is selected', () => {- renderSaveAgent({- messages: [],- children: <SaveAgentButton />,- });+async function findStackedDialog(label: string): Promise<HTMLDialogElement> {+ await waitFor(() => expect(document.querySelectorAll('dialog')[1]).toHaveAttribute('aria-label', label));+ const dialog = document.querySelectorAll('dialog')[1];+ if (!(dialog instanceof HTMLDialogElement)) throw new Error(`Expected stacked dialog: ${label}`);+ return dialog;+}- expect(screen.getByRole('button', { name: 'Save agent' })).toBeInTheDocument();+describe('SaveAgentButton', () => {+ beforeEach(() => {+ agentSpec = {+ model: { name: 'openai/gpt-4.1' },+ instructions: 'Be helpful.',+ mcpServers: [{ id: 'github', name: 'GitHub' }],+ skills: [{ id: 'research', name: 'Research' }],+ };+ flushAgentSpec.mockReset();+ flushAgentSpec.mockResolvedValue(undefined);+ adoptAgentSpec.mockClear();});- it('is hidden when the draft has no model', () => {- const previous = agentSpecState.agentSpec;- agentSpecState.agentSpec = { skills: [{ id: 's1', name: 'Skill One' }] };- try {- renderSaveAgent({- children: <SaveAgentButton />,- });- expect(screen.queryByRole('button', { name: 'Save agent' })).not.toBeInTheDocument();- } finally {- agentSpecState.agentSpec = previous;- }+ it('is hidden when the shell is locked to a named agent', () => {+ renderButton({ agentConfig: { mode: 'SingleAgent', name: 'locked-agent' } });+ expect(screen.queryByRole('button', { name: 'Save Agent' })).not.toBeInTheDocument();});- it('opens a modal with name + system instructions and saves them on agentSpec', async () => {- const saveAgent = vi.fn(async () => ({ agentId: 'agt_1' }));+ it('shows on an empty new chat when a model is selected', () => {+ renderButton();+ expect(screen.getByRole('button', { name: 'Save Agent' })).toBeInTheDocument();+ });- renderSaveAgent({- saveAgent,- children: <SaveAgentButton />,- });+ it('is hidden when the draft has no model', () => {+ agentSpec = {+ model: { name: '' },+ skills: [{ id: 's1', name: 'Skill One' }],+ };+ renderButton();+ expect(screen.queryByRole('button', { name: 'Save Agent' })).not.toBeInTheDocument();+ });- fireEvent.click(screen.getByRole('button', { name: 'Save agent' }));- const dialog = screen.getByRole('dialog', { name: 'Save agent' });- expect(dialog).toBeInTheDocument();- expect(dialog.className).toContain('h-auto');- expect(dialog.className).toContain('md:max-w-md');- expect(dialog).toHaveStyle({ height: 'fit-content' });- expect(screen.getByLabelText('Name')).toBeInTheDocument();- expect(screen.getByLabelText('System instructions')).toBeInTheDocument();-- fireEvent.change(screen.getByLabelText('Name'), { target: { value: ' my-agent ' } });- fireEvent.change(screen.getByLabelText('System instructions'), {- target: { value: ' You write release notes. ' },- });- fireEvent.click(getSubmitButton(dialog));-- await waitFor(() => {- expect(saveAgent).toHaveBeenCalledWith({- agentName: 'my-agent',- agentSpec: {- model: { name: 'openai-main/gpt-4.1' },- skills: [{ id: 's1', name: 'Skill One' }],- instructions: 'You write release notes.',- },- intent: 'create',- });- });- await waitFor(() => {- expect(screen.queryByRole('dialog', { name: 'Save agent' })).not.toBeInTheDocument();+ it('is hidden in idle library mode without loading catalogs', () => {+ const getModels = vi.fn(async () => []);+ const getSkills = vi.fn(async () => []);+ const getMcp = vi.fn(async () => []);+ renderButton({+ agentConfig: { mode: 'AgentLibrary' },+ serverOverrides: { getModels, getSkills, getMcp },});- // Bound as mutable Edit with saved identity + spec; chrome flips to Update Agent.- expect(screen.getByRole('button', { name: 'Update Agent' })).toBeInTheDocument();++ expect(screen.queryByRole('button', { name: 'Save Agent' })).not.toBeInTheDocument();+ expect(getModels).not.toHaveBeenCalled();+ expect(getSkills).not.toHaveBeenCalled();+ expect(getMcp).not.toHaveBeenCalled();});- it('binds the same draft chat as editable agent without remounting', async () => {- const saveAgent = vi.fn(async () => ({ agentId: 'agt_1' }));- let shellSnap: ReturnType<typeof useShellMode> | undefined;+ it('uses SDK theme tokens for editable controls', async () => {+ renderButton();+ fireEvent.click(screen.getByRole('button', { name: 'Save Agent' }));++ const dialog = await screen.findByRole('dialog', { name: 'Save agent' });+ expect(dialog).toHaveClass('bg-card-bg', 'text-text-primary');+ expect(within(dialog).getByLabelText('Agent name')).toHaveClass(+ 'border-input-border',+ 'bg-input-box-bg',+ 'text-text-primary',+ 'focus-visible:ring-focus-ring/40',+ );+ expect(within(dialog).getByLabelText('Instructions')).toHaveClass(+ 'border-input-border',+ 'bg-input-box-bg',+ 'text-text-primary',+ 'focus-visible:ring-focus-ring/40',+ );+ });- function Probe() {- shellSnap = useShellMode();- return <SaveAgentButton />;- }+ it('opens with the latest runtime spec after flushing pending picker edits', async () => {+ const pendingFlush = deferred<undefined>();+ flushAgentSpec.mockReturnValueOnce(pendingFlush.promise);+ const rendered = renderButton();++ fireEvent.click(screen.getByRole('button', { name: 'Save Agent' }));+ await waitFor(() => expect(flushAgentSpec).toHaveBeenCalledOnce());++ agentSpec = {+ model: { name: 'openai/gpt-4.1' },+ instructions: 'Latest flushed instructions.',+ mcpServers: [{ id: 'slack', name: 'Slack' }],+ skills: [{ id: 'writing', name: 'Writing' }],+ config: { generativeUi: { enabled: false } },+ };+ rendered.rerenderButton();+ pendingFlush.resolve(undefined);++ const dialog = await screen.findByRole('dialog', { name: 'Save agent' });+ expect(within(dialog).getByLabelText('Instructions')).toHaveValue('Latest flushed instructions.');+ expect(within(dialog).getByRole('switch', { name: 'Generative UI' })).toHaveAttribute('aria-checked', 'false');++ fireEvent.click(within(dialog).getByRole('button', { name: 'Edit MCP servers' }));+ const mcpDialog = await findStackedDialog('Edit MCP servers');+ expect(await within(mcpDialog).findByRole('menuitemcheckbox', { name: /Slack/ })).toHaveAttribute(+ 'aria-checked',+ 'true',+ );+ });- renderSaveAgent({+ it('labels an existing mutable binding as Update Agent and submits an update', async () => {+ const saveAgent = vi.fn(async (): Promise<SaveAgentResult> => ({ agentId: 'writer' }));+ renderButton({saveAgent,- children: <Probe />,+ children: <BoundMutableSaveButton agentId="writer" />,});- expect(shellSnap).toBeDefined();- if (shellSnap == null) throw new Error('expected shell');- const epochBefore = shellSnap.agentsListEpoch;- const runtimeKeyBefore = shellSnap.runtimeKey;+ const trigger = await screen.findByRole('button', { name: 'Update Agent' });+ expect(screen.queryByRole('button', { name: 'Save Agent' })).not.toBeInTheDocument();+ fireEvent.click(trigger);+ const dialog = await screen.findByRole('dialog', { name: 'Update agent' });+ expect(within(dialog).getByLabelText('Agent name')).toHaveValue('writer');+ fireEvent.click(within(dialog).getByRole('button', { name: 'Save changes' }));- fireEvent.click(screen.getByRole('button', { name: 'Save agent' }));- const dialog = screen.getByRole('dialog', { name: 'Save agent' });- fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'saved-agent' } });- fireEvent.change(screen.getByLabelText('System instructions'), {- target: { value: 'Be helpful.' },- });- const submit = dialog.querySelector('button[type="submit"]');- expect(submit).toBeInstanceOf(HTMLButtonElement);- if (!(submit instanceof HTMLButtonElement)) throw new Error('expected submit');- fireEvent.click(submit);-- await waitFor(() => {- expect(shellSnap?.mode).toEqual({- status: 'active',- isMutable: true,- agentId: 'saved-agent',- agentName: 'saved-agent',- agentSpec: {- model: { name: 'openai-main/gpt-4.1' },- skills: [{ id: 's1', name: 'Skill One' }],- instructions: 'Be helpful.',- },- locked: false,- });- });- expect(shellSnap.agentsListEpoch).toBe(epochBefore + 1);- // Same chat continues — runtime must not remount.- expect(shellSnap.runtimeKey).toBe(runtimeKeyBefore);+ await waitFor(() =>+ expect(saveAgent).toHaveBeenCalledWith(expect.objectContaining({ agentName: 'writer', intent: 'update' })),+ );});- it('surfaces save errors without closing', async () => {- const saveAgent = vi.fn(async () => {- throw new Error('Name taken');- });-- renderSaveAgent({- saveAgent,- children: <SaveAgentButton />,- });+ it('discards modal-only changes when closed', async () => {+ renderButton();+ fireEvent.click(screen.getByRole('button', { name: 'Save Agent' }));+ const dialog = await screen.findByRole('dialog', { name: 'Save agent' });+ fireEvent.change(within(dialog).getByLabelText('Agent name'), { target: { value: 'discard-me' } });+ fireEvent.click(within(dialog).getByRole('switch', { name: 'Generative UI' }));+ fireEvent.click(within(dialog).getByRole('button', { name: 'Close' }));++ fireEvent.click(screen.getByRole('button', { name: 'Save Agent' }));+ const reopened = await screen.findByRole('dialog', { name: 'Save agent' });+ expect(within(reopened).getByLabelText('Agent name')).toHaveValue('');+ expect(within(reopened).getByRole('switch', { name: 'Generative UI' })).toHaveAttribute('aria-checked', 'true');+ });- fireEvent.click(screen.getByRole('button', { name: 'Save agent' }));- const dialog = screen.getByRole('dialog', { name: 'Save agent' });- fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'dup' } });- fireEvent.click(getSubmitButton(dialog));+ it('opens model editing as a stacked dialog', async () => {+ renderButton();+ fireEvent.click(screen.getByRole('button', { name: 'Save Agent' }));+ const saveDialog = await screen.findByRole('dialog', { name: 'Save agent' });+ fireEvent.click(within(saveDialog).getByRole('button', { name: 'Edit Model' }));++ const modelDialog = document.querySelectorAll('dialog')[1];+ expect(modelDialog).toBeInstanceOf(HTMLDialogElement);+ if (!(modelDialog instanceof HTMLDialogElement)) throw new Error('expected stacked model dialog');+ expect(modelDialog).toHaveAttribute('aria-label', 'Edit model');+ expect(saveDialog).toHaveAttribute('open');+ expect(modelDialog).toHaveAttribute('open');+ fireEvent.click(await within(modelDialog).findByRole('option', { name: 'claude-sonnet-4-6' }));+ expect(within(saveDialog).getByText('claude-sonnet-4-6')).toBeInTheDocument();+ });- await waitFor(() => {- expect(screen.getByText('Name taken')).toBeInTheDocument();+ it('submits one explicit create request and adopts the persisted session spec', async () => {+ const saveAgent = vi.fn(async (): Promise<SaveAgentResult> => ({+ agentId: 'agent-1',+ sessionUpdatedAt: '2026-08-12T08:00:00.000Z',+ }));+ renderButton({ saveAgent });+ fireEvent.click(screen.getByRole('button', { name: 'Save Agent' }));+ const dialog = await screen.findByRole('dialog', { name: 'Save agent' });+ fireEvent.change(within(dialog).getByLabelText('Agent name'), { target: { value: 'my-agent' } });+ fireEvent.click(within(dialog).getByRole('switch', { name: 'Generative UI' }));+ fireEvent.click(within(dialog).getByRole('button', { name: 'Save changes' }));++ await waitFor(() => expect(saveAgent).toHaveBeenCalledOnce());+ expect(saveAgent).toHaveBeenCalledWith({+ agentName: 'my-agent',+ agentSpec: {+ model: { name: 'openai/gpt-4.1', params: undefined },+ instructions: 'Be helpful.',+ mcpServers: [{ id: 'github', name: 'GitHub' }],+ skills: [{ id: 'research', name: 'Research' }],+ config: {+ generativeUi: { enabled: false },+ dynamicSubAgents: { enabled: true },+ askUserQuestions: { enabled: true },+ },+ },+ intent: 'create',+ sessionId: 'draft-1',});- expect(screen.getByRole('dialog', { name: 'Save agent' })).toBeInTheDocument();+ await waitFor(() =>+ expect(adoptAgentSpec).toHaveBeenCalledWith({+ agentSpec: expect.objectContaining({ model: { name: 'openai/gpt-4.1', params: undefined } }),+ updatedAt: '2026-08-12T08:00:00.000Z',+ }),+ );});- it('shows Update Agent on an empty library Edit and prefills name', async () => {- function EditSeed() {- const shell = useShellMode();- const seeded = useRef(false);- useEffect(() => {- if (seeded.current) return;- seeded.current = true;- shell.selectLibraryAgent({- isMutable: true,- agentId: 'writer',- agentName: 'writer',- agentSpec: {- model: { name: 'openai-main/gpt-4.1' },- instructions: 'Write release notes.',+ it('preserves opaque mount fields while adding catalog selections', async () => {+ agentSpec = {+ model: { name: 'openai/gpt-4.1' },+ mcpServers: [{ id: 'github', name: 'GitHub', enableTools: ['@read-only'], config: { project: 'sdk' } }],+ skills: [{ id: 'research', name: 'Research', fqn: 'skills/research:1', config: { depth: 2 } }],+ };+ const saveAgent = vi.fn(async (): Promise<SaveAgentResult> => ({ agentId: 'agent-1' }));+ renderButton({ saveAgent });+ fireEvent.click(screen.getByRole('button', { name: 'Save Agent' }));+ const saveDialog = await screen.findByRole('dialog', { name: 'Save agent' });+ fireEvent.change(within(saveDialog).getByLabelText('Agent name'), { target: { value: 'preserved-agent' } });++ fireEvent.click(within(saveDialog).getByRole('button', { name: 'Edit MCP servers' }));+ const mcpDialog = await findStackedDialog('Edit MCP servers');+ fireEvent.click(await within(mcpDialog).findByRole('menuitemcheckbox', { name: /Slack/ }));+ fireEvent.click(within(mcpDialog).getByRole('button', { name: 'Close' }));++ fireEvent.click(within(saveDialog).getByRole('button', { name: 'Edit Skills' }));+ const skillsDialog = await findStackedDialog('Edit skills');+ fireEvent.click(await within(skillsDialog).findByRole('menuitemcheckbox', { name: /Writing/ }));+ fireEvent.click(within(skillsDialog).getByRole('button', { name: 'Close' }));+ fireEvent.click(within(saveDialog).getByRole('button', { name: 'Save changes' }));++ await waitFor(() => expect(saveAgent).toHaveBeenCalledOnce());+ expect(saveAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ agentSpec: expect.objectContaining({+ mcpServers: [+ { id: 'github', name: 'GitHub', enableTools: ['@read-only'], config: { project: 'sdk' } },+ { id: 'slack', name: 'Slack' },+ ],+ skills: [+ { id: 'research', name: 'Research', fqn: 'skills/research:1', config: { depth: 2 } },+ { id: 'writing', name: 'Writing' },+ ],+ }),+ }),+ );+ });++ it('allows unavailable selected connectors and skills to be removed', async () => {+ const saveAgent = vi.fn(async (): Promise<SaveAgentResult> => ({ agentId: 'agent-1' }));+ renderButton({+ saveAgent,+ serverOverrides: {+ getCapabilities: async () => ({+ data: {+ sandbox: { enabled: true },+ skill: { enabled: false, reason: 'Configure a sandbox provider' },},- });- }, [shell]);- return <SaveAgentButton />;- }-- renderSaveAgent({- messages: [],- agentConfig: { mode: 'AgentLibraryWithComposer' },- children: <EditSeed />,+ }),+ getMcp: async () => [{ id: 'github', name: 'GitHub', authenticated: false }],+ },});+ fireEvent.click(screen.getByRole('button', { name: 'Save Agent' }));+ const saveDialog = await screen.findByRole('dialog', { name: 'Save agent' });+ fireEvent.change(within(saveDialog).getByLabelText('Agent name'), { target: { value: 'trimmed-agent' } });++ fireEvent.click(within(saveDialog).getByRole('button', { name: 'Edit MCP servers' }));+ const mcpDialog = await findStackedDialog('Edit MCP servers');+ fireEvent.click(await within(mcpDialog).findByRole('menuitemcheckbox', { name: /GitHub/ }));+ fireEvent.click(within(mcpDialog).getByRole('button', { name: 'Close' }));++ fireEvent.click(within(saveDialog).getByRole('button', { name: 'Edit Skills' }));+ const skillsDialog = await findStackedDialog('Edit skills');+ fireEvent.click(await within(skillsDialog).findByRole('menuitemcheckbox', { name: /Research/ }));+ fireEvent.click(within(skillsDialog).getByRole('button', { name: 'Close' }));+ fireEvent.click(within(saveDialog).getByRole('button', { name: 'Save changes' }));++ await waitFor(() => expect(saveAgent).toHaveBeenCalledOnce());+ expect(saveAgent).toHaveBeenCalledWith(+ expect.objectContaining({+ agentSpec: expect.objectContaining({ mcpServers: [], skills: [] }),+ }),+ );+ });++ it('keeps the save form immutable until an in-flight request settles', async () => {+ const pending = deferred<SaveAgentResult>();+ renderButton({ saveAgent: vi.fn(() => pending.promise) });+ fireEvent.click(screen.getByRole('button', { name: 'Save Agent' }));+ const dialog = await screen.findByRole('dialog', { name: 'Save agent' });+ fireEvent.change(within(dialog).getByLabelText('Agent name'), { target: { value: 'pending-agent' } });+ fireEvent.click(within(dialog).getByRole('button', { name: 'Save changes' }));++ expect(within(dialog).getByLabelText('Agent name')).toBeDisabled();+ expect(within(dialog).getByLabelText('Instructions')).toBeDisabled();+ expect(within(dialog).getByRole('button', { name: 'Edit Model' })).toBeDisabled();+ expect(within(dialog).getByRole('switch', { name: 'Generative UI' })).toBeDisabled();+ expect(within(dialog).getByRole('button', { name: 'Cancel' })).toBeDisabled();++ pending.resolve({ agentId: 'agent-1' });+ await waitFor(() => expect(screen.queryByRole('dialog', { name: 'Save agent' })).not.toBeInTheDocument());+ });- await waitFor(() => {- expect(screen.getByRole('button', { name: 'Update Agent' })).toBeInTheDocument();+ it('surfaces API-shaped save errors', async () => {+ renderButton({+ saveAgent: vi.fn(async () => {+ throw { body: { error: { message: 'Agent name already exists' } } };+ }),});+ fireEvent.click(screen.getByRole('button', { name: 'Save Agent' }));+ const dialog = await screen.findByRole('dialog', { name: 'Save agent' });+ fireEvent.change(within(dialog).getByLabelText('Agent name'), { target: { value: 'duplicate' } });+ fireEvent.click(within(dialog).getByRole('button', { name: 'Save changes' }));- fireEvent.click(screen.getByRole('button', { name: 'Update Agent' }));- expect(screen.getByRole('dialog', { name: 'Update Agent' })).toBeInTheDocument();- const nameInput = screen.getByLabelText('Name');- expect(nameInput).toHaveValue('writer');- expect(nameInput).toBeDisabled();- expect(screen.getByLabelText('System instructions')).toHaveValue('Write release notes.');+ expect(await within(dialog).findByRole('alert')).toHaveTextContent('Agent name already exists');});});diff --git a/packages/trueforge-ui-sdk/test/atoms/draft/DraftCatalogProvider.test.tsx b/packages/trueforge-ui-sdk/test/atoms/draft/DraftCatalogProvider.test.tsxindex f5012ddb9..553e9519c 100644--- a/packages/trueforge-ui-sdk/test/atoms/draft/DraftCatalogProvider.test.tsx+++ b/packages/trueforge-ui-sdk/test/atoms/draft/DraftCatalogProvider.test.tsx@@ -199,4 +199,36 @@ describe('DraftCatalogProvider', () => {expect(getModels).toHaveBeenCalledTimes(1);expect(getSkills).toHaveBeenCalledTimes(1);});++ it('uses the nearest server when catalog providers are nested', async () => {+ const outerGetModels = vi.fn(async () => []);+ const innerGetModels = vi.fn(async () => [+ {+ id: 'inner-model',+ name: 'inner/model',+ provider: { name: 'Inner' },+ properties: {},+ },+ ]);+ const outerServer = createMockAgentUIServer({ getModels: outerGetModels });+ const innerServer = createMockAgentUIServer({ getModels: innerGetModels });++ render(+ <ServerProvider server={outerServer}>+ <DraftCatalogProvider>+ <ServerProvider server={innerServer}>+ <DraftCatalogProvider>+ <CatalogProbe />+ </DraftCatalogProvider>+ </ServerProvider>+ </DraftCatalogProvider>+ </ServerProvider>,+ );++ fireEvent.click(screen.getByRole('button', { name: 'Load catalog' }));++ await waitFor(() => expect(screen.getByTestId('models')).toHaveTextContent('inner/model'));+ expect(innerGetModels).toHaveBeenCalledOnce();+ expect(outerGetModels).not.toHaveBeenCalled();+ });});diff --git a/packages/trueforge-ui-sdk/test/atoms/draft/DraftComposerSections.test.tsx b/packages/trueforge-ui-sdk/test/atoms/draft/DraftComposerSections.test.tsxindex acadb7e13..ca0dcb6ed 100644--- a/packages/trueforge-ui-sdk/test/atoms/draft/DraftComposerSections.test.tsx+++ b/packages/trueforge-ui-sdk/test/atoms/draft/DraftComposerSections.test.tsx@@ -59,16 +59,12 @@ describe('draft composer sections', () => {updateAgentSpec.mockReset();});- it('composes selection chips and forwards attachment behavior from the left section', () => {+ it('composes the Tools count and standalone attachment control', () => {const onAttach = vi.fn();render(<DraftSections onAttach={onAttach} />);- expect(screen.getByText('1 Connector')).toBeInTheDocument();- expect(screen.getByText('2 Skills')).toBeInTheDocument();-- fireEvent.click(screen.getByRole('button', { name: 'Add connectors, skills, or attachments' }));- fireEvent.click(screen.getByRole('button', { name: 'Attachment' }));- fireEvent.click(screen.getByRole('button', { name: /Add files or photos/ }));+ expect(screen.getByRole('button', { name: 'Tools (3)' })).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Attach a file' }));expect(onAttach).toHaveBeenCalledTimes(1);});@@ -83,12 +79,12 @@ describe('draft composer sections', () => {it('propagates disabled and running state to composed controls', async () => {const { rerender } = render(<DraftSections disabled />);- expect(screen.getByRole('button', { name: 'Add connectors, skills, or attachments' })).toBeDisabled();+ expect(screen.getByRole('button', { name: 'Tools (3)' })).toBeDisabled();expect(await screen.findByTitle('Select model')).toBeDisabled();expect(await screen.findByTitle('Select reasoning effort')).toBeDisabled();rerender(<DraftSections isRunning />);- expect(screen.getByRole('button', { name: 'Add connectors, skills, or attachments' })).toBeDisabled();+ expect(screen.getByRole('button', { name: 'Tools (3)' })).toBeDisabled();expect(await screen.findByTitle('Select model')).toBeDisabled();expect(await screen.findByTitle('Select reasoning effort')).toBeDisabled();});diff --git a/packages/trueforge-ui-sdk/test/atoms/draft/DraftCompositeSelector.test.tsx b/packages/trueforge-ui-sdk/test/atoms/draft/DraftCompositeSelector.test.tsxindex 9ab58816c..e27fc8957 100644--- a/packages/trueforge-ui-sdk/test/atoms/draft/DraftCompositeSelector.test.tsx+++ b/packages/trueforge-ui-sdk/test/atoms/draft/DraftCompositeSelector.test.tsx@@ -1,22 +1,12 @@// @vitest-environment jsdom-import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';+import { act, fireEvent, render, screen } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { DraftCatalogProvider } from '@/atoms/draft/DraftCatalogProvider.js';-import {- DraftCompositeSelector,- DraftSelectionChips,- type DraftCompositeSelectorProps,-} from '@/atoms/draft/DraftCompositeSelector.js';+import { DraftCompositeSelector } from '@/atoms/draft/DraftCompositeSelector.js';import { ServerProvider } from '@/server/ServerContext.js';-import type {- AgentBuilderCapabilitiesResponse,- AgentSpec,- AgentUIServer,- CatalogServer,- ConnectorState,-} from '@/server/types.js';-import { createMockAgentUIServer, createMockCatalog } from '../../server/mockServer.js';+import type { AgentSpec } from '@/server/types.js';+import { createMockAgentUIServer } from '../../server/mockServer.js';let agentSpec: AgentSpec;const updateAgentSpec = vi.fn();@@ -26,36 +16,25 @@ vi.mock('@truefoundry/assistant-ui-runtime', () => ({useTrueFoundryUpdateAgentSpec: () => updateAgentSpec,}));-type RenderSelectorOptions = {- props?: DraftCompositeSelectorProps;- getCapabilities?: () => Promise<AgentBuilderCapabilitiesResponse>;- getSkills?: AgentUIServer['getSkills'];- getMcp?: AgentUIServer['getMcp'];- catalog?: CatalogServer;-};--function renderSelector({ props = {}, getCapabilities, getSkills, getMcp, catalog }: RenderSelectorOptions = {}) {+function renderSelector({ onAttach }: { onAttach?: () => void } = {}) {const server = createMockAgentUIServer({- ...(getCapabilities === undefined ? {} : { getCapabilities }),- ...(catalog === undefined ? {} : { catalog }),- getSkills:- getSkills ??- (async () => [- { id: 'research', name: 'Research', description: 'Find relevant sources' },- { id: 'writer', name: 'Writer', description: 'Draft polished copy' },- ]),- getMcp:- getMcp ??- (async () => [- { id: 'github', name: 'GitHub', description: 'Code hosting' },- { id: 'slack', name: 'Slack', description: 'Team messages' },- ]),+ getCapabilities: async () => ({+ data: {+ sandbox: { enabled: true },+ skill: { enabled: true },+ },+ }),+ getModels: async () => [],+ getSkills: async () => [{ id: 'research', name: 'Research' }],+ getMcp: async () => [+ { id: 'github', name: 'GitHub', authenticated: true },+ { id: 'slack', name: 'Slack', authenticated: true },+ ],});-return render(<ServerProvider server={server}><DraftCatalogProvider>- <DraftCompositeSelector {...props} />+ <DraftCompositeSelector onAttach={onAttach} /></DraftCatalogProvider></ServerProvider>,);@@ -76,280 +55,92 @@ describe('DraftCompositeSelector', () => {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' }));-- const github = await screen.findByRole('menuitemcheckbox', { name: /GitHub/ });- 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('shows an unauthenticated DCR connector, authorizes it, and refetches connectors', async () => {- const pendingConnector = {- id: 'linear',- name: 'Linear',- description: 'Issue tracking',- auth: { type: 'dcr' as const },- requiresAuth: true,- authenticated: false,- };- const connectedConnector = { ...pendingConnector, requiresAuth: false, authenticated: true };- const getMcp = vi- .fn<() => Promise<ConnectorState[]>>()- .mockResolvedValueOnce([pendingConnector])- .mockResolvedValueOnce([connectedConnector]);- const authenticateConnector = vi.fn(async () => ({ status: 'AUTHENTICATED' }));- const defaultCatalog = createMockCatalog();- const catalog = createMockCatalog({- connectorCatalog: {- ...defaultCatalog.connectorCatalog,- authenticateConnector,- },- });-- renderSelector({ getMcp, catalog });- fireEvent.click(screen.getByRole('button', { name: 'Add connectors, skills, or attachments' }));+ it('shows one combined Tools count only for a valid model', () => {+ const view = renderSelector();+ expect(screen.getByRole('button', { name: 'Tools (2)' })).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Tools (2)' }));+ expect(screen.getByRole('dialog', { name: 'Add to composer' })).toBeInTheDocument();- const connect = await screen.findByRole('button', { name: 'Connect Linear' });- const linear = screen.getByRole('menuitemcheckbox', { name: /Linear/ });- expect(linear).toHaveAttribute('aria-checked', 'false');- fireEvent.click(linear);- expect(linear).toHaveAttribute('aria-checked', 'true');- fireEvent.click(connect);- expect(linear).toHaveAttribute('aria-checked', 'true');-- await waitFor(() =>- expect(authenticateConnector).toHaveBeenCalledWith({- id: 'linear',- redirectURL: expect.stringContaining('screenType=mcp-auth'),- }),+ agentSpec = { ...agentSpec, model: { name: ' ' } };+ view.rerender(+ <ServerProvider server={createMockAgentUIServer()}>+ <DraftCatalogProvider>+ <DraftCompositeSelector />+ </DraftCatalogProvider>+ </ServerProvider>,);- await waitFor(() => expect(getMcp).toHaveBeenCalledTimes(2));- await waitFor(() => expect(screen.getByRole('menuitemcheckbox', { name: /Linear/ })).toBeEnabled());- expect(screen.queryByRole('button', { name: 'Connect Linear' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: /Tools/ })).not.toBeInTheDocument();+ expect(screen.queryByRole('dialog', { name: 'Add to composer' })).not.toBeInTheDocument();});- it('lists selectable connectors before connectors that require connection', async () => {- agentSpec = {- model: { name: 'openai/gpt-4.1' },- mcpServers: [],- skills: [],- };- const pendingConnector = {- id: 'linear',- name: 'Linear',- auth: { type: 'dcr' as const },- requiresAuth: true,- authenticated: false,- };- const readyConnector = {- id: 'github',- name: 'GitHub',- requiresAuth: false,- authenticated: true,- };-- renderSelector({- getMcp: async () => [pendingConnector, readyConnector],- catalog: createMockCatalog(),- });- fireEvent.click(screen.getByRole('button', { name: 'Add connectors, skills, or attachments' }));+ it('renders attachment as a standalone tooltip control', () => {+ const onAttach = vi.fn();+ renderSelector({ onAttach });- const dialog = await screen.findByRole('dialog', { name: 'Add to composer' });- const readyRow = within(dialog).getByRole('menuitemcheckbox', { name: /GitHub/ });- const connectButton = within(dialog).getByRole('button', { name: 'Connect Linear' });- expect(readyRow.compareDocumentPosition(connectButton)).toBe(Node.DOCUMENT_POSITION_FOLLOWING);+ const attach = screen.getByRole('button', { name: 'Attach a file' });+ fireEvent.mouseEnter(attach);+ expect(screen.getByRole('tooltip')).toHaveTextContent('Attach a file');+ fireEvent.click(attach);+ expect(onAttach).toHaveBeenCalledOnce();+ expect(screen.queryByRole('dialog', { name: 'Add to composer' })).not.toBeInTheDocument();});- it('hydrates name-only wire mounts so a toggle does not wipe them', async () => {- agentSpec = {- model: { name: 'openai/gpt-4.1' },- // Harness round-trip: id stripped; catalog keys by name.- mcpServers: [{ name: 'slack' }],- skills: [{ name: 'research' }],- };- renderSelector({- getSkills: async () => [- { id: 'research', name: 'research', description: 'Find relevant sources' },- { id: 'writer', name: 'writer', description: 'Draft polished copy' },- ],- getMcp: async () => [- { id: 'github', name: 'github', description: 'Code hosting' },- { id: 'slack', name: 'slack', description: 'Team messages' },- ],- });-- fireEvent.click(screen.getByRole('button', { name: 'Add connectors, skills, or attachments' }));- const slack = await screen.findByRole('menuitemcheckbox', { name: /slack/ });- expect(slack).toHaveAttribute('aria-checked', 'true');-- fireEvent.click(screen.getByRole('menuitemcheckbox', { name: /github/ }));+ it('debounces connector changes into one draft update', async () => {+ renderSelector();+ fireEvent.click(screen.getByRole('button', { name: 'Tools (2)' }));+ fireEvent.click(await screen.findByRole('menuitemcheckbox', { name: /GitHub/ }));+ expect(updateAgentSpec).not.toHaveBeenCalled();await act(async () => {await vi.advanceTimersByTimeAsync(300);});-expect(updateAgentSpec).toHaveBeenCalledWith({mcpServers: [- { id: 'slack', name: 'slack' },- { id: 'github', name: 'github' },+ { id: 'slack', name: 'Slack' },+ { id: 'github', name: 'GitHub' },],- skills: [{ id: 'research', name: 'research' }],+ skills: [{ id: 'research', name: 'Research' }],});});- it('switches tabs, resets search, and removes a selected skill on close flush', async () => {+ it('treats omitted capabilities as enabled and patches only capability branches', async () => {+ agentSpec = { ...agentSpec, config: {} };renderSelector();- fireEvent.click(screen.getByRole('button', { name: 'Add connectors, skills, or attachments' }));- await screen.findByRole('menuitemcheckbox', { name: /GitHub/ });-- fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'github' } });- expect(screen.queryByRole('menuitemcheckbox', { name: /Slack/ })).not.toBeInTheDocument();-- fireEvent.click(screen.getByRole('button', { name: /Skills/ }));- const skillSearch = screen.getByRole('searchbox');- expect(skillSearch).toHaveValue('');- expect(skillSearch).toHaveAttribute('placeholder', 'Search skills...');+ fireEvent.click(screen.getByRole('button', { name: 'Tools (2)' }));+ fireEvent.click(screen.getByRole('button', { name: /Capabilities/ }));- const dialog = screen.getByRole('dialog', { name: 'Add to composer' });- const research = within(dialog).getByRole('menuitemcheckbox', { name: /Research/ });- expect(research).toHaveAttribute('aria-checked', 'true');- expect(within(dialog).getByRole('menuitemcheckbox', { name: /Writer/ })).toBeInTheDocument();- fireEvent.click(research);-- // Close before debounce — flush pending local state.- fireEvent.click(screen.getByRole('button', { name: 'Add connectors, skills, or attachments' }));+ const generativeUi = screen.getByRole('switch', { name: 'Generative UI' });+ expect(generativeUi).toHaveAttribute('aria-checked', 'true');+ fireEvent.click(generativeUi);expect(updateAgentSpec).toHaveBeenCalledWith({- mcpServers: [{ id: 'slack', name: 'Slack' }],- skills: [],+ config: {+ generativeUi: { enabled: false },+ dynamicSubAgents: { enabled: true },+ askUserQuestions: { enabled: true },+ },});});- it('forwards attachment requests and closes the picker', async () => {- const onAttach = vi.fn();- renderSelector({ props: { onAttach } });- const trigger = screen.getByRole('button', { name: 'Add connectors, skills, or attachments' });- fireEvent.click(trigger);- await screen.findByRole('menuitemcheckbox', { name: /GitHub/ });- fireEvent.click(screen.getByRole('button', { name: 'Attachment' }));- fireEvent.click(screen.getByRole('button', { name: /Add files or photos/ }));-- expect(onAttach).toHaveBeenCalledTimes(1);- expect(screen.queryByRole('dialog', { name: 'Add to composer' })).not.toBeInTheDocument();- expect(trigger).toHaveAttribute('aria-expanded', 'false');- });-- it('disables available skills while allowing selected skills to be removed', async () => {- renderSelector({- getCapabilities: async () => ({- data: {- sandbox: { enabled: false },- skill: { enabled: false, reason: 'Select Sandbox first' },- },- }),- });- fireEvent.click(screen.getByRole('button', { name: 'Add connectors, skills, or attachments' }));- fireEvent.click(screen.getByRole('button', { name: /Skills/ }));-- expect(await screen.findByRole('status')).toHaveTextContent('Select Sandbox first');- const research = screen.getByRole('menuitemcheckbox', { name: /Research/ });- expect(research).toBeEnabled();- expect(screen.getByRole('menuitemcheckbox', { name: /Writer/ })).toBeDisabled();- fireEvent.click(research);-- // Close before debounce — flush pending local state.- fireEvent.click(screen.getByRole('button', { name: 'Add connectors, skills, or attachments' }));+ it('folds dirty connector toggles into a capability update', async () => {+ renderSelector();+ fireEvent.click(screen.getByRole('button', { name: 'Tools (2)' }));+ fireEvent.click(await screen.findByRole('menuitemcheckbox', { name: /GitHub/ }));+ fireEvent.click(screen.getByRole('button', { name: /Capabilities/ }));+ fireEvent.click(screen.getByRole('switch', { name: 'Generative UI' }));+ expect(updateAgentSpec).toHaveBeenCalledTimes(1);expect(updateAgentSpec).toHaveBeenCalledWith({- mcpServers: [{ id: 'slack', name: 'Slack' }],- skills: [],- });- });-- it('disables available skills until capabilities load', async () => {- renderSelector({- getCapabilities: () => new Promise<AgentBuilderCapabilitiesResponse>(() => {}),- });- fireEvent.click(screen.getByRole('button', { name: 'Add connectors, skills, or attachments' }));- fireEvent.click(screen.getByRole('button', { name: /Skills/ }));-- expect(await screen.findByRole('menuitemcheckbox', { name: /Research/ })).toBeEnabled();- expect(screen.getByRole('menuitemcheckbox', { name: /Writer/ })).toBeDisabled();- });-- it('cannot open while disabled or running', () => {- const { rerender } = render(<DraftCompositeSelector disabled />);-- expect(screen.getByRole('button', { name: 'Add connectors, skills, or attachments' })).toBeDisabled();-- rerender(<DraftCompositeSelector isRunning />);- expect(screen.getByRole('button', { name: 'Add connectors, skills, or attachments' })).toBeDisabled();- });-});--describe('DraftSelectionChips', () => {- beforeEach(() => {- agentSpec = {- model: { name: 'openai/gpt-4.1' },mcpServers: [{ id: 'slack', name: 'Slack' },{ id: 'github', name: 'GitHub' },],skills: [{ id: 'research', name: 'Research' }],- };- });-- it('shows selected entity names in tooltips on hover', () => {- render(<DraftSelectionChips />);-- const connectorsChip = screen.getByRole('button', { name: 'View 2 selected connectors' });- fireEvent.mouseEnter(connectorsChip);- expect(screen.getByRole('tooltip')).toHaveTextContent('Slack');- expect(screen.getByRole('tooltip')).toHaveTextContent('GitHub');- fireEvent.mouseLeave(connectorsChip);-- const skillsChip = screen.getByRole('button', { name: 'View 1 selected skill' });- fireEvent.mouseEnter(skillsChip);- expect(screen.getByRole('tooltip')).toHaveTextContent('Research');- });-- it('opens the composite selector on the matching tab when a chip is clicked', async () => {- renderSelector();-- const skillsChip = screen.getByRole('button', { name: 'View 1 selected skill' });- fireEvent.mouseEnter(skillsChip);- expect(screen.getByRole('tooltip')).toBeInTheDocument();-- fireEvent.click(skillsChip);-- expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();- expect(await screen.findByRole('dialog', { name: 'Add to composer' })).toBeInTheDocument();- expect(screen.getByRole('button', { name: /Skills/ })).toHaveClass('text-text-primary');- expect(await screen.findByRole('menuitemcheckbox', { name: /Research/ })).toBeInTheDocument();-- fireEvent.click(screen.getByRole('button', { name: 'View 2 selected connectors' }));- expect(screen.getByRole('button', { name: /Connectors/ })).toHaveClass('text-text-primary');- expect(await screen.findByRole('menuitemcheckbox', { name: /Slack/ })).toBeInTheDocument();- });-- it('renders nothing when nothing is selected', () => {- agentSpec = { model: { name: 'openai/gpt-4.1' }, mcpServers: [], skills: [] };- const { container } = render(<DraftSelectionChips />);- expect(container).toBeEmptyDOMElement();+ config: {+ generativeUi: { enabled: false },+ dynamicSubAgents: { enabled: true },+ askUserQuestions: { enabled: true },+ },+ });});});diff --git a/packages/trueforge-ui-sdk/test/atoms/primitives/Switch.test.tsx b/packages/trueforge-ui-sdk/test/atoms/primitives/Switch.test.tsxnew file mode 100644index 000000000..68600e2a0--- /dev/null+++ b/packages/trueforge-ui-sdk/test/atoms/primitives/Switch.test.tsx@@ -0,0 +1,33 @@+// @vitest-environment jsdom+import { fireEvent, render, screen } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { Switch } from '@/atoms/primitives/Switch.js';++describe('Switch', () => {+ it('reports the next controlled value', () => {+ const onCheckedChange = vi.fn();+ const { rerender } = render(<Switch checked={false} aria-label="Capability" onCheckedChange={onCheckedChange} />);++ const control = screen.getByRole('switch', { name: 'Capability' });+ expect(control).toHaveAttribute('aria-checked', 'false');+ expect(control).toHaveClass('bg-text-secondary/35', 'focus-visible:ring-focus-ring/40');+ expect(control.firstElementChild).toHaveClass('bg-primary-bg');+ fireEvent.click(control);+ expect(onCheckedChange).toHaveBeenCalledWith(true);++ rerender(<Switch checked aria-label="Capability" onCheckedChange={onCheckedChange} />);+ expect(control).toHaveAttribute('aria-checked', 'true');+ expect(control).toHaveAttribute('data-state', 'checked');+ expect(control).toHaveClass('bg-primary-button-bg');+ expect(control.firstElementChild).toHaveClass('bg-primary-button-text');+ });++ it('does not change while disabled', () => {+ const onCheckedChange = vi.fn();+ render(<Switch checked={false} aria-label="Capability" disabled onCheckedChange={onCheckedChange} />);++ fireEvent.click(screen.getByRole('switch', { name: 'Capability' }));+ expect(onCheckedChange).not.toHaveBeenCalled();+ });+});diff --git a/packages/trueforge-ui-sdk/test/containers/SettingsBuilder/ConnectorDetails.test.tsx b/packages/trueforge-ui-sdk/test/containers/SettingsBuilder/ConnectorDetails.test.tsxindex b3a778c8f..28b7d412d 100644--- a/packages/trueforge-ui-sdk/test/containers/SettingsBuilder/ConnectorDetails.test.tsx+++ b/packages/trueforge-ui-sdk/test/containers/SettingsBuilder/ConnectorDetails.test.tsx@@ -28,7 +28,7 @@ function wrapperFor(tools: ToolBase[]) {getToolsByConnectorId: async () => tools,createConnector: async () => connector,updateConnector: async () => connector,- authenticateConnector: async () => connector,+ authenticateConnector: async () => ({ authorization_endpoint: '' }),disconnectConnector: async () => connector,},}),diff --git a/packages/trueforge-ui-sdk/test/containers/TrueforgeUI.test.tsx b/packages/trueforge-ui-sdk/test/containers/TrueforgeUI.test.tsxindex 98358063b..7b0cd34a5 100644--- a/packages/trueforge-ui-sdk/test/containers/TrueforgeUI.test.tsx+++ b/packages/trueforge-ui-sdk/test/containers/TrueforgeUI.test.tsx@@ -2,7 +2,7 @@import type { CatalogServer } from '@/server/types.js';import { useExternalStoreRuntime, type ThreadMessageLike } from '@assistant-ui/react';import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';-import { describe, expect, it, vi } from 'vitest';+import { beforeAll, describe, expect, it, vi } from 'vitest';import { createMockAgentUIServer, createMockCatalog } from '../server/mockServer.js';vi.mock('@truefoundry/assistant-ui-runtime', () => ({@@ -26,6 +26,8 @@ vi.mock('@truefoundry/assistant-ui-runtime', () => ({useTrueFoundryAgentSpec: () => ({agentSpec: { model: { name: 'openai-main/gpt-4.1' } },}),+ useTrueFoundryFlushAgentSpec: () => async () => {},+ useTrueFoundryAdoptAgentSpec: () => vi.fn(),useTrueFoundryUpdateAgentSpec: () => vi.fn(),}));@@ -55,6 +57,16 @@ function mockServer(catalog?: CatalogServer) {/** Minimal catalog stub — ShellActions only checks presence. */const stubCatalog = createMockCatalog();+beforeAll(() => {+ HTMLDialogElement.prototype.showModal = function showModal() {+ this.setAttribute('open', '');+ };+ HTMLDialogElement.prototype.close = function close() {+ this.removeAttribute('open');+ this.dispatchEvent(new Event('close'));+ };+});+describe('TrueforgeUI', () => {const server = mockServer();const layouts: ChatLayout[] = ['sidebar', 'drawer', 'dock', 'widget'];@@ -151,11 +163,49 @@ describe('TrueforgeUI', () => {expect(getMcp).toHaveBeenCalledTimes(2);});- fireEvent.click(screen.getByRole('button', { name: 'Add connectors, skills, or attachments' }));+ fireEvent.click(screen.getByRole('button', { name: 'Tools (0)' }));fireEvent.click(screen.getByRole('button', { name: /Skills/ }));expect(await screen.findByRole('status')).toHaveTextContent('Select Sandbox first');});+ it('shares catalog data with the Save Agent stacked editors', async () => {+ const getModels = vi.fn(async () => [+ {+ id: 'openai-main/gpt-4.1',+ name: 'openai-main/gpt-4.1',+ provider: { name: 'OpenAI' },+ properties: {},+ },+ ]);+ const getMcp = vi.fn(async () => [{ id: 'github', name: 'GitHub', authenticated: true }]);+ const getSkills = vi.fn(async () => [{ id: 'research', name: 'Research' }]);++ render(+ <TrueforgeUI+ server={createMockAgentUIServer({ getModels, getMcp, getSkills })}+ agentConfig={{ mode: 'AgentComposer' }}+ layout="sidebar"+ />,+ );++ fireEvent.click(await screen.findByRole('button', { name: 'Save Agent' }));+ const saveDialog = await screen.findByRole('dialog', { name: 'Save agent' });+ fireEvent.click(within(saveDialog).getByRole('button', { name: 'Edit Model' }));++ const modelDialog = document.querySelector('dialog[aria-label="Edit model"]');+ if (!(modelDialog instanceof HTMLDialogElement)) throw new Error('expected stacked model dialog');+ expect(await within(modelDialog).findByRole('option', { name: 'gpt-4.1' })).toBeInTheDocument();+ fireEvent.click(within(modelDialog).getByRole('button', { name: 'Close' }));++ fireEvent.click(within(saveDialog).getByRole('button', { name: 'Edit MCP servers' }));+ const mcpDialog = document.querySelector('dialog[aria-label="Edit MCP servers"]');+ if (!(mcpDialog instanceof HTMLDialogElement)) throw new Error('expected stacked MCP dialog');+ expect(await within(mcpDialog).findByText('GitHub')).toBeInTheDocument();+ expect(getModels).toHaveBeenCalledOnce();+ expect(getMcp).toHaveBeenCalledOnce();+ expect(getSkills).toHaveBeenCalledOnce();+ });+it('renders only the MCP authorization screen when requested by the URL', async () => {const originalUrl = window.location.href;const postMessage = vi.fn();diff --git a/packages/trueforge-ui-sdk/test/publicUiExports.test.ts b/packages/trueforge-ui-sdk/test/publicUiExports.test.tsindex 46c89d093..67852fb31 100644--- a/packages/trueforge-ui-sdk/test/publicUiExports.test.ts+++ b/packages/trueforge-ui-sdk/test/publicUiExports.test.ts@@ -68,6 +68,7 @@ const expectedRuntimeExports: Array<keyof typeof sdk> = ['ShellModeProvider','SlotsProvider','SubAgentCard',+ 'Switch','SyntaxHighlighter','ThemeProvider','Thread',diff --git a/packages/trueforge-ui-sdk/test/server/createTrueFoundryServer.test.ts b/packages/trueforge-ui-sdk/test/server/createTrueFoundryServer.test.tsindex 71c220630..a40c26614 100644--- a/packages/trueforge-ui-sdk/test/server/createTrueFoundryServer.test.ts+++ b/packages/trueforge-ui-sdk/test/server/createTrueFoundryServer.test.ts@@ -1,3 +1,4 @@+import type { SaveAgentResult } from '@/index.js';import type { CatalogServer } from '@/server/types.js';import { describe, expect, it, vi } from 'vitest';@@ -33,7 +34,7 @@ describe('createTrueFoundryServer', () => {const getSkills = vi.fn(async () => []);const getMcp = vi.fn(async () => []);const searchAgents = vi.fn(async () => [{ name: 'ask-ai-agent', agentId: 'ask-ai-agent' }]);- const saveAgent = vi.fn(async () => ({ agentId: 'agt_1' }));+ const saveAgent = vi.fn(async (): Promise<SaveAgentResult> => ({ agentId: 'agent-1' }));const server = createTrueFoundryServer({chatServer,@@ -165,7 +166,7 @@ describe('createTrueFoundryServer', () => {getSkills: async () => [],getMcp: async () => [],searchAgents: async () => [],- saveAgent: async () => ({ agentId: 'agt_1' }),+ saveAgent: async () => ({ agentId: 'agent-1' }),catalog,});