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(page-agent): inject active documentId into context on send (#15610)

Arvin Xu5b4b50e050be
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts
index 442c7eb5fc7..02906c488fd 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts
@@ -12,6 +12,7 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { topicMapKey } from '@/store/chat/utils/topicMapKey';
import { getSessionStoreState } from '@/store/session';
import * as toolStoreModule from '@/store/tool';
+import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-page-agent';
import { useChatStore } from '../../../../store';
import { createMockAgentConfig, createMockMessage, TEST_CONTENT, TEST_IDS } from './fixtures';
@@ -689,6 +690,80 @@ describe('ConversationLifecycle actions', () => {
});
});
+ describe('page scope documentId injection', () => {
+ it('injects the active page documentId into the gateway context when scope is page', async () => {
+ const { result } = renderHook(() => useChatStore());
+
+ const getCurrentDocIdSpy = vi
+ .spyOn(pageAgentRuntime, 'getCurrentDocId')
+ .mockReturnValue('doc-page-1');
+
+ const executeGatewayAgentSpy = vi.fn().mockResolvedValue({
+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ operationId: 'op-1',
+ userMessageId: TEST_IDS.USER_MESSAGE_ID,
+ });
+
+ act(() => {
+ useChatStore.setState({
+ executeGatewayAgent: executeGatewayAgentSpy,
+ isGatewayModeEnabled: () => true,
+ });
+ });
+
+ await act(async () => {
+ await result.current.sendMessage({
+ message: TEST_CONTENT.USER_MESSAGE,
+ context: {
+ agentId: TEST_IDS.SESSION_ID,
+ scope: 'page',
+ threadId: null,
+ topicId: null,
+ },
+ });
+ });
+
+ expect(getCurrentDocIdSpy).toHaveBeenCalled();
+ expect(executeGatewayAgentSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ context: expect.objectContaining({ documentId: 'doc-page-1', scope: 'page' }),
+ }),
+ );
+ });
+
+ it('does not inject documentId for non-page scope conversations', async () => {
+ const { result } = renderHook(() => useChatStore());
+
+ vi.spyOn(pageAgentRuntime, 'getCurrentDocId').mockReturnValue('doc-page-1');
+
+ const executeGatewayAgentSpy = vi.fn().mockResolvedValue({
+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ operationId: 'op-1',
+ userMessageId: TEST_IDS.USER_MESSAGE_ID,
+ });
+
+ act(() => {
+ useChatStore.setState({
+ executeGatewayAgent: executeGatewayAgentSpy,
+ isGatewayModeEnabled: () => true,
+ });
+ });
+
+ await act(async () => {
+ await result.current.sendMessage({
+ message: TEST_CONTENT.USER_MESSAGE,
+ context: createTestContext(),
+ });
+ });
+
+ expect(executeGatewayAgentSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ context: expect.not.objectContaining({ documentId: expect.anything() }),
+ }),
+ );
+ });
+ });
+
describe('group chat supervisor metadata', () => {
it('should pass isSupervisor metadata when agentId matches supervisorAgentId', async () => {
const { result } = renderHook(() => useChatStore());
diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
index 74ae502bf24..0fab4f9d1d7 100644
--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
@@ -57,6 +57,7 @@ import {
import { getElectronStoreState } from '@/store/electron';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
+import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-page-agent';
import { type StoreSetter } from '@/store/types';
import { useUserMemoryStore } from '@/store/userMemory';
import { markdownToTxt } from '@/utils/markdownToTxt';
@@ -320,12 +321,30 @@ export class ConversationLifecycleActionImpl {
const hasMentionedAgents =
!context.groupId && !directMentionRoute && mentionedAgents.length > 0;
+ // Page-scoped conversations: the page editor runtime tracks the currently
+ // open document. Inject its id at send time so the agent-runtime context
+ // (and downstream server-side PageAgent tool calls, which only receive that
+ // context) is scoped to the open document. Without this the server runtime
+ // throws "received a tool call without documentId in context".
+ //
+ // This fallback is only authoritative when the active page's editor is
+ // mounted (StoreUpdater has called setCurrentDocId for it). Callers that
+ // create a document and send before that editor mounts (e.g. sendAsWrite)
+ // MUST pass the new documentId in context explicitly β€” the `!context.documentId`
+ // guard preserves it, so the singleton (still bound to the previous page) is
+ // not consulted and a stale id is never injected.
+ const activePageDocumentId =
+ context.scope === 'page' && !context.documentId
+ ? pageAgentRuntime.getCurrentDocId()
+ : undefined;
+
const operationContext = {
...context,
...(isCreatingNewThread && { threadId: undefined }),
// Only set isSupervisor for actual group supervisors β€” NOT for @agent mentions.
// isSupervisor triggers group-specific UI rendering (SupervisorMessage with group avatars).
...(isGroupSupervisor && { isSupervisor: true }),
+ ...(activePageDocumentId ? { documentId: activePageDocumentId } : {}),
};
const fileIdList = files?.map((f) => f.id);
diff --git a/src/store/home/slices/homeInput/action.test.ts b/src/store/home/slices/homeInput/action.test.ts
index 252f45f9cb6..a7fb85451a1 100644
--- a/src/store/home/slices/homeInput/action.test.ts
+++ b/src/store/home/slices/homeInput/action.test.ts
@@ -16,6 +16,7 @@ const toggleRightPanelMock = vi.hoisted(() => vi.fn());
const setChatPanelExpandedMock = vi.hoisted(() => vi.fn());
const createGroupMock = vi.hoisted(() => vi.fn());
const loadGroupsMock = vi.hoisted(() => vi.fn());
+const createDocumentMock = vi.hoisted(() => vi.fn());
const agentState = vi.hoisted(() => ({
agentConfigMap: {
@@ -27,10 +28,12 @@ const agentState = vi.hoisted(() => ({
agentMap: {
agentBuilder: {},
groupAgentBuilder: {},
+ pageAgent: {},
},
builtinAgentIdMap: {
'agent-builder': 'agentBuilder',
'group-agent-builder': 'groupAgentBuilder',
+ 'page-agent': 'pageAgent',
},
createAgent: createAgentMock,
inboxAgentId: 'inbox',
@@ -42,6 +45,13 @@ vi.mock('@lobechat/builtin-agents', () => ({
BUILTIN_AGENT_SLUGS: {
agentBuilder: 'agent-builder',
groupAgentBuilder: 'group-agent-builder',
+ pageAgent: 'page-agent',
+ },
+}));
+
+vi.mock('@/services/document', () => ({
+ documentService: {
+ createDocument: createDocumentMock,
},
}));
@@ -127,6 +137,7 @@ describe('HomeInputActionImpl', () => {
id: 'group-new',
},
});
+ createDocumentMock.mockResolvedValue({ id: 'doc-new' });
});
describe('sendAsAgent', () => {
@@ -163,4 +174,23 @@ describe('HomeInputActionImpl', () => {
);
});
});
+
+ describe('sendAsWrite', () => {
+ it('passes the freshly created document id through the page context', async () => {
+ const action = createAction();
+
+ await action.sendAsWrite({ message: 'write me a doc' });
+
+ expect(createDocumentMock).toHaveBeenCalled();
+ expect(navigateMock).toHaveBeenCalledWith('/page/doc-new');
+ // The new editor has not mounted yet, so the doc id must travel in context
+ // explicitly rather than relying on the page editor runtime singleton.
+ expect(sendMessageMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ context: { agentId: 'pageAgent', documentId: 'doc-new', scope: 'page' },
+ message: 'write me a doc',
+ }),
+ );
+ });
+ });
});
diff --git a/src/store/home/slices/homeInput/action.ts b/src/store/home/slices/homeInput/action.ts
index b5fa4083280..66648a90900 100644
--- a/src/store/home/slices/homeInput/action.ts
+++ b/src/store/home/slices/homeInput/action.ts
@@ -245,7 +245,11 @@ export class HomeInputActionImpl {
const { sendMessage } = useChatStore.getState();
await sendMessage({
- context: { agentId: pageAgentId, scope: 'page' },
+ // Pass the freshly created document id explicitly. The new PageEditor
+ // has not mounted yet, so the page editor runtime singleton may still
+ // be bound to the previously open document β€” relying on its fallback
+ // here would scope server-side PageAgent tools to the wrong document.
+ context: { agentId: pageAgentId, documentId: newDoc.id, scope: 'page' },
editorData,
message,
});