The open-source agent harness - the runtime layer that turns an LLM into a working agent.
Chore: Add agent filter in chat history (#670)
harshil-2096d2fdfc90e924
diff --git a/.changeset/agent-chat-navigation.md b/.changeset/agent-chat-navigation.mdnew file mode 100644index 000000000..412bf3041--- /dev/null+++ b/.changeset/agent-chat-navigation.md@@ -0,0 +1,5 @@+---+"@truefoundry/trueforge-ui": patch+---++Add agent-filtered chat history labels, preserve Try Agent and explicit history-filter intent in URL query state while resolving backend IDs, reset active chats when users change filters, keep Try Agent highlighted as chat, and route fresh agent builders at `/build-agent` before their session URL is assigned.diff --git a/.changeset/mcp-tool-sections.md b/.changeset/mcp-tool-sections.mdnew file mode 100644index 000000000..7f59c70fa--- /dev/null+++ b/.changeset/mcp-tool-sections.md@@ -0,0 +1,5 @@+---+"@truefoundry/trueforge-ui": patch+---++Section MCP tools in the Build Agent selector by read-only, others, and destructive annotations, with a read-only enable-all toggle.diff --git a/packages/trueforge-ui/docs/customization.md b/packages/trueforge-ui/docs/customization.mdindex c365c4caf..2bfba623f 100644--- a/packages/trueforge-ui/docs/customization.md+++ b/packages/trueforge-ui/docs/customization.md@@ -96,6 +96,7 @@ router should leave it off (the default).Places mirrored to the URL:- `/` — new chat / library landing (mode-dependent)+- `/build-agent` — new agent builder- `/agents/:agentName` — immutable "Try" of a library agent- `/sessions` — all-user Sessions browser (named agents and drafts)- `/sessions/:sessionId` — a specific chat session@@ -113,7 +114,12 @@ to keep that place overlay-only with no URL:withRouterroutes={{basename: '/app',- paths: { session: '/chats/:sessionId', libraryAgent: '/library/:agentId', settings: false },+ paths: {+ buildAgent: '/new-agent',+ session: '/chats/:sessionId',+ libraryAgent: '/library/:agentId',+ settings: false,+ },}}/>```@@ -142,6 +148,15 @@ Notes on behaviour:so a refresh still finds that row on page 1 without scrolling the list.- A `/sessions/:sessionId` link is resolved through `getSession` so the chatopens with its own agent binding and mutability rather than as a new draft.+- `/build-agent` is used for a fresh builder; after its draft session persists,+ the URL transitions to `/sessions/:sessionId`.+- Agent-filtered chat history keeps one intent key in the query string:+ `try_agent_name` hides the filter for a Try Agent flow, while+ `history_agent_name` shows an explicitly selected filter. Both values are+ display names; the shell resolves the backend agent id before listing sessions.+ Non-chat destinations such as Build Agent, Agents, Sessions, Schedules, and+ Settings clear this query state. User filter changes start a clean chat and+ reset history pagination; All Chats remains paginated in 20-session pages.- Unrecognized paths (and malformed escapes) normalize to the root place.- `/settings` is registered only while Settings chrome is available (catalogpresent and `capabilities.settings.enabled !== false`). When that gate isdiff --git a/packages/trueforge-ui/src/atoms/AgentHistoryFilterButton.tsx b/packages/trueforge-ui/src/atoms/AgentHistoryFilterButton.tsxindex 36d91b551..92cea89cb 100644--- a/packages/trueforge-ui/src/atoms/AgentHistoryFilterButton.tsx+++ b/packages/trueforge-ui/src/atoms/AgentHistoryFilterButton.tsx@@ -5,7 +5,7 @@ import { createPortal } from 'react-dom';import { Icon } from '../icons/Icon.js';import { useOptionalServer } from '../server/ServerContext.js';-import { libraryAgentId, useOptionalShellMode } from '../server/ShellModeContext.js';+import { libraryAgentId, useOptionalShellMode, type HistoryAgentFilter } from '../server/ShellModeContext.js';import { auiButtonClass } from './lib/buttonClasses.js';import { cn } from './lib/cn.js';import { useCompactLayout } from './lib/CompactLayoutContext.js';@@ -79,8 +79,14 @@ export function AgentHistoryFilterButton() {if (!enabled) return null;- const pick = (agentId: string | null) => {- shell?.setHistoryAgentFilter(agentId);+ // Reset the active session so the newly scoped history starts from a clean runtime and first page.+ const pick = (filter: HistoryAgentFilter | null) => {+ if (shell?.isComposerEnabled === true) {+ shell.openDraft();+ } else {+ shell?.openLibraryHome();+ }+ shell?.setHistoryAgentFilter(filter);setOpen(false);};@@ -120,7 +126,7 @@ export function AgentHistoryFilterButton() {<>{agents.map(agent => {const id = libraryAgentId(agent);- const active = selected === id;+ const active = selected?.agentId === id;return (<DropdownMenuItemkey={id}@@ -128,7 +134,7 @@ export function AgentHistoryFilterButton() {'justify-between gap-2 text-left',active && 'bg-dropdown-selected-item-bg text-dropdown-selected-item-text',)}- onClick={() => pick(id)}+ onClick={() => pick({ agentId: id, agentName: agent.name, intent: 'history' })}><span className="min-w-0 truncate">{agent.name}</span>{active ? <Icon name="check" className="size-3.5 shrink-0" /> : null}@@ -155,7 +161,9 @@ export function AgentHistoryFilterButton() {<buttonref={buttonRef}type="button"- aria-label={selected != null ? `Filter chat history by agent (${selected})` : 'Filter chat history by agent'}+ aria-label={+ selected != null ? `Filter chat history by agent (${selected.agentName})` : 'Filter chat history by agent'+ }aria-haspopup={useSheet ? 'dialog' : 'menu'}aria-expanded={open}aria-controls={open ? menuId : undefined}diff --git a/packages/trueforge-ui/src/atoms/draft/AgentMcpEditorContent.tsx b/packages/trueforge-ui/src/atoms/draft/AgentMcpEditorContent.tsxindex 7e0d2790c..dd1bb20c3 100644--- a/packages/trueforge-ui/src/atoms/draft/AgentMcpEditorContent.tsx+++ b/packages/trueforge-ui/src/atoms/draft/AgentMcpEditorContent.tsx@@ -15,6 +15,7 @@ import { Switch } from '../primitives/Switch.js';import { Tooltip } from '../primitives/Tooltip.js';import { editableMountsFromSpec, enabledToolsFromMount, withEnabledTools } from './agentConfigMounts.js';import { connectorsWithSelectedStubs } from './mcpConnectorStubs.js';+import { MCP_TOOL_SECTION_LABELS, MCP_TOOL_SECTION_ORDER, partitionMcpToolsBySection } from './mcpToolSections.js';export type AgentMcpEditorContentProps = {spec: AgentSpec;@@ -133,6 +134,11 @@ export function AgentMcpEditorContent({const normalizedToolQuery = toolQuery.trim().toLowerCase();const filteredTools =normalizedToolQuery === '' ? tools : tools.filter(tool => tool.name.toLowerCase().includes(normalizedToolQuery));+ const toolSections = partitionMcpToolsBySection(filteredTools);+ const readOnlyTools = partitionMcpToolsBySection(tools)['read-only'];+ const readOnlyNames = readOnlyTools.map(tool => tool.name);+ const allReadOnlyEnabled =+ readOnlyNames.length > 0 && (enabledTools === 'all' || readOnlyNames.every(name => enabledTools.includes(name)));const updateMount = (mountId: string, value: object) => {onChange({@@ -153,6 +159,26 @@ export function AgentMcpEditorContent({onSelectConnector(match?.id ?? mount.id);};+ const setEnabledToolNames = (next: string[]) => {+ if (!selectedConnector) return;+ if (next.length === 0) {+ if (activeMount) removeMount(activeMount.id);+ return;+ }+ if (activeMount) {+ updateMount(activeMount.id, withEnabledTools(activeMount.value, next));+ return;+ }+ if (!canAddActiveConnector) return;+ onChange({+ ...spec,+ mcpServers: [+ ...(spec.mcpServers ?? []),+ withEnabledTools({ id: selectedConnector.id, name: selectedConnector.name }, next),+ ],+ });+ };+const toggleTool = (toolName: string) => {if (!selectedConnector) return;if (!activeMount) {@@ -169,11 +195,26 @@ export function AgentMcpEditorContent({const current = enabledTools === 'all' ? tools.map(tool => tool.name) : enabledTools;const checked = current.includes(toolName);const next = checked ? current.filter(name => name !== toolName) : [...current, toolName];- if (next.length === 0) {- removeMount(activeMount.id);- } else {- updateMount(activeMount.id, withEnabledTools(activeMount.value, next));+ setEnabledToolNames(next);+ };++ const setAllReadOnlyTools = (enabled: boolean) => {+ if (!selectedConnector || readOnlyNames.length === 0) return;+ if (enabled) {+ if (enabledTools === 'all') return;+ const current = activeMount ? enabledTools : [];+ const merged = [...current];+ for (const name of readOnlyNames) {+ if (!merged.includes(name)) merged.push(name);+ }+ setEnabledToolNames(merged);+ return;}+ if (enabledTools === 'all') {+ setEnabledToolNames(tools.map(tool => tool.name).filter(name => !readOnlyNames.includes(name)));+ return;+ }+ setEnabledToolNames(enabledTools.filter(name => !readOnlyNames.includes(name)));};const connectDuringChat = () => {@@ -321,27 +362,63 @@ export function AgentMcpEditorContent({</div>) : null}{!toolsLoading- ? filteredTools.map(tool => {- const checked = enabledTools === 'all' || enabledTools.includes(tool.name);+ ? MCP_TOOL_SECTION_ORDER.map(sectionId => {+ const sectionTools = toolSections[sectionId];+ if (sectionTools.length === 0) return null;+ const onlyOthers =+ toolSections['read-only'].length === 0 && toolSections.destructive.length === 0;+ const showSectionHeader = sectionId !== 'others' || !onlyOthers;return (- <button- key={tool.id}- type="button"- role="menuitemcheckbox"- aria-checked={checked}- aria-label={tool.name}- disabled={!canAddActiveConnector && activeMount === undefined}- className="hover:bg-ghost-button-hover flex w-full cursor-pointer items-center gap-2 rounded-md px-2 py-2 text-left disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent"- onClick={() => toggleTool(tool.name)}- >- <ToolCheckbox checked={checked} />- <span className="min-w-0 flex-1">- <span className="text-text-primary block truncate text-sm font-medium">{tool.name}</span>- {tool.description ? (- <span className="text-text-secondary line-clamp-1 text-xs">{tool.description}</span>- ) : null}- </span>- </button>+ <div key={sectionId} className="mb-3">+ {showSectionHeader ? (+ <div className="flex items-center justify-between gap-3 px-2 py-2">+ <p+ className={cn(+ 'min-w-0 truncate text-sm font-semibold',+ sectionId === 'destructive' ? 'text-failure-bg' : 'text-text-primary',+ )}+ >+ {MCP_TOOL_SECTION_LABELS[sectionId]}+ </p>+ {sectionId === 'read-only' ? (+ <label className="text-text-secondary flex shrink-0 cursor-pointer items-center gap-2 text-xs has-[:disabled]:cursor-not-allowed">+ Enable All Read-only Tools+ <Switch+ checked={allReadOnlyEnabled}+ disabled={!canAddActiveConnector && activeMount === undefined}+ onCheckedChange={setAllReadOnlyTools}+ aria-label="Enable all read-only tools"+ />+ </label>+ ) : null}+ </div>+ ) : null}+ {sectionTools.map(tool => {+ const checked = enabledTools === 'all' || enabledTools.includes(tool.name);+ return (+ <button+ key={tool.id}+ type="button"+ role="menuitemcheckbox"+ aria-checked={checked}+ aria-label={tool.name}+ disabled={!canAddActiveConnector && activeMount === undefined}+ className="hover:bg-ghost-button-hover flex w-full cursor-pointer items-center gap-2 rounded-md px-2 py-2 text-left disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent"+ onClick={() => toggleTool(tool.name)}+ >+ <ToolCheckbox checked={checked} />+ <span className="min-w-0 flex-1">+ <span className="text-text-primary block truncate text-sm font-medium">+ {tool.name}+ </span>+ {tool.description ? (+ <span className="text-text-secondary line-clamp-1 text-xs">{tool.description}</span>+ ) : null}+ </span>+ </button>+ );+ })}+ </div>);}): null}diff --git a/packages/trueforge-ui/src/atoms/draft/mcpToolSections.ts b/packages/trueforge-ui/src/atoms/draft/mcpToolSections.tsnew file mode 100644index 000000000..f91fba49c--- /dev/null+++ b/packages/trueforge-ui/src/atoms/draft/mcpToolSections.ts@@ -0,0 +1,49 @@+import type { McpToolSelection } from '../../server/types.js';++export type McpToolSectionId = 'read-only' | 'others' | 'destructive';++export type McpToolAnnotations = {+ readOnlyHint?: boolean;+ destructiveHint?: boolean;+};++export function mcpToolAnnotations(tool: McpToolSelection): McpToolAnnotations | undefined {+ const raw = Reflect.get(tool, 'annotations');+ if (typeof raw !== 'object' || raw === null) return undefined;+ const readOnlyHint = Reflect.get(raw, 'readOnlyHint');+ const destructiveHint = Reflect.get(raw, 'destructiveHint');+ const annotations: McpToolAnnotations = {+ ...(typeof readOnlyHint === 'boolean' ? { readOnlyHint } : {}),+ ...(typeof destructiveHint === 'boolean' ? { destructiveHint } : {}),+ };+ return Object.keys(annotations).length > 0 ? annotations : undefined;+}++export function mcpToolSectionId(tool: McpToolSelection): McpToolSectionId {+ const annotations = mcpToolAnnotations(tool);+ if (annotations?.readOnlyHint === true) return 'read-only';+ if (annotations?.destructiveHint === true) return 'destructive';+ return 'others';+}++export const MCP_TOOL_SECTION_ORDER: readonly McpToolSectionId[] = ['read-only', 'others', 'destructive'];++export const MCP_TOOL_SECTION_LABELS: Record<McpToolSectionId, string> = {+ 'read-only': 'Read-only Actions',+ others: 'Other Actions',+ destructive: 'Destructive Actions',+};++export function partitionMcpToolsBySection(+ tools: readonly McpToolSelection[],+): Record<McpToolSectionId, McpToolSelection[]> {+ const sections: Record<McpToolSectionId, McpToolSelection[]> = {+ 'read-only': [],+ others: [],+ destructive: [],+ };+ for (const tool of tools) {+ sections[mcpToolSectionId(tool)].push(tool);+ }+ return sections;+}diff --git a/packages/trueforge-ui/src/atoms/lib/useSearchAgentsList.ts b/packages/trueforge-ui/src/atoms/lib/useSearchAgentsList.tsindex acc0e70ca..89f8498a6 100644--- a/packages/trueforge-ui/src/atoms/lib/useSearchAgentsList.ts+++ b/packages/trueforge-ui/src/atoms/lib/useSearchAgentsList.ts@@ -21,6 +21,22 @@ export async function searchAllAgents(return [...rows, ...(await searchAllAgents(server, offset + rows.length))];}+/** Exact-name queries can still span multiple server-filtered pages. */+export async function findAgentByName({+ server,+ agentName,+ offset = 0,+}: {+ server: Pick<AgentBuilderServer, 'searchAgents'>;+ agentName: string;+ offset?: number;+}): Promise<AgentLibraryEntry | undefined> {+ const rows = await server.searchAgents({ query: agentName, limit: SEARCH_AGENTS_PAGE_SIZE, offset });+ const match = rows.find(agent => agent.name === agentName);+ if (match != null || rows.length < SEARCH_AGENTS_PAGE_SIZE) return match;+ return findAgentByName({ server, agentName, offset: offset + rows.length });+}+export type UseSearchAgentsListOptions = {/** When false, no fetches run. */enabled: boolean;diff --git a/packages/trueforge-ui/src/containers/ThreadListContainer.tsx b/packages/trueforge-ui/src/containers/ThreadListContainer.tsxindex f88191ff4..f9ac4e641 100644--- a/packages/trueforge-ui/src/containers/ThreadListContainer.tsx+++ b/packages/trueforge-ui/src/containers/ThreadListContainer.tsx@@ -246,20 +246,29 @@ function RecentChatsSection({children,viewportRef,hideScrollbar,- showAgentFilter,}: {children: ReactNode;viewportRef: Ref<HTMLDivElement>;hideScrollbar: boolean;- showAgentFilter: boolean;}) {const shell = useOptionalShellMode();- const showFilter = showAgentFilter && shell?.isLibraryEnabled === true;+ const activeRemoteId = useAuiState(s => s.threadListItem.remoteId);+ const historyFilterIntent = shell?.historyAgentFilter?.intent;+ const showFilter =+ shell?.isLibraryEnabled === true &&+ historyFilterIntent !== 'try-agent' &&+ (historyFilterIntent === 'history' ||+ shell.mode.status !== 'active' ||+ shell.mode.isMutable ||+ shell.pendingSessionId != null ||+ activeRemoteId != null);+ const heading =+ shell?.historyAgentFilter == null ? 'Chat History' : `Chats for ${shell.historyAgentFilter.agentName}`;return (<div className="flex min-h-0 flex-1 flex-col"><div className="flex shrink-0 items-center gap-1 px-1 py-1">- <h2 className="min-w-0 flex-1 truncate px-1.5 py-1 text-sm font-medium text-text-secondary">My History</h2>+ <h2 className="min-w-0 flex-1 truncate px-1.5 py-1 text-sm font-medium text-text-secondary">{heading}</h2>{showFilter ? <AgentHistoryFilterButton /> : null}</div><div@@ -383,7 +392,7 @@ export function ThreadListContainer({ onThreadOpen, variant = 'default' }: Threa)}>- <RecentChatsSection viewportRef={viewportRef} hideScrollbar={isRecentHistory} showAgentFilter={!isRecentHistory}>+ <RecentChatsSection viewportRef={viewportRef} hideScrollbar={isRecentHistory}>{listBody}{!isIdle && hasMore ? <div className="h-4 shrink-0" aria-hidden /> : null}</RecentChatsSection>diff --git a/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsx b/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsxindex 7f9cdde83..07edaca5a 100644--- a/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsx+++ b/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsx@@ -161,7 +161,7 @@ function ChatProviderFromShell({/** When routing, reports the active thread's remote id up to `ShellRouteSync`. */onRemoteIdChange?: (id: string | undefined) => void;} & Omit<TrueFoundryChatProviderProps, 'agent' | 'agentName' | 'listSessionsAgentId' | 'children'>) {- const { mode, runtimeKey, listSessionsAgentId, pendingSessionId } = useShellMode();+ const { mode, runtimeKey, historyAgentFilter, listSessionsAgentId, pendingSessionId } = useShellMode();const isCreateAgent = mode.status === 'active' && mode.isMutable && mode.isCreateAgent;@@ -186,10 +186,15 @@ function ChatProviderFromShell({};}, [server, isCreateAgent]);- const runtimeServer = useMemo(+ const cachedRuntimeServer = useMemo(() => withSessionListCache({ server: serverWithCreateIntent, cache: sessionListCache }),[serverWithCreateIntent, sessionListCache],);+ const runtimeServer = useMemo<AgentUIServer>(() => {+ if (historyAgentFilter == null || historyAgentFilter.agentId != null) return cachedRuntimeServer;+ // Do not expose an unfiltered page under a filter label while its backend id resolves.+ return { ...cachedRuntimeServer, listSessions: async () => ({ data: [] }) };+ }, [cachedRuntimeServer, historyAgentFilter]);// Freeze draft seed for the life of this runtimeKey so bindMutableAgent (identity /// instructions on shell) does not push a new defaultAgentSpec into the runtime.diff --git a/packages/trueforge-ui/src/layouts/SidebarLayout.tsx b/packages/trueforge-ui/src/layouts/SidebarLayout.tsxindex 0f7fe6b7d..934ad262d 100644--- a/packages/trueforge-ui/src/layouts/SidebarLayout.tsx+++ b/packages/trueforge-ui/src/layouts/SidebarLayout.tsx@@ -59,7 +59,7 @@ function SidebarNav(): ReactNode {shell?.sessionsOpen === true ||shell?.schedulesOpen === true;const mode = shell?.mode;- const newChatSelected = !overlayOpen && mode?.status === 'active' && mode.isMutable && !mode.isCreateAgent;+ const newChatSelected = !overlayOpen && mode?.status === 'active' && !mode.isCreateAgent;const newAgentSelected = !overlayOpen && mode != null && shellIsCreateAgent(mode);const handleNewChat = () => {diff --git a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/catalogs/connectorCatalog.ts b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/catalogs/connectorCatalog.tsindex ec887c1e6..48d2edf0a 100644--- a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/catalogs/connectorCatalog.ts+++ b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/catalogs/connectorCatalog.ts@@ -64,10 +64,27 @@ export function toUiCatalogEntry(server: TrueForgeApi.CatalogMcpServer): UiConne};}-export function toUiTool(tool: Record<string, unknown>): ToolBase {+export type UiToolAnnotations = {+ readOnlyHint?: boolean;+ destructiveHint?: boolean;+};++function toUiToolAnnotations(value: unknown): UiToolAnnotations | undefined {+ if (typeof value !== 'object' || value === null) return undefined;+ const readOnlyHint = Reflect.get(value, 'readOnlyHint');+ const destructiveHint = Reflect.get(value, 'destructiveHint');+ const annotations: UiToolAnnotations = {+ ...(typeof readOnlyHint === 'boolean' ? { readOnlyHint } : {}),+ ...(typeof destructiveHint === 'boolean' ? { destructiveHint } : {}),+ };+ return Object.keys(annotations).length > 0 ? annotations : undefined;+}++export function toUiTool(tool: Record<string, unknown>): ToolBase & { annotations?: UiToolAnnotations } {const name = typeof tool.name === 'string' && tool.name !== '' ? tool.name : 'tool';const description = typeof tool.description === 'string' ? tool.description : '';- return { id: name, name, description };+ const annotations = toUiToolAnnotations(Reflect.get(tool, 'annotations'));+ return annotations === undefined ? { id: name, name, description } : { id: name, name, description, annotations };}export function toUiConnector(server: TrueForgeApi.ConfiguredMcpServer): UiConnector {diff --git a/packages/trueforge-ui/src/routing/ShellRouteSync.tsx b/packages/trueforge-ui/src/routing/ShellRouteSync.tsxindex 6e6a58f09..2f64790a7 100644--- a/packages/trueforge-ui/src/routing/ShellRouteSync.tsx+++ b/packages/trueforge-ui/src/routing/ShellRouteSync.tsx@@ -4,6 +4,7 @@ import { useCallback, useEffect, useMemo, useRef } from 'react';import { useLocation, useNavigate } from 'react-router-dom';import { sessionIsCreateAgent } from '../atoms/lib/sessionCreateAgent.js';+import { findAgentByName } from '../atoms/lib/useSearchAgentsList.js';import {useOptionalAgentSessionsServer,useOptionalCatalogServer,@@ -12,12 +13,22 @@ import {useServerCapabilities,useServerCapabilitiesSettled,} from '../server/ServerContext.js';-import { useShellMode } from '../server/ShellModeContext.js';+import { libraryAgentId, useShellMode } from '../server/ShellModeContext.js';import { toEffectiveRoutes } from '../server/serverChrome.js';+import {+ readHistoryAgentSearch,+ updateHistoryAgentSearch,+ type HistoryAgentSearch,+} from '../utils/historyAgentSearch.js';import { deriveChatPlace, derivePlace } from './derivePlace.js';import { buildPath, matchLocation, placesEqual, sanitizeSearchForPlace } from './paths.js';import type { ResolvedRoutes, RoutePlace, ShellSnapshot } from './types.js';+// Filter intent follows chat history across chat/session URLs, but must not leak into unrelated surfaces.+function placeOwnsHistoryAgentSearch(place: RoutePlace): boolean {+ return place.type === 'root' || place.type === 'agent' || place.type === 'session';+}+/*** Single bidirectional bridge between shell state and the URL. Mounted under* `ShellModeProvider` but outside the keyed chat runtime so boot applies once.@@ -74,9 +85,13 @@ export function ShellRouteSync({// URL->shell effect does not re-apply it. `prevPlaceRef` powers push/replace.const selfNavPathRef = useRef<string | null>(null);const prevPlaceRef = useRef<RoutePlace | null>(null);+ const appliedUrlPlaceRef = useRef<RoutePlace | null>(null);const bootedRef = useRef(false);+ const bootPlaceRef = useRef<RoutePlace | null>(null);+ const bootHistoryAgentRef = useRef<HistoryAgentSearch | null>(null);// Latest session id the URL asked for, so slower lookups cannot bind over it.const requestedSessionRef = useRef<string | null>(null);+ const requestedHistoryAgentRef = useRef<string | null>(null);// Boot owns the first URL; the ongoing effects skip their initial commit so// they do not fight boot with the stale first-render place.const shellSyncStartedRef = useRef(false);@@ -114,6 +129,60 @@ export function ShellRouteSync({[server, shell],);+ const applyHistoryAgentSearch = useCallback(+ (next: HistoryAgentSearch | null) => {+ if (next == null) {+ requestedHistoryAgentRef.current = null;+ bootHistoryAgentRef.current = null;+ shell.setHistoryAgentFilter(null);+ return;+ }++ const requestKey = `${next.intent}\0${next.agentName}`;+ const current = shell.historyAgentFilter;+ if (current?.intent === next.intent && current.agentName === next.agentName && current.agentId != null) {+ requestedHistoryAgentRef.current = null;+ return;+ }++ requestedHistoryAgentRef.current = requestKey;+ shell.setHistoryAgentFilter(next);+ if (server == null) return;++ void findAgentByName({ server, agentName: next.agentName })+ .then(agent => {+ if (requestedHistoryAgentRef.current !== requestKey) return;+ if (agent == null) {+ requestedHistoryAgentRef.current = null;+ bootHistoryAgentRef.current = null;+ shell.setHistoryAgentFilter(null);+ return;+ }+ requestedHistoryAgentRef.current = null;+ shell.setHistoryAgentFilter({+ agentId: libraryAgentId(agent),+ agentName: agent.name,+ intent: next.intent,+ });+ })+ .catch(() => {+ if (requestedHistoryAgentRef.current !== requestKey) return;+ requestedHistoryAgentRef.current = null;+ bootHistoryAgentRef.current = null;+ shell.setHistoryAgentFilter(null);+ });+ },+ [server, shell],+ );++ const openAgent = useCallback(+ (agentName: string) => {+ shell.selectLibraryAgent({ isMutable: false, agentName });+ applyHistoryAgentSearch({ intent: 'try-agent', agentName });+ },+ [applyHistoryAgentSearch, shell],+ );+const applyPlace = useCallback((target: RoutePlace) => {switch (target.type) {@@ -132,6 +201,9 @@ export function ShellRouteSync({case 'schedules':shell.setSchedulesOpen(true);return;+ case 'buildAgent':+ shell.openAgentBuilder();+ return;case 'session':shell.setLibraryOpen(false);if (shell.pendingSessionId === target.sessionId || activeRemoteId === target.sessionId) return;@@ -139,7 +211,7 @@ export function ShellRouteSync({return;case 'agent':shell.setLibraryOpen(false);- shell.selectLibraryAgent({ isMutable: false, agentName: target.agentName });+ openAgent(target.agentName);return;case 'root':shell.setSettingsOpen(false);@@ -159,7 +231,7 @@ export function ShellRouteSync({}}},- [shell, activeRemoteId, openSession],+ [shell, activeRemoteId, openAgent, openSession],);// Boot: URL wins, except an explicit `initialSettingsOpen` overlay. Boot is the@@ -179,6 +251,14 @@ export function ShellRouteSync({search: location.search,routes: effectiveRoutes,}) ?? { type: 'root' };+ const historyAgentSearch: HistoryAgentSearch | null =+ urlPlace.type === 'agent'+ ? { intent: 'try-agent', agentName: urlPlace.agentName }+ : placeOwnsHistoryAgentSearch(urlPlace)+ ? readHistoryAgentSearch(location.search)+ : null;+ bootHistoryAgentRef.current = historyAgentSearch;+ appliedUrlPlaceRef.current = urlPlace;const settingsOnBoot = settingsChromeEnabled && (initialSettingsOpen || urlPlace.type === 'settings');if (urlPlace.type === 'settings') {@@ -196,10 +276,19 @@ export function ShellRouteSync({if (!placesEqual(chatPlace, urlPlace)) applyPlace(urlPlace);if (settingsOnBoot) shell.setSettingsOpen(true);}+ if (urlPlace.type !== 'agent' && historyAgentSearch != null) {+ applyHistoryAgentSearch(historyAgentSearch);+ } else if (!placeOwnsHistoryAgentSearch(urlPlace)) {+ applyHistoryAgentSearch(null);+ }const desiredPlace: RoutePlace = settingsOnBoot ? { type: 'settings' } : urlPlace;+ bootPlaceRef.current = placesEqual(place, desiredPlace) ? null : desiredPlace;const desiredPath = buildPath(desiredPlace, effectiveRoutes);- const desiredSearch = sanitizeSearchForPlace(desiredPlace, location.search);+ const desiredSearch = updateHistoryAgentSearch(+ sanitizeSearchForPlace(desiredPlace, location.search),+ historyAgentSearch,+ );prevPlaceRef.current = desiredPlace;if (desiredPath != null && (desiredPath !== location.pathname || desiredSearch !== location.search)) {selfNavPathRef.current = desiredPath !== location.pathname ? desiredPath : null;@@ -216,6 +305,11 @@ export function ShellRouteSync({shellSyncStartedRef.current = true;return;}+ const bootPlace = bootPlaceRef.current;+ if (bootPlace != null) {+ if (!placesEqual(place, bootPlace)) return;+ bootPlaceRef.current = null;+ }const target = buildPath(place, effectiveRoutes);if (target == null) return; // place has no configured URL (e.g. settings disabled)const basename = effectiveRoutes.basename.endsWith('/')@@ -223,7 +317,21 @@ export function ShellRouteSync({: effectiveRoutes.basename;const browserPathname = `${basename}${location.pathname}` || '/';const latestSearch = window.location.pathname === browserPathname ? window.location.search : location.search;- const targetSearch = sanitizeSearchForPlace(place, latestSearch);+ const ownsHistoryAgentSearch = placeOwnsHistoryAgentSearch(place);+ const historyAgentSearch = ownsHistoryAgentSearch+ ? shell.historyAgentFilter == null+ ? bootHistoryAgentRef.current+ : {+ intent: shell.historyAgentFilter.intent,+ agentName: shell.historyAgentFilter.agentName,+ }+ : null;+ if (!ownsHistoryAgentSearch && shell.historyAgentFilter != null) {+ requestedHistoryAgentRef.current = null;+ shell.setHistoryAgentFilter(null);+ }+ if (shell.historyAgentFilter != null) bootHistoryAgentRef.current = null;+ const targetSearch = updateHistoryAgentSearch(sanitizeSearchForPlace(place, latestSearch), historyAgentSearch);const prev = prevPlaceRef.current;prevPlaceRef.current = place;@@ -239,7 +347,7 @@ export function ShellRouteSync({navigate({ pathname: target, search: targetSearch, hash: location.hash }, { replace });// location.pathname intentionally excluded: only react to shell-derived place changes.// eslint-disable-next-line react-hooks/exhaustive-deps- }, [placeKey, routeGatesKey]);+ }, [placeKey, routeGatesKey, shell.historyAgentFilter?.agentName, shell.historyAgentFilter?.intent]);// URL -> shell: apply on genuine location changes (Back/Forward, manual edits).useEffect(() => {@@ -250,6 +358,7 @@ export function ShellRouteSync({}if (selfNavPathRef.current === location.pathname) {selfNavPathRef.current = null;+ appliedUrlPlaceRef.current = place;return;}const urlPlace = matchLocation({@@ -264,25 +373,35 @@ export function ShellRouteSync({selfNavPathRef.current = rootPath;navigate({ pathname: rootPath, search: rootSearch, hash: location.hash }, { replace: true });applyPlace({ type: 'root' });+ applyHistoryAgentSearch(readHistoryAgentSearch(rootSearch));return;}- if (urlPlace.type !== 'settings' && shell.settingsOpen) {- // Leaving settings via Back to a chat place.- shell.setSettingsOpen(false);- }- if (urlPlace.type !== 'library' && urlPlace.type !== 'libraryAgent' && shell.libraryOpen) {- shell.setLibraryOpen(false);- }- if (urlPlace.type !== 'sessionsBrowser' && shell.sessionsOpen) {- shell.setSessionsOpen(false);+ const previousUrlPlace = appliedUrlPlaceRef.current;+ appliedUrlPlaceRef.current = urlPlace;+ if (previousUrlPlace == null || !placesEqual(previousUrlPlace, urlPlace)) {+ if (urlPlace.type !== 'settings' && shell.settingsOpen) {+ // Leaving settings via Back to a chat place.+ shell.setSettingsOpen(false);+ }+ if (urlPlace.type !== 'library' && urlPlace.type !== 'libraryAgent' && shell.libraryOpen) {+ shell.setLibraryOpen(false);+ }+ if (urlPlace.type !== 'sessionsBrowser' && shell.sessionsOpen) {+ shell.setSessionsOpen(false);+ }+ if (urlPlace.type !== 'schedules' && shell.schedulesOpen) {+ // Leaving schedules via Back to a chat place.+ shell.setSchedulesOpen(false);+ }+ applyPlace(urlPlace);}- if (urlPlace.type !== 'schedules' && shell.schedulesOpen) {- // Leaving schedules via Back to a chat place.- shell.setSchedulesOpen(false);+ if (urlPlace.type !== 'agent' && placeOwnsHistoryAgentSearch(urlPlace)) {+ applyHistoryAgentSearch(readHistoryAgentSearch(location.search));+ } else if (!placeOwnsHistoryAgentSearch(urlPlace)) {+ applyHistoryAgentSearch(null);}- applyPlace(urlPlace);// eslint-disable-next-line react-hooks/exhaustive-deps- }, [location.pathname]);+ }, [location.pathname, location.search]);return null;}diff --git a/packages/trueforge-ui/src/routing/derivePlace.ts b/packages/trueforge-ui/src/routing/derivePlace.tsindex cb0d3b87d..fb28c7d55 100644--- a/packages/trueforge-ui/src/routing/derivePlace.ts+++ b/packages/trueforge-ui/src/routing/derivePlace.ts@@ -13,6 +13,10 @@ export function deriveChatPlace(snapshot: ShellSnapshot): RoutePlace {if (sessionId != null) return { type: 'session', sessionId };const { mode, agentConfigMode } = snapshot;+ if (mode.status === 'active' && mode.isMutable && mode.isCreateAgent) {+ return { type: 'buildAgent' };+ }+if (mode.status === 'active' && !mode.isMutable && agentConfigMode !== 'SingleAgent') {const agentName = mode.agentName ?? mode.agentId;if (agentName != null) return { type: 'agent', agentName };diff --git a/packages/trueforge-ui/src/routing/paths.ts b/packages/trueforge-ui/src/routing/paths.tsindex 0050515d4..485aa03e8 100644--- a/packages/trueforge-ui/src/routing/paths.ts+++ b/packages/trueforge-ui/src/routing/paths.ts@@ -12,6 +12,7 @@ const DEFAULTS = {library: '/library',libraryAgent: '/library/:agentId',schedules: '/schedules',+ buildAgent: '/build-agent',agent: '/agents/:agentName',session: '/sessions/:sessionId',sessionsBrowser: '/sessions',@@ -38,6 +39,7 @@ export function resolveRoutesConfig(routes?: RoutesConfig): ResolvedRoutes {library: resolveOptional(paths?.library, DEFAULTS.library),libraryAgent: resolveOptional(paths?.libraryAgent, DEFAULTS.libraryAgent),schedules: resolveOptional(paths?.schedules, DEFAULTS.schedules),+ buildAgent: resolveOptional(paths?.buildAgent, DEFAULTS.buildAgent),agent: resolveOptional(paths?.agent, DEFAULTS.agent),session: resolveOptional(paths?.session, DEFAULTS.session),sessionsBrowser: resolveOptional(paths?.sessionsBrowser, DEFAULTS.sessionsBrowser),@@ -71,6 +73,8 @@ export function buildPath(place: RoutePlace, routes: ResolvedRoutes): string | nreturn routes.libraryAgent == null ? null : fillTemplate(routes.libraryAgent, place.agentId);case 'schedules':return routes.schedules;+ case 'buildAgent':+ return routes.buildAgent;case 'agent':return routes.agent == null ? null : fillTemplate(routes.agent, place.agentName);case 'session':@@ -203,6 +207,9 @@ export function matchPath(pathname: string, routes: ResolvedRoutes): RoutePlaceif (routes.schedules != null && normalized === routes.schedules) {return { type: 'schedules' };}+ if (routes.buildAgent != null && normalized === routes.buildAgent) {+ return { type: 'buildAgent' };+ }if (routes.agent != null) {const agentName = matchTemplate(routes.agent, segments);if (agentName != null) return { type: 'agent', agentName };diff --git a/packages/trueforge-ui/src/routing/types.ts b/packages/trueforge-ui/src/routing/types.tsindex ff79cefd1..ea5024005 100644--- a/packages/trueforge-ui/src/routing/types.ts+++ b/packages/trueforge-ui/src/routing/types.ts@@ -12,7 +12,8 @@ export type RoutePlace =| { type: 'library' }| { type: 'libraryAgent'; agentId: string }| { type: 'sessionsBrowser' }- | { type: 'schedules' };+ | { type: 'schedules' }+ | { type: 'buildAgent' };/*** Host-facing route path customization. Only honored when `withRouter`.@@ -33,6 +34,8 @@ export type RoutesConfig = {libraryAgent?: string | false;/** Schedules page. `false` keeps schedules overlay-only (no URL). Default `'/schedules'`. */schedules?: string | false;+ /** Agent builder. `false` disables its dedicated URL. Default `'/build-agent'`. */+ buildAgent?: string | false;/** Immutable "Try" agent. `false` disables. Default `'/agents/:agentName'`. */agent?: string | false;/** Session deep link. `false` disables. Default `'/sessions/:sessionId'`. */@@ -50,6 +53,7 @@ export type ResolvedRoutes = {library: string | null;libraryAgent: string | null;schedules: string | null;+ buildAgent: string | null;agent: string | null;session: string | null;sessionsBrowser: string | null;diff --git a/packages/trueforge-ui/src/server/ShellModeContext.tsx b/packages/trueforge-ui/src/server/ShellModeContext.tsxindex 9367ba531..4408e4899 100644--- a/packages/trueforge-ui/src/server/ShellModeContext.tsx+++ b/packages/trueforge-ui/src/server/ShellModeContext.tsx@@ -2,6 +2,7 @@import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';+import type { HistoryAgentIntent } from '../utils/historyAgentSearch.js';import { replaceSessionShareSearch } from '../utils/sessionShareUrl.js';import {readDraftSpecPreferences,@@ -68,6 +69,12 @@ export type SelectLibraryAgentRequest = {export type SettingsSection = 'models' | 'connectors' | 'skills' | 'sandbox';+export type HistoryAgentFilter = {+ agentId?: string;+ agentName: string;+ intent: HistoryAgentIntent;+};+type ShellModeContextValue = {mode: ShellMode;/** Host agentConfig mode (capabilities source). */@@ -133,8 +140,8 @@ type ShellModeContextValue = {* History list filter forwarded as `listSessions({ agentId })`.* `null` = All chats. Only meaningful when `isLibraryEnabled`.*/- historyAgentFilter: string | null;- setHistoryAgentFilter: (agentId: string | null) => void;+ historyAgentFilter: HistoryAgentFilter | null;+ setHistoryAgentFilter: (filter: HistoryAgentFilter | null) => void;/** Effective `listSessionsAgentId` for the runtime (SingleAgent locks to name). */listSessionsAgentId: string | undefined;/** Session selected from history. */@@ -234,7 +241,7 @@ export function ShellModeProvider({const [sessionsOpenState, setSessionsOpenState] = useState(false);const [libraryAgentId, setLibraryAgentId] = useState<string | null>(null);const [schedulesOpenState, setSchedulesOpenState] = useState(false);- const [historyAgentFilter, setHistoryAgentFilter] = useState<string | null>(null);+ const [historyAgentFilter, setHistoryAgentFilter] = useState<HistoryAgentFilter | null>(null);const [pendingSessionId, setPendingSessionId] = useState<string | undefined>(undefined);const [pendingSessionEpoch, setPendingSessionEpoch] = useState(0);const settingsEnabled = isSettingsChromeEnabled({ catalog, capabilities });@@ -378,7 +385,7 @@ export function ShellModeProvider({const listSessionsAgentId = useMemo(() => {if (locked) return lockedAgentName;if (!isLibraryEnabled) return undefined;- return historyAgentFilter ?? undefined;+ return historyAgentFilter?.agentId;}, [locked, lockedAgentName, isLibraryEnabled, historyAgentFilter]);const bumpEpoch = useCallback((isMutable: boolean) => {@@ -429,6 +436,15 @@ export function ShellModeProvider({agentName,locked: false,});+ if (req.agentId != null) {+ setHistoryAgentFilter({+ agentId: req.agentId,+ agentName,+ intent: 'try-agent',+ });+ } else {+ setHistoryAgentFilter(null);+ }bumpEpoch(false);},[isComposerEnabled, isLibraryEnabled, bumpEpoch, setSettingsOpen, setSessionsOpen, setSchedulesOpen],diff --git a/packages/trueforge-ui/src/utils/historyAgentSearch.ts b/packages/trueforge-ui/src/utils/historyAgentSearch.tsnew file mode 100644index 000000000..42a09bda5--- /dev/null+++ b/packages/trueforge-ui/src/utils/historyAgentSearch.ts@@ -0,0 +1,35 @@+export const TRY_AGENT_NAME_QUERY = 'try_agent_name';+export const HISTORY_AGENT_NAME_QUERY = 'history_agent_name';++export type HistoryAgentIntent = 'try-agent' | 'history';++export type HistoryAgentSearch = {+ intent: HistoryAgentIntent;+ agentName: string;+};++function nonEmpty(value: string | null): string | null {+ return value != null && value.length > 0 ? value : null;+}++export function readHistoryAgentSearch(search: string): HistoryAgentSearch | null {+ const params = new URLSearchParams(search.startsWith('?') ? search.slice(1) : search);+ const tryAgentName = nonEmpty(params.get(TRY_AGENT_NAME_QUERY));+ if (tryAgentName != null) return { intent: 'try-agent', agentName: tryAgentName };+ const historyAgentName = nonEmpty(params.get(HISTORY_AGENT_NAME_QUERY));+ return historyAgentName == null ? null : { intent: 'history', agentName: historyAgentName };+}++export function writeHistoryAgentSearch(params: URLSearchParams, next: HistoryAgentSearch | null): void {+ params.delete(TRY_AGENT_NAME_QUERY);+ params.delete(HISTORY_AGENT_NAME_QUERY);+ if (next == null) return;+ params.set(next.intent === 'try-agent' ? TRY_AGENT_NAME_QUERY : HISTORY_AGENT_NAME_QUERY, next.agentName);+}++export function updateHistoryAgentSearch(search: string, next: HistoryAgentSearch | null): string {+ const params = new URLSearchParams(search.startsWith('?') ? search.slice(1) : search);+ writeHistoryAgentSearch(params, next);+ const updated = params.toString();+ return updated.length > 0 ? `?${updated}` : '';+}diff --git a/packages/trueforge-ui/test/atoms/AgentHistoryFilterButton.test.tsx b/packages/trueforge-ui/test/atoms/AgentHistoryFilterButton.test.tsxindex ef3cf0ef1..3d9e9660c 100644--- a/packages/trueforge-ui/test/atoms/AgentHistoryFilterButton.test.tsx+++ b/packages/trueforge-ui/test/atoms/AgentHistoryFilterButton.test.tsx@@ -41,7 +41,17 @@ function mockServer(partial: Partial<AgentUIServer> = {}): AgentUIServer {function FilterProbe() {const shell = useShellMode();- return <span data-testid="filter-value">{shell.historyAgentFilter ?? 'all'}</span>;+ const filter = shell.historyAgentFilter;+ return (+ <>+ <span data-testid="filter-value">{filter == null ? 'all' : `${filter.agentName}:${filter.intent}`}</span>+ <span data-testid="runtime-key">{shell.runtimeKey}</span>+ <span data-testid="pending-session">{shell.pendingSessionId ?? 'none'}</span>+ <button type="button" onClick={() => shell.openHistorySession({ sessionId: 'draft-session', isMutable: true })}>+ Open draft session+ </button>+ </>+ );}function wrap({@@ -99,6 +109,9 @@ describe('AgentHistoryFilterButton', () => {expect(screen.getByTestId('filter-value')).toHaveTextContent('all');expect(screen.queryByTestId('history-filter-active-dot')).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Open draft session' }));+ const runtimeKeyBeforeFilter = screen.getByTestId('runtime-key').textContent;+ expect(screen.getByTestId('pending-session')).toHaveTextContent('draft-session');fireEvent.click(screen.getByRole('button', { name: /Filter chat history/i }));await waitFor(() => expect(screen.getByRole('menuitem', { name: /From SDK/i })).toBeInTheDocument());@@ -111,9 +124,17 @@ describe('AgentHistoryFilterButton', () => {fireEvent.click(screen.getByRole('menuitem', { name: /From SDK/i }));});- expect(screen.getByTestId('filter-value')).toHaveTextContent('from-sdk');+ expect(screen.getByTestId('filter-value')).toHaveTextContent('From SDK:history');+ expect(screen.getByTestId('pending-session')).toHaveTextContent('none');+ expect(screen.getByTestId('runtime-key').textContent).not.toBe(runtimeKeyBeforeFilter);expect(screen.getByTestId('history-filter-active-dot')).toBeInTheDocument();expect(searchAgents).toHaveBeenCalled();++ const runtimeKeyBeforeClear = screen.getByTestId('runtime-key').textContent;+ fireEvent.click(screen.getByRole('button', { name: /Filter chat history/i }));+ fireEvent.click(await screen.findByRole('menuitem', { name: 'All chats' }));+ expect(screen.getByTestId('filter-value')).toHaveTextContent('all');+ expect(screen.getByTestId('runtime-key').textContent).not.toBe(runtimeKeyBeforeClear);});it('hides All chats while a search query is active', async () => {diff --git a/packages/trueforge-ui/test/atoms/draft/AgentMcpEditorContent.sections.test.tsx b/packages/trueforge-ui/test/atoms/draft/AgentMcpEditorContent.sections.test.tsxnew file mode 100644index 000000000..6d3f05ea1--- /dev/null+++ b/packages/trueforge-ui/test/atoms/draft/AgentMcpEditorContent.sections.test.tsx@@ -0,0 +1,194 @@+// @vitest-environment jsdom+import { fireEvent, render, screen } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { AgentMcpEditorContent } from '@/atoms/draft/AgentMcpEditorContent.js';+import type { McpToolSelection } from '@/server/types.js';+import { SlotsProvider } from '@/theme/SlotsProvider.js';++function tool(+ name: string,+ description: string,+ annotations?: { readOnlyHint?: boolean; destructiveHint?: boolean },+): McpToolSelection {+ const row: McpToolSelection = { id: name, name, description };+ if (annotations !== undefined) Reflect.set(row, 'annotations', annotations);+ return row;+}++const sectionedTools = [+ tool('list_items', 'List items', { readOnlyHint: true, destructiveHint: false }),+ tool('get_item', 'Get one item', { readOnlyHint: true, destructiveHint: false }),+ tool('rename_item', 'Rename an item', { readOnlyHint: false, destructiveHint: false }),+ tool('delete_item', 'Delete an item', { readOnlyHint: false, destructiveHint: true }),+];++describe('AgentMcpEditorContent tool sections', () => {+ it('groups tools into Read-only, Other, and Destructive sections', () => {+ render(+ <SlotsProvider>+ <AgentMcpEditorContent+ spec={{ model: { name: 'openai/gpt' } }}+ connectors={[{ id: 'linear', name: 'Linear', authenticated: true }]}+ query=""+ activeConnectorId="linear"+ tools={sectionedTools}+ connectorLoading={false}+ connectorError={null}+ toolsLoading={false}+ toolsError={null}+ onQueryChange={vi.fn()}+ onSelectConnector={vi.fn()}+ onRetryTools={vi.fn()}+ onChange={vi.fn()}+ />+ </SlotsProvider>,+ );++ expect(screen.getByText('Read-only Actions')).toBeInTheDocument();+ expect(screen.getByText('Other Actions')).toBeInTheDocument();+ expect(screen.getByText('Destructive Actions')).toBeInTheDocument();+ expect(screen.getByRole('switch', { name: 'Enable all read-only tools' })).toBeInTheDocument();+ });++ it('enables only read-only tools from the section toggle', () => {+ const onChange = vi.fn();+ render(+ <SlotsProvider>+ <AgentMcpEditorContent+ spec={{ model: { name: 'openai/gpt' } }}+ connectors={[{ id: 'linear', name: 'Linear', authenticated: true }]}+ query=""+ activeConnectorId="linear"+ tools={sectionedTools}+ connectorLoading={false}+ connectorError={null}+ toolsLoading={false}+ toolsError={null}+ onQueryChange={vi.fn()}+ onSelectConnector={vi.fn()}+ onRetryTools={vi.fn()}+ onChange={onChange}+ />+ </SlotsProvider>,+ );++ fireEvent.click(screen.getByRole('switch', { name: 'Enable all read-only tools' }));++ expect(onChange).toHaveBeenCalledWith({+ model: { name: 'openai/gpt' },+ mcpServers: [+ {+ id: 'linear',+ name: 'Linear',+ enableTools: ['list_items', 'get_item'],+ },+ ],+ });+ });++ it('clears only read-only tools when the section toggle is turned off', () => {+ const onChange = vi.fn();+ render(+ <SlotsProvider>+ <AgentMcpEditorContent+ spec={{+ model: { name: 'openai/gpt' },+ mcpServers: [+ {+ id: 'linear',+ name: 'Linear',+ enableTools: ['list_items', 'get_item', 'delete_item'],+ },+ ],+ }}+ connectors={[{ id: 'linear', name: 'Linear', authenticated: true }]}+ query=""+ activeConnectorId="linear"+ tools={sectionedTools}+ connectorLoading={false}+ connectorError={null}+ toolsLoading={false}+ toolsError={null}+ onQueryChange={vi.fn()}+ onSelectConnector={vi.fn()}+ onRetryTools={vi.fn()}+ onChange={onChange}+ />+ </SlotsProvider>,+ );++ fireEvent.click(screen.getByRole('switch', { name: 'Enable all read-only tools' }));++ expect(onChange).toHaveBeenCalledWith({+ model: { name: 'openai/gpt' },+ mcpServers: [+ {+ id: 'linear',+ name: 'Linear',+ enableTools: ['delete_item'],+ },+ ],+ });+ });++ it('hides empty sections while searching tools by name', () => {+ render(+ <SlotsProvider>+ <AgentMcpEditorContent+ spec={{ model: { name: 'openai/gpt' } }}+ connectors={[{ id: 'linear', name: 'Linear', authenticated: true }]}+ query=""+ activeConnectorId="linear"+ tools={sectionedTools}+ connectorLoading={false}+ connectorError={null}+ toolsLoading={false}+ toolsError={null}+ onQueryChange={vi.fn()}+ onSelectConnector={vi.fn()}+ onRetryTools={vi.fn()}+ onChange={vi.fn()}+ />+ </SlotsProvider>,+ );++ fireEvent.change(screen.getByPlaceholderText('Search Tools'), { target: { value: 'delete' } });++ expect(screen.queryByText('Read-only Actions')).not.toBeInTheDocument();+ expect(screen.queryByText('Other Actions')).not.toBeInTheDocument();+ expect(screen.getByText('Destructive Actions')).toBeInTheDocument();+ expect(screen.getByRole('menuitemcheckbox', { name: 'delete_item' })).toBeInTheDocument();+ });++ it('hides the Other Actions label when it is the only section', () => {+ render(+ <SlotsProvider>+ <AgentMcpEditorContent+ spec={{ model: { name: 'openai/gpt' } }}+ connectors={[{ id: 'linear', name: 'Linear', authenticated: true }]}+ query=""+ activeConnectorId="linear"+ tools={[+ tool('rename_item', 'Rename an item'),+ tool('tag_item', 'Tag an item', { readOnlyHint: false, destructiveHint: false }),+ ]}+ connectorLoading={false}+ connectorError={null}+ toolsLoading={false}+ toolsError={null}+ onQueryChange={vi.fn()}+ onSelectConnector={vi.fn()}+ onRetryTools={vi.fn()}+ onChange={vi.fn()}+ />+ </SlotsProvider>,+ );++ expect(screen.queryByText('Other Actions')).not.toBeInTheDocument();+ expect(screen.queryByText('Read-only Actions')).not.toBeInTheDocument();+ expect(screen.queryByText('Destructive Actions')).not.toBeInTheDocument();+ expect(screen.getByRole('menuitemcheckbox', { name: 'rename_item' })).toBeInTheDocument();+ expect(screen.getByRole('menuitemcheckbox', { name: 'tag_item' })).toBeInTheDocument();+ });+});diff --git a/packages/trueforge-ui/test/atoms/draft/mcpToolSections.test.ts b/packages/trueforge-ui/test/atoms/draft/mcpToolSections.test.tsnew file mode 100644index 000000000..5e0df55e1--- /dev/null+++ b/packages/trueforge-ui/test/atoms/draft/mcpToolSections.test.ts@@ -0,0 +1,33 @@+import assert from 'node:assert/strict';+import { describe, it } from 'vitest';++import { MCP_TOOL_SECTION_ORDER, mcpToolSectionId, partitionMcpToolsBySection } from '@/atoms/draft/mcpToolSections.js';+import type { McpToolSelection } from '@/server/types.js';++function tool(name: string, annotations?: { readOnlyHint?: boolean; destructiveHint?: boolean }): McpToolSelection {+ const row: McpToolSelection = { id: name, name };+ if (annotations !== undefined) Reflect.set(row, 'annotations', annotations);+ return row;+}++describe('mcpToolSections', () => {+ it('classifies tools by readOnlyHint then destructiveHint', () => {+ assert.equal(mcpToolSectionId(tool('list', { readOnlyHint: true })), 'read-only');+ assert.equal(mcpToolSectionId(tool('delete', { destructiveHint: true })), 'destructive');+ assert.equal(mcpToolSectionId(tool('write', { readOnlyHint: false, destructiveHint: false })), 'others');+ assert.equal(mcpToolSectionId(tool('plain')), 'others');+ assert.equal(mcpToolSectionId(tool('both', { readOnlyHint: true, destructiveHint: true })), 'read-only');+ });++ it('partitions in Read-only → Other → Destructive order', () => {+ const sections = partitionMcpToolsBySection([+ tool('delete', { destructiveHint: true }),+ tool('list', { readOnlyHint: true }),+ tool('plain'),+ ]);+ assert.deepEqual(+ MCP_TOOL_SECTION_ORDER.map(id => sections[id].map(item => item.name)),+ [['list'], ['plain'], ['delete']],+ );+ });+});diff --git a/packages/trueforge-ui/test/atoms/lib/useSearchAgentsList.test.tsx b/packages/trueforge-ui/test/atoms/lib/useSearchAgentsList.test.tsxindex 9951775ae..4d5ca0e96 100644--- a/packages/trueforge-ui/test/atoms/lib/useSearchAgentsList.test.tsx+++ b/packages/trueforge-ui/test/atoms/lib/useSearchAgentsList.test.tsx@@ -3,7 +3,7 @@ import { act, renderHook, waitFor } from '@testing-library/react';import type { ReactNode } from 'react';import { afterEach, describe, expect, it, vi } from 'vitest';-import { SEARCH_AGENTS_PAGE_SIZE, useSearchAgentsList } from '@/atoms/lib/useSearchAgentsList.js';+import { findAgentByName, SEARCH_AGENTS_PAGE_SIZE, useSearchAgentsList } from '@/atoms/lib/useSearchAgentsList.js';import { ServerProvider } from '@/server/ServerContext.js';import type { AgentLibraryEntry, AgentUIServer } from '@/server/types.js';import { createMockAgentUIServer } from '../../server/mockServer.js';@@ -19,6 +19,29 @@ describe('useSearchAgentsList', () => {vi.useRealTimers();});+ it('finds an exact name on a later filtered search page', async () => {+ const firstPage = Array.from({ length: SEARCH_AGENTS_PAGE_SIZE }, (_, index) => ({+ name: `helper-copy-${index}`,+ agentId: `copy-${index}`,+ }));+ const searchAgents = vi+ .fn()+ .mockResolvedValueOnce(firstPage)+ .mockResolvedValueOnce([{ name: 'helper', agentId: 'helper-id' }]);++ await expect(+ findAgentByName({+ server: createMockAgentUIServer({ searchAgents }),+ agentName: 'helper',+ }),+ ).resolves.toEqual({ name: 'helper', agentId: 'helper-id' });+ expect(searchAgents).toHaveBeenLastCalledWith({+ query: 'helper',+ limit: SEARCH_AGENTS_PAGE_SIZE,+ offset: SEARCH_AGENTS_PAGE_SIZE,+ });+ });+it('fetches the first page when enabled and paginates via loadMore sentinel', async () => {const page1 = Array.from({ length: SEARCH_AGENTS_PAGE_SIZE }, (_, i) => ({name: `agent-${i}`,diff --git a/packages/trueforge-ui/test/containers/ThreadListContainer.test.tsx b/packages/trueforge-ui/test/containers/ThreadListContainer.test.tsxindex c1b4e2527..7cb6a7e31 100644--- a/packages/trueforge-ui/test/containers/ThreadListContainer.test.tsx+++ b/packages/trueforge-ui/test/containers/ThreadListContainer.test.tsx@@ -55,6 +55,55 @@ function ThreadListRowOverride({ title, active, onSelect, actions }: ThreadListR);}+function TryAgentButton() {+ const shell = useShellMode();+ return (+ <>+ <button+ type="button"+ onClick={() =>+ shell.selectLibraryAgent({+ isMutable: false,+ agentId: 'support-id',+ agentName: 'Support Agent',+ })+ }+ >+ Try Support Agent+ </button>+ <button+ type="button"+ onClick={() =>+ shell.openHistorySession({+ sessionId: 'support-session',+ isMutable: false,+ agentName: 'Support Agent',+ })+ }+ >+ Open Support Session+ </button>+ <button+ type="button"+ onClick={() => {+ shell.setHistoryAgentFilter({+ agentId: 'support-id',+ agentName: 'Support Agent',+ intent: 'history',+ });+ shell.openHistorySession({+ sessionId: 'filtered-support-session',+ isMutable: false,+ agentName: 'Support Agent',+ });+ }}+ >+ Open Filtered Support Session+ </button>+ </>+ );+}+function renderThreadList({adapter,onThreadOpen,@@ -184,11 +233,44 @@ describe('ThreadListContainer', () => {expect(screen.queryByRole('button', { name: 'Unsaved chat' })).not.toBeInTheDocument();expect(screen.queryByRole('button', { name: 'Start new chat' })).not.toBeInTheDocument();expect(screen.queryByText('New Chat')).not.toBeInTheDocument();- expect(screen.getByRole('heading', { name: 'My History' })).toBeInTheDocument();- expect(screen.queryByRole('button', { name: 'My History' })).not.toBeInTheDocument();+ expect(screen.getByRole('heading', { name: 'Chat History' })).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Chat History' })).not.toBeInTheDocument();expect(container.querySelector('[data-slot="aui_thread-list-viewport"]')).toHaveClass('aui-scrollbar-hidden');});+ it('uses filter intent to distinguish Try Agent from a filtered agent session', () => {+ const server = createMockAgentUIServer({+ searchAgents: async () => [{ name: 'Support Agent', agentId: 'support-id' }],+ });++ render(+ <ServerProvider server={server}>+ <ShellModeProvider agentConfig={{ mode: 'AgentLibraryWithComposer' }}>+ <SlotsProvider overrides={{ ThreadListRow: ThreadListRowOverride }}>+ <ThreadListRuntimeHarness threadList={{ threads: [] }}>+ <CompactLayoutProvider>+ <TryAgentButton />+ <ThreadListContainer variant="recent-history" />+ </CompactLayoutProvider>+ </ThreadListRuntimeHarness>+ </SlotsProvider>+ </ShellModeProvider>+ </ServerProvider>,+ );++ expect(screen.getByRole('button', { name: 'Filter chat history by agent' })).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Try Support Agent' }));++ expect(screen.getByRole('heading', { name: 'Chats for Support Agent' })).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: /Filter chat history by agent/ })).not.toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: 'Open Support Session' }));+ expect(screen.queryByRole('button', { name: /Filter chat history by agent/ })).not.toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: 'Open Filtered Support Session' }));+ expect(screen.getByRole('button', { name: /Filter chat history by agent/ })).toBeInTheDocument();+ });+it('shows the recent-history empty state when only an unsaved session exists', () => {renderThreadList({adapter: {@@ -244,7 +326,7 @@ describe('ThreadListContainer', () => {fireEvent.click(screen.getByRole('button', { name: 'Named chat' }));await waitFor(() => expect(screen.getByRole('status', { name: 'Active agent' })).toHaveTextContent('named-agent'));- expect(screen.getByRole('heading', { name: 'My History' })).toBeInTheDocument();+ expect(screen.getByRole('heading', { name: 'Chat History' })).toBeInTheDocument();});it('exposes delete only for remote sessions and delegates deletion to the runtime', async () => {diff --git a/packages/trueforge-ui/test/containers/TrueForgeUI.test.tsx b/packages/trueforge-ui/test/containers/TrueForgeUI.test.tsxindex 4b3757c64..42ff9f52d 100644--- a/packages/trueforge-ui/test/containers/TrueForgeUI.test.tsx+++ b/packages/trueforge-ui/test/containers/TrueForgeUI.test.tsx@@ -551,12 +551,22 @@ describe('SidebarLayout', () => {});it('highlights New Chat, New Agent, and Settings when selected', async () => {+ function TryAgentButton() {+ const shell = useShellMode();+ return (+ <button type="button" onClick={() => shell.selectLibraryAgent({ isMutable: false, agentName: 'support' })}>+ Try support+ </button>+ );+ }+render(<SlotsProvider theme={{ brand: { mode: 'icon-title', name: 'Acme' } }}><ServerProvider server={mockServer(stubCatalog)}><ShellModeProvider><AgentConfigInstructionsProvider><RuntimeHarness messages={[]}>+ <TryAgentButton /><div className="h-96"><SidebarLayout /></div>@@ -572,6 +582,10 @@ describe('SidebarLayout', () => {expect(newChat).toHaveAttribute('aria-current', 'page');expect(newAgent).not.toHaveAttribute('aria-current');+ fireEvent.click(screen.getByRole('button', { name: 'Try support' }));+ expect(newChat).toHaveAttribute('aria-current', 'page');+ expect(newAgent).not.toHaveAttribute('aria-current');+fireEvent.click(newAgent);const selectedNewAgent = await screen.findByRole('button', { name: 'Start new agent' });const deselectedNewChat = screen.getByRole('button', { name: 'Start new chat' });diff --git a/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/catalogs/connectorCatalog.test.ts b/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/catalogs/connectorCatalog.test.tsindex f22a38f34..77fea178a 100644--- a/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/catalogs/connectorCatalog.test.ts+++ b/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/catalogs/connectorCatalog.test.ts@@ -145,6 +145,39 @@ describe('connectorCatalog mappers', () => {assert.deepEqual(toUiTool({}), { id: 'tool', name: 'tool', description: '' });});+ it('forwards boolean readOnlyHint and destructiveHint annotations', () => {+ assert.deepEqual(+ toUiTool({+ name: 'list',+ description: 'List items',+ annotations: { readOnlyHint: true, destructiveHint: false, title: 'List' },+ }),+ {+ id: 'list',+ name: 'list',+ description: 'List items',+ annotations: { readOnlyHint: true, destructiveHint: false },+ },+ );+ assert.deepEqual(+ toUiTool({+ name: 'delete',+ annotations: { destructiveHint: true },+ }),+ {+ id: 'delete',+ name: 'delete',+ description: '',+ annotations: { destructiveHint: true },+ },+ );+ assert.deepEqual(toUiTool({ name: 'search', annotations: { title: 'Search' } }), {+ id: 'search',+ name: 'search',+ description: '',+ });+ });+it('builds upsert manifests from UI create/update requests', () => {assert.deepEqual(toHarnessManifest({diff --git a/packages/trueforge-ui/test/routing/ShellRouteSync.test.tsx b/packages/trueforge-ui/test/routing/ShellRouteSync.test.tsxindex f4b7fff58..99c506f58 100644--- a/packages/trueforge-ui/test/routing/ShellRouteSync.test.tsx+++ b/packages/trueforge-ui/test/routing/ShellRouteSync.test.tsx@@ -1,6 +1,6 @@// @vitest-environment jsdomimport { act, render, waitFor } from '@testing-library/react';-import { useEffect, useState, type ReactNode } from 'react';+import { StrictMode, useEffect, useState, type ReactNode } from 'react';import { MemoryRouter, useLocation } from 'react-router-dom';import { describe, expect, it } from 'vitest';@@ -76,6 +76,7 @@ function SettingsCatalogProvider({createdAt: '2026-01-01T00:00:00Z',updatedAt: '2026-01-01T00:00:00Z',}),+ searchAgents: async req => (req?.query === 'helper' ? [{ name: 'helper', agentId: 'helper-id' }] : []),});return <ServerProvider server={server}>{children}</ServerProvider>;}@@ -127,8 +128,9 @@ function renderSync(opts: {includeCatalog?: boolean;includeSessions?: boolean;includeSchedules?: boolean;+ strict?: boolean;}) {- return render(+ const tree = (<MemoryRouter initialEntries={opts.initialEntries ?? ['/']}><HarnessagentConfig={opts.agentConfig}@@ -139,8 +141,9 @@ function renderSync(opts: {includeSessions={opts.includeSessions}includeSchedules={opts.includeSchedules}/>- </MemoryRouter>,+ </MemoryRouter>);+ return render(opts.strict ? <StrictMode>{tree}</StrictMode> : tree);}describe('ShellRouteSync', () => {@@ -150,16 +153,118 @@ describe('ShellRouteSync', () => {expect(pathname).toBe('/sessions/abc');});- it('applies an agent deep link on boot', () => {- renderSync({ initialEntries: ['/agents/helper'], agentConfig: { mode: 'AgentLibrary' } });+ it('applies an agent deep link on boot and resolves its history filter id', async () => {+ renderSync({ initialEntries: ['/agents/helper'], agentConfig: { mode: 'AgentLibrary' }, strict: true });expect(shell.mode).toMatchObject({ status: 'active', isMutable: false, agentName: 'helper' });+ await waitFor(() => expect(shell.listSessionsAgentId).toBe('helper-id'));+ expect(pathname).toBe('/agents/helper');+ expect(search).toBe('?try_agent_name=helper');+ expect(shell.historyAgentFilter?.intent).toBe('try-agent');+ });++ it('restores a filtered history session from its agent-name query', async () => {+ renderSync({+ initialEntries: ['/sessions/abc?history_agent_name=helper'],+ agentConfig: { mode: 'AgentLibraryWithComposer' },+ });++ await waitFor(() => expect(shell.pendingSessionId).toBe('abc'));+ await waitFor(() => expect(shell.listSessionsAgentId).toBe('helper-id'));+ expect(shell.historyAgentFilter).toEqual({+ agentId: 'helper-id',+ agentName: 'helper',+ intent: 'history',+ });+ expect(search).toBe('?history_agent_name=helper');+ });++ it('clears a restored filter when no exact agent name exists', async () => {+ renderSync({+ initialEntries: ['/sessions/abc?history_agent_name=missing'],+ agentConfig: { mode: 'AgentLibraryWithComposer' },+ });++ await waitFor(() => expect(shell.pendingSessionId).toBe('abc'));+ await waitFor(() => expect(shell.historyAgentFilter).toBeNull());+ await waitFor(() => expect(search).toBe(''));+ expect(shell.listSessionsAgentId).toBeUndefined();});it('pushes the URL when the shell selects an immutable agent', () => {renderSync({ initialEntries: ['/'], agentConfig: { mode: 'AgentLibrary' } });expect(pathname).toBe('/');- act(() => shell.selectLibraryAgent({ isMutable: false, agentName: 'foo' }));+ act(() => shell.selectLibraryAgent({ isMutable: false, agentId: 'foo-id', agentName: 'foo' }));expect(pathname).toBe('/agents/foo');+ expect(search).toBe('?try_agent_name=foo');+ });++ it('preserves Try Agent intent when its new chat acquires a session id', async () => {+ renderSync({ initialEntries: ['/agents/helper'], agentConfig: { mode: 'AgentLibraryWithComposer' } });+ await waitFor(() => expect(shell.listSessionsAgentId).toBe('helper-id'));++ act(() => setRemoteId('session-from-try'));++ expect(pathname).toBe('/sessions/session-from-try');+ expect(search).toBe('?try_agent_name=helper');+ });++ it('writes and clears a manual history filter without changing the chat place', () => {+ renderSync({ initialEntries: ['/'], agentConfig: { mode: 'AgentLibraryWithComposer' } });++ act(() =>+ shell.setHistoryAgentFilter({+ agentId: 'helper-id',+ agentName: 'helper',+ intent: 'history',+ }),+ );+ expect(pathname).toBe('/');+ expect(search).toBe('?history_agent_name=helper');++ act(() => shell.setHistoryAgentFilter(null));+ expect(pathname).toBe('/');+ expect(search).toBe('');+ });++ it('clears history filter query state when leaving chat routes', () => {+ renderSync({ initialEntries: ['/'], agentConfig: { mode: 'AgentLibraryWithComposer' } });++ act(() =>+ shell.setHistoryAgentFilter({+ agentId: 'helper-id',+ agentName: 'helper',+ intent: 'history',+ }),+ );+ expect(search).toBe('?history_agent_name=helper');++ act(() => shell.openAgentBuilder());+ expect(pathname).toBe('/build-agent');+ expect(search).toBe('');+ expect(shell.historyAgentFilter).toBeNull();++ act(() =>+ shell.setHistoryAgentFilter({+ agentId: 'helper-id',+ agentName: 'helper',+ intent: 'history',+ }),+ );+ act(() => shell.setLibraryOpen(true));+ expect(pathname).toBe('/library');+ expect(search).toBe('');+ expect(shell.historyAgentFilter).toBeNull();+ });++ it('applies and mirrors the build-agent route', () => {+ renderSync({ initialEntries: ['/build-agent'] });+ expect(shell.mode).toMatchObject({ status: 'active', isMutable: true, isCreateAgent: true });+ expect(pathname).toBe('/build-agent');++ act(() => shell.openDraft());+ expect(pathname).toBe('/');+ act(() => shell.openAgentBuilder());+ expect(pathname).toBe('/build-agent');});it('mirrors settings open/close through history', async () => {diff --git a/packages/trueforge-ui/test/routing/derivePlace.test.ts b/packages/trueforge-ui/test/routing/derivePlace.test.tsindex 3b52f1f0b..01587c7e2 100644--- a/packages/trueforge-ui/test/routing/derivePlace.test.ts+++ b/packages/trueforge-ui/test/routing/derivePlace.test.ts@@ -63,6 +63,17 @@ describe('derivePlace', () => {});});+ it('agent builder moves to the session place after its session persists', () => {+ expect(+ deriveChatPlace(+ snap({+ activeRemoteId: 'builder-session',+ mode: { status: 'active', isMutable: true, isCreateAgent: true, locked: false },+ }),+ ),+ ).toEqual({ type: 'session', sessionId: 'builder-session' });+ });+it('active immutable agent maps to an agent place', () => {expect(deriveChatPlace(diff --git a/packages/trueforge-ui/test/routing/paths.test.ts b/packages/trueforge-ui/test/routing/paths.test.tsindex 9373fe0e4..9ccd59796 100644--- a/packages/trueforge-ui/test/routing/paths.test.ts+++ b/packages/trueforge-ui/test/routing/paths.test.ts@@ -19,6 +19,7 @@ describe('resolveRoutesConfig', () => {library: '/library',libraryAgent: '/library/:agentId',schedules: '/schedules',+ buildAgent: '/build-agent',agent: '/agents/:agentName',session: '/sessions/:sessionId',sessionsBrowser: '/sessions',@@ -53,6 +54,7 @@ describe('buildPath', () => {expect(buildPath({ type: 'library' }, routes)).toBe('/library');expect(buildPath({ type: 'libraryAgent', agentId: 'agent/id' }, routes)).toBe('/library/agent%2Fid');expect(buildPath({ type: 'schedules' }, routes)).toBe('/schedules');+ expect(buildPath({ type: 'buildAgent' }, routes)).toBe('/build-agent');expect(buildPath({ type: 'agent', agentName: 'code-helper' }, routes)).toBe('/agents/code-helper');expect(buildPath({ type: 'session', sessionId: 'abc123' }, routes)).toBe('/sessions/abc123');expect(buildPath({ type: 'sessionsBrowser' }, routes)).toBe('/sessions');@@ -131,6 +133,7 @@ describe('matchPath', () => {expect(matchPath('/library', routes)).toEqual({ type: 'library' });expect(matchPath('/library/agent%2Fid', routes)).toEqual({ type: 'libraryAgent', agentId: 'agent/id' });expect(matchPath('/schedules', routes)).toEqual({ type: 'schedules' });+ expect(matchPath('/build-agent', routes)).toEqual({ type: 'buildAgent' });expect(matchPath('/agents/a%2Fb', routes)).toEqual({ type: 'agent', agentName: 'a/b' });expect(matchPath('/sessions', routes)).toEqual({ type: 'sessionsBrowser' });expect(matchPath('/sessions/xyz', routes)).toEqual({ type: 'session', sessionId: 'xyz' });@@ -160,6 +163,7 @@ describe('matchPath', () => {{ type: 'library' as const },{ type: 'libraryAgent' as const, agentId: 'agent id/1' },{ type: 'schedules' as const },+ { type: 'buildAgent' as const },{ type: 'agent' as const, agentName: 'weird name/1' },{ type: 'session' as const, sessionId: 'sess 9' },{ type: 'sessionsBrowser' as const },diff --git a/packages/trueforge-ui/test/server/ShellModeContext.test.tsx b/packages/trueforge-ui/test/server/ShellModeContext.test.tsxindex 5a9ffbbe3..93832813c 100644--- a/packages/trueforge-ui/test/server/ShellModeContext.test.tsx+++ b/packages/trueforge-ui/test/server/ShellModeContext.test.tsx@@ -443,20 +443,68 @@ describe('ShellModeProvider', () => {expect(result.current.listSessionsAgentId).toBeUndefined();expect(result.current.historyAgentFilter).toBeNull();- act(() => result.current.setHistoryAgentFilter('from-sdk'));- expect(result.current.historyAgentFilter).toBe('from-sdk');+ act(() =>+ result.current.setHistoryAgentFilter({+ agentId: 'from-sdk',+ agentName: 'From SDK',+ intent: 'history',+ }),+ );+ expect(result.current.historyAgentFilter).toEqual({+ agentId: 'from-sdk',+ agentName: 'From SDK',+ intent: 'history',+ });expect(result.current.listSessionsAgentId).toBe('from-sdk');act(() => result.current.setHistoryAgentFilter(null));expect(result.current.listSessionsAgentId).toBeUndefined();});+ it('filters history to an immutable agent selected from the library', () => {+ const { result } = renderHook(() => useShellMode(), {+ wrapper: wrap({ mode: 'AgentLibraryWithComposer' }),+ });++ act(() =>+ result.current.selectLibraryAgent({+ isMutable: false,+ agentId: 'agent-id',+ agentName: 'Agent Name',+ }),+ );++ expect(result.current.historyAgentFilter).toEqual({+ agentId: 'agent-id',+ agentName: 'Agent Name',+ intent: 'try-agent',+ });+ expect(result.current.listSessionsAgentId).toBe('agent-id');+ });++ it('does not use an agent name as the history agent id', () => {+ const { result } = renderHook(() => useShellMode(), {+ wrapper: wrap({ mode: 'AgentLibraryWithComposer' }),+ });++ act(() => result.current.selectLibraryAgent({ isMutable: false, agentName: 'Agent Name' }));++ expect(result.current.historyAgentFilter).toBeNull();+ expect(result.current.listSessionsAgentId).toBeUndefined();+ });+it('SingleAgent locks listSessionsAgentId to the agent name', () => {const { result } = renderHook(() => useShellMode(), {wrapper: wrap({ mode: 'SingleAgent', name: 'locked' }),});expect(result.current.listSessionsAgentId).toBe('locked');- act(() => result.current.setHistoryAgentFilter('ignored'));+ act(() =>+ result.current.setHistoryAgentFilter({+ agentId: 'ignored',+ agentName: 'Ignored',+ intent: 'history',+ }),+ );expect(result.current.listSessionsAgentId).toBe('locked');});diff --git a/packages/trueforge-ui/test/utils/historyAgentSearch.test.ts b/packages/trueforge-ui/test/utils/historyAgentSearch.test.tsnew file mode 100644index 000000000..dab6624de--- /dev/null+++ b/packages/trueforge-ui/test/utils/historyAgentSearch.test.ts@@ -0,0 +1,42 @@+import assert from 'node:assert/strict';+import { describe, it } from 'vitest';++import {+ readHistoryAgentSearch,+ updateHistoryAgentSearch,+ writeHistoryAgentSearch,+} from '@/utils/historyAgentSearch.js';++describe('historyAgentSearch', () => {+ it('reads one agent intent and gives Try Agent precedence for malformed input', () => {+ assert.deepEqual(readHistoryAgentSearch('?try_agent_name=Helper'), {+ intent: 'try-agent',+ agentName: 'Helper',+ });+ assert.deepEqual(readHistoryAgentSearch('?history_agent_name=Writer'), {+ intent: 'history',+ agentName: 'Writer',+ });+ assert.deepEqual(readHistoryAgentSearch('?try_agent_name=Helper&history_agent_name=Writer'), {+ intent: 'try-agent',+ agentName: 'Helper',+ });+ assert.equal(readHistoryAgentSearch('?try_agent_name='), null);+ });++ it('writes mutually exclusive keys without dropping host query state', () => {+ const params = new URLSearchParams('theme=dark&history_agent_name=Writer');+ writeHistoryAgentSearch(params, { intent: 'try-agent', agentName: 'Helper' });+ assert.equal(params.toString(), 'theme=dark&try_agent_name=Helper');++ writeHistoryAgentSearch(params, { intent: 'history', agentName: 'Writer' });+ assert.equal(params.toString(), 'theme=dark&history_agent_name=Writer');++ writeHistoryAgentSearch(params, null);+ assert.equal(params.toString(), 'theme=dark');+ assert.equal(+ updateHistoryAgentSearch('?theme=dark', { intent: 'history', agentName: 'Support Agent' }),+ '?theme=dark&history_agent_name=Support+Agent',+ );+ });+});