Skip to content

🤯 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.

🐛 fix(search): surface web search provider failures (#17100)

H-TTTTT1b8e12a7ab39
diff --git a/apps/cli/src/commands/search.test.ts b/apps/cli/src/commands/search.test.ts
index ea4867d8ce7..6f72d57e890 100644
--- a/apps/cli/src/commands/search.test.ts
+++ b/apps/cli/src/commands/search.test.ts
@@ -1,9 +1,15 @@
import { Command } from 'commander';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { log } from '../utils/logger';
import { registerSearchCommand } from './search';
-const { mockTrpcClient } = vi.hoisted(() => ({
+const { mockTrpcClient, mockToolsTrpcClient } = vi.hoisted(() => ({
+ mockToolsTrpcClient: {
+ search: {
+ webSearch: { query: vi.fn() },
+ },
+ },
mockTrpcClient: {
search: {
query: { query: vi.fn() },
@@ -11,11 +17,17 @@ const { mockTrpcClient } = vi.hoisted(() => ({
},
}));
-const { getTrpcClient: mockGetTrpcClient } = vi.hoisted(() => ({
- getTrpcClient: vi.fn(),
-}));
+const { getTrpcClient: mockGetTrpcClient, getToolsTrpcClient: mockGetToolsTrpcClient } = vi.hoisted(
+ () => ({
+ getToolsTrpcClient: vi.fn(),
+ getTrpcClient: vi.fn(),
+ }),
+);
-vi.mock('../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));
+vi.mock('../api/client', () => ({
+ getToolsTrpcClient: mockGetToolsTrpcClient,
+ getTrpcClient: mockGetTrpcClient,
+}));
vi.mock('../utils/logger', () => ({
log: { debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() },
setVerbose: vi.fn(),
@@ -29,7 +41,10 @@ describe('search command', () => {
exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);
consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
mockGetTrpcClient.mockResolvedValue(mockTrpcClient);
+ mockGetToolsTrpcClient.mockResolvedValue(mockToolsTrpcClient);
mockTrpcClient.search.query.query.mockReset();
+ mockToolsTrpcClient.search.webSearch.query.mockReset();
+ vi.mocked(log.error).mockClear();
});
afterEach(() => {
@@ -130,4 +145,38 @@ describe('search command', () => {
expect(exitSpy).toHaveBeenCalledWith(1);
stderrSpy.mockRestore();
});
+
+ it('should surface web search provider failures for non-JSON output', async () => {
+ mockToolsTrpcClient.search.webSearch.query.mockResolvedValue({
+ costTime: 0,
+ errorDetail: 'All search providers failed',
+ query: 'broken',
+ resultNumbers: 0,
+ results: [],
+ });
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'search', '-w', '-q', 'broken']);
+
+ expect(log.error).toHaveBeenCalledWith('All search providers failed');
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ expect(consoleSpy).not.toHaveBeenCalled();
+ });
+
+ it('should keep JSON web search failure output and exit nonzero', async () => {
+ const failure = {
+ costTime: 0,
+ errorDetail: 'All search providers failed',
+ query: 'broken',
+ resultNumbers: 0,
+ results: [],
+ };
+ mockToolsTrpcClient.search.webSearch.query.mockResolvedValue(failure);
+
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'search', '-w', '-q', 'broken', '--json']);
+
+ expect(consoleSpy).toHaveBeenCalledWith(JSON.stringify(failure, null, 2));
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ });
});
diff --git a/apps/cli/src/commands/search.ts b/apps/cli/src/commands/search.ts
index 627e0823691..ef91bc2e236 100644
--- a/apps/cli/src/commands/search.ts
+++ b/apps/cli/src/commands/search.ts
@@ -3,6 +3,7 @@ import pc from 'picocolors';
import { getToolsTrpcClient, getTrpcClient } from '../api/client';
import { outputJson, printTable, truncate } from '../utils/format';
+import { log } from '../utils/logger';
const SEARCH_TYPES = [
'agent',
@@ -184,14 +185,20 @@ async function webSearch(
if (options.timeRange) input.searchTimeRange = options.timeRange;
const result = await toolsClient.search.webSearch.query(input);
+ const res = result as any;
if (options.json !== undefined) {
const fields = typeof options.json === 'string' ? options.json : undefined;
outputJson(result, fields);
+ if (res.errorDetail) process.exit(1);
return;
}
- const res = result as any;
+ if (res.errorDetail) {
+ log.error(String(res.errorDetail));
+ process.exit(1);
+ return;
+ }
console.log(
pc.dim(
diff --git a/apps/server/src/services/search/index.test.ts b/apps/server/src/services/search/index.test.ts
index ccd981fb38c..33dfc715425 100644
--- a/apps/server/src/services/search/index.test.ts
+++ b/apps/server/src/services/search/index.test.ts
@@ -99,18 +99,33 @@ describe('SearchService', () => {
expect(mockSearchImpl.query).toHaveBeenCalledWith('test query', params);
});
- it('should return errorDetail instead of throwing when impl fails', async () => {
- mockSearchImpl.query.mockRejectedValue(new Error('Service unavailable'));
+ it('should return errorDetail without logging sensitive provider details', async () => {
+ const errorMessage = '401 Bearer sk-sensitive-token - upstream response body';
+ class TestSearchImpl {
+ query = vi.fn().mockRejectedValue(new Error(errorMessage));
+ }
+ const testSearchImpl = new TestSearchImpl();
+ vi.mocked(createSearchServiceImpl).mockReturnValue(testSearchImpl as any);
+ searchService = new SearchService();
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
const result = await searchService.query('test query');
expect(result).toEqual({
costTime: 0,
- errorDetail: 'Service unavailable',
+ errorDetail: errorMessage,
query: 'test query',
resultNumbers: 0,
results: [],
});
+ expect(consoleError).toHaveBeenCalledWith('[SearchService] query failed', {
+ provider: 'TestSearchImpl',
+ });
+
+ const loggedContent = JSON.stringify(consoleError.mock.calls);
+ expect(loggedContent).not.toContain('sk-sensitive-token');
+ expect(loggedContent).not.toContain('upstream response body');
+ consoleError.mockRestore();
});
});
@@ -322,7 +337,7 @@ describe('SearchService', () => {
expect(result).toBe(successResponse);
});
- it('should return empty results after all retries fail', async () => {
+ it('should return the successful empty response after all retries find no results', async () => {
const emptyResponse = {
costTime: 100,
query: 'test',
@@ -337,8 +352,9 @@ describe('SearchService', () => {
searchEngines: ['google'],
});
- expect(result.results).toHaveLength(0);
- expect(result).toEqual({ costTime: 0, query: 'test', resultNumbers: 0, results: [] });
+ expect(mockSearchImpl.query).toHaveBeenCalledTimes(2);
+ expect(result).toBe(emptyResponse);
+ expect(result).not.toHaveProperty('errorDetail');
});
});
@@ -386,7 +402,7 @@ describe('SearchService', () => {
expect(result).toBe(successResponse);
});
- it('should try all providers in order and return empty when all fail', async () => {
+ it('should try all providers in order and return empty when none find results', async () => {
const mockImpl1 = { query: vi.fn().mockResolvedValue(emptyResponse) };
const mockImpl2 = { query: vi.fn().mockResolvedValue(emptyResponse) };
const mockImpl3 = { query: vi.fn().mockResolvedValue(emptyResponse) };
@@ -404,7 +420,7 @@ describe('SearchService', () => {
expect(mockImpl1.query).toHaveBeenCalled();
expect(mockImpl2.query).toHaveBeenCalled();
expect(mockImpl3.query).toHaveBeenCalled();
- expect(result.results).toHaveLength(0);
+ expect(result).toBe(emptyResponse);
});
it('should not call later providers if first provider succeeds', async () => {
@@ -447,14 +463,7 @@ describe('SearchService', () => {
expect(result).toBe(successResponse);
});
- it('should handle provider errors gracefully and continue to next', async () => {
- const errorResponse = {
- costTime: 0,
- errorDetail: 'Service unavailable',
- query: 'test',
- resultNumbers: 0,
- results: [],
- };
+ it('should skip retries for a failed provider and return a later provider success', async () => {
const mockImpl1 = { query: vi.fn().mockRejectedValue(new Error('Service unavailable')) };
const mockImpl2 = { query: vi.fn().mockResolvedValue(successResponse) };
@@ -465,12 +474,67 @@ describe('SearchService', () => {
vi.mocked(toolsEnv).SEARCH_PROVIDERS = 'searxng,exa';
searchService = new SearchService();
- const result = await searchService.webSearch({ query: 'test' });
+ const result = await searchService.webSearch({
+ query: 'test',
+ searchEngines: ['google'],
+ });
- // First provider error results in empty results -> next provider
- expect(mockImpl2.query).toHaveBeenCalled();
+ expect(mockImpl1.query).toHaveBeenCalledTimes(1);
+ expect(mockImpl2.query).toHaveBeenCalledTimes(1);
expect(result).toBe(successResponse);
});
+
+ it('should preserve an earlier successful empty response when a later provider fails', async () => {
+ const mockImpl1 = { query: vi.fn().mockResolvedValue(emptyResponse) };
+ const mockImpl2 = { query: vi.fn().mockRejectedValue(new Error('Service unavailable')) };
+
+ vi.mocked(createSearchServiceImpl)
+ .mockReturnValueOnce(mockImpl1 as any)
+ .mockReturnValueOnce(mockImpl2 as any);
+
+ vi.mocked(toolsEnv).SEARCH_PROVIDERS = 'searxng,exa';
+ searchService = new SearchService();
+
+ const result = await searchService.webSearch({ query: 'test' });
+
+ expect(mockImpl1.query).toHaveBeenCalledTimes(1);
+ expect(mockImpl2.query).toHaveBeenCalledTimes(1);
+ expect(result).toBe(emptyResponse);
+ expect(result).not.toHaveProperty('errorDetail');
+ });
+
+ it('should return a sanitized error when every provider fails', async () => {
+ const mockImpl1 = {
+ query: vi.fn().mockRejectedValue(new Error('401 Bearer sk-sensitive-token')),
+ };
+ const mockImpl2 = {
+ query: vi.fn().mockRejectedValue(new Error('503 upstream response body')),
+ };
+
+ vi.mocked(createSearchServiceImpl)
+ .mockReturnValueOnce(mockImpl1 as any)
+ .mockReturnValueOnce(mockImpl2 as any);
+
+ vi.mocked(toolsEnv).SEARCH_PROVIDERS = 'searxng,exa';
+ searchService = new SearchService();
+
+ const result = await searchService.webSearch({
+ query: 'test',
+ searchEngines: ['google'],
+ });
+
+ expect(mockImpl1.query).toHaveBeenCalledTimes(1);
+ expect(mockImpl2.query).toHaveBeenCalledTimes(1);
+ expect(result).toEqual({
+ costTime: 0,
+ errorDetail: 'Web search failed because all configured providers returned errors',
+ query: 'test',
+ resultNumbers: 0,
+ results: [],
+ });
+ expect(result.errorDetail).not.toContain('sk-sensitive-token');
+ expect(result.errorDetail).not.toContain('upstream response body');
+ });
});
describe('crawlPages', () => {
diff --git a/apps/server/src/services/search/index.ts b/apps/server/src/services/search/index.ts
index f02e38d0fd6..f443eb62c89 100644
--- a/apps/server/src/services/search/index.ts
+++ b/apps/server/src/services/search/index.ts
@@ -1,4 +1,4 @@
-import type { SearchParams, SearchQuery } from '@lobechat/types';
+import type { SearchParams, SearchQuery, UniformSearchResponse } from '@lobechat/types';
import type { Crawler, CrawlImplType, CrawlUniformResult } from '@lobechat/web-crawler';
import debug from 'debug';
import pMap from 'p-map';
@@ -10,6 +10,8 @@ import { createSearchServiceImpl } from './impls';
const DEFAULT_CRAWL_CONCURRENCY = 3;
const DEFAULT_CRAWLER_RETRY = 1;
+const SEARCH_PROVIDERS_FAILED =
+ 'Web search failed because all configured providers returned errors';
const log = debug('lobe-oom:web-browsing:search-service');
const parseImplEnv = (envString: string = '') => {
@@ -164,7 +166,9 @@ export class SearchService {
try {
return await impl.query(query, params);
} catch (e) {
- console.error('[SearchService] query failed:', (e as Error).message);
+ console.error('[SearchService] query failed', {
+ provider: impl.constructor.name || 'UnknownSearchImpl',
+ });
return {
costTime: 0,
errorDetail: (e as Error).message,
@@ -196,6 +200,8 @@ export class SearchService {
}
} catch {}
+ let lastSuccessfulEmpty: UniformSearchResponse | undefined;
+
for (const impl of this.searchImpList) {
try {
if (log.enabled) {
@@ -212,30 +218,40 @@ export class SearchService {
searchEngines: impl.useAutoSearchEngineSelection ? undefined : searchEngines,
searchTimeRange,
});
- let data = await this.queryWithImpl(impl, query, currentParams);
-
- // First retry: remove search engine restrictions if no results found
- if (data.results.length === 0 && currentParams?.searchEngines?.length) {
- currentParams = buildSearchParams({
- searchCategories,
- searchTimeRange,
- });
- data = await this.queryWithImpl(impl, query, currentParams);
- }
+ while (true) {
+ const data = await this.queryWithImpl(impl, query, currentParams);
- // Second retry: remove all restrictions if still no results found
- if (data.results.length === 0 && currentParams) {
- data = await this.queryWithImpl(impl, query);
- }
+ if (data.errorDetail) break;
+ if (data.results.length > 0) return data;
+
+ lastSuccessfulEmpty = data;
+
+ if (currentParams?.searchEngines?.length) {
+ currentParams = buildSearchParams({
+ searchCategories,
+ searchTimeRange,
+ });
+ continue;
+ }
+
+ if (currentParams) {
+ currentParams = undefined;
+ continue;
+ }
- // If this provider returned results, use them
- if (data.results.length > 0) {
- return data;
+ break;
}
}
- // All providers exhausted, return empty result
- return { costTime: 0, query, resultNumbers: 0, results: [] };
+ if (lastSuccessfulEmpty) return lastSuccessfulEmpty;
+
+ return {
+ costTime: 0,
+ errorDetail: SEARCH_PROVIDERS_FAILED,
+ query,
+ resultNumbers: 0,
+ results: [],
+ };
}
}