The open-source agent harness - the runtime layer that turns an LLM into a working agent.
feat: add Web search as a Built-in connector in New Chat (#1020)
harshil-2096bf619ad450ff
diff --git a/.changeset/chat-web-search-connector-toggle.md b/.changeset/chat-web-search-connector-toggle.mdnew file mode 100644index 000000000..e08a2891b--- /dev/null+++ b/.changeset/chat-web-search-connector-toggle.md@@ -0,0 +1,5 @@+---+'@truefoundry/trueforge-ui': patch+---++Show Web search as a Built-in connector toggle in New Chat, persist an explicit chat draft choice across New Chat / reload, and restore capability-forced off only when the user never chose off.diff --git a/packages/trueforge-ui/src/atoms/draft/DraftCompositeSelector.tsx b/packages/trueforge-ui/src/atoms/draft/DraftCompositeSelector.tsxindex acb900ccb..d387ec5f1 100644--- a/packages/trueforge-ui/src/atoms/draft/DraftCompositeSelector.tsx+++ b/packages/trueforge-ui/src/atoms/draft/DraftCompositeSelector.tsx@@ -69,6 +69,7 @@ export function CatalogRow({fallbackIcon,checked,disabled = false,+ disabledReason,selectionControl = 'checkbox',onToggle,onActivate,@@ -82,6 +83,8 @@ export function CatalogRow({fallbackIcon?: string;checked: boolean;disabled?: boolean;+ /** Shown on hover when `disabled` — e.g. host capability unavailable. */+ disabledReason?: string;selectionControl?: 'checkbox' | 'radio';onToggle: () => void;onActivate?: () => void;@@ -127,43 +130,66 @@ export function CatalogRow({);const role = selectionControl === 'radio' ? 'menuitemradio' : 'menuitemcheckbox';+ const controlButton = (+ <button+ type="button"+ role={selectionControl === 'radio' ? 'radio' : 'checkbox'}+ aria-checked={checked}+ aria-label={`${checked ? 'Deselect' : 'Select'} ${title}`}+ disabled={disabled}+ className="shrink-0 disabled:cursor-not-allowed disabled:opacity-50"+ onClick={event => {+ event.stopPropagation();+ if (disabled) return;+ onToggle();+ }}+ >+ {control}+ </button>+ );+ // Tooltip only on the control — row hover must not surface the disabled reason.+ const selectionControlNode =+ disabled && disabledReason ? (+ <Tooltip content={disabledReason} className="max-w-xs text-left">+ <span className="inline-flex shrink-0">{controlButton}</span>+ </Tooltip>+ ) : (+ controlButton+ );- if (action || onActivate) {+ if (action || onActivate || disabled) {return (<divrole={role}aria-checked={checked}- tabIndex={0}- className="hover:bg-ghost-button-hover flex w-full cursor-pointer items-center gap-2 rounded-md px-2 py-2 text-left"- onClick={onActivate ?? onToggle}+ aria-disabled={disabled || undefined}+ tabIndex={disabled ? -1 : 0}+ className={cn(+ 'hover:bg-ghost-button-hover flex w-full cursor-pointer items-center gap-2 rounded-md px-2 py-2 text-left',+ disabled && 'cursor-default opacity-50 hover:bg-transparent',+ )}+ onClick={() => {+ if (disabled) return;+ (onActivate ?? onToggle)();+ }}onKeyDown={event => {if (event.key !== 'Enter' && event.key !== ' ') return;event.preventDefault();+ if (disabled) return;(onActivate ?? onToggle)();}}>{content}- <span- className="shrink-0"- onClick={event => event.stopPropagation()}- onKeyDown={event => event.stopPropagation()}- >- {action}- </span>- <button- type="button"- role={selectionControl === 'radio' ? 'radio' : 'checkbox'}- aria-checked={checked}- aria-label={`${checked ? 'Deselect' : 'Select'} ${title}`}- disabled={disabled}- className="shrink-0 disabled:cursor-not-allowed disabled:opacity-50"- onClick={event => {- event.stopPropagation();- onToggle();- }}- >- {control}- </button>+ {action ? (+ <span+ className="shrink-0"+ onClick={event => event.stopPropagation()}+ onKeyDown={event => event.stopPropagation()}+ >+ {action}+ </span>+ ) : null}+ {selectionControlNode}</div>);}@@ -173,12 +199,11 @@ export function CatalogRow({type="button"role={role}aria-checked={checked}- disabled={disabled}- 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"+ className="hover:bg-ghost-button-hover flex w-full cursor-pointer items-center gap-2 rounded-md px-2 py-2 text-left"onClick={onToggle}>{content}- {disabled ? <Icon name="lock" className="text-text-secondary size-3" /> : control}+ {control}</button>);}@@ -255,10 +280,14 @@ export type DraftCompositeSelectorProps = {onAttach?: () => void;};-function SectionHeading({ label, count }: { label: string; count: number }) {+const NO_WEB_SEARCH_PROVIDER_HINT = 'Web search is not configured';+const WEB_SEARCH_BUILTIN_TITLE = 'Web search';+const WEB_SEARCH_BUILTIN_DESCRIPTION = 'Search the web for up-to-date answers';++function SectionHeading({ label, count }: { label: string; count?: number }) {return (<div className="text-text-secondary px-3 pt-2 pb-1 text-[0.6875rem] font-medium tracking-wide uppercase">- {label} ({count})+ {count == null ? label : `${label} (${count})`}</div>);}@@ -293,6 +322,8 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftCconst compactLayout = useCompactLayout();const skillsDisabled = capabilities?.skill.enabled !== true;const skillsDisabledReason = capabilities?.skill.reason;+ const webSearchCapabilityEnabled = capabilities?.webSearch?.enabled === true;+ const webSearchEnabled = agentSpec?.config?.webSearch?.enabled ?? webSearchCapabilityEnabled;const needsSandbox = capabilities?.sandbox.enabled === false;const settingsEnabled = capabilities?.settings?.enabled !== false;const canConfigureConnectors = settingsEnabled && settingsCatalog?.connectorCatalog != null;@@ -306,7 +337,7 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftCconst selectedSkills = open ? localSkills : specSkills;const selectedMcpIds = useMemo(() => new Set(selectedMcp.map(m => m.id)), [selectedMcp]);const hasValidModel = Boolean(agentSpec?.model?.name.trim());- const toolsCount = selectedMcp.length + selectedSkills.length;+ const toolsCount = selectedMcp.length + selectedSkills.length + (webSearchEnabled ? 1 : 0);const toolsTooltip = useMemo(() => {const formatNames = (items: Array<{ name: string }>) => {const names = items.map(item => item.name);@@ -314,6 +345,9 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftCreturn `${names.slice(0, 4).join(', ')} +${names.length - 4}`;};const lines: string[] = [];+ if (webSearchEnabled) {+ lines.push(`Built-in: ${WEB_SEARCH_BUILTIN_TITLE}`);+ }if (selectedMcp.length > 0) {lines.push(`Connectors: ${formatNames(selectedMcp)}`);}@@ -321,7 +355,7 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftClines.push(`Skills: ${formatNames(selectedSkills)}`);}return lines.length > 0 ? lines.join('\n') : 'No connectors or skills selected';- }, [selectedMcp, selectedSkills]);+ }, [selectedMcp, selectedSkills, webSearchEnabled]);const clearFlushTimer = useCallback(() => {if (flushTimerRef.current != null) {@@ -440,6 +474,30 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftCscheduleFlush();};+ const toggleWebSearch = () => {+ if (!webSearchCapabilityEnabled || agentSpec == null) return;+ const nextEnabled = !webSearchEnabled;+ const nextSpec = {+ ...agentSpec,+ config: {+ ...agentSpec.config,+ webSearch: { enabled: nextEnabled },+ },+ };+ updateAgentSpec?.({ config: nextSpec.config });+ // Flush seed immediately — New Chat can run before the preference bridge effect.+ shell?.rememberDraftSpec(nextSpec, 'chat');+ };++ const showWebSearchBuiltin = useMemo(() => {+ const needle = query.trim().toLowerCase();+ if (!needle) return true;+ return (+ WEB_SEARCH_BUILTIN_TITLE.toLowerCase().includes(needle) ||+ WEB_SEARCH_BUILTIN_DESCRIPTION.toLowerCase().includes(needle)+ );+ }, [query]);+const toggleSkill = (skill: AgentSkill) => {const family = skillFamilyId(skill.id);const adding = !localSkillsRef.current.some(item => skillFamilyId(item.id) === family);@@ -598,6 +656,20 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftC<div className="min-h-0 flex-1 overflow-y-auto px-1 pb-2">{tab === 'connectors' ? (<>+ {showWebSearchBuiltin ? (+ <>+ <SectionHeading label="Built-in" />+ <CatalogRow+ title={WEB_SEARCH_BUILTIN_TITLE}+ description={WEB_SEARCH_BUILTIN_DESCRIPTION}+ fallbackIcon="searchGlobe"+ checked={webSearchEnabled}+ disabled={!webSearchCapabilityEnabled}+ disabledReason={NO_WEB_SEARCH_PROVIDER_HINT}+ onToggle={toggleWebSearch}+ />+ </>+ ) : null}{pinnedSelectedConnectors.length > 0 ? (<><SectionHeading label="Selected" count={pinnedSelectedConnectors.length} />@@ -638,7 +710,7 @@ export function DraftCompositeSelector({ disabled, isRunning, onAttach }: DraftC))}</>) : null}- {filteredConnectors.length === 0 && connectors.length > 0 ? (+ {filteredConnectors.length === 0 && connectors.length > 0 && !showWebSearchBuiltin ? (<DraftCatalogEmptyState loading={loading} emptyLabel="No connectors" settingsTarget="Connectors" />) : null}{connectors.length === 0 ? (diff --git a/packages/trueforge-ui/src/atoms/draft/DraftSpecPreferenceBridge.tsx b/packages/trueforge-ui/src/atoms/draft/DraftSpecPreferenceBridge.tsxindex 9f68df2ca..f321c2914 100644--- a/packages/trueforge-ui/src/atoms/draft/DraftSpecPreferenceBridge.tsx+++ b/packages/trueforge-ui/src/atoms/draft/DraftSpecPreferenceBridge.tsx@@ -1,10 +1,12 @@'use client';import { useTrueForgeAgentSpec, useTrueForgeUpdateAgentSpec } from '@truefoundry/trueforge-assistant-ui-runtime';-import { useEffect } from 'react';+import { useEffect, useRef } from 'react';import {type DraftPreferenceKind,+ persistedWebSearchEnabled,+ recoverWebSearchAfterCapabilityAvailable,withCapabilitiesSandbox,withCapabilitiesWebSearch,} from '../../server/draftSpecPreferences.js';@@ -118,20 +120,32 @@ export function reconcileDraftSandbox({export function reconcileDraftWebSearch({agentSpec,webSearchEnabled,+ previousWebSearchEnabled,+ explicitOff = false,kind = 'agent',}: {agentSpec: AgentSpec;webSearchEnabled: boolean | null | undefined;+ previousWebSearchEnabled?: boolean | null | undefined;+ explicitOff?: boolean;kind?: DraftPreferenceKind;}): Partial<AgentSpec> {- const nextSpec = withCapabilitiesWebSearch({ spec: agentSpec, webSearchEnabled, kind });+ const recovered = recoverWebSearchAfterCapabilityAvailable({+ spec: agentSpec,+ previousWebSearchEnabled,+ webSearchEnabled,+ explicitOff,+ kind,+ });+ const nextSpec = withCapabilitiesWebSearch({ spec: recovered, webSearchEnabled, kind });return nextSpec === agentSpec ? {} : { config: nextSpec.config };}/*** Mirrors plain-draft composer choices into the shell seed and removes catalog* entries that disappeared since those choices were stored.- * New Chat and New Agent keep separate seeds; chat never persists runtime config.+ * New Chat and New Agent keep separate seeds; chat persists web-search only+ * among runtime config fields.*/export function DraftSpecPreferenceBridge() {const { mode, pendingSessionId, rememberDraftSpec } = useShellMode();@@ -140,14 +154,11 @@ export function DraftSpecPreferenceBridge() {const capabilities = useServerCapabilities();const sandboxEnabled = capabilities?.sandbox.enabled;const webSearchEnabled = capabilities?.webSearch?.enabled;+ const prevWebSearchEnabledRef = useRef(webSearchEnabled);const { models, skills, connectors, loaded, error, ensureLoaded } = useDraftCatalog();const isMutableDraft = mode.status === 'active' && mode.isMutable && pendingSessionId == null;const isPlainDraft = isMutableDraft && mode.agentId == null;const preferenceKind = mode.status === 'active' && mode.isMutable && mode.isCreateAgent ? 'agent' : 'chat';- // New Chat forces on; New Agent + edit existing only fill when absent.- const webSearchKind: DraftPreferenceKind =- mode.status === 'active' && mode.isMutable && (mode.isCreateAgent || mode.agentId != null) ? 'agent' : 'chat';-useEffect(() => {if (isPlainDraft) ensureLoaded();}, [ensureLoaded, isPlainDraft]);@@ -169,12 +180,22 @@ export function DraftSpecPreferenceBridge() {useEffect(() => {// Apply to New Chat / New Agent / edit-existing mutable drafts.+ // Available → default on when absent; unavailable → force off. Explicit toggles are preserved.+ // Force-off recovery is only for plain drafts, and only when no choice was stored.+ const previousWebSearchEnabled = prevWebSearchEnabledRef.current;+ prevWebSearchEnabledRef.current = webSearchEnabled;if (!isMutableDraft || agentSpec == null || updateAgentSpec == null) return;- const update = reconcileDraftWebSearch({ agentSpec, webSearchEnabled, kind: webSearchKind });+ const update = reconcileDraftWebSearch({+ agentSpec,+ webSearchEnabled,+ previousWebSearchEnabled: isPlainDraft ? previousWebSearchEnabled : undefined,+ explicitOff: isPlainDraft && persistedWebSearchEnabled(preferenceKind) === false,+ kind: preferenceKind,+ });if (Object.keys(update).length > 0) {updateAgentSpec(update);}- }, [agentSpec, isMutableDraft, webSearchEnabled, webSearchKind, updateAgentSpec]);+ }, [agentSpec, isMutableDraft, isPlainDraft, preferenceKind, webSearchEnabled, updateAgentSpec]);useEffect(() => {if (!isPlainDraft || agentSpec == null || updateAgentSpec == null || !loaded || error != null) return;diff --git a/packages/trueforge-ui/src/server/ShellModeContext.tsx b/packages/trueforge-ui/src/server/ShellModeContext.tsxindex a88c40b83..5ff625eb6 100644--- a/packages/trueforge-ui/src/server/ShellModeContext.tsx+++ b/packages/trueforge-ui/src/server/ShellModeContext.tsx@@ -7,6 +7,7 @@ import { replaceSessionShareSearch } from '../utils/sessionShareUrl.js';import {readDraftSpecPreferences,selectDraftSpecPreferences,+ webSearchPreferenceToStore,withCapabilitiesSandbox,withCapabilitiesWebSearch,writeDraftSpecPreferences,@@ -572,7 +573,11 @@ export function ShellModeProvider({if (!isComposerEnabled) return;refreshCapabilities?.();setHistoryAgentFilter(null);- selectLibraryAgent({ isMutable: true, isCreateAgent: false, agentSpec: chatSeedRef.current });+ // Prefer storage so a just-toggled web-search preference is not lost if the+ // in-memory seed has not been rewritten yet this tick.+ const seed = readDraftSpecPreferences('chat') ?? chatSeedRef.current;+ chatSeedRef.current = seed;+ selectLibraryAgent({ isMutable: true, isCreateAgent: false, agentSpec: seed });}, [isComposerEnabled, refreshCapabilities, selectLibraryAgent]);const isActiveAgentBuilder =@@ -607,27 +612,43 @@ export function ShellModeProvider({const sandboxEnabled = capabilities?.sandbox.enabled;const webSearchEnabled = capabilities?.webSearch?.enabled;+ // Child effects (DraftSpecPreferenceBridge) run before this updates — so remember still+ // sees the prior capability when Settings refresh flips web-search on.+ const prevWebSearchEnabledRef = useRef(webSearchEnabled);+ useEffect(() => {+ prevWebSearchEnabledRef.current = webSearchEnabled;+ }, [webSearchEnabled]);const rememberDraftSpec = useCallback((agentSpec: AgentSpec, kind: DraftPreferenceKind = 'chat') => {+ const previousWebSearchEnabled = prevWebSearchEnabledRef.current;const selected = selectDraftSpecPreferences(agentSpec, kind);const withSandbox = kind === 'agent' ? withCapabilitiesSandbox(selected, sandboxEnabled) : selected;- const preferences =- kind === 'agent'- ? withCapabilitiesWebSearch({- spec: withSandbox,- webSearchEnabled,- kind: 'agent',- })- : withSandbox;+ const aligned = withCapabilitiesWebSearch({+ spec: withSandbox,+ webSearchEnabled,+ kind,+ });+ const preferences = webSearchPreferenceToStore({+ spec: aligned,+ webSearchEnabled,+ previousWebSearchEnabled,+ kind,+ });if (kind === 'chat') {chatSeedRef.current = preferences;} else {// Keep the active builder intact in memory; storage remains limited to reusable preferences.- agentSeedRef.current = withCapabilitiesWebSearch({+ const agentAligned = withCapabilitiesWebSearch({spec: withCapabilitiesSandbox(agentSpec, sandboxEnabled),webSearchEnabled,kind: 'agent',});+ agentSeedRef.current = webSearchPreferenceToStore({+ spec: agentAligned,+ webSearchEnabled,+ previousWebSearchEnabled,+ kind: 'agent',+ });}writeDraftSpecPreferences(kind, preferences);},@@ -700,15 +721,24 @@ export function ShellModeProvider({if (effectiveMode.status === 'idle') return;setPendingSessionId(undefined);if (effectiveMode.isMutable) {- // Preserve Edit / builder vs chat intent; blank drafts fall back to host seed.+ // Preserve Edit / builder vs chat intent. New Chat must use the latest+ // chat seed (storage), not the stale mode.agentSpec from draft open —+ // toggles like web search update the seed without rewriting mode.agentSpec.const kind: DraftPreferenceKind = effectiveMode.isCreateAgent ? 'agent' : 'chat';+ const agentSpec =+ kind === 'chat'+ ? (readDraftSpecPreferences('chat') ?? chatSeedRef.current)+ : (effectiveMode.agentSpec ?? agentSeedRef.current);+ if (kind === 'chat') {+ chatSeedRef.current = agentSpec;+ }setMode({status: 'active',isMutable: true,isCreateAgent: effectiveMode.isCreateAgent,agentId: effectiveMode.agentId,agentName: effectiveMode.agentName,- agentSpec: effectiveMode.agentSpec ?? (kind === 'agent' ? agentSeedRef.current : chatSeedRef.current),+ agentSpec,locked: false,});setAgentConfigOpenState(effectiveMode.isCreateAgent);diff --git a/packages/trueforge-ui/src/server/draftSpecPreferences.ts b/packages/trueforge-ui/src/server/draftSpecPreferences.tsindex 9e7f38e78..0b42a1a86 100644--- a/packages/trueforge-ui/src/server/draftSpecPreferences.ts+++ b/packages/trueforge-ui/src/server/draftSpecPreferences.ts@@ -46,12 +46,32 @@ function storageKeyForKind(kind: DraftPreferenceKind): string {return kind === 'chat' ? CHAT_DRAFT_SPEC_PREFERENCES_STORAGE_KEY : AGENT_DRAFT_SPEC_PREFERENCES_STORAGE_KEY;}-/** New Chat: model (+ reasoning params), skills, and MCP only — no runtime config. */+function readSandboxEnabled(spec: AgentSpec): boolean | undefined {+ if (spec.config === undefined) return undefined;+ // `sandbox` is persisted on draft config but is not part of AgentRuntimeConfig.+ const sandbox = Reflect.get(spec.config, 'sandbox');+ if (!isObject(sandbox)) return undefined;+ const enabled = Reflect.get(sandbox, 'enabled');+ return typeof enabled === 'boolean' ? enabled : undefined;+}++function readWebSearchEnabled(spec: AgentSpec): boolean | undefined {+ if (spec.config?.webSearch === undefined) return undefined;+ const enabled = spec.config.webSearch.enabled;+ return typeof enabled === 'boolean' ? enabled : undefined;+}++/**+ * New Chat: model (+ reasoning params), skills, MCP, and the web-search toggle.+ * Other runtime config (sandbox, ask-user, …) is not persisted for chat.+ */export function selectChatDraftSpecPreferences(spec: AgentSpec): AgentSpec {+ const webSearchEnabled = readWebSearchEnabled(spec);return {model: spec.model,...(spec.skills !== undefined ? { skills: spec.skills } : {}),...(spec.mcpServers !== undefined ? { mcpServers: spec.mcpServers } : {}),+ ...(webSearchEnabled !== undefined ? { config: { webSearch: { enabled: webSearchEnabled } } } : {}),};}@@ -67,21 +87,6 @@ export function selectDraftSpecPreferences(spec: AgentSpec, kind: DraftPreferencreturn kind === 'chat' ? selectChatDraftSpecPreferences(spec) : selectAgentDraftSpecPreferences(spec);}-function readSandboxEnabled(spec: AgentSpec): boolean | undefined {- if (spec.config === undefined) return undefined;- // `sandbox` is persisted on draft config but is not part of AgentRuntimeConfig.- const sandbox = Reflect.get(spec.config, 'sandbox');- if (!isObject(sandbox)) return undefined;- const enabled = Reflect.get(sandbox, 'enabled');- return typeof enabled === 'boolean' ? enabled : undefined;-}--function readWebSearchEnabled(spec: AgentSpec): boolean | undefined {- if (spec.config?.webSearch === undefined) return undefined;- const enabled = spec.config.webSearch.enabled;- return typeof enabled === 'boolean' ? enabled : undefined;-}-/** Disable sandbox when unavailable; availability must not override the user's runtime choice. */export function withCapabilitiesSandbox(spec: AgentSpec, sandboxEnabled: boolean | null | undefined): AgentSpec {if (sandboxEnabled !== false || readSandboxEnabled(spec) === false) return spec;@@ -97,17 +102,16 @@ export function withCapabilitiesSandbox(spec: AgentSpec, sandboxEnabled: boolean/*** Align `config.webSearch` with host capability.- * - unavailable → force false- * - chat + available → force true- * - agent + available → fill true only when the key is absent (preserve explicit values)+ * - unavailable → force false on the live draft (do not persist — see `withoutWebSearchPreference`)+ * - available → fill true only when the key is absent (preserve explicit user toggles)*/export function withCapabilitiesWebSearch({spec,webSearchEnabled,- kind = 'agent',}: {spec: AgentSpec;webSearchEnabled: boolean | null | undefined;+ /** Kept for call-site compatibility; chat and agent share the same fill/preserve rules. */kind?: DraftPreferenceKind;}): AgentSpec {if (webSearchEnabled == null) return spec;@@ -123,18 +127,7 @@ export function withCapabilitiesWebSearch({};}- if (kind === 'chat') {- if (readWebSearchEnabled(spec) === true) return spec;- return {- ...spec,- config: {- ...spec.config,- webSearch: { ...spec.config?.webSearch, enabled: true },- },- };- }-- // Agent: only default true when the field is missing from the spec.+ // Only default true when the field is missing — chat and agent both keep user toggles.if (spec.config?.webSearch !== undefined) return spec;return {...spec,@@ -145,6 +138,90 @@ export function withCapabilitiesWebSearch({};}+/** Drop webSearch so a capability-forced off is not stored as a user preference. */+export function withoutWebSearchPreference(spec: AgentSpec): AgentSpec {+ if (spec.config?.webSearch === undefined) return spec;+ const { webSearch: _ignored, ...restConfig } = spec.config;+ if (Object.keys(restConfig).length === 0) {+ const { config: _config, ...rest } = spec;+ return rest;+ }+ return { ...spec, config: restConfig };+}++/**+ * When web-search flips unavailable → available, a live `enabled: false` may be leftover+ * force-off. Default-fill on only when that false is not an explicit user/saved choice.+ */+export function recoverWebSearchAfterCapabilityAvailable({+ spec,+ previousWebSearchEnabled,+ webSearchEnabled,+ explicitOff = false,+ kind,+}: {+ spec: AgentSpec;+ previousWebSearchEnabled: boolean | null | undefined;+ webSearchEnabled: boolean | null | undefined;+ /** Saved or previously persisted off — not a capability-forced value. */+ explicitOff?: boolean;+ kind?: DraftPreferenceKind;+}): AgentSpec {+ if (explicitOff) return spec;+ if (previousWebSearchEnabled !== false || webSearchEnabled !== true) return spec;+ if (readWebSearchEnabled(spec) !== false) return spec;+ return withCapabilitiesWebSearch({+ spec: withoutWebSearchPreference(spec),+ webSearchEnabled: true,+ kind,+ });+}++function withWebSearchEnabled(spec: AgentSpec, enabled: boolean): AgentSpec {+ if (readWebSearchEnabled(spec) === enabled) return spec;+ return {+ ...spec,+ config: {+ ...spec.config,+ webSearch: { ...spec.config?.webSearch, enabled },+ },+ };+}++export function persistedWebSearchEnabled(kind: DraftPreferenceKind): boolean | undefined {+ const stored = readDraftSpecPreferences(kind);+ return stored == null ? undefined : readWebSearchEnabled(stored);+}++/**+ * Remember a user web-search choice. Capability-forced off is omitted unless a choice+ * was already stored, and that stored off is not rewritten to on when search returns.+ */+export function webSearchPreferenceToStore({+ spec,+ webSearchEnabled,+ previousWebSearchEnabled,+ kind,+}: {+ spec: AgentSpec;+ webSearchEnabled: boolean | null | undefined;+ previousWebSearchEnabled: boolean | null | undefined;+ kind: DraftPreferenceKind;+}): AgentSpec {+ const persistedEnabled = persistedWebSearchEnabled(kind);+ if (webSearchEnabled === false) {+ const stripped = withoutWebSearchPreference(spec);+ return persistedEnabled === undefined ? stripped : withWebSearchEnabled(stripped, persistedEnabled);+ }+ return recoverWebSearchAfterCapabilityAvailable({+ spec,+ previousWebSearchEnabled,+ webSearchEnabled,+ explicitOff: persistedEnabled === false,+ kind,+ });+}+function readStoredSpec(key: string): AgentSpec | null {if (typeof window === 'undefined') return null;try {diff --git a/packages/trueforge-ui/test/atoms/draft/DraftCompositeSelector.test.tsx b/packages/trueforge-ui/test/atoms/draft/DraftCompositeSelector.test.tsxindex d01980507..d55fb463b 100644--- a/packages/trueforge-ui/test/atoms/draft/DraftCompositeSelector.test.tsx+++ b/packages/trueforge-ui/test/atoms/draft/DraftCompositeSelector.test.tsx@@ -1,5 +1,5 @@// @vitest-environment jsdom-import { act, fireEvent, render, screen } from '@testing-library/react';+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';import { DraftCatalogProvider } from '@/atoms/draft/DraftCatalogProvider.js';@@ -23,6 +23,7 @@ import {let agentSpec: AgentSpec;const updateAgentSpec = vi.fn();const setSettingsOpen = vi.fn();+const rememberDraftSpec = vi.fn();async function unavailable(): Promise<never> {throw new Error('Unexpected settings catalog call');@@ -51,7 +52,7 @@ vi.mock('@truefoundry/trueforge-assistant-ui-runtime', () => ({}));vi.mock('@/server/ShellModeContext.js', () => ({- useOptionalShellMode: () => ({ setSettingsOpen, setEnvironmentsOpen }),+ useOptionalShellMode: () => ({ setSettingsOpen, setEnvironmentsOpen, rememberDraftSpec }),}));beforeAll(() => {@@ -79,6 +80,7 @@ function renderSelector({sandbox: { enabled: boolean };skill: { enabled: boolean; reason?: string };settings?: { enabled: boolean };+ webSearch?: { enabled: boolean };};}>;getSkills?: () => Promise<AgentSkill[]>;@@ -128,6 +130,7 @@ describe('DraftCompositeSelector', () => {updateAgentSpec.mockReset();setSettingsOpen.mockReset();setEnvironmentsOpen.mockReset();+ rememberDraftSpec.mockReset();});afterEach(() => {@@ -469,4 +472,80 @@ describe('DraftCompositeSelector', () => {}),});});++ it('shows Web search under Built-in and toggles draft config when available', async () => {+ agentSpec = {+ ...agentSpec,+ config: { webSearch: { enabled: true } },+ };+ renderSelector({+ getCapabilities: async () => ({+ data: {+ sandbox: { enabled: true },+ skill: { enabled: true },+ webSearch: { enabled: true },+ },+ }),+ });++ fireEvent.click(screen.getByRole('button', { name: 'Tools (3)' }));+ expect(screen.getByText('Built-in')).toBeInTheDocument();+ await waitFor(() => {+ const row = screen.getByRole('menuitemcheckbox', { name: /Web search/ });+ expect(row).toBeEnabled();+ expect(row).toHaveAttribute('aria-checked', 'true');+ });++ fireEvent.click(screen.getByRole('menuitemcheckbox', { name: /Web search/ }));+ expect(updateAgentSpec).toHaveBeenCalledWith({+ config: { webSearch: { enabled: false } },+ });+ expect(rememberDraftSpec).toHaveBeenCalledWith(+ {+ ...agentSpec,+ config: { webSearch: { enabled: false } },+ },+ 'chat',+ );+ });++ it('keeps Web search disabled with a tooltip when the capability is off', async () => {+ agentSpec = {+ ...agentSpec,+ config: { webSearch: { enabled: false } },+ };+ renderSelector({+ getCapabilities: async () => ({+ data: {+ sandbox: { enabled: true },+ skill: { enabled: true },+ webSearch: { enabled: false },+ },+ }),+ });++ fireEvent.click(screen.getByRole('button', { name: 'Tools (2)' }));+ await waitFor(() => {+ const row = screen.getByRole('menuitemcheckbox', { name: /Web search/ });+ expect(row).toHaveAttribute('aria-disabled', 'true');+ expect(row).toHaveAttribute('aria-checked', 'false');+ });++ const checkbox = screen.getByRole('checkbox', { name: /Select Web search/ });+ expect(checkbox).toBeDisabled();+ fireEvent.mouseEnter(checkbox.parentElement!);+ expect(await screen.findByRole('tooltip')).toHaveTextContent('Web search is not configured');++ fireEvent.mouseLeave(checkbox.parentElement!);+ await act(async () => {+ await vi.advanceTimersByTimeAsync(150);+ });+ expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();++ fireEvent.mouseEnter(screen.getByRole('menuitemcheckbox', { name: /Web search/ }));+ expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();++ fireEvent.click(checkbox);+ expect(updateAgentSpec).not.toHaveBeenCalled();+ });});diff --git a/packages/trueforge-ui/test/server/ShellModeContext.test.tsx b/packages/trueforge-ui/test/server/ShellModeContext.test.tsxindex ca8744336..929151935 100644--- a/packages/trueforge-ui/test/server/ShellModeContext.test.tsx+++ b/packages/trueforge-ui/test/server/ShellModeContext.test.tsx@@ -399,6 +399,89 @@ describe('ShellModeProvider', () => {expect(result.current.runtimeKey).not.toBe(keyBefore);});+ it('clearChat and openDraft keep a disabled chat web-search preference', () => {+ const { result } = renderHook(() => useShellMode(), {+ wrapper: wrap({+ mode: 'AgentComposer',+ defaultAgentSpec: {+ model: { name: 'openai-main/gpt-4.1' },+ config: { webSearch: { enabled: true } },+ },+ }),+ });++ act(() =>+ result.current.rememberDraftSpec(+ {+ model: { name: 'openai-main/gpt-4.1' },+ config: { webSearch: { enabled: false } },+ },+ 'chat',+ ),+ );++ act(() => result.current.clearChat());+ expect(result.current.mode).toMatchObject({+ status: 'active',+ isMutable: true,+ isCreateAgent: false,+ agentSpec: { config: { webSearch: { enabled: false } } },+ });++ act(() =>+ result.current.rememberDraftSpec(+ {+ model: { name: 'openai-main/gpt-4.1' },+ config: { webSearch: { enabled: false } },+ },+ 'chat',+ ),+ );+ act(() => result.current.openDraft());+ expect(result.current.mode).toMatchObject({+ agentSpec: { config: { webSearch: { enabled: false } } },+ });+ });++ it('does not persist capability-forced web-search off as a chat preference', async () => {+ const getCapabilities = vi.fn(async () => ({+ data: {+ sandbox: { enabled: true },+ skill: { enabled: true },+ settings: { enabled: true },+ webSearch: { enabled: false },+ },+ }));+ const server = createMockAgentUIServer({ catalog: createMockCatalog(), getCapabilities });+ const { result } = renderHook(+ () => ({+ shell: useShellMode(),+ capabilities: useServerCapabilities(),+ }),+ {+ wrapper: wrapWithServer(server, {+ mode: 'AgentComposer',+ defaultAgentSpec: { model: { name: 'openai-main/gpt-4.1' } },+ }),+ },+ );+ await waitFor(() => expect(result.current.capabilities?.webSearch?.enabled).toBe(false));++ act(() =>+ result.current.shell.rememberDraftSpec(+ {+ model: { name: 'openai-main/gpt-4.1' },+ config: { webSearch: { enabled: true } },+ },+ 'chat',+ ),+ );++ expect(readDraftSpecPreferences('chat')).toEqual({+ model: { name: 'openai-main/gpt-4.1' },+ });+ });+it('clearChat is a no-op while idle', () => {const { result } = renderHook(() => useShellMode(), {wrapper: wrap({ mode: 'AgentLibrary' }),diff --git a/packages/trueforge-ui/test/server/draftSpecPreferences.test.ts b/packages/trueforge-ui/test/server/draftSpecPreferences.test.tsindex 7e432f230..f1610d4d1 100644--- a/packages/trueforge-ui/test/server/draftSpecPreferences.test.ts+++ b/packages/trueforge-ui/test/server/draftSpecPreferences.test.ts@@ -6,30 +6,43 @@ import {CHAT_DRAFT_SPEC_PREFERENCES_STORAGE_KEY,DRAFT_SPEC_PREFERENCES_STORAGE_KEY,readDraftSpecPreferences,+ recoverWebSearchAfterCapabilityAvailable,selectAgentDraftSpecPreferences,selectChatDraftSpecPreferences,+ webSearchPreferenceToStore,withCapabilitiesSandbox,withCapabilitiesWebSearch,+ withoutWebSearchPreference,writeDraftSpecPreferences,} from '@/server/draftSpecPreferences.js';describe('selectDraftSpecPreferences', () => {- it('keeps only model, skills, and MCP for chat', () => {+ it('keeps model, skills, MCP, and web-search for chat — not other runtime config', () => {expect(selectChatDraftSpecPreferences({model: { name: 'm', params: { reasoningEffort: 'high' } },skills: [{ name: 's' }],mcpServers: [{ name: 'c' }],- config: { sandbox: { enabled: true } },+ config: { sandbox: { enabled: true }, webSearch: { enabled: false } },instructions: 'nope',}),).toEqual({model: { name: 'm', params: { reasoningEffort: 'high' } },skills: [{ name: 's' }],mcpServers: [{ name: 'c' }],+ config: { webSearch: { enabled: false } },});});+ it('omits chat config when web search was never set', () => {+ expect(+ selectChatDraftSpecPreferences({+ model: { name: 'm' },+ config: { sandbox: { enabled: true } },+ }),+ ).toEqual({ model: { name: 'm' } });+ });+it('keeps runtime config for agent', () => {expect(selectAgentDraftSpecPreferences({@@ -68,6 +81,18 @@ describe('draft preference storage', () => {});});+ it('persists the chat web-search toggle across read/write', () => {+ writeDraftSpecPreferences('chat', {+ model: { name: 'chat/model' },+ config: { sandbox: { enabled: true }, webSearch: { enabled: false } },+ });++ expect(readDraftSpecPreferences('chat')).toEqual({+ model: { name: 'chat/model' },+ config: { webSearch: { enabled: false } },+ });+ });+it('migrates the legacy shared key into both stores', () => {window.localStorage.setItem(DRAFT_SPEC_PREFERENCES_STORAGE_KEY,@@ -191,10 +216,16 @@ describe('withCapabilitiesWebSearch', () => {});});- it('forces true for New Chat when the capability is on', () => {+ it('preserves an explicit chat toggle when the capability is on', () => {+ const spec = { model: { name: 'model' }, config: { webSearch: { enabled: false } } };++ expect(withCapabilitiesWebSearch({ spec, webSearchEnabled: true, kind: 'chat' })).toBe(spec);+ });++ it('fills true when the field is absent and the capability is on', () => {expect(withCapabilitiesWebSearch({- spec: { model: { name: 'model' }, config: { webSearch: { enabled: false } } },+ spec: { model: { name: 'model' } },webSearchEnabled: true,kind: 'chat',}),@@ -204,12 +235,56 @@ describe('withCapabilitiesWebSearch', () => {});});- it('fills true for New Agent when the field is absent', () => {+ it('preserves an explicit agent value when the capability is on', () => {+ const spec = { model: { name: 'model' }, config: { webSearch: { enabled: false } } };++ expect(withCapabilitiesWebSearch({ spec, webSearchEnabled: true, kind: 'agent' })).toBe(spec);+ });++ it('does not change the spec while capabilities are still loading', () => {+ const spec = { model: { name: 'model' } };++ expect(withCapabilitiesWebSearch({ spec, webSearchEnabled: undefined, kind: 'chat' })).toBe(spec);+ expect(withCapabilitiesWebSearch({ spec, webSearchEnabled: null, kind: 'agent' })).toBe(spec);+ });+});++describe('withoutWebSearchPreference', () => {+ it('removes webSearch and drops empty config', () => {+ expect(+ withoutWebSearchPreference({+ model: { name: 'model' },+ config: { webSearch: { enabled: false } },+ }),+ ).toEqual({ model: { name: 'model' } });+ });++ it('keeps other config fields', () => {+ expect(+ withoutWebSearchPreference({+ model: { name: 'model' },+ config: { sandbox: { enabled: true }, webSearch: { enabled: false } },+ }),+ ).toEqual({+ model: { name: 'model' },+ config: { sandbox: { enabled: true } },+ });+ });++ it('returns the same spec when webSearch is already absent', () => {+ const spec = { model: { name: 'model' } };+ expect(withoutWebSearchPreference(spec)).toBe(spec);+ });+});++describe('recoverWebSearchAfterCapabilityAvailable', () => {+ it('default-fills on when capability flips unavailable → available with forced-off live', () => {expect(- withCapabilitiesWebSearch({- spec: { model: { name: 'model' } },+ recoverWebSearchAfterCapabilityAvailable({+ spec: { model: { name: 'model' }, config: { webSearch: { enabled: false } } },+ previousWebSearchEnabled: false,webSearchEnabled: true,- kind: 'agent',+ kind: 'chat',}),).toEqual({model: { name: 'model' },@@ -217,16 +292,96 @@ describe('withCapabilitiesWebSearch', () => {});});- it('preserves an explicit agent value when the capability is on', () => {+ it('is a no-op when capability did not just become available', () => {const spec = { model: { name: 'model' }, config: { webSearch: { enabled: false } } };+ expect(+ recoverWebSearchAfterCapabilityAvailable({+ spec,+ previousWebSearchEnabled: true,+ webSearchEnabled: true,+ kind: 'chat',+ }),+ ).toBe(spec);+ });- expect(withCapabilitiesWebSearch({ spec, webSearchEnabled: true, kind: 'agent' })).toBe(spec);+ it('is a no-op when live webSearch is not forced off', () => {+ const spec = { model: { name: 'model' }, config: { webSearch: { enabled: true } } };+ expect(+ recoverWebSearchAfterCapabilityAvailable({+ spec,+ previousWebSearchEnabled: false,+ webSearchEnabled: true,+ kind: 'chat',+ }),+ ).toBe(spec);});- it('does not change the spec while capabilities are still loading', () => {- const spec = { model: { name: 'model' } };+ it('keeps an explicit off when capability becomes available', () => {+ const spec = { model: { name: 'model' }, config: { webSearch: { enabled: false } } };+ expect(+ recoverWebSearchAfterCapabilityAvailable({+ spec,+ previousWebSearchEnabled: false,+ webSearchEnabled: true,+ explicitOff: true,+ kind: 'chat',+ }),+ ).toBe(spec);+ });+});- expect(withCapabilitiesWebSearch({ spec, webSearchEnabled: undefined, kind: 'chat' })).toBe(spec);- expect(withCapabilitiesWebSearch({ spec, webSearchEnabled: null, kind: 'agent' })).toBe(spec);+describe('webSearchPreferenceToStore', () => {+ beforeEach(() => {+ window.localStorage.removeItem(CHAT_DRAFT_SPEC_PREFERENCES_STORAGE_KEY);+ });++ it('omits a forced off when nothing was chosen', () => {+ expect(+ webSearchPreferenceToStore({+ spec: { model: { name: 'model' }, config: { webSearch: { enabled: false } } },+ webSearchEnabled: false,+ previousWebSearchEnabled: true,+ kind: 'chat',+ }),+ ).toEqual({ model: { name: 'model' } });+ });++ it('keeps a stored off while search is unavailable and after it returns', () => {+ writeDraftSpecPreferences('chat', {+ model: { name: 'model' },+ config: { webSearch: { enabled: false } },+ });+ const forcedOff = { model: { name: 'model' }, config: { webSearch: { enabled: false } } };++ expect(+ webSearchPreferenceToStore({+ spec: forcedOff,+ webSearchEnabled: false,+ previousWebSearchEnabled: true,+ kind: 'chat',+ }),+ ).toEqual(forcedOff);+ expect(+ webSearchPreferenceToStore({+ spec: forcedOff,+ webSearchEnabled: true,+ previousWebSearchEnabled: false,+ kind: 'chat',+ }),+ ).toEqual(forcedOff);+ });++ it('default-fills on after an outage when no choice was stored', () => {+ expect(+ webSearchPreferenceToStore({+ spec: { model: { name: 'model' }, config: { webSearch: { enabled: false } } },+ webSearchEnabled: true,+ previousWebSearchEnabled: false,+ kind: 'chat',+ }),+ ).toEqual({+ model: { name: 'model' },+ config: { webSearch: { enabled: true } },+ });});});