π€― 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(chat): isolate context selections by conversation key (#18011)
AmAzing-30daf9e20b48
diff --git a/src/features/AgentDocumentPage/index.test.tsx b/src/features/AgentDocumentPage/index.test.tsxindex 3e81843275b..2f8242f1b23 100644--- a/src/features/AgentDocumentPage/index.test.tsx+++ b/src/features/AgentDocumentPage/index.test.tsx@@ -5,6 +5,8 @@ import { render, screen } from '@testing-library/react';import type { ReactNode } from 'react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';+import AgentDocumentPage from './index';vi.mock('react-router', () => ({@@ -17,12 +19,19 @@ vi.mock('@lobehub/ui', () => ({),}));+const pageEditorProps = vi.hoisted(() => ({+ current: undefined as undefined | Record<string, unknown>,+}));+vi.mock('@/features/PageEditor', () => ({- PageEditor: ({ pageId, header }: { header?: ReactNode; pageId?: string }) => (- <div data-page-id={pageId} data-testid="page-editor">- {header}- </div>- ),+ PageEditor: (props: { header?: ReactNode; pageId?: string }) => {+ pageEditorProps.current = props;+ return (+ <div data-page-id={props.pageId} data-testid="page-editor">+ {props.header}+ </div>+ );+ },}));vi.mock('@/features/WideScreenContainer', () => ({@@ -109,6 +118,7 @@ describe('AgentDocumentPage', () => {};headerProps.current = undefined;panelProps.current = undefined;+ pageEditorProps.current = undefined;docChatTopicCalls.current = [];navigateMock.mockClear();});@@ -157,6 +167,16 @@ describe('AgentDocumentPage', () => {documentId: 'docs_abc',topicId: 'doc-topic-1',});+ expect(pageEditorProps.current?.askCopilotTarget).toEqual({+ contextKey: messageMapKey({+ agentId: 'agent-from-url',+ documentId: 'docs_abc',+ scope: 'main',+ threadId: null,+ topicId: 'doc-topic-1',+ }),+ writable: true,+ });});it('skips the panel until the doc-anchored topic id resolves', () => {diff --git a/src/features/AgentDocumentPage/index.tsx b/src/features/AgentDocumentPage/index.tsxindex e8d4becc084..8b27fb82f81 100644--- a/src/features/AgentDocumentPage/index.tsx+++ b/src/features/AgentDocumentPage/index.tsx@@ -4,11 +4,13 @@ import { Flexbox } from '@lobehub/ui';import { memo, useCallback, useEffect, useMemo } from 'react';import { useParams } from 'react-router';+import { type ComposerTarget, createComposerTarget } from '@/features/Conversation/types';import FloatingChatPanel from '@/features/FloatingChatPanel';import { useDocumentChatTopic } from '@/features/FloatingChatPanel/useDocumentChatTopic';import { PageEditor } from '@/features/PageEditor';import WideScreenContainer from '@/features/WideScreenContainer';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';import Header from './Header';import { buildAgentDocumentsPath } from './navigation';@@ -50,6 +52,21 @@ const AgentDocumentPage = memo<AgentDocumentPageProps>(({ documentId }) => {agentId: ownsDocument ? chatAgentId : undefined,documentId: ownsDocument ? documentId : undefined,});+ const askCopilotTarget = useMemo<ComposerTarget>(+ () =>+ chatAgentId && docChatTopicId+ ? createComposerTarget(+ messageMapKey({+ agentId: chatAgentId,+ documentId,+ scope: 'main',+ threadId: null,+ topicId: docChatTopicId,+ }),+ )+ : { reason: 'no-composer', writable: false },+ [chatAgentId, docChatTopicId, documentId],+ );const backToChat = useCallback(() => navigate(agentId ? `/agent/${agentId}` : '/agent'),@@ -105,6 +122,7 @@ const AgentDocumentPage = memo<AgentDocumentPageProps>(({ documentId }) => {<Flexbox flex={1} style={{ minHeight: 0 }} width={'100%'}><PageEditorfullWidthHeader+ askCopilotTarget={askCopilotTarget}header={header}key={documentId}// A skill index's visible name is the bundle title; renaming must godiff --git a/src/features/ChatInput/ChatInputProvider.tsx b/src/features/ChatInput/ChatInputProvider.tsxindex 0e242f05019..144ff08eff8 100644--- a/src/features/ChatInput/ChatInputProvider.tsx+++ b/src/features/ChatInput/ChatInputProvider.tsx@@ -15,6 +15,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(({agentId,children,+ contextSelectionKey,contextWindowMessages,draftKey,feature = DEFAULT_CHAT_INPUT_FEATURE,@@ -39,6 +40,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(createStore={() =>createStore({allowExpand,+ contextSelectionKey,contextWindowMessages,draftKey,editor,@@ -58,6 +60,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(agentId={agentId}allowExpand={allowExpand}chatInputEditorRef={chatInputEditorRef}+ contextSelectionKey={contextSelectionKey}contextWindowMessages={contextWindowMessages}draftKey={draftKey}feature={feature}diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextList.tsx b/src/features/ChatInput/Desktop/ContextContainer/ContextList.tsxindex b903622672d..26729f14bdb 100644--- a/src/features/ChatInput/Desktop/ContextContainer/ContextList.tsx+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextList.tsx@@ -1,11 +1,11 @@import { Flexbox, ScrollShadow } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';-import { memo, useEffect, useMemo, useRef } from 'react';+import { memo, useMemo } from 'react';+import { useChatInputStore } from '@/features/ChatInput/store';import { fileChatSelectors, useFileStore } from '@/store/file';import { UPLOAD_STATUS_SET } from '@/types/files/upload';-import { useAgentId } from '../../hooks/useAgentId';import FileItem from '../FilePreview/FileItem';import ContextItem from './ContextItem';import ElementItem from './ElementItem';@@ -24,21 +24,15 @@ const styles = createStaticStyles(({ css }) => ({}));const ContextList = memo(() => {- const agentId = useAgentId();- const prevAgentIdRef = useRef<string | undefined>(undefined);+ const contextSelectionKey = useChatInputStore((s) => s.contextSelectionKey);const inputFilesList = useFileStore(fileChatSelectors.chatUploadFileList);const showFileList = useFileStore(fileChatSelectors.chatUploadFileListHasItem);- const rawSelectionList = useFileStore(fileChatSelectors.chatContextSelections);- const showSelectionList = useFileStore(fileChatSelectors.chatContextSelectionHasItem);- const clearChatContextSelections = useFileStore((s) => s.clearChatContextSelections);-- // Clear selections only when agentId changes (not on initial mount)- useEffect(() => {- if (prevAgentIdRef.current !== undefined && prevAgentIdRef.current !== agentId) {- clearChatContextSelections();- }- prevAgentIdRef.current = agentId;- }, [agentId, clearChatContextSelections]);+ const rawSelectionList = useFileStore(+ fileChatSelectors.chatContextSelections(contextSelectionKey),+ );+ const showSelectionList = useFileStore(+ fileChatSelectors.chatContextSelectionHasItem(contextSelectionKey),+ );// Filter duplicates based on preview contentconst selectionList = rawSelectionList.filter(diff --git a/src/features/ChatInput/Desktop/ContextContainer/ElementItem.tsx b/src/features/ChatInput/Desktop/ContextContainer/ElementItem.tsxindex 68fc6c8ecf7..c3ca8370a87 100644--- a/src/features/ChatInput/Desktop/ContextContainer/ElementItem.tsx+++ b/src/features/ChatInput/Desktop/ContextContainer/ElementItem.tsx@@ -4,6 +4,7 @@ import { createStaticStyles, cssVar } from 'antd-style';import { SquareDashedMousePointer } from 'lucide-react';import { memo } from 'react';+import { useChatInputStore } from '@/features/ChatInput/store';import { useFileStore } from '@/store/file';const styles = createStaticStyles(({ css }) => ({@@ -65,6 +66,7 @@ const styles = createStaticStyles(({ css }) => ({* element's own cropped screenshot in the tooltip.*/const ElementItem = memo<ChatContextContent>(({ element, id, preview }) => {+ const contextSelectionKey = useChatInputStore((s) => s.contextSelectionKey);const [removeSelection] = useFileStore((s) => [s.removeChatContextSelection]);if (!element) return null;@@ -89,7 +91,9 @@ const ElementItem = memo<ChatContextContent>(({ element, id, preview }) => {closableicon={<SquareDashedMousePointer size={16} />}size={'large'}- onClose={() => removeSelection(id)}+ onClose={() => {+ if (contextSelectionKey) removeSelection({ contextKey: contextSelectionKey, id });+ }}><Tooltip title={tooltip}><span>diff --git a/src/features/ChatInput/Desktop/ContextContainer/SelectionItem.tsx b/src/features/ChatInput/Desktop/ContextContainer/SelectionItem.tsxindex c01bb83b939..fd4c69729a0 100644--- a/src/features/ChatInput/Desktop/ContextContainer/SelectionItem.tsx+++ b/src/features/ChatInput/Desktop/ContextContainer/SelectionItem.tsx@@ -4,6 +4,7 @@ import { createStaticStyles, cssVar } from 'antd-style';import { Code2Icon, TextIcon } from 'lucide-react';import { memo, useMemo } from 'react';+import { useChatInputStore } from '@/features/ChatInput/store';import { useFileStore } from '@/store/file';const styles = createStaticStyles(({ css }) => ({@@ -104,6 +105,7 @@ const getLocationText = ({const SelectionItem = memo<ChatContextContent>(({ content, filePath, id, lineRange, preview, source, title }) => {+ const contextSelectionKey = useChatInputStore((s) => s.contextSelectionKey);const [removeSelection] = useFileStore((s) => [s.removeChatContextSelection]);const displayText = useMemo(@@ -149,7 +151,9 @@ const SelectionItem = memo<ChatContextContent>(closableicon={isCodeSelection ? <Code2Icon size={16} /> : <TextIcon size={16} />}size={'large'}- onClose={() => removeSelection(id)}+ onClose={() => {+ if (contextSelectionKey) removeSelection({ contextKey: contextSelectionKey, id });+ }}><Tooltip title={tooltip}><span className={styles.name}>{displayText}</span>diff --git a/src/features/ChatInput/Desktop/index.tsx b/src/features/ChatInput/Desktop/index.tsxindex 9e4f35f5ad5..f3d62e5d7f4 100644--- a/src/features/ChatInput/Desktop/index.tsx+++ b/src/features/ChatInput/Desktop/index.tsx@@ -135,7 +135,10 @@ const DesktopChatInput = memo<DesktopChatInputProps>(systemStatusSelectors.chatInputHeight(s),s.updateSystemStatus,]);- const hasContextSelections = useFileStore(fileChatSelectors.chatContextSelectionHasItem);+ const contextSelectionKey = useChatInputStore((s) => s.contextSelectionKey);+ const hasContextSelections = useFileStore(+ fileChatSelectors.chatContextSelectionHasItem(contextSelectionKey),+ );const hasFiles = useFileStore(fileChatSelectors.chatUploadFileListHasItem);const [slashMenuRef, expand, showTypoBar, editor, leftActions] = useChatInputStore((s) => [s.slashMenuRef,diff --git a/src/features/ChatInput/StoreUpdater.tsx b/src/features/ChatInput/StoreUpdater.tsxindex d6c0ba21510..515f9a42e06 100644--- a/src/features/ChatInput/StoreUpdater.tsx+++ b/src/features/ChatInput/StoreUpdater.tsx@@ -18,6 +18,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(({agentId,chatInputEditorRef,+ contextSelectionKey,contextWindowMessages,draftKey,feature = DEFAULT_CHAT_INPUT_FEATURE,@@ -38,6 +39,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(const editor = useChatInputEditor();useStoreUpdater('agentId', agentId);+ useStoreUpdater('contextSelectionKey', contextSelectionKey);useStoreUpdater('contextWindowMessages', contextWindowMessages);useStoreUpdater('draftKey', draftKey);useStoreUpdater('mobile', mobile!);diff --git a/src/features/ChatInput/store/initialState.ts b/src/features/ChatInput/store/initialState.tsindex bc23643c7b4..b2fc89b868f 100644--- a/src/features/ChatInput/store/initialState.ts+++ b/src/features/ChatInput/store/initialState.ts@@ -56,6 +56,7 @@ export const DEFAULT_CHAT_INPUT_FEATURE = {export interface PublicState {agentId?: string;allowExpand?: boolean;+ contextSelectionKey?: string;contextWindowMessages?: ContextWindowMessage[];draftKey?: string;expand?: boolean;diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsxindex c24e7bbafe0..d582d895639 100644--- a/src/features/Conversation/ChatInput/index.tsx+++ b/src/features/Conversation/ChatInput/index.tsx@@ -184,7 +184,7 @@ const ChatInput = memo<ChatInputProps>(const storeApi = useConversationStoreApi();const dbMessages = useConversationStore(dataSelectors.dbMessages);const context = useConversationStore((s) => s.context);- const draftKey = useMemo(() => messageMapKey(context), [context]);+ const contextKey = useMemo(() => messageMapKey(context), [context]);const [agentId, inputMessage, sendMessage, stopGenerating] = useConversationStore((s) => [s.context.agentId,s.inputMessage,@@ -255,7 +255,7 @@ const ChatInput = memo<ChatInputProps>(// File store - for UI state only (disabled button, etc.)const fileList = useFileStore(fileChatSelectors.chatUploadFileList);- const contextList = useFileStore(fileChatSelectors.chatContextSelections);+ const contextList = useFileStore(fileChatSelectors.chatContextSelections(contextKey));const isUploadingFiles = useFileStore(fileChatSelectors.isUploadingFiles);// Queue state@@ -308,7 +308,7 @@ const ChatInput = memo<ChatInputProps>(const fileStore = useFileStore.getState();const currentFileList = fileChatSelectors.chatUploadFileList(fileStore);const currentIsUploading = fileChatSelectors.isUploadingFiles(fileStore);- const currentContextList = fileChatSelectors.chatContextSelections(fileStore);+ const currentContextList = fileChatSelectors.chatContextSelections(contextKey)(fileStore);if (currentIsUploading) return;@@ -327,7 +327,7 @@ const ChatInput = memo<ChatInputProps>(const clearComposer = () => {clearContent();fileStore.clearChatUploadFileList();- fileStore.clearChatContextSelections();+ fileStore.clearChatContextSelections(contextKey);};// A deferred send was armed from the composer (see `scheduledSendAt`):@@ -356,10 +356,13 @@ const ChatInput = memo<ChatInputProps>(editorData,files: currentFileList,message,+ onPreflightFailure: () => {+ useFileStore.getState().restoreChatContextSelections(contextKey, currentContextList);+ },pageSelections,});},- [sendMessage, storeApi, disableQueue, disableSend, isInputQueueBlocked],+ [contextKey, sendMessage, storeApi, disableQueue, disableSend, isInputQueueBlocked],);const sendButtonProps: SendButtonProps = {@@ -439,8 +442,9 @@ const ChatInput = memo<ChatInputProps>(<ChatInputProvideragentId={agentId}allowExpand={allowExpand}+ contextSelectionKey={contextKey}contextWindowMessages={contextWindowMessages}- draftKey={draftKey}+ draftKey={contextKey}feature={feature}getMessages={getMessages}leftActions={leftActions}diff --git a/src/features/Conversation/ConversationProvider.tsx b/src/features/Conversation/ConversationProvider.tsxindex 4e47580088b..6570977d065 100644--- a/src/features/Conversation/ConversationProvider.tsx+++ b/src/features/Conversation/ConversationProvider.tsx@@ -14,8 +14,10 @@ import { createStore, Provider } from './store';import StoreUpdater from './StoreUpdater';import {type ActionsBarConfig,+ type ComposerTarget,type ConversationContext,type ConversationHooks,+ createComposerTarget,type MessagesChangeMeta,type OperationState,} from './types';@@ -40,6 +42,11 @@ export interface ConversationProviderProps {*/actionsBar?: ActionsBarConfig;children: ReactNode;+ /**+ * Explicit composer capability for this surface. Defaults to this+ * conversation's own context key.+ */+ composerTarget?: ComposerTarget;/*** Conversation context (data coordinates)*/@@ -95,6 +102,7 @@ export const ConversationProvider = memo<ConversationProviderProps>(({actionsBar,children,+ composerTarget,context,hooks = {},hasInitMessages,@@ -104,6 +112,10 @@ export const ConversationProvider = memo<ConversationProviderProps>(skipFetch,}) => {const contextKey = useMemo(() => messageMapKey(context), [context]);+ const resolvedComposerTarget = useMemo(+ () => composerTarget ?? createComposerTarget(contextKey),+ [composerTarget, contextKey],+ );log('[Provider] render | contextKey=%s | messagesCount=%d | hasInitMessages=%s | skipFetch=%s',@@ -115,11 +127,20 @@ export const ConversationProvider = memo<ConversationProviderProps>(return (<Provider- createStore={() => createStore({ context, hooks, initialMessages: messages, skipFetch })}key={contextKey}+ createStore={() =>+ createStore({+ composerTarget: resolvedComposerTarget,+ context,+ hooks,+ initialMessages: messages,+ skipFetch,+ })+ }><StoreUpdateractionsBar={actionsBar}+ composerTarget={resolvedComposerTarget}context={context}hasInitMessages={hasInitMessages}hooks={hooks}diff --git a/src/features/Conversation/Messages/components/TextSelectionActionLayer/index.tsx b/src/features/Conversation/Messages/components/TextSelectionActionLayer/index.tsxindex 90625f9d996..d0e5ffcd529 100644--- a/src/features/Conversation/Messages/components/TextSelectionActionLayer/index.tsx+++ b/src/features/Conversation/Messages/components/TextSelectionActionLayer/index.tsx@@ -11,8 +11,9 @@ import { createPortal } from 'react-dom';import { useTranslation } from 'react-i18next';import { useChatStore } from '@/store/chat';-import { useFileStore } from '@/store/file';+import { fileChatSelectors, useFileStore } from '@/store/file';+import { useConversationStore } from '../../../store';import {createTextSelectionContext,getRangeFirstLineRect,@@ -67,6 +68,7 @@ const TextSelectionActionLayer = memo<TextSelectionActionLayerProps>(({ childrenconst toolbarRef = useRef<HTMLDivElement | null>(null);const [activeSelection, setActiveSelection] = useState<ActiveSelection | null>(null);+ const composerTarget = useConversationStore((s) => s.composerTarget);const addChatContextSelection = useFileStore((s) => s.addChatContextSelection);const hideToolbar = useCallback(() => {@@ -79,7 +81,7 @@ const TextSelectionActionLayer = memo<TextSelectionActionLayerProps>(({ children}, [hideToolbar]);const updateSelection = useCallback(() => {- if (disabled) {+ if (disabled || !composerTarget.writable) {hideToolbar();return;}@@ -114,7 +116,7 @@ const TextSelectionActionLayer = memo<TextSelectionActionLayerProps>(({ childrenposition: getSelectionToolbarPosition(rect, window.innerWidth),text,});- }, [disabled, hideToolbar]);+ }, [composerTarget.writable, disabled, hideToolbar]);const scheduleSelectionUpdate = useCallback(() => {window.setTimeout(updateSelection, 0);@@ -144,9 +146,11 @@ const TextSelectionActionLayer = memo<TextSelectionActionLayerProps>(({ childrenconst addSelectionToConversation = useCallback(() => {const text = activeSelection?.text;- if (!text) return;+ if (!text || !composerTarget.writable) return;- const currentSelections = useFileStore.getState().chatContextSelections;+ const currentSelections = fileChatSelectors.chatContextSelections(composerTarget.contextKey)(+ useFileStore.getState(),+ );const existing = currentSelections.find((item) => isSameTextSelectionContext(item, text));const context =existing ??@@ -156,9 +160,9 @@ const TextSelectionActionLayer = memo<TextSelectionActionLayerProps>(({ childrentitle: t('textSelection.title'),});- addChatContextSelection(context);+ addChatContextSelection({ contextKey: composerTarget.contextKey, selection: context });toast.success(t('textSelection.added'));- }, [activeSelection?.text, addChatContextSelection, t]);+ }, [activeSelection?.text, addChatContextSelection, composerTarget, t]);const handleAddToConversation = useCallback(() => {addSelectionToConversation();diff --git a/src/features/Conversation/StoreUpdater.tsx b/src/features/Conversation/StoreUpdater.tsxindex 10f4f1f5b8c..a4c573369f1 100644--- a/src/features/Conversation/StoreUpdater.tsx+++ b/src/features/Conversation/StoreUpdater.tsx@@ -2,7 +2,7 @@import { type UIChatMessage } from '@lobechat/types';import debug from 'debug';-import { memo, useEffect, useLayoutEffect, useRef } from 'react';+import { memo, useEffect, useLayoutEffect, useMemo, useRef } from 'react';import { createStoreUpdater } from 'zustand-utils';import { messageMapKey } from '@/store/chat/utils/messageMapKey';@@ -10,8 +10,10 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { useConversationStoreApi } from './store';import {type ActionsBarConfig,+ type ComposerTarget,type ConversationContext,type ConversationHooks,+ createComposerTarget,type MessagesChangeMeta,type OperationState,} from './types';@@ -23,6 +25,7 @@ export interface StoreUpdaterProps {* Actions bar configuration by message type*/actionsBar?: ActionsBarConfig;+ composerTarget?: ComposerTarget;context: ConversationContext;/*** Whether external messages have been initialized@@ -54,6 +57,7 @@ export interface StoreUpdaterProps {const StoreUpdater = memo<StoreUpdaterProps>(({actionsBar,+ composerTarget,context,hasInitMessages,hooks,@@ -66,8 +70,13 @@ const StoreUpdater = memo<StoreUpdaterProps>(const useStoreUpdater = createStoreUpdater(storeApi);const prevMessagesRef = useRef<UIChatMessage[] | undefined>(undefined);const contextKey = messageMapKey(context);+ const resolvedComposerTarget = useMemo(+ () => composerTarget ?? createComposerTarget(contextKey),+ [composerTarget, contextKey],+ );useStoreUpdater('actionsBar', actionsBar);+ useStoreUpdater('composerTarget', resolvedComposerTarget);useStoreUpdater('context', context);useStoreUpdater('hooks', hooks!);useStoreUpdater('onMessagesChange', onMessagesChange);diff --git a/src/features/Conversation/WorkingSidebar/Browser/index.tsx b/src/features/Conversation/WorkingSidebar/Browser/index.tsxindex 15eabe10f26..369ba2f22d8 100644--- a/src/features/Conversation/WorkingSidebar/Browser/index.tsx+++ b/src/features/Conversation/WorkingSidebar/Browser/index.tsx@@ -26,6 +26,7 @@ import { useChatStore } from '@/store/chat';import { useFileStore } from '@/store/file';import { useGlobalStore } from '@/store/global';+import type { ComposerTarget } from '../../types';import { BROWSER_IMPORT_BANNER_DISMISSED_STORAGE_KEY } from './const';import { useBrowserSidebarState } from './useBrowserSidebarState';import {@@ -151,11 +152,13 @@ const styles = createStaticStyles(({ css, cssVar }) => ({interface BrowserPaneProps {/** The conversation the chat input belongs to β screenshots are attached there. */agentId?: string;+ composerTarget: ComposerTarget;onMetadataChange?: (metadata: { faviconUrl?: string; title: string; url: string }) => void;sessionId: string;}-const BrowserPane = memo<BrowserPaneProps>(({ agentId, onMetadataChange, sessionId }) => {+const BrowserPane = memo<BrowserPaneProps>((props) => {+ const { agentId, composerTarget, onMetadataChange, sessionId } = props;const { t } = useTranslation('chat');const state = useBrowserSidebarState(sessionId);const [address, setAddress] = useState('');@@ -254,6 +257,8 @@ const BrowserPane = memo<BrowserPaneProps>(({ agentId, onMetadataChange, session};const pickElementContext = async () => {+ if (!composerTarget.writable) return;+setIsPicking(true);try {const result = await electronBrowserSidebarService.pickElement({@@ -266,13 +271,14 @@ const BrowserPane = memo<BrowserPaneProps>(({ agentId, onMetadataChange, session}if (result.cancelled || !result.element) return;- useFileStore.getState().addChatContextSelection(- createElementContext({+ useFileStore.getState().addChatContextSelection({+ contextKey: composerTarget.contextKey,+ selection: createElementContext({element: result.element,elementTitle: t('workingPanel.browser.context.elementTitle'),id: `browser-element-${nanoid(6)}`,}),- );+ });toast.success(t('workingPanel.browser.context.elementAdded'));focusChatInput();} catch (error) {@@ -403,7 +409,7 @@ const BrowserPane = memo<BrowserPaneProps>(({ agentId, onMetadataChange, session/>) : (<ActionIcon- disabled={!state.attached || state.isLoading}+ disabled={!state.attached || state.isLoading || !composerTarget.writable}icon={SquareDashedMousePointer}size={DESKTOP_HEADER_ICON_SMALL_SIZE}title={t('workingPanel.browser.context.pickElement')}diff --git a/src/features/Conversation/WorkingSidebar/Review/FileItem.tsx b/src/features/Conversation/WorkingSidebar/Review/FileItem.tsxindex 336acabac45..f5eb98fa720 100644--- a/src/features/Conversation/WorkingSidebar/Review/FileItem.tsx+++ b/src/features/Conversation/WorkingSidebar/Review/FileItem.tsx@@ -14,6 +14,7 @@ import { gitService } from '@/services/git';import { useFileStore } from '@/store/file';import { useGlobalStore } from '@/store/global';+import type { ComposerTarget } from '../../types';import type { DiffSelectedLineRange } from './selection';import { buildCodeContextSelection } from './selection';@@ -305,6 +306,7 @@ export const FileItemHeader = memo<FileItemHeaderProps>(FileItemHeader.displayName = 'ReviewFileItemHeader';interface FileItemBodyProps {+ composerTarget: ComposerTarget;/** Whether the Collapse panel is expanded β gates the heavy PatchDiff render. */expanded: boolean;filePath: string;@@ -320,6 +322,7 @@ interface FileItemBodyProps {const FileItemBody = memo<FileItemBodyProps>(({+ composerTarget,filePath,patch,isBinary,@@ -338,10 +341,12 @@ const FileItemBody = memo<FileItemBodyProps>(const diffOptions = useMemo(() => ({- enableGutterUtility: true,+ enableGutterUtility: composerTarget.writable,enableLineSelection: true,lineDiffType: textDiff ? ('word-alt' as const) : ('none' as const),onGutterUtilityClick: (range: DiffSelectedLineRange) => {+ if (!composerTarget.writable) return;+const selection = buildCodeContextSelection({filePath,language,@@ -353,16 +358,29 @@ const FileItemBody = memo<FileItemBodyProps>(if (!selection) return;addChatContextSelection({- ...selection,- id: `code-selection-${nanoid(6)}`,- type: 'text',+ contextKey: composerTarget.contextKey,+ selection: {+ ...selection,+ id: `code-selection-${nanoid(6)}`,+ type: 'text',+ },});toast.success(t('workingPanel.review.addSelectionToContext.success'));},overflow: wordWrap ? ('wrap' as const) : ('scroll' as const),unsafeCSS: reviewDiffUnsafeCSS,}),- [addChatContextSelection, filePath, language, patch, t, textDiff, wordWrap, workingDirectory],+ [+ addChatContextSelection,+ composerTarget,+ filePath,+ language,+ patch,+ t,+ textDiff,+ wordWrap,+ workingDirectory,+ ],);if (!expanded) return null;diff --git a/src/features/Conversation/WorkingSidebar/Review/FileRow.tsx b/src/features/Conversation/WorkingSidebar/Review/FileRow.tsxindex 23b924941cf..fae0cebc3da 100644--- a/src/features/Conversation/WorkingSidebar/Review/FileRow.tsx+++ b/src/features/Conversation/WorkingSidebar/Review/FileRow.tsx@@ -6,6 +6,7 @@ import { ChevronRightIcon } from 'lucide-react';import { AnimatePresence, m } from 'motion/react';import { type KeyboardEvent, memo, useCallback } from 'react';+import type { ComposerTarget } from '../../types';import FileItemBody, { FileItemHeader } from './FileItem';import type { ReviewMode } from './useReviewPatches';@@ -56,6 +57,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({}));interface FileRowProps {+ composerTarget: ComposerTarget;/** Scroll anchor β the tree-nav rail scrolls to `[data-file-key]` on select. */dataFileKey?: string;/** Target device the repo lives on β undefined for local desktop. */@@ -81,6 +83,7 @@ interface FileRowProps {const FileRow = memo<FileRowProps>(({+ composerTarget,dataFileKey,deviceId,entry,@@ -148,6 +151,7 @@ const FileRow = memo<FileRowProps>(><FileItemBodyexpanded+ composerTarget={composerTarget}filePath={entry.filePath}isBinary={entry.isBinary}patch={entry.patch}diff --git a/src/features/Conversation/WorkingSidebar/Review/index.tsx b/src/features/Conversation/WorkingSidebar/Review/index.tsxindex eba75ff6d02..0a595a80c72 100644--- a/src/features/Conversation/WorkingSidebar/Review/index.tsx+++ b/src/features/Conversation/WorkingSidebar/Review/index.tsx@@ -27,6 +27,7 @@ import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';import { useLocalStorageState } from '@/hooks/useLocalStorageState';import { useFetchGitBranch } from '@/store/device';+import type { ComposerTarget } from '../../types';import FileRow from './FileRow';import FileTreeNav from './FileTreeNav';import GroupHeader from './GroupHeader';@@ -55,6 +56,7 @@ const BASE_REF_OVERRIDES_STORAGE_KEY = 'lobechat-review-base-overrides';interface ReviewProps {active: boolean;+ composerTarget: ComposerTarget;/*** Target device the working directory lives on. Undefined for local desktop;* set for a remote / web-bound device so git ops route through the device RPCs.@@ -225,7 +227,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({}));const Review = memo<ReviewProps>(- ({ active, deviceId, onToggleTree, showTree, workingDirectory }) => {+ ({ active, composerTarget, deviceId, onToggleTree, showTree, workingDirectory }) => {const { t } = useTranslation('chat');const [mode, setMode] = useLocalStorageState<ReviewMode>(REVIEW_MODE_STORAGE_KEY, 'unstaged');// Per-repo base-ref override β when set, the branch diff compares against@@ -670,6 +672,7 @@ const Review = memo<ReviewProps>(const expanded = activeKeys.includes(key);return (<FileRow+ composerTarget={composerTarget}dataFileKey={key}deviceId={deviceId}entry={entry}diff --git a/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx b/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsxindex bc04ea9e4f7..3b7beb3c625 100644--- a/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx+++ b/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx@@ -2,6 +2,10 @@ import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'import type { MouseEvent, ReactNode } from 'react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { PortalViewType } from '@/store/chat/slices/portal/initialState';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';++import type { ComposerTarget } from '../../types';import AgentWorkingSidebar from '../index';// βββ captured RightPanel props ββββββββββββββββββββββββββββββββββββββββββββββββ@@ -58,11 +62,16 @@ const paramsSectionState = vi.hoisted(() => ({const browserPanes = vi.hoisted(() => ({current: [] as {+ composerTarget: ComposerTarget;onMetadataChange?: (metadata: { faviconUrl?: string; title: string; url: string }) => void;sessionId: string;}[],}));+const renderedReview = vi.hoisted(() => ({+ current: undefined as { composerTarget: ComposerTarget } | undefined,+}));+const localStorageState = vi.hoisted(() => ({openTabsByContext: {} as Record<string, string[]>,pinnedTabsByAgent: {} as Record<string, string[]>,@@ -76,9 +85,14 @@ const dropdownMenuState = vi.hoisted(() => ({const workspace = vi.hoisted(() => ({ id: undefined as string | undefined }));const chatStore = vi.hoisted(() => ({+ activeAgentId: undefined as string | undefined,+ activeGroupId: undefined as string | undefined,+ activeThreadId: undefined as string | undefined,activeTopicId: undefined as string | undefined,openTopicComments: vi.fn(),- portalStack: [] as Array<{ topicId?: string; type: string }>,+ portalStack: [] as Array<{ startMessageId?: string; threadId?: string; type: string }>,+ showPortal: false,+ threadMaps: {} as Record<string, any[]>,}));const globalStore = vi.hoisted(() => ({@@ -111,7 +125,12 @@ vi.mock('../Files', () => ({return <div data-testid="files" />;},}));-vi.mock('../Review', () => ({ default: () => <div /> }));+vi.mock('../Review', () => ({+ default: (props: { composerTarget: ComposerTarget }) => {+ renderedReview.current = props;+ return <div />;+ },+}));vi.mock('../ProgressSection', () => ({ default: () => <div /> }));vi.mock('../ResourcesSection', () => ({ default: () => <div /> }));vi.mock('../ParamsSection', () => ({@@ -329,8 +348,13 @@ beforeEach(() => {localStorageState.openTabsByContext = { 'draft:default:none': ['params'] };localStorageState.pinnedTabsByAgent = {};workspace.id = undefined;+ chatStore.activeAgentId = undefined;+ chatStore.activeGroupId = undefined;+ chatStore.activeThreadId = undefined;chatStore.activeTopicId = undefined;chatStore.portalStack = [];+ chatStore.showPortal = false;+ chatStore.threadMaps = {};chatStore.openTopicComments.mockReset();agentStore.activeAgentId = undefined;agentStore.isHeterogeneous = false;@@ -339,6 +363,7 @@ beforeEach(() => {effectiveConfig.workspaceScoped = false;platform.isDesktop = true;filesProps.current = undefined;+ renderedReview.current = undefined;reviewState.repoType = undefined;reviewState.setRepoType = undefined;reviewState.showTree = false;@@ -820,6 +845,63 @@ describe('AgentWorkingSidebar β tab strip', () => {);});+ it('routes Browser and Review context selections to the open portal thread', async () => {+ const agentId = 'agent';+ const topicId = 'topic';+ const threadId = 'thread';+ const expectedKey = messageMapKey({ agentId, threadId, topicId });+ agentStore.activeAgentId = agentId;+ chatStore.activeAgentId = agentId;+ chatStore.activeTopicId = topicId;+ chatStore.portalStack = [{ threadId, type: PortalViewType.Thread }];+ chatStore.showPortal = true;+ chatStore.threadMaps = { [topicId]: [{ agentId, id: threadId, topicId }] };+ reviewState.repoType = 'git';+ reviewState.workingDirectory = '/repo';+ localStorageState.openTabsByContext = { [`topic:${topicId}`]: ['browser'] };+ globalStore.status.workingSidebarTab = 'browser';++ render(<AgentWorkingSidebar />);++ await waitFor(() => expect(browserPanes.current.at(-1)).toBeDefined());+ expect(browserPanes.current.at(-1)?.composerTarget).toEqual({+ contextKey: expectedKey,+ writable: true,+ });+ expect(renderedReview.current?.composerTarget).toEqual({+ contextKey: expectedKey,+ writable: true,+ });+ });++ it('marks Browser and Review context actions read-only for a subagent thread', async () => {+ const topicId = 'topic';+ const threadId = 'subagent-thread';+ chatStore.activeAgentId = 'agent';+ chatStore.activeTopicId = topicId;+ chatStore.portalStack = [{ threadId, type: PortalViewType.Thread }];+ chatStore.showPortal = true;+ chatStore.threadMaps = {+ [topicId]: [{ id: threadId, metadata: { sourceToolCallId: 'tool-call' }, topicId }],+ };+ reviewState.repoType = 'git';+ reviewState.workingDirectory = '/repo';+ localStorageState.openTabsByContext = { [`topic:${topicId}`]: ['browser'] };+ globalStore.status.workingSidebarTab = 'browser';++ render(<AgentWorkingSidebar />);++ await waitFor(() => expect(browserPanes.current.at(-1)).toBeDefined());+ expect(browserPanes.current.at(-1)?.composerTarget).toEqual({+ reason: 'read-only',+ writable: false,+ });+ expect(renderedReview.current?.composerTarget).toEqual({+ reason: 'read-only',+ writable: false,+ });+ });+it('uses browser page metadata for the tab title and favicon', async () => {localStorageState.openTabsByContext = { 'draft:default:none': ['browser'] };globalStore.status.workingSidebarTab = 'browser';diff --git a/src/features/Conversation/WorkingSidebar/index.tsx b/src/features/Conversation/WorkingSidebar/index.tsxindex 68737aa2271..7ba76d7797c 100644--- a/src/features/Conversation/WorkingSidebar/index.tsx+++ b/src/features/Conversation/WorkingSidebar/index.tsx@@ -54,14 +54,16 @@ import type { NativeContextMenuItem } from '@/libs/contextMenu/types';import { useAgentStore } from '@/store/agent';import { agentSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';-import { chatPortalSelectors } from '@/store/chat/selectors';+import { chatPortalSelectors, portalThreadSelectors } from '@/store/chat/selectors';import { PortalViewType } from '@/store/chat/slices/portal/initialState';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { useElectronStore } from '@/store/electron';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';import { useUserStore } from '@/store/user';import { labPreferSelectors } from '@/store/user/selectors';+import { type ComposerTarget, createComposerTarget, resolveThreadComposerTarget } from '../types';import Files from './Files';import { sidebarWidthBudget } from './fitsBesidePortal';import Overview from './Overview';@@ -196,11 +198,56 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })]);const activeAgentId = useAgentStore((s) => s.activeAgentId);const workspaceId = useActiveWorkspaceId();- const [topicId, currentPortalView, portalOpen, openTopicComments] = useChatStore((s) => [+ const [+ topicId,+ currentPortalView,+ portalOpen,+ openTopicComments,+ portalThread,+ chatAgentId,+ chatGroupId,+ chatThreadId,+ ] = useChatStore((s) => [s.activeTopicId,chatPortalSelectors.currentView(s),chatPortalSelectors.showStandalonePortal(s),s.openTopicComments,+ portalThreadSelectors.portalCurrentThread(s),+ s.activeAgentId,+ s.activeGroupId,+ s.activeThreadId,+ ]);+ const composerTarget = useMemo<ComposerTarget>(() => {+ if (!portalOpen || currentPortalView?.type !== PortalViewType.Thread) {+ return createComposerTarget(+ messageMapKey({+ agentId: chatAgentId,+ groupId: chatGroupId,+ threadId: chatThreadId,+ topicId,+ }),+ );+ }++ return resolveThreadComposerTarget({+ contextKey: messageMapKey({+ agentId: chatAgentId,+ isNew: !currentPortalView.threadId,+ scope: 'thread',+ threadId: currentPortalView.threadId,+ topicId,+ }),+ metadataResolved: !currentPortalView.threadId || !!portalThread,+ sourceToolCallId: portalThread?.metadata?.sourceToolCallId,+ });+ }, [+ chatAgentId,+ chatGroupId,+ chatThreadId,+ currentPortalView,+ portalOpen,+ portalThread,+ topicId,]);const portalWidth = getPortalViewWidth({legacyWidth: legacyPortalWidth,@@ -880,6 +927,7 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })<Flexbox className={activeTab === 'review' ? styles.pane : styles.paneHidden}><Reviewactive={activeTab === 'review'}+ composerTarget={composerTarget}deviceId={remoteDeviceId}showTree={showReviewTree}workingDirectory={workingDirectory}@@ -906,6 +954,7 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })><BrowserPaneagentId={activeAgentId}+ composerTarget={composerTarget}sessionId={sessionId}onMetadataChange={(metadata) => {const metadataKey = `${openTabsContextKey}:${tab}`;diff --git a/src/features/Conversation/store/action.ts b/src/features/Conversation/store/action.tsindex b23ab648a38..06a2e59acd6 100644--- a/src/features/Conversation/store/action.ts+++ b/src/features/Conversation/store/action.ts@@ -2,7 +2,14 @@ import { parse } from '@lobechat/conversation-flow';import { type UIChatMessage } from '@lobechat/types';import { type StateCreator } from 'zustand/vanilla';-import { type ConversationContext, type ConversationHooks } from '../types';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';++import {+ type ComposerTarget,+ type ConversationContext,+ type ConversationHooks,+ createComposerTarget,+} from '../types';import { type State } from './initialState';import { initialState } from './initialState';import { type DataAction } from './slices/data/action';@@ -37,6 +44,7 @@ export type ConversationStore = Store;// ===== Store Creator =====export interface CreateStoreParams {+ composerTarget?: ComposerTarget;context: ConversationContext;hooks?: ConversationHooks;/**@@ -61,9 +69,10 @@ type CreateStore = () => StateCreator<Store, [['zustand/devtools', never]]>;export const createStoreAction: CreateStore =- ({ context, hooks = {}, initialMessages, skipFetch }) =>+ ({ composerTarget, context, hooks = {}, initialMessages, skipFetch }) =>(...params) => ({...initialState,+ composerTarget: composerTarget ?? createComposerTarget(messageMapKey(context)),context,hooks,skipFetch,diff --git a/src/features/Conversation/store/initialState.ts b/src/features/Conversation/store/initialState.tsindex d5b5ece9274..973116d1906 100644--- a/src/features/Conversation/store/initialState.ts+++ b/src/features/Conversation/store/initialState.ts@@ -2,6 +2,7 @@ import { type UIChatMessage } from '@lobechat/types';import {type ActionsBarConfig,+ type ComposerTarget,type ConversationContext,type ConversationHooks,type MessagesChangeMeta,@@ -23,6 +24,11 @@ export interface State extends DataState, InputState, MessageStateState, VirtuaL*/actionsBar?: ActionsBarConfig;+ /**+ * Composer capability for this mounted conversation surface+ */+ composerTarget: ComposerTarget;+/*** Conversation context (data coordinates)*/@@ -60,6 +66,7 @@ export const initialState: State = {...virtuaListInitialState,actionsBar: undefined,+ composerTarget: { reason: 'unresolved', writable: false },context: {agentId: '',threadId: null,diff --git a/src/features/Conversation/store/selectors.test.ts b/src/features/Conversation/store/selectors.test.tsindex 559f938072b..7edf624b140 100644--- a/src/features/Conversation/store/selectors.test.ts+++ b/src/features/Conversation/store/selectors.test.ts@@ -28,6 +28,7 @@ const createMockState = (overrides: Partial<State> = {}): State => ({visibleItems: new Map(),// Core state+ composerTarget: { contextKey: 'main_session-1_new', writable: true },context: {agentId: 'session-1',topicId: null,diff --git a/src/features/Conversation/store/slices/message/action/sendMessage.ts b/src/features/Conversation/store/slices/message/action/sendMessage.tsindex 75e8e76be70..8cbaef3533a 100644--- a/src/features/Conversation/store/slices/message/action/sendMessage.ts+++ b/src/features/Conversation/store/slices/message/action/sendMessage.ts@@ -5,6 +5,10 @@ import { useChatStore } from '@/store/chat';import { isLocalOnlyMessage } from '../../../../utils/localMessages';import { type Store as ConversationStore } from '../../../action';+interface ConversationSendMessageParams extends SendMessageParams {+ onPreflightFailure?: () => void;+}+/*** Send a message in this conversation*@@ -19,15 +23,22 @@ export const sendMessage = (set: (partial: Partial<ConversationStore>) => void,get: () => ConversationStore,) => {- return async (params: SendMessageParams) => {+ return async (params: ConversationSendMessageParams) => {const state = get();const { context, editor, hooks, displayMessages } = state;// ===== Hook: onBeforeSendMessage =====if (hooks.onBeforeSendMessage) {- const result = await hooks.onBeforeSendMessage(params);+ let result: boolean | void;+ try {+ result = await hooks.onBeforeSendMessage(params);+ } catch (error) {+ params.onPreflightFailure?.();+ throw error;+ }if (result === false) {console.info('[ConversationStore] sendMessage blocked by onBeforeSendMessage hook');+ params.onPreflightFailure?.();return;}}diff --git a/src/features/Conversation/types/composerTarget.ts b/src/features/Conversation/types/composerTarget.tsnew file mode 100644index 00000000000..582a08d8776--- /dev/null+++ b/src/features/Conversation/types/composerTarget.ts@@ -0,0 +1,29 @@+export type ComposerTarget =+ | {+ contextKey: string;+ writable: true;+ }+ | {+ reason: 'no-composer' | 'read-only' | 'unresolved';+ writable: false;+ };++export const createComposerTarget = (contextKey: string): ComposerTarget => ({+ contextKey,+ writable: true,+});++export const resolveThreadComposerTarget = ({+ contextKey,+ metadataResolved,+ sourceToolCallId,+}: {+ contextKey: string;+ metadataResolved: boolean;+ sourceToolCallId?: string;+}): ComposerTarget => {+ if (!metadataResolved) return { reason: 'unresolved', writable: false };+ if (sourceToolCallId) return { reason: 'read-only', writable: false };++ return createComposerTarget(contextKey);+};diff --git a/src/features/Conversation/types/index.ts b/src/features/Conversation/types/index.tsindex 9ef4e5316ac..95491e4096b 100644--- a/src/features/Conversation/types/index.ts+++ b/src/features/Conversation/types/index.ts@@ -1,3 +1,4 @@+export * from './composerTarget';export * from './context';export * from './hooks';export * from './operation';diff --git a/src/features/Home/InputArea/EditorInput.tsx b/src/features/Home/InputArea/EditorInput.tsxindex a4d046fcf36..96baa905e2e 100644--- a/src/features/Home/InputArea/EditorInput.tsx+++ b/src/features/Home/InputArea/EditorInput.tsx@@ -24,6 +24,7 @@ const ACTION_BAR_INSET = 8;export interface HomeEditorInputProps {agentId?: string;+ contextSelectionKey: string;initialValue: string;isAgentConfigLoading: boolean;loading: boolean;@@ -37,6 +38,7 @@ export interface HomeEditorInputProps {const HomeEditorInput = memo<HomeEditorInputProps>(({agentId,+ contextSelectionKey,initialValue,isAgentConfigLoading,loading,@@ -70,6 +72,7 @@ const HomeEditorInput = memo<HomeEditorInputProps>(<ChatInputProvideragentId={agentId}allowExpand={false}+ contextSelectionKey={contextSelectionKey}leftActions={leftActions}rightActions={rightActions}slashPlacement="bottom"diff --git a/src/features/Home/InputArea/index.tsx b/src/features/Home/InputArea/index.tsxindex f14e277ab81..6e5a9e2cabe 100644--- a/src/features/Home/InputArea/index.tsx+++ b/src/features/Home/InputArea/index.tsx@@ -35,7 +35,7 @@ interface InputAreaProps {const InputArea = ({ inputValue, mode, onInputValueChange, onModeChange }: InputAreaProps) => {const { t } = useTranslation('home');- const { loading, send, agentId } = useSend(mode);+ const { agentId, contextSelectionKey, loading, send } = useSend(mode);// Subscribe to the SWR key so `internal_refreshAgentConfig`'s `mutate(...)`// has a listener after toggleFile / toggleKnowledgeBase β otherwise the// Library submenu doesn't reflect server-side toggles. Pass `agentId`@@ -79,6 +79,7 @@ const InputArea = ({ inputValue, mode, onInputValueChange, onModeChange }: Input<div className={styles.inputSlot}><EditorSlotagentId={agentId}+ contextSelectionKey={contextSelectionKey}initialValue={inputValue}isAgentConfigLoading={isAgentConfigLoading}loading={loading}diff --git a/src/features/Home/InputArea/useSend.test.ts b/src/features/Home/InputArea/useSend.test.tsindex 23a06730d9b..3d7547750c4 100644--- a/src/features/Home/InputArea/useSend.test.ts+++ b/src/features/Home/InputArea/useSend.test.ts@@ -17,6 +17,7 @@ const sendMessageMock = vi.hoisted(() => vi.fn());const clearContentMock = vi.hoisted(() => vi.fn());const clearChatUploadFileListMock = vi.hoisted(() => vi.fn());const clearChatContextSelectionsMock = vi.hoisted(() => vi.fn());+const restoreChatContextSelectionsMock = vi.hoisted(() => vi.fn());const createTaskMock = vi.hoisted(() => vi.fn());const runTaskMock = vi.hoisted(() => vi.fn());const toggleTaskAgentPanelMock = vi.hoisted(() => vi.fn());@@ -32,10 +33,11 @@ const chatState = vi.hoisted(() => ({}));const fileState = vi.hoisted(() => ({- chatContextSelections: [] as any[],+ chatContextSelectionsByContext: {} as Record<string, any[]>,chatUploadFileList: [],clearChatContextSelections: clearChatContextSelectionsMock,clearChatUploadFileList: clearChatUploadFileListMock,+ restoreChatContextSelections: restoreChatContextSelectionsMock,}));const homeState = vi.hoisted(() => ({@@ -155,7 +157,8 @@ vi.mock('@/store/file', () => {return {fileChatSelectors: {- chatContextSelections: (state: typeof fileState) => state.chatContextSelections,+ chatContextSelections: (contextKey: string) => (state: typeof fileState) =>+ state.chatContextSelectionsByContext[contextKey] ?? [],chatUploadFileList: (state: typeof fileState) => state.chatUploadFileList,},useFileStore,@@ -181,6 +184,7 @@ describe('Home InputArea useSend', () => {clearContentMock.mockReset();clearChatUploadFileListMock.mockReset();clearChatContextSelectionsMock.mockReset();+ restoreChatContextSelectionsMock.mockReset();createTaskMock.mockReset();runTaskMock.mockReset();toggleTaskAgentPanelMock.mockReset();@@ -188,7 +192,7 @@ describe('Home InputArea useSend', () => {homeDailyBriefState.advance.mockReset();homeDailyBriefState.currentPair = undefined;chatState.inputMessage = 'hello';- fileState.chatContextSelections = [];+ fileState.chatContextSelectionsByContext = {};fileState.chatUploadFileList = [];homeState.inputActiveMode = null;homeState.ungroupedAgents = [];@@ -364,6 +368,9 @@ describe('Home InputArea useSend', () => {const sentPayload = sendMessageMock.mock.calls[0][0];+ sentPayload.onPreflightFailure();+ expect(restoreChatContextSelectionsMock).toHaveBeenCalledWith('home:chat:agt_inbox', []);+await act(async () => {await sentPayload.onTopicCreated('tpc_created');});@@ -451,18 +458,20 @@ describe('Home InputArea useSend', () => {it('passes context selections through starter agent mode sends', async () => {homeState.inputActiveMode = 'agent';activeWorkspaceSlugMock.value = 'team';- fileState.chatContextSelections = [- {- content: 'const selected = true;',- filePath: 'src/example.ts',- id: 'code-selection',- lineRange: { endLine: 12, startLine: 10 },- preview: 'src/example.ts:10-12',- source: 'code',- title: 'src/example.ts:10-12',- workingDirectory: '/repo',- },- ];+ fileState.chatContextSelectionsByContext = {+ 'home:chat:agt_inbox': [+ {+ content: 'const selected = true;',+ filePath: 'src/example.ts',+ id: 'code-selection',+ lineRange: { endLine: 12, startLine: 10 },+ preview: 'src/example.ts:10-12',+ source: 'code',+ title: 'src/example.ts:10-12',+ workingDirectory: '/repo',+ },+ ],+ };const { result } = renderHook(() => useSend());const params: Parameters<SendButtonHandler>[0] = {@@ -490,6 +499,6 @@ describe('Home InputArea useSend', () => {workspaceSlug: 'team',}),);- expect(clearChatContextSelectionsMock).toHaveBeenCalledTimes(1);+ expect(clearChatContextSelectionsMock).toHaveBeenCalledWith('home:chat:agt_inbox');});});diff --git a/src/features/Home/InputArea/useSend.ts b/src/features/Home/InputArea/useSend.tsindex db5e467bad6..9ee18c3ecac 100644--- a/src/features/Home/InputArea/useSend.ts+++ b/src/features/Home/InputArea/useSend.ts@@ -62,6 +62,7 @@ export const useSend = (mode: HomeMode = 'chat') => {const sendMessage = useChatStore((s) => s.sendMessage);const clearChatUploadFileList = useFileStore((s) => s.clearChatUploadFileList);const clearChatContextSelections = useFileStore((s) => s.clearChatContextSelections);+ const restoreChatContextSelections = useFileStore((s) => s.restoreChatContextSelections);const homeInputLoading = useHomeStore((s) => s.homeInputLoading);const createTask = useTaskStore((s) => s.createTask);@@ -73,6 +74,7 @@ export const useSend = (mode: HomeMode = 'chat') => {const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);const { agentId: selectedAgentId } = useResolvedHomeAgentId();const agentId = selectedAgentId;+ const contextSelectionKey = `home:${mode}:${selectedAgentId ?? 'unresolved'}`;const { allowed: canCreateContent } = usePermission('create_content');const agentVisibility = useAgentStore((s) =>selectedAgentId ? s.agentMap[selectedAgentId]?.visibility : undefined,@@ -96,7 +98,9 @@ export const useSend = (mode: HomeMode = 'chat') => {// cache catches up and the empty-message guard would bail incorrectly.const typed = (getMarkdownContent?.() ?? inputMessage ?? '').trim();const fileList = fileChatSelectors.chatUploadFileList(useFileStore.getState());- const contextList = fileChatSelectors.chatContextSelections(useFileStore.getState());+ const contextList = fileChatSelectors.chatContextSelections(contextSelectionKey)(+ useFileStore.getState(),+ );const { sendAsAgent, sendAsGroup, sendAsWrite, sendAsResearch, inputActiveMode } =useHomeStore.getState();@@ -238,6 +242,9 @@ export const useSend = (mode: HomeMode = 'chat') => {editorData,files: fileList,message,+ onPreflightFailure: () => {+ restoreChatContextSelections(contextSelectionKey, contextList);+ },onTopicCreated: (topicId) => {router.replace(AGENT_CHAT_TOPIC_URL(selectedAgentId, topicId, false));},@@ -256,7 +263,7 @@ export const useSend = (mode: HomeMode = 'chat') => {// editor, files and context are one unit from the user's perspective.if (submitted) {clearChatUploadFileList();- clearChatContextSelections();+ clearChatContextSelections(contextSelectionKey);mainInputEditor?.clearContent();}setIsSubmitting(false);@@ -267,7 +274,9 @@ export const useSend = (mode: HomeMode = 'chat') => {activeWorkspaceId,sendMessage,clearChatContextSelections,+ restoreChatContextSelections,clearChatUploadFileList,+ contextSelectionKey,router,currentPair,mode,@@ -284,6 +293,7 @@ export const useSend = (mode: HomeMode = 'chat') => {return {agentId,+ contextSelectionKey,loading: homeInputLoading || isSubmitting,send,};diff --git a/src/features/PageEditor/EditorCanvas/index.tsx b/src/features/PageEditor/EditorCanvas/index.tsxindex 2417d75c4fb..db7a1ed25f8 100644--- a/src/features/PageEditor/EditorCanvas/index.tsx+++ b/src/features/PageEditor/EditorCanvas/index.tsx@@ -6,6 +6,7 @@ import { type CSSProperties, useMemo } from 'react';import { memo } from 'react';import { useTranslation } from 'react-i18next';+import type { ComposerTarget } from '@/features/Conversation/types';import { EditorCanvas as SharedEditorCanvas } from '@/features/EditorCanvas';import { usePageEditorStore } from '../store';@@ -14,11 +15,12 @@ import { useAskCopilotItem } from './useAskCopilotItem';import { useSlashItems } from './useSlashItems';interface EditorCanvasProps {+ askCopilotTarget?: ComposerTarget;placeholder?: string;style?: CSSProperties;}-const EditorCanvas = memo<EditorCanvasProps>(({ placeholder, style }) => {+const EditorCanvas = memo<EditorCanvasProps>(({ askCopilotTarget, placeholder, style }) => {const { t } = useTranslation(['file', 'ui']);const editable = usePageEditable();@@ -26,7 +28,7 @@ const EditorCanvas = memo<EditorCanvasProps>(({ placeholder, style }) => {const documentId = usePageEditorStore((s) => s.documentId);const slashItems = useSlashItems();- const askCopilotItem = useAskCopilotItem(editor);+ const askCopilotItem = useAskCopilotItem(editor, askCopilotTarget);const extraPlugins = useMemo(() => [Editor.withProps(ReactBlockPlugin, { anchorPadding: 0 })],diff --git a/src/features/PageEditor/EditorCanvas/useAskCopilotItem.tsx b/src/features/PageEditor/EditorCanvas/useAskCopilotItem.tsxindex c64f88bddf8..99b82439ae2 100644--- a/src/features/PageEditor/EditorCanvas/useAskCopilotItem.tsx+++ b/src/features/PageEditor/EditorCanvas/useAskCopilotItem.tsx@@ -10,6 +10,8 @@ import { createStaticStyles, cssVar } from 'antd-style';import { useMemo } from 'react';import { useTranslation } from 'react-i18next';+import { useConversationStore } from '@/features/Conversation/store';+import type { ComposerTarget } from '@/features/Conversation/types';import { useFileStore } from '@/store/file';import { usePageAgentPanelControl } from '../RightPanel/OverrideContext';@@ -26,15 +28,20 @@ const styles = createStaticStyles(({ css }) => ({`,}));-export const useAskCopilotItem = (editor: IEditor | undefined): ChatInputActionsProps['items'] => {+export const useAskCopilotItem = (+ editor: IEditor | undefined,+ explicitComposerTarget?: ComposerTarget,+): ChatInputActionsProps['items'] => {const { t } = useTranslation('common');+ const providerComposerTarget = useConversationStore((s) => s.composerTarget);+ const composerTarget = explicitComposerTarget ?? providerComposerTarget;const addSelectionContext = useFileStore((s) => s.addChatContextSelection);const pageId = usePageEditorStore((s) => s.documentId);const setRightPanelMode = usePageEditorStore((s) => s.setRightPanelMode);const { toggle: togglePageAgentPanel } = usePageAgentPanelControl();return useMemo(() => {- if (!editor) return [];+ if (!editor || !composerTarget.writable) return [];const label = t('cmdk.askLobeAI');@@ -66,13 +73,16 @@ export const useAskCopilotItem = (editor: IEditor | undefined): ChatInputActions// Store action handles deduplicationaddSelectionContext({- content,- format,- id: `selection-${nanoid(6)}`,- pageId,- preview,- title: 'Selection',- type: 'text',+ contextKey: composerTarget.contextKey,+ selection: {+ content,+ format,+ id: `selection-${nanoid(6)}`,+ pageId,+ preview,+ title: 'Selection',+ type: 'text',+ },});// Open right panel if not opened@@ -103,5 +113,13 @@ export const useAskCopilotItem = (editor: IEditor | undefined): ChatInputActionsonClick: () => {},},];- }, [addSelectionContext, editor, pageId, setRightPanelMode, t, togglePageAgentPanel]);+ }, [+ addSelectionContext,+ composerTarget,+ editor,+ pageId,+ setRightPanelMode,+ t,+ togglePageAgentPanel,+ ]);};diff --git a/src/features/PageEditor/PageEditor.tsx b/src/features/PageEditor/PageEditor.tsxindex ceed5e8a98b..5280b2e9022 100644--- a/src/features/PageEditor/PageEditor.tsx+++ b/src/features/PageEditor/PageEditor.tsx@@ -7,6 +7,7 @@ import type { CSSProperties, FC, ReactNode, UIEvent } from 'react';import { memo, useCallback, useEffect, useRef } from 'react';import { CONVERSATION_MIN_WIDTH } from '@/const/layoutTokens';+import type { ComposerTarget } from '@/features/Conversation/types';import DiffAllToolbar from '@/features/EditorCanvas/DiffAllToolbar';import PageMetaBar from '@/features/PageEditor/PageMetaBar';import WideScreenContainer from '@/features/WideScreenContainer';@@ -99,6 +100,8 @@ const overrideStyles = createStaticStyles(({ css }) => ({}));interface PageEditorProps {+ /** Composer that receives selections created by the Ask Copilot toolbar item. */+ askCopilotTarget?: ComposerTarget;emoji?: string;/*** When true, the header spans the full editor width above the body and the@@ -138,12 +141,14 @@ interface PageEditorProps {}interface PageEditorCanvasProps {+ askCopilotTarget?: ComposerTarget;fullWidthHeader?: boolean;header?: PageEditorHeader;rightPanel?: boolean;}-const PageEditorCanvas = memo<PageEditorCanvasProps>(({ header, fullWidthHeader, rightPanel }) => {+const PageEditorCanvas = memo<PageEditorCanvasProps>((props) => {+ const { askCopilotTarget, header, fullWidthHeader, rightPanel } = props;const showRightPanel = rightPanel !== false;const editable = usePageEditable();const editor = usePageEditorStore((s) => s.editor);@@ -309,7 +314,7 @@ const PageEditorCanvas = memo<PageEditorCanvasProps>(({ header, fullWidthHeader,{/* Prominent in-body notice when another member holds the lock; thecompact status badge lives in the Header (EditingIndicator). */}<LockedAlert />- <EditorCanvas />+ <EditorCanvas askCopilotTarget={askCopilotTarget} /></Flexbox></WideScreenContainer></Flexbox>@@ -348,6 +353,7 @@ const PageEditorCanvas = memo<PageEditorCanvasProps>(({ header, fullWidthHeader,* A reusable component. Should NOT depend on context.*/export const PageEditor: FC<PageEditorProps> = ({+ askCopilotTarget,pageId,header,fullWidthHeader,@@ -399,6 +405,7 @@ export const PageEditor: FC<PageEditorProps> = ({}}><PageEditorCanvas+ askCopilotTarget={askCopilotTarget}fullWidthHeader={fullWidthHeader}header={header}rightPanel={rightPanel}diff --git a/src/features/Portal/Thread/Chat/index.tsx b/src/features/Portal/Thread/Chat/index.tsxindex b35b53b9679..417d2bb9a37 100644--- a/src/features/Portal/Thread/Chat/index.tsx+++ b/src/features/Portal/Thread/Chat/index.tsx@@ -14,6 +14,7 @@ import {} from '@/features/Conversation';import SkeletonList from '@/features/Conversation/components/SkeletonList';import { useChatFollowUp } from '@/features/Conversation/hooks/useChatFollowUp';+import { type ComposerTarget, resolveThreadComposerTarget } from '@/features/Conversation/types';import { mergeConversationHooks } from '@/features/Conversation/utils/mergeConversationHooks';import { useOperationState } from '@/hooks/useOperationState';import { useAgentStore } from '@/store/agent';@@ -31,10 +32,11 @@ import { useThreadActionsBarConfig } from './useThreadActionsBarConfig';* Must be inside ConversationProvider to access the store*/interface ThreadChatContentProps {- isSubagentThread: boolean;+ composerWritable: boolean;+ readOnly: boolean;}-const ThreadChatContent = memo<ThreadChatContentProps>(({ isSubagentThread }) => {+const ThreadChatContent = memo<ThreadChatContentProps>(({ composerWritable, readOnly }) => {// Get display messages from ConversationStore to determine thread divider position// With the new backend API, parent messages have threadId === null// and thread messages have threadId === context.threadId@@ -70,14 +72,14 @@ const ThreadChatContent = memo<ThreadChatContentProps>(({ isSubagentThread }) =>return (<MessageIteminPortalThread- disableEditing={isSubagentThread || isParentMessage}+ disableEditing={readOnly || isParentMessage}endRender={enableThreadDivider ? <ThreadDivider /> : undefined}id={id}index={index}/>);},- [threadSourceInfo.sourceMessageId, threadSourceInfo.sourceMessageIndex, isSubagentThread],+ [threadSourceInfo.sourceMessageId, threadSourceInfo.sourceMessageIndex, readOnly],);return (@@ -101,7 +103,7 @@ const ThreadChatContent = memo<ThreadChatContentProps>(({ isSubagentThread }) =><ChatList itemContent={itemContent} /></Flexbox></Suspense>- {!isSubagentThread && <ChatInput leftActions={['typo']} rightActions={['contextWindow']} />}+ {composerWritable && <ChatInput leftActions={['typo']} rightActions={['contextWindow']} />}</>);});@@ -132,12 +134,14 @@ const ThreadChat = memo(() => {// executor on every spawn β unambiguous marker to flip the thread into a// read-only record (hides composer, wipes per-message actions, disables// double-click editing).- const isSubagentThread = useChatStore(- (s) => !!portalThreadSelectors.portalCurrentThread(s)?.metadata?.sourceToolCallId,- );+ const portalThread = useChatStore(portalThreadSelectors.portalCurrentThread);+ const threadMetadataResolved = !portalThreadId || !!portalThread;+ const isSubagentThread = !!portalThread?.metadata?.sourceToolCallId;// Get thread-specific actionsBar config- const actionsBarConfig = useThreadActionsBarConfig({ readonly: isSubagentThread });+ const actionsBarConfig = useThreadActionsBarConfig({+ readonly: !threadMetadataResolved || isSubagentThread,+ });// Build ConversationContext for thread// When creating new thread (!portalThreadId), use isNew + scope: 'thread'@@ -180,6 +184,15 @@ const ThreadChat = memo(() => {// Generate messageMapKey for direct subscription to dbMessagesMapconst chatKey = useMemo(() => messageMapKey(keyContext), [keyContext]);+ const composerTarget = useMemo<ComposerTarget>(+ () =>+ resolveThreadComposerTarget({+ contextKey: chatKey,+ metadataResolved: threadMetadataResolved,+ sourceToolCallId: portalThread?.metadata?.sourceToolCallId,+ }),+ [chatKey, portalThread?.metadata?.sourceToolCallId, threadMetadataResolved],+ );// Subscribe directly to dbMessagesMap for reactive updates// This ensures optimistic updates work (read/write use same key)@@ -232,6 +245,7 @@ const ThreadChat = memo(() => {return (<ConversationProvideractionsBar={actionsBarConfig}+ composerTarget={composerTarget}context={context}hasInitMessages={!!messages}hooks={hooks}@@ -242,7 +256,10 @@ const ThreadChat = memo(() => {replaceMessages(msgs, { context: ctx, source: meta?.source });}}>- <ThreadChatContent isSubagentThread={isSubagentThread} />+ <ThreadChatContent+ composerWritable={composerTarget.writable}+ readOnly={!composerTarget.writable}+ /></ConversationProvider>);});diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.tsindex 29afc8f7590..54cbe42d548 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts@@ -6,12 +6,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { agentService } from '@/services/agent';import { aiChatService } from '@/services/aiChat';import { chatService } from '@/services/chat';+import * as skillPreload from '@/services/chat/mecha/skillPreload';import { messageService } from '@/services/message';import * as agentGroupStore from '@/store/agentGroup';import { setPendingTopicRepos } from '@/store/chat/pendingTopicRepos';import { operationSelectors } from '@/store/chat/slices/operation/selectors';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { topicMapKey } from '@/store/chat/utils/topicMapKey';+import { fileChatSelectors, useFileStore } from '@/store/file';import { getSessionStoreState } from '@/store/session';import * as toolStoreModule from '@/store/tool';import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/pageAgentRuntime';@@ -68,6 +70,7 @@ beforeEach(() => {vi.spyOn(sessionStore, 'triggerSessionUpdate').mockResolvedValue(undefined);vi.spyOn(agentService, 'getAgentConfigById').mockResolvedValue(createMockAgentConfig() as any);useUserStore.setState({ workspaceUserPreference: {} });+ useFileStore.setState({ chatContextSelectionsByContext: {} });act(() => {useChatStore.setState({@@ -473,10 +476,17 @@ describe('ConversationLifecycle actions', () => {expect(result.current.executeClientAgent).toHaveBeenCalled();});- it('should adopt the minted topic id for the whole send (no _new -> topic transition)', async () => {+ it('should adopt the minted topic id and move context added during preflight', async () => {const { result } = renderHook(() => useChatStore());const agentId = TEST_IDS.SESSION_ID;const newBucketKey = messageMapKey({ agentId, topicId: null });+ let resolveSkillPreload!: (value: []) => void;+ const skillPreloadPromise = new Promise<[]>((resolve) => {+ resolveSkillPreload = resolve;+ });+ const skillPreloadSpy = vi+ .spyOn(skillPreload, 'resolveSelectedSkillsWithContent')+ .mockReturnValue(skillPreloadPromise);let resolveServerSend!: (value: any) => void;const serverSendPromise = new Promise<any>((resolve) => {resolveServerSend = resolve;@@ -511,14 +521,26 @@ describe('ConversationLifecycle actions', () => {});});+ await waitFor(() => expect(skillPreloadSpy).toHaveBeenCalled());++ const pendingSelection = {+ content: 'context added while preparing the first send',+ id: 'pending-selection',+ type: 'text' as const,+ };+ act(() => {+ useFileStore.getState().addChatContextSelection({+ contextKey: newBucketKey,+ selection: pendingSelection,+ });+ resolveSkillPreload([]);+ });+await waitFor(() => expect(sendMessageInServerSpy).toHaveBeenCalled());// The conversation adopted the minted id BEFORE the server answered:// activeTopicId already points at it, the optimistic pair lives in the- // minted bucket (NOT `_new`), and the id is marked as creating. This is- // the invariant that keeps the conversation surface's contextKey stable- // for the whole send β the remount/blank-frame flicker cannot happen- // when the key never changes.+ // minted bucket (NOT `_new`), and the id is marked as creating.const midState = useChatStore.getState();const mintedTopicId = midState.activeTopicId!;expect(mintedTopicId).toMatch(/^tpc_/);@@ -528,6 +550,12 @@ describe('ConversationLifecycle actions', () => {const mintedBucketKey = messageMapKey({ agentId, topicId: mintedTopicId });expect(midState.dbMessagesMap[mintedBucketKey]?.length).toBe(2);expect(midState.dbMessagesMap[newBucketKey] ?? []).toEqual([]);+ expect(+ fileChatSelectors.chatContextSelections(mintedBucketKey)(useFileStore.getState()),+ ).toEqual([pendingSelection]);+ expect(+ fileChatSelectors.chatContextSelections(newBucketKey)(useFileStore.getState()),+ ).toEqual([]);await act(async () => {resolveServerSend({@@ -560,6 +588,26 @@ describe('ConversationLifecycle actions', () => {expect(endState.creatingTopicIds).not.toContain(mintedTopicId);});+ it('should return composer context ownership when preflight fails', async () => {+ const { result } = renderHook(() => useChatStore());+ const preflightError = new Error('skill preload failed');+ const onPreflightFailure = vi.fn();+ vi.spyOn(skillPreload, 'resolveSelectedSkillsWithContent').mockRejectedValue(+ preflightError,+ );++ await expect(+ result.current.sendMessage({+ context: createTestContext(),+ message: TEST_CONTENT.USER_MESSAGE,+ onPreflightFailure,+ }),+ ).rejects.toBe(preflightError);++ expect(onPreflightFailure).toHaveBeenCalledOnce();+ expect(result.current.operations).toEqual({});+ });+it('should show an optimistic topic while the first message is still creating the server topic', async () => {const { result } = renderHook(() => useChatStore());const agentId = TEST_IDS.SESSION_ID;@@ -1201,6 +1249,89 @@ describe('ConversationLifecycle actions', () => {expect(useChatStore.getState().activeTopicId).not.toBe(optimisticTopicId);});+ it('should restore optimistic topic selections after switching away before rollback', async () => {+ const { result } = renderHook(() => useChatStore());+ const agentId = TEST_IDS.SESSION_ID;+ const topicKey = topicMapKey({ agentId });+ const newContextKey = messageMapKey({ agentId, topicId: null });+ const otherTopicId = 'other-topic';+ let resolveServerSend!: (value: any) => void;+ const serverSendPromise = new Promise<any>((resolve) => {+ resolveServerSend = resolve;+ });++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: undefined,+ executeClientAgent: vi.fn().mockResolvedValue(undefined),+ summaryTopicTitle: vi.fn().mockResolvedValue(undefined),+ topicDataMap: {+ [topicKey]: {+ currentPage: 0,+ hasMore: false,+ isExpandingPageSize: false,+ isLoadingMore: false,+ items: [],+ pageSize: 20,+ total: 0,+ },+ },+ });+ });++ vi.spyOn(aiChatService, 'sendMessageInServer').mockReturnValue(serverSendPromise);++ let sendPromise!: ReturnType<typeof result.current.sendMessage>;+ act(() => {+ sendPromise = result.current.sendMessage({+ context: { agentId, threadId: null, topicId: null },+ message: TEST_CONTENT.USER_MESSAGE,+ });+ });++ await waitFor(() =>+ expect(useChatStore.getState().topicDataMap[topicKey]?.items[0]?.id).toMatch(/^tpc_/),+ );+ const optimisticTopicId = useChatStore.getState().topicDataMap[topicKey]!.items[0].id;+ const optimisticContextKey = messageMapKey({ agentId, topicId: optimisticTopicId });+ const pendingSelection = {+ content: 'context added before the failed send',+ id: 'rollback-selection',+ type: 'text' as const,+ };++ act(() => {+ useFileStore.getState().addChatContextSelection({+ contextKey: optimisticContextKey,+ selection: pendingSelection,+ });+ useChatStore.setState({ activeTopicId: otherTopicId });+ });++ await act(async () => {+ resolveServerSend({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ messages: [+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),+ createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),+ ],+ topics: undefined,+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any);+ await sendPromise;+ });++ expect(useChatStore.getState().activeTopicId).toBe(otherTopicId);+ expect(useChatStore.getState().topicDataMap[topicKey]?.items ?? []).toEqual([]);+ expect(+ fileChatSelectors.chatContextSelections(newContextKey)(useFileStore.getState()),+ ).toEqual([pendingSelection]);+ expect(+ fileChatSelectors.chatContextSelections(optimisticContextKey)(useFileStore.getState()),+ ).toEqual([]);+ });+it('should persist selected tool tags into user message content before runtime execution', async () => {const { result } = renderHook(() => useChatStore());diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.tsindex 92cf0ebd5c2..395909a083f 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts@@ -30,6 +30,11 @@ vi.mock('@/services/topic', () => ({},}));+const moveChatContextSelections = vi.hoisted(() => vi.fn());+vi.mock('@/store/file/store', () => ({+ getFileStoreState: () => ({ moveChatContextSelections }),+}));+const mockUserDefaultConfig = vi.hoisted(() => ({disableGatewayMode: undefined as boolean | undefined,}));@@ -160,6 +165,7 @@ function createTestAction() {describe('GatewayActionImpl', () => {beforeEach(() => {+ moveChatContextSelections.mockClear();mockAgentStore.state = { activeAgentId: undefined, agentMap: {} };mockUserDefaultConfig.disableGatewayMode = undefined;mockToolInterventionConfig.approvalMode = 'manual';@@ -776,6 +782,20 @@ describe('GatewayActionImpl', () => {title: '666',},});+ expect(moveChatContextSelections).toHaveBeenCalledWith(+ messageMapKey({+ agentId: 'agent-1',+ scope: 'main',+ threadId: null,+ topicId: 'tmp-topic',+ }),+ messageMapKey({+ agentId: 'agent-1',+ scope: 'main',+ threadId: null,+ topicId: 'topic-1',+ }),+ );});it('should keep optimistic topic metadata when replacing the placeholder topic id', async () => {diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex aac376ce219..22717a28de2 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -81,6 +81,7 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { snapshotAgentModel } from '@/store/chat/utils/snapshotAgentModel';import { topicMapKey } from '@/store/chat/utils/topicMapKey';import { getElectronStoreState } from '@/store/electron';+import { getFileStoreState } from '@/store/file/store';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/pageAgentRuntime';@@ -120,6 +121,8 @@ export interface SendMessageWithContextParams extends SendMessageParams {* sibling panel.*/inputEditor?: ChatInputEditor | null;+ /** Restore composer-owned context when sending fails before a message owns it. */+ onPreflightFailure?: () => void;/*** Called as soon as the backend reports a newly created topic id, so callers* with an isolated topic scope (e.g. Task Manager) can switch their UI to the@@ -265,6 +268,7 @@ export class ConversationLifecycleActionImpl {messages: inputMessages,parentId: inputParentId,pageSelections,+ onPreflightFailure,onTopicCreated,}: SendMessageWithContextParams): Promise<SendMessageResult | undefined> => {let editorData = inputEditorData;@@ -292,7 +296,10 @@ export class ConversationLifecycleActionImpl {}: undefined;- if (!agentId) return;+ if (!agentId) {+ onPreflightFailure?.();+ return;+ }const agentState = getAgentStoreState();const agentConfig = agentSelectors.getAgentConfigById(agentId)(agentState);@@ -426,10 +433,11 @@ export class ConversationLifecycleActionImpl {* bucket, `activeTopicId` and the sidebar row all use it from the first* frame, and the server honours it verbatim (`newTopic.id` / `clientIds`).*- * This is what removes the `_new` β topic transition β the conversation's- * `contextKey` never changes, so the conversation surface never remounts- * and the virtualized list never repaints from an empty viewport (the- * first-send "messages vanish for a frame" flicker).+ * This removes the server-confirmation re-key: optimistic messages use the+ * final topic key immediately, so the virtualized list does not repaint from+ * an empty viewport when the server responds. The composer still pivots once+ * from `_new` to this minted key below, and its pending context is migrated+ * before that switch.** Isolated-topic callers keep the legacy flow (they re-subscribe via* `onTopicCreated` and never render the main conversation surface).@@ -458,7 +466,10 @@ export class ConversationLifecycleActionImpl {!metadata?.localSystemToolSnapshots?.length &&(!!heterogeneousProvider || isLocalSystemEnabled);const localSystemToolSnapshots = canMaterializeLocalFiles- ? await materializeLocalSystemToolSnapshots(localFileReferences)+ ? await materializeLocalSystemToolSnapshots(localFileReferences).catch((error) => {+ onPreflightFailure?.();+ throw error;+ }): [];const userMessageMetadata =metadata ||@@ -478,6 +489,9 @@ export class ConversationLifecycleActionImpl {const enrichedSelectedSkills = await resolveSelectedSkillsWithContent({message,selectedSkills,+ }).catch((error) => {+ onPreflightFailure?.();+ throw error;});const enrichedSelectedTools = resolveSelectedToolsWithContent({message,@@ -489,7 +503,10 @@ export class ConversationLifecycleActionImpl {const hasFile = !!fileIdList && fileIdList.length > 0;// if message is empty or no files, then stop- if (!message && !hasFile) return;+ if (!message && !hasFile) {+ onPreflightFailure?.();+ return;+ }const newTopicTitle = markdownToTxt(message).slice(0, 80) || t('defaultTitle', { ns: 'topic' });@@ -727,6 +744,10 @@ export class ConversationLifecycleActionImpl {},'sendMessage/optimisticCreateTopic',);+ getFileStoreState().moveChatContextSelections(+ messageMapKey({ ...operationContext, topicId: null }),+ currentContextKey,+ );await this.#get().switchTopic(mintedTopicId, { skipRefreshMessage: true });}@@ -910,6 +931,10 @@ export class ConversationLifecycleActionImpl {const rollbackOptimisticTopic = (action: string) => {if (!optimisticTopic || !optimisticTopicActive) return;+ getFileStoreState().moveChatContextSelections(+ currentContextKey,+ messageMapKey({ ...operationContext, topicId: null }),+ );if (this.#get().activeTopicId === optimisticTopic.id) {void this.#get().switchTopic(null, { skipRefreshMessage: true });}@@ -1042,6 +1067,7 @@ export class ConversationLifecycleActionImpl {const heteroResponseMeta = heteroData as SendMessageServerResponseMeta;const heteroMessageKey = messageMapKey(heteroContext);this.#get().moveQueuedMessages(currentContextKey, heteroMessageKey);+ getFileStoreState().moveChatContextSelections(currentContextKey, heteroMessageKey);// Legacy queue location: follow-ups enqueued behind an op still// registered under the pre-mint `_new` key.if (willCreateNewTopic)@@ -1469,6 +1495,7 @@ export class ConversationLifecycleActionImpl {};const finalMessageKey = messageMapKey(finalContext);this.#get().moveQueuedMessages(currentContextKey, finalMessageKey);+ getFileStoreState().moveChatContextSelections(currentContextKey, finalMessageKey);// Legacy queue location: follow-ups enqueued behind an op still// registered under the pre-mint `_new` key.if (willCreateNewTopic)diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex bd9bfd2440f..7d65c982a19 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -31,6 +31,7 @@ import { topicSelectors } from '@/store/chat/selectors';import type { ChatStore } from '@/store/chat/store';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { topicMapKey } from '@/store/chat/utils/topicMapKey';+import { getFileStoreState } from '@/store/file/store';import type { StoreSetter } from '@/store/types';import { useUserStore } from '@/store/user';import {@@ -633,6 +634,10 @@ export class GatewayActionImpl {title: optimisticTopic.title,},});+ getFileStoreState().moveChatContextSelections(+ messageMapKey({ ...messageContext, topicId: optimisticTopic.id }),+ messageMapKey({ ...messageContext, topicId: result.topicId }),+ );}try {const newContext = { ...messageContext, topicId: result.topicId };diff --git a/src/store/file/slices/chat/action.test.ts b/src/store/file/slices/chat/action.test.tsindex 817bd02bd4f..7bef3dd4e45 100644--- a/src/store/file/slices/chat/action.test.ts+++ b/src/store/file/slices/chat/action.test.ts@@ -1,3 +1,4 @@+import type { ChatContextContent } from '@lobechat/types';import { toast } from '@lobehub/ui/base-ui';import { act, renderHook } from '@testing-library/react';import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';@@ -69,6 +70,112 @@ beforeEach(() => {});describe('useFileStore:chat', () => {+ it('isolates context selections by conversation key', () => {+ const { result } = renderHook(() => useStore());+ const sharedIdSelectionA: ChatContextContent = {+ content: 'selection A',+ id: 'shared-selection',+ type: 'text',+ };+ const sharedIdSelectionB: ChatContextContent = {+ content: 'selection B',+ id: 'shared-selection',+ type: 'text',+ };++ act(() => {+ useStore.setState({ chatContextSelectionsByContext: {} });+ result.current.addChatContextSelection({+ contextKey: 'topic-a',+ selection: sharedIdSelectionA,+ });+ result.current.addChatContextSelection({+ contextKey: 'topic-b',+ selection: sharedIdSelectionB,+ });+ });++ expect(result.current.chatContextSelectionsByContext).toEqual({+ 'topic-a': [sharedIdSelectionA],+ 'topic-b': [sharedIdSelectionB],+ });++ act(() => {+ result.current.removeChatContextSelection({+ contextKey: 'topic-a',+ id: sharedIdSelectionA.id,+ });+ });++ expect(result.current.chatContextSelectionsByContext).toEqual({+ 'topic-b': [sharedIdSelectionB],+ });++ act(() => {+ result.current.clearChatContextSelections('topic-b');+ });++ expect(result.current.chatContextSelectionsByContext).toEqual({});+ });++ it('moves context selections to a new conversation key without overwriting the target', () => {+ const { result } = renderHook(() => useStore());+ const sourceSelection: ChatContextContent = {+ content: 'source selection',+ id: 'shared-selection',+ type: 'text',+ };+ const targetSelection: ChatContextContent = {+ content: 'stale target selection',+ id: 'shared-selection',+ type: 'text',+ };+ const targetOnlySelection: ChatContextContent = {+ content: 'target only',+ id: 'target-only',+ type: 'text',+ };++ act(() => {+ useStore.setState({+ chatContextSelectionsByContext: {+ 'topic-new': [sourceSelection],+ 'topic-real': [targetSelection, targetOnlySelection],+ },+ });+ result.current.moveChatContextSelections('topic-new', 'topic-real');+ });++ expect(result.current.chatContextSelectionsByContext).toEqual({+ 'topic-real': [sourceSelection, targetOnlySelection],+ });+ });++ it('restores submitted selections without overwriting context added while sending', () => {+ const { result } = renderHook(() => useStore());+ const submittedSelection: ChatContextContent = {+ content: 'submitted selection',+ id: 'submitted',+ type: 'text',+ };+ const newerSelection: ChatContextContent = {+ content: 'newer selection',+ id: 'newer',+ type: 'text',+ };++ act(() => {+ useStore.setState({+ chatContextSelectionsByContext: { topic: [newerSelection] },+ });+ result.current.restoreChatContextSelections('topic', [submittedSelection]);+ });++ expect(result.current.chatContextSelectionsByContext).toEqual({+ topic: [submittedSelection, newerSelection],+ });+ });+it('clearChatUploadFileList should clear the inputFilesList', () => {const { result } = renderHook(() => useStore());diff --git a/src/store/file/slices/chat/action.ts b/src/store/file/slices/chat/action.tsindex 4120f8a3251..b2d4aa3470f 100644--- a/src/store/file/slices/chat/action.ts+++ b/src/store/file/slices/chat/action.ts@@ -69,15 +69,30 @@ export class FileActionImpl {this.#get = get;}- addChatContextSelection = (context: ChatContextContent): void => {- const current = this.#get().chatContextSelections;- const next = [context, ...current.filter((item) => item.id !== context.id)];-- this.#set({ chatContextSelections: next }, false, n('addChatContextSelection'));+ addChatContextSelection = ({+ contextKey,+ selection,+ }: {+ contextKey: string;+ selection: ChatContextContent;+ }): void => {+ const currentMap = this.#get().chatContextSelectionsByContext;+ const current = currentMap[contextKey] ?? [];+ const next = [selection, ...current.filter((item) => item.id !== selection.id)];++ this.#set(+ { chatContextSelectionsByContext: { ...currentMap, [contextKey]: next } },+ false,+ n('addChatContextSelection'),+ );};- clearChatContextSelections = (): void => {- this.#set({ chatContextSelections: [] }, false, n('clearChatContextSelections'));+ clearChatContextSelections = (contextKey: string): void => {+ const currentMap = this.#get().chatContextSelectionsByContext;+ if (!(contextKey in currentMap)) return;++ const { [contextKey]: _removed, ...nextMap } = currentMap;+ this.#set({ chatContextSelectionsByContext: nextMap }, false, n('clearChatContextSelections'));};clearChatUploadFileList = (): void => {@@ -91,9 +106,61 @@ export class FileActionImpl {this.#set({ chatUploadFileList: nextValue }, false, `dispatchChatFileList/${payload.type}`);};- removeChatContextSelection = (id: string): void => {- const next = this.#get().chatContextSelections.filter((item) => item.id !== id);- this.#set({ chatContextSelections: next }, false, n('removeChatContextSelection'));+ moveChatContextSelections = (fromContextKey: string, toContextKey: string): void => {+ if (fromContextKey === toContextKey) return;++ const currentMap = this.#get().chatContextSelectionsByContext;+ const source = currentMap[fromContextKey];+ if (!source || source.length === 0) return;++ const sourceIds = new Set(source.map((item) => item.id));+ const target = currentMap[toContextKey] ?? [];+ const nextTarget = [...source, ...target.filter((item) => !sourceIds.has(item.id))];+ const { [fromContextKey]: _removed, ...nextMap } = currentMap;++ this.#set(+ { chatContextSelectionsByContext: { ...nextMap, [toContextKey]: nextTarget } },+ false,+ n('moveChatContextSelections'),+ );+ };++ removeChatContextSelection = ({ contextKey, id }: { contextKey: string; id: string }): void => {+ const currentMap = this.#get().chatContextSelectionsByContext;+ const current = currentMap[contextKey];+ if (!current) return;++ const next = current.filter((item) => item.id !== id);+ if (next.length === 0) {+ const { [contextKey]: _removed, ...nextMap } = currentMap;+ this.#set(+ { chatContextSelectionsByContext: nextMap },+ false,+ n('removeChatContextSelection'),+ );+ return;+ }++ this.#set(+ { chatContextSelectionsByContext: { ...currentMap, [contextKey]: next } },+ false,+ n('removeChatContextSelection'),+ );+ };++ restoreChatContextSelections = (contextKey: string, selections: ChatContextContent[]): void => {+ if (selections.length === 0) return;++ const currentMap = this.#get().chatContextSelectionsByContext;+ const restoredIds = new Set(selections.map((item) => item.id));+ const current = currentMap[contextKey] ?? [];+ const next = [...selections, ...current.filter((item) => !restoredIds.has(item.id))];++ this.#set(+ { chatContextSelectionsByContext: { ...currentMap, [contextKey]: next } },+ false,+ n('restoreChatContextSelections'),+ );};removeChatUploadFile = async (id: string): Promise<void> => {diff --git a/src/store/file/slices/chat/initialState.ts b/src/store/file/slices/chat/initialState.tsindex 5141f04fc0a..ff1b2579cf1 100644--- a/src/store/file/slices/chat/initialState.ts+++ b/src/store/file/slices/chat/initialState.ts@@ -3,13 +3,13 @@ import { type ChatContextContent } from '@lobechat/types';import { type UploadFileItem } from '@/types/files/upload';export interface ImageFileState {- chatContextSelections: ChatContextContent[];+ chatContextSelectionsByContext: Record<string, ChatContextContent[]>;chatUploadFileList: UploadFileItem[];uploadingIds: string[];}export const initialImageFileState: ImageFileState = {- chatContextSelections: [],+ chatContextSelectionsByContext: {},chatUploadFileList: [],uploadingIds: [],};diff --git a/src/store/file/slices/chat/selectors.test.ts b/src/store/file/slices/chat/selectors.test.tsindex de6f5123885..7a28aec910a 100644--- a/src/store/file/slices/chat/selectors.test.ts+++ b/src/store/file/slices/chat/selectors.test.ts@@ -1,3 +1,4 @@+import type { ChatContextContent } from '@lobechat/types';import { describe, expect, it } from 'vitest';import { type FilesStoreState } from '@/store/file/initialState';@@ -32,6 +33,42 @@ describe('filesSelectors', () => {});describe('fileChatSelectors', () => {+ describe('chatContextSelections', () => {+ it('returns only the selections owned by the requested conversation', () => {+ const selectionA: ChatContextContent = {+ content: 'selection A',+ id: 'selection-a',+ type: 'text',+ };+ const selectionB: ChatContextContent = {+ content: 'selection B',+ id: 'selection-b',+ type: 'text',+ };+ const state = {+ ...initialState,+ chatContextSelectionsByContext: {+ 'topic-a': [selectionA],+ 'topic-b': [selectionB],+ },+ } as FilesStoreState;++ expect(fileChatSelectors.chatContextSelections('topic-a')(state)).toEqual([selectionA]);+ expect(fileChatSelectors.chatContextSelections('topic-b')(state)).toEqual([selectionB]);+ expect(fileChatSelectors.chatContextSelections('topic-c')(state)).toEqual([]);+ expect(fileChatSelectors.chatContextSelectionHasItem('topic-a')(state)).toBe(true);+ expect(fileChatSelectors.chatContextSelectionHasItem('topic-c')(state)).toBe(false);+ });++ it('returns the same empty list when no conversation key is available', () => {+ const first = fileChatSelectors.chatContextSelections()(initialState);+ const second = fileChatSelectors.chatContextSelections()(initialState);++ expect(first).toBe(second);+ expect(first).toEqual([]);+ });+ });+describe('chatRawFileList', () => {it('should return a list of raw files', () => {const state = {diff --git a/src/store/file/slices/chat/selectors.ts b/src/store/file/slices/chat/selectors.tsindex dec935219f5..f1af3e046d7 100644--- a/src/store/file/slices/chat/selectors.ts+++ b/src/store/file/slices/chat/selectors.ts@@ -1,14 +1,22 @@+import { type ChatContextContent } from '@lobechat/types';+import { UPLOAD_STATUS_SET } from '@/types/files/upload';import { type FilesStoreState } from '../../initialState';+const EMPTY_CHAT_CONTEXT_SELECTIONS: ChatContextContent[] = [];+const chatUploadFileList = (s: FilesStoreState) => s.chatUploadFileList;-const chatContextSelections = (s: FilesStoreState) => s.chatContextSelections;+const chatContextSelections = (contextKey?: string) => (s: FilesStoreState) =>+ contextKey+ ? (s.chatContextSelectionsByContext[contextKey] ?? EMPTY_CHAT_CONTEXT_SELECTIONS)+ : EMPTY_CHAT_CONTEXT_SELECTIONS;const isImageUploading = (s: FilesStoreState) => s.uploadingIds.length > 0;const chatRawFileList = (s: FilesStoreState) => s.chatUploadFileList.map((item) => item.file);const chatUploadFileListHasItem = (s: FilesStoreState) => s.chatUploadFileList.length > 0;-const chatContextSelectionHasItem = (s: FilesStoreState) => s.chatContextSelections.length > 0;+const chatContextSelectionHasItem = (contextKey?: string) => (s: FilesStoreState) =>+ contextKey ? (s.chatContextSelectionsByContext[contextKey]?.length ?? 0) > 0 : false;const isUploadingFiles = (s: FilesStoreState) =>s.chatUploadFileList.some(