🤯 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(page-editor): isolate page copilot context from global agent/document state (#15826)
Arvin Xu602e76841970
diff --git a/src/features/PageEditor/PageAgentProvider.test.tsx b/src/features/PageEditor/PageAgentProvider.test.tsxindex 294fa579bfc..f85fa3d54b4 100644--- a/src/features/PageEditor/PageAgentProvider.test.tsx+++ b/src/features/PageEditor/PageAgentProvider.test.tsx@@ -9,6 +9,7 @@ import { PageAgentProvider } from './PageAgentProvider';interface AgentState {activeAgentId?: string;+ heterogeneousAgentIds?: string[];pageAgentId: string;setActiveAgentId: (agentId: string) => void;useInitBuiltinAgent: (slug: string) => void;@@ -50,6 +51,10 @@ vi.mock('@/store/agent', () => ({}));vi.mock('@/store/agent/selectors', () => ({+ agentByIdSelectors: {+ isAgentHeterogeneousById: (agentId: string) => (state: AgentState) =>+ !!state.heterogeneousAgentIds?.includes(agentId),+ },builtinAgentSelectors: {pageAgentId: (state: AgentState) => state.pageAgentId,},@@ -65,8 +70,12 @@ vi.mock('@/store/chat', () => ({}));vi.mock('@/store/chat/utils/messageMapKey', () => ({- messageMapKey: (context: { agentId?: string; scope?: string; topicId?: string | null }) =>- `${context.scope}_${context.agentId}_${context.topicId ?? 'new'}`,+ messageMapKey: (context: {+ agentId?: string;+ documentId?: string | null;+ scope?: string;+ topicId?: string | null;+ }) => `${context.scope}_${context.agentId}_${context.topicId ?? context.documentId ?? 'new'}`,}));beforeEach(() => {@@ -157,4 +166,38 @@ describe('PageAgentProvider', () => {expect(chatState.switchTopic).toHaveBeenCalledTimes(2);});});++ it('falls back to the page agent when the active agent is heterogeneous', async () => {+ agentState.activeAgentId = 'claude-code';+ agentState.heterogeneousAgentIds = ['claude-code'];++ render(+ <PageAgentProvider>+ <div>child</div>+ </PageAgentProvider>,+ );++ await waitFor(() => {+ expect(conversationProviderSpy).toHaveBeenCalled();+ });++ const { context } = conversationProviderSpy.mock.calls.at(-1)![0];+ expect(context.agentId).toBe('page-agent');+ });++ it('injects the open document id into the conversation context', async () => {+ render(+ <PageAgentProvider pageId="doc-1">+ <div>child</div>+ </PageAgentProvider>,+ );++ await waitFor(() => {+ expect(conversationProviderSpy).toHaveBeenCalled();+ });++ const { context } = conversationProviderSpy.mock.calls.at(-1)![0];+ expect(context.documentId).toBe('doc-1');+ expect(context.scope).toBe('page');+ });});diff --git a/src/features/PageEditor/PageAgentProvider.tsx b/src/features/PageEditor/PageAgentProvider.tsxindex db5b2c19304..665705b53b3 100644--- a/src/features/PageEditor/PageAgentProvider.tsx+++ b/src/features/PageEditor/PageAgentProvider.tsx@@ -4,32 +4,48 @@ import type { ReactNode } from 'react';import { memo, useEffect, useMemo, useRef } from 'react';import Loading from '@/components/Loading/BrandTextLoading';+import type { ConversationContext } from '@/features/Conversation';import { ConversationProvider } from '@/features/Conversation';import { useOperationState } from '@/hooks/useOperationState';import { useAgentStore } from '@/store/agent';-import { builtinAgentSelectors } from '@/store/agent/selectors';+import { agentByIdSelectors, builtinAgentSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';-import type { MessageMapKeyInput } from '@/store/chat/utils/messageMapKey';import { messageMapKey } from '@/store/chat/utils/messageMapKey';interface PageAgentProviderProps {children: ReactNode;+ /**+ * The id of the document currently open in the editor. Injected into the+ * conversation context as `documentId` so page-scoped tool calls are bound to+ * this exact document instead of relying on the process-wide+ * `pageAgentRuntime` singleton, which can only represent one open document and+ * gets cleared/overwritten when switching tabs.+ */+ pageId?: string;}-export const PageAgentProvider = memo<PageAgentProviderProps>(({ children }) => {+export const PageAgentProvider = memo<PageAgentProviderProps>(({ children, pageId }) => {const useInitBuiltinAgent = useAgentStore((s) => s.useInitBuiltinAgent);const pageAgentId = useAgentStore(builtinAgentSelectors.pageAgentId);const activeTopicId = useChatStore((s) => s.activeTopicId);const activeAgentId = useAgentStore((s) => s.activeAgentId);+ const isActiveAgentHeterogeneous = useAgentStore((s) =>+ activeAgentId ? agentByIdSelectors.isAgentHeterogeneousById(activeAgentId)(s) : false,+ );const setActiveAgentId = useAgentStore((s) => s.setActiveAgentId);const syncedAgentIdRef = useRef<string | undefined>(undefined);useInitBuiltinAgent(BUILTIN_AGENT_SLUGS.pageAgent);// Build conversation context for page agent.- // Ignore chat-group ids in page scope and fall back to page agent.+ // Fall back to the page agent when the global active agent cannot drive a page+ // copilot: empty, a chat-group id, or a heterogeneous agent (e.g. Claude Code+ // / Codex). Heterogeneous agents run on external runtimes and must not leak+ // into the page-scoped conversation when navigating from their tab.const selectedAgentId =- !activeAgentId || isChatGroupSessionId(activeAgentId) ? pageAgentId : activeAgentId;+ !activeAgentId || isChatGroupSessionId(activeAgentId) || isActiveAgentHeterogeneous+ ? pageAgentId+ : activeAgentId;useEffect(() => {if (!selectedAgentId) return;@@ -58,13 +74,17 @@ export const PageAgentProvider = memo<PageAgentProviderProps>(({ children }) =>}}, [selectedAgentId, setActiveAgentId]);- const context = useMemo<MessageMapKeyInput>(+ const context = useMemo<ConversationContext>(() => ({agentId: selectedAgentId,+ // Bind the conversation to the open document directly so page-scoped tool+ // calls don't depend on the `pageAgentRuntime` singleton, which can't+ // represent multiple tabs/documents and is cleared on tab switch.+ documentId: pageId,scope: 'page',topicId: activeTopicId, // No topic initially, can be extended later}),- [selectedAgentId, activeTopicId],+ [selectedAgentId, activeTopicId, pageId],);// Get messages from ChatStore based on contextdiff --git a/src/features/PageEditor/PageEditor.tsx b/src/features/PageEditor/PageEditor.tsxindex cda654ae8c7..5c0660dfafd 100644--- a/src/features/PageEditor/PageEditor.tsx+++ b/src/features/PageEditor/PageEditor.tsx@@ -339,7 +339,7 @@ export const PageEditor: FC<PageEditorProps> = ({const deletePage = usePageStore((s) => s.deletePage);return (- <PageAgentProvider>+ <PageAgentProvider pageId={pageId}><EditorProvider><PageEditorProvideremoji={emoji}diff --git a/src/store/chat/utils/messageMapKey.test.ts b/src/store/chat/utils/messageMapKey.test.tsindex cb9ec1ef7fe..bf2f2f2d63b 100644--- a/src/store/chat/utils/messageMapKey.test.ts+++ b/src/store/chat/utils/messageMapKey.test.ts@@ -79,6 +79,34 @@ describe('messageMapKey', () => {});});+ describe('Page mode', () => {+ it('should bind a page conversation to the open document id', () => {+ const result = messageMapKey({ scope: 'page', agentId: 'agt_page', documentId: 'doc_aaa' });+ expect(result).toBe('page_agt_page_doc_aaa');+ });++ it('should isolate different documents sharing the same page agent', () => {+ const a = messageMapKey({ scope: 'page', agentId: 'agt_page', documentId: 'doc_aaa' });+ const b = messageMapKey({ scope: 'page', agentId: 'agt_page', documentId: 'doc_bbb' });+ expect(a).not.toBe(b);+ });++ it('should fall back to the new bucket when no document is open', () => {+ const result = messageMapKey({ scope: 'page', agentId: 'agt_page' });+ expect(result).toBe('page_agt_page_new');+ });++ it('should include topicId alongside documentId when a page topic exists', () => {+ const result = messageMapKey({+ scope: 'page',+ agentId: 'agt_page',+ documentId: 'doc_aaa',+ topicId: 'tpc_yyy',+ });+ expect(result).toBe('page_agt_page_tpc_yyy_doc_aaa');+ });+ });+describe('Group mode with groupId (auto-detected)', () => {it('should auto-detect group scope when groupId is present', () => {const result = messageMapKey({diff --git a/src/store/chat/utils/messageMapKey.ts b/src/store/chat/utils/messageMapKey.tsindex 38513054cd5..59a7957fa5d 100644--- a/src/store/chat/utils/messageMapKey.ts+++ b/src/store/chat/utils/messageMapKey.ts@@ -9,6 +9,13 @@ export interface MessageMapKeyInput {* Agent ID (maps to scopeId in main/thread scope)*/agentId: string;+ /**+ * Document ID (page scope only). The page agent is a single builtin agent+ * shared by every open document, so the documentId is what isolates one+ * document's conversation/operation bucket from another's. Maps to subTopicId+ * in page scope; ignored for every other scope.+ */+ documentId?: string;groupId?: string;/*** Whether this is a new/creating state (for optimistic updates)@@ -41,7 +48,22 @@ export interface MessageMapKeyInput {* Handles mapping from agentId/threadId to scopeId/subTopicId format*/const toMessageMapContext = (input: MessageMapKeyInput): MessageMapContext => {- const { agentId, topicId, threadId, isNew, groupId, subAgentId, scope } = input;+ const { agentId, topicId, threadId, isNew, groupId, subAgentId, scope, documentId } = input;++ // Page scope: the page agent is a single shared builtin agent, so the open+ // documentId is the only thing that distinguishes one document's conversation+ // from another's. Carry it as subTopicId so the generated key isolates each+ // document; without it, document A and B collapse into the same `page_<agent>`+ // bucket and leak history / queue behind each other's operations.+ if (scope === 'page' && documentId) {+ return {+ isNew,+ scope: 'page',+ scopeId: agentId,+ subTopicId: documentId,+ topicId,+ };+ }// If threadId is present and scope is explicitly 'thread', use thread scope// Thread scope takes priority when explicitly requested, even with groupId@@ -102,9 +124,11 @@ const generateKey = (context: MessageMapContext): string => {const base = `${scope}_${scopeId}`;- // Has subTopicId (existing thread or existing agent topic in group)+ // Has subTopicId (existing thread, agent topic in group, or page documentId).+ // Page scope is usually topicless, so guard against emitting a literal `null`+ // segment when topicId is absent.if (subTopicId) {- return `${base}_${topicId}_${subTopicId}`;+ return topicId ? `${base}_${topicId}_${subTopicId}` : `${base}_${subTopicId}`;}// New thread/sub-topic with parent topicId@@ -143,6 +167,8 @@ const generateKey = (context: MessageMapContext): string => {* - Group agent existing topic: `group_agent_grp_xxx_tpc_yyy_tpc_zzz`* - Task new topic: `task_agt_xxx_new`* - Task existing topic: `task_agt_xxx_tpc_yyy`+ * - Page document (topicless): `page_agt_xxx_doc_zzz`+ * - Page without an open document: `page_agt_xxx_new`** Auto-detection rules (when scope is not explicitly set):* - If threadId exists: scope = 'thread', subTopicId = threadId