π€― 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
β¨ feat(portal): embed thread chat in document preview portal (#15216)
Innei202f062a0d1c
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex ad14d1a9e9e..03c9d780fd4 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -5,6 +5,14 @@ import type { ChatTopic } from '../topic';* Application context for message storage*/export interface ExecAgentAppContext {+ /**+ * Agent document row id (`agent_documents.id`) for the document the user is+ * currently viewing. When supplied, the active document context is built+ * directly without a `listDocumentsForTopic` reverse lookup, so docs opened+ * outside the active topic (skills, web docs) still carry `agent_document_id`+ * for downstream tool calls.+ */+ agentDocumentId?: string | null;/** Optional default assignee candidate for task manager prompts */defaultTaskAssigneeAgentId?: string;/** Current document ID for page-scoped conversations */diff --git a/packages/types/src/conversation.ts b/packages/types/src/conversation.tsindex 1f56c983beb..3dbcf9a1b78 100644--- a/packages/types/src/conversation.ts+++ b/packages/types/src/conversation.ts@@ -119,6 +119,14 @@ export interface MessageMapContext {* ```*/export interface ConversationContext {+ /**+ * Agent document row id (`agent_documents.id`) that the user is currently+ * viewing. When set, callers can skip the `listDocumentsForTopic` reverse+ * lookup in `ActiveTopicDocumentContextInjector` and the `<document>` block+ * is guaranteed to carry `agent_document_id` for downstream tool calls+ * (`readDocument`, `modifyNodes`).+ */+ agentDocumentId?: string;agentId: string;/*** Optional default assignee candidate for task manager conversations.diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsxindex f9cb10769f8..fb39851abe7 100644--- a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx@@ -7,10 +7,8 @@ import type { ExplorerTreeNode } from '@/features/ExplorerTree';import DocumentExplorerTree from './DocumentExplorerTree';import type { AgentDocumentItem } from './types';-const { navigate, openDocument, useMatchMock } = vi.hoisted(() => ({- navigate: vi.fn(),+const { openDocument } = vi.hoisted(() => ({openDocument: vi.fn(),- useMatchMock: vi.fn(),}));const messageError = vi.hoisted(() => vi.fn());const messageSuccess = vi.hoisted(() => vi.fn());@@ -53,11 +51,6 @@ vi.mock('react-i18next', () => ({}),}));-vi.mock('react-router-dom', () => ({- useMatch: () => useMatchMock(),- useNavigate: () => navigate,-}));-vi.mock('@/store/chat', () => ({useChatStore: (selector: (state: Record<string, unknown>) => unknown) =>selector({ openDocument }),@@ -178,7 +171,6 @@ const createDocument = (overrides: Partial<AgentDocumentItem>): AgentDocumentItedescribe('DocumentExplorerTree', () => {beforeEach(() => {- navigate.mockReset();messageError.mockReset();messageSuccess.mockReset();messageWarning.mockReset();@@ -186,8 +178,6 @@ describe('DocumentExplorerTree', () => {openDocument.mockReset();removeDocumentMock.mockReset();removeDocumentMock.mockResolvedValue({ deleted: true, id: 'skill-bundle-row' });- useMatchMock.mockReset();- useMatchMock.mockReturnValue(null);});it('renders managed skill bundle as a folder with SKILL.md underneath', () => {@@ -270,7 +260,7 @@ describe('DocumentExplorerTree', () => {expect(openDocument).not.toHaveBeenCalled();fireEvent.click(screen.getByTestId('tree-node-button-skill-index-row'));- expect(openDocument).toHaveBeenCalledWith('skill-index-doc');+ expect(openDocument).toHaveBeenCalledWith('skill-index-doc', 'skill-index-row');});it('shows delete recovery action for a managed skill bundle without SKILL.md', async () => {diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsxindex 101f635ba0a..15771585f1b 100644--- a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.tsx@@ -4,7 +4,6 @@ import { Trash2Icon } from 'lucide-react';import type { CSSProperties } from 'react';import { memo, useCallback, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';-import { useMatch, useNavigate } from 'react-router-dom';import type { KeyedMutator } from 'swr';import type {@@ -21,7 +20,6 @@ import type { AgentDocumentItem } from './types';import { isOrphanSkillBundleItem } from './types';import { canDropDocument } from './utils/canDrop';-const PAGE_ROUTE_PATTERN = '/agent/:aid/:topicId/page/:docId?';const SKILL_INDEX_FILENAME = 'SKILL.md';const styles = createStaticStyles(({ css, cssVar }) => ({@@ -53,8 +51,6 @@ interface Props {const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, style }) => {const { t } = useTranslation(['chat', 'common']);- const navigate = useNavigate();- const pageMatch = useMatch(PAGE_ROUTE_PATTERN);const openDocument = useChatStore((s) => s.openDocument);const treeRef = useRef<ExplorerTreeHandle | null>(null);@@ -62,12 +58,7 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, style }) => {treeRef.current?.startRenaming(id);}, []);- const ops = useDocumentTreeOps({- agentId,- data,- mutate,- topicId: pageMatch?.params.topicId,- });+ const ops = useDocumentTreeOps({ agentId, data, mutate });const documents = useMemo(() => data.filter((doc) => doc.category !== 'web'), [data]);@@ -140,15 +131,9 @@ const DocumentExplorerTree = memo<Props>(({ agentId, data, mutate, style }) => {(node: ExplorerTreeNode<AgentDocumentItem>) => {const doc = node.data;if (!doc || node.isFolder) return;- if (pageMatch?.params.aid && pageMatch.params.topicId) {- navigate(- `/agent/${pageMatch.params.aid}/${pageMatch.params.topicId}/page/${doc.documentId}`,- );- return;- }- openDocument(doc.documentId);+ openDocument(doc.documentId, doc.id);},- [navigate, openDocument, pageMatch?.params.aid, pageMatch?.params.topicId],+ [openDocument],);const handleCommitRename = useCallback(diff --git a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.test.tsx b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.test.tsxindex 0ea7b2482e4..d0129de74f3 100644--- a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.test.tsx+++ b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.test.tsx@@ -134,7 +134,7 @@ describe('AgentSignalReceiptList', () => {fireEvent.click(screen.getByRole('button', { name: /GitHub PR review workflow/ }));- expect(mocks.openDocument).toHaveBeenCalledWith('document-1');+ expect(mocks.openDocument).toHaveBeenCalledWith('document-1', undefined);});it('renders receipts without openable targets as non-clickable status cards', () => {@@ -197,7 +197,7 @@ describe('AgentSignalReceiptList', () => {fireEvent.click(screen.getByText('GitHub PR review workflow'));- expect(mocks.openDocument).toHaveBeenCalledWith('document-1');+ expect(mocks.openDocument).toHaveBeenCalledWith('document-1', undefined);});it('opens skill receipt document refs while keeping the bundle target id for display metadata', () => {@@ -230,7 +230,7 @@ describe('AgentSignalReceiptList', () => {fireEvent.click(screen.getByRole('button', { name: /GitHub PR review workflow/ }));- expect(mocks.openDocument).toHaveBeenCalledWith('index-document-1');+ expect(mocks.openDocument).toHaveBeenCalledWith('index-document-1', 'index-agent-document-1');});it('navigates memory receipts to the memory surface', () => {diff --git a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsxindex 61955732a5e..129d3a231f0 100644--- a/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx+++ b/src/features/Conversation/ChatList/components/AgentSignalReceiptList.tsx@@ -15,7 +15,6 @@ import { useChatStore } from '@/store/chat';import type { AgentSignalReceiptView } from '../hooks/useAgentSignalReceipts';-const PAGE_ROUTE_PATTERN = /^\/agent\/([^/]+)\/([^/]+)\/page(?:\/[^/?#]+)?/;const MEMORY_ROUTE_BY_LAYER = {[LayersEnum.Activity]: { idParam: 'activityId', path: '/memory/activities' },[LayersEnum.Context]: { idParam: 'contextId', path: '/memory/contexts' },@@ -78,6 +77,10 @@ const AgentSignalReceiptItem = memo<AgentSignalReceiptItemProps>(({ receipt }) =const tooltip = `${fallbackTitle}: ${summary}`;const target = receipt.target;const documentId = target?.type === 'skill' ? (target.documentId ?? target.id) : undefined;+ const agentDocumentId =+ target?.type === 'skill' && typeof target.agentDocumentId === 'string'+ ? target.agentDocumentId+ : undefined;const memoryRoute = getMemoryRoute(target);const canOpen = Boolean(memoryRoute) || Boolean(documentId);const handleOpen = useCallback(() => {@@ -89,16 +92,8 @@ const AgentSignalReceiptItem = memo<AgentSignalReceiptItemProps>(({ receipt }) =if (target?.type !== 'skill') return;if (!documentId) return;- const pathname = globalThis.location?.pathname ?? '';- const pageMatch = PAGE_ROUTE_PATTERN.exec(pathname);-- if (pageMatch?.[1] && pageMatch[2]) {- navigate(`/agent/${pageMatch[1]}/${pageMatch[2]}/page/${documentId}`);- return;- }-- openDocument(documentId);- }, [documentId, memoryRoute, navigate, openDocument, target]);+ openDocument(documentId, agentDocumentId);+ }, [agentDocumentId, documentId, memoryRoute, navigate, openDocument, target]);return (<PortalResourceCarddiff --git a/src/features/Electron/titlebar/TabBar/storage.ts b/src/features/Electron/titlebar/TabBar/storage.tsindex 544bdb63ffe..b5a2e9de055 100644--- a/src/features/Electron/titlebar/TabBar/storage.ts+++ b/src/features/Electron/titlebar/TabBar/storage.ts@@ -34,12 +34,6 @@ const reconstructUrlFromV1 = (type: unknown, params: unknown): string | null =>case 'agent-topic': {return p.agentId && p.topicId ? `/agent/${p.agentId}/${p.topicId}` : null;}- case 'agent-topic-page': {- if (!p.agentId || !p.topicId) return null;- return p.docId- ? `/agent/${p.agentId}/${p.topicId}/page/${p.docId}`- : `/agent/${p.agentId}/${p.topicId}/page`;- }case 'group': {return p.groupId ? `/group/${p.groupId}` : null;}diff --git a/src/features/FloatingChatPanel/ChatBody.test.tsx b/src/features/FloatingChatPanel/ChatBody.test.tsxindex da1acbe8180..cb7002ffa14 100644--- a/src/features/FloatingChatPanel/ChatBody.test.tsx+++ b/src/features/FloatingChatPanel/ChatBody.test.tsx@@ -36,13 +36,10 @@ vi.mock('@lobehub/ui', () => ({}));vi.mock('@/features/Conversation', () => ({+ ChatInput: () => <div data-testid="floating-chat-input">chat input</div>,ChatList: () => <div data-testid="floating-chat-list">chat list</div>,}));-vi.mock('@/routes/(main)/agent/features/Conversation/MainChatInput', () => ({- default: () => <div data-testid="floating-chat-input">chat input</div>,-}));-describe('FloatingChatPanel ChatBody', () => {it('keeps the chat input after the list while leaving scroll ownership to the virtual list', () => {render(<ChatBody />);diff --git a/src/features/FloatingChatPanel/ChatBody.tsx b/src/features/FloatingChatPanel/ChatBody.tsxindex a38171818b3..9f8ac085145 100644--- a/src/features/FloatingChatPanel/ChatBody.tsx+++ b/src/features/FloatingChatPanel/ChatBody.tsx@@ -3,15 +3,8 @@import { Flexbox } from '@lobehub/ui';import { memo } from 'react';-import { ChatList } from '@/features/Conversation';-import MainChatInput from '@/routes/(main)/agent/features/Conversation/MainChatInput';+import { ChatInput, ChatList } from '@/features/Conversation';-/**- * Inner body of FloatingChatPanel.- *- * Assumes it is rendered inside a ConversationProvider. Pure layout β does not- * read the chat store directly.- */const ChatBody = memo(() => {return (<Flexbox@@ -33,7 +26,7 @@ const ChatBody = memo(() => {><ChatList /></Flexbox>- <MainChatInput />+ <ChatInput leftActions={['typo', 'stt']} rightActions={['contextWindow']} /></Flexbox>);});diff --git a/src/features/FloatingChatPanel/index.test.tsx b/src/features/FloatingChatPanel/index.test.tsxindex 559e73222d8..66cc8bea560 100644--- a/src/features/FloatingChatPanel/index.test.tsx+++ b/src/features/FloatingChatPanel/index.test.tsx@@ -55,14 +55,26 @@ vi.mock('@/hooks/useOperationState', () => ({useOperationState: () => undefined,}));-vi.mock('@/store/chat', () => ({- useChatStore: (selector: any) =>- selector({- dbMessagesMap: {},- replaceMessages: vi.fn(),- }),+const mockChatState = vi.hoisted(() => ({+ current: {+ dbMessagesMap: {} as Record<string, Array<{ id: string; threadId?: string | null }>>,+ portalThreadId: undefined as string | undefined,+ replaceMessages: vi.fn(),+ },}));+vi.mock('@/store/chat', () => {+ const useChatStore: any = (selector: any) => selector(mockChatState.current);+ useChatStore.getState = () => mockChatState.current;+ useChatStore.setState = (patch: any) => {+ Object.assign(+ mockChatState.current,+ typeof patch === 'function' ? patch(mockChatState.current) : patch,+ );+ };+ return { useChatStore };+});+vi.mock('@/store/chat/utils/messageMapKey', () => ({messageMapKey: (ctx: any) => `${ctx.agentId}:${ctx.topicId}:${ctx.threadId}`,}));@@ -70,37 +82,95 @@ vi.mock('@/store/chat/utils/messageMapKey', () => ({describe('FloatingChatPanel', () => {beforeEach(() => {__resetFloatingChatPanelRegistry();+ mockChatState.current.dbMessagesMap = {};+ mockChatState.current.portalThreadId = undefined;});- it('builds a main-scope context from agentId + topicId', () => {+ it('builds an ephemeral thread context by default from agentId + topicId', () => {const { getByTestId } = render(<FloatingChatPanel agentId="agent-1" topicId="topic-1" />);const ctx = JSON.parse(getByTestId('provider').dataset.context!);expect(ctx).toEqual({agentId: 'agent-1',- scope: 'main',+ isNew: true,+ scope: 'thread',threadId: null,topicId: 'topic-1',});});- it('switches scope to thread when threadId is provided', () => {+ it('drops isNew when an existing threadId is supplied', () => {const { getByTestId } = render(<FloatingChatPanel agentId="agent-1" threadId="thread-1" topicId="topic-1" />,);const ctx = JSON.parse(getByTestId('provider').dataset.context!);- expect(ctx.scope).toBe('thread');- expect(ctx.threadId).toBe('thread-1');+ expect(ctx).toEqual({+ agentId: 'agent-1',+ scope: 'thread',+ threadId: 'thread-1',+ topicId: 'topic-1',+ });+ });++ it('builds a main-scope context when scope is forced to main', () => {+ const { getByTestId } = render(+ <FloatingChatPanel agentId="agent-1" scope="main" topicId="topic-1" />,+ );+ const ctx = JSON.parse(getByTestId('provider').dataset.context!);+ expect(ctx).toEqual({+ agentId: 'agent-1',+ scope: 'main',+ threadId: null,+ topicId: 'topic-1',+ });+ });++ it('anchors a new thread on the topic last main message when one is present', () => {+ mockChatState.current.dbMessagesMap = {+ // mocked messageMapKey: `${agentId}:${topicId}:${threadId}`; main scope+ // omits threadId so it serializes as "agent-1:topic-1:undefined".+ 'agent-1:topic-1:undefined': [+ { id: 'msg-1', threadId: null },+ { id: 'msg-2', threadId: null },+ ],+ };++ const { getByTestId } = render(<FloatingChatPanel agentId="agent-1" topicId="topic-1" />);+ const ctx = JSON.parse(getByTestId('provider').dataset.context!);+ expect(ctx).toEqual({+ agentId: 'agent-1',+ isNew: true,+ scope: 'thread',+ sourceMessageId: 'msg-2',+ threadId: null,+ threadType: 'standalone',+ topicId: 'topic-1',+ });+ });++ it('skips thread-scoped rows when picking the source message anchor', () => {+ mockChatState.current.dbMessagesMap = {+ 'agent-1:topic-1:undefined': [+ { id: 'msg-1', threadId: null },+ { id: 'msg-2', threadId: null },+ { id: 'msg-3', threadId: 'thread-x' },+ ],+ };++ const { getByTestId } = render(<FloatingChatPanel agentId="agent-1" topicId="topic-1" />);+ const ctx = JSON.parse(getByTestId('provider').dataset.context!);+ expect(ctx.sourceMessageId).toBe('msg-2');});- it('supports page-scoped context with the active document id', () => {+ it('forwards documentId into the conversation context for document-aware injection', () => {const { getByTestId } = render(- <FloatingChatPanel agentId="agent-1" documentId="doc-1" scope="page" topicId="topic-1" />,+ <FloatingChatPanel agentId="agent-1" documentId="doc-1" topicId="topic-1" />,);const ctx = JSON.parse(getByTestId('provider').dataset.context!);expect(ctx).toEqual({agentId: 'agent-1',documentId: 'doc-1',- scope: 'page',+ isNew: true,+ scope: 'thread',threadId: null,topicId: 'topic-1',});diff --git a/src/features/FloatingChatPanel/index.tsx b/src/features/FloatingChatPanel/index.tsxindex c8eed25448f..d4aeb959b0f 100644--- a/src/features/FloatingChatPanel/index.tsx+++ b/src/features/FloatingChatPanel/index.tsx@@ -1,10 +1,10 @@'use client';-import { type UIChatMessage } from '@lobechat/types';+import { ThreadType, type UIChatMessage } from '@lobechat/types';import { FloatingSheet, type FloatingSheetProps } from '@lobehub/ui/base-ui';import { createStaticStyles } from 'antd-style';import type { ReactNode } from 'react';-import { memo, useMemo, useState } from 'react';+import { memo, useEffect, useMemo, useState } from 'react';import {type ActionsBarConfig,@@ -67,11 +67,22 @@ export interface FloatingChatPanelProps {*/actionsBar?: ActionsBarConfig;activeSnapPoint?: number;- /** Agent identifier. */+ /**+ * Agent document row id (`agent_documents.id`) for the document the user is+ * viewing. When supplied, the active document is injected with+ * `agent_document_id` so LLM tool calls (`readDocument` / `modifyNodes`) can+ * use it directly without a `listDocuments` reverse lookup.+ */+ agentDocumentId?: string;agentId: string;className?: string;dismissible?: boolean;- /** Current document identifier for page-scoped conversations. */+ /**+ * Active document id for the conversation context. Passed through so the+ * `ActiveTopicDocumentContextInjector` can tell the LLM which agent document+ * the user is currently viewing (e.g. when opened from a document preview+ * portal). Omit when no document is in focus.+ */documentId?: string;headerActions?: ReactNode;/**@@ -86,10 +97,16 @@ export interface FloatingChatPanelProps {onOpenChange?: (open: boolean) => void;onSnapPointChange?: (point: number) => void;open?: boolean;- /** Optional conversation scope override for non-thread contexts. */- scope?: 'main' | 'page';+ /**+ * Conversation scope. Defaults to `'thread'` for ephemeral side-chat usage.+ * When `'thread'` and `threadId` is absent, the context is marked `isNew`+ * so a fresh thread can be created on first send (caller must supply+ * `sourceMessageId` + `threadType` via `hooks` / context override if real+ * thread persistence is required).+ */+ scope?: 'main' | 'thread';snapPoints?: number[];- /** Optional thread identifier. When provided, scope becomes `'thread'`. */+ /** Opens an existing thread when set; otherwise the panel starts ephemeral. */threadId?: string | null;title?: ReactNode;/** Topic identifier. `null` means a new / unpersisted conversation. */@@ -101,17 +118,12 @@ export interface FloatingChatPanelProps {/*** FloatingChatPanel*- * A reusable floating conversation panel. Composes ChatList + MainChatInput inside- * a container shell. Consumers provide conversation coordinates via flat- * `agentId`/`topicId` props; the component builds its own `ConversationContext`- * internally.+ * Reusable floating conversation panel β composes `ChatList` + `ChatInput`+ * inside a `FloatingSheet`. Consumers provide conversation coordinates via+ * flat `agentId` / `topicId` / `threadId` props; the panel builds its own+ * `ConversationContext` internally.*- * @FIXME β οΈ Single instance per page. Mounting a second FloatingChatPanel while one is- * already mounted will throw. See `./guard.ts` for the rationale.- *- * @FIXME β οΈ Must not coexist with the main-page ConversationArea (both use MainChatInput,- * which writes to the global `useChatStore.mainInputEditor` slot). This is NOT- * enforced at runtime β consumer responsibility.+ * Single instance per page (see `./guard.ts`).*/const FloatingChatPanel = memo<FloatingChatPanelProps>(({@@ -119,7 +131,8 @@ const FloatingChatPanel = memo<FloatingChatPanelProps>(topicId,threadId = null,documentId,- scope,+ agentDocumentId,+ scope = 'thread',actionsBar,hooks,@@ -133,21 +146,88 @@ const FloatingChatPanel = memo<FloatingChatPanelProps>(}) => {useSingleInstanceGuard();+ // Adopt the global portal-thread state so streaming AI chunks (which the+ // lifecycle writes under the persisted `_<threadId>` key the moment the+ // server returns `createdThreadId`) become visible in this panel without+ // waiting for the post-stream `onAfterMessageCreate` hook. `lifecycle.ts`+ // calls `syncThreadInPortal` *before* stream chunks start arriving, so+ // subscribing here flips this panel's chatKey from `_new` to the persisted+ // thread in time to render the stream.+ const storePortalThreadId = useChatStore((s) => s.portalThreadId);+ const effectiveThreadId = threadId ?? storePortalThreadId ?? null;++ // Clear any stale `portalThreadId` left by a sibling portal session so a+ // fresh mount starts in `isNew` state. Body's `key` already remounts the+ // panel when `(agentId, topicId, documentId)` changes; this guards the+ // first paint of that fresh mount against a leftover thread id.+ useEffect(() => {+ if (threadId) return;+ if (useChatStore.getState().portalThreadId) {+ useChatStore.setState({ portalThreadId: undefined });+ }+ }, [threadId]);++ // Source message for `newThread`: the latest message of the topic's main+ // scope. Without this, `conversationLifecycle.ts:215` treats the send as a+ // plain topic message and never creates a thread row. Falls back to+ // ephemeral (no source) when the topic has no messages yet.+ const isCreatingNewThread = scope === 'thread' && !effectiveThreadId;+ const sourceMessageId = useChatStore((s) => {+ if (!isCreatingNewThread || !topicId) return undefined;+ const mainKey = messageMapKey({ agentId, topicId });+ const mainMessages = s.dbMessagesMap[mainKey];+ if (!mainMessages?.length) return undefined;+ // Anchor on the latest main-scope message (ignore thread-scoped rows).+ for (let i = mainMessages.length - 1; i >= 0; i -= 1) {+ const msg = mainMessages[i]!;+ if (!msg.threadId) return msg.id;+ }+ return undefined;+ });+const context = useMemo<ConversationContext>(() => ({agentId,- documentId,- scope: threadId ? 'thread' : (scope ?? 'main'),- threadId,+ ...(agentDocumentId ? { agentDocumentId } : {}),+ ...(documentId ? { documentId } : {}),+ ...(isCreatingNewThread && sourceMessageId+ ? { isNew: true, sourceMessageId, threadType: ThreadType.Standalone }+ : isCreatingNewThread+ ? { isNew: true }+ : {}),+ scope,+ threadId: effectiveThreadId,topicId,}),- [agentId, documentId, scope, topicId, threadId],+ [+ agentId,+ agentDocumentId,+ documentId,+ effectiveThreadId,+ isCreatingNewThread,+ scope,+ sourceMessageId,+ topicId,+ ],);const chatKey = useMemo(() => messageMapKey(context), [context]);- const messages = useChatStore((s) => s.dbMessagesMap[chatKey]);+ const rawMessages = useChatStore((s) => s.dbMessagesMap[chatKey]);const replaceMessages = useChatStore((s) => s.replaceMessages);+ // Document portal chat is an isolated doc-anchored side conversation β+ // never the continuation of the main topic. Pre-send (no thread yet) we+ // render empty regardless of whatever the `_new` thread key may hold from+ // a sibling flow; post-send we keep only the thread's own rows, since+ // `lifecycle.ts:replaceMessages(data.messages, { context: { threadId } })`+ // also dumps every main-topic parent message into the thread key for the+ // Portal/Thread parent β divider β thread layout we don't want here.+ const messages = useMemo(() => {+ if (!effectiveThreadId) return [];+ if (!rawMessages) return rawMessages;+ return rawMessages.filter((m) => m.threadId === effectiveThreadId);+ }, [rawMessages, effectiveThreadId]);+const operationState = useOperationState(context);const defaultActionsBar = useActionsBarConfig();const resolvedActionsBar = actionsBar ?? defaultActionsBar;@@ -166,7 +246,7 @@ const FloatingChatPanel = memo<FloatingChatPanelProps>(const chatFollowUpHooks = useChatFollowUp({agentChatConfig,conversationKey: chatKey,- threadId: threadId ?? undefined,+ threadId: effectiveThreadId ?? undefined,topicId: topicId ?? undefined,});@@ -212,11 +292,17 @@ const FloatingChatPanel = memo<FloatingChatPanelProps>(<FloatingSheet {...sheetProps}><div className={styles.body}><ConversationProvider+ // Doc-anchored side chat owns its messages via the external+ // `messages` prop (filtered from `dbMessagesMap` above). Letting+ // ConversationProvider fire its own `useFetchMessages` here would+ // pull the main-topic history from the server and drop it into+ // this panel β exactly the parent dump A-mode is meant to avoid.+ hasInitMessages+ skipFetchactionsBar={resolvedActionsBar}context={context}- hasInitMessages={!!messages}hooks={mergedHooks}- messages={messages}+ messages={messages ?? []}operationState={operationState}onMessagesChange={handleMessagesChange}>diff --git a/src/features/Portal/Document/Body.tsx b/src/features/Portal/Document/Body.tsxindex ee0247044da..30e2385518a 100644--- a/src/features/Portal/Document/Body.tsx+++ b/src/features/Portal/Document/Body.tsx@@ -7,6 +7,8 @@ import type { ChangeEvent } from 'react';import { memo, useCallback, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';+import FloatingChatPanel from '@/features/FloatingChatPanel';+import { useAgentStore } from '@/store/agent';import { useChatStore } from '@/store/chat';import { chatPortalSelectors } from '@/store/chat/selectors';import { useDocumentStore } from '@/store/document';@@ -192,6 +194,9 @@ const SkillFrontmatterBlock = memo<SkillFrontmatterBlockProps>(({ documentId, frconst DocumentBody = memo(() => {const documentId = useChatStore(chatPortalSelectors.portalDocumentId);+ const agentDocumentId = useChatStore(chatPortalSelectors.portalAgentDocumentId);+ const activeAgentId = useAgentStore((s) => s.activeAgentId);+ const activeTopicId = useChatStore((s) => s.activeTopicId);const [skillFrontmatter, contentFormat] = useDocumentStore((s) =>documentId? [s.documents[documentId]?.skillFrontmatter ?? '', s.documents[documentId]?.contentFormat]@@ -208,6 +213,15 @@ const DocumentBody = memo(() => {<EditorCanvas /></div><TodoList />+ {activeAgentId && (+ <FloatingChatPanel+ agentDocumentId={agentDocumentId}+ agentId={activeAgentId}+ documentId={documentId ?? undefined}+ key={`${activeAgentId}:${activeTopicId ?? 'none'}:${documentId ?? 'none'}`}+ topicId={activeTopicId ?? null}+ />+ )}</Flexbox>);});diff --git a/src/features/TopicCanvas/TitleSection.tsx b/src/features/TopicCanvas/TitleSection.tsxdeleted file mode 100644index 8df384fd35d..00000000000--- a/src/features/TopicCanvas/TitleSection.tsx+++ /dev/null@@ -1,61 +0,0 @@-'use client';--import { Flexbox, TextArea } from '@lobehub/ui';-import { memo, useState } from 'react';-import { useTranslation } from 'react-i18next';--import { truncateByWeightedLength } from '@/utils/textLength';--export interface TitleSectionProps {- onTitleChange?: (title: string) => void;- title?: string;-}--const TitleSection = memo<TitleSectionProps>(({ title: titleProp, onTitleChange }) => {- const { t } = useTranslation('file');-- const isTitleControlled = titleProp !== undefined;-- const [innerTitle, setInnerTitle] = useState('');-- const title = isTitleControlled ? titleProp : innerTitle;-- const setTitle = (value: string) => {- if (!isTitleControlled) setInnerTitle(value);- onTitleChange?.(value);- };-- return (- <Flexbox- gap={16}- paddingBlock={16}- style={{ cursor: 'default' }}- onClick={(e) => {- e.stopPropagation();- e.preventDefault();- }}- >- <TextArea- autoSize={{ minRows: 1 }}- placeholder={t('pageEditor.titlePlaceholder')}- value={title}- variant={'borderless'}- style={{- fontSize: 36,- fontWeight: 600,- padding: 0,- resize: 'none',- width: '100%',- }}- onChange={(e) => {- const truncated = truncateByWeightedLength(e.target.value, 100);- setTitle(truncated);- }}- />- </Flexbox>- );-});--TitleSection.displayName = 'TopicCanvasTitleSection';--export default TitleSection;diff --git a/src/features/TopicCanvas/index.test.tsx b/src/features/TopicCanvas/index.test.tsxdeleted file mode 100644index e77b3e79c94..00000000000--- a/src/features/TopicCanvas/index.test.tsx+++ /dev/null@@ -1,199 +0,0 @@-import { render, screen, waitFor } from '@testing-library/react';-import type * as React from 'react';-import type { ReactNode } from 'react';-import { afterEach, describe, expect, it, vi } from 'vitest';--import { documentHistoryQueueService } from '@/services/documentHistoryQueue';--import TopicCanvas from './index';--const mockEditor = {- dataTypeMap: new Map([- ['json', {}],- ['litexml', {}],- ['markdown', {}],- ]),- focus: vi.fn(),- getDocument: vi.fn((): unknown => ({ root: true })),- getLexicalEditor: vi.fn(() => ({})),-} as const;--const runtimeSpies = vi.hoisted(() => ({- setAfterMutateHandler: vi.fn(),- setBeforeMutateHandler: vi.fn(),- setCurrentDocId: vi.fn(),- setEditor: vi.fn(),- setTitleHandlers: vi.fn(),-}));--const useEditorMock = vi.hoisted(() => vi.fn(() => mockEditor));-const documentStoreMock = vi.hoisted(() => ({- commitEditorMutation: vi.fn(),-}));--vi.mock('@lobehub/editor/react', () => ({- EditorProvider: ({ children }: { children: ReactNode }) => <>{children}</>,- useEditor: useEditorMock,-}));--vi.mock('@lobehub/ui', () => ({- Flexbox: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (- <div {...props}>{children}</div>- ),- TextArea: ({- value,- onChange,- }: {- onChange?: (event: { target: { value: string } }) => void;- value?: string;- }) => (- <textarea- data-testid="topic-title-input"- value={value ?? ''}- onChange={(event) => onChange?.({ target: { value: event.target.value } })}- />- ),-}));--vi.mock('@/features/EditorCanvas', async () => {- const ReactActual = (await vi.importActual('react')) as typeof React;-- return {- DiffAllToolbar: ({ documentId, editor }: { documentId: string; editor: typeof mockEditor }) => (- <div- data-document-id={documentId}- data-editor={editor === mockEditor ? 'shared' : 'other'}- data-testid="diff-toolbar"- />- ),- EditorCanvas: ({- documentId,- editor,- onInit,- }: {- documentId?: string;- editor?: typeof mockEditor;- onInit?: (editor: typeof mockEditor) => void;- }) => {- ReactActual.useEffect(() => {- if (editor) onInit?.(editor);- }, [editor, onInit]);-- return (- <div- data-document-id={documentId ?? ''}- data-editor={editor === mockEditor ? 'shared' : 'other'}- data-testid="editor-canvas"- />- );- },- };-});--vi.mock('@/features/WideScreenContainer', () => ({- default: ({ children }: { children: ReactNode }) => <div>{children}</div>,-}));--vi.mock('@/hooks/useHotkeys', () => ({- useRegisterFilesHotkeys: vi.fn(),-}));--vi.mock('react-i18next', () => ({- useTranslation: () => ({ t: (key: string) => key }),-}));--vi.mock('@/services/documentHistoryQueue', () => ({- documentHistoryQueueService: {- enqueue: vi.fn(),- enqueueEditorSnapshot: vi.fn(),- flush: vi.fn(),- },-}));--vi.mock('@/store/document', () => ({- useDocumentStore: {- getState: () => documentStoreMock,- },-}));--vi.mock('@/store/tool/slices/builtin/executors/lobe-page-agent', () => ({- pageAgentRuntime: runtimeSpies,-}));--afterEach(() => {- vi.clearAllMocks();-});--describe('TopicCanvas', () => {- it('mounts diff toolbar and page-agent runtime bridge for the current document', async () => {- const { unmount } = render(- <TopicCanvas documentId="doc-1" title="Topic Title" onTitleChange={vi.fn()} />,- );-- expect(screen.getByTestId('editor-canvas')).toHaveAttribute('data-document-id', 'doc-1');- expect(screen.getByTestId('diff-toolbar')).toHaveAttribute('data-document-id', 'doc-1');- expect(screen.getByTestId('diff-toolbar')).toHaveAttribute('data-editor', 'shared');-- await waitFor(() => {- expect(runtimeSpies.setEditor).toHaveBeenCalledWith(mockEditor);- expect(runtimeSpies.setCurrentDocId).toHaveBeenCalledWith('doc-1');- expect(runtimeSpies.setTitleHandlers).toHaveBeenCalledTimes(1);- expect(runtimeSpies.setBeforeMutateHandler).toHaveBeenCalledWith(expect.any(Function));- expect(runtimeSpies.setAfterMutateHandler).toHaveBeenCalledWith(expect.any(Function));- });-- const beforeMutateHandler = runtimeSpies.setBeforeMutateHandler.mock.calls.find(- ([handler]) => typeof handler === 'function',- )?.[0] as ((context: { apiName: 'modifyNodes' }) => void) | undefined;- beforeMutateHandler?.({ apiName: 'modifyNodes' });-- expect(documentHistoryQueueService.enqueueEditorSnapshot).toHaveBeenCalledWith({- documentId: 'doc-1',- editor: mockEditor,- });-- const afterMutateHandler = runtimeSpies.setAfterMutateHandler.mock.calls.find(- ([handler]) => typeof handler === 'function',- )?.[0] as (() => Promise<void>) | undefined;- await afterMutateHandler?.();-- expect(documentStoreMock.commitEditorMutation).toHaveBeenCalledWith('doc-1', {- saveSource: 'llm_call',- });-- unmount();-- expect(runtimeSpies.setCurrentDocId).toHaveBeenLastCalledWith(undefined);- expect(runtimeSpies.setAfterMutateHandler).toHaveBeenLastCalledWith(null);- expect(runtimeSpies.setTitleHandlers).toHaveBeenLastCalledWith(null, null);- expect(runtimeSpies.setBeforeMutateHandler).toHaveBeenLastCalledWith(null);- expect(runtimeSpies.setEditor).toHaveBeenLastCalledWith(null);- });-- it('does not save a history snapshot for an empty editor state', async () => {- const { unmount } = render(- <TopicCanvas documentId="doc-1" title="Topic Title" onTitleChange={vi.fn()} />,- );-- await waitFor(() => {- expect(runtimeSpies.setBeforeMutateHandler).toHaveBeenCalledWith(expect.any(Function));- });-- const beforeMutateHandler = runtimeSpies.setBeforeMutateHandler.mock.calls.find(- ([handler]) => typeof handler === 'function',- )?.[0] as ((context: { apiName: 'modifyNodes' }) => void) | undefined;-- mockEditor.getDocument.mockReturnValueOnce({- root: {- children: [{ children: [], type: 'paragraph' }],- type: 'root',- },- });-- beforeMutateHandler?.({ apiName: 'modifyNodes' });-- expect(documentHistoryQueueService.enqueueEditorSnapshot).not.toHaveBeenCalled();-- unmount();- });-});diff --git a/src/features/TopicCanvas/index.tsx b/src/features/TopicCanvas/index.tsxdeleted file mode 100644index 9ddee11b427..00000000000--- a/src/features/TopicCanvas/index.tsx+++ /dev/null@@ -1,312 +0,0 @@-'use client';--import type { IEditor } from '@lobehub/editor';-import { EditorProvider, useEditor } from '@lobehub/editor/react';-import { Flexbox } from '@lobehub/ui';-import { cssVar } from 'antd-style';-import debug from 'debug';-import type { CSSProperties } from 'react';-import { memo, useCallback, useEffect, useRef, useState } from 'react';--import { DiffAllToolbar, EditorCanvas as SharedEditorCanvas } from '@/features/EditorCanvas';-import WideScreenContainer from '@/features/WideScreenContainer';-import { useRegisterFilesHotkeys } from '@/hooks/useHotkeys';-import { hasMeaningfulEditorContent } from '@/libs/editor/hasMeaningfulEditorContent';-import { documentHistoryQueueService } from '@/services/documentHistoryQueue';-import { useDocumentStore } from '@/store/document';-import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/lobe-page-agent';-import { StyleSheet } from '@/utils/styles';--import TitleSection, { type TitleSectionProps } from './TitleSection';--const log = debug('lobe-client:topic-canvas');--const styles = StyleSheet.create({- contentWrapper: {- display: 'flex',- position: 'relative',- },- editorContainer: {- minWidth: 0,- position: 'relative',- },- editorContent: {- paddingBlock: 16,- position: 'relative',- },- root: {- background: cssVar.colorBgContainer,- borderRadius: 12,- overflow: 'hidden',- },-});--export interface TopicCanvasProps extends TitleSectionProps {- agentId?: string;- documentId?: string;- placeholder?: string;- style?: CSSProperties;- topicId?: string | null;-}--type PageAgentEditor = NonNullable<Parameters<typeof pageAgentRuntime.setEditor>[0]>;--const PAGE_AGENT_DATA_SOURCE_TYPES = ['json', 'litexml', 'markdown'] as const;-const PAGE_AGENT_READY_RETRY_LIMIT = 30;-const PAGE_AGENT_READY_RETRY_INTERVAL = 16;--interface InspectableEditor extends IEditor {- dataTypeMap?: Map<string, unknown> | Record<string, unknown>;-}--const getEditorDataSourceTypes = (editor: InspectableEditor): string[] => {- const dataTypeMap = editor.dataTypeMap;-- if (!dataTypeMap) return [];-- if (dataTypeMap instanceof Map) {- return [...dataTypeMap.keys()].sort();- }-- return Object.keys(dataTypeMap).sort();-};--const getPageAgentEditorSnapshot = (editor: IEditor | undefined) => {- if (!editor) {- return {- dataSourceTypes: [],- hasLexicalEditor: false,- isReady: false,- };- }-- const dataSourceTypes = getEditorDataSourceTypes(editor as InspectableEditor);- const hasLexicalEditor = !!editor.getLexicalEditor?.();-- return {- dataSourceTypes,- hasLexicalEditor,- isReady:- hasLexicalEditor &&- PAGE_AGENT_DATA_SOURCE_TYPES.every((type) => dataSourceTypes.includes(type)),- };-};--const TopicCanvasPageAgentBridge = memo<- Pick<TopicCanvasProps, 'documentId' | 'onTitleChange' | 'title'> & {- editor: IEditor | undefined;- editorReady: boolean;- }->(({ documentId, editor, editorReady, onTitleChange, title }) => {- const pageAgentEditor = editor as unknown as PageAgentEditor | undefined;- const titleRef = useRef(title ?? '');- const onTitleChangeRef = useRef(onTitleChange);-- useEffect(() => {- titleRef.current = title ?? '';- }, [title]);-- useEffect(() => {- onTitleChangeRef.current = onTitleChange;- }, [onTitleChange]);-- useEffect(() => {- if (editorReady && pageAgentEditor) {- log('[TopicCanvas/PageAgentBridge] setEditor', {- dataSourceTypes: getPageAgentEditorSnapshot(editor).dataSourceTypes,- documentId,- editorReady,- hasLexicalEditor: !!pageAgentEditor.getLexicalEditor?.(),- });- pageAgentRuntime.setEditor(pageAgentEditor);- }-- return () => {- log('[TopicCanvas/PageAgentBridge] clearEditor', { documentId });- pageAgentRuntime.setEditor(null);- };- }, [documentId, editor, editorReady, pageAgentEditor]);-- useEffect(() => {- log('[TopicCanvas/PageAgentBridge] bindDocumentContext', {- dataSourceTypes: getPageAgentEditorSnapshot(editor).dataSourceTypes,- documentId,- hasEditor: !!editor,- });- pageAgentRuntime.setCurrentDocId(documentId);- pageAgentRuntime.setTitleHandlers(- (nextTitle) => {- titleRef.current = nextTitle;- onTitleChangeRef.current?.(nextTitle);- },- () => titleRef.current,- );- pageAgentRuntime.setBeforeMutateHandler(({ apiName }) => {- const editorData = editor?.getDocument('json');- const hasHistorySnapshot = hasMeaningfulEditorContent(editorData);-- log('[TopicCanvas/PageAgentBridge] beforeMutate', {- apiName,- dataSourceTypes: getPageAgentEditorSnapshot(editor).dataSourceTypes,- documentId,- hasEditor: !!editor,- hasHistorySnapshot,- });- if (!hasHistorySnapshot) {- return;- }-- documentHistoryQueueService.enqueueEditorSnapshot({ documentId, editor });- });- pageAgentRuntime.setAfterMutateHandler(async () => {- if (!documentId) return;-- await useDocumentStore- .getState()- .commitEditorMutation(documentId, { saveSource: 'llm_call' });- });-- return () => {- log('[TopicCanvas/PageAgentBridge] clearDocumentContext', { documentId });- pageAgentRuntime.setCurrentDocId(undefined);- pageAgentRuntime.setAfterMutateHandler(null);- pageAgentRuntime.setTitleHandlers(null, null);- pageAgentRuntime.setBeforeMutateHandler(null);- void documentHistoryQueueService.flush();- };- }, [documentId, editor]);-- return null;-});--TopicCanvasPageAgentBridge.displayName = 'TopicCanvasPageAgentBridge';--const TopicCanvasBody = memo<TopicCanvasProps>(- ({ placeholder, style, title, documentId, onTitleChange, topicId }) => {- const editor = useEditor();- const [editorReady, setEditorReady] = useState(false);- const readyTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);- const previousEditorContextRef = useRef<{ documentId?: string; editor?: IEditor } | undefined>(- undefined,- );-- useRegisterFilesHotkeys();-- useEffect(() => {- const previous = previousEditorContextRef.current;-- if (previous && (previous.documentId !== documentId || previous.editor !== editor)) {- setEditorReady(false);- if (readyTimerRef.current) clearTimeout(readyTimerRef.current);- }-- previousEditorContextRef.current = { documentId, editor };- }, [documentId, editor]);-- useEffect(() => {- return () => {- if (readyTimerRef.current) clearTimeout(readyTimerRef.current);- };- }, []);-- const handleEditorInit = useCallback(- (editorInstance: IEditor) => {- let retryCount = 0;-- if (readyTimerRef.current) clearTimeout(readyTimerRef.current);-- const markReadyWhenAvailable = () => {- const snapshot = getPageAgentEditorSnapshot(editorInstance);-- log('[TopicCanvas] editor:onInit', {- ...snapshot,- documentId,- retryCount,- });-- if (snapshot.isReady) {- setEditorReady(true);- return;- }-- if (retryCount >= PAGE_AGENT_READY_RETRY_LIMIT) {- console.warn('[TopicCanvas] Page agent editor is not ready:', {- ...snapshot,- documentId,- });- return;- }-- retryCount += 1;- readyTimerRef.current = setTimeout(- markReadyWhenAvailable,- PAGE_AGENT_READY_RETRY_INTERVAL,- );- };-- markReadyWhenAvailable();- },- [documentId],- );-- return (- <>- <TopicCanvasPageAgentBridge- documentId={documentId}- editor={editor}- editorReady={editorReady}- title={title}- onTitleChange={onTitleChange}- />- <Flexbox- horizontal- style={styles.contentWrapper}- width={'100%'}- onClick={() => editor?.focus()}- >- <Flexbox flex={1} style={styles.editorContainer}>- <WideScreenContainer wrapperStyle={{ cursor: 'text' }}>- <Flexbox flex={1} style={styles.editorContent}>- <TitleSection title={title} onTitleChange={onTitleChange} />- <SharedEditorCanvas- documentId={documentId}- editor={editor}- placeholder={placeholder}- sourceType={'notebook'}- style={style}- topicId={topicId}- onInit={handleEditorInit}- />- </Flexbox>- </WideScreenContainer>- {documentId && editor && <DiffAllToolbar documentId={documentId} editor={editor} />}- </Flexbox>- </Flexbox>- </>- );- },-);--TopicCanvasBody.displayName = 'TopicCanvasBody';--/**- * TopicCanvas- *- * Document canvas for a Topic. Mirrors PageEditor's editor-region layout but- * without the page chrome (header, title, right panel). Renders an empty- * editor; topic-document data wiring (fetch/auto-save) is intentionally- * deferred.- */-const TopicCanvas = memo<TopicCanvasProps>((props) => {- return (- <Flexbox style={styles.root} width={'100%'}>- <EditorProvider>- <TopicCanvasBody {...props} />- </EditorProvider>- </Flexbox>- );-});--TopicCanvas.displayName = 'TopicCanvas';--export default TopicCanvas;diff --git a/src/features/TopicCanvas/useAutoCreateTopicDocument.test.tsx b/src/features/TopicCanvas/useAutoCreateTopicDocument.test.tsxdeleted file mode 100644index 167a8c58921..00000000000--- a/src/features/TopicCanvas/useAutoCreateTopicDocument.test.tsx+++ /dev/null@@ -1,101 +0,0 @@-/**- * @vitest-environment happy-dom- */-import { renderHook, waitFor } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { useAutoCreateTopicDocument } from './useAutoCreateTopicDocument';--const createForTopicMock = vi.hoisted(() => vi.fn());-const notebookMock = vi.hoisted(() => ({- documents: [] as Array<{ id: string }>,- isLoading: false,- useFetchDocuments: vi.fn(),-}));-const chatMock = vi.hoisted(() => ({- topicTitle: 'Research Topic',-}));--interface MockNotebookState {- notebookMap: Record<string, Array<{ id: string }>>;- useFetchDocuments: typeof notebookMock.useFetchDocuments;-}--interface MockChatState {- topicDataMap: Record<string, { items: Array<{ id: string; title: string }> }>;-}--vi.mock('@/services/agentDocument', () => ({- agentDocumentService: {- createForTopic: createForTopicMock,- },-}));--vi.mock('@/store/chat', () => ({- useChatStore: (selector: (state: MockChatState) => unknown) =>- selector({- topicDataMap: {- 'agent:agt_test': { items: [{ id: 'tpc_test', title: chatMock.topicTitle }] },- },- }),-}));--vi.mock('@/store/chat/selectors', () => ({- topicSelectors: {- getTopicById: (id: string) => (state: MockChatState) =>- Object.values(state.topicDataMap)- .flatMap((data) => data.items)- .find((topic) => topic.id === id),- },-}));--vi.mock('@/store/notebook', () => ({- notebookSelectors: {- getDocumentsByTopicId: (topicId: string | undefined) => (state: MockNotebookState) => {- if (!topicId) return [];-- return state.notebookMap[topicId] ?? [];- },- },- useNotebookStore: (selector: (state: MockNotebookState) => unknown) =>- selector({- notebookMap: { tpc_test: notebookMock.documents },- useFetchDocuments: notebookMock.useFetchDocuments,- }),-}));--describe('useAutoCreateTopicDocument', () => {- beforeEach(() => {- createForTopicMock.mockReset();- chatMock.topicTitle = 'Research Topic';- notebookMock.documents = [];- notebookMock.isLoading = false;- notebookMock.useFetchDocuments.mockReset();- notebookMock.useFetchDocuments.mockImplementation(() => ({- isLoading: notebookMock.isLoading,- }));- });-- it('returns an existing topic document id without creating a new page', () => {- notebookMock.documents = [{ id: 'doc_existing' }];-- const { result } = renderHook(() => useAutoCreateTopicDocument('tpc_test', 'agt_test'));-- expect(result.current.documentId).toBe('doc_existing');- expect(createForTopicMock).not.toHaveBeenCalled();- });-- it('creates a topic page and exposes the created document id before the list refresh is observed', async () => {- createForTopicMock.mockResolvedValue({ documentId: 'doc_created' });-- const { result } = renderHook(() => useAutoCreateTopicDocument('tpc_test', 'agt_test'));-- await waitFor(() => expect(result.current.documentId).toBe('doc_created'));- expect(createForTopicMock).toHaveBeenCalledWith({- agentId: 'agt_test',- content: '',- title: 'Research Topic',- topicId: 'tpc_test',- });- });-});diff --git a/src/features/TopicCanvas/useAutoCreateTopicDocument.ts b/src/features/TopicCanvas/useAutoCreateTopicDocument.tsdeleted file mode 100644index ebba3bba27b..00000000000--- a/src/features/TopicCanvas/useAutoCreateTopicDocument.ts+++ /dev/null@@ -1,88 +0,0 @@-'use client';--import type { NotebookDocument } from '@lobechat/types';-import { useEffect, useState } from 'react';--import { agentDocumentService } from '@/services/agentDocument';-import { useChatStore } from '@/store/chat';-import { topicSelectors } from '@/store/chat/selectors';-import { notebookSelectors, useNotebookStore } from '@/store/notebook';--interface UseAutoCreateTopicDocumentResult {- document: NotebookDocument | undefined;- documentId: string | undefined;- isLoading: boolean;-}--const inflight = new Map<string, Promise<string | undefined>>();--/**- * Fetch the topic-scoped document for a topic; auto-create one via the- * agent-document pipeline when the list is empty, then associate it with the- * topic through `topic_documents`. Returns the first document (topic β page is- * 1:1 in practice).- *- * Deduplicates concurrent creations across component instances via a- * module-level promise map keyed by topicId.- */-export const useAutoCreateTopicDocument = (- topicId: string | undefined,- agentId: string | undefined,-): UseAutoCreateTopicDocumentResult => {- const useFetchDocuments = useNotebookStore((s) => s.useFetchDocuments);- const topicTitle = useChatStore((s) =>- topicId ? topicSelectors.getTopicById(topicId)(s)?.title : undefined,- );- const [createdDocument, setCreatedDocument] = useState<- { documentId: string; topicId: string } | undefined- >();-- const { isLoading } = useFetchDocuments(topicId);- const documents = useNotebookStore(notebookSelectors.getDocumentsByTopicId(topicId));-- useEffect(() => {- if (!topicId || !agentId || isLoading) return;- if (documents.length > 0) return;-- let ignore = false;- const promise =- inflight.get(topicId) ??- agentDocumentService- .createForTopic({- agentId,- content: '',- title: topicTitle?.trim() || '',- topicId,- })- .then((document) => document.documentId)- .catch((error) => {- console.error('[TopicCanvas] Failed to auto-create topic document:', error);-- return undefined;- })- .finally(() => {- inflight.delete(topicId);- });-- if (!inflight.has(topicId)) inflight.set(topicId, promise);-- void promise.then((documentId) => {- if (ignore || !documentId) return;- setCreatedDocument({ documentId, topicId });- });-- return () => {- ignore = true;- };- }, [topicId, agentId, topicTitle, isLoading, documents.length]);-- const document = documents[0];- const createdDocumentId =- createdDocument && createdDocument.topicId === topicId ? createdDocument.documentId : undefined;-- return {- document,- documentId: document?.id ?? createdDocumentId,- isLoading,- };-};diff --git a/src/routes/(main)/agent/[topicId]/page/[docId]/index.tsx b/src/routes/(main)/agent/[topicId]/page/[docId]/index.tsxdeleted file mode 100644index 6ddb411b336..00000000000--- a/src/routes/(main)/agent/[topicId]/page/[docId]/index.tsx+++ /dev/null@@ -1 +0,0 @@-export { default } from '@/routes/(main)/agent/features/Page';diff --git a/src/routes/(main)/agent/[topicId]/page/index.tsx b/src/routes/(main)/agent/[topicId]/page/index.tsxdeleted file mode 100644index 02324f3a945..00000000000--- a/src/routes/(main)/agent/[topicId]/page/index.tsx+++ /dev/null@@ -1 +0,0 @@-export { default } from '@/routes/(main)/agent/features/Page/PageRedirect';diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsxindex 550ccedd3e6..dcf4dd02658 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx@@ -9,8 +9,6 @@ const modalConfirm = vi.hoisted(() => vi.fn());const messageError = vi.hoisted(() => vi.fn());const messageSuccess = vi.hoisted(() => vi.fn());const removeDocumentMock = vi.hoisted(() => vi.fn());-const useMatchMock = vi.hoisted(() => vi.fn());-const useNavigateMock = vi.hoisted(() => vi.fn());vi.mock('@lobehub/ui', () => ({Accordion: ({ children }: { children?: ReactNode }) => <div>{children}</div>,@@ -80,11 +78,6 @@ vi.mock('react-i18next', () => ({}),}));-vi.mock('react-router-dom', () => ({- useMatch: () => useMatchMock(),- useNavigate: () => useNavigateMock,-}));-vi.mock('@/features/AgentDocumentsExplorer', () => ({DocumentExplorerTree: ({ data }: { data: unknown[] }) => (<div data-doc-count={data.length} data-testid="document-explorer-tree" />@@ -276,9 +269,6 @@ describe('AgentDocumentsGroup', () => {messageSuccess.mockReset();openDocument.mockReset();removeDocumentMock.mockReset();- useMatchMock.mockReset();- useNavigateMock.mockReset();- useMatchMock.mockReturnValue(null);removeDocumentMock.mockResolvedValue({ deleted: true, id: 'doc-1' });});@@ -313,7 +303,7 @@ describe('AgentDocumentsGroup', () => {render(<AgentDocumentsGroup />);fireEvent.click(screen.getByText('YouTube Comment Retrieval Workflow'));- expect(openDocument).toHaveBeenCalledWith('skill-index-doc');+ expect(openDocument).toHaveBeenCalledWith('skill-index-doc', 'skill-index-row');});it('falls back to the bundle id when opening an orphan skill bundle', () => {@@ -327,7 +317,7 @@ describe('AgentDocumentsGroup', () => {render(<AgentDocumentsGroup />);fireEvent.click(screen.getByText('YouTube Comment Retrieval Workflow'));- expect(openDocument).toHaveBeenCalledWith('skill-bundle-doc');+ expect(openDocument).toHaveBeenCalledWith('skill-bundle-doc', 'skill-bundle-row');});it('opens a child file by relative path through onOpenFile', () => {@@ -341,7 +331,7 @@ describe('AgentDocumentsGroup', () => {render(<AgentDocumentsGroup />);fireEvent.click(screen.getByTestId('skill-skill-bundle-doc-open-skill-md'));- expect(openDocument).toHaveBeenCalledWith('skill-index-doc');+ expect(openDocument).toHaveBeenCalledWith('skill-index-doc', 'skill-index-row');});it('renders the document tree when switching to the Documents tab', () => {@@ -379,7 +369,7 @@ describe('AgentDocumentsGroup', () => {expect(screen.queryByText('Brief')).not.toBeInTheDocument();fireEvent.click(screen.getByText('Example'));- expect(openDocument).toHaveBeenCalledWith('doc-content-2');+ expect(openDocument).toHaveBeenCalledWith('doc-content-2', 'doc-2');fireEvent.click(screen.getByLabelText('delete'));const [firstConfirmCall] = modalConfirm.mock.calls;@@ -390,29 +380,11 @@ describe('AgentDocumentsGroup', () => {agentId: 'agent-1',documentId: 'doc-content-2',id: 'doc-2',- topicId: undefined,});expect(mutate).toHaveBeenCalled();expect(messageSuccess).toHaveBeenCalledWith('workingPanel.resources.deleteSuccess');});- it('navigates to the page route when opening a web card from a topic page', () => {- useMatchMock.mockReturnValue({ params: { aid: 'agent-1', topicId: 'topic-1' } });- useClientDataSWR.mockReturnValue({- data: [webDocRow],- error: undefined,- isLoading: false,- mutate: vi.fn(),- });-- render(<AgentDocumentsGroup />);- fireEvent.click(screen.getByText('Web'));- fireEvent.click(screen.getByText('Example'));-- expect(useNavigateMock).toHaveBeenCalledWith('/agent/agent-1/topic-1/page/doc-content-2');- expect(openDocument).not.toHaveBeenCalled();- });-it('falls back to a single empty placeholder when every skill source is empty', () => {useClientDataSWR.mockReturnValue({data: [fileDocRow, webDocRow],diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsxindex afb35c01017..de8fc8e3389 100644--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx@@ -10,7 +10,6 @@ import { FileTextIcon, GlobeIcon, Trash2Icon } from 'lucide-react';import type { CSSProperties, MouseEvent } from 'react';import { memo, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';-import { useMatch, useNavigate } from 'react-router-dom';import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';import { DocumentExplorerTree } from '@/features/AgentDocumentsExplorer';@@ -31,8 +30,6 @@ import { chatPortalSelectors } from '@/store/chat/selectors';import ProjectLevelSkills from './ProjectLevelSkills';import UserLevelSkills, { useUserSkills } from './UserLevelSkills';-const PAGE_ROUTE_PATTERN = '/agent/:aid/:topicId/page/:docId?';-dayjs.extend(relativeTime);type ResourceFilter = 'skills' | 'documents' | 'web';@@ -120,8 +117,6 @@ const DocumentItem = memo<DocumentItemProps>(const openDocument = useChatStore((s) => s.openDocument);const closeDocument = useChatStore((s) => s.closeDocument);const portalDocumentId = useChatStore(chatPortalSelectors.portalDocumentId);- const navigate = useNavigate();- const pageMatch = useMatch(PAGE_ROUTE_PATTERN);const title = document.title || document.filename || '';const description = document.description ?? undefined;@@ -134,18 +129,11 @@ const DocumentItem = memo<DocumentItemProps>(}): null;- const activeDocumentId = pageMatch ? pageMatch.params.docId : portalDocumentId;- const isActive = activeDocumentId === document.documentId;+ const isActive = portalDocumentId === document.documentId;const handleOpen = () => {if (!document.documentId) return;- if (pageMatch?.params.aid && pageMatch.params.topicId) {- navigate(- `/agent/${pageMatch.params.aid}/${pageMatch.params.topicId}/page/${document.documentId}`,- );- return;- }- openDocument(document.documentId);+ openDocument(document.documentId, document.id);};const handleDelete = (e: MouseEvent) => {@@ -164,7 +152,6 @@ const DocumentItem = memo<DocumentItemProps>(agentId,documentId: document.documentId,id: document.id,- topicId: pageMatch?.params.topicId,});await mutate();message.success(t('workingPanel.resources.deleteSuccess', { ns: 'chat' }));@@ -272,8 +259,6 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(({ style, workingDireagentId ? chatConfigByIdSelectors.isLocalSystemEnabledById(agentId)(s) : false,);const openDocument = useChatStore((s) => s.openDocument);- const navigate = useNavigate();- const pageMatch = useMatch(PAGE_ROUTE_PATTERN);const [filter, setFilter] = useState<ResourceFilter>('skills');const showProjectSkills = isLocalEnabled && !!workingDirectory;@@ -313,14 +298,6 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(({ style, workingDire[skillBundleViews],);- const openDocumentByRoute = (documentId: string) => {- if (pageMatch?.params.aid && pageMatch.params.topicId) {- navigate(`/agent/${pageMatch.params.aid}/${pageMatch.params.topicId}/page/${documentId}`);- return;- }- openDocument(documentId);- };-if (!agentId) return null;if (isLoading) {@@ -345,14 +322,18 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(({ style, workingDireonOpenFile={(item, relativePath) => {const view = skillBundleViews.find((v) => v.bundle.documentId === item.id);const docId = view?.pathToDocumentId.get(relativePath);- if (docId) openDocumentByRoute(docId);+ if (!docId) return;+ const row = data.find((d) => d.documentId === docId);+ openDocument(docId, row?.id);}}onOpenSkill={(item) => {// Open the SKILL.md (skills/index child) when present; fall back to// the bundle itself (orphan bundles surface for recovery).const view = skillBundleViews.find((v) => v.bundle.documentId === item.id);const indexChild = data.find((doc) => doc.parentId === item.id && doc.isSkillIndex);- openDocumentByRoute(indexChild?.documentId ?? view?.bundle.documentId ?? item.id);+ const targetDocId = indexChild?.documentId ?? view?.bundle.documentId ?? item.id;+ const targetRow = data.find((d) => d.documentId === targetDocId);+ openDocument(targetDocId, targetRow?.id);}}onSkillDragStart={(item, event) => {// The runtime resolves these via the `agent-skills:<filename>`diff --git a/src/routes/(main)/agent/features/Page/PageRedirect.test.tsx b/src/routes/(main)/agent/features/Page/PageRedirect.test.tsxdeleted file mode 100644index 6fb7be5655f..00000000000--- a/src/routes/(main)/agent/features/Page/PageRedirect.test.tsx+++ /dev/null@@ -1,74 +0,0 @@-/**- * @vitest-environment happy-dom- */-import { render, waitFor } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import PageRedirect from './PageRedirect';--const navigateMock = vi.hoisted(() => vi.fn());-const useAutoCreateTopicDocumentMock = vi.hoisted(() => vi.fn());-const useParamsMock = vi.hoisted(() => vi.fn());--vi.mock('react-router-dom', async () => {- // eslint-disable-next-line @typescript-eslint/consistent-type-imports- const actual = (await vi.importActual('react-router-dom')) as typeof import('react-router-dom');-- return {- ...actual,- useNavigate: () => navigateMock,- useParams: useParamsMock,- };-});--vi.mock('@/components/Loading/BrandTextLoading', () => ({- default: ({ debugId }: { debugId: string }) => <div data-testid={debugId} />,-}));--vi.mock('@/features/TopicCanvas/useAutoCreateTopicDocument', () => ({- useAutoCreateTopicDocument: useAutoCreateTopicDocumentMock,-}));--describe('PageRedirect', () => {- beforeEach(() => {- navigateMock.mockReset();- useAutoCreateTopicDocumentMock.mockReset();- useParamsMock.mockReset();-- useAutoCreateTopicDocumentMock.mockReturnValue({- document: undefined,- documentId: undefined,- isLoading: false,- });- });-- it('redirects to the page created for an empty topic', async () => {- useParamsMock.mockReturnValue({ aid: 'agt_test', topicId: 'tpc_test' });- useAutoCreateTopicDocumentMock.mockReturnValue({- document: undefined,- documentId: 'doc_created',- isLoading: false,- });-- render(<PageRedirect />);-- await waitFor(() =>- expect(navigateMock).toHaveBeenCalledWith('/agent/agt_test/tpc_test/page/doc_created', {- replace: true,- }),- );- });-- it('keeps the loading state while the topic document id is not available', () => {- useParamsMock.mockReturnValue({ aid: 'agt_test', topicId: 'tpc_test' });- useAutoCreateTopicDocumentMock.mockReturnValue({- document: undefined,- documentId: undefined,- isLoading: true,- });-- render(<PageRedirect />);-- expect(navigateMock).not.toHaveBeenCalled();- });-});diff --git a/src/routes/(main)/agent/features/Page/PageRedirect.tsx b/src/routes/(main)/agent/features/Page/PageRedirect.tsxdeleted file mode 100644index 57bb24d548a..00000000000--- a/src/routes/(main)/agent/features/Page/PageRedirect.tsx+++ /dev/null@@ -1,25 +0,0 @@-'use client';--import { memo, useEffect } from 'react';-import { useNavigate, useParams } from 'react-router-dom';--import BrandTextLoading from '@/components/Loading/BrandTextLoading';-import { useAutoCreateTopicDocument } from '@/features/TopicCanvas/useAutoCreateTopicDocument';--const PageRedirect = memo(() => {- const { aid, topicId } = useParams<{ aid?: string; topicId?: string }>();- const navigate = useNavigate();-- const { documentId } = useAutoCreateTopicDocument(topicId, aid);-- useEffect(() => {- if (!aid || !topicId || !documentId) return;- navigate(`/agent/${aid}/${topicId}/page/${documentId}`, { replace: true });- }, [aid, topicId, documentId, navigate]);-- return <BrandTextLoading debugId={'PageRedirect'} />;-});--PageRedirect.displayName = 'PageRedirect';--export default PageRedirect;diff --git a/src/routes/(main)/agent/features/Page/index.test.tsx b/src/routes/(main)/agent/features/Page/index.test.tsxdeleted file mode 100644index e90e8d3f818..00000000000--- a/src/routes/(main)/agent/features/Page/index.test.tsx+++ /dev/null@@ -1,188 +0,0 @@-/**- * @vitest-environment happy-dom- */-import { render, screen, waitFor } from '@testing-library/react';-import type { ReactNode } from 'react';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import TopicPage from './index';--const useParamsMock = vi.hoisted(() => vi.fn());-const useNavigateMock = vi.hoisted(() => vi.fn());-const useClientDataSWRMock = vi.hoisted(() => vi.fn());-const useAutoCreateTopicDocumentMock = vi.hoisted(() => vi.fn());--vi.mock('react-router-dom', async () => {- // eslint-disable-next-line @typescript-eslint/consistent-type-imports- const actual = (await vi.importActual('react-router-dom')) as typeof import('react-router-dom');-- return {- ...actual,- useNavigate: () => useNavigateMock,- useParams: useParamsMock,- };-});--vi.mock('swr', () => ({- mutate: vi.fn(),-}));--vi.mock('@/features/EditorCanvas', () => ({- AutoSaveHint: ({ documentId }: { documentId: string }) => (- <div data-document-id={documentId} data-testid="autosave-hint" />- ),-}));--vi.mock('@/libs/swr', () => ({- useClientDataSWR: (...args: unknown[]) => useClientDataSWRMock(...args),-}));--vi.mock('@/services/document', () => ({- documentService: {- getDocumentById: vi.fn(),- updateDocument: vi.fn(),- },-}));--vi.mock('@/services/agentDocument', () => ({- agentDocumentSWRKeys: { documentsList: (id: string) => ['agent-documents-list', id] },-}));--vi.mock('@/store/notebook/action', () => ({- SWR_USE_FETCH_NOTEBOOK_DOCUMENTS: 'SWR_USE_FETCH_NOTEBOOK_DOCUMENTS',-}));--vi.mock('@/features/TopicCanvas/useAutoCreateTopicDocument', () => ({- useAutoCreateTopicDocument: (...args: unknown[]) => useAutoCreateTopicDocumentMock(...args),-}));--vi.mock('@lobehub/ui', () => ({- Flexbox: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (- <div {...props}>{children}</div>- ),-}));--vi.mock('@/features/FloatingChatPanel', () => ({- default: ({- agentId,- documentId,- open,- scope,- title,- topicId,- variant,- }: {- agentId: string;- documentId?: string;- open?: boolean;- scope?: string;- title?: string;- topicId: string | null;- variant?: string;- }) => (- <div- data-agent-id={agentId}- data-document-id={documentId ?? ''}- data-open={String(open)}- data-scope={scope ?? ''}- data-testid="floating-chat-panel"- data-title={title ?? ''}- data-topic-id={topicId ?? 'null'}- data-variant={variant ?? ''}- />- ),-}));--vi.mock('@/features/TopicCanvas', () => ({- default: ({- agentId,- documentId,- topicId,- }: {- agentId?: string;- documentId?: string;- topicId?: string | null;- }) => (- <div- data-agent-id={agentId ?? ''}- data-document-id={documentId ?? ''}- data-testid="topic-canvas"- data-topic-id={topicId ?? 'null'}- />- ),-}));--describe('Topic page route', () => {- beforeEach(() => {- useClientDataSWRMock.mockReset();- useAutoCreateTopicDocumentMock.mockReset();- useNavigateMock.mockReset();- useParamsMock.mockReset();-- useClientDataSWRMock.mockReturnValue({ data: null, error: undefined, isLoading: false });- useAutoCreateTopicDocumentMock.mockReturnValue({- document: undefined,- documentId: undefined,- isLoading: false,- });- });-- it('renders FloatingChatPanel with route topic context', () => {- useParamsMock.mockReturnValue({- aid: 'agt_test',- docId: 'doc_test',- topicId: 'tpc_test',- });-- render(<TopicPage />);-- expect(screen.getByTestId('agent-page-container')).toBeInTheDocument();- expect(screen.getByTestId('topic-canvas')).toHaveAttribute('data-agent-id', 'agt_test');- expect(screen.getByTestId('topic-canvas')).toHaveAttribute('data-topic-id', 'tpc_test');- expect(screen.getByTestId('topic-canvas')).toHaveAttribute('data-document-id', 'doc_test');- expect(screen.getByTestId('floating-chat-panel')).toHaveAttribute('data-agent-id', 'agt_test');- expect(screen.getByTestId('floating-chat-panel')).toHaveAttribute(- 'data-document-id',- 'doc_test',- );- expect(screen.getByTestId('floating-chat-panel')).toHaveAttribute('data-scope', 'page');-- expect(screen.getByTestId('floating-chat-panel')).toHaveAttribute('data-topic-id', 'tpc_test');- expect(screen.getByTestId('floating-chat-panel')).toHaveAttribute('data-variant', 'embedded');- expect(useAutoCreateTopicDocumentMock).toHaveBeenCalledWith('tpc_test', 'agt_test');- });-- it('redirects to the topic page document when the current doc id is invalid', async () => {- useParamsMock.mockReturnValue({- aid: 'agt_test',- docId: 'doc_deleted',- topicId: 'tpc_test',- });- useClientDataSWRMock.mockReturnValue({- data: undefined,- error: undefined,- isLoading: false,- });- useAutoCreateTopicDocumentMock.mockReturnValue({- document: undefined,- documentId: 'doc_created',- isLoading: false,- });-- render(<TopicPage />);-- await waitFor(() =>- expect(useNavigateMock).toHaveBeenCalledWith('/agent/agt_test/tpc_test/page/doc_created', {- replace: true,- }),- );- });-- it('returns null when aid or topicId is missing', () => {- useParamsMock.mockReturnValue({ aid: 'agt_test' });-- const { container } = render(<TopicPage />);-- expect(container).toBeEmptyDOMElement();- });-});diff --git a/src/routes/(main)/agent/features/Page/index.tsx b/src/routes/(main)/agent/features/Page/index.tsxdeleted file mode 100644index 8cf5048d0c4..00000000000--- a/src/routes/(main)/agent/features/Page/index.tsx+++ /dev/null@@ -1,130 +0,0 @@-'use client';--import { Flexbox } from '@lobehub/ui';-import { debounce } from 'es-toolkit/compat';-import { memo, useEffect, useMemo, useState } from 'react';-import { useNavigate, useParams } from 'react-router-dom';--import { AutoSaveHint } from '@/features/EditorCanvas';-import FloatingChatPanel from '@/features/FloatingChatPanel';-import TopicCanvas from '@/features/TopicCanvas';-import { useAutoCreateTopicDocument } from '@/features/TopicCanvas/useAutoCreateTopicDocument';-import { useClientDataSWR } from '@/libs/swr';-import HeaderSlot from '@/routes/(main)/agent/(chat)/_layout/HeaderSlot';-import { documentService } from '@/services/document';-import { invalidateDocumentMutation } from '@/services/document/invalidation';-import { documentSWRKeys } from '@/services/document/swrKeys';--const MAX_PANEL_WIDTH = 1024;-const TITLE_SAVE_DEBOUNCE = 500;--const TopicPage = memo(() => {- const { aid, topicId, docId } = useParams<{ aid?: string; docId?: string; topicId?: string }>();- const navigate = useNavigate();-- const { documentId: topicDocumentId } = useAutoCreateTopicDocument(topicId, aid);-- const [titleDraft, setTitleDraft] = useState<string | undefined>();-- const {- data: documentMeta,- error: documentError,- isLoading: isDocLoading,- } = useClientDataSWR(docId ? documentSWRKeys.pageMeta(docId) : null, () =>- documentService.getDocumentById(docId!),- );-- const isInvalidDoc = Boolean(docId && !isDocLoading && (documentError || documentMeta == null));-- useEffect(() => {- if (!aid || !topicId) return;- if (!isInvalidDoc) return;- if (!topicDocumentId) return;- if (topicDocumentId === docId) return;- navigate(`/agent/${aid}/${topicId}/page/${topicDocumentId}`, { replace: true });- }, [aid, topicId, docId, isInvalidDoc, topicDocumentId, navigate]);-- useEffect(() => {- setTitleDraft(undefined);- }, [docId]);-- const debouncedSaveTitle = useMemo(- () =>- debounce(- async (- id: string,- nextTitle: string,- ctx: { agentId: string | undefined; topicId: string | undefined },- ) => {- await documentService.updateDocument({- id,- saveSource: 'autosave',- title: nextTitle,- });- await invalidateDocumentMutation({- agentId: ctx.agentId,- cause: 'page-title',- documentId: id,- refreshDocumentEditor: false,- topicId: ctx.topicId,- });- },- TITLE_SAVE_DEBOUNCE,- ),- [],- );-- const handleTitleChange = (next: string) => {- setTitleDraft(next);- if (docId) debouncedSaveTitle(docId, next, { agentId: aid, topicId });- };-- if (!aid || !topicId) return null;-- const displayTitle = titleDraft ?? documentMeta?.title ?? '';-- return (- <Flexbox- align={'center'}- data-testid="agent-page-container"- height={'100%'}- style={{ minHeight: 0, minWidth: 0, position: 'relative' }}- width={'100%'}- >- {docId && (- <HeaderSlot>- <AutoSaveHint documentId={docId} />- </HeaderSlot>- )}- <Flexbox- align={'center'}- flex={1}- style={{ minHeight: 0, overflowX: 'hidden', overflowY: 'auto' }}- width={'100%'}- >- <Flexbox style={{ maxWidth: MAX_PANEL_WIDTH, paddingBlockEnd: 16 }} width={'100%'}>- <TopicCanvas- agentId={aid}- documentId={docId}- title={displayTitle}- topicId={topicId}- onTitleChange={handleTitleChange}- />- </Flexbox>- </Flexbox>- <Flexbox style={{ maxWidth: MAX_PANEL_WIDTH, zIndex: 19 }} width={'100%'}>- <FloatingChatPanel- agentId={aid}- documentId={docId}- maxHeight={0.92}- minHeight={320}- scope={'page'}- topicId={topicId}- variant={'embedded'}- />- </Flexbox>- </Flexbox>- );-});--export default TopicPage;diff --git a/src/routes/(main)/agent/features/topicPageRouteMeta.ts b/src/routes/(main)/agent/features/topicPageRouteMeta.tsdeleted file mode 100644index 36bfdc186e8..00000000000--- a/src/routes/(main)/agent/features/topicPageRouteMeta.ts+++ /dev/null@@ -1,32 +0,0 @@-import { FilePenIcon } from 'lucide-react';--import { type DynamicRouteMeta, routeMeta } from '@/spa/router/routeMeta';-import { useAgentStore } from '@/store/agent';-import { agentSelectors } from '@/store/agent/selectors';-import { useChatStore } from '@/store/chat';--const useTopicTitle = (topicId: string | undefined): string | undefined =>- useChatStore((s) => {- if (!topicId) return undefined;- for (const data of Object.values(s.topicDataMap)) {- const topic = data.items?.find((item) => item.id === topicId);- if (topic?.title) return topic.title;- }- return undefined;- });--export const agentTopicPageRouteMeta = routeMeta({- icon: FilePenIcon,- titleKey: 'navigation.page',- useDynamicMeta: (params): DynamicRouteMeta => {- const meta = useAgentStore(agentSelectors.getAgentMetaById(params.aid ?? ''));- const topicTitle = useTopicTitle(params.topicId);- const hasMeta = Object.keys(meta).length > 0;-- return {- avatar: meta.avatar,- backgroundColor: meta.backgroundColor,- title: topicTitle || (hasMeta ? meta.title : undefined),- };- },-});diff --git a/src/routes/(main)/agent/page/index.tsx b/src/routes/(main)/agent/page/index.tsxdeleted file mode 100644index 09093b9f69b..00000000000--- a/src/routes/(main)/agent/page/index.tsx+++ /dev/null@@ -1,14 +0,0 @@-'use client';--import { memo } from 'react';-import { Navigate, useParams } from 'react-router-dom';--import { SESSION_CHAT_URL } from '@/const/url';--const PageRedirect = memo(() => {- const params = useParams<{ aid?: string }>();-- return <Navigate replace to={params.aid ? SESSION_CHAT_URL(params.aid) : '/agent'} />;-});--export default PageRedirect;diff --git a/src/server/services/agentDocuments/index.ts b/src/server/services/agentDocuments/index.tsindex 3203bf5e389..25ff5f26447 100644--- a/src/server/services/agentDocuments/index.ts+++ b/src/server/services/agentDocuments/index.ts@@ -336,6 +336,16 @@ export class AgentDocumentsService {return this.getDocumentByIdInAgent(id, expectedAgentId);}+ /**+ * Resolve an `agent_documents` row from `(agentId, documentId)`. Use when the+ * caller has a `documents.id` but needs the row id (e.g. when building the+ * `<document agent_document_id ... />` injection from a portal payload).+ * Returns undefined when the agent does not own this document binding.+ */+ async findRowByDocumentId(agentId: string, documentId: string) {+ return this.agentDocumentModel.findByDocumentId(agentId, documentId);+ }+async getDocumentSnapshotById(id: string, expectedAgentId?: string) {const doc = await this.agentDocumentModel.findById(id);diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsindex 230dc1da2e2..87cb247e66b 100644--- a/src/server/services/aiAgent/index.ts+++ b/src/server/services/aiAgent/index.ts@@ -1987,23 +1987,25 @@ export class AiAgentService {},};- if (appContext?.scope !== 'page' && appContext?.documentId && topicId) {+ if (appContext?.scope !== 'page' && appContext?.documentId) {+ // Server is authoritative β `(agentId, documentId)` is a unique binding+ // so a single indexed lookup both validates any caller-supplied+ // `agentDocumentId` hint and resolves the row id when one was not+ // provided (covers docs opened outside the active topic, e.g. skills+ // and web docs).try {- const topicDocuments = await this.agentDocumentsService.listDocumentsForTopic(+ const row = await this.agentDocumentsService.findRowByDocumentId(resolvedAgentId,- topicId,- );- const activeTopicDocument = topicDocuments.find(- (document) => document.documentId === appContext.documentId,+ appContext.documentId,);initialContext = {...initialContext,initialContext: {activeTopicDocument: {- agentDocumentId: activeTopicDocument?.id,+ ...(row?.id ? { agentDocumentId: row.id } : {}),documentId: appContext.documentId,- title: activeTopicDocument?.title,+ ...(row?.title ? { title: row.title } : {}),},},};diff --git a/src/spa/router/desktopRouter.config.desktop.tsx b/src/spa/router/desktopRouter.config.desktop.tsxindex c7ebd120728..e922c1c02ae 100644--- a/src/spa/router/desktopRouter.config.desktop.tsx+++ b/src/spa/router/desktopRouter.config.desktop.tsx@@ -29,12 +29,8 @@ import TaskWorkspaceLayout from '@/routes/(main)/(task-workspace)/_layout';import AgentPage from '@/routes/(main)/agent';import DesktopChatLayout from '@/routes/(main)/agent/_layout';import DesktopAgentChatLayout from '@/routes/(main)/agent/(chat)/_layout';-import AgentTopicNotebookRedirectPage from '@/routes/(main)/agent/[topicId]/page';-import AgentTopicNotebookDocPage from '@/routes/(main)/agent/[topicId]/page/[docId]';import AgentChannelPage from '@/routes/(main)/agent/channel';import { agentRouteMeta } from '@/routes/(main)/agent/features/routeMeta';-import { agentTopicPageRouteMeta } from '@/routes/(main)/agent/features/topicPageRouteMeta';-import AgentPageRedirectPage from '@/routes/(main)/agent/page';import AgentProfilePage from '@/routes/(main)/agent/profile';import AgentTaskDetailRoute from '@/routes/(main)/agent/task/[taskId]';import AgentTopicsPage from '@/routes/(main)/agent/topics';@@ -121,37 +117,13 @@ export const desktopRoutes: RouteObject[] = [index: true,},{- children: [- {- element: <AgentPage />,- handle: { meta: agentRouteMeta },- index: true,- },- {- children: [- {- element: <AgentTopicNotebookRedirectPage />,- handle: { meta: agentTopicPageRouteMeta },- index: true,- },- {- element: <AgentTopicNotebookDocPage />,- handle: { meta: agentTopicPageRouteMeta },- path: ':docId',- },- ],- path: 'page',- },- ],+ element: <AgentPage />,+ handle: { meta: agentRouteMeta },path: ':topicId',},],element: <DesktopAgentChatLayout />,},- {- element: <AgentPageRedirectPage />,- path: 'page',- },{element: <AgentProfilePage />,path: 'profile',diff --git a/src/spa/router/desktopRouter.config.tsx b/src/spa/router/desktopRouter.config.tsxindex 1c63f862e55..84877b27b04 100644--- a/src/spa/router/desktopRouter.config.tsx+++ b/src/spa/router/desktopRouter.config.tsx@@ -18,7 +18,6 @@ import {import { taskRouteMeta, tasksRouteMeta } from '@/features/AgentTasks/routeMeta';import { pageRouteMeta } from '@/features/Pages/routeMeta';import { agentRouteMeta } from '@/routes/(main)/agent/features/routeMeta';-import { agentTopicPageRouteMeta } from '@/routes/(main)/agent/features/topicPageRouteMeta';import { groupRouteMeta } from '@/routes/(main)/group/features/routeMeta';import { settingsRouteMeta } from '@/routes/(main)/settings/features/routeMeta';import { routeMeta } from '@/spa/router/routeMeta';@@ -47,34 +46,8 @@ export const desktopRoutes: RouteObject[] = [index: true,},{- children: [- {- element: agentChatElement,- handle: { meta: agentRouteMeta },- index: true,- },- {- children: [- {- element: dynamicElement(- () => import('@/routes/(main)/agent/[topicId]/page'),- 'Desktop > Chat > Topic > Page > Redirect',- ),- handle: { meta: agentTopicPageRouteMeta },- index: true,- },- {- element: dynamicElement(- () => import('@/routes/(main)/agent/[topicId]/page/[docId]'),- 'Desktop > Chat > Topic > Page > Doc',- ),- handle: { meta: agentTopicPageRouteMeta },- path: ':docId',- },- ],- path: 'page',- },- ],+ element: agentChatElement,+ handle: { meta: agentRouteMeta },path: ':topicId',},],@@ -83,13 +56,6 @@ export const desktopRoutes: RouteObject[] = ['Desktop > Chat > ChatLayout',),},- {- element: dynamicElement(- () => import('@/routes/(main)/agent/page'),- 'Desktop > Chat > Invalid Page Redirect',- ),- path: 'page',- },{element: dynamicElement(() => import('@/routes/(main)/agent/profile'),diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.tsindex ae1f48a955a..6a3651d6d6a 100644--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts@@ -42,6 +42,8 @@ import { agentGroupByIdSelectors, getChatGroupStoreState } from '@/store/agentGrimport { selectRuntimeType } from '@/store/chat/slices/aiChat/actions/agentDispatcher';import { resolveHeteroResume } from '@/store/chat/slices/aiChat/actions/heteroResume';import { dispatchNonHeteroSubAgent } from '@/store/chat/slices/aiChat/actions/nonHeteroSubAgentDispatcher';+import { PortalViewType } from '@/store/chat/slices/portal/initialState';+import { chatPortalSelectors } from '@/store/chat/slices/portal/selectors';import { type ChatStore } from '@/store/chat/store';import {mergeAgentRuntimeInitialContexts,@@ -816,9 +818,18 @@ export class ConversationLifecycleActionImpl {if (data.createdThreadId) {this.#get().updateOperationMetadata(operationId, { createdThreadId: data.createdThreadId });- // Update portalThreadId to switch from "new thread" mode to "existing thread" mode- // This ensures the Portal Thread UI displays correctly with the real thread ID- this.#get().openThreadInPortal(data.createdThreadId, context.sourceMessageId);+ // When the active portal view is already the Thread surface (the+ // main-page "create subtopic" flow staged it before sending), pivot it+ // from `isNew` β persisted thread id. Otherwise the thread was started+ // by a panel-hosted ConversationProvider (e.g. FloatingChatPanel inside+ // the Document portal) and we must NOT push a Thread view β doing so+ // would cover the host view the user is still reading.+ const currentPortalViewType = chatPortalSelectors.currentViewType(this.#get());+ if (currentPortalViewType === PortalViewType.Thread) {+ this.#get().openThreadInPortal(data.createdThreadId, context.sourceMessageId);+ } else {+ this.#get().syncThreadInPortal(data.createdThreadId, context.sourceMessageId);+ }// Refresh threads list to update the sidebarthis.#get().refreshThreads();diff --git a/src/store/chat/slices/aiChat/actions/gateway.ts b/src/store/chat/slices/aiChat/actions/gateway.tsindex 2458c3d30aa..d87ddf939d6 100644--- a/src/store/chat/slices/aiChat/actions/gateway.ts+++ b/src/store/chat/slices/aiChat/actions/gateway.ts@@ -359,6 +359,7 @@ export class GatewayActionImpl {{agentId: context.agentId,appContext: {+ agentDocumentId: context.agentDocumentId,defaultTaskAssigneeAgentId: context.defaultTaskAssigneeAgentId,documentId: context.documentId,groupId: context.groupId,diff --git a/src/store/chat/slices/portal/action.ts b/src/store/chat/slices/portal/action.tsindex fd3938cbaae..962b01e342e 100644--- a/src/store/chat/slices/portal/action.ts+++ b/src/store/chat/slices/portal/action.ts@@ -169,8 +169,8 @@ export class ChatPortalActionImpl {this.#get().pushPortalView({ artifact, type: PortalViewType.Artifact });};- openDocument = (documentId: string): void => {- this.#get().pushPortalView({ documentId, type: PortalViewType.Document });+ openDocument = (documentId: string, agentDocumentId?: string): void => {+ this.#get().pushPortalView({ agentDocumentId, documentId, type: PortalViewType.Document });};openFilePreview = (file: PortalFile): void => {diff --git a/src/store/chat/slices/portal/initialState.ts b/src/store/chat/slices/portal/initialState.tsindex 27723d34dd8..15ed370aa4f 100644--- a/src/store/chat/slices/portal/initialState.ts+++ b/src/store/chat/slices/portal/initialState.ts@@ -29,7 +29,7 @@ export interface PortalFile {export type PortalViewData =| { type: PortalViewType.Home }| { artifact: PortalArtifact; type: PortalViewType.Artifact }- | { documentId: string; type: PortalViewType.Document }+ | { agentDocumentId?: string; documentId: string; type: PortalViewType.Document }| { type: PortalViewType.Notebook }| { file: PortalFile; type: PortalViewType.FilePreview }| { type: PortalViewType.LocalFile }diff --git a/src/store/chat/slices/portal/selectors.ts b/src/store/chat/slices/portal/selectors.tsindex a697a51ac94..1e411463cc7 100644--- a/src/store/chat/slices/portal/selectors.ts+++ b/src/store/chat/slices/portal/selectors.ts@@ -117,6 +117,11 @@ const portalDocumentId = (s: ChatStoreState): string | undefined => {return view?.documentId;};+const portalAgentDocumentId = (s: ChatStoreState): string | undefined => {+ const view = getViewData(s, PortalViewType.Document);+ return view?.agentDocumentId;+};+// File Preview selectorsconst currentFile = (s: ChatStoreState): PortalFile | undefined => {const view = getViewData(s, PortalViewType.FilePreview);@@ -194,6 +199,7 @@ export const chatPortalSelectors = {isArtifactTagClosed,// Document data+ portalAgentDocumentId,portalDocumentId,// File preview datadiff --git a/src/store/chat/slices/thread/action.ts b/src/store/chat/slices/thread/action.tsindex ff7233f8786..b26dd1bb7e0 100644--- a/src/store/chat/slices/thread/action.ts+++ b/src/store/chat/slices/thread/action.ts@@ -103,6 +103,21 @@ export class ChatThreadActionImpl {});};+ /**+ * Sync the portal slice's thread state to a freshly-created thread *without*+ * pushing a Thread view onto the portal stack. Use after `sendMessage`+ * creates a thread from a panel-hosted ConversationProvider (e.g. the+ * Document portal's FloatingChatPanel) so portal-bound selectors resolve to+ * the persisted thread while the host view remains visible.+ */+ syncThreadInPortal = (threadId: string, sourceMessageId?: string | null): void => {+ this.#set(+ { portalThreadId: threadId, startToForkThread: false, threadStartMessageId: sourceMessageId },+ false,+ 'syncThreadInPortal',+ );+ };+closeThreadPortal = (): void => {this.#set({ threadStartMessageId: undefined, portalThreadId: undefined, startToForkThread: undefined },diff --git a/src/store/chat/utils/activeTopicDocumentContext.test.ts b/src/store/chat/utils/activeTopicDocumentContext.test.tsindex ccda58b562a..4338fab717b 100644--- a/src/store/chat/utils/activeTopicDocumentContext.test.ts+++ b/src/store/chat/utils/activeTopicDocumentContext.test.ts@@ -47,6 +47,37 @@ describe('activeTopicDocumentContext', () => {});});+ it('short-circuits the reverse lookup when context carries agentDocumentId', async () => {+ const context = await resolveActiveTopicDocumentInitialContext({+ agentDocumentId: 'agd_caller',+ agentId: 'agt_1',+ documentId: 'docs_1',+ scope: 'thread',+ topicId: 'tpc_1',+ });++ expect(agentDocumentService.listDocuments).not.toHaveBeenCalled();+ expect(context?.initialContext?.activeTopicDocument).toEqual({+ agentDocumentId: 'agd_caller',+ documentId: 'docs_1',+ });+ });++ it('resolves with caller-supplied agentDocumentId even without an active topic', async () => {+ const context = await resolveActiveTopicDocumentInitialContext({+ agentDocumentId: 'agd_caller',+ agentId: 'agt_1',+ documentId: 'docs_1',+ scope: 'thread',+ });++ expect(agentDocumentService.listDocuments).not.toHaveBeenCalled();+ expect(context?.initialContext?.activeTopicDocument).toEqual({+ agentDocumentId: 'agd_caller',+ documentId: 'docs_1',+ });+ });+it('does not resolve active topic document context in page scope', async () => {const context = await resolveActiveTopicDocumentInitialContext({agentId: 'agt_1',diff --git a/src/store/chat/utils/activeTopicDocumentContext.ts b/src/store/chat/utils/activeTopicDocumentContext.tsindex 02ce9e39c76..bab643037e6 100644--- a/src/store/chat/utils/activeTopicDocumentContext.ts+++ b/src/store/chat/utils/activeTopicDocumentContext.ts@@ -38,7 +38,20 @@ const resolveActiveTopicDocument = async (context: ConversationContext,): Promise<RuntimeActiveTopicDocumentContext | undefined> => {if (context.scope === 'page') return;- if (!context.agentId || !context.topicId || !context.documentId) return;+ if (!context.agentId || !context.documentId) return;++ // When the caller already knows the agent_documents row id (e.g. portal+ // openers pass it through), skip the listDocuments reverse lookup entirely β+ // the lookup is scoped to currentTopic and would miss docs opened outside+ // the active topic (skills, web docs).+ if (context.agentDocumentId) {+ return {+ agentDocumentId: context.agentDocumentId,+ documentId: context.documentId,+ };+ }++ if (!context.topicId) return;try {const documents = await agentDocumentService.listDocuments({