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(agentDocuments): should fetch passively for agent documents (#13508)

Neko71df4aa473c4
diff --git a/src/features/Conversation/ChatList/index.tsx b/src/features/Conversation/ChatList/index.tsx
index b5f7fd3489a..482dadead90 100644
--- a/src/features/Conversation/ChatList/index.tsx
+++ b/src/features/Conversation/ChatList/index.tsx
@@ -3,8 +3,10 @@
import { type ReactNode } from 'react';
import { memo, useCallback } from 'react';
+import { useFetchAgentDocuments } from '@/hooks/useFetchAgentDocuments';
import { useFetchTopicMemories } from '@/hooks/useFetchMemoryForTopic';
import { useFetchNotebookDocuments } from '@/hooks/useFetchNotebookDocuments';
+import { useChatStore } from '@/store/chat';
import { useUserStore } from '@/store/user';
import { settingsSelectors } from '@/store/user/selectors';
@@ -42,12 +44,14 @@ const ChatList = memo<ChatListProps>(({ disableActionsBar, welcome, itemContent
dataSelectors.skipFetch(s),
s.useFetchMessages,
]);
+ const activeAgentId = useChatStore((s) => s.activeAgentId);
useFetchMessages(context, skipFetch);
// Skip fetching notebook and memories for share pages (they require authentication)
const isSharePage = !!context.topicShareId;
// Fetch notebook documents when topic is selected (skip for share pages)
+ useFetchAgentDocuments(isSharePage ? undefined : activeAgentId);
useFetchNotebookDocuments(isSharePage ? undefined : context.topicId!);
useFetchTopicMemories(enableUserMemories && !isSharePage ? context.topicId : undefined);
diff --git a/src/hooks/useFetchAgentDocuments.ts b/src/hooks/useFetchAgentDocuments.ts
new file mode 100644
index 00000000000..f63c4cd5cfd
--- /dev/null
+++ b/src/hooks/useFetchAgentDocuments.ts
@@ -0,0 +1,7 @@
+import { useAgentStore } from '@/store/agent';
+
+export const useFetchAgentDocuments = (agentId?: string | null) => {
+ const useFetchAgentDocuments = useAgentStore((s) => s.useFetchAgentDocuments);
+
+ useFetchAgentDocuments(agentId);
+};
diff --git a/src/services/agentDocument.test.ts b/src/services/agentDocument.test.ts
new file mode 100644
index 00000000000..8b1b2b1512f
--- /dev/null
+++ b/src/services/agentDocument.test.ts
@@ -0,0 +1,162 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { mutate } from '@/libs/swr';
+
+import {
+ agentDocumentService,
+ mapAgentDocumentsToContext,
+ resolveAgentDocumentsContext,
+} from './agentDocument';
+
+const { queryMock } = vi.hoisted(() => ({
+ queryMock: vi.fn(),
+}));
+
+vi.mock('@/libs/swr', () => ({
+ mutate: vi.fn(),
+}));
+
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: {
+ agentDocument: {
+ copyDocument: { mutate: queryMock },
+ createDocument: { mutate: queryMock },
+ editDocument: { mutate: queryMock },
+ getDocuments: { query: queryMock },
+ getTemplates: { query: queryMock },
+ initializeFromTemplate: { mutate: queryMock },
+ listDocuments: { query: queryMock },
+ readDocument: { query: queryMock },
+ readDocumentByFilename: { query: queryMock },
+ removeDocument: { mutate: queryMock },
+ renameDocument: { mutate: queryMock },
+ updateLoadRule: { mutate: queryMock },
+ upsertDocumentByFilename: { mutate: queryMock },
+ },
+ },
+}));
+
+describe('AgentDocumentService', () => {
+ beforeEach(() => {
+ queryMock.mockResolvedValue({ ok: true });
+ vi.mocked(mutate).mockClear();
+ queryMock.mockClear();
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('should revalidate agent documents after createDocument', async () => {
+ await agentDocumentService.createDocument({
+ agentId: 'agent-1',
+ content: 'content',
+ title: 'title',
+ });
+
+ expect(mutate).toHaveBeenCalledWith(['agent-documents', 'agent-1']);
+ });
+
+ it('should revalidate agent documents after removeDocument', async () => {
+ await agentDocumentService.removeDocument({
+ agentId: 'agent-1',
+ id: 'doc-1',
+ });
+
+ expect(mutate).toHaveBeenCalledWith(['agent-documents', 'agent-1']);
+ });
+
+ it('should revalidate agent documents after updateLoadRule', async () => {
+ await agentDocumentService.updateLoadRule({
+ agentId: 'agent-1',
+ id: 'doc-1',
+ rule: {},
+ });
+
+ expect(mutate).toHaveBeenCalledWith(['agent-documents', 'agent-1']);
+ });
+
+ it('should map fetched documents into context format', () => {
+ expect(
+ mapAgentDocumentsToContext([
+ {
+ content: 'Target agent setup',
+ filename: 'setup.md',
+ id: 'doc-1',
+ loadRules: [],
+ policy: null,
+ policyLoadFormat: null,
+ policyLoadPosition: null,
+ templateId: null,
+ title: 'Setup',
+ },
+ ] as any),
+ ).toEqual([
+ {
+ content: 'Target agent setup',
+ filename: 'setup.md',
+ id: 'doc-1',
+ loadPosition: undefined,
+ loadRules: [],
+ policyId: null,
+ policyLoadFormat: undefined,
+ title: 'Setup',
+ },
+ ]);
+ });
+
+ it('should fetch target agent documents when cache is missing', async () => {
+ queryMock.mockResolvedValueOnce([
+ {
+ content: 'Target agent setup',
+ filename: 'setup.md',
+ id: 'doc-1',
+ loadRules: [],
+ policy: null,
+ policyLoadFormat: null,
+ policyLoadPosition: null,
+ templateId: null,
+ title: 'Setup',
+ },
+ ]);
+
+ await expect(
+ resolveAgentDocumentsContext({
+ agentId: 'target-agent',
+ }),
+ ).resolves.toEqual([
+ {
+ content: 'Target agent setup',
+ filename: 'setup.md',
+ id: 'doc-1',
+ loadPosition: undefined,
+ loadRules: [],
+ policyId: null,
+ policyLoadFormat: undefined,
+ title: 'Setup',
+ },
+ ]);
+
+ expect(queryMock).toHaveBeenCalledWith({ agentId: 'target-agent' });
+ });
+
+ it('should reuse cached agent documents without refetching', async () => {
+ const cachedDocuments = [
+ {
+ content: 'cached',
+ filename: 'cached.md',
+ id: 'cached-doc',
+ title: 'Cached',
+ },
+ ];
+
+ await expect(
+ resolveAgentDocumentsContext({
+ agentId: 'target-agent',
+ cachedDocuments,
+ }),
+ ).resolves.toBe(cachedDocuments);
+
+ expect(queryMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/services/agentDocument.ts b/src/services/agentDocument.ts
index e302fa93263..ebde0e76888 100644
--- a/src/services/agentDocument.ts
+++ b/src/services/agentDocument.ts
@@ -1,7 +1,34 @@
import type { DocumentLoadFormat, DocumentLoadRule } from '@lobechat/agent-templates';
+import {
+ AGENT_DOCUMENT_INJECTION_POSITIONS,
+ type AgentContextDocument,
+} from '@lobechat/context-engine';
+import { mutate } from '@/libs/swr';
import { lambdaClient } from '@/libs/trpc/client';
+export const agentDocumentSWRKeys = {
+ documents: (agentId: string) => ['agent-documents', agentId] as const,
+};
+
+const VALID_DOCUMENT_POSITIONS = new Set<AgentContextDocument['loadPosition']>(
+ AGENT_DOCUMENT_INJECTION_POSITIONS,
+);
+
+export const normalizeAgentDocumentPosition = (
+ position: string | null | undefined,
+): AgentContextDocument['loadPosition'] | undefined => {
+ if (!position) return undefined;
+
+ return VALID_DOCUMENT_POSITIONS.has(position as AgentContextDocument['loadPosition'])
+ ? (position as AgentContextDocument['loadPosition'])
+ : undefined;
+};
+
+const revalidateAgentDocuments = async (agentId: string) => {
+ await mutate(agentDocumentSWRKeys.documents(agentId));
+};
+
class AgentDocumentService {
getTemplates = async () => {
return lambdaClient.agentDocument.getTemplates.query();
@@ -12,7 +39,10 @@ class AgentDocumentService {
};
initializeFromTemplate = async (params: { agentId: string; templateSet: string }) => {
- return lambdaClient.agentDocument.initializeFromTemplate.mutate(params);
+ const result = await lambdaClient.agentDocument.initializeFromTemplate.mutate(params);
+ await revalidateAgentDocuments(params.agentId);
+
+ return result;
};
listDocuments = async (params: { agentId: string }) => {
@@ -28,11 +58,17 @@ class AgentDocumentService {
content: string;
filename: string;
}) => {
- return lambdaClient.agentDocument.upsertDocumentByFilename.mutate(params);
+ const result = await lambdaClient.agentDocument.upsertDocumentByFilename.mutate(params);
+ await revalidateAgentDocuments(params.agentId);
+
+ return result;
};
createDocument = async (params: { agentId: string; content: string; title: string }) => {
- return lambdaClient.agentDocument.createDocument.mutate(params);
+ const result = await lambdaClient.agentDocument.createDocument.mutate(params);
+ await revalidateAgentDocuments(params.agentId);
+
+ return result;
};
readDocument = async (params: { agentId: string; id: string }) => {
@@ -40,19 +76,31 @@ class AgentDocumentService {
};
editDocument = async (params: { agentId: string; content: string; id: string }) => {
- return lambdaClient.agentDocument.editDocument.mutate(params);
+ const result = await lambdaClient.agentDocument.editDocument.mutate(params);
+ await revalidateAgentDocuments(params.agentId);
+
+ return result;
};
removeDocument = async (params: { agentId: string; id: string }) => {
- return lambdaClient.agentDocument.removeDocument.mutate(params);
+ const result = await lambdaClient.agentDocument.removeDocument.mutate(params);
+ await revalidateAgentDocuments(params.agentId);
+
+ return result;
};
copyDocument = async (params: { agentId: string; id: string; newTitle?: string }) => {
- return lambdaClient.agentDocument.copyDocument.mutate(params);
+ const result = await lambdaClient.agentDocument.copyDocument.mutate(params);
+ await revalidateAgentDocuments(params.agentId);
+
+ return result;
};
renameDocument = async (params: { agentId: string; id: string; newTitle: string }) => {
- return lambdaClient.agentDocument.renameDocument.mutate(params);
+ const result = await lambdaClient.agentDocument.renameDocument.mutate(params);
+ await revalidateAgentDocuments(params.agentId);
+
+ return result;
};
updateLoadRule = async (params: {
@@ -72,8 +120,41 @@ class AgentDocumentService {
};
};
}) => {
- return lambdaClient.agentDocument.updateLoadRule.mutate(params);
+ const result = await lambdaClient.agentDocument.updateLoadRule.mutate(params);
+ await revalidateAgentDocuments(params.agentId);
+
+ return result;
};
}
+export const mapAgentDocumentsToContext = (
+ documents: Awaited<ReturnType<AgentDocumentService['getDocuments']>>,
+): AgentContextDocument[] =>
+ documents.map((doc) => ({
+ content: doc.content,
+ filename: doc.filename,
+ id: doc.id,
+ loadPosition: normalizeAgentDocumentPosition(
+ doc.policy?.context?.position || doc.policyLoadPosition,
+ ),
+ loadRules: doc.loadRules,
+ policyId: doc.templateId,
+ policyLoadFormat: doc.policy?.context?.policyLoadFormat || doc.policyLoadFormat || undefined,
+ title: doc.title,
+ }));
+
+export const resolveAgentDocumentsContext = async (params: {
+ agentId?: string;
+ cachedDocuments?: AgentContextDocument[];
+}) => {
+ const { agentId, cachedDocuments } = params;
+
+ if (cachedDocuments !== undefined) return cachedDocuments;
+ if (!agentId) return undefined;
+
+ const documents = await agentDocumentService.getDocuments({ agentId });
+
+ return mapAgentDocumentsToContext(documents);
+};
+
export const agentDocumentService = new AgentDocumentService();
diff --git a/src/services/agentRuntime/__tests__/client.test.ts b/src/services/agentRuntime/__tests__/client.test.ts
index 94dc36352d7..996884b5f03 100644
--- a/src/services/agentRuntime/__tests__/client.test.ts
+++ b/src/services/agentRuntime/__tests__/client.test.ts
@@ -39,6 +39,7 @@ describe('AgentRuntimeClient', () => {
const operationId = 'agent_1758302563222_abc';
const events: any[] = [];
let connectCalled = false;
+ // eslint-disable-next-line unused-imports/no-unused-vars
let disconnectCalled = false;
// Capture the callbacks passed to fetchEventSource
@@ -159,7 +160,7 @@ describe('AgentRuntimeClient', () => {
onEvent: (event) => {
events.push(event);
},
- onError: (error) => {
+ onError: () => {
errorOccurred = true;
},
});
diff --git a/src/services/agentRuntime/__tests__/index.test.ts b/src/services/agentRuntime/__tests__/index.test.ts
new file mode 100644
index 00000000000..bed4cac6b2c
--- /dev/null
+++ b/src/services/agentRuntime/__tests__/index.test.ts
@@ -0,0 +1,107 @@
+import { type UIChatMessage } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { agentRuntimeService } from '../index';
+
+const {
+ contextEngineeringMock,
+ createOperationMutateMock,
+ createAgentToolsEngineMock,
+ getAgentStoreStateMock,
+} = vi.hoisted(() => ({
+ contextEngineeringMock: vi.fn(),
+ createAgentToolsEngineMock: vi.fn(),
+ createOperationMutateMock: vi.fn(),
+ getAgentStoreStateMock: vi.fn(),
+}));
+
+vi.mock('@/helpers/toolEngineering', () => ({
+ createAgentToolsEngine: createAgentToolsEngineMock,
+}));
+
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: {
+ aiAgent: {
+ createOperation: {
+ mutate: createOperationMutateMock,
+ },
+ getOperationStatus: {
+ query: vi.fn(),
+ },
+ processHumanIntervention: {
+ mutate: vi.fn(),
+ },
+ },
+ },
+}));
+
+vi.mock('@/services/chat/mecha', () => ({
+ contextEngineering: contextEngineeringMock,
+}));
+
+vi.mock('@/store/agent', () => ({
+ getAgentStoreState: getAgentStoreStateMock,
+}));
+
+vi.mock('@/store/agent/selectors', () => ({
+ agentChatConfigSelectors: {
+ currentChatConfig: vi.fn(() => ({ inputTemplate: 'input-template' })),
+ enableHistoryCount: vi.fn(() => true),
+ historyCount: vi.fn(() => 3),
+ isAgentEnableSearch: vi.fn(() => false),
+ },
+ agentSelectors: {
+ currentAgentConfig: vi.fn(() => ({
+ model: 'gpt-4o',
+ plugins: ['plugin-1'],
+ provider: 'openai',
+ systemRole: 'system-role',
+ })),
+ getAgentDocumentsById: vi.fn(() => () => undefined),
+ },
+}));
+
+describe('AgentRuntimeService', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+
+ createAgentToolsEngineMock.mockReturnValue({
+ generateToolsDetailed: vi.fn(() => ({
+ enabledToolIds: ['plugin-1'],
+ tools: [{ function: { name: 'plugin-1____api-1' }, type: 'function' }],
+ })),
+ getEnabledPluginManifests: vi.fn(() => new Map([['plugin-1', { identifier: 'plugin-1' }]])),
+ });
+
+ contextEngineeringMock.mockResolvedValue([{ content: 'compiled', role: 'system' }]);
+ createOperationMutateMock.mockResolvedValue({ operationId: 'op-1' });
+ });
+
+ it('should keep agent documents optional when hydration returns undefined', async () => {
+ const ensureAgentDocuments = vi.fn().mockResolvedValue(undefined);
+
+ getAgentStoreStateMock.mockReturnValue({
+ activeAgentId: 'agent-1',
+ ensureAgentDocuments,
+ });
+
+ const messages = [{ content: 'Hello', role: 'user' }] as UIChatMessage[];
+
+ await agentRuntimeService.createOperation({
+ messages,
+ userMessageId: 'msg-1',
+ });
+
+ expect(ensureAgentDocuments).toHaveBeenCalledWith('agent-1');
+ expect(contextEngineeringMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentDocuments: undefined,
+ }),
+ );
+ expect(createOperationMutateMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ messages: [{ content: 'compiled', role: 'system' }],
+ }),
+ );
+ });
+});
diff --git a/src/services/agentRuntime/index.ts b/src/services/agentRuntime/index.ts
index 9b3bc8f6744..4a37381b3e8 100644
--- a/src/services/agentRuntime/index.ts
+++ b/src/services/agentRuntime/index.ts
@@ -1,3 +1,4 @@
+import type { AgentContextDocument } from '@lobechat/context-engine';
import { type UIChatMessage } from '@lobechat/types';
import { createAgentToolsEngine } from '@/helpers/toolEngineering';
@@ -24,6 +25,17 @@ class AgentRuntimeService {
const agentStoreState = getAgentStoreState();
const agentConfig = agentSelectors.currentAgentConfig(agentStoreState);
const chatConfig = agentChatConfigSelectors.currentChatConfig(agentStoreState);
+ let agentDocuments: AgentContextDocument[] | undefined = agentSelectors.getAgentDocumentsById(
+ agentStoreState.activeAgentId || '',
+ )(agentStoreState);
+
+ if (agentStoreState.activeAgentId && agentDocuments === undefined) {
+ try {
+ agentDocuments = await agentStoreState.ensureAgentDocuments(agentStoreState.activeAgentId);
+ } catch (error) {
+ console.error('[AgentRuntimeService] Failed to ensure agent documents:', error);
+ }
+ }
const modelRuntimeConfig = {
model: agentConfig.model,
@@ -43,6 +55,7 @@ class AgentRuntimeService {
// Apply context engineering with preprocessing configuration
const llmMessages = await contextEngineering({
+ agentDocuments,
agentId: agentStoreState.activeAgentId,
enableHistoryCount: agentChatConfigSelectors.enableHistoryCount(agentStoreState),
// historyCount is number of history messages; add 1 for current user message
diff --git a/src/services/chat/chat.test.ts b/src/services/chat/chat.test.ts
index 790ee4cfdc4..2ddac410bb8 100644
--- a/src/services/chat/chat.test.ts
+++ b/src/services/chat/chat.test.ts
@@ -1,3 +1,4 @@
+import { AgentBuilderIdentifier } from '@lobechat/builtin-tool-agent-builder';
import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';
import { type ChatStreamPayload, type LobeTool, type UIChatMessage } from '@lobechat/types';
import { ChatErrorType } from '@lobechat/types';
@@ -6,8 +7,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { DEFAULT_AGENT_CONFIG } from '@/const/settings';
import * as toolEngineeringModule from '@/helpers/toolEngineering';
+import { agentDocumentService } from '@/services/agentDocument';
+import { useAgentStore } from '@/store/agent';
import { agentSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
import { aiModelSelectors } from '@/store/aiInfra';
+import { useChatStore } from '@/store/chat';
import { useToolStore } from '@/store/tool';
import { settingsSelectors } from '@/store/user/selectors';
@@ -106,10 +110,15 @@ beforeEach(async () => {
vi.spyOn(agentSelectors, 'getAgentConfigById').mockReturnValue(
() => ({ plugins: [], systemRole: '' }) as any,
);
+ vi.spyOn(agentSelectors, 'getAgentDocumentsById').mockImplementation(
+ (agentId: string) => (state) => state.agentDocumentsMap[agentId],
+ );
vi.spyOn(agentSelectors, 'getAgentSlugById').mockReturnValue(() => undefined);
vi.spyOn(chatConfigByIdSelectors, 'getChatConfigById').mockReturnValue(
() => ({ searchMode: 'off' }) as any,
);
+ useAgentStore.setState({ activeAgentId: undefined, agentDocumentsMap: {} } as any);
+ useChatStore.setState({ activeAgentId: undefined } as any);
});
// mock auth
@@ -1427,6 +1436,88 @@ describe('ChatService', () => {
);
});
});
+
+ describe('agent documents readiness', () => {
+ it('should ensure agent documents before assistant generation when cache is empty', async () => {
+ const contextEngineeringSpy = vi
+ .spyOn(mechaModule, 'contextEngineering')
+ .mockResolvedValue([]);
+ vi.spyOn(chatService, 'getChatCompletion').mockResolvedValue(new Response(''));
+ vi.spyOn(agentDocumentService, 'getDocuments').mockResolvedValue([
+ {
+ content: 'Project setup steps',
+ filename: 'setup.md',
+ id: 'doc-1',
+ loadRules: [],
+ policy: null,
+ policyLoadFormat: null,
+ policyLoadPosition: null,
+ templateId: null,
+ title: 'Setup',
+ },
+ ] as any);
+
+ await chatService.createAssistantMessage({
+ agentId: 'agent-1',
+ messages: [{ content: 'Hello', role: 'user' }] as UIChatMessage[],
+ resolvedAgentConfig: createMockResolvedConfig(),
+ });
+
+ expect(agentDocumentService.getDocuments).toHaveBeenCalledWith({ agentId: 'agent-1' });
+ expect(contextEngineeringSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentDocuments: [
+ expect.objectContaining({
+ content: 'Project setup steps',
+ filename: 'setup.md',
+ id: 'doc-1',
+ }),
+ ],
+ }),
+ );
+ });
+
+ it('should resolve agent builder documents from the edited agent', async () => {
+ const contextEngineeringSpy = vi
+ .spyOn(mechaModule, 'contextEngineering')
+ .mockResolvedValue([]);
+ vi.spyOn(chatService, 'getChatCompletion').mockResolvedValue(new Response(''));
+ vi.spyOn(agentDocumentService, 'getDocuments').mockResolvedValue([
+ {
+ content: 'Edited agent setup',
+ filename: 'builder-target.md',
+ id: 'doc-1',
+ loadRules: [],
+ policy: null,
+ policyLoadFormat: null,
+ policyLoadPosition: null,
+ templateId: null,
+ title: 'Builder Target',
+ },
+ ] as any);
+
+ useChatStore.setState({ activeAgentId: 'edited-agent' } as any);
+
+ await chatService.createAssistantMessage({
+ agentId: 'builder-agent',
+ messages: [{ content: 'Hello', role: 'user' }] as UIChatMessage[],
+ resolvedAgentConfig: createMockResolvedConfig({
+ enabledToolIds: [AgentBuilderIdentifier],
+ }),
+ });
+
+ expect(agentDocumentService.getDocuments).toHaveBeenCalledWith({ agentId: 'edited-agent' });
+ expect(contextEngineeringSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentDocuments: [
+ expect.objectContaining({
+ content: 'Edited agent setup',
+ }),
+ ],
+ }),
+ );
+ });
+ });
});
describe('getChatCompletion', () => {
@@ -1537,6 +1628,22 @@ describe('ChatService', () => {
});
describe('fetchPresetTaskResult', () => {
+ it('should not wait for agent documents on preset task chains', async () => {
+ vi.spyOn(chatService, 'getChatCompletion').mockResolvedValue(new Response(''));
+ vi.spyOn(agentDocumentService, 'getDocuments').mockResolvedValue([]);
+
+ await chatService.fetchPresetTaskResult({
+ abortController: new AbortController(),
+ params: {
+ messages: [{ content: 'Hello', role: 'user' as const }],
+ model: 'gpt-4',
+ provider: 'openai',
+ },
+ });
+
+ expect(agentDocumentService.getDocuments).not.toHaveBeenCalled();
+ });
+
it('should handle successful chat completion response', async () => {
// Mock getChatCompletion to simulate successful completion
const getChatCompletionSpy = vi
diff --git a/src/services/chat/index.ts b/src/services/chat/index.ts
index 0f35f2be5a7..c6fe5998fda 100644
--- a/src/services/chat/index.ts
+++ b/src/services/chat/index.ts
@@ -96,6 +96,17 @@ interface CreateAssistantMessageStream extends FetchSSEOptions {
}
class ChatService {
+ private resolveAgentDocumentsTargetId = (
+ targetAgentId: string,
+ enabledToolIds: string[] = [],
+ ): string | undefined => {
+ if (enabledToolIds.includes(AgentBuilderIdentifier)) {
+ return getChatStoreState().activeAgentId || targetAgentId || undefined;
+ }
+
+ return targetAgentId || undefined;
+ };
+
createAssistantMessage = async (
{
messages,
@@ -152,7 +163,20 @@ class ChatService {
// Note: When Agent Builder is active, we need to get the context of the agent being edited,
// which is stored in chatStore.activeAgentId, not the targetAgentId (which is the Agent Builder itself)
const isAgentBuilderEnabled = enabledToolIds.includes(AgentBuilderIdentifier);
+ const documentsAgentId = this.resolveAgentDocumentsTargetId(targetAgentId, enabledToolIds);
let agentBuilderContext;
+ let agentDocuments = documentsAgentId
+ ? agentSelectors.getAgentDocumentsById(documentsAgentId)(getAgentStoreState())
+ : undefined;
+
+ if (documentsAgentId && agentDocuments === undefined) {
+ try {
+ agentDocuments = await getAgentStoreState().ensureAgentDocuments(documentsAgentId);
+ } catch (error) {
+ // Agent documents are optional on the client; keep generation working if hydration fails.
+ console.error('[ChatService] Failed to ensure agent documents:', error);
+ }
+ }
if (isAgentBuilderEnabled) {
const activeAgentId = getChatStoreState().activeAgentId || '';
@@ -239,6 +263,7 @@ class ChatService {
// Note: agentConfig.systemRole is already resolved by resolveAgentConfig for builtin agents
const modelMessages = await contextEngineering({
agentBuilderContext,
+ agentDocuments,
agentId: targetAgentId,
// Use raw chatConfig values, not selectors with business logic that may force false
enableHistoryCount: chatConfig.enableHistoryCount,
diff --git a/src/services/chat/mecha/contextEngineering.test.ts b/src/services/chat/mecha/contextEngineering.test.ts
index 2982ee8a5be..eae5aa7b5cb 100644
--- a/src/services/chat/mecha/contextEngineering.test.ts
+++ b/src/services/chat/mecha/contextEngineering.test.ts
@@ -2,6 +2,7 @@ import { type UIChatMessage } from '@lobechat/types';
import { afterEach, describe, expect, it, vi } from 'vitest';
import * as isCanUseFCModule from '@/helpers/isCanUseFC';
+import { agentDocumentService } from '@/services/agentDocument';
import * as helpers from '../helper';
import { contextEngineering } from './contextEngineering';
@@ -17,6 +18,12 @@ vi.mock('@/helpers/parserPlaceholder', () => ({
},
}));
+vi.mock('@/services/agentDocument', () => ({
+ agentDocumentService: {
+ getDocuments: vi.fn(),
+ },
+}));
+
// 默认设置 isServerMode 为 false
let isServerMode = false;
@@ -48,6 +55,55 @@ const getCurrentDateContent = () => {
};
describe('contextEngineering', () => {
+ it('should not fetch agent documents implicitly when agentId is provided', async () => {
+ const messages = [{ content: 'Hello', role: 'user' }] as UIChatMessage[];
+
+ await contextEngineering({
+ agentId: 'agent-1',
+ messages,
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ expect(agentDocumentService.getDocuments).not.toHaveBeenCalled();
+ });
+
+ it('should use provided agent documents without fetching', async () => {
+ const messages = [{ content: 'Summarize the setup', role: 'user' }] as UIChatMessage[];
+
+ const output = await contextEngineering({
+ agentDocuments: [
+ {
+ content: 'Project setup steps',
+ filename: 'setup.md',
+ id: 'doc-1',
+ title: 'Setup',
+ },
+ ],
+ agentId: 'agent-1',
+ messages,
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ expect(agentDocumentService.getDocuments).not.toHaveBeenCalled();
+ const documentsMessage = output.find(
+ (message) =>
+ message.role === 'system' &&
+ typeof message.content === 'string' &&
+ message.content.includes('<documents>'),
+ );
+
+ expect(documentsMessage).toEqual({
+ content: expect.stringContaining('<documents>'),
+ role: 'system',
+ });
+ expect(documentsMessage).toEqual({
+ content: expect.stringContaining('setup.md'),
+ role: 'system',
+ });
+ });
+
describe('handle with files content in server mode', () => {
it('should includes files', async () => {
isServerMode = true;
diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.ts
index ffa813caf29..df23cdccb5d 100644
--- a/src/services/chat/mecha/contextEngineering.ts
+++ b/src/services/chat/mecha/contextEngineering.ts
@@ -18,11 +18,7 @@ import type {
ToolDiscoveryConfig,
UserMemoryData,
} from '@lobechat/context-engine';
-import {
- AGENT_DOCUMENT_INJECTION_POSITIONS,
- MessagesEngine,
- resolveTopicReferences,
-} from '@lobechat/context-engine';
+import { MessagesEngine, resolveTopicReferences } from '@lobechat/context-engine';
import { historySummaryPrompt } from '@lobechat/prompts';
import type {
OpenAIChatMessage,
@@ -35,7 +31,6 @@ import debug from 'debug';
import { isCanUseFC } from '@/helpers/isCanUseFC';
import { VARIABLE_GENERATORS } from '@/helpers/parserPlaceholder';
import { lambdaClient } from '@/libs/trpc/client';
-import { agentDocumentService } from '@/services/agentDocument';
import { notebookService } from '@/services/notebook';
import { getAgentStoreState } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
@@ -59,22 +54,10 @@ import { stripActionTagsFromText } from './skillPreload';
const log = debug('context-engine:contextEngineering');
-const VALID_DOCUMENT_POSITIONS = new Set<AgentContextDocument['loadPosition']>(
- AGENT_DOCUMENT_INJECTION_POSITIONS,
-);
-
-const normalizeDocumentPosition = (
- position: string | null | undefined,
-): AgentContextDocument['loadPosition'] | undefined => {
- if (!position) return undefined;
- return VALID_DOCUMENT_POSITIONS.has(position as AgentContextDocument['loadPosition'])
- ? (position as AgentContextDocument['loadPosition'])
- : undefined;
-};
-
interface ContextEngineeringContext {
/** Agent Builder context for injecting current agent info */
agentBuilderContext?: AgentBuilderContext;
+ agentDocuments?: AgentContextDocument[];
/** The agent ID that will respond (for group context injection) */
agentId?: string;
enableHistoryCount?: boolean;
@@ -157,6 +140,7 @@ export const contextEngineering = async ({
historyCount,
historySummary,
agentBuilderContext,
+ agentDocuments,
agentId,
groupId,
initialContext,
@@ -224,7 +208,6 @@ export const contextEngineering = async ({
// Get agent store state (used for both group agent builder context and file/knowledge base)
const agentStoreState = getAgentStoreState();
- const resolvedAgentId = agentId || agentStoreState.activeAgentId;
// Build group agent builder context if Group Agent Builder is enabled
// Note: Uses activeGroupId from chatStore to get the group being edited
@@ -351,31 +334,6 @@ export const contextEngineering = async ({
.filter((kb) => kb.enabled)
.map((kb) => ({ description: kb.description, id: kb.id, name: kb.name }));
- let agentDocuments: AgentContextDocument[] | undefined;
-
- if (resolvedAgentId) {
- try {
- const documents = await agentDocumentService.getDocuments({ agentId: resolvedAgentId });
- agentDocuments = documents.map((doc) => ({
- content: doc.content,
- filename: doc.filename,
- id: doc.id,
- loadRules: doc.loadRules,
- policyLoadFormat: doc.policy?.context?.policyLoadFormat || doc.policyLoadFormat,
- loadPosition: normalizeDocumentPosition(
- doc.policy?.context?.position || doc.policyLoadPosition,
- ),
- policyId: doc.templateId,
- title: doc.title,
- }));
-
- log('agentDocuments resolved: %d', agentDocuments.length);
- } catch (error) {
- // Agent documents are optional context; failure should not block message processing.
- log('Failed to resolve agent documents for agent %s: %O', resolvedAgentId, error);
- }
- }
-
// Resolve user memories: topic memories and user persona are independent layers
// Both functions now read from cache only (no network requests) to avoid blocking sendMessage
let userMemoryData: UserMemoryData | undefined;
diff --git a/src/store/agent/selectors/selectors.ts b/src/store/agent/selectors/selectors.ts
index 03adf5f784e..4c61dff7fb6 100644
--- a/src/store/agent/selectors/selectors.ts
+++ b/src/store/agent/selectors/selectors.ts
@@ -262,6 +262,9 @@ const currentAgentWorkingDirectory = (s: AgentStoreState): string | undefined =>
const isCurrentAgentExternal = (s: AgentStoreState): boolean => !currentAgentData(s)?.virtual;
+const getAgentDocumentsById = (agentId: string) => (s: AgentStoreState) =>
+ s.agentDocumentsMap[agentId];
+
export const agentSelectors = {
currentAgentAvatar,
currentAgentBackgroundColor,
@@ -285,6 +288,7 @@ export const agentSelectors = {
currentKnowledgeIds,
displayableAgentPlugins,
getAgentConfigById,
+ getAgentDocumentsById,
getAgentMetaById,
getAgentSlugById,
hasEnabledKnowledge,
diff --git a/src/store/agent/slices/agent/action.test.ts b/src/store/agent/slices/agent/action.test.ts
index 339d987e614..14e45067959 100644
--- a/src/store/agent/slices/agent/action.test.ts
+++ b/src/store/agent/slices/agent/action.test.ts
@@ -3,6 +3,7 @@ import { act, renderHook, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { agentService } from '@/services/agent';
+import { agentDocumentService } from '@/services/agentDocument';
import { type LobeAgentConfig } from '@/types/agent';
import { withSWR } from '~test-utils';
@@ -21,6 +22,26 @@ vi.mock('@/services/agent', () => ({
},
}));
+vi.mock('@/services/agentDocument', () => ({
+ agentDocumentSWRKeys: {
+ documents: (agentId: string) => ['agent-documents', agentId] as const,
+ },
+ agentDocumentService: {
+ getDocuments: vi.fn(),
+ },
+ mapAgentDocumentsToContext: (documents: any[]) =>
+ documents.map((doc) => ({
+ content: doc.content,
+ filename: doc.filename,
+ id: doc.id,
+ loadPosition: undefined,
+ loadRules: doc.loadRules,
+ policyId: doc.templateId,
+ policyLoadFormat: undefined,
+ title: doc.title,
+ })),
+}));
+
// Mock sessionStore
vi.mock('@/store/session', () => ({
useSessionStore: {
@@ -46,6 +67,7 @@ beforeEach(() => {
agentMap: {},
builtinAgentIdMap: {},
updateAgentConfigSignal: undefined,
+ agentDocumentsMap: {},
updateAgentMetaSignal: undefined,
});
});
@@ -55,6 +77,43 @@ afterEach(() => {
});
describe('AgentSlice Actions', () => {
+ describe('useFetchAgentDocuments', () => {
+ it('should sync fetched agent documents into store cache', async () => {
+ vi.mocked(agentDocumentService.getDocuments).mockResolvedValue([
+ {
+ content: 'setup steps',
+ filename: 'setup.md',
+ id: 'doc-1',
+ loadRules: [],
+ policy: null,
+ policyLoadFormat: null,
+ policyLoadPosition: null,
+ templateId: null,
+ title: 'Setup',
+ },
+ ] as any);
+
+ const { result } = renderHook(() => useAgentStore(), { wrapper: withSWR });
+
+ renderHook(() => result.current.useFetchAgentDocuments('agent-1'), { wrapper: withSWR });
+
+ await waitFor(() => {
+ expect(result.current.agentDocumentsMap['agent-1']).toEqual([
+ {
+ content: 'setup steps',
+ filename: 'setup.md',
+ id: 'doc-1',
+ loadPosition: undefined,
+ loadRules: [],
+ policyId: null,
+ policyLoadFormat: undefined,
+ title: 'Setup',
+ },
+ ]);
+ });
+ });
+ });
+
describe('internal_dispatchAgentMap', () => {
it('should create new agent entry if not exists', () => {
const { result } = renderHook(() => useAgentStore());
diff --git a/src/store/agent/slices/agent/action.ts b/src/store/agent/slices/agent/action.ts
index d8a734730c6..c09e6e12cc5 100644
--- a/src/store/agent/slices/agent/action.ts
+++ b/src/store/agent/slices/agent/action.ts
@@ -1,27 +1,30 @@
+import { type AgentContextDocument } from '@lobechat/context-engine';
import { isChatGroupSessionId } from '@lobechat/types';
import { getSingletonAnalyticsOptional } from '@lobehub/analytics';
import isEqual from 'fast-deep-equal';
import { produce } from 'immer';
-import { type SWRResponse } from 'swr';
-import { type PartialDeep } from 'type-fest';
+import type { SWRResponse } from 'swr';
+import type { PartialDeep } from 'type-fest';
import { MESSAGE_CANCEL_FLAT } from '@/const/message';
-import { mutate, useClientDataSWR } from '@/libs/swr';
-import { type CreateAgentParams, type CreateAgentResult } from '@/services/agent';
+import { mutate, useClientDataSWR, useClientDataSWRWithSync } from '@/libs/swr';
+import type { CreateAgentParams, CreateAgentResult } from '@/services/agent';
import { agentService } from '@/services/agent';
-import { type StoreSetter } from '@/store/types';
+import {
+ agentDocumentService,
+ agentDocumentSWRKeys,
+ mapAgentDocumentsToContext,
+ resolveAgentDocumentsContext,
+} from '@/services/agentDocument';
+import type { StoreSetter } from '@/store/types';
import { getUserStoreState } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
-import {
- type LobeAgentChatConfig,
- type LobeAgentConfig,
- type RuntimeEnvConfig,
-} from '@/types/agent';
-import { type MetaData } from '@/types/meta';
+import type { LobeAgentChatConfig, LobeAgentConfig, RuntimeEnvConfig } from '@/types/agent';
+import type { MetaData } from '@/types/meta';
import { merge } from '@/utils/merge';
-import { type AgentStore } from '../../store';
-import { type AgentSliceState, type LoadingState, type SaveStatus } from './initialState';
+import type { AgentStore } from '../../store';
+import type { AgentSliceState, LoadingState, SaveStatus } from './initialState';
const FETCH_AGENT_CONFIG_KEY = 'FETCH_AGENT_CONFIG';
@@ -37,6 +40,7 @@ export const createAgentSlice = (set: Setter, get: () => AgentStore, _api?: unkn
export class AgentSliceActionImpl {
readonly #get: () => AgentStore;
readonly #set: Setter;
+ readonly #pendingAgentDocuments = new Map<string, Promise<AgentContextDocument[] | undefined>>();
constructor(set: Setter, get: () => AgentStore, _api?: unknown) {
void _api;
@@ -44,6 +48,19 @@ export class AgentSliceActionImpl {
this.#get = get;
}
+ #syncAgentDocuments = (agentId: string, documents: AgentContextDocument[]) => {
+ this.#set(
+ (state) => ({
+ agentDocumentsMap: {
+ ...state.agentDocumentsMap,
+ [agentId]: documents,
+ },
+ }),
+ false,
+ 'syncAgentDocuments',
+ );
+ };
+
appendStreamingSystemRole = (chunk: string): void => {
const currentContent = this.#get().streamingSystemRole || '';
this.#set({ streamingSystemRole: currentContent + chunk }, false, 'appendStreamingSystemRole');
@@ -252,6 +269,50 @@ export class AgentSliceActionImpl {
);
};
+ useFetchAgentDocuments = (agentId?: string | null): SWRResponse<AgentContextDocument[]> => {
+ return useClientDataSWRWithSync<AgentContextDocument[]>(
+ agentId ? agentDocumentSWRKeys.documents(agentId) : null,
+ async () =>
+ mapAgentDocumentsToContext(await agentDocumentService.getDocuments({ agentId: agentId! })),
+ {
+ onData: (data) => {
+ if (!agentId) return;
+
+ this.#syncAgentDocuments(agentId, data);
+ },
+ revalidateOnFocus: false,
+ },
+ );
+ };
+
+ ensureAgentDocuments = async (
+ agentId?: string | null,
+ ): Promise<AgentContextDocument[] | undefined> => {
+ if (!agentId) return undefined;
+
+ const cachedDocuments = this.#get().agentDocumentsMap[agentId];
+ if (cachedDocuments !== undefined) return cachedDocuments;
+
+ const pendingRequest = this.#pendingAgentDocuments.get(agentId);
+ if (pendingRequest) return pendingRequest;
+
+ const request = resolveAgentDocumentsContext({ agentId })
+ .then((documents) => {
+ if (documents) {
+ this.#syncAgentDocuments(agentId, documents);
+ }
+
+ return documents;
+ })
+ .finally(() => {
+ this.#pendingAgentDocuments.delete(agentId);
+ });
+
+ this.#pendingAgentDocuments.set(agentId, request);
+
+ return request;
+ };
+
internal_dispatchAgentMap = (id: string, config: PartialDeep<LobeAgentConfig>): void => {
const agentMap = produce(this.#get().agentMap, (draft) => {
if (!draft[id]) {
diff --git a/src/store/agent/slices/agent/initialState.ts b/src/store/agent/slices/agent/initialState.ts
index 3bf79334e84..817d2d67d60 100644
--- a/src/store/agent/slices/agent/initialState.ts
+++ b/src/store/agent/slices/agent/initialState.ts
@@ -1,4 +1,5 @@
-import { type PartialDeep } from 'type-fest';
+import type { AgentContextDocument } from '@lobechat/context-engine';
+import type { PartialDeep } from 'type-fest';
import { type AgentSettingsInstance } from '@/features/AgentSetting';
import { type AgentItem } from '@/types/agent';
@@ -9,6 +10,7 @@ export type SaveStatus = 'idle' | 'saving' | 'saved';
export interface AgentSliceState {
activeAgentId?: string;
+ agentDocumentsMap: Record<string, AgentContextDocument[]>;
agentMap: Record<string, PartialDeep<AgentItem>>;
agentSettingInstance?: AgentSettingsInstance | null;
/**
@@ -42,6 +44,7 @@ export interface AgentSliceState {
}
export const initialAgentSliceState: AgentSliceState = {
+ agentDocumentsMap: {},
agentMap: {},
isAgentPinned: false,
lastUpdatedTime: null,