🤯 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
🐛 fix(knowledge-base): say when no knowledge base is in search scope (#20084)
Arvin Xuc90328da6315
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/knowledgeBase.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/knowledgeBase.test.tsnew file mode 100644index 00000000000..ec146f039df--- /dev/null+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/knowledgeBase.test.ts@@ -0,0 +1,86 @@+import type { LobeChatDatabase } from '@lobechat/database';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { ToolExecutionContext } from '../../types';+import { knowledgeBaseRuntime } from '../knowledgeBase';++const mocks = vi.hoisted(() => ({+ getAgentAssignedKnowledge: vi.fn(),+ getEnabledKnowledgeBaseIdsForTask: vi.fn(),+ semanticSearchForChat: vi.fn(),+}));++vi.mock('@/database/models/agent', () => ({+ AgentModel: vi.fn().mockImplementation(function () {+ return { getAgentAssignedKnowledge: mocks.getAgentAssignedKnowledge };+ }),+}));++vi.mock('@/database/models/project', () => ({+ ProjectModel: vi.fn().mockImplementation(function () {+ return { getEnabledKnowledgeBaseIdsForTask: mocks.getEnabledKnowledgeBaseIdsForTask };+ }),+}));++vi.mock('@/database/models/file', () => ({ FileModel: vi.fn() }));+vi.mock('@/database/models/knowledgeBase', () => ({ KnowledgeBaseModel: vi.fn() }));+vi.mock('@/database/repositories/knowledge', () => ({ KnowledgeRepo: vi.fn() }));+vi.mock('@/server/services/document', () => ({ DocumentService: vi.fn() }));+vi.mock('@/server/services/file', () => ({ FileService: vi.fn() }));++vi.mock('@/server/services/knowledgeBase', () => ({+ KnowledgeBaseSearchService: vi.fn().mockImplementation(function () {+ return { semanticSearchForChat: mocks.semanticSearchForChat };+ }),+}));++const createRuntime = (context: Partial<ToolExecutionContext> = {}) =>+ knowledgeBaseRuntime.factory({+ agentId: 'agt_research',+ serverDB: {} as LobeChatDatabase,+ toolManifestMap: {},+ userId: 'user_alice',+ ...context,+ } as ToolExecutionContext);++describe('knowledgeBaseRuntime searchKnowledgeBase scope', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.getEnabledKnowledgeBaseIdsForTask.mockResolvedValue([]);+ });++ it('reports an empty scope instead of "no relevant files" when the agent has no attached knowledge base', async () => {+ // The KB the agent just created exists, but is not attached to the agent.+ mocks.getAgentAssignedKnowledge.mockResolvedValue({ files: [], knowledgeBases: [] });++ const result = await createRuntime().searchKnowledgeBase({ query: 'launch checklist' });++ expect(mocks.semanticSearchForChat).not.toHaveBeenCalled();+ expect(result.success).toBe(true);+ expect(result.content).toContain('No enabled knowledge base is in this agent');+ expect(result.content).not.toContain('No relevant files found');+ });++ it('searches the attached knowledge bases and keeps the no-match message when nothing matches', async () => {+ mocks.getAgentAssignedKnowledge.mockResolvedValue({+ files: [],+ knowledgeBases: [+ { enabled: true, id: 'kb_product' },+ { enabled: false, id: 'kb_archived' },+ ],+ });+ mocks.semanticSearchForChat.mockResolvedValue({+ chunks: [],+ documents: [],+ fileResults: [],+ totalResults: 0,+ });++ const result = await createRuntime().searchKnowledgeBase({ query: 'launch checklist' });++ expect(mocks.semanticSearchForChat).toHaveBeenCalledWith(+ expect.objectContaining({ knowledgeIds: ['kb_product'], query: 'launch checklist' }),+ );+ expect(result.content).toContain('No relevant files found');+ });+});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts b/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.tsindex 7b2f18627f9..bfd1878a466 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/knowledgeBase.ts@@ -52,6 +52,12 @@ export const knowledgeBaseRuntime: ServerRuntimeRegistration = {getFileContents: (fileIds) => searchService.getFileContents(fileIds),semanticSearchForChat: async ({ knowledgeIds, query, topK }) => {const effectiveKnowledgeIds = await resolveAgentKnowledgeBaseIds(knowledgeIds);+ // No enabled KB in scope (none attached, or all turned off) → both search paths would return nothing (BM25 is+ // KB-scoped; vector has no file scope). Skip the embedding call and+ // report the empty scope so the runtime can tell the model why.+ if (effectiveKnowledgeIds.length === 0) {+ return { chunks: [], documents: [], fileResults: [], searchedKnowledgeBaseIds: [] };+ }const result = await searchService.semanticSearchForChat({knowledgeIds: effectiveKnowledgeIds,query,@@ -62,6 +68,7 @@ export const knowledgeBaseRuntime: ServerRuntimeRegistration = {documents: result.documents,errors: result.errors,fileResults: result.fileResults,+ searchedKnowledgeBaseIds: effectiveKnowledgeIds,};},},diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.jsonindex ffdfe1dc240..0f9e97af822 100644--- a/locales/en-US/plugin.json+++ b/locales/en-US/plugin.json@@ -349,6 +349,8 @@"builtins.lobe-knowledge-base.apiName.searchKnowledgeBase": "Search Library","builtins.lobe-knowledge-base.inspector.andMoreFiles": "and {{count}} more","builtins.lobe-knowledge-base.inspector.noResults": "No results",+ "builtins.lobe-knowledge-base.inspector.noScope": "No enabled library",+ "builtins.lobe-knowledge-base.render.noScope": "No enabled library is attached to this agent, so nothing was searched. Attach a library, or turn on an attached one, to let it search your files.","builtins.lobe-knowledge-base.title": "Library","builtins.lobe-local-system.apiName.editFile": "Edit file","builtins.lobe-local-system.apiName.editLocalFile": "Edit file",diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.jsonindex ad12b2f9ba1..d0688e00dc2 100644--- a/locales/zh-CN/plugin.json+++ b/locales/zh-CN/plugin.json@@ -349,6 +349,8 @@"builtins.lobe-knowledge-base.apiName.searchKnowledgeBase": "搜索资源库","builtins.lobe-knowledge-base.inspector.andMoreFiles": "还有 {{count}} 个","builtins.lobe-knowledge-base.inspector.noResults": "无结果",+ "builtins.lobe-knowledge-base.inspector.noScope": "没有已启用的资源库",+ "builtins.lobe-knowledge-base.render.noScope": "该 Agent 没有已启用的资源库(未关联,或已关联但未启用),因此没有进行搜索。关联或启用资源库后即可搜索其中的文件。","builtins.lobe-knowledge-base.title": "资源库","builtins.lobe-local-system.apiName.editFile": "编辑文件","builtins.lobe-local-system.apiName.editLocalFile": "编辑文件",diff --git a/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/index.ts b/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/index.tsindex 85bf1c20c9d..5f43f2a5b2e 100644--- a/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/index.ts@@ -1,4 +1,9 @@-import { formatSearchResults, promptFileContents, promptNoSearchResults } from '@lobechat/prompts';+import {+ formatSearchResults,+ promptFileContents,+ promptNoKnowledgeBaseInScope,+ promptNoSearchResults,+} from '@lobechat/prompts';import { sliceReadWindow } from '@lobechat/prompts/textWindow';import type { BuiltinServerRuntimeOutput } from '@lobechat/types';@@ -82,6 +87,12 @@ interface RagService {documents?: any[];errors?: { bm25?: string; vector?: string };fileResults: any[];+ /**+ * Knowledge base IDs the search actually covered, when the service+ * resolves the scope itself (server runtime: agent + task project KBs).+ * An empty array means there was nothing to search.+ */+ searchedKnowledgeBaseIds?: string[];}>;}@@ -272,10 +283,35 @@ export class KnowledgeBaseExecutionRuntime {try {const { query, topK = 20 } = args;+ const noScopeOutput = (): BuiltinServerRuntimeOutput => ({+ content: promptNoKnowledgeBaseInScope(query),+ state: {+ chunks: [],+ documents: [],+ fileResults: [],+ scope: 'none',+ totalResults: 0,+ } satisfies SearchKnowledgeBaseState,+ success: true,+ });++ // Caller already resolved the scope (client: the agent's enabled KBs)+ // and it is empty — there is nothing to search, and reporting "no+ // relevant files" would make the model believe the content is missing.+ if (options?.knowledgeBaseIds && options.knowledgeBaseIds.length === 0) {+ return noScopeOutput();+ }+const result = await this.ragService.semanticSearchForChat({ knowledgeIds: options?.knowledgeBaseIds, query, topK },options?.signal,);++ // Service resolved the scope itself (server runtime) and found none.+ if (result.searchedKnowledgeBaseIds && result.searchedKnowledgeBaseIds.length === 0) {+ return noScopeOutput();+ }+const chunks = result.chunks ?? [];const fileResults = result.fileResults ?? [];const documents = result.documents ?? [];diff --git a/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/searchKnowledgeBase.test.ts b/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/searchKnowledgeBase.test.tsnew file mode 100644index 00000000000..256405ffe19--- /dev/null+++ b/packages/builtin-tool-knowledge-base/src/ExecutionRuntime/searchKnowledgeBase.test.ts@@ -0,0 +1,54 @@+import { describe, expect, it, vi } from 'vitest';++import { KnowledgeBaseExecutionRuntime } from './index';++const emptySearch = { chunks: [], documents: [], fileResults: [] };++const createRuntime = (searchResult: Record<string, unknown> = emptySearch) => {+ const ragService = {+ getFileContents: vi.fn(),+ semanticSearchForChat: vi.fn(async () => searchResult as any),+ };+ return { ragService, runtime: new KnowledgeBaseExecutionRuntime(ragService) };+};++describe('KnowledgeBaseExecutionRuntime.searchKnowledgeBase', () => {+ it('tells the model no knowledge base is attached when the service searched an empty scope', async () => {+ const { runtime } = createRuntime({ ...emptySearch, searchedKnowledgeBaseIds: [] });++ const result = await runtime.searchKnowledgeBase({ query: 'quarterly revenue forecast' });++ expect(result.success).toBe(true);+ expect(result.content).toContain('No enabled knowledge base is in this agent');+ expect(result.content).toContain('readKnowledge');+ expect(result.content).not.toContain('No relevant files found');+ // The card and chip read this to say "no library attached" instead of "No results".+ expect(result.state).toMatchObject({ scope: 'none', totalResults: 0 });+ });++ it('skips the search entirely when the caller passes an empty knowledge base scope', async () => {+ const { ragService, runtime } = createRuntime();++ const result = await runtime.searchKnowledgeBase(+ { query: 'quarterly revenue forecast' },+ { knowledgeBaseIds: [] },+ );++ expect(ragService.semanticSearchForChat).not.toHaveBeenCalled();+ expect(result.content).toContain('No enabled knowledge base is in this agent');+ expect(result.state).toMatchObject({ scope: 'none' });+ });++ it('keeps the "no relevant files" message when an attached knowledge base has no match', async () => {+ const { runtime } = createRuntime({ ...emptySearch, searchedKnowledgeBaseIds: ['kb_sales'] });++ const result = await runtime.searchKnowledgeBase(+ { query: 'quarterly revenue forecast' },+ { knowledgeBaseIds: ['kb_sales'] },+ );++ expect(result.content).toContain('No relevant files found');+ expect(result.content).not.toContain('No enabled knowledge base');+ expect(result.state).not.toHaveProperty('scope');+ });+});diff --git a/packages/builtin-tool-knowledge-base/src/client/Inspector/SearchKnowledgeBase/index.tsx b/packages/builtin-tool-knowledge-base/src/client/Inspector/SearchKnowledgeBase/index.tsxindex bbe85363e60..4ac8f46a941 100644--- a/packages/builtin-tool-knowledge-base/src/client/Inspector/SearchKnowledgeBase/index.tsx+++ b/packages/builtin-tool-knowledge-base/src/client/Inspector/SearchKnowledgeBase/index.tsx@@ -22,6 +22,8 @@ export const SearchKnowledgeBaseInspector = memo<const resultCount = pluginState?.resultCount ?? pluginState?.fileResults?.length ?? 0;const hasSettled = !!pluginState?.fileResults || typeof pluginState?.resultCount === 'number';const hasResults = resultCount > 0;+ // No library was in scope, so nothing was searched — not the same as 0 hits.+ const isUnscoped = pluginState?.scope === 'none';// During argument streamingif (isArgumentsStreaming) {@@ -62,7 +64,13 @@ export const SearchKnowledgeBaseInspector = memo<fontSize={12}style={{ marginInlineStart: 4 }}>- ({t('builtins.lobe-knowledge-base.inspector.noResults')})+ (+ {t(+ isUnscoped+ ? 'builtins.lobe-knowledge-base.inspector.noScope'+ : 'builtins.lobe-knowledge-base.inspector.noResults',+ )}+ )</Text>))}</span>diff --git a/packages/builtin-tool-knowledge-base/src/client/Render/SearchKnowledgeBase/index.tsx b/packages/builtin-tool-knowledge-base/src/client/Render/SearchKnowledgeBase/index.tsxindex 1c73d5d6b48..86343a4369b 100644--- a/packages/builtin-tool-knowledge-base/src/client/Render/SearchKnowledgeBase/index.tsx+++ b/packages/builtin-tool-knowledge-base/src/client/Render/SearchKnowledgeBase/index.tsx@@ -12,7 +12,13 @@ const SearchKnowledgeBase = memo<BuiltinRenderProps<SearchKnowledgeBaseArgs, SearchKnowledgeBaseState>>(({ pluginState }) => {const { t } = useTranslation('plugin');- const { fileResults } = pluginState || {};+ const { fileResults, scope } = pluginState || {};++ // Nothing was searched — saying "No results" would read as "the files don't+ // contain it" when the agent simply has no library to look in.+ if (scope === 'none') {+ return <Empty description={t('builtins.lobe-knowledge-base.render.noScope')} />;+ }if (!fileResults || fileResults.length === 0) {return <Empty description={t('builtins.lobe-knowledge-base.inspector.noResults')} />;diff --git a/packages/builtin-tool-knowledge-base/src/manifest.test.ts b/packages/builtin-tool-knowledge-base/src/manifest.test.tsnew file mode 100644index 00000000000..330b5765226--- /dev/null+++ b/packages/builtin-tool-knowledge-base/src/manifest.test.ts@@ -0,0 +1,20 @@+import { describe, expect, it } from 'vitest';++import { KnowledgeBaseManifest } from './manifest';+import { KnowledgeBaseApiName } from './types';++describe('KnowledgeBaseManifest', () => {+ it('only points searchKnowledgeBase recovery at other APIs when they are available', () => {+ // Graph-agent nodes can expose searchKnowledgeBase alone, so an unconditional+ // "read those with readKnowledge" sends empty-scope recovery into a missing tool.+ const search = KnowledgeBaseManifest.api.find(+ (api) => api.name === KnowledgeBaseApiName.searchKnowledgeBase,+ );++ expect(search?.description).toContain(+ 'if readKnowledge or viewKnowledgeBase is among your available tools',+ );+ expect(search?.description).toContain('otherwise tell the user');+ expect(search?.description).not.toContain('read those directly with readKnowledge');+ });+});diff --git a/packages/builtin-tool-knowledge-base/src/manifest.ts b/packages/builtin-tool-knowledge-base/src/manifest.tsindex b10a05acb98..b04d918d256 100644--- a/packages/builtin-tool-knowledge-base/src/manifest.ts+++ b/packages/builtin-tool-knowledge-base/src/manifest.ts@@ -97,7 +97,7 @@ export const KnowledgeBaseManifest: BuiltinToolManifest = {// ---- Search & Read ----{description:- 'Search the knowledge base. Returns two result types: (1) <files> — uploaded files matched by semantic vector search at chunk-level (file_* IDs); (2) <documents> — inline notes/documents matched by full-text BM25 search at document-level (docs_* IDs). Use this to discover relevant content first, then call readKnowledge with the returned IDs to get full content. Resolve pronouns/references to concrete entities for best vector recall.',+ 'Search the knowledge base. Returns two result types: (1) <files> — uploaded files matched by semantic vector search at chunk-level (file_* IDs); (2) <documents> — inline notes/documents matched by full-text BM25 search at document-level (docs_* IDs). Only covers knowledge bases attached to and enabled for this agent (plus, in task runs, knowledge bases enabled on the task project) — a knowledge base or document you just created is not searchable until it is attached and enabled; if readKnowledge or viewKnowledgeBase is among your available tools, read or browse those directly instead, otherwise tell the user. Use this to discover relevant content first, then call readKnowledge with the returned IDs to get full content. Resolve pronouns/references to concrete entities for best vector recall.',name: KnowledgeBaseApiName.searchKnowledgeBase,parameters: {properties: {diff --git a/packages/builtin-tool-knowledge-base/src/types.ts b/packages/builtin-tool-knowledge-base/src/types.tsindex 19fbf58eea4..1c4cbd34a52 100644--- a/packages/builtin-tool-knowledge-base/src/types.ts+++ b/packages/builtin-tool-knowledge-base/src/types.ts@@ -50,6 +50,11 @@ export interface SearchKnowledgeBaseState {* card hydrates the real hits when the row is expanded.*/resultCount?: number;+ /**+ * `'none'` when no knowledge base was in scope, so nothing was searched at+ * all — distinct from a search that ran and matched nothing.+ */+ scope?: 'none';totalResults: number;}diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.tsindex c0e795324cb..ce047740b23 100644--- a/packages/locales/src/default/plugin.ts+++ b/packages/locales/src/default/plugin.ts@@ -364,6 +364,9 @@ export default {'builtins.lobe-knowledge-base.apiName.searchKnowledgeBase': 'Search Library','builtins.lobe-knowledge-base.inspector.andMoreFiles': 'and {{count}} more','builtins.lobe-knowledge-base.inspector.noResults': 'No results',+ 'builtins.lobe-knowledge-base.inspector.noScope': 'No enabled library',+ 'builtins.lobe-knowledge-base.render.noScope':+ 'No enabled library is attached to this agent, so nothing was searched. Attach a library, or turn on an attached one, to let it search your files.','builtins.lobe-knowledge-base.title': 'Library','builtins.lobe-local-system.apiName.editFile': 'Edit file','builtins.lobe-local-system.apiName.getCommandOutput': 'Get command output',diff --git a/packages/prompts/src/prompts/knowledgeBaseQA/formatNoSearchResults.test.ts b/packages/prompts/src/prompts/knowledgeBaseQA/formatNoSearchResults.test.tsindex 76f15cf41e8..4d713207e21 100644--- a/packages/prompts/src/prompts/knowledgeBaseQA/formatNoSearchResults.test.ts+++ b/packages/prompts/src/prompts/knowledgeBaseQA/formatNoSearchResults.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { promptNoSearchResults } from './formatNoSearchResults';+import { promptNoKnowledgeBaseInScope, promptNoSearchResults } from './formatNoSearchResults';describe('promptNoSearchResults', () => {it('should format no search results with simple query', () => {@@ -23,3 +23,29 @@ describe('promptNoSearchResults', () => {expect(result).toMatchSnapshot();});});++describe('promptNoKnowledgeBaseInScope', () => {+ it('only suggests tools conditionally and always offers a user-facing fallback', () => {+ // Graph-agent nodes can expose searchKnowledgeBase without the other KB APIs.+ const prompt = promptNoKnowledgeBaseInScope('Project Falcon ships');++ expect(prompt).toContain('searchedKnowledgeBases="0"');+ expect(prompt).toContain('If readKnowledge is among your available tools');+ expect(prompt).toContain(+ 'If listKnowledgeBases / viewKnowledgeBase are among your available tools',+ );+ expect(prompt).toContain('Otherwise, tell the user nothing was searched');+ expect(prompt).not.toMatch(/<suggestion>Call /);+ });++ it('covers attached-but-disabled libraries instead of claiming none is attached', () => {+ // The scope resolver drops disabled libraries (`k.enabled`), so an empty scope can mean+ // "attached but turned off"; the remedy must include enabling it.+ const prompt = promptNoKnowledgeBaseInScope('Project Falcon ships');++ expect(prompt).toContain('No enabled knowledge base is in this agent');+ expect(prompt).toContain('the attached ones are turned off');+ expect(prompt).toContain('or turn on the one already attached');+ expect(prompt).not.toContain('No knowledge base is attached to this agent');+ });+});diff --git a/packages/prompts/src/prompts/knowledgeBaseQA/formatNoSearchResults.ts b/packages/prompts/src/prompts/knowledgeBaseQA/formatNoSearchResults.tsindex f225f5d80e1..dbd692a1d2e 100644--- a/packages/prompts/src/prompts/knowledgeBaseQA/formatNoSearchResults.ts+++ b/packages/prompts/src/prompts/knowledgeBaseQA/formatNoSearchResults.ts@@ -11,3 +11,21 @@ export const promptNoSearchResults = (query: string): string => {</suggestions></knowledge_base_search_results>`;};++/**+ * Format prompt when the search had no knowledge base to cover at all — the+ * agent (and its task's project, if any) has no enabled knowledge base: none+ * is attached, or every attached one is turned off. Distinct from `promptNoSearchResults` so the model does not read+ * an empty scope as "the content does not exist" (e.g. right after it created+ * a knowledge base and documents that are not attached to this agent).+ */+export const promptNoKnowledgeBaseInScope = (query: string): string => {+ return `<knowledge_base_search_results query="${query}" totalCount="0" searchedKnowledgeBases="0">+<instruction>No enabled knowledge base is in this agent's search scope (none is attached to the agent or its task's project, or the attached ones are turned off), so searchKnowledgeBase had nothing to search. This does NOT mean the content does not exist — knowledge bases and documents you created are not searchable until the knowledge base is attached to this agent and enabled.</instruction>+<suggestions>+<suggestion>If readKnowledge is among your available tools and you already know the document or file IDs (e.g. from createDocument), read them directly</suggestion>+<suggestion>If listKnowledgeBases / viewKnowledgeBase are among your available tools, browse a knowledge base's items there, then read the ones you need</suggestion>+<suggestion>Otherwise, tell the user nothing was searched and ask them to attach the knowledge base to this agent, or turn on the one already attached</suggestion>+</suggestions>+</knowledge_base_search_results>`;+};diff --git a/packages/prompts/src/prompts/knowledgeBaseQA/index.ts b/packages/prompts/src/prompts/knowledgeBaseQA/index.tsindex 562d8b432b7..a75f488da45 100644--- a/packages/prompts/src/prompts/knowledgeBaseQA/index.ts+++ b/packages/prompts/src/prompts/knowledgeBaseQA/index.ts@@ -6,7 +6,7 @@ import { userQueryPrompt } from './userQuery';export type { FileContent, FileContentRange } from './formatFileContents';export { promptFileContents, readKnowledgeContinuation } from './formatFileContents';-export { promptNoSearchResults } from './formatNoSearchResults';+export { promptNoKnowledgeBaseInScope, promptNoSearchResults } from './formatNoSearchResults';export type { FileSearchResult, FileSearchResultChunk } from './formatSearchResults';export { formatSearchResults } from './formatSearchResults';