🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(setting): configurable search & crawl channel preferences (#17093)
YuTengjing5fc9e33caeea
diff --git a/apps/server/src/routers/lambda/__tests__/user.test.ts b/apps/server/src/routers/lambda/__tests__/user.test.tsindex 4547c436316..861a096169e 100644--- a/apps/server/src/routers/lambda/__tests__/user.test.ts+++ b/apps/server/src/routers/lambda/__tests__/user.test.ts@@ -983,6 +983,36 @@ describe('userRouter', () => {});});+ describe('updateToolChannels', () => {+ it('delegates to the atomic model patch with the raw input', async () => {+ const replaceToolChannelsSetting = vi.fn().mockResolvedValue({ rowCount: 1 });+ vi.mocked(UserModel).mockImplementation(function () {+ return { replaceToolChannelsSetting } as any;+ });++ await userRouter+ .createCaller({ ...mockCtx })+ .updateToolChannels({ searchProviders: ['exa', 'searxng'] });++ expect(replaceToolChannelsSetting).toHaveBeenCalledWith({+ searchProviders: ['exa', 'searxng'],+ });+ });++ it('rejects workspace members without content permission', async () => {+ const { RbacModel } = await import('@/database/models/rbac');+ vi.mocked(RbacModel).mockImplementation(function () {+ return { hasAnyPermission: vi.fn().mockResolvedValue(false) } as any;+ });++ await expect(+ userRouter+ .createCaller({ ...mockCtx, workspaceId: 'ws_1' } as any)+ .updateToolChannels({ crawlerImpls: ['jina'] }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ });+ });+describe('updateToolIntervention', () => {it('delegates to the atomic model merge with the raw input', async () => {const mergeToolInterventionSetting = vi.fn().mockResolvedValue({ rowCount: 1 });diff --git a/apps/server/src/routers/lambda/user.ts b/apps/server/src/routers/lambda/user.tsindex c842bc0d1ad..6ff16babe80 100644--- a/apps/server/src/routers/lambda/user.ts+++ b/apps/server/src/routers/lambda/user.ts@@ -939,6 +939,36 @@ export const userRouter = router({return ctx.userModel.mergeToolInterventionSetting(input);}),+ updateToolChannels: userProcedure+ .input(+ z+ .object({+ crawlerImpls: z.array(z.string().trim().min(1).max(64)).max(32).optional(),+ searchProviders: z.array(z.string().trim().min(1).max(64)).max(32).optional(),+ })+ .strict(),+ )+ .mutation(async ({ ctx, input }) => {+ // `tool` is a member-scope workspace setting — same RBAC gate as updateSettings+ if (ctx.workspaceId) {+ const rbac = new RbacModel(ctx.serverDB, ctx.userId);+ const allowed = await rbac.hasAnyPermission([...WORKSPACE_CONTENT_PERMISSIONS], {+ workspaceId: ctx.workspaceId,+ });++ if (!allowed) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'You do not have permission to perform this action.',+ });+ }+ }++ // Patch only the channel keys atomically — a whole-column `tool` write+ // built from a stale tab snapshot would revert other tool settings.+ return ctx.userModel.replaceToolChannelsSetting(input);+ }),+updateUninstalledBuiltinTools: userProcedure.input(zdiff --git a/apps/server/src/routers/tools/search.ts b/apps/server/src/routers/tools/search.tsindex 2a2da0cfb57..e94e3abc49e 100644--- a/apps/server/src/routers/tools/search.ts+++ b/apps/server/src/routers/tools/search.ts@@ -2,9 +2,11 @@ import { hasApiKeyScope, isFullAccessApiKey } from '@lobechat/const/apiKeyScope'import { TRPCError } from '@trpc/server';import { z } from 'zod';+import { getServerDB } from '@/database/core/db-adaptor';import { authedProcedure, router } from '@/libs/trpc/lambda';import { trpc } from '@/libs/trpc/lambda/init';-import { searchService } from '@/server/services/search';+import { SearchService } from '@/server/services/search';+import { getUserChannelPreferences } from '@/server/services/search/userChannels';// This surface executes external search/crawl providers and spends server-side// search quota — unlike the lambda `search` namespace (app content search),@@ -29,6 +31,27 @@ const requireModelInvokeForRestrictedKeys = trpc.middleware(async ({ ctx, next }const searchProcedure = authedProcedure.use(requireModelInvokeForRestrictedKeys);+/**+ * Build a per-request search service seeded with the caller's ordered channel+ * preferences (search providers / crawler impls).+ *+ * The per-user preference read is optional: deployments (or local/dev mode)+ * with search/crawler env but no server database must keep web search usable.+ * `getServerDB()` throws when `KEY_VAULTS_SECRET` / `DATABASE_URL` are unset, so+ * we guard it here — a missing or failing database degrades to the server+ * default channel order rather than making the whole search path DB-required.+ */+const createUserSearchService = async (userId: string) => {+ let userChannels;+ try {+ const serverDB = await getServerDB();+ userChannels = await getUserChannelPreferences(serverDB, userId);+ } catch {+ // No server database configured — fall back to the server default order.+ }+ return new SearchService({ userChannels });+};+export const searchRouter = router({crawlPages: searchProcedure.input(@@ -40,10 +63,18 @@ export const searchRouter = router({urls: z.string().array(),}),)- .mutation(async ({ input }) => {+ .mutation(async ({ ctx, input }) => {+ const searchService = await createUserSearchService(ctx.userId);return searchService.crawlPages(input);}),+ /**+ * Server-enabled search providers / crawler impls in env default order, so+ * the client can render a channel-ordering picker. This only reads env config+ * and never touches the database.+ */+ getAvailableChannels: searchProcedure.query(() => SearchService.getAvailableChannels()),+query: searchProcedure.input(z.object({@@ -57,7 +88,8 @@ export const searchRouter = router({query: z.string(),}),)- .query(async ({ input }) => {+ .query(async ({ ctx, input }) => {+ const searchService = await createUserSearchService(ctx.userId);return await searchService.query(input.query, input.optionalParams);}),@@ -70,7 +102,8 @@ export const searchRouter = router({searchTimeRange: z.string().optional(),}),)- .query(async ({ input }) => {+ .query(async ({ ctx, input }) => {+ const searchService = await createUserSearchService(ctx.userId);return await searchService.webSearch(input);}),});diff --git a/apps/server/src/services/search/index.test.ts b/apps/server/src/services/search/index.test.tsindex dfcb8182e3a..8a359847bdb 100644--- a/apps/server/src/services/search/index.test.ts+++ b/apps/server/src/services/search/index.test.ts@@ -4,7 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { toolsEnv } from '@/envs/tools';import { createSearchServiceImpl, SearchImplType } from './impls';-import { SearchService } from './index';+import { DEFAULT_CRAWLER_IMPLS, resolveOrderedChannels, SearchService } from './index';// Mock dependenciesvi.mock('@lobechat/web-crawler');@@ -779,4 +779,206 @@ describe('SearchService', () => {expect(result.results[0]).toBe(successResult);});});++ describe('resolveOrderedChannels', () => {+ it('should return the enabled order untouched when no user order is given', () => {+ expect(resolveOrderedChannels(undefined, ['a', 'b', 'c'])).toEqual(['a', 'b', 'c']);+ expect(resolveOrderedChannels([], ['a', 'b', 'c'])).toEqual(['a', 'b', 'c']);+ });++ it('should keep only enabled ids in the user order', () => {+ expect(resolveOrderedChannels(['c', 'a'], ['a', 'b', 'c'])).toEqual(['c', 'a']);+ });++ it('should drop unknown / disabled ids from the user order', () => {+ expect(resolveOrderedChannels(['x', 'b', 'y'], ['a', 'b', 'c'])).toEqual(['b']);+ });++ it('should fall back to the enabled order when intersection is empty', () => {+ expect(resolveOrderedChannels(['x', 'y'], ['a', 'b', 'c'])).toEqual(['a', 'b', 'c']);+ });+ });++ describe('DEFAULT_CRAWLER_IMPLS', () => {+ it('should stay in sync with DEFAULT_CRAWL_IMPLS from @lobechat/web-crawler', async () => {+ // The local copy is an intentional duplicate to avoid eagerly importing+ // the crawler module graph; this guards against the two drifting apart.+ // `@lobechat/web-crawler` is auto-mocked in this file (which empties its+ // arrays), so read the real export via importActual.+ const { DEFAULT_CRAWL_IMPLS } = await vi.importActual<{ DEFAULT_CRAWL_IMPLS: string[] }>(+ '@lobechat/web-crawler',+ );++ expect(DEFAULT_CRAWLER_IMPLS).toEqual(DEFAULT_CRAWL_IMPLS);+ });+ });++ describe('user channel preferences - search providers', () => {+ it('should reorder providers by user preference intersected with env', () => {+ vi.mocked(toolsEnv).SEARCH_PROVIDERS = 'searxng,exa,brave';+ // Drop the construction the shared beforeEach already recorded.+ vi.mocked(createSearchServiceImpl).mockClear();++ searchService = new SearchService({ userChannels: { searchProviders: ['exa', 'searxng'] } });++ // Providers are instantiated in the resolved (user) order.+ expect(createSearchServiceImpl).toHaveBeenNthCalledWith(1, SearchImplType.Exa);+ expect(createSearchServiceImpl).toHaveBeenNthCalledWith(2, SearchImplType.SearXNG);+ expect(createSearchServiceImpl).toHaveBeenCalledTimes(2);+ });++ it('should ignore user providers not enabled in env', () => {+ vi.mocked(toolsEnv).SEARCH_PROVIDERS = 'searxng,exa';+ vi.mocked(createSearchServiceImpl).mockClear();++ searchService = new SearchService({+ userChannels: { searchProviders: ['tavily', 'exa'] },+ });++ expect(createSearchServiceImpl).toHaveBeenCalledTimes(1);+ expect(createSearchServiceImpl).toHaveBeenCalledWith(SearchImplType.Exa);+ });++ it('should fall back to env order when user preference filters to empty', () => {+ vi.mocked(toolsEnv).SEARCH_PROVIDERS = 'searxng,exa';+ vi.mocked(createSearchServiceImpl).mockClear();++ searchService = new SearchService({ userChannels: { searchProviders: ['tavily', 'brave'] } });++ expect(createSearchServiceImpl).toHaveBeenNthCalledWith(1, SearchImplType.SearXNG);+ expect(createSearchServiceImpl).toHaveBeenNthCalledWith(2, SearchImplType.Exa);+ });++ it('should intersect against the runtime default when SEARCH_PROVIDERS is empty', () => {+ vi.mocked(toolsEnv).SEARCH_PROVIDERS = '';+ vi.mocked(createSearchServiceImpl).mockClear();++ // 'exa' is not a default provider, so it is dropped; only SearXNG remains,+ // matching what `getAvailableChannels` exposes to the settings page.+ searchService = new SearchService({ userChannels: { searchProviders: ['exa', 'searxng'] } });++ expect(createSearchServiceImpl).toHaveBeenCalledTimes(1);+ expect(createSearchServiceImpl).toHaveBeenCalledWith(SearchImplType.SearXNG);+ });++ it('should behave identically to no-config when userChannels is omitted', () => {+ vi.mocked(toolsEnv).SEARCH_PROVIDERS = 'searxng,exa';+ vi.mocked(createSearchServiceImpl).mockClear();++ searchService = new SearchService();++ expect(createSearchServiceImpl).toHaveBeenNthCalledWith(1, SearchImplType.SearXNG);+ expect(createSearchServiceImpl).toHaveBeenNthCalledWith(2, SearchImplType.Exa);+ });+ });++ describe('user channel preferences - crawler impls', () => {+ const mockCrawler = () => {+ const crawler = {+ crawl: vi.fn().mockResolvedValue({+ crawler: 'jina',+ data: { content: 'ok', contentType: 'text' },+ originalUrl: 'https://example.com',+ }),+ };+ vi.mocked(Crawler).mockImplementation(function () {+ return crawler as any;+ });+ return crawler;+ };++ it('should intersect user crawler impls with env in user order', async () => {+ vi.mocked(toolsEnv).CRAWLER_IMPLS = 'jina,naive,firecrawl';+ mockCrawler();++ searchService = new SearchService({+ userChannels: { crawlerImpls: ['firecrawl', 'jina'] },+ });+ await searchService.crawlPages({ urls: ['https://example.com'] });++ expect(Crawler).toHaveBeenCalledWith({+ impls: ['firecrawl', 'jina'],+ urlRuleImpls: ['jina', 'naive', 'firecrawl'],+ });+ });++ it('should intersect against Crawler defaults when env is not configured', async () => {+ vi.mocked(toolsEnv).CRAWLER_IMPLS = '';+ mockCrawler();++ searchService = new SearchService({+ userChannels: { crawlerImpls: ['naive', 'jina', 'firecrawl'] },+ });+ await searchService.crawlPages({ urls: ['https://example.com'] });++ // 'firecrawl' is not a default impl, so it is dropped; the rest keep user order.+ expect(Crawler).toHaveBeenCalledWith({+ impls: ['naive', 'jina'],+ urlRuleImpls: ['jina', 'naive', 'search1api', 'browserless'],+ });+ });++ it('should fall back to env impls when user preference filters to empty', async () => {+ vi.mocked(toolsEnv).CRAWLER_IMPLS = 'jina,naive';+ mockCrawler();++ searchService = new SearchService({ userChannels: { crawlerImpls: ['firecrawl'] } });+ await searchService.crawlPages({ urls: ['https://example.com'] });++ expect(Crawler).toHaveBeenCalledWith({+ impls: ['jina', 'naive'],+ urlRuleImpls: ['jina', 'naive'],+ });+ });++ it('should forward the raw env list unchanged when userChannels is omitted', async () => {+ vi.mocked(toolsEnv).CRAWLER_IMPLS = '';+ mockCrawler();++ searchService = new SearchService();+ await searchService.crawlPages({ urls: ['https://example.com'] });++ // Preserves current behavior: empty list, letting Crawler apply defaults.+ expect(Crawler).toHaveBeenCalledWith({ impls: [] });+ });+ });++ describe('getAvailableChannels', () => {+ it('should return enabled channels in env default order', () => {+ vi.mocked(toolsEnv).SEARCH_PROVIDERS = 'searxng,exa,brave';+ vi.mocked(toolsEnv).CRAWLER_IMPLS = 'jina,naive';++ expect(SearchService.getAvailableChannels()).toEqual({+ crawlerImpls: [{ id: 'jina' }, { id: 'naive' }],+ searchProviders: [{ id: 'searxng' }, { id: 'exa' }, { id: 'brave' }],+ });+ });++ it('should fall back to Crawler default impls when CRAWLER_IMPLS is empty', () => {+ vi.mocked(toolsEnv).SEARCH_PROVIDERS = 'searxng';+ vi.mocked(toolsEnv).CRAWLER_IMPLS = '';++ expect(SearchService.getAvailableChannels()).toEqual({+ crawlerImpls: [+ { id: 'jina' },+ { id: 'naive' },+ { id: 'search1api' },+ { id: 'browserless' },+ ],+ searchProviders: [{ id: 'searxng' }],+ });+ });++ it('should fall back to the runtime default provider when SEARCH_PROVIDERS is empty', () => {+ vi.mocked(toolsEnv).SEARCH_PROVIDERS = '';+ vi.mocked(toolsEnv).CRAWLER_IMPLS = 'jina';++ // Matches the runtime default (single SearXNG provider) so the settings+ // page never reports "no channels available" while search still works.+ expect(SearchService.getAvailableChannels()).toEqual({+ crawlerImpls: [{ id: 'jina' }],+ searchProviders: [{ id: 'searxng' }],+ });+ });+ });});diff --git a/apps/server/src/services/search/index.ts b/apps/server/src/services/search/index.tsindex 5fb128a62bf..0ce33d72ee2 100644--- a/apps/server/src/services/search/index.ts+++ b/apps/server/src/services/search/index.ts@@ -1,4 +1,9 @@-import type { SearchParams, SearchQuery, UniformSearchResponse } from '@lobechat/types';+import type {+ SearchParams,+ SearchQuery,+ UniformSearchResponse,+ UserChannelPreferences,+} from '@lobechat/types';import type { Crawler, CrawlImplType, CrawlUniformResult } from '@lobechat/web-crawler';import debug from 'debug';import pMap from 'p-map';@@ -14,12 +19,65 @@ const SEARCH_PROVIDERS_FAILED ='Web search failed because all configured providers returned errors';const log = debug('lobe-oom:web-browsing:search-service');+/**+ * Built-in crawler impl order applied when `CRAWLER_IMPLS` is not configured.+ *+ * Intentional copy of `DEFAULT_CRAWL_IMPLS` from `@lobechat/web-crawler`: the+ * search service only loads `@lobechat/web-crawler` lazily inside `crawlPages`,+ * so importing this value eagerly would pull the whole crawler module graph+ * into every request path. Drift between the two is guarded by a test that+ * asserts equality against the package export.+ */+export const DEFAULT_CRAWLER_IMPLS = ['jina', 'naive', 'search1api', 'browserless'];++/**+ * Search provider order applied when `SEARCH_PROVIDERS` is not configured.+ *+ * Mirrors the runtime default: when no provider is enabled via env, the service+ * falls back to a single SearXNG provider (see `createSearchServiceImpl`'s+ * default `type` of `SearchImplType.SearXNG`). Keeping this list in sync with+ * that default guarantees the settings page shows exactly the channels the+ * runtime can actually use.+ */+export const DEFAULT_SEARCH_IMPLS = ['searxng'];+const parseImplEnv = (envString: string = '') => {// Handle full-width commas and extra whitespaceconst envValue = envString.replaceAll(',', ',').trim();return envValue.split(',').filter(Boolean);};+/**+ * Resolve the effective ordered channel list from a user's preferred order+ * intersected with the server-enabled set.+ *+ * - The user's order is authoritative for priority: only ids present in the+ * enabled set are kept, in the user's order.+ * - When the user has no preference, or the intersection is empty (e.g. all+ * preferred ids are unknown/disabled), fall back to the server default order+ * (`enabledOrder`) unchanged — so an unconfigured user behaves exactly as before.+ */+export const resolveOrderedChannels = (+ userOrder: string[] | undefined,+ enabledOrder: string[],+): string[] => {+ if (!userOrder?.length) return enabledOrder;++ const enabledSet = new Set(enabledOrder);+ const filtered = userOrder.filter((id) => enabledSet.has(id));++ return filtered.length > 0 ? filtered : enabledOrder;+};++export interface SearchServiceOptions {+ /**+ * User-level ordered channel preferences (search providers / crawler impls).+ * Each list is intersected with the server-enabled set and reordered by the+ * user's priority; missing or fully-filtered lists fall back to the env order.+ */+ userChannels?: UserChannelPreferences;+}+const buildSearchParams = ({searchCategories,searchEngines,@@ -58,9 +116,31 @@ const getMemorySnapshot = () => {*/export class SearchService {private searchImpList: SearchServiceImpl[];+ private userChannels?: UserChannelPreferences;++ private get crawlerOptions(): { impls: string[]; urlRuleImpls?: string[] } {+ const enabledFromEnv = parseImplEnv(toolsEnv.CRAWLER_IMPLS);++ // No user preference → preserve current behavior exactly: forward the env+ // list as-is (possibly empty, letting `Crawler` apply its own defaults).+ if (!this.userChannels?.crawlerImpls?.length) return { impls: enabledFromEnv };++ // When crawler impls aren't configured via env, the effective enabled set+ // is the Crawler's built-in default order — intersect against that so a+ // user preference still resolves in a default deployment.+ const enabledSet = enabledFromEnv.length > 0 ? enabledFromEnv : DEFAULT_CRAWLER_IMPLS;++ return {+ impls: resolveOrderedChannels(this.userChannels.crawlerImpls, enabledSet),+ // URL rules (PDF, YouTube, ...) keep choosing from every server-enabled+ // impl, even ones the user disabled: the user order only applies to URLs+ // no rule matches, so rule-specific crawl quality does not regress.+ urlRuleImpls: enabledSet,+ };+ }private get crawlerImpls() {- return parseImplEnv(toolsEnv.CRAWLER_IMPLS);+ return this.crawlerOptions.impls;}private get crawlConcurrency() {@@ -71,7 +151,9 @@ export class SearchService {return toolsEnv.CRAWLER_RETRY ?? DEFAULT_CRAWLER_RETRY;}- constructor() {+ constructor(options: SearchServiceOptions = {}) {+ this.userChannels = options.userChannels;+const impls = this.searchImpls;this.searchImpList =impls.length > 0@@ -79,6 +161,31 @@ export class SearchService {: [createSearchServiceImpl()];}+ /**+ * Server-enabled channel candidates in env default order, for the client to+ * render a channel-ordering picker. Returns objects (rather than bare ids) to+ * leave room for future per-channel metadata. Both lists fall back to their+ * built-in runtime defaults when the corresponding env (`SEARCH_PROVIDERS` /+ * `CRAWLER_IMPLS`) is not configured, so the picker shows exactly what the+ * runtime would actually use.+ */+ static getAvailableChannels(): {+ crawlerImpls: { id: string }[];+ searchProviders: { id: string }[];+ } {+ const enabledProviders = parseImplEnv(toolsEnv.SEARCH_PROVIDERS);+ // Match the runtime default (single SearXNG provider) when unconfigured, so+ // the settings page never shows "no channels available" while search still works.+ const searchProviders = enabledProviders.length > 0 ? enabledProviders : DEFAULT_SEARCH_IMPLS;+ const enabledCrawlers = parseImplEnv(toolsEnv.CRAWLER_IMPLS);+ const crawlerImpls = enabledCrawlers.length > 0 ? enabledCrawlers : DEFAULT_CRAWLER_IMPLS;++ return {+ crawlerImpls: crawlerImpls.map((id) => ({ id })),+ searchProviders: searchProviders.map((id) => ({ id })),+ };+ }+async crawlPages(input: { impls?: CrawlImplType[]; urls: string[] }) {try {if (log.enabled) {@@ -92,7 +199,7 @@ export class SearchService {} catch {}const { Crawler } = await import('@lobechat/web-crawler');- const crawler = new Crawler({ impls: this.crawlerImpls });+ const crawler = new Crawler(this.crawlerOptions);const results = await pMap(input.urls,@@ -166,7 +273,21 @@ export class SearchService {}private get searchImpls() {- return parseImplEnv(toolsEnv.SEARCH_PROVIDERS) as SearchImplType[];+ const enabledFromEnv = parseImplEnv(toolsEnv.SEARCH_PROVIDERS);++ // No user preference → preserve current behavior exactly: forward the env+ // list as-is (possibly empty, letting the constructor apply its own default).+ if (!this.userChannels?.searchProviders?.length) return enabledFromEnv as SearchImplType[];++ // When search providers aren't configured via env, the effective enabled set+ // is the runtime's built-in default (SearXNG) — intersect against that so a+ // user preference still resolves in a default deployment.+ const enabledSet = enabledFromEnv.length > 0 ? enabledFromEnv : DEFAULT_SEARCH_IMPLS;++ return resolveOrderedChannels(+ this.userChannels.searchProviders,+ enabledSet,+ ) as SearchImplType[];}/**@@ -264,6 +385,3 @@ export class SearchService {};}}--// Add a default exported instance for convenience-export const searchService = new SearchService();diff --git a/apps/server/src/services/search/userChannels.ts b/apps/server/src/services/search/userChannels.tsnew file mode 100644index 00000000000..17a7d0e1014--- /dev/null+++ b/apps/server/src/services/search/userChannels.ts@@ -0,0 +1,29 @@+import type { LobeChatDatabase } from '@lobechat/database';+import type { UserChannelPreferences, UserToolConfig } from '@lobechat/types';++import { UserModel } from '@/database/models/user';++/**+ * Read the caller's search / crawl channel preferences (ordered search providers+ * / crawler impls) from user settings.+ *+ * Read failures degrade to `undefined` (i.e. "no preference") rather than+ * throwing, so a settings hiccup never breaks search/crawl — the service then+ * falls back to the server default channel order.+ */+export const getUserChannelPreferences = async (+ serverDB: LobeChatDatabase,+ userId: string,+): Promise<UserChannelPreferences | undefined> => {+ try {+ const settings = await new UserModel(serverDB, userId).getUserSettings();+ // `userSettings.tool` is an untyped jsonb column.+ const tool = settings?.tool as UserToolConfig | undefined;+ if (!tool) return undefined;++ return { crawlerImpls: tool.crawlerImpls, searchProviders: tool.searchProviders };+ } catch (e) {+ console.error('[SearchService] failed to read user channel preferences:', (e as Error).message);+ return undefined;+ }+};diff --git a/apps/server/src/services/toolExecution/serverRuntimes/webBrowsing.ts b/apps/server/src/services/toolExecution/serverRuntimes/webBrowsing.tsindex 0d074e836f4..7407256c6cb 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/webBrowsing.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/webBrowsing.ts@@ -3,15 +3,22 @@ import { WebBrowsingExecutionRuntime } from '@lobechat/builtin-tool-web-browsingimport { AgentDocumentsService } from '@/server/services/agentDocuments';import { SearchService } from '@/server/services/search';+import { getUserChannelPreferences } from '@/server/services/search/userChannels';import { WebBrowsingDocumentService } from '@/server/services/webBrowsing';import { type ServerRuntimeRegistration } from './types';export const webBrowsingRuntime: ServerRuntimeRegistration = {- factory: (context) => {+ factory: async (context) => {const { userId, serverDB, agentId, agentVisibility } = context;const canSaveDocuments = userId && serverDB && agentId;+ // Seed the search service with the caller's ordered channel preferences.+ // Only reachable when both userId and serverDB are present; otherwise the+ // service falls back to the server default channel order.+ const userChannels =+ userId && serverDB ? await getUserChannelPreferences(serverDB, userId) : undefined;+return new WebBrowsingExecutionRuntime({documentService: canSaveDocuments? {@@ -40,7 +47,7 @@ export const webBrowsingRuntime: ServerRuntimeRegistration = {},}: undefined,- searchService: new SearchService(),+ searchService: new SearchService({ userChannels }),});},identifier: WebBrowsingManifest.identifier,diff --git a/locales/ar/setting.json b/locales/ar/setting.jsonindex 28e5139453f..3122929bdc2 100644--- a/locales/ar/setting.json+++ b/locales/ar/setting.json@@ -1225,6 +1225,13 @@"settingTTS.voice.desc": "اختر صوتًا للوكيل الحالي، حيث تدعم خدمات TTS المختلفة أصواتًا مختلفة","settingTTS.voice.preview": "معاينة الصوت","settingTTS.voice.title": "صوت تحويل النص إلى كلام",+ "settingTool.crawler.desc": "رتب الخدمات المستخدمة لقراءة صفحات الويب بالكامل. يتم تجربة العناصر الأعلى أولاً؛ يتم تخطي العناصر المعطلة. بعض المواقع، مثل ملفات PDF و YouTube، تستخدم دائمًا خدمة مخصصة.",+ "settingTool.crawler.title": "قارئ الويب",+ "settingTool.empty": "لا توجد قنوات متاحة",+ "settingTool.item.disabled": "معطل",+ "settingTool.item.enabled": "مفعل",+ "settingTool.search.desc": "رتب الخدمات المستخدمة للبحث في الويب. يتم تجربة العناصر الأعلى أولاً؛ يتم تخطي العناصر المعطلة.",+ "settingTool.search.title": "محركات البحث","settingsSearch.empty": "لم يتم العثور على إعدادات لـ \"{{keyword}}\"","settingsSearch.placeholder": "ابحث في الإعدادات...","settingsSearch.tabKeywords.about": "حول، الإصدار، سجل التغييرات، الملاحظات، المساعدة",@@ -1474,6 +1481,7 @@"tab.storage": "تخزين البيانات","tab.sync": "مزامنة السحابة","tab.systemTools": "أدوات النظام",+ "tab.tools": "الأدوات","tab.tts": "تحويل النص إلى كلام","tab.uploadZip": "رفع ملف مضغوط","tab.uploadZip.desc": "رفع ملف .zip أو .skill محلي",diff --git a/locales/bg-BG/setting.json b/locales/bg-BG/setting.jsonindex 3201a1fed66..5b2fd3976b4 100644--- a/locales/bg-BG/setting.json+++ b/locales/bg-BG/setting.json@@ -1225,6 +1225,13 @@"settingTTS.voice.desc": "Изберете глас за текущия агент, различните TTS услуги поддържат различни гласове","settingTTS.voice.preview": "Преглед на гласа","settingTTS.voice.title": "Глас за текст в реч",+ "settingTool.crawler.desc": "Подредете услугите, използвани за четене на цели уеб страници. По-високо разположените елементи се опитват първи; деактивираните се пропускат. Някои сайтове, като PDF файлове и YouTube, винаги използват специализирана услуга.",+ "settingTool.crawler.title": "Уеб Четец",+ "settingTool.empty": "Няма налични канали",+ "settingTool.item.disabled": "Деактивирано",+ "settingTool.item.enabled": "Активирано",+ "settingTool.search.desc": "Подредете услугите, използвани за търсене в интернет. По-високо разположените елементи се опитват първи; деактивираните се пропускат.",+ "settingTool.search.title": "Търсачки","settingsSearch.empty": "Няма намерени настройки за \"{{keyword}}\"","settingsSearch.placeholder": "Търсене на настройки...","settingsSearch.tabKeywords.about": "за, версия, променен дневник, обратна връзка, помощ",@@ -1474,6 +1481,7 @@"tab.storage": "Съхранение на данни","tab.sync": "Облачна синхронизация","tab.systemTools": "Системни инструменти",+ "tab.tools": "Инструменти","tab.tts": "Текст в реч","tab.uploadZip": "Качване на Zip","tab.uploadZip.desc": "Качване на локален .zip или .skill файл",diff --git a/locales/de-DE/setting.json b/locales/de-DE/setting.jsonindex 993d3a79765..e91abfb965d 100644--- a/locales/de-DE/setting.json+++ b/locales/de-DE/setting.json@@ -1225,6 +1225,13 @@"settingTTS.voice.desc": "Stimme für den aktuellen Agenten auswählen – je nach Dienst unterschiedlich","settingTTS.voice.preview": "Stimmvorschau","settingTTS.voice.title": "Text-zu-Sprache-Stimme",+ "settingTool.crawler.desc": "Ordnen Sie die Dienste, die zum Lesen vollständiger Webseiten verwendet werden. Höher platzierte Elemente werden zuerst ausprobiert; deaktivierte werden übersprungen. Einige Websites, etwa PDFs und YouTube, verwenden immer einen speziellen Dienst.",+ "settingTool.crawler.title": "Web-Leser",+ "settingTool.empty": "Keine Kanäle verfügbar",+ "settingTool.item.disabled": "Deaktiviert",+ "settingTool.item.enabled": "Aktiviert",+ "settingTool.search.desc": "Ordnen Sie die Dienste, die zum Durchsuchen des Webs verwendet werden. Höher platzierte Elemente werden zuerst ausprobiert; deaktivierte werden übersprungen.",+ "settingTool.search.title": "Suchmaschinen","settingsSearch.empty": "Keine Einstellungen gefunden für \"{{keyword}}\"","settingsSearch.placeholder": "Einstellungen suchen...","settingsSearch.tabKeywords.about": "über, Version, Änderungsprotokoll, Feedback, Hilfe",@@ -1474,6 +1481,7 @@"tab.storage": "Datenspeicherung","tab.sync": "Cloud-Synchronisation","tab.systemTools": "Systemwerkzeuge",+ "tab.tools": "Werkzeuge","tab.tts": "Text-zu-Sprache","tab.uploadZip": "Zip hochladen","tab.uploadZip.desc": "Laden Sie eine lokale .zip- oder .skill-Datei hoch",diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 34c48d22b9b..388dce3403b 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -1243,6 +1243,14 @@"settingTTS.voice.desc": "Select a voice for the current agent, different TTS services support different voices","settingTTS.voice.preview": "Voice Preview","settingTTS.voice.title": "Text-to-Speech Voice",+ "settingTool.crawler.desc": "Order the services used to read full web pages. Higher items are tried first; disabled ones are skipped. Some sites, such as PDFs and YouTube, always use a dedicated service.",+ "settingTool.crawler.title": "Web Reader",+ "settingTool.empty": "No services available",+ "settingTool.item.disabled": "Disabled",+ "settingTool.item.enabled": "Enabled",+ "settingTool.item.locked": "Keep at least one service enabled",+ "settingTool.search.desc": "Order the services used to search the web. Higher items are tried first; disabled ones are skipped.",+ "settingTool.search.title": "Search Engines","settingsSearch.empty": "No settings found for \"{{keyword}}\"","settingsSearch.placeholder": "Search settings...","settingsSearch.tabKeywords.about": "about, version, changelog, feedback, help",@@ -1492,6 +1500,7 @@"tab.storage": "Storage","tab.sync": "Cloud Sync","tab.systemTools": "System Tools",+ "tab.tools": "Tools","tab.tts": "Text-to-Speech","tab.uploadZip": "Upload Zip","tab.uploadZip.desc": "Upload a local .zip or .skill file",diff --git a/locales/es-ES/setting.json b/locales/es-ES/setting.jsonindex 9c75c88857e..31bfe2961c7 100644--- a/locales/es-ES/setting.json+++ b/locales/es-ES/setting.json@@ -1225,6 +1225,13 @@"settingTTS.voice.desc": "Selecciona una voz para el agente actual, los diferentes servicios TTS admiten diferentes voces","settingTTS.voice.preview": "Vista Previa de Voz","settingTTS.voice.title": "Voz de Texto a Voz",+ "settingTool.crawler.desc": "Ordena los servicios utilizados para leer páginas web completas. Los elementos superiores se intentan primero; los deshabilitados se omiten. Algunos sitios, como PDF y YouTube, siempre usan un servicio específico.",+ "settingTool.crawler.title": "Lector Web",+ "settingTool.empty": "No hay canales disponibles",+ "settingTool.item.disabled": "Deshabilitado",+ "settingTool.item.enabled": "Habilitado",+ "settingTool.search.desc": "Ordena los servicios utilizados para buscar en la web. Los elementos superiores se intentan primero; los deshabilitados se omiten.",+ "settingTool.search.title": "Motores de Búsqueda","settingsSearch.empty": "No se encontraron configuraciones para \"{{keyword}}\"","settingsSearch.placeholder": "Buscar configuraciones...","settingsSearch.tabKeywords.about": "acerca de, versión, registro de cambios, comentarios, ayuda",@@ -1474,6 +1481,7 @@"tab.storage": "Almacenamiento de Datos","tab.sync": "Sincronización en la Nube","tab.systemTools": "Herramientas del sistema",+ "tab.tools": "Herramientas","tab.tts": "Texto a Voz","tab.uploadZip": "Subir Archivo Zip","tab.uploadZip.desc": "Sube un archivo local .zip o .skill",diff --git a/locales/fa-IR/setting.json b/locales/fa-IR/setting.jsonindex 98085f7e2bf..05b5e38d145 100644--- a/locales/fa-IR/setting.json+++ b/locales/fa-IR/setting.json@@ -1225,6 +1225,13 @@"settingTTS.voice.desc": "یک صدا برای عامل فعلی انتخاب کنید، سرویسهای مختلف TTS از صداهای متفاوتی پشتیبانی میکنند","settingTTS.voice.preview": "پیشنمایش صدا","settingTTS.voice.title": "صدای تبدیل متن به گفتار",+ "settingTool.crawler.desc": "ترتیب خدماتی که برای خواندن صفحات کامل وب استفاده میشوند را مشخص کنید. موارد بالاتر ابتدا امتحان میشوند؛ موارد غیرفعال نادیده گرفته میشوند. برخی سایتها، مانند PDF و YouTube، همیشه از یک سرویس اختصاصی استفاده میکنند.",+ "settingTool.crawler.title": "خواننده وب",+ "settingTool.empty": "هیچ کانالی موجود نیست",+ "settingTool.item.disabled": "غیرفعال",+ "settingTool.item.enabled": "فعال",+ "settingTool.search.desc": "ترتیب خدماتی که برای جستجوی وب استفاده میشوند را مشخص کنید. موارد بالاتر ابتدا امتحان میشوند؛ موارد غیرفعال نادیده گرفته میشوند.",+ "settingTool.search.title": "موتورهای جستجو","settingsSearch.empty": "هیچ تنظیماتی برای \"{{keyword}}\" یافت نشد","settingsSearch.placeholder": "جستجوی تنظیمات...","settingsSearch.tabKeywords.about": "درباره، نسخه، تغییرات، بازخورد، کمک",@@ -1474,6 +1481,7 @@"tab.storage": "ذخیرهسازی داده","tab.sync": "همگامسازی ابری","tab.systemTools": "ابزارهای سیستم",+ "tab.tools": "ابزارها","tab.tts": "تبدیل متن به گفتار","tab.uploadZip": "آپلود فایل Zip","tab.uploadZip.desc": "یک فایل .zip یا .skill محلی را آپلود کنید",diff --git a/locales/fr-FR/setting.json b/locales/fr-FR/setting.jsonindex 71ff6c0724a..aef5b1fa8f7 100644--- a/locales/fr-FR/setting.json+++ b/locales/fr-FR/setting.json@@ -1225,6 +1225,13 @@"settingTTS.voice.desc": "Sélectionnez une voix pour l’agent actuel, les services TTS prennent en charge différentes voix","settingTTS.voice.preview": "Aperçu de la voix","settingTTS.voice.title": "Voix de synthèse vocale",+ "settingTool.crawler.desc": "Ordonnez les services utilisés pour lire les pages web complètes. Les éléments les plus hauts sont essayés en premier ; ceux désactivés sont ignorés. Certains sites, comme les PDF et YouTube, utilisent toujours un service dédié.",+ "settingTool.crawler.title": "Lecteur Web",+ "settingTool.empty": "Aucun canal disponible",+ "settingTool.item.disabled": "Désactivé",+ "settingTool.item.enabled": "Activé",+ "settingTool.search.desc": "Ordonnez les services utilisés pour rechercher sur le web. Les éléments les plus hauts sont essayés en premier ; ceux désactivés sont ignorés.",+ "settingTool.search.title": "Moteurs de Recherche","settingsSearch.empty": "Aucun paramètre trouvé pour \"{{keyword}}\"","settingsSearch.placeholder": "Rechercher des paramètres...","settingsSearch.tabKeywords.about": "à propos, version, journal des modifications, retour d'information, aide",@@ -1474,6 +1481,7 @@"tab.storage": "Stockage des données","tab.sync": "Synchronisation cloud","tab.systemTools": "Outils système",+ "tab.tools": "Outils","tab.tts": "Synthèse vocale","tab.uploadZip": "Télécharger un fichier Zip","tab.uploadZip.desc": "Téléchargez un fichier local .zip ou .skill",diff --git a/locales/it-IT/setting.json b/locales/it-IT/setting.jsonindex 78cbb886a9f..236f5bc5864 100644--- a/locales/it-IT/setting.json+++ b/locales/it-IT/setting.json@@ -1225,6 +1225,13 @@"settingTTS.voice.desc": "Seleziona una voce per l'agente corrente, diversi servizi TTS supportano voci differenti","settingTTS.voice.preview": "Anteprima Voce","settingTTS.voice.title": "Voce Sintesi Vocale",+ "settingTool.crawler.desc": "Ordina i servizi utilizzati per leggere intere pagine web. Gli elementi più in alto vengono provati per primi; quelli disabilitati vengono saltati. Alcuni siti, come PDF e YouTube, usano sempre un servizio dedicato.",+ "settingTool.crawler.title": "Lettore Web",+ "settingTool.empty": "Nessun canale disponibile",+ "settingTool.item.disabled": "Disabilitato",+ "settingTool.item.enabled": "Abilitato",+ "settingTool.search.desc": "Ordina i servizi utilizzati per cercare sul web. Gli elementi più in alto vengono provati per primi; quelli disabilitati vengono saltati.",+ "settingTool.search.title": "Motori di Ricerca","settingsSearch.empty": "Nessuna impostazione trovata per \"{{keyword}}\"","settingsSearch.placeholder": "Cerca impostazioni...","settingsSearch.tabKeywords.about": "informazioni, versione, changelog, feedback, aiuto",@@ -1474,6 +1481,7 @@"tab.storage": "Archiviazione Dati","tab.sync": "Sincronizzazione Cloud","tab.systemTools": "Strumenti di Sistema",+ "tab.tools": "Strumenti","tab.tts": "Sintesi Vocale","tab.uploadZip": "Carica Zip","tab.uploadZip.desc": "Carica un file locale .zip o .skill",diff --git a/locales/ja-JP/setting.json b/locales/ja-JP/setting.jsonindex 4f29da0ce2a..5b84b8c505b 100644--- a/locales/ja-JP/setting.json+++ b/locales/ja-JP/setting.json@@ -1225,6 +1225,13 @@"settingTTS.voice.desc": "現在のアシスタントに適した音声を選択します。異なる TTS サービスは異なる音声をサポートしています","settingTTS.voice.preview": "音声を試聴","settingTTS.voice.title": "音声合成音声",+ "settingTool.crawler.desc": "ウェブページ全体を読むために使用されるサービスの順序を設定します。上位の項目が優先され、無効化されたものはスキップされます。PDF や YouTube など一部のサイトでは、常に専用のサービスが使用されます。",+ "settingTool.crawler.title": "ウェブリーダー",+ "settingTool.empty": "利用可能なチャンネルがありません",+ "settingTool.item.disabled": "無効",+ "settingTool.item.enabled": "有効",+ "settingTool.search.desc": "ウェブ検索に使用されるサービスの順序を設定します。上位の項目が優先され、無効化されたものはスキップされます。",+ "settingTool.search.title": "検索エンジン","settingsSearch.empty": "「{{keyword}}」に該当する設定が見つかりません","settingsSearch.placeholder": "設定を検索...","settingsSearch.tabKeywords.about": "概要, バージョン, 更新履歴, フィードバック, ヘルプ",@@ -1474,6 +1481,7 @@"tab.storage": "データストレージ","tab.sync": "クラウド同期","tab.systemTools": "システムツール",+ "tab.tools": "ツール","tab.tts": "音声サービス","tab.uploadZip": "Zipをアップロード","tab.uploadZip.desc": "ローカルの.zipまたは.skillファイルをアップロード",diff --git a/locales/ko-KR/setting.json b/locales/ko-KR/setting.jsonindex c5304018f7f..01ab6914ea9 100644--- a/locales/ko-KR/setting.json+++ b/locales/ko-KR/setting.json@@ -1225,6 +1225,13 @@"settingTTS.voice.desc": "현재 도우미에 대한 음성을 선택하십시오. 각 TTS 서비스는 다른 음성을 지원합니다","settingTTS.voice.preview": "음성 미리듣기","settingTTS.voice.title": "음성 합성 음성",+ "settingTool.crawler.desc": "전체 웹 페이지를 읽는 데 사용되는 서비스를 순서대로 정렬합니다. 상위 항목이 먼저 시도되며, 비활성화된 항목은 건너뜁니다. PDF, YouTube 등 일부 사이트는 항상 전용 서비스를 사용합니다.",+ "settingTool.crawler.title": "웹 리더",+ "settingTool.empty": "사용 가능한 채널이 없습니다",+ "settingTool.item.disabled": "비활성화됨",+ "settingTool.item.enabled": "활성화됨",+ "settingTool.search.desc": "웹 검색에 사용되는 서비스를 순서대로 정렬합니다. 상위 항목이 먼저 시도되며, 비활성화된 항목은 건너뜁니다.",+ "settingTool.search.title": "검색 엔진","settingsSearch.empty": "\"{{keyword}}\"에 대한 설정을 찾을 수 없습니다","settingsSearch.placeholder": "설정 검색...","settingsSearch.tabKeywords.about": "정보, 버전, 변경 로그, 피드백, 도움말",@@ -1474,6 +1481,7 @@"tab.storage": "데이터 저장소","tab.sync": "클라우드 동기화","tab.systemTools": "시스템 도구",+ "tab.tools": "도구","tab.tts": "음성 서비스","tab.uploadZip": "Zip 업로드","tab.uploadZip.desc": "로컬 .zip 또는 .skill 파일 업로드",diff --git a/locales/nl-NL/setting.json b/locales/nl-NL/setting.jsonindex a7b6a59fce0..14385a8ee92 100644--- a/locales/nl-NL/setting.json+++ b/locales/nl-NL/setting.json@@ -1225,6 +1225,13 @@"settingTTS.voice.desc": "Selecteer een stem voor de huidige agent, verschillende TTS-services ondersteunen verschillende stemmen","settingTTS.voice.preview": "Stemvoorbeeld","settingTTS.voice.title": "Tekst-naar-Spraak Stem",+ "settingTool.crawler.desc": "Rangschik de services die worden gebruikt om volledige webpagina's te lezen. Hogere items worden eerst geprobeerd; uitgeschakelde worden overgeslagen. Sommige sites, zoals PDF's en YouTube, gebruiken altijd een specifieke service.",+ "settingTool.crawler.title": "Weblezer",+ "settingTool.empty": "Geen kanalen beschikbaar",+ "settingTool.item.disabled": "Uitgeschakeld",+ "settingTool.item.enabled": "Ingeschakeld",+ "settingTool.search.desc": "Rangschik de services die worden gebruikt om op het web te zoeken. Hogere items worden eerst geprobeerd; uitgeschakelde worden overgeslagen.",+ "settingTool.search.title": "Zoekmachines","settingsSearch.empty": "Geen instellingen gevonden voor \"{{keyword}}\"","settingsSearch.placeholder": "Instellingen zoeken...","settingsSearch.tabKeywords.about": "over, versie, changelog, feedback, hulp",@@ -1474,6 +1481,7 @@"tab.storage": "Gegevensopslag","tab.sync": "Cloudsynchronisatie","tab.systemTools": "Systeemhulpmiddelen",+ "tab.tools": "Hulpmiddelen","tab.tts": "Tekst-naar-Spraak","tab.uploadZip": "Zip Uploaden","tab.uploadZip.desc": "Upload een lokaal .zip- of .skill-bestand",diff --git a/locales/pl-PL/setting.json b/locales/pl-PL/setting.jsonindex eb2aae0b523..247046e38ef 100644--- a/locales/pl-PL/setting.json+++ b/locales/pl-PL/setting.json@@ -1225,6 +1225,13 @@"settingTTS.voice.desc": "Wybierz głos dla bieżącego agenta, różne usługi TTS obsługują różne głosy","settingTTS.voice.preview": "Podgląd głosu","settingTTS.voice.title": "Głos syntezy mowy",+ "settingTool.crawler.desc": "Ustal kolejność usług używanych do odczytu pełnych stron internetowych. Wyższe pozycje są próbowane jako pierwsze; wyłączone są pomijane. Niektóre witryny, takie jak pliki PDF i YouTube, zawsze korzystają z dedykowanej usługi.",+ "settingTool.crawler.title": "Czytnik stron internetowych",+ "settingTool.empty": "Brak dostępnych kanałów",+ "settingTool.item.disabled": "Wyłączone",+ "settingTool.item.enabled": "Włączone",+ "settingTool.search.desc": "Ustal kolejność usług używanych do przeszukiwania internetu. Wyższe pozycje są próbowane jako pierwsze; wyłączone są pomijane.",+ "settingTool.search.title": "Wyszukiwarki","settingsSearch.empty": "Nie znaleziono ustawień dla \"{{keyword}}\"","settingsSearch.placeholder": "Szukaj ustawień...","settingsSearch.tabKeywords.about": "o, wersja, dziennik zmian, opinie, pomoc",@@ -1474,6 +1481,7 @@"tab.storage": "Przechowywanie danych","tab.sync": "Synchronizacja w chmurze","tab.systemTools": "Narzędzia systemowe",+ "tab.tools": "Narzędzia","tab.tts": "Synteza mowy","tab.uploadZip": "Prześlij plik Zip","tab.uploadZip.desc": "Prześlij lokalny plik .zip lub .skill",diff --git a/locales/pt-BR/setting.json b/locales/pt-BR/setting.jsonindex a90d20b17e2..484c9320f86 100644--- a/locales/pt-BR/setting.json+++ b/locales/pt-BR/setting.json@@ -1225,6 +1225,13 @@"settingTTS.voice.desc": "Selecione uma voz para o agente atual, diferentes serviços TTS suportam vozes diferentes","settingTTS.voice.preview": "Prévia da Voz","settingTTS.voice.title": "Voz de Texto para Fala",+ "settingTool.crawler.desc": "Organize os serviços usados para ler páginas da web completas. Os itens mais altos são tentados primeiro; os desativados são ignorados. Alguns sites, como PDFs e YouTube, sempre usam um serviço dedicado.",+ "settingTool.crawler.title": "Leitor de Web",+ "settingTool.empty": "Nenhum canal disponível",+ "settingTool.item.disabled": "Desativado",+ "settingTool.item.enabled": "Ativado",+ "settingTool.search.desc": "Organize os serviços usados para pesquisar na web. Os itens mais altos são tentados primeiro; os desativados são ignorados.",+ "settingTool.search.title": "Motores de Busca","settingsSearch.empty": "Nenhuma configuração encontrada para \"{{keyword}}\"","settingsSearch.placeholder": "Pesquisar configurações...","settingsSearch.tabKeywords.about": "sobre, versão, changelog, feedback, ajuda",@@ -1474,6 +1481,7 @@"tab.storage": "Armazenamento de Dados","tab.sync": "Sincronização em Nuvem","tab.systemTools": "Ferramentas do Sistema",+ "tab.tools": "Ferramentas","tab.tts": "Texto para Fala","tab.uploadZip": "Enviar Zip","tab.uploadZip.desc": "Envie um arquivo local .zip ou .skill",diff --git a/locales/ru-RU/setting.json b/locales/ru-RU/setting.jsonindex 5ebf8475c71..db44ce2bcf8 100644--- a/locales/ru-RU/setting.json+++ b/locales/ru-RU/setting.json@@ -1225,6 +1225,13 @@"settingTTS.voice.desc": "Выберите голос для текущего агента. Разные службы TTS поддерживают разные голоса","settingTTS.voice.preview": "Предпрослушивание голоса","settingTTS.voice.title": "Голос синтеза речи",+ "settingTool.crawler.desc": "Упорядочьте сервисы, используемые для чтения полных веб-страниц. Сначала пробуются элементы, расположенные выше; отключенные пропускаются. Некоторые сайты, например PDF и YouTube, всегда используют специальный сервис.",+ "settingTool.crawler.title": "Веб-ридер",+ "settingTool.empty": "Нет доступных каналов",+ "settingTool.item.disabled": "Отключено",+ "settingTool.item.enabled": "Включено",+ "settingTool.search.desc": "Упорядочьте сервисы, используемые для поиска в интернете. Сначала пробуются элементы, расположенные выше; отключенные пропускаются.",+ "settingTool.search.title": "Поисковые системы","settingsSearch.empty": "Настройки для \"{{keyword}}\" не найдены","settingsSearch.placeholder": "Поиск настроек...","settingsSearch.tabKeywords.about": "о программе, версия, изменения, обратная связь, помощь",@@ -1474,6 +1481,7 @@"tab.storage": "Хранилище данных","tab.sync": "Облачная синхронизация","tab.systemTools": "Системные инструменты",+ "tab.tools": "Инструменты","tab.tts": "Синтез речи","tab.uploadZip": "Загрузить архив","tab.uploadZip.desc": "Загрузите локальный файл .zip или .skill",diff --git a/locales/tr-TR/setting.json b/locales/tr-TR/setting.jsonindex fc0df38d991..c8ce8107a92 100644--- a/locales/tr-TR/setting.json+++ b/locales/tr-TR/setting.json@@ -1225,6 +1225,13 @@"settingTTS.voice.desc": "Geçerli ajan için bir ses seçin, farklı TTS hizmetleri farklı sesleri destekler","settingTTS.voice.preview": "Ses Önizlemesi","settingTTS.voice.title": "Metinden Konuşmaya Sesi",+ "settingTool.crawler.desc": "Tam web sayfalarını okumak için kullanılan hizmetleri sırala. Üstteki öğeler önce denenir; devre dışı bırakılanlar atlanır. PDF'ler ve YouTube gibi bazı siteler her zaman özel bir hizmet kullanır.",+ "settingTool.crawler.title": "Web Okuyucu",+ "settingTool.empty": "Kanal bulunamadı",+ "settingTool.item.disabled": "Devre Dışı",+ "settingTool.item.enabled": "Etkin",+ "settingTool.search.desc": "Web'de arama yapmak için kullanılan hizmetleri sırala. Üstteki öğeler önce denenir; devre dışı bırakılanlar atlanır.",+ "settingTool.search.title": "Arama Motorları","settingsSearch.empty": "\"{{keyword}}\" için ayar bulunamadı","settingsSearch.placeholder": "Ayarları ara...","settingsSearch.tabKeywords.about": "hakkında, sürüm, değişiklik günlüğü, geri bildirim, yardım",@@ -1474,6 +1481,7 @@"tab.storage": "Veri Depolama","tab.sync": "Bulut Senkronizasyonu","tab.systemTools": "Sistem Araçları",+ "tab.tools": "Araçlar","tab.tts": "Metinden Konuşmaya","tab.uploadZip": "Zip Yükle","tab.uploadZip.desc": "Yerel bir .zip veya .skill dosyasını yükleyin",diff --git a/locales/vi-VN/setting.json b/locales/vi-VN/setting.jsonindex 2a8d505f99d..d7208b2ef1c 100644--- a/locales/vi-VN/setting.json+++ b/locales/vi-VN/setting.json@@ -1225,6 +1225,13 @@"settingTTS.voice.desc": "Chọn giọng nói cho tác nhân hiện tại, các dịch vụ TTS khác nhau hỗ trợ các giọng nói khác nhau","settingTTS.voice.preview": "Xem Trước Giọng Nói","settingTTS.voice.title": "Giọng Nói Chuyển Văn Bản",+ "settingTool.crawler.desc": "Sắp xếp các dịch vụ được sử dụng để đọc toàn bộ trang web. Các mục ở vị trí cao hơn sẽ được thử trước; các mục bị vô hiệu hóa sẽ bị bỏ qua. Một số trang, như PDF và YouTube, luôn dùng dịch vụ chuyên biệt.",+ "settingTool.crawler.title": "Trình Đọc Web",+ "settingTool.empty": "Không có kênh nào khả dụng",+ "settingTool.item.disabled": "Đã vô hiệu hóa",+ "settingTool.item.enabled": "Đã kích hoạt",+ "settingTool.search.desc": "Sắp xếp các dịch vụ được sử dụng để tìm kiếm trên web. Các mục ở vị trí cao hơn sẽ được thử trước; các mục bị vô hiệu hóa sẽ bị bỏ qua.",+ "settingTool.search.title": "Công Cụ Tìm Kiếm","settingsSearch.empty": "Không tìm thấy cài đặt nào cho \"{{keyword}}\"","settingsSearch.placeholder": "Tìm kiếm cài đặt...","settingsSearch.tabKeywords.about": "giới thiệu, phiên bản, nhật ký thay đổi, phản hồi, trợ giúp",@@ -1474,6 +1481,7 @@"tab.storage": "Lưu Trữ Dữ Liệu","tab.sync": "Đồng Bộ Đám Mây","tab.systemTools": "Công cụ hệ thống",+ "tab.tools": "Công Cụ","tab.tts": "Chuyển Văn Bản Thành Giọng Nói","tab.uploadZip": "Tải lên Tệp Zip","tab.uploadZip.desc": "Tải lên tệp .zip hoặc .skill từ máy tính",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 4742088d6e9..8ed5be82319 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -1243,6 +1243,14 @@"settingTTS.voice.desc": "为当前助理挑选一个声音,不同 TTS 服务支持的声源不同","settingTTS.voice.preview": "试听声源","settingTTS.voice.title": "语音合成声源",+ "settingTool.crawler.desc": "调整用于读取完整网页内容的服务顺序。靠前的优先使用,已停用的会被跳过;PDF、YouTube 等特定网站固定使用专门的服务。",+ "settingTool.crawler.title": "网页读取",+ "settingTool.empty": "暂无可用服务",+ "settingTool.item.disabled": "已停用",+ "settingTool.item.enabled": "已启用",+ "settingTool.item.locked": "至少保留一个已启用的服务",+ "settingTool.search.desc": "调整用于联网搜索的服务顺序。靠前的优先使用,已停用的会被跳过。",+ "settingTool.search.title": "搜索引擎","settingsSearch.empty": "未找到与“{{keyword}}”相关的设置","settingsSearch.placeholder": "搜索设置...","settingsSearch.tabKeywords.about": "关于,版本,更新日志,反馈,帮助",@@ -1492,6 +1500,7 @@"tab.storage": "数据存储","tab.sync": "云端同步","tab.systemTools": "系统工具",+ "tab.tools": "工具","tab.tts": "语音服务","tab.uploadZip": "上传 Zip","tab.uploadZip.desc": "上传本地 .zip 或 .skill 文件",diff --git a/locales/zh-TW/setting.json b/locales/zh-TW/setting.jsonindex c83589e1e44..130fa3acaa4 100644--- a/locales/zh-TW/setting.json+++ b/locales/zh-TW/setting.json@@ -1225,6 +1225,13 @@"settingTTS.voice.desc": "為當前助手挑選一個聲音,不同 TTS 服務支持的聲源不同","settingTTS.voice.preview": "試聽聲源","settingTTS.voice.title": "語音合成聲源",+ "settingTool.crawler.desc": "排序用於閱讀完整網頁的服務。優先嘗試排在前面的項目;已停用的項目將被跳過。PDF、YouTube 等特定網站固定使用專門的服務。",+ "settingTool.crawler.title": "網頁閱讀器",+ "settingTool.empty": "沒有可用的頻道",+ "settingTool.item.disabled": "已停用",+ "settingTool.item.enabled": "已啟用",+ "settingTool.search.desc": "排序用於網頁搜尋的服務。優先嘗試排在前面的項目;已停用的項目將被跳過。",+ "settingTool.search.title": "搜尋引擎","settingsSearch.empty": "未找到符合「{{keyword}}」的設定","settingsSearch.placeholder": "搜尋設定...","settingsSearch.tabKeywords.about": "關於, 版本, 更新日誌, 回饋, 幫助",@@ -1474,6 +1481,7 @@"tab.storage": "資料儲存","tab.sync": "雲端同步","tab.systemTools": "系統工具",+ "tab.tools": "工具","tab.tts": "語音服務","tab.uploadZip": "上傳壓縮檔","tab.uploadZip.desc": "上傳本地 .zip 或 .skill 檔案",diff --git a/packages/database/src/models/__tests__/user.test.ts b/packages/database/src/models/__tests__/user.test.tsindex d1c83aa61f6..50f42b72f9c 100644--- a/packages/database/src/models/__tests__/user.test.ts+++ b/packages/database/src/models/__tests__/user.test.ts@@ -510,6 +510,64 @@ describe('UserModel', () => {});});+ describe('replaceToolChannelsSetting', () => {+ it('should create the settings row when none exists', async () => {+ await userModel.replaceToolChannelsSetting({ searchProviders: ['exa', 'searxng'] });++ const settings = await serverDB.query.userSettings.findFirst({+ where: eq(userSettings.id, userId),+ });++ expect(settings?.tool).toEqual({ searchProviders: ['exa', 'searxng'] });+ });++ it('should replace only the given channel list, preserving sibling tool keys', async () => {+ await serverDB.insert(userSettings).values({+ id: userId,+ tool: {+ crawlerImpls: ['jina'],+ humanIntervention: { approvalMode: 'auto-run' },+ searchProviders: ['searxng', 'exa'],+ uninstalledBuiltinTools: ['dalle'],+ },+ });++ await userModel.replaceToolChannelsSetting({ searchProviders: ['exa'] });++ const settings = await serverDB.query.userSettings.findFirst({+ where: eq(userSettings.id, userId),+ });++ expect(settings?.tool).toEqual({+ crawlerImpls: ['jina'],+ humanIntervention: { approvalMode: 'auto-run' },+ searchProviders: ['exa'],+ uninstalledBuiltinTools: ['dalle'],+ });+ });++ it('should not drop an approvalMode change when a channel write overlaps it', async () => {+ await serverDB.insert(userSettings).values({+ id: userId,+ tool: { humanIntervention: { approvalMode: 'manual' } },+ });++ await Promise.all([+ userModel.mergeToolInterventionSetting({ approvalMode: 'auto-run' }),+ userModel.replaceToolChannelsSetting({ crawlerImpls: ['naive', 'jina'] }),+ ]);++ const settings = await serverDB.query.userSettings.findFirst({+ where: eq(userSettings.id, userId),+ });++ expect(settings?.tool).toEqual({+ crawlerImpls: ['naive', 'jina'],+ humanIntervention: { approvalMode: 'auto-run' },+ });+ });+ });+describe('updatePreference', () => {it('should update user preference', async () => {await userModel.updatePreference({diff --git a/packages/database/src/models/user.ts b/packages/database/src/models/user.tsindex b5379112661..b0885017005 100644--- a/packages/database/src/models/user.ts+++ b/packages/database/src/models/user.ts@@ -399,6 +399,32 @@ export class UserModel {});};+ /**+ * Atomically replace the ordered search-provider and/or crawler-impl lists+ * inside the `tool` column, leaving every other key untouched. Same rationale+ * as `mergeToolInterventionSetting`: a whole-column write built from a+ * possibly-stale tab snapshot would revert sibling keys (e.g. approvalMode)+ * changed from other tabs.+ */+ replaceToolChannelsSetting = async (value: {+ crawlerImpls?: string[];+ searchProviders?: string[];+ }) => {+ const patch: Record<string, string[]> = {};+ if (value.crawlerImpls) patch.crawlerImpls = value.crawlerImpls;+ if (value.searchProviders) patch.searchProviders = value.searchProviders;++ return this.db+ .insert(userSettings)+ .values({ id: this.userId, tool: patch })+ .onConflictDoUpdate({+ set: {+ tool: sql`coalesce(${userSettings.tool}, '{}'::jsonb) || ${JSON.stringify(patch)}::jsonb`,+ },+ target: userSettings.id,+ });+ };+updatePreference = async (value: Partial<UserPreference>) => {const user = await this.db.query.users.findFirst({ where: eq(users.id, this.userId) });if (!user) return;diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex c5a5ff2a66f..4b547ac9f2d 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -1489,6 +1489,16 @@ export default {'Select a voice for the current agent, different TTS services support different voices','settingTTS.voice.preview': 'Voice Preview','settingTTS.voice.title': 'Text-to-Speech Voice',+ 'settingTool.crawler.desc':+ 'Order the services used to read full web pages. Higher items are tried first; disabled ones are skipped. Some sites, such as PDFs and YouTube, always use a dedicated service.',+ 'settingTool.crawler.title': 'Web Reader',+ 'settingTool.empty': 'No services available',+ 'settingTool.item.disabled': 'Disabled',+ 'settingTool.item.enabled': 'Enabled',+ 'settingTool.item.locked': 'Keep at least one service enabled',+ 'settingTool.search.desc':+ 'Order the services used to search the web. Higher items are tried first; disabled ones are skipped.',+ 'settingTool.search.title': 'Search Engines','skillGroup.agentConnectors': 'Agent Connectors','skillGroup.builtinSkills': 'Built-in Skills','skillGroup.builtinTools': 'Built-in Tools',@@ -1760,6 +1770,7 @@ When I am ___, I need ___'tab.storage': 'Storage','tab.sync': 'Cloud Sync','tab.systemTools': 'System Tools',+ 'tab.tools': 'Tools','tab.tts': 'Text-to-Speech','tab.uploadZip': 'Upload Zip','tab.uploadZip.desc': 'Upload a local .zip or .skill file',diff --git a/packages/types/src/user/settings/tool.ts b/packages/types/src/user/settings/tool.tsindex 618d1b98905..f8c5727c83e 100644--- a/packages/types/src/user/settings/tool.ts+++ b/packages/types/src/user/settings/tool.ts@@ -1,7 +1,23 @@import type { UserInterventionConfig } from '../../tool';export interface UserToolConfig {+ /**+ * Ordered crawler impl ids, e.g. ['jina', 'naive']: index 0 is tried first.+ *+ * Ids must be a subset of the server-enabled channels (`CRAWLER_IMPLS`);+ * unknown or disabled ids are ignored at runtime. An empty or missing list+ * falls back to the server default order.+ */+ crawlerImpls?: string[];humanIntervention?: UserInterventionConfig;+ /**+ * Ordered search provider ids, e.g. ['searxng', 'exa']: index 0 is tried first.+ *+ * Ids must be a subset of the server-enabled channels (`SEARCH_PROVIDERS`);+ * unknown or disabled ids are ignored at runtime. An empty or missing list+ * falls back to the server default order.+ */+ searchProviders?: string[];/*** List of builtin tool identifiers that have been uninstalled by the user.* By default, all builtin tools are enabled. Users can explicitly@@ -19,3 +35,11 @@ export interface UserToolConfig {*/uninstalledBuiltinToolsByWorkspace?: Record<string, string[]>;}++/**+ * User-level search / crawl channel preferences, projected from `UserToolConfig`.+ *+ * Both lists are ordered by priority (index 0 tried first) and share the same+ * subset / fallback semantics documented on the underlying fields.+ */+export type UserChannelPreferences = Pick<UserToolConfig, 'crawlerImpls' | 'searchProviders'>;diff --git a/packages/web-crawler/src/__tests__/crawler.test.ts b/packages/web-crawler/src/__tests__/crawler.test.tsindex 9db63bb221b..9fd49461c6f 100644--- a/packages/web-crawler/src/__tests__/crawler.test.ts+++ b/packages/web-crawler/src/__tests__/crawler.test.ts@@ -220,6 +220,32 @@ describe('Crawler', () => {});});+ it('should let url rules use urlRuleImpls outside the fallback impls', async () => {+ const mockResult = {+ content: 'test content'.padEnd(101, ' '),+ contentType: 'text' as const,+ url: 'https://example.com',+ };++ // Fallback order narrowed to naive, but rules may still pick any enabled impl+ const narrowedCrawler = new Crawler({ impls: ['naive'], urlRuleImpls: ['jina', 'naive'] });++ const { crawlImpls } = await import('../crawImpl');+ vi.mocked(crawlImpls.jina).mockResolvedValue(mockResult);++ const { applyUrlRules } = await import('../utils/appUrlRules');+ vi.mocked(applyUrlRules).mockReturnValue({+ transformedUrl: 'https://example.com',+ filterOptions: {},+ impls: ['jina'],+ });++ const result = await narrowedCrawler.crawl({ url: 'https://example.com' });++ expect(result.crawler).toBe('jina');+ expect(crawlImpls.naive).not.toHaveBeenCalled();+ });+it('should skip results with content length <= 100', async () => {const mockResult = {content: 'short content', // Content length <= 100diff --git a/packages/web-crawler/src/crawler.ts b/packages/web-crawler/src/crawler.tsindex a05ab5cbfb5..a474eaa23ca 100644--- a/packages/web-crawler/src/crawler.ts+++ b/packages/web-crawler/src/crawler.ts@@ -11,13 +11,32 @@ import {} from './utils/errorType';import { getNonDocumentExtension, normalizeCrawlUrl } from './utils/urlPreflight';-const defaultImpls = ['jina', 'naive', 'search1api', 'browserless'] as CrawlImplType[];+/**+ * Built-in crawler impl order used when no impls are provided. Re-exported from+ * the package entry (`@lobechat/web-crawler`) so callers resolving a+ * user-preferred order can intersect against the same default set the Crawler+ * falls back to.+ */+export const DEFAULT_CRAWL_IMPLS = [+ 'jina',+ 'naive',+ 'search1api',+ 'browserless',+] as CrawlImplType[];/** Pseudo crawler name for failures raised before any provider was contacted. */const PREFLIGHT_CRAWLER = 'preflight';interface CrawlOptions {impls?: string[];+ /**+ * Impls that URL rules may pick from. Defaults to `impls`.+ *+ * Lets a caller narrow the general fallback order (e.g. to a user's preferred+ * channels) while site-specific rules (PDF, YouTube, ...) can still use any+ * server-enabled impl, so their crawl quality does not regress.+ */+ urlRuleImpls?: string[];}/**@@ -50,13 +69,18 @@ const buildErrorData = (error: Error | undefined): CrawlErrorResult => {};};+const toKnownImpls = (impls: string[] | undefined): CrawlImplType[] =>+ impls?.length+ ? (impls.filter((impl) => Object.keys(crawlImpls).includes(impl)) as CrawlImplType[])+ : DEFAULT_CRAWL_IMPLS;+export class Crawler {impls: CrawlImplType[];+ urlRuleImpls: CrawlImplType[];constructor(options: CrawlOptions = {}) {- this.impls = !!options.impls?.length- ? (options.impls.filter((impl) => Object.keys(crawlImpls).includes(impl)) as CrawlImplType[])- : defaultImpls;+ this.impls = toKnownImpls(options.impls);+ this.urlRuleImpls = options.urlRuleImpls ? toKnownImpls(options.urlRuleImpls) : this.impls;}/**@@ -110,7 +134,9 @@ export class Crawler {let finalError: Error | undefined;const filteredRuleImpls = ruleImpls- ? (ruleImpls.filter((impl) => this.impls.includes(impl as CrawlImplType)) as CrawlImplType[])+ ? (ruleImpls.filter((impl) =>+ this.urlRuleImpls.includes(impl as CrawlImplType),+ ) as CrawlImplType[]): undefined;const systemImpls = (filteredRuleImpls?.length ? filteredRuleImpls : this.implsdiff --git a/packages/web-crawler/src/index.ts b/packages/web-crawler/src/index.tsindex 9f3c3bf9241..3650a468e91 100644--- a/packages/web-crawler/src/index.ts+++ b/packages/web-crawler/src/index.ts@@ -1,5 +1,5 @@export type { CrawlImplType } from './crawImpl';-export { Crawler } from './crawler';+export { Crawler, DEFAULT_CRAWL_IMPLS } from './crawler';export * from './type';export {HTTPStatusError,diff --git a/src/features/Settings/features/componentMap.desktop.ts b/src/features/Settings/features/componentMap.desktop.tsindex f25a872338a..73450908580 100644--- a/src/features/Settings/features/componentMap.desktop.ts+++ b/src/features/Settings/features/componentMap.desktop.ts@@ -29,6 +29,7 @@ import Skill from '../skill';import Stats from '../stats';import Storage from '../storage';import SystemTools from '../system-tools';+import Tools from '../tools';export const componentMap = {[SettingsTabs.Advanced]: Advanced,@@ -57,6 +58,7 @@ export const componentMap = {[SettingsTabs.Security]: Security,[SettingsTabs.Skill]: Skill,[SettingsTabs.Connector]: Connector,+ [SettingsTabs.Tools]: Tools,[SettingsTabs.Plans]: Plans,[SettingsTabs.Credits]: Credits,diff --git a/src/features/Settings/features/componentMap.ts b/src/features/Settings/features/componentMap.tsindex a8ba0f61b7c..1e7987cc6db 100644--- a/src/features/Settings/features/componentMap.ts+++ b/src/features/Settings/features/componentMap.ts@@ -87,6 +87,9 @@ export const componentMap = {[SettingsTabs.Connector]: dynamic(() => import('../connector'), {loading: loading('Settings > Connector'),}),+ [SettingsTabs.Tools]: dynamic(() => import('../tools'), {+ loading: loading('Settings > Tools'),+ }),[SettingsTabs.Plans]: dynamic(() => import('@/business/client/BusinessSettingPages/Plans'), {loading: loading('Settings > Plans'),diff --git a/src/features/Settings/hooks/useCategory.tsx b/src/features/Settings/hooks/useCategory.tsxindex 721a5e404df..dd9eda70773 100644--- a/src/features/Settings/hooks/useCategory.tsx+++ b/src/features/Settings/hooks/useCategory.tsx@@ -27,6 +27,7 @@ import {Sparkles,TagIcon,TerminalSquare,+ Wrench,} from 'lucide-react';import { useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -214,6 +215,11 @@ export const useCategory = () => {key: SettingsTabs.Memory,label: t('tab.memory'),},+ {+ icon: Wrench,+ key: SettingsTabs.Tools,+ label: t('tab.tools'),+ },{icon: KeyRound,key: SettingsTabs.Creds,diff --git a/src/features/Settings/tools/index.tsx b/src/features/Settings/tools/index.tsxnew file mode 100644index 00000000000..5e17fede3e2--- /dev/null+++ b/src/features/Settings/tools/index.tsx@@ -0,0 +1 @@+export { default } from '@/features/ToolSetting';diff --git a/src/features/ToolSetting/ChannelItem.tsx b/src/features/ToolSetting/ChannelItem.tsxnew file mode 100644index 00000000000..8adeab63b27--- /dev/null+++ b/src/features/ToolSetting/ChannelItem.tsx@@ -0,0 +1,99 @@+import { Center, Flexbox, SortableList, Tooltip } from '@lobehub/ui';+import { Switch, Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cx } from 'antd-style';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { getChannelDisplayName, getChannelIcon } from './const';++const ICON_SIZE = 24;++const styles = createStaticStyles(({ css, cssVar }) => ({+ icon: css`+ flex: none;+ width: ${ICON_SIZE}px;+ height: ${ICON_SIZE}px;+ `,+ inactive: css`+ opacity: 0.45;+ `,+ item: css`+ padding-block: 8px;+ padding-inline: 12px;+ border-radius: ${cssVar.borderRadius};+ transition: background 0.2s ease-in-out;++ &:hover {+ background: ${cssVar.colorFillTertiary};+ }+ `,+ name: css`+ font-weight: 500;+ `,+ rank: css`+ min-width: 16px;++ font-size: 12px;+ font-variant-numeric: tabular-nums;+ color: ${cssVar.colorTextQuaternary};+ text-align: end;+ `,+}));++interface ChannelItemProps {+ enabled: boolean;+ id: string;+ /**+ * Locks the toggle in its current state. Used to keep the last enabled channel+ * on: this list only picks & orders channels, so turning the tool itself off+ * is handled elsewhere and must not be reachable by disabling every channel.+ */+ locked?: boolean;+ onToggle: (id: string, enabled: boolean) => void;+ /** 1-based priority among enabled channels; omitted for disabled channels. */+ rank?: number;+}++const ChannelItem = memo<ChannelItemProps>(({ id, enabled, locked, rank, onToggle }) => {+ const { t } = useTranslation('setting');++ const toggle = (+ <Switch+ aria-label={t(enabled ? 'settingTool.item.enabled' : 'settingTool.item.disabled')}+ checked={enabled}+ disabled={locked}+ size={'small'}+ onChange={(checked) => onToggle(id, checked)}+ />+ );++ return (+ <SortableList.Item+ horizontal+ align={'center'}+ className={styles.item}+ gap={8}+ id={id}+ justify={'space-between'}+ >+ <Flexbox horizontal align={'center'} gap={8}>+ <SortableList.DragHandle />+ <span className={styles.rank}>{rank ?? ''}</span>+ <Flexbox horizontal align={'center'} className={cx(!enabled && styles.inactive)} gap={10}>+ <Center className={styles.icon}>{getChannelIcon(id, ICON_SIZE)}</Center>+ <Text className={styles.name}>{getChannelDisplayName(id)}</Text>+ </Flexbox>+ </Flexbox>+ {locked ? (+ // A disabled switch swallows pointer events, so the tooltip needs a wrapper.+ <Tooltip title={t('settingTool.item.locked')}>+ <span>{toggle}</span>+ </Tooltip>+ ) : (+ toggle+ )}+ </SortableList.Item>+ );+});++export default ChannelItem;diff --git a/src/features/ToolSetting/ChannelSection.tsx b/src/features/ToolSetting/ChannelSection.tsxnew file mode 100644index 00000000000..9e912b46e36--- /dev/null+++ b/src/features/ToolSetting/ChannelSection.tsx@@ -0,0 +1,59 @@+import { Block, Empty, Flexbox, SortableList } from '@lobehub/ui';+import { Text } from '@lobehub/ui/base-ui';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import type { SaveStateHandle } from '@/hooks/useSaveState';++import ChannelItem from './ChannelItem';+import { type ChannelKey, type ChannelRow, useChannelRows } from './useChannelRows';++interface ChannelSectionProps {+ availableIds: string[];+ channelKey: ChannelKey;+ desc: string;+ save: SaveStateHandle['save'];+ title: string;+}++const ChannelSection = memo<ChannelSectionProps>((props) => {+ const { channelKey, availableIds, save, title, desc } = props;+ const { t } = useTranslation('setting');+ const { rows, toggle, reorder } = useChannelRows(channelKey, availableIds, save);++ // Keep at least one channel enabled: once a single channel is left on, lock+ // its switch so users can't disable the whole section from here.+ const enabledIds = rows.filter((row) => row.enabled).map((row) => row.id);++ return (+ <Flexbox gap={8}>+ <Text strong fontSize={16}>+ {title}+ </Text>+ <Text fontSize={13} type={'secondary'}>+ {desc}+ </Text>+ <Block padding={4} style={{ marginBlockStart: 8 }} variant={'outlined'}>+ {rows.length === 0 ? (+ <Empty description={t('settingTool.empty')} />+ ) : (+ <SortableList+ items={rows}+ renderItem={(item: ChannelRow) => (+ <ChannelItem+ enabled={item.enabled}+ id={item.id}+ locked={item.enabled && enabledIds.length <= 1}+ rank={item.enabled ? enabledIds.indexOf(item.id) + 1 : undefined}+ onToggle={toggle}+ />+ )}+ onChange={reorder}+ />+ )}+ </Block>+ </Flexbox>+ );+});++export default ChannelSection;diff --git a/src/features/ToolSetting/const.tsx b/src/features/ToolSetting/const.tsxnew file mode 100644index 00000000000..3a08093d78d--- /dev/null+++ b/src/features/ToolSetting/const.tsx@@ -0,0 +1,58 @@+import { Bing, Exa, Google, Jina, Search1API, Tavily } from '@lobehub/icons';+import { Icon } from '@lobehub/ui';+import { Globe } from 'lucide-react';+import type { ReactNode } from 'react';++/**+ * Static display names for known web-browsing channel ids. Unknown ids fall+ * back to their raw id, so the picker keeps working when the server enables a+ * channel the client doesn't know about yet.+ */+const CHANNEL_DISPLAY_NAME: Record<string, string> = {+ anspire: 'Anspire',+ bing: 'Bing',+ bocha: 'Bocha',+ brave: 'Brave',+ browserless: 'Browserless',+ exa: 'Exa',+ firecrawl: 'Firecrawl',+ google: 'Google',+ jina: 'Jina',+ kagi: 'Kagi',+ naive: 'Naive',+ search1api: 'Search1API',+ searxng: 'SearXNG',+ tavily: 'Tavily',+};++export const getChannelDisplayName = (id: string): string => CHANNEL_DISPLAY_NAME[id] ?? id;++/**+ * Brand avatars for channels that ship an official icon in `@lobehub/icons`.+ * Channels without a brand icon render a generic globe glyph.+ */+export const getChannelIcon = (id: string, size = 24): ReactNode => {+ switch (id) {+ case 'bing': {+ return <Bing.Avatar size={size} />;+ }+ case 'exa': {+ return <Exa.Avatar size={size} />;+ }+ case 'google': {+ return <Google.Avatar size={size} />;+ }+ case 'jina': {+ return <Jina.Avatar size={size} />;+ }+ case 'search1api': {+ return <Search1API.Avatar size={size} />;+ }+ case 'tavily': {+ return <Tavily.Avatar size={size} />;+ }+ default: {+ return <Icon icon={Globe} size={size - 8} style={{ opacity: 0.6 }} />;+ }+ }+};diff --git a/src/features/ToolSetting/index.tsx b/src/features/ToolSetting/index.tsxnew file mode 100644index 00000000000..f28a150dc66--- /dev/null+++ b/src/features/ToolSetting/index.tsx@@ -0,0 +1,78 @@+'use client';++import { Flexbox } from '@lobehub/ui';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncBoundary from '@/components/AsyncBoundary';+import AutoSaveHint from '@/components/Editor/AutoSaveHint';+import SettingHeader from '@/features/Settings/features/SettingHeader';+import { useSaveState } from '@/hooks/useSaveState';+import { useClientDataSWR } from '@/libs/swr';+import { searchService } from '@/services/search';+import { useUserStore } from '@/store/user';++import ChannelSection from './ChannelSection';++const FETCH_AVAILABLE_CHANNELS_KEY = 'FETCH_AVAILABLE_WEB_BROWSING_CHANNELS';++const ToolSetting = memo(() => {+ const { t } = useTranslation('setting');+ const { status: saveStatus, lastSavedAt, save, retry } = useSaveState();++ const { data, error, isLoading, mutate } = useClientDataSWR(FETCH_AVAILABLE_CHANNELS_KEY, () =>+ searchService.getAvailableChannels(),+ );++ // `ChannelSection` (via `useChannelRows`) seeds its local rows ONCE on mount+ // from the saved channel order. So it must only mount after BOTH the available+ // channels (SWR) AND the user settings store have hydrated — otherwise on a+ // hard refresh it seeds from an unhydrated (undefined) `savedOrder`, silently+ // rendering the default order and ignoring the user's saved priority (and any+ // edit then overwrites the real saved order). Fold the user-state init into the+ // boundary so its skeleton covers both, and mount the sections only once ready.+ const [isUserStateInit, isUserStateInitError, refreshUserState] = useUserStore((s) => [+ s.isUserStateInit,+ s.isUserStateInitError,+ s.refreshUserState,+ ]);++ return (+ <>+ <SettingHeader+ title={t('tab.tools')}+ extra={+ <AutoSaveHint lastUpdatedTime={lastSavedAt} saveStatus={saveStatus} onRetry={retry} />+ }+ />+ <AsyncBoundary+ data={isUserStateInit ? data : undefined}+ error={error ?? (isUserStateInit ? undefined : isUserStateInitError)}+ isLoading={isLoading || !isUserStateInit}+ onRetry={() => {+ void mutate();+ void refreshUserState();+ }}+ >+ <Flexbox gap={32} style={{ paddingBlock: 16 }}>+ <ChannelSection+ availableIds={(data?.searchProviders ?? []).map((c) => c.id)}+ channelKey={'searchProviders'}+ desc={t('settingTool.search.desc')}+ save={save}+ title={t('settingTool.search.title')}+ />+ <ChannelSection+ availableIds={(data?.crawlerImpls ?? []).map((c) => c.id)}+ channelKey={'crawlerImpls'}+ desc={t('settingTool.crawler.desc')}+ save={save}+ title={t('settingTool.crawler.title')}+ />+ </Flexbox>+ </AsyncBoundary>+ </>+ );+});++export default ToolSetting;diff --git a/src/features/ToolSetting/useChannelRows.test.ts b/src/features/ToolSetting/useChannelRows.test.tsnew file mode 100644index 00000000000..5838e6d5053--- /dev/null+++ b/src/features/ToolSetting/useChannelRows.test.ts@@ -0,0 +1,69 @@+import { act, renderHook, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useSaveState } from '@/hooks/useSaveState';++import { useChannelRows } from './useChannelRows';++const mockUpdateToolChannels = vi.hoisted(() => vi.fn());+const mockUseUserStore = vi.hoisted(() => vi.fn());++vi.mock('@/store/user', () => ({+ useUserStore: mockUseUserStore,+}));++vi.mock('@/store/user/slices/settings/selectors', () => ({+ settingsSelectors: {+ currentSettings: (state: { settings: { tool: { searchProviders: string[] } } }) =>+ state.settings,+ },+}));++const useSubject = () => {+ const { status, lastSavedAt, retry, save } = useSaveState();+ const channelRows = useChannelRows('searchProviders', ['searxng', 'google'], save);++ return { ...channelRows, lastSavedAt, retry, status };+};++describe('useChannelRows', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockUseUserStore.mockImplementation((selector) =>+ selector({+ updateToolChannels: mockUpdateToolChannels,+ settings: { tool: { searchProviders: ['searxng'] } },+ }),+ );+ });++ it('keeps the local change visible and retries a failed preference save', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ mockUpdateToolChannels.mockRejectedValueOnce(new Error('network error'));++ const { result } = renderHook(useSubject);++ act(() => {+ result.current.toggle('google', true);+ });++ await waitFor(() => expect(result.current.status).toBe('failed'));+ expect(result.current.rows).toEqual([+ { enabled: true, id: 'searxng' },+ { enabled: true, id: 'google' },+ ]);+ expect(mockUpdateToolChannels).toHaveBeenLastCalledWith({+ searchProviders: ['searxng', 'google'],+ });++ mockUpdateToolChannels.mockResolvedValueOnce(undefined);+ await act(async () => result.current.retry());++ expect(result.current.status).toBe('saved');+ expect(result.current.lastSavedAt).toBeInstanceOf(Date);+ expect(mockUpdateToolChannels).toHaveBeenCalledTimes(2);+ expect(mockUpdateToolChannels).toHaveBeenLastCalledWith({+ searchProviders: ['searxng', 'google'],+ });+ });+});diff --git a/src/features/ToolSetting/useChannelRows.ts b/src/features/ToolSetting/useChannelRows.tsnew file mode 100644index 00000000000..39802296878--- /dev/null+++ b/src/features/ToolSetting/useChannelRows.ts@@ -0,0 +1,86 @@+import { useState } from 'react';++import type { SaveStateHandle } from '@/hooks/useSaveState';+import { useUserStore } from '@/store/user';+import { settingsSelectors } from '@/store/user/slices/settings/selectors';++export type ChannelKey = 'crawlerImpls' | 'searchProviders';++export interface ChannelRow {+ enabled: boolean;+ id: string;+}++/**+ * Build the initial ordered rows from the server-provided available channels+ * and the user's saved config.+ *+ * - No saved config → all channels enabled, in server default order.+ * - Saved config → enabled channels first (in the user's saved priority order,+ * filtered to still-available ids), then the remaining available channels as+ * disabled, in server order.+ *+ * An empty saved array — or a saved array whose ids no longer intersect the+ * available set (e.g. the configured providers were disabled/renamed on the+ * server) — is treated as "unconfigured" (all enabled). This matches the+ * server-side `resolveOrderedChannels` fallback (empty intersection → default+ * order), keeps the "at least one enabled" invariant, and avoids rendering every+ * channel as disabled while search/crawl actually runs on the default set.+ */+const buildRows = (availableIds: string[], savedOrder: string[] | undefined): ChannelRow[] => {+ if (!savedOrder?.length) return availableIds.map((id) => ({ enabled: true, id }));++ const enabledIds = savedOrder.filter((id) => availableIds.includes(id));+ if (enabledIds.length === 0) return availableIds.map((id) => ({ enabled: true, id }));++ const enabledSet = new Set(enabledIds);+ const disabledIds = availableIds.filter((id) => !enabledSet.has(id));++ return [+ ...enabledIds.map((id) => ({ enabled: true, id })),+ ...disabledIds.map((id) => ({ enabled: false, id })),+ ];+};++/**+ * Manage the local order + enabled state for a single channel list and persist+ * changes to the corresponding top-level `settings.tool.<channelKey>` field.+ *+ * Only enabled ids are persisted (as an ordered array = priority). Disabled+ * ids are simply absent, matching the `UserChannelPreferences` contract.+ *+ * Local UI state is seeded ONCE from `availableIds` + `savedOrder` on mount and+ * is intentionally NOT re-synced afterwards (avoids the write-back → re-render →+ * reset loop). The parent (`ToolSetting`) MUST therefore only mount this+ * component after BOTH the available channels have been fetched AND the user+ * settings store has hydrated (`isUserStateInit`) — otherwise `savedOrder` reads+ * as `undefined` at mount and the saved priority order is lost on a hard refresh.+ */+export const useChannelRows = (+ channelKey: ChannelKey,+ availableIds: string[],+ save: SaveStateHandle['save'],+) => {+ const savedOrder = useUserStore((s) => settingsSelectors.currentSettings(s).tool?.[channelKey]);+ const updateToolChannels = useUserStore((s) => s.updateToolChannels);++ const [rows, setRows] = useState<ChannelRow[]>(() => buildRows(availableIds, savedOrder));++ const persist = (nextRows: ChannelRow[]) => {+ const enabledIds = nextRows.filter((row) => row.enabled).map((row) => row.id);+ return updateToolChannels({ [channelKey]: enabledIds });+ };++ const reorder = (nextRows: ChannelRow[]) => {+ setRows(nextRows);+ void save(() => persist(nextRows));+ };++ const toggle = (id: string, enabled: boolean) => {+ const nextRows = rows.map((row) => (row.id === id ? { ...row, enabled } : row));+ setRows(nextRows);+ void save(() => persist(nextRows));+ };++ return { reorder, rows, toggle };+};diff --git a/src/routes/(mobile)/me/settings/features/useCategory.tsx b/src/routes/(mobile)/me/settings/features/useCategory.tsxindex 4a37e20fb37..022d5c227c3 100644--- a/src/routes/(mobile)/me/settings/features/useCategory.tsx+++ b/src/routes/(mobile)/me/settings/features/useCategory.tsx@@ -18,6 +18,7 @@ import {Sparkles,TagIcon,UserCircle,+ Wrench,} from 'lucide-react';import { useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -119,6 +120,7 @@ export const useCategory = (): CategoryGroup[] => {makeItem({ icon: TagIcon, key: SettingsTabs.Labels, label: t('setting:tab.labels') }),makeItem({ icon: Blocks, key: SettingsTabs.Connector, label: t('setting:tab.connector') }),makeItem({ icon: BrainCircuit, key: SettingsTabs.Memory, label: t('setting:tab.memory') }),+ makeItem({ icon: Wrench, key: SettingsTabs.Tools, label: t('setting:tab.tools') }),makeItem({ icon: KeyRound, key: SettingsTabs.Creds, label: t('setting:tab.creds') }),showApiKeyManage &&makeItem({ icon: KeyIcon, key: SettingsTabs.APIKey, label: t('auth:tab.apikey') }),diff --git a/src/services/search.ts b/src/services/search.tsindex a0c903d8dfc..c57d2c25367 100644--- a/src/services/search.ts+++ b/src/services/search.ts@@ -18,6 +18,15 @@ class SearchService {async webSearch(params: SearchQuery, options?: { signal?: AbortSignal }) {return toolsClient.search.webSearch.query(params, { signal: options?.signal });}++ /**+ * Server-enabled search providers / crawler impls in the server default+ * priority order. Used by the Web Search settings page to render the+ * channel-ordering picker.+ */+ async getAvailableChannels() {+ return toolsClient.search.getAvailableChannels.query();+ }}export const searchService = new SearchService();diff --git a/src/services/user/index.ts b/src/services/user/index.tsindex 4b0ebc3e846..1d4b47da5a1 100644--- a/src/services/user/index.ts+++ b/src/services/user/index.ts@@ -138,6 +138,10 @@ export class UserService {return lambdaClient.user.updateToolIntervention.mutate(value);};+ updateToolChannels = async (value: { crawlerImpls?: string[]; searchProviders?: string[] }) => {+ return lambdaClient.user.updateToolChannels.mutate(value);+ };+updateUninstalledBuiltinTools = async (uninstalledBuiltinTools: string[],workspaceId: string | null,diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.tsindex 77dcc8d3d42..06d6bde0d3d 100644--- a/src/store/global/initialState.ts+++ b/src/store/global/initialState.ts@@ -97,6 +97,7 @@ export enum SettingsTabs {Stats = 'stats',Storage = 'storage',SystemTools = 'system-tools',+ Tools = 'tools',/** @deprecated Use ServiceModel instead */TTS = 'tts',Usage = 'usage',diff --git a/src/store/user/slices/settings/action.test.ts b/src/store/user/slices/settings/action.test.tsindex 41d0bb76c71..ef91e43f9e3 100644--- a/src/store/user/slices/settings/action.test.ts+++ b/src/store/user/slices/settings/action.test.ts@@ -12,6 +12,7 @@ import { merge } from '@/utils/merge';// Mock userServicevi.mock('@/services/user', () => ({userService: {+ updateToolChannels: vi.fn(),updateToolIntervention: vi.fn(),updateUserSettings: vi.fn(),resetUserSettings: vi.fn(),@@ -157,6 +158,41 @@ describe('SettingsAction', () => {expect(payload.market).toEqual(expect.objectContaining({ accessToken: 'tok-1' }));});+ it('should resend a failed change when the same change is retried', async () => {+ const { result } = renderHook(() => useUserStore());+ const change = {+ tool: { searchProviders: ['searxng', 'tavily'] },+ } as PartialDeep<UserSettings>;++ vi.mocked(userService.updateUserSettings).mockRejectedValueOnce(new Error('network error'));++ await act(async () => {+ await expect(result.current.setSettings(change)).rejects.toThrow('network error');+ });++ // The optimistic value is still in local state, so the retry diffs as+ // "no change" — it must still reach the server instead of resolving silently.+ vi.mocked(userService.updateUserSettings).mockClear();+ await act(async () => {+ await result.current.setSettings(change);+ });++ expect(userService.updateUserSettings).toHaveBeenCalledTimes(1);+ expect(userService.updateUserSettings).toHaveBeenLastCalledWith(+ expect.objectContaining({+ tool: expect.objectContaining({ searchProviders: ['searxng', 'tavily'] }),+ }),+ expect.any(AbortSignal),+ );++ // Once persisted, an identical call is a no-op again.+ vi.mocked(userService.updateUserSettings).mockClear();+ await act(async () => {+ await result.current.setSettings(change);+ });+ expect(userService.updateUserSettings).not.toHaveBeenCalled();+ });+it('should keep legacy scalar system agent fields unchanged', async () => {const { result } = renderHook(() => useUserStore());const settingsWithLegacySystemAgent = {@@ -200,6 +236,86 @@ describe('SettingsAction', () => {});});+ describe('updateToolChannels', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('should write through the server-side patch endpoint instead of setSettings', async () => {+ const { result } = renderHook(() => useUserStore());++ await act(async () => {+ await result.current.updateToolChannels({ searchProviders: ['exa', 'searxng'] });+ });++ expect(userService.updateToolChannels).toHaveBeenCalledWith({+ searchProviders: ['exa', 'searxng'],+ });+ // A whole-settings diff write would replace the full `tool` column with+ // this tab's possibly-stale snapshot+ expect(userService.updateUserSettings).not.toHaveBeenCalled();+ expect(result.current.settings.tool?.searchProviders).toEqual(['exa', 'searxng']);+ });++ it('should send rapid successive writes one at a time, in call order', async () => {+ const { result } = renderHook(() => useUserStore());+ const resolvers: Array<() => void> = [];+ vi.mocked(userService.updateToolChannels).mockImplementation(+ () => new Promise((resolve) => resolvers.push(() => resolve(undefined as any))),+ );++ let first!: Promise<void>;+ let second!: Promise<void>;+ act(() => {+ first = result.current.updateToolChannels({ searchProviders: ['exa'] });+ second = result.current.updateToolChannels({ searchProviders: ['searxng'] });+ });++ // The second request is not sent until the first has committed+ await vi.waitFor(() => expect(userService.updateToolChannels).toHaveBeenCalledTimes(1));+ expect(userService.updateToolChannels).toHaveBeenLastCalledWith({+ searchProviders: ['exa'],+ });++ await act(async () => {+ resolvers[0]();+ await first;+ });+ await vi.waitFor(() => expect(userService.updateToolChannels).toHaveBeenCalledTimes(2));+ expect(userService.updateToolChannels).toHaveBeenLastCalledWith({+ searchProviders: ['searxng'],+ });++ await act(async () => {+ resolvers[1]();+ await second;+ });+ expect(result.current.settings.tool?.searchProviders).toEqual(['searxng']);+ });++ it('should still send a later write after an earlier one fails', async () => {+ const { result } = renderHook(() => useUserStore());+ vi.mocked(userService.updateToolChannels)+ .mockRejectedValueOnce(new Error('network error'))+ .mockResolvedValueOnce(undefined as any);++ let first!: Promise<void>;+ let second!: Promise<void>;+ act(() => {+ first = result.current.updateToolChannels({ crawlerImpls: ['jina'] });+ second = result.current.updateToolChannels({ crawlerImpls: ['naive'] });+ });++ await expect(first).rejects.toThrow('network error');+ await act(async () => {+ await second;+ });+ expect(userService.updateToolChannels).toHaveBeenLastCalledWith({+ crawlerImpls: ['naive'],+ });+ });+ });+describe('addToolToAllowList', () => {beforeEach(() => {vi.clearAllMocks();diff --git a/src/store/user/slices/settings/action.ts b/src/store/user/slices/settings/action.tsindex 5b4247a9549..e28c5c631a9 100644--- a/src/store/user/slices/settings/action.ts+++ b/src/store/user/slices/settings/action.ts@@ -38,6 +38,12 @@ export class UserSettingsActionImpl {* payload or the aborted change would silently never persist.*/readonly #pendingSettingKeys = new Set<string>();+ /**+ * Tail of the in-flight `updateToolChannels` writes. Each write waits for the+ * previous one so rapid toggles/reorders land in call order — parallel+ * requests could commit out of order and leave an older list in the DB.+ */+ #toolChannelsWrite: Promise<unknown> = Promise.resolve();constructor(set: Setter, get: () => UserStore, _api?: unknown) {void _api;@@ -107,7 +113,11 @@ export class UserSettingsActionImpl {const nextSettings = merge(prevSetting, settings);- if (isEqual(prevSetting, nextSettings)) return;+ // A failed write leaves its optimistic value in local state and its columns+ // in `#pendingSettingKeys`. Retrying the same change then diffs as "no+ // change", so only skip when nothing is still waiting to be persisted —+ // otherwise a retry would resolve without a request and look saved.+ if (isEqual(prevSetting, nextSettings) && this.#pendingSettingKeys.size === 0) return;const diffs = difference(nextSettings, defaultSettings);const isEmptyObjectDiff = (value: unknown): boolean =>@@ -275,6 +285,34 @@ export class UserSettingsActionImpl {await this.#get().refreshUserState();};+ updateToolChannels = async (channels: {+ crawlerImpls?: string[];+ searchProviders?: string[];+ }): Promise<void> => {+ // Optimistic local update, then a server-side patch of only these keys —+ // setSettings would replace the whole `tool` column with this tab's+ // snapshot and revert sibling keys changed elsewhere (see+ // updateHumanIntervention). `merge` replaces arrays wholesale, so the new+ // ordered lists are stored as-is.+ this.#set(+ { settings: merge(this.#get().settings, { tool: channels }) },+ false,+ 'optimistic_updateToolChannels',+ );++ // A failed earlier write must not block later ones; its caller still+ // receives the rejection through its own `write` promise.+ const write = this.#toolChannelsWrite+ .catch(() => {})+ .then(() => userService.updateToolChannels(channels));+ this.#toolChannelsWrite = write;++ await write;+ // Only the latest write refreshes: an intermediate refresh would pull a+ // list that a queued write is about to replace.+ if (this.#toolChannelsWrite === write) await this.#get().refreshUserState();+ };+updateKeyVaults = async (keyVaults: Partial<UserKeyVaults>): Promise<void> => {await this.#get().setSettings({ keyVaults });};