Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(chat): keep composer uploads per conversation (#22329)

AmAzing-257689b723b7
diff --git a/src/components/DragUploadZone/useUploadFiles.ts b/src/components/DragUploadZone/useUploadFiles.ts
index 8e7e1216e06..78e68118a50 100644
--- a/src/components/DragUploadZone/useUploadFiles.ts
+++ b/src/components/DragUploadZone/useUploadFiles.ts
@@ -9,6 +9,11 @@ import { useFileStore } from '@/store/file';
interface UseUploadFilesOptions {
/** The conversation's agent id. Decides whether the chat-only file-type whitelist applies. */
agentId: string;
+ /**
+ * The composer the files land in (its `contextSelectionKey`). Without one
+ * there is no attachment list to show them, so nothing is uploaded.
+ */
+ contextKey?: string;
model?: string;
provider?: string;
}
@@ -57,7 +62,7 @@ export const partitionFilesByMediaAbility = (
* @returns handleUploadFiles - Callback to handle file uploads
*/
export const useUploadFiles = (options: UseUploadFilesOptions) => {
- const { agentId, model = '', provider = '' } = options;
+ const { agentId, contextKey, model = '', provider = '' } = options;
const { t } = useTranslation('chat');
const { canUploadImage, canUploadVideo, canUploadAudio } = useMediaUploadAbility(
@@ -70,7 +75,7 @@ export const useUploadFiles = (options: UseUploadFilesOptions) => {
const handleUploadFiles = useCallback(
async (files: File[]) => {
- if (!canUpload) return;
+ if (!canUpload || !contextKey) return;
// Filter out media files if the model cannot receive them directly or via fallback.
const { accepted, rejected } = partitionFilesByMediaAbility(files, {
@@ -90,10 +95,19 @@ export const useUploadFiles = (options: UseUploadFilesOptions) => {
}
if (accepted.length > 0) {
- uploadFiles(accepted, agentId);
+ uploadFiles(contextKey, accepted, agentId);
}
},
- [agentId, canUpload, canUploadImage, canUploadVideo, canUploadAudio, t, uploadFiles],
+ [
+ agentId,
+ canUpload,
+ canUploadImage,
+ canUploadVideo,
+ canUploadAudio,
+ contextKey,
+ t,
+ uploadFiles,
+ ],
);
return { canUploadImage, canUploadVideo, canUploadAudio, handleUploadFiles };
diff --git a/src/features/AgentBuilder/AgentBuilderConversation.tsx b/src/features/AgentBuilder/AgentBuilderConversation.tsx
index 56f2876afc1..51870165414 100644
--- a/src/features/AgentBuilder/AgentBuilderConversation.tsx
+++ b/src/features/AgentBuilder/AgentBuilderConversation.tsx
@@ -3,7 +3,12 @@ import { memo } from 'react';
import DragUploadZone, { useUploadFiles } from '@/components/DragUploadZone';
import { type ActionKeys } from '@/features/ChatInput';
-import { ChatInput, ChatList } from '@/features/Conversation';
+import {
+ ChatInput,
+ ChatList,
+ conversationSelectors,
+ useConversationStore,
+} from '@/features/Conversation';
import { usePermission } from '@/hooks/usePermission';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
@@ -26,7 +31,13 @@ const AgentBuilderConversation = memo<AgentBuilderConversationProps>(({ agentId
// Get agent's model info for vision support check
const model = useAgentStore((s) => agentByIdSelectors.getAgentModelById(agentId)(s));
const provider = useAgentStore((s) => agentByIdSelectors.getAgentModelProviderById(agentId)(s));
- const { handleUploadFiles } = useUploadFiles({ agentId, model, provider });
+ const composerKey = useConversationStore(conversationSelectors.composerKey);
+ const { handleUploadFiles } = useUploadFiles({
+ agentId,
+ contextKey: composerKey,
+ model,
+ provider,
+ });
const { allowed: canCreate } = usePermission('create_content');
// Resolve usage_in_followup / manual_edit feedback when a suggestion-seeded
diff --git a/src/features/AgentGoals/GoalChat/index.tsx b/src/features/AgentGoals/GoalChat/index.tsx
index 0c9c01fdf86..b5a2c634ac3 100644
--- a/src/features/AgentGoals/GoalChat/index.tsx
+++ b/src/features/AgentGoals/GoalChat/index.tsx
@@ -43,7 +43,13 @@ const Conversation = memo<ConversationProps>(
const provider = useAgentStore((s) =>
agentByIdSelectors.getAgentModelProviderById(currentAgentId)(s),
);
- const { handleUploadFiles } = useUploadFiles({ agentId: currentAgentId, model, provider });
+ const composerKey = useConversationStore(conversationSelectors.composerKey);
+ const { handleUploadFiles } = useUploadFiles({
+ agentId: currentAgentId,
+ contextKey: composerKey,
+ model,
+ provider,
+ });
return (
<DragUploadZone style={{ flex: 1, height: '100%' }} onUploadFiles={handleUploadFiles}>
diff --git a/src/features/AgentTaskManager/Conversation.tsx b/src/features/AgentTaskManager/Conversation.tsx
index 873e3a697f6..b0919b8dedc 100644
--- a/src/features/AgentTaskManager/Conversation.tsx
+++ b/src/features/AgentTaskManager/Conversation.tsx
@@ -55,7 +55,13 @@ const Conversation = memo(() => {
const provider = useAgentStore((s) =>
agentByIdSelectors.getAgentModelProviderById(currentAgentId)(s),
);
- const { handleUploadFiles } = useUploadFiles({ agentId: currentAgentId, model, provider });
+ const composerKey = useConversationStore(conversationSelectors.composerKey);
+ const { handleUploadFiles } = useUploadFiles({
+ agentId: currentAgentId,
+ contextKey: composerKey,
+ model,
+ provider,
+ });
const handleAgentChange = useCallback(
(id: string) => {
diff --git a/src/features/ChatInput/ActionBar/Clear/index.tsx b/src/features/ChatInput/ActionBar/Clear/index.tsx
index ecf4d0723c0..c5bdc1cfa82 100644
--- a/src/features/ChatInput/ActionBar/Clear/index.tsx
+++ b/src/features/ChatInput/ActionBar/Clear/index.tsx
@@ -8,16 +8,18 @@ import { useChatStore } from '@/store/chat';
import { useFileStore } from '@/store/file';
import { useChatInputResourceAccess } from '../../hooks/useChatInputResourceAccess';
+import { useChatInputUploadKey } from '../../hooks/useChatInputUpload';
import { ChatInputAction } from '../components/ChatInputAction';
export const useClearCurrentMessages = () => {
const clearMessage = useChatStore((s) => s.clearMessage);
const clearImageList = useFileStore((s) => s.clearChatUploadFileList);
+ const contextKey = useChatInputUploadKey();
return useCallback(async () => {
await clearMessage();
- clearImageList();
- }, [clearImageList, clearMessage]);
+ if (contextKey) clearImageList(contextKey);
+ }, [clearImageList, clearMessage, contextKey]);
};
const Clear = memo(() => {
diff --git a/src/features/ChatInput/ActionBar/Plus/index.tsx b/src/features/ChatInput/ActionBar/Plus/index.tsx
index ba767c0311c..79990269e1f 100644
--- a/src/features/ChatInput/ActionBar/Plus/index.tsx
+++ b/src/features/ChatInput/ActionBar/Plus/index.tsx
@@ -25,7 +25,6 @@ import { useMediaUploadAbility } from '@/hooks/useMediaUploadAbility';
import { useModelSupportToolUse } from '@/hooks/useModelSupportToolUse';
import { useAgentStore } from '@/store/agent';
import { agentSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
-import { useFileStore } from '@/store/file';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import {
@@ -38,6 +37,7 @@ import { labPreferSelectors, settingsSelectors } from '@/store/user/selectors';
import { useAgentId } from '../../hooks/useAgentId';
import { useChatInputResourceAccess } from '../../hooks/useChatInputResourceAccess';
+import { useChatInputUpload } from '../../hooks/useChatInputUpload';
import { useEffectiveModel } from '../../hooks/useEffectiveModel';
import { useLargeFileLocalPath } from '../../hooks/useLargeFileLocalPath';
import { useUpdateAgentConfig } from '../../hooks/useUpdateAgentConfig';
@@ -238,7 +238,7 @@ const usePlusMenuItems = ({ close }: { close: () => void }): ActionDropdownMenuI
// Goal creation is lab-gated while the product surface is being rolled out.
const enableGoals = useUserStore(labPreferSelectors.enableGoals);
- const upload = useFileStore((s) => s.uploadChatFiles);
+ const upload = useChatInputUpload();
const { enableKnowledgeBase } = useServerConfigStore(featureFlagsSelectors);
const enableGatewayMode = useServerConfigStore(serverConfigSelectors.enableGatewayMode);
const defaultDisableGatewayMode = useUserStore(
diff --git a/src/features/ChatInput/ActionBar/Upload/index.tsx b/src/features/ChatInput/ActionBar/Upload/index.tsx
index 09d59afb75b..94e6da11d4c 100644
--- a/src/features/ChatInput/ActionBar/Upload/index.tsx
+++ b/src/features/ChatInput/ActionBar/Upload/index.tsx
@@ -7,12 +7,12 @@ import { useTranslation } from 'react-i18next';
import TipGuide from '@/components/TipGuide';
import { useMediaUploadAbility } from '@/hooks/useMediaUploadAbility';
import { usePermission } from '@/hooks/usePermission';
-import { useFileStore } from '@/store/file';
import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
import { useUserStore } from '@/store/user';
import { preferenceSelectors } from '@/store/user/selectors';
import { useAgentId } from '../../hooks/useAgentId';
+import { useChatInputUpload } from '../../hooks/useChatInputUpload';
import { useEffectiveModel } from '../../hooks/useEffectiveModel';
import { useLargeFileLocalPath } from '../../hooks/useLargeFileLocalPath';
import { useChatInputStore } from '../../store';
@@ -40,7 +40,7 @@ const FileUpload = memo<FileUploadProps>(({ includeKnowledge = true }) => {
(s) => featureFlagsSelectors(s).enableKnowledgeBase,
);
- const upload = useFileStore((s) => s.uploadChatFiles);
+ const upload = useChatInputUpload();
const editor = useChatInputStore((s) => s.editor);
const agentId = useAgentId();
diff --git a/src/features/ChatInput/ChatInputProvider.tsx b/src/features/ChatInput/ChatInputProvider.tsx
index 7d5abd8add6..dea862863f9 100644
--- a/src/features/ChatInput/ChatInputProvider.tsx
+++ b/src/features/ChatInput/ChatInputProvider.tsx
@@ -36,6 +36,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(
getMessages,
resolveSendBlocked,
topicId,
+ uploadContextKey,
}) => {
const editor = useEditor();
const slashMenuRef = useRef<HTMLDivElement>(null);
@@ -61,6 +62,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(
slashMenuRef,
slashPlacement,
topicId,
+ uploadContextKey,
})
}
>
@@ -83,6 +85,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(
sendMenu={sendMenu}
slashPlacement={slashPlacement}
topicId={topicId}
+ uploadContextKey={uploadContextKey}
onMarkdownContentChange={onMarkdownContentChange}
onSend={onSend}
onVoiceMessageSend={onVoiceMessageSend}
diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx
index dbb11da498e..ee320ee8b62 100644
--- a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx
+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx
@@ -13,6 +13,7 @@ import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { FileUploadErrorActions } from '@/business/client/features/FileUploadErrorActions';
+import { useChatInputUploadKey } from '@/features/ChatInput/hooks/useChatInputUpload';
import { useEventCallback } from '@/hooks/useEventCallback';
import { useFileStore } from '@/store/file';
import { type UploadFileItem } from '@/types/files/upload';
@@ -83,6 +84,7 @@ type FileItemProps = UploadFileItem;
const ContextItem = memo<FileItemProps>((props) => {
const { error, errorCode, file, id, status, tasks, uploadState } = props;
const { t } = useTranslation(['chat', 'common']);
+ const contextKey = useChatInputUploadKey();
const removeChatUploadFile = useFileStore((s) => s.removeChatUploadFile);
const retryChatUploadFile = useFileStore((s) => s.retryChatUploadFile);
const { busy, canPreview, canRetry, indicator, progress } = getUploadChipState(props);
@@ -94,7 +96,7 @@ const ContextItem = memo<FileItemProps>((props) => {
if (canPreview) void openFilePreviewModal(props);
});
const handleClose = useEventCallback(() => {
- void removeChatUploadFile(id);
+ if (contextKey) void removeChatUploadFile(contextKey, id);
});
const detail = (
@@ -185,7 +187,7 @@ const ContextItem = memo<FileItemProps>((props) => {
size={{ blockSize: 24, size: 12 }}
title={t('retry', { ns: 'common' })}
onClick={() => {
- void retryChatUploadFile(id);
+ if (contextKey) void retryChatUploadFile(contextKey, id);
}}
/>
)}
diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextList.tsx b/src/features/ChatInput/Desktop/ContextContainer/ContextList.tsx
index 9546a935a5c..0a4ec7f0d81 100644
--- a/src/features/ChatInput/Desktop/ContextContainer/ContextList.tsx
+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextList.tsx
@@ -1,6 +1,7 @@
import { createStaticStyles, Flexbox, ScrollShadow } from '@lobehub/ui';
import { memo } from 'react';
+import { useChatInputUploadKey } from '@/features/ChatInput/hooks/useChatInputUpload';
import { useChatInputStore } from '@/features/ChatInput/store';
import { fileChatSelectors, useFileStore } from '@/store/file';
@@ -17,8 +18,9 @@ const styles = createStaticStyles(({ css }) => ({
const ContextList = memo(() => {
const contextSelectionKey = useChatInputStore((s) => s.contextSelectionKey);
- const inputFilesList = useFileStore(fileChatSelectors.chatUploadFileList);
- const showFileList = useFileStore(fileChatSelectors.chatUploadFileListHasItem);
+ const uploadContextKey = useChatInputUploadKey();
+ const inputFilesList = useFileStore(fileChatSelectors.chatUploadFileList(uploadContextKey));
+ const showFileList = useFileStore(fileChatSelectors.chatUploadFileListHasItem(uploadContextKey));
const rawSelectionList = useFileStore(
fileChatSelectors.chatContextSelections(contextSelectionKey),
);
diff --git a/src/features/ChatInput/Desktop/index.tsx b/src/features/ChatInput/Desktop/index.tsx
index 59244a5340d..717e7451f85 100644
--- a/src/features/ChatInput/Desktop/index.tsx
+++ b/src/features/ChatInput/Desktop/index.tsx
@@ -9,6 +9,7 @@ import { useTranslation } from 'react-i18next';
import ChatInputNotice from '@/features/ChatInput/ChatInputNotice';
import ComposerExpandButton from '@/features/ChatInput/components/ComposerExpandButton';
+import { useChatInputUploadKey } from '@/features/ChatInput/hooks/useChatInputUpload';
import { useChatInputStore } from '@/features/ChatInput/store';
import { LayoutContainerContext } from '@/features/DesktopLayoutContainer/LayoutContainerContext';
import { useChatStore } from '@/store/chat';
@@ -139,7 +140,8 @@ const DesktopChatInput = memo<DesktopChatInputProps>(
const hasContextSelections = useFileStore(
fileChatSelectors.chatContextSelectionHasItem(contextSelectionKey),
);
- const hasFiles = useFileStore(fileChatSelectors.chatUploadFileListHasItem);
+ const uploadContextKey = useChatInputUploadKey();
+ const hasFiles = useFileStore(fileChatSelectors.chatUploadFileListHasItem(uploadContextKey));
const [slashMenuRef, expand, showTypoBar, editor, leftActions] = useChatInputStore((s) => [
s.slashMenuRef,
s.expand,
diff --git a/src/features/ChatInput/InputEditor/index.test.tsx b/src/features/ChatInput/InputEditor/index.test.tsx
index c02fa97701e..56f8daec55f 100644
--- a/src/features/ChatInput/InputEditor/index.test.tsx
+++ b/src/features/ChatInput/InputEditor/index.test.tsx
@@ -221,6 +221,7 @@ vi.mock('@/store/user/selectors', () => ({
}));
vi.mock('../hooks/useAgentId', () => ({ useAgentId: () => 'agent-id' }));
+vi.mock('../hooks/useChatInputUpload', () => ({ useChatInputUploadKey: () => 'composer-key' }));
vi.mock('../hooks/useLargeFileLocalPath', () => ({
useLargeFileLocalPath: () => (files: File[]) => files,
}));
diff --git a/src/features/ChatInput/InputEditor/index.tsx b/src/features/ChatInput/InputEditor/index.tsx
index edeb659ed73..99da5955ea7 100644
--- a/src/features/ChatInput/InputEditor/index.tsx
+++ b/src/features/ChatInput/InputEditor/index.tsx
@@ -44,6 +44,7 @@ import { useAgentId } from '../hooks/useAgentId';
import { useChatInputDraft } from '../hooks/useChatInputDraft';
import { useChatInputHistory } from '../hooks/useChatInputHistory';
import { useChatInputResourceAccess } from '../hooks/useChatInputResourceAccess';
+import { useChatInputUploadKey } from '../hooks/useChatInputUpload';
import { useEffectiveModel } from '../hooks/useEffectiveModel';
import { useLargeFileLocalPath } from '../hooks/useLargeFileLocalPath';
import { useChatInputStore, useStoreApi } from '../store';
@@ -276,7 +277,13 @@ const InputEditor = memo<{
isMentionEnabled &&
!heterogeneousName &&
categories.some((category) => category.id === 'agent');
- const { handleUploadFiles } = useUploadFiles({ agentId, model, provider });
+ const uploadContextKey = useChatInputUploadKey();
+ const { handleUploadFiles } = useUploadFiles({
+ agentId,
+ contextKey: uploadContextKey,
+ model,
+ provider,
+ });
const routeLargeFilesToLocalPaths = useLargeFileLocalPath(agentId, editor);
const handlePasteFiles = useCallback(
(files: File[]) => handleUploadFiles(routeLargeFilesToLocalPaths(files)),
diff --git a/src/features/ChatInput/Mobile/FilePreview/FileItem/index.tsx b/src/features/ChatInput/Mobile/FilePreview/FileItem/index.tsx
index f2f0c53e4b9..f0707f858b4 100644
--- a/src/features/ChatInput/Mobile/FilePreview/FileItem/index.tsx
+++ b/src/features/ChatInput/Mobile/FilePreview/FileItem/index.tsx
@@ -1,6 +1,7 @@
import { type CSSProperties } from 'react';
import { memo } from 'react';
+import { useChatInputUploadKey } from '@/features/ChatInput/hooks/useChatInputUpload';
import { useFileStore } from '@/store/file';
import { type UploadFileItem } from '@/types/files';
@@ -19,10 +20,17 @@ interface FileItemProps extends UploadFileItem {
const FileItem = memo<FileItemProps>((props) => {
const { errorCode, file, id, previewUrl, status } = props;
- const [removeFile, retryFile] = useFileStore((s) => [
+ const contextKey = useChatInputUploadKey();
+ const [removeChatUploadFile, retryChatUploadFile] = useFileStore((s) => [
s.removeChatUploadFile,
s.retryChatUploadFile,
]);
+ const removeFile = (fileId: string) => {
+ if (contextKey) void removeChatUploadFile(contextKey, fileId);
+ };
+ const retryFile = async (fileId: string) => {
+ if (contextKey) await retryChatUploadFile(contextKey, fileId);
+ };
if (file.type.startsWith('image')) {
return (
diff --git a/src/features/ChatInput/Mobile/FilePreview/index.tsx b/src/features/ChatInput/Mobile/FilePreview/index.tsx
index ffdf8d28b04..a520a5b60b5 100644
--- a/src/features/ChatInput/Mobile/FilePreview/index.tsx
+++ b/src/features/ChatInput/Mobile/FilePreview/index.tsx
@@ -2,8 +2,9 @@ import { createStaticStyles, Flexbox, PreviewGroup, ScrollShadow } from '@lobehu
import isEqual from 'fast-deep-equal';
import { memo } from 'react';
+import { useChatInputUploadKey } from '@/features/ChatInput/hooks/useChatInputUpload';
import { useChatInputStore } from '@/features/ChatInput/store';
-import { filesSelectors, useFileStore } from '@/store/file';
+import { fileChatSelectors, useFileStore } from '@/store/file';
import FileItem from './FileItem';
@@ -16,7 +17,8 @@ const styles = createStaticStyles(({ css }) => ({
const FilePreview = memo(() => {
const expand = useChatInputStore((s) => s.expand);
- const list = useFileStore(filesSelectors.chatUploadFileList, isEqual);
+ const contextKey = useChatInputUploadKey();
+ const list = useFileStore(fileChatSelectors.chatUploadFileList(contextKey), isEqual);
if (!list || list?.length === 0) return null;
return (
diff --git a/src/features/ChatInput/StoreUpdater.tsx b/src/features/ChatInput/StoreUpdater.tsx
index c37052b9ee5..fa60ad1ebdf 100644
--- a/src/features/ChatInput/StoreUpdater.tsx
+++ b/src/features/ChatInput/StoreUpdater.tsx
@@ -37,6 +37,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(
getMessages,
resolveSendBlocked,
topicId,
+ uploadContextKey,
}) => {
const storeApi = useStoreApi();
const useStoreUpdater = createStoreUpdater(storeApi);
@@ -46,6 +47,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(
useStoreUpdater('topicId', topicId);
useStoreUpdater('canRecordVoiceMessage', canRecordVoiceMessage);
useStoreUpdater('contextSelectionKey', contextSelectionKey);
+ useStoreUpdater('uploadContextKey', uploadContextKey);
useStoreUpdater('contextWindowMessages', contextWindowMessages);
// Sync draftKey before paint: the draft-transition subscriber
diff --git a/src/features/ChatInput/hooks/useChatInputUpload.ts b/src/features/ChatInput/hooks/useChatInputUpload.ts
new file mode 100644
index 00000000000..b479d607867
--- /dev/null
+++ b/src/features/ChatInput/hooks/useChatInputUpload.ts
@@ -0,0 +1,31 @@
+'use client';
+
+import { useCallback } from 'react';
+
+import { useFileStore } from '@/store/file';
+
+import { useChatInputStore } from '../store';
+
+/**
+ * Key of this composer's upload list. Uploads are kept per conversation, like
+ * the text draft, so switching conversations never carries them along.
+ */
+export const useChatInputUploadKey = () =>
+ useChatInputStore((s) => s.uploadContextKey ?? s.contextSelectionKey);
+
+/**
+ * Upload into this composer's own attachment list. A composer without a key
+ * has nowhere to show the files, so the upload is skipped.
+ */
+export const useChatInputUpload = () => {
+ const contextKey = useChatInputUploadKey();
+ const uploadChatFiles = useFileStore((s) => s.uploadChatFiles);
+
+ return useCallback(
+ async (files: File[], agentId: string) => {
+ if (!contextKey) return;
+ await uploadChatFiles(contextKey, files, agentId);
+ },
+ [contextKey, uploadChatFiles],
+ );
+};
diff --git a/src/features/ChatInput/store/initialState.ts b/src/features/ChatInput/store/initialState.ts
index 75736c32f0b..77f6ddd8a46 100644
--- a/src/features/ChatInput/store/initialState.ts
+++ b/src/features/ChatInput/store/initialState.ts
@@ -105,6 +105,13 @@ export interface PublicState {
* topic than the surrounding page.
*/
topicId?: string | null;
+ /**
+ * Key of this composer's upload list in the file store. Defaults to
+ * `contextSelectionKey`; a host whose text draft outlives that key (Home
+ * keeps its text across mode and agent switches) passes a steadier one so
+ * attachments stay alongside the text.
+ */
+ uploadContextKey?: string;
}
export interface State extends PublicState {
diff --git a/src/features/Conversation/ChatInput/QueueTray.tsx b/src/features/Conversation/ChatInput/QueueTray.tsx
index 0cff5be0e3f..64b73b9266e 100644
--- a/src/features/Conversation/ChatInput/QueueTray.tsx
+++ b/src/features/Conversation/ChatInput/QueueTray.tsx
@@ -238,10 +238,10 @@ const QueueTray = memo(() => {
editor?.focus();
if (msg.filesPreview?.length) {
const restored = reconstructUploadFilesFromQueue(msg.filesPreview);
- dispatchChatUploadFileList({ files: restored, type: 'addFiles' });
+ dispatchChatUploadFileList(contextKey, { files: restored, type: 'addFiles' });
}
},
- [dispatchChatUploadFileList, editor, withdraw],
+ [contextKey, dispatchChatUploadFileList, editor, withdraw],
);
// "Send now": cancel the currently running agent run for this context, then
diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsx
index 5329b567f6d..c3c6fe7d87b 100644
--- a/src/features/Conversation/ChatInput/index.tsx
+++ b/src/features/Conversation/ChatInput/index.tsx
@@ -278,9 +278,9 @@ const ChatInput = memo<ChatInputProps>(
const clearSendMessageError = useChatStore((s) => s.clearSendMessageError);
// File store - for UI state only (disabled button, etc.)
- const fileList = useFileStore(fileChatSelectors.chatUploadFileList);
+ const fileList = useFileStore(fileChatSelectors.chatUploadFileList(contextKey));
const contextList = useFileStore(fileChatSelectors.chatContextSelections(contextKey));
- const isUploadingFiles = useFileStore(fileChatSelectors.isUploadingFiles);
+ const isUploadingFiles = useFileStore(fileChatSelectors.isUploadingFiles(contextKey));
// Queue state
const hasQueuedMessages = useChatStore(
@@ -317,11 +317,12 @@ const ChatInput = memo<ChatInputProps>(
const resolveSendBlocked = useCallback(() => {
if (disableSend) return true;
+ const { context: liveContext, editor } = storeApi.getState();
+ const liveContextKey = messageMapKey(liveContext);
const fileStore = useFileStore.getState();
- if (fileChatSelectors.isUploadingFiles(fileStore)) return true;
+ if (fileChatSelectors.isUploadingFiles(liveContextKey)(fileStore)) return true;
if (customDisabled !== undefined) return customDisabled;
- const { context: liveContext, editor } = storeApi.getState();
if (
disableQueue &&
operationSelectors.isInputLoadingByContext(liveContext)(useChatStore.getState())
@@ -329,9 +330,9 @@ const ChatInput = memo<ChatInputProps>(
return true;
const hasText = String(editor?.getMarkdownContent?.() || '').trim().length > 0;
- const hasFiles = fileChatSelectors.chatUploadFileList(fileStore).length > 0;
+ const hasFiles = fileChatSelectors.chatUploadFileList(liveContextKey)(fileStore).length > 0;
const hasContextSelections =
- fileChatSelectors.chatContextSelections(messageMapKey(liveContext))(fileStore).length > 0;
+ fileChatSelectors.chatContextSelections(liveContextKey)(fileStore).length > 0;
return !hasText && !hasFiles && !hasContextSelections;
}, [customDisabled, disableQueue, disableSend, storeApi]);
const shouldUsePlainSendButton = !showSendMenu && !!sendMenu;
@@ -347,8 +348,8 @@ const ChatInput = memo<ChatInputProps>(
// Get instant values from stores at trigger time
const fileStore = useFileStore.getState();
- const currentFileList = fileChatSelectors.chatUploadFileList(fileStore);
- const currentIsUploading = fileChatSelectors.isUploadingFiles(fileStore);
+ const currentFileList = fileChatSelectors.chatUploadFileList(contextKey)(fileStore);
+ const currentIsUploading = fileChatSelectors.isUploadingFiles(contextKey)(fileStore);
const currentContextList = fileChatSelectors.chatContextSelections(contextKey)(fileStore);
if (currentIsUploading) return;
@@ -382,7 +383,7 @@ const ChatInput = memo<ChatInputProps>(
const clearComposer = () => {
clearContent();
- fileStore.clearChatUploadFileList();
+ fileStore.clearChatUploadFileList(contextKey);
fileStore.clearChatContextSelections(contextKey);
};
@@ -418,7 +419,7 @@ const ChatInput = memo<ChatInputProps>(
// message owned the content must hand every part of it back —
// uploads and context selections, not just the editor text the
// lifecycle restores on its own.
- store.restoreChatUploadFileList(currentFileList);
+ store.restoreChatUploadFileList(contextKey, currentFileList);
store.restoreChatContextSelections(contextKey, currentContextList);
},
pageSelections,
diff --git a/src/features/Conversation/ComposerDraftReceiver.test.tsx b/src/features/Conversation/ComposerDraftReceiver.test.tsx
index b599ef1530b..7063af442de 100644
--- a/src/features/Conversation/ComposerDraftReceiver.test.tsx
+++ b/src/features/Conversation/ComposerDraftReceiver.test.tsx
@@ -20,6 +20,7 @@ const mocks = vi.hoisted(() => ({
}));
vi.mock('./store', () => ({
+ conversationSelectors: { composerKey: () => 'main_agt_inbox_new' },
useConversationStore: (selector: (s: unknown) => unknown) =>
selector({
context: mocks.context,
diff --git a/src/features/Conversation/ComposerDraftReceiver.tsx b/src/features/Conversation/ComposerDraftReceiver.tsx
index d2310e0a2b6..223beae5ba5 100644
--- a/src/features/Conversation/ComposerDraftReceiver.tsx
+++ b/src/features/Conversation/ComposerDraftReceiver.tsx
@@ -3,7 +3,7 @@
import { memo, useEffect } from 'react';
import { useComposerDraftBus } from './composerDraftBus';
-import { useConversationStore, useConversationStoreApi } from './store';
+import { conversationSelectors, useConversationStore, useConversationStoreApi } from './store';
/**
* Renders nothing — consumes composerDraftBus drafts into the live composer.
@@ -18,15 +18,19 @@ const ComposerDraftReceiver = memo(() => {
const updateInputMessage = useConversationStore((s) => s.updateInputMessage);
const agentId = useConversationStore((s) => s.context.agentId);
const topicId = useConversationStore((s) => s.context.topicId);
+ const contextKey = useConversationStore(conversationSelectors.composerKey);
const storeApi = useConversationStoreApi();
const draft = useComposerDraftBus((s) => s.draft);
useEffect(() => {
- useComposerDraftBus.setState({ attached: Boolean(editor) });
+ useComposerDraftBus.setState({
+ attached: Boolean(editor),
+ contextKey: editor ? contextKey : undefined,
+ });
return () => {
- useComposerDraftBus.setState({ attached: false });
+ useComposerDraftBus.setState({ attached: false, contextKey: undefined });
};
- }, [editor]);
+ }, [contextKey, editor]);
useEffect(() => {
if (!draft || !editor) return;
diff --git a/src/features/Conversation/Messages/components/MessageActionBar/actions/restoreToInput.test.ts b/src/features/Conversation/Messages/components/MessageActionBar/actions/restoreToInput.test.ts
index 279875cfd2a..5e7a802a187 100644
--- a/src/features/Conversation/Messages/components/MessageActionBar/actions/restoreToInput.test.ts
+++ b/src/features/Conversation/Messages/components/MessageActionBar/actions/restoreToInput.test.ts
@@ -18,7 +18,8 @@ const clearChatUploadFileList = vi.fn();
const dispatchChatUploadFileList = vi.fn();
vi.mock('../../../../store', () => ({
- useConversationStore: (selector: (s: any) => any) => selector({ editor, updateInputMessage }),
+ useConversationStore: (selector: (s: any) => any) =>
+ selector({ context: { agentId: 'agt_1', topicId: 'tpc_1' }, editor, updateInputMessage }),
}));
vi.mock('@/store/file', () => ({
@@ -78,8 +79,8 @@ describe('restoreToInputAction', () => {
imageList: [{ alt: 'pic', id: 'i1', url: 'u-i1' }],
})!.handleClick!();
- expect(clearChatUploadFileList).toHaveBeenCalled();
- expect(dispatchChatUploadFileList).toHaveBeenCalledWith({
+ expect(clearChatUploadFileList).toHaveBeenCalledWith('main_agt_1_tpc_1');
+ expect(dispatchChatUploadFileList).toHaveBeenCalledWith('main_agt_1_tpc_1', {
files: [
expect.objectContaining({
fileUrl: 'u-i1',
@@ -97,7 +98,7 @@ describe('restoreToInputAction', () => {
type: 'addFiles',
});
- const [{ files }] = dispatchChatUploadFileList.mock.calls[0];
+ const [, { files }] = dispatchChatUploadFileList.mock.calls[0];
expect(files[0].file.type).toBe('image/*');
expect(files[1].file).toMatchObject({ name: 'a.pdf', size: 100, type: 'application/pdf' });
});
diff --git a/src/features/Conversation/Messages/components/MessageActionBar/actions/restoreToInput.ts b/src/features/Conversation/Messages/components/MessageActionBar/actions/restoreToInput.ts
index d9f8543139a..19d1b3b4677 100644
--- a/src/features/Conversation/Messages/components/MessageActionBar/actions/restoreToInput.ts
+++ b/src/features/Conversation/Messages/components/MessageActionBar/actions/restoreToInput.ts
@@ -3,6 +3,7 @@ import { Undo2 } from 'lucide-react';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { cleanBotPromptTags } from '@/store/chat/utils/parseReferencedMessage';
import { unescapeMarkdown } from '@/store/chat/utils/unescapeMarkdown';
import { useFileStore } from '@/store/file';
@@ -25,6 +26,7 @@ export const restoreToInputAction = defineAction({
const { t } = useTranslation('common');
const editor = useConversationStore((s) => s.editor);
+ const contextKey = useConversationStore((s) => messageMapKey(s.context));
const updateInputMessage = useConversationStore((s) => s.updateInputMessage);
return useMemo(() => {
@@ -93,9 +95,9 @@ export const restoreToInputAction = defineAction({
];
const fileStore = useFileStore.getState();
- fileStore.clearChatUploadFileList();
+ fileStore.clearChatUploadFileList(contextKey);
if (restored.length > 0) {
- fileStore.dispatchChatUploadFileList({ files: restored, type: 'addFiles' });
+ fileStore.dispatchChatUploadFileList(contextKey, { files: restored, type: 'addFiles' });
}
editor.focus();
@@ -105,6 +107,6 @@ export const restoreToInputAction = defineAction({
key: 'restoreToInput',
label: t('restoreToInput'),
};
- }, [t, ctx.role, ctx.data, editor, updateInputMessage]);
+ }, [t, ctx.role, ctx.data, contextKey, editor, updateInputMessage]);
},
});
diff --git a/src/features/Conversation/WorkingSidebar/Browser/index.tsx b/src/features/Conversation/WorkingSidebar/Browser/index.tsx
index b98deddfda6..092e95dd099 100644
--- a/src/features/Conversation/WorkingSidebar/Browser/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/Browser/index.tsx
@@ -242,7 +242,8 @@ const BrowserPane = memo<BrowserPaneProps>((props) => {
};
const addScreenshotToInput = async () => {
- if (isCapturing || !agentId) return;
+ if (isCapturing || !agentId || !composerTarget.writable) return;
+ const { contextKey } = composerTarget;
setIsCapturing(true);
try {
const result = await electronBrowserSidebarService.captureScreenshot({ sessionId });
@@ -254,7 +255,7 @@ const BrowserPane = memo<BrowserPaneProps>((props) => {
const file = dataUrlToFile(result.dataUrl, buildScreenshotFileName(result.title));
// The attachment appears in the input immediately (pending state); the
// upload itself reports its own progress and errors.
- void useFileStore.getState().uploadChatFiles([file], agentId);
+ void useFileStore.getState().uploadChatFiles(contextKey, [file], agentId);
toast.success(t('workingPanel.browser.actions.captured'));
focusChatInput();
} catch (error) {
@@ -435,7 +436,7 @@ const BrowserPane = memo<BrowserPaneProps>((props) => {
}
/>
<ActionIcon
- disabled={!state.attached || !agentId}
+ disabled={!state.attached || !agentId || !composerTarget.writable}
icon={Camera}
loading={isCapturing}
size={DESKTOP_HEADER_ICON_SMALL_SIZE}
diff --git a/src/features/Conversation/composerDraftBus.ts b/src/features/Conversation/composerDraftBus.ts
index d3cc53d52eb..2fb1487d786 100644
--- a/src/features/Conversation/composerDraftBus.ts
+++ b/src/features/Conversation/composerDraftBus.ts
@@ -14,6 +14,8 @@ import { createWithEqualityFn } from 'zustand/traditional';
interface ComposerDraftBusState {
/** A receiver with a live editor is mounted and will consume drafts. */
attached: boolean;
+ /** The attached composer's key (see `conversationSelectors.composerKey`); set while attached. */
+ contextKey?: string;
/**
* The pending draft, cleared by the receiver once applied. `append` adds it
* after what the user already typed instead of replacing it. A draft with a
diff --git a/src/features/Conversation/store/slices/context/selectors.ts b/src/features/Conversation/store/slices/context/selectors.ts
index da9af231359..8784ad7c5ed 100644
--- a/src/features/Conversation/store/slices/context/selectors.ts
+++ b/src/features/Conversation/store/slices/context/selectors.ts
@@ -25,11 +25,19 @@ const conversationKey = (s: State): string => {
});
};
+/**
+ * The key this conversation's composer files its draft, uploads and context
+ * selections under. Unlike `conversationKey` it keeps `documentId`, so a page
+ * copilot gets its own key.
+ */
+const composerKey = (s: State): string => messageMapKey(s.context);
+
const hooks = (s: State) => s.hooks;
const hook = (hookName: keyof State['hooks']) => (s: State) => s.hooks[hookName];
export const contextSelectors = {
agentId,
+ composerKey,
context,
conversationKey,
groupId,
diff --git a/src/features/FileViewer/Renderer/Image/Tools/index.test.tsx b/src/features/FileViewer/Renderer/Image/Tools/index.test.tsx
index 577e83e9f2f..4f598fb4249 100644
--- a/src/features/FileViewer/Renderer/Image/Tools/index.test.tsx
+++ b/src/features/FileViewer/Renderer/Image/Tools/index.test.tsx
@@ -21,6 +21,9 @@ const fileStore = vi.hoisted(() => ({
uploadWithProgress: vi.fn(),
}));
vi.mock('@/store/file', () => ({
+ fileChatSelectors: {
+ chatUploadFileList: () => (s: typeof fileStore) => s.chatUploadFileList,
+ },
fileManagerSelectors: {
getFileByChunkTargetId: () => () => ({ id: 'file_src', parentId: 'docs_folder' }),
},
@@ -118,12 +121,16 @@ const renderTools = (stage: Partial<ImageStageValue> = {}) => {
describe('ImageEditTools', () => {
beforeEach(() => {
- useComposerDraftBus.setState({ attached: true, draft: null });
+ useComposerDraftBus.setState({
+ attached: true,
+ contextKey: 'main_agt_current_tpc_1',
+ draft: null,
+ });
fileStore.chatUploadFileList = [];
chatState.activeTopicId = 'tpc_1';
permission.allowed = true;
permission.reason = undefined;
- fileStore.uploadChatFiles.mockImplementation(async ([file]: File[]) => {
+ fileStore.uploadChatFiles.mockImplementation(async (_contextKey: string, [file]: File[]) => {
fileStore.chatUploadFileList = [{ file, id: 'file_chat', status: 'success' }];
});
exporter.loadStageImage.mockResolvedValue({ naturalHeight: 1000, naturalWidth: 2000 });
@@ -325,7 +332,8 @@ describe('ImageEditTools', () => {
'Remove this',
]);
- const [[file], agentId] = fileStore.uploadChatFiles.mock.calls[0];
+ const [contextKey, [file], agentId] = fileStore.uploadChatFiles.mock.calls[0];
+ expect(contextKey).toBe('main_agt_current_tpc_1');
expect(file.name).toBe('sunset-annotated.png');
expect(agentId).toBe('agt_current');
// Nothing is saved to the library.
@@ -375,7 +383,8 @@ describe('ImageEditTools', () => {
});
await waitFor(() => expect(navigate).toHaveBeenCalledWith('/agent/agt_inbox'));
- expect(fileStore.uploadChatFiles.mock.calls[0][1]).toBe('agt_inbox');
+ expect(fileStore.uploadChatFiles.mock.calls[0][0]).toBe('main_agt_inbox_new');
+ expect(fileStore.uploadChatFiles.mock.calls[0][2]).toBe('agt_inbox');
// Queued for the composer that mounts after navigating.
expect(useComposerDraftBus.getState().draft?.text).toContain(
'imageViewer.markup.message.item',
@@ -399,7 +408,7 @@ describe('ImageEditTools', () => {
// Regression: the text and success used to land before the attachment was
// in the input, so Send could go out with the text alone.
it('keeps the marks and adds no text when the attachment does not reach the input', async () => {
- fileStore.uploadChatFiles.mockImplementation(async ([file]: File[]) => {
+ fileStore.uploadChatFiles.mockImplementation(async (_contextKey: string, [file]: File[]) => {
fileStore.chatUploadFileList = [
{ error: 'Upload failed', file, id: 'sunset-annotated.png', status: 'error' },
];
@@ -413,7 +422,7 @@ describe('ImageEditTools', () => {
});
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('imageViewer.markup.failed'));
- expect(fileStore.dispatchChatUploadFileList).toHaveBeenCalledWith({
+ expect(fileStore.dispatchChatUploadFileList).toHaveBeenCalledWith('main_agt_current_tpc_1', {
id: 'sunset-annotated.png',
type: 'removeFile',
});
@@ -425,7 +434,7 @@ describe('ImageEditTools', () => {
// Regression: switching conversations during the upload sent the marks to
// whichever conversation was open when it finished.
it('does not hand the marks to another conversation opened meanwhile', async () => {
- fileStore.uploadChatFiles.mockImplementation(async ([file]: File[]) => {
+ fileStore.uploadChatFiles.mockImplementation(async (_contextKey: string, [file]: File[]) => {
chatState.activeTopicId = 'tpc_other';
fileStore.chatUploadFileList = [{ file, id: 'file_chat', status: 'success' }];
});
@@ -438,7 +447,7 @@ describe('ImageEditTools', () => {
});
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('imageViewer.markup.failed'));
- expect(fileStore.dispatchChatUploadFileList).toHaveBeenCalledWith({
+ expect(fileStore.dispatchChatUploadFileList).toHaveBeenCalledWith('main_agt_current_tpc_1', {
id: 'file_chat',
type: 'removeFile',
});
@@ -446,11 +455,34 @@ describe('ImageEditTools', () => {
expect(screen.getByTestId('image-markup-send')).toBeEnabled();
});
+ // Regression: a thread switch within the same topic kept agent and topic, so
+ // the text went to the new thread while the image stayed in the old one.
+ it('does not hand the marks to another thread of the same topic', async () => {
+ fileStore.uploadChatFiles.mockImplementation(async (_contextKey: string, [file]: File[]) => {
+ useComposerDraftBus.setState({ contextKey: 'thread_agt_current_tpc_1_thd_other' });
+ fileStore.chatUploadFileList = [{ file, id: 'file_chat', status: 'success' }];
+ });
+ const { overlay } = renderTools();
+ fireEvent.click(screen.getByText('imageViewer.tool.annotate'));
+ drawBox(overlay);
+
+ await act(async () => {
+ fireEvent.click(screen.getByTestId('image-markup-send'));
+ });
+
+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('imageViewer.markup.failed'));
+ expect(fileStore.dispatchChatUploadFileList).toHaveBeenCalledWith('main_agt_current_tpc_1', {
+ id: 'file_chat',
+ type: 'removeFile',
+ });
+ expect(useComposerDraftBus.getState().draft).toBeNull();
+ });
+
// Regression: marks added while the handoff uploaded were cleared unsent.
it('keeps marks added while the image was uploading', async () => {
let finishUpload!: () => void;
fileStore.uploadChatFiles.mockImplementation(
- ([file]: File[]) =>
+ (_contextKey: string, [file]: File[]) =>
new Promise<void>((resolve) => {
finishUpload = () => {
fileStore.chatUploadFileList = [{ file, id: 'file_chat', status: 'success' }];
@@ -480,7 +512,7 @@ describe('ImageEditTools', () => {
it('drops the handoff when the viewer closes during the upload', async () => {
let finishUpload!: () => void;
fileStore.uploadChatFiles.mockImplementation(
- ([file]: File[]) =>
+ (_contextKey: string, [file]: File[]) =>
new Promise<void>((resolve) => {
finishUpload = () => {
fileStore.chatUploadFileList = [{ file, id: 'file_chat', status: 'success' }];
@@ -500,7 +532,7 @@ describe('ImageEditTools', () => {
await act(async () => finishUpload());
expect(useComposerDraftBus.getState().draft).toBeNull();
- expect(fileStore.dispatchChatUploadFileList).toHaveBeenCalledWith({
+ expect(fileStore.dispatchChatUploadFileList).toHaveBeenCalledWith('main_agt_current_tpc_1', {
id: 'file_chat',
type: 'removeFile',
});
@@ -511,7 +543,7 @@ describe('ImageEditTools', () => {
// Regression: an upload that failed without throwing left a pending chip
// that was taken for success.
it('treats an attachment left pending as a failed handoff', async () => {
- fileStore.uploadChatFiles.mockImplementation(async ([file]: File[]) => {
+ fileStore.uploadChatFiles.mockImplementation(async (_contextKey: string, [file]: File[]) => {
fileStore.chatUploadFileList = [{ file, id: 'sunset-annotated.png', status: 'pending' }];
});
const { overlay } = renderTools();
@@ -523,7 +555,7 @@ describe('ImageEditTools', () => {
});
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('imageViewer.markup.failed'));
- expect(fileStore.dispatchChatUploadFileList).toHaveBeenCalledWith({
+ expect(fileStore.dispatchChatUploadFileList).toHaveBeenCalledWith('main_agt_current_tpc_1', {
id: 'sunset-annotated.png',
type: 'removeFile',
});
@@ -533,7 +565,7 @@ describe('ImageEditTools', () => {
it('judges this upload, not an earlier attachment with the same name', async () => {
const earlier = new File(['old'], 'sunset-annotated.png', { type: 'image/png' });
fileStore.chatUploadFileList = [{ file: earlier, id: 'file_earlier', status: 'success' }];
- fileStore.uploadChatFiles.mockImplementation(async ([file]: File[]) => {
+ fileStore.uploadChatFiles.mockImplementation(async (_contextKey: string, [file]: File[]) => {
fileStore.chatUploadFileList = [
...fileStore.chatUploadFileList,
{ error: 'Upload failed', file, id: 'sunset-annotated.png', status: 'error' },
diff --git a/src/features/FileViewer/Renderer/Image/Tools/useSendMarkupToChat.ts b/src/features/FileViewer/Renderer/Image/Tools/useSendMarkupToChat.ts
index 36dfc05f719..6f153e9ec5c 100644
--- a/src/features/FileViewer/Renderer/Image/Tools/useSendMarkupToChat.ts
+++ b/src/features/FileViewer/Renderer/Image/Tools/useSendMarkupToChat.ts
@@ -12,7 +12,8 @@ import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwar
import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
-import { useFileStore } from '@/store/file';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+import { fileChatSelectors, useFileStore } from '@/store/file';
import { useImageStage } from '../context';
import { buildDerivedFileName } from '../geometry';
@@ -48,10 +49,15 @@ export const useSendMarkupToChat = () => {
const send = useCallback(
async (markup: ImageMarkup): Promise<boolean> => {
if (isMarkupEmpty(markup)) return false;
- const attached = useComposerDraftBus.getState().attached;
+ const { attached, contextKey: attachedContextKey } = useComposerDraftBus.getState();
const { activeAgentId, activeTopicId } = useChatStore.getState();
const agentId = attached ? activeAgentId : inboxAgentId;
- if (!agentId) {
+ // The attachment goes to the input it is handed to: the open
+ // conversation's, or the new inbox conversation the viewer navigates to.
+ const contextKey = attached
+ ? attachedContextKey
+ : agentId && messageMapKey({ agentId, topicId: null });
+ if (!agentId || !contextKey) {
toast.error(t('imageViewer.markup.noConversation'));
return false;
}
@@ -77,23 +83,30 @@ export const useSendMarkupToChat = () => {
// under the same name; only the item this upload adds counts.
// The export and upload take a while; if the user moved to another
// conversation meanwhile, the marks must not land there.
+ // The composer key also tells threads of one topic apart, so the image
+ // and its text cannot split across two of them.
const isStillTarget = () => {
const chat = useChatStore.getState();
+ const bus = useComposerDraftBus.getState();
return (
aliveRef.current &&
- useComposerDraftBus.getState().attached === attached &&
+ bus.attached === attached &&
(!attached ||
- (chat.activeAgentId === activeAgentId && chat.activeTopicId === activeTopicId))
+ (bus.contextKey === contextKey &&
+ chat.activeAgentId === activeAgentId &&
+ chat.activeTopicId === activeTopicId))
);
};
if (!isStillTarget())
throw new Error('The conversation changed before the image was ready');
- const before = new Set(useFileStore.getState().chatUploadFileList.map((item) => item.id));
- await useFileStore.getState().uploadChatFiles([file], agentId);
- const staged = useFileStore
- .getState()
- .chatUploadFileList.find((item) => !before.has(item.id) && item.file?.name === file.name);
+ const stagedList = () =>
+ fileChatSelectors.chatUploadFileList(contextKey)(useFileStore.getState());
+ const before = new Set(stagedList().map((item) => item.id));
+ await useFileStore.getState().uploadChatFiles(contextKey, [file], agentId);
+ const staged = stagedList().find(
+ (item) => !before.has(item.id) && item.file?.name === file.name,
+ );
// Only a finished upload counts: a failed upload can also leave the
// chip pending without throwing.
if (!staged || staged.status !== 'success') {
@@ -101,11 +114,13 @@ export const useSendMarkupToChat = () => {
if (staged)
useFileStore
.getState()
- .dispatchChatUploadFileList({ id: staged.id, type: 'removeFile' });
+ .dispatchChatUploadFileList(contextKey, { id: staged.id, type: 'removeFile' });
throw new Error(staged?.error ?? 'The annotated image did not reach the input');
}
if (!isStillTarget()) {
- useFileStore.getState().dispatchChatUploadFileList({ id: staged.id, type: 'removeFile' });
+ useFileStore
+ .getState()
+ .dispatchChatUploadFileList(contextKey, { id: staged.id, type: 'removeFile' });
throw new Error('The conversation changed while the image was uploading');
}
diff --git a/src/features/Home/InputArea/EditorInput.tsx b/src/features/Home/InputArea/EditorInput.tsx
index 5c2210429d7..00093c27b6b 100644
--- a/src/features/Home/InputArea/EditorInput.tsx
+++ b/src/features/Home/InputArea/EditorInput.tsx
@@ -13,7 +13,7 @@ import FileUpload from '@/features/ChatInput/ActionBar/Upload';
import { useChatStore } from '@/store/chat';
import type { HomeMode } from '../types';
-import { HOME_INPUT_BODY_HEIGHT } from './constants';
+import { HOME_INPUT_BODY_HEIGHT, HOME_UPLOAD_CONTEXT_KEY } from './constants';
import ModeSelect from './ModeSelect';
const leftActions: ActionKeys[] = ['plus'];
@@ -77,6 +77,7 @@ const HomeEditorInput = memo<HomeEditorInputProps>(
leftActions={leftActions}
rightActions={rightActions}
slashPlacement="bottom"
+ uploadContextKey={HOME_UPLOAD_CONTEXT_KEY}
chatInputEditorRef={(instance) => {
if (!instance) return;
useChatStore.setState({ mainInputEditor: instance });
diff --git a/src/features/Home/InputArea/constants.ts b/src/features/Home/InputArea/constants.ts
index 7d1ab3968a6..3a98ff5dc06 100644
--- a/src/features/Home/InputArea/constants.ts
+++ b/src/features/Home/InputArea/constants.ts
@@ -4,3 +4,10 @@ export const HOME_INPUT_ACTION_BAR_HEIGHT = 40;
export const HOME_INPUT_FRAME_HEIGHT = HOME_INPUT_BODY_HEIGHT + HOME_INPUT_ACTION_BAR_HEIGHT + 2;
export const HOME_INPUT_BOTTOM_PADDING = 8;
export const HOME_INPUT_RESERVED_HEIGHT = HOME_INPUT_FRAME_HEIGHT + HOME_INPUT_BOTTOM_PADDING;
+
+/**
+ * The Home composer's upload list key. Its text survives mode and agent
+ * switches, so its attachments use one key rather than the per-mode, per-agent
+ * context selection key.
+ */
+export const HOME_UPLOAD_CONTEXT_KEY = 'home';
diff --git a/src/features/Home/InputArea/index.tsx b/src/features/Home/InputArea/index.tsx
index fd9a05f9d3c..01a6f957e4b 100644
--- a/src/features/Home/InputArea/index.tsx
+++ b/src/features/Home/InputArea/index.tsx
@@ -12,7 +12,7 @@ import { systemStatusSelectors } from '@/store/global/selectors';
import { HOME_NEW_MODELS_BANNER_ID, NewModelShortcuts } from '../NewModelShortcuts';
import type { HomeMode } from '../types';
-import { HOME_INPUT_RESERVED_HEIGHT } from './constants';
+import { HOME_INPUT_RESERVED_HEIGHT, HOME_UPLOAD_CONTEXT_KEY } from './constants';
import { EditorSlot } from './EditorSlot';
import { stripMarkdownLinks } from './hintFormat';
import { InputBannerQueue, InputBannerSegment } from './InputBanner';
@@ -70,7 +70,12 @@ const InputArea = ({
const provider = useAgentStore((s) =>
agentByIdSelectors.getAgentModelProviderById(resolvedAgentId)(s),
);
- const { handleUploadFiles } = useUploadFiles({ agentId: resolvedAgentId, model, provider });
+ const { handleUploadFiles } = useUploadFiles({
+ agentId: resolvedAgentId,
+ contextKey: HOME_UPLOAD_CONTEXT_KEY,
+ model,
+ provider,
+ });
// Daily-generated input hint paired with the fixed Home greeting.
const { currentPair } = useHomeDailyBrief();
diff --git a/src/features/Home/InputArea/useSend.test.ts b/src/features/Home/InputArea/useSend.test.ts
index 1a0c1d3ffae..eb9ed15a218 100644
--- a/src/features/Home/InputArea/useSend.test.ts
+++ b/src/features/Home/InputArea/useSend.test.ts
@@ -163,7 +163,8 @@ vi.mock('@/store/file', () => {
fileChatSelectors: {
chatContextSelections: (contextKey: string) => (state: typeof fileState) =>
state.chatContextSelectionsByContext[contextKey] ?? [],
- chatUploadFileList: (state: typeof fileState) => state.chatUploadFileList,
+ chatUploadFileList: (contextKey: string) => (state: typeof fileState) =>
+ contextKey === 'home' ? state.chatUploadFileList : [],
},
useFileStore,
};
@@ -187,13 +188,16 @@ describe('Home InputArea useSend', () => {
sendMessageMock.mockReset();
clearContentMock.mockReset();
clearChatUploadFileListMock.mockReset();
- clearChatUploadFileListMock.mockImplementation((submittedIds?: string[]) => {
- fileState.chatUploadFileList = submittedIds
- ? fileState.chatUploadFileList.filter(
- (file: { id: string }) => !submittedIds.includes(file.id),
- )
- : [];
- });
+ clearChatUploadFileListMock.mockImplementation(
+ (contextKey: string, submittedIds?: string[]) => {
+ if (contextKey !== 'home') return;
+ fileState.chatUploadFileList = submittedIds
+ ? fileState.chatUploadFileList.filter(
+ (file: { id: string }) => !submittedIds.includes(file.id),
+ )
+ : [];
+ },
+ );
clearChatContextSelectionsMock.mockReset();
restoreChatContextSelectionsMock.mockReset();
createTaskMock.mockReset();
diff --git a/src/features/Home/InputArea/useSend.ts b/src/features/Home/InputArea/useSend.ts
index fbbc679c189..bb7dd2c0575 100644
--- a/src/features/Home/InputArea/useSend.ts
+++ b/src/features/Home/InputArea/useSend.ts
@@ -24,6 +24,7 @@ import { useTaskStore } from '@/store/task';
import { useResolvedHomeAgentId } from '../AgentSelect/useResolvedHomeAgentId';
import type { HomeMode } from '../types';
+import { HOME_UPLOAD_CONTEXT_KEY } from './constants';
import { appendTaskAttachments } from './taskAttachments';
import { taskNameFromMessage } from './taskName';
@@ -158,7 +159,9 @@ export const useSend = (mode: HomeMode = 'chat') => {
// `onChange`, so a fast type-then-Enter sequence can fire before the
// cache catches up and the empty-message guard would bail incorrectly.
const typed = (getMarkdownContent?.() ?? inputMessage ?? '').trim();
- const fileList = fileChatSelectors.chatUploadFileList(useFileStore.getState());
+ const fileList = fileChatSelectors.chatUploadFileList(HOME_UPLOAD_CONTEXT_KEY)(
+ useFileStore.getState(),
+ );
const contextList = fileChatSelectors.chatContextSelections(contextSelectionKey)(
useFileStore.getState(),
);
@@ -331,7 +334,10 @@ export const useSend = (mode: HomeMode = 'chat') => {
// Preserve the complete draft when creation or execution fails. The
// editor, files and context are one unit from the user's perspective.
if (submitted) {
- clearChatUploadFileList(mode === 'task' ? fileList.map((file) => file.id) : undefined);
+ clearChatUploadFileList(
+ HOME_UPLOAD_CONTEXT_KEY,
+ mode === 'task' ? fileList.map((file) => file.id) : undefined,
+ );
clearChatContextSelections(contextSelectionKey);
mainInputEditor?.clearContent();
}
diff --git a/src/features/PageEditor/Copilot/Conversation.tsx b/src/features/PageEditor/Copilot/Conversation.tsx
index 1a762727c85..5c6eaa39bd1 100644
--- a/src/features/PageEditor/Copilot/Conversation.tsx
+++ b/src/features/PageEditor/Copilot/Conversation.tsx
@@ -43,7 +43,13 @@ const Conversation = memo(() => {
const provider = useAgentStore((s) =>
agentByIdSelectors.getAgentModelProviderById(currentAgentId)(s),
);
- const { handleUploadFiles } = useUploadFiles({ agentId: currentAgentId, model, provider });
+ const composerKey = useConversationStore(conversationSelectors.composerKey);
+ const { handleUploadFiles } = useUploadFiles({
+ agentId: currentAgentId,
+ contextKey: composerKey,
+ model,
+ provider,
+ });
const handleAgentChange = useCallback(
(id: string) => {
diff --git a/src/features/Projects/Workspace/ProjectComposer.tsx b/src/features/Projects/Workspace/ProjectComposer.tsx
index 40d9620fb19..be0db2dab10 100644
--- a/src/features/Projects/Workspace/ProjectComposer.tsx
+++ b/src/features/Projects/Workspace/ProjectComposer.tsx
@@ -22,6 +22,7 @@ import ProjectAgentSelect from './ProjectAgentSelect';
import { projectComposerAgents } from './projectComposerAgents';
import {
AttachmentsNotReadyError,
+ getProjectComposerContextKey,
type ProjectComposerMode,
useProjectComposer,
} from './useProjectComposer';
@@ -91,7 +92,13 @@ const ProjectComposer = memo<ProjectComposerProps>(({ detail, request }) => {
);
const model = useAgentStore((s) => agentByIdSelectors.getAgentModelById(agentId)(s));
const provider = useAgentStore((s) => agentByIdSelectors.getAgentModelProviderById(agentId)(s));
- const { handleUploadFiles } = useUploadFiles({ agentId, model, provider });
+ const contextSelectionKey = getProjectComposerContextKey(project.id);
+ const { handleUploadFiles } = useUploadFiles({
+ agentId,
+ contextKey: contextSelectionKey,
+ model,
+ provider,
+ });
const submit: SendButtonHandler = async (params) => {
try {
@@ -122,7 +129,7 @@ const ProjectComposer = memo<ProjectComposerProps>(({ detail, request }) => {
<ChatInputProvider
agentId={agentId}
allowExpand={false}
- contextSelectionKey={`project-home:${project.id}`}
+ contextSelectionKey={contextSelectionKey}
leftActions={leftActions}
rightActions={rightActions}
sendButtonProps={sendButtonProps}
diff --git a/src/features/Projects/Workspace/useProjectComposer.test.ts b/src/features/Projects/Workspace/useProjectComposer.test.ts
index 5161a067bda..40f59abbcfb 100644
--- a/src/features/Projects/Workspace/useProjectComposer.test.ts
+++ b/src/features/Projects/Workspace/useProjectComposer.test.ts
@@ -92,7 +92,8 @@ vi.mock('@/store/file', () => {
});
return {
fileChatSelectors: {
- chatUploadFileList: (s: { chatUploadFileList: unknown[] }) => s.chatUploadFileList,
+ chatUploadFileList: (contextKey: string) => (s: { chatUploadFileList: unknown[] }) =>
+ contextKey.startsWith('project-home:') ? s.chatUploadFileList : [],
},
useFileStore,
};
@@ -250,7 +251,7 @@ describe('useProjectComposer', () => {
});
expect(editor.setJSONState).toHaveBeenCalledWith(editorData);
- expect(mocks.restoreChatUploadFileList).toHaveBeenCalledWith([image]);
+ expect(mocks.restoreChatUploadFileList).toHaveBeenCalledWith('main_coordinator_tpc_1', [image]);
expect(mocks.toastError).toHaveBeenCalledWith('overview.messageNotSent');
});
@@ -397,7 +398,7 @@ describe('useProjectComposer', () => {
projectId: 'prj_1',
}),
);
- expect(mocks.clearChatUploadFileList).toHaveBeenCalledWith(['file_1']);
+ expect(mocks.clearChatUploadFileList).toHaveBeenCalledWith('project-home:prj_1', ['file_1']);
expect(mocks.navigate).toHaveBeenCalledWith('/task/T-1/ship-it');
expect(mocks.createProjectTopic).not.toHaveBeenCalled();
expect(mocks.sendMessage).not.toHaveBeenCalled();
diff --git a/src/features/Projects/Workspace/useProjectComposer.ts b/src/features/Projects/Workspace/useProjectComposer.ts
index 97ffc100345..6179d749953 100644
--- a/src/features/Projects/Workspace/useProjectComposer.ts
+++ b/src/features/Projects/Workspace/useProjectComposer.ts
@@ -94,6 +94,9 @@ export const createConversationComposer = (conversation: { agentId: string; topi
const isAbort = (error: unknown) =>
error instanceof Error && (error.name === 'AbortError' || error.message.includes('aborted'));
+/** The project home composer's key for its draft attachments and context selections. */
+export const getProjectComposerContextKey = (projectId: string) => `project-home:${projectId}`;
+
export class AttachmentsNotReadyError extends Error {
constructor() {
super('Attachments are still uploading');
@@ -119,7 +122,8 @@ export const useProjectComposer = (
/** Rejects when nothing left the composer, so the caller can report it. */
const send: SendButtonHandler = async ({ clearContent, getEditorData, getMarkdownContent }) => {
const message = getMarkdownContent().trim();
- const files = fileChatSelectors.chatUploadFileList(useFileStore.getState());
+ const composerKey = getProjectComposerContextKey(project.id);
+ const files = fileChatSelectors.chatUploadFileList(composerKey)(useFileStore.getState());
if ((!message && files.length === 0) || sending) return;
if (files.some((file) => file.status !== 'success' || !file.fileUrl))
throw new AttachmentsNotReadyError();
@@ -138,7 +142,10 @@ export const useProjectComposer = (
projectId: project.id,
});
clearContent();
- clearChatUploadFileList(files.map((file) => file.id));
+ clearChatUploadFileList(
+ composerKey,
+ files.map((file) => file.id),
+ );
if (task) navigate(taskDetailPath(task.identifier, undefined, task.name));
return;
}
@@ -156,7 +163,7 @@ export const useProjectComposer = (
// accepted it. From here the conversation's composer owns the draft, so a
// refused send puts it back there rather than here.
clearContent();
- clearChatUploadFileList();
+ clearChatUploadFileList(composerKey);
navigate(getProjectTopicPath(project.slug ?? project.id, topic.id));
const conversation = createConversationComposer({ agentId, topicId: topic.id });
@@ -164,7 +171,9 @@ export const useProjectComposer = (
let filesRestored = false;
const restoreFiles = () => {
filesRestored = true;
- useFileStore.getState().restoreChatUploadFileList(files);
+ useFileStore
+ .getState()
+ .restoreChatUploadFileList(messageMapKey({ agentId, topicId: topic.id }), files);
};
sendMessage({
context: { agentId, topicId: topic.id, ...(workspaceSlug ? { workspaceSlug } : {}) },
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/useHeteroUpload.test.ts b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/useHeteroUpload.test.ts
index fa404b94fc2..50a1ea07d2b 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/useHeteroUpload.test.ts
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/useHeteroUpload.test.ts
@@ -24,7 +24,8 @@ vi.mock('@/features/ChatInput/hooks/useLargeFileLocalPath', () => ({
}));
vi.mock('@/features/ChatInput/store', () => ({
- useChatInputStore: (selector: (s: any) => unknown) => selector({ editor: mocks.editor }),
+ useChatInputStore: (selector: (s: any) => unknown) =>
+ selector({ contextSelectionKey: 'main_agt_hetero_new', editor: mocks.editor }),
}));
vi.mock('@/store/file', () => ({
@@ -46,7 +47,7 @@ describe('useHeteroUpload', () => {
expect(onPicked).toHaveBeenCalled();
expect(mocks.editor.focus).toHaveBeenCalled();
expect(mocks.routeLargeFiles).toHaveBeenCalledWith(files);
- expect(mocks.upload).toHaveBeenCalledWith(files, 'agt_hetero');
+ expect(mocks.upload).toHaveBeenCalledWith('main_agt_hetero_new', files, 'agt_hetero');
});
it('skips the upload when every picked file became a local-path reference', async () => {
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/useHeteroUpload.ts b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/useHeteroUpload.ts
index a2f8268390c..b6a90133df9 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/useHeteroUpload.ts
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/useHeteroUpload.ts
@@ -10,9 +10,9 @@ import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';
+import { useChatInputUpload } from '@/features/ChatInput/hooks/useChatInputUpload';
import { useLargeFileLocalPath } from '@/features/ChatInput/hooks/useLargeFileLocalPath';
import { useChatInputStore } from '@/features/ChatInput/store';
-import { useFileStore } from '@/store/file';
/**
* File/image picking for the hetero `+` menu.
@@ -27,7 +27,7 @@ export const useHeteroUpload = (providerType: string | undefined, onPicked: () =
const { t } = useTranslation('chat');
const agentId = useAgentId();
const editor = useChatInputStore((s) => s.editor);
- const upload = useFileStore((s) => s.uploadChatFiles);
+ const upload = useChatInputUpload();
// On desktop, big non-media files become local-path tags the CLI reads in place.
const routeLargeFilesToLocalPaths = useLargeFileLocalPath(agentId, editor);
diff --git a/src/routes/(main)/agent/features/Conversation/index.tsx b/src/routes/(main)/agent/features/Conversation/index.tsx
index 8989a79b4c8..0533b79ea37 100644
--- a/src/routes/(main)/agent/features/Conversation/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/index.tsx
@@ -9,6 +9,7 @@ import { useLocalPathReference } from '@/features/Conversation/useLocalPathRefer
import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import ConversationArea from './ConversationArea';
@@ -20,7 +21,8 @@ const wrapperStyle: React.CSSProperties = {
};
const ChatConversation = memo(() => {
- const { agentId, topicId } = useAgentContext();
+ const context = useAgentContext();
+ const { agentId, topicId } = context;
const model = useAgentStore(agentByIdSelectors.getAgentModelById(agentId));
const provider = useAgentStore(agentByIdSelectors.getAgentModelProviderById(agentId));
@@ -35,7 +37,12 @@ const ChatConversation = memo(() => {
agentId && agentId !== inboxAgentId && agentVisibility !== 'private' ? agentId : undefined;
const { canUseResource } = useResourceAccess('agent', gatedResourceId);
- const { handleUploadFiles } = useUploadFiles({ agentId, model, provider });
+ const { handleUploadFiles } = useUploadFiles({
+ agentId,
+ contextKey: messageMapKey(context),
+ model,
+ provider,
+ });
const { enableLocalPathReference, handleLocalPaths } = useLocalPathReference(agentId, topicId);
const content = (
diff --git a/src/routes/(main)/group/features/Conversation/index.tsx b/src/routes/(main)/group/features/Conversation/index.tsx
index cd521004624..9c4d3a78c48 100644
--- a/src/routes/(main)/group/features/Conversation/index.tsx
+++ b/src/routes/(main)/group/features/Conversation/index.tsx
@@ -4,16 +4,25 @@ import { memo } from 'react';
import DragUploadZone, { useUploadFiles } from '@/components/DragUploadZone';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import ConversationArea from './ConversationArea';
import ChatHeader from './Header';
+import { useGroupContext } from './useGroupContext';
const ChatConversation = memo(() => {
// Get current agent's model info for vision support check
const agentId = useAgentStore((s) => s.activeAgentId || '');
const model = useAgentStore(agentSelectors.currentAgentModel);
const provider = useAgentStore(agentSelectors.currentAgentModelProvider);
- const { handleUploadFiles } = useUploadFiles({ agentId, model, provider });
+ // Same key as the group composer's draft, so dropped files land in it.
+ const composerKey = messageMapKey(useGroupContext());
+ const { handleUploadFiles } = useUploadFiles({
+ agentId,
+ contextKey: composerKey,
+ model,
+ provider,
+ });
return (
<DragUploadZone style={{ height: '100%', width: '100%' }} onUploadFiles={handleUploadFiles}>
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.externalProducerSettle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.externalProducerSettle.test.ts
index 2a0584008b8..369e47ad719 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.externalProducerSettle.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.externalProducerSettle.test.ts
@@ -47,9 +47,9 @@ vi.mock('@/services/topic', () => ({
},
}));
-const moveChatContextSelections = vi.hoisted(() => vi.fn());
+const moveChatComposerAttachments = vi.hoisted(() => vi.fn());
vi.mock('@/store/file/store', () => ({
- getFileStoreState: () => ({ moveChatContextSelections }),
+ getFileStoreState: () => ({ moveChatComposerAttachments }),
}));
const mockUserDefaultConfig = vi.hoisted(() => ({
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.ts
index 14e371c71ca..87b700bebc8 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.test.ts
@@ -40,7 +40,7 @@ vi.mock('@/services/topic', () => ({
}));
vi.mock('@/store/file/store', () => ({
- getFileStoreState: () => ({ moveChatContextSelections: vi.fn() }),
+ getFileStoreState: () => ({ moveChatComposerAttachments: vi.fn() }),
}));
/** The deployment capability the transport requires. */
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.unownedRuns.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.unownedRuns.test.ts
index 880d2fd8b4e..cd55b033e1b 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.unownedRuns.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.mux.unownedRuns.test.ts
@@ -39,7 +39,7 @@ vi.mock('@/services/topic', () => ({
}));
vi.mock('@/store/file/store', () => ({
- getFileStoreState: () => ({ moveChatContextSelections: vi.fn() }),
+ getFileStoreState: () => ({ moveChatComposerAttachments: vi.fn() }),
}));
/** The deployment capability the transport requires. */
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.reconnectTeammateRun.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.reconnectTeammateRun.test.ts
index ba96196dd03..28a8f621842 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.reconnectTeammateRun.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.reconnectTeammateRun.test.ts
@@ -33,7 +33,7 @@ vi.mock('@/services/topic', () => ({
}));
vi.mock('@/store/file/store', () => ({
- getFileStoreState: () => ({ moveChatContextSelections: vi.fn() }),
+ getFileStoreState: () => ({ moveChatComposerAttachments: vi.fn() }),
}));
const mockUserState = vi.hoisted(() => ({
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.stopReclaim.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.stopReclaim.test.ts
index 77fd1dc2b93..fce863f1823 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.stopReclaim.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.stopReclaim.test.ts
@@ -47,9 +47,9 @@ vi.mock('@/services/topic', () => ({
},
}));
-const moveChatContextSelections = vi.hoisted(() => vi.fn());
+const moveChatComposerAttachments = vi.hoisted(() => vi.fn());
vi.mock('@/store/file/store', () => ({
- getFileStoreState: () => ({ moveChatContextSelections }),
+ getFileStoreState: () => ({ moveChatComposerAttachments }),
}));
const mockUserDefaultConfig = vi.hoisted(() => ({
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
index 2763176200c..743f429ff4c 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts
@@ -54,9 +54,9 @@ vi.mock('@/services/topic', () => ({
},
}));
-const moveChatContextSelections = vi.hoisted(() => vi.fn());
+const moveChatComposerAttachments = vi.hoisted(() => vi.fn());
vi.mock('@/store/file/store', () => ({
- getFileStoreState: () => ({ moveChatContextSelections }),
+ getFileStoreState: () => ({ moveChatComposerAttachments }),
}));
const mockUserDefaultConfig = vi.hoisted(() => ({
@@ -188,7 +188,7 @@ function createTestAction() {
describe('GatewayActionImpl', () => {
beforeEach(() => {
- moveChatContextSelections.mockClear();
+ moveChatComposerAttachments.mockClear();
vi.mocked(topicService.getTopicDetail).mockResolvedValue(null as never);
vi.mocked(topicService.settleRunningOperation).mockResolvedValue(undefined as never);
mockAgentStore.state = { activeAgentId: undefined, agentMap: {} };
@@ -1854,7 +1854,7 @@ describe('GatewayActionImpl', () => {
title: '666',
},
});
- expect(moveChatContextSelections).toHaveBeenCalledWith(
+ expect(moveChatComposerAttachments).toHaveBeenCalledWith(
messageMapKey({
agentId: 'agent-1',
scope: 'main',
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.watchSubAgentRun.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.watchSubAgentRun.test.ts
index 396a8abf5cb..2e4cc3f7b07 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.watchSubAgentRun.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.watchSubAgentRun.test.ts
@@ -32,7 +32,7 @@ vi.mock('@/services/topic', () => ({
}));
vi.mock('@/store/file/store', () => ({
- getFileStoreState: () => ({ moveChatContextSelections: vi.fn() }),
+ getFileStoreState: () => ({ moveChatComposerAttachments: vi.fn() }),
}));
const mockUserState = vi.hoisted(() => ({
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts
index 24201bc5ed8..4394d110c1c 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts
@@ -1096,7 +1096,7 @@ export class ConversationLifecycleActionImpl {
},
'sendMessage/optimisticCreateTopic',
);
- getFileStoreState().moveChatContextSelections(
+ getFileStoreState().moveChatComposerAttachments(
messageMapKey({ ...operationContext, topicId: null }),
currentContextKey,
);
@@ -1345,7 +1345,7 @@ export class ConversationLifecycleActionImpl {
const rollbackOptimisticTopic = (action: string) => {
if (!optimisticTopic || !optimisticTopicActive) return;
- getFileStoreState().moveChatContextSelections(
+ getFileStoreState().moveChatComposerAttachments(
currentContextKey,
messageMapKey({ ...operationContext, topicId: null }),
);
@@ -1504,7 +1504,7 @@ export class ConversationLifecycleActionImpl {
const heteroResponseMeta = heteroData as SendMessageServerResponseMeta;
const heteroMessageKey = messageMapKey(heteroContext);
this.#get().moveQueuedMessages(currentContextKey, heteroMessageKey);
- getFileStoreState().moveChatContextSelections(currentContextKey, heteroMessageKey);
+ getFileStoreState().moveChatComposerAttachments(currentContextKey, heteroMessageKey);
// Legacy queue location: follow-ups enqueued behind an op still
// registered under the pre-mint `_new` key.
if (willCreateNewTopic)
@@ -2055,7 +2055,7 @@ export class ConversationLifecycleActionImpl {
};
const finalMessageKey = messageMapKey(finalContext);
this.#get().moveQueuedMessages(currentContextKey, finalMessageKey);
- getFileStoreState().moveChatContextSelections(currentContextKey, finalMessageKey);
+ getFileStoreState().moveChatComposerAttachments(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.ts
index 51b1748fb4f..ae077502b0f 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -1277,7 +1277,7 @@ export class GatewayActionImpl {
// Attachments picked in the subtopic composer were staged under the
// `_new` key; carry them over so the next turn in the thread still sees
// them (mirrors the new-topic handoff below).
- getFileStoreState().moveChatContextSelections(
+ getFileStoreState().moveChatComposerAttachments(
messageMapKey(messageContext),
messageMapKey(resolvedMessageContext),
);
@@ -1328,7 +1328,7 @@ export class GatewayActionImpl {
title: optimisticTopic.title,
},
});
- getFileStoreState().moveChatContextSelections(
+ getFileStoreState().moveChatComposerAttachments(
messageMapKey({ ...messageContext, topicId: optimisticTopic.id }),
messageMapKey({ ...messageContext, topicId: result.topicId }),
);
diff --git a/src/store/file/slices/chat/action.test.ts b/src/store/file/slices/chat/action.test.ts
index db9134325e5..1891ed334aa 100644
--- a/src/store/file/slices/chat/action.test.ts
+++ b/src/store/file/slices/chat/action.test.ts
@@ -12,6 +12,8 @@ import { agentByIdSelectors } from '@/store/agent/selectors';
import { useFileStore as useStore } from '../../store';
const AGENT_ID = 'agent-1';
+const CONTEXT_KEY = 'main_agent-1_new';
+const uploadList = () => useStore.getState().chatUploadFileListByContext[CONTEXT_KEY] ?? [];
/** Force the conversation agent into chat / agent / heterogeneous mode for the by-id selectors. */
const mockAgentMode = ({
@@ -203,30 +205,32 @@ describe('useFileStore:chat', () => {
const { result } = renderHook(() => useStore());
act(() => {
- useStore.setState({ chatUploadFileList: [{ id: 'abc' }] as any });
+ useStore.setState({ chatUploadFileListByContext: { [CONTEXT_KEY]: [{ id: 'abc' }] } as any });
});
- expect(result.current.chatUploadFileList).toEqual([{ id: 'abc' }]);
+ expect(uploadList()).toEqual([{ id: 'abc' }]);
act(() => {
- result.current.clearChatUploadFileList();
+ result.current.clearChatUploadFileList(CONTEXT_KEY);
});
- expect(result.current.chatUploadFileList).toEqual([]);
+ expect(uploadList()).toEqual([]);
});
it('clears only submitted uploads while retaining newer files and their status', () => {
const { result } = renderHook(() => useStore());
const newerFile = { id: 'new', status: 'uploading' };
act(() => {
- useStore.setState({ chatUploadFileList: [{ id: 'submitted' }, newerFile] as any });
- result.current.clearChatUploadFileList(['submitted']);
+ useStore.setState({
+ chatUploadFileListByContext: { [CONTEXT_KEY]: [{ id: 'submitted' }, newerFile] } as any,
+ });
+ result.current.clearChatUploadFileList(CONTEXT_KEY, ['submitted']);
});
- expect(result.current.chatUploadFileList).toEqual([newerFile]);
+ expect(uploadList()).toEqual([newerFile]);
act(() => {
- result.current.clearChatUploadFileList([]);
+ result.current.clearChatUploadFileList(CONTEXT_KEY, []);
});
- expect(result.current.chatUploadFileList).toEqual([newerFile]);
+ expect(uploadList()).toEqual([newerFile]);
});
it('restoreChatUploadFileList puts cleared uploads back without duplicating newer drafts', () => {
@@ -237,16 +241,128 @@ describe('useFileStore:chat', () => {
// The composer cleared everything on send; a fresh draft arrived while the
// rejected send was still unwinding.
act(() => {
- useStore.setState({ chatUploadFileList: [newerFile] as any });
- result.current.restoreChatUploadFileList([submittedFile, newerFile] as any);
+ useStore.setState({ chatUploadFileListByContext: { [CONTEXT_KEY]: [newerFile] } as any });
+ result.current.restoreChatUploadFileList(CONTEXT_KEY, [submittedFile, newerFile] as any);
+ });
+
+ expect(uploadList()).toEqual([newerFile, submittedFile]);
+
+ act(() => {
+ result.current.restoreChatUploadFileList(CONTEXT_KEY, []);
+ });
+ expect(uploadList()).toEqual([newerFile, submittedFile]);
+ });
+
+ // Regression: one global upload list showed a conversation's attachments in
+ // every other conversation, while its text draft stayed behind.
+ it('keeps the uploads of each conversation to itself', () => {
+ const { result } = renderHook(() => useStore());
+ const fileA = { id: 'a', status: 'success' };
+ const fileB = { id: 'b', status: 'success' };
+
+ act(() => {
+ useStore.setState({ chatUploadFileListByContext: {} });
+ result.current.dispatchChatUploadFileList('topic-a', {
+ files: [fileA] as any,
+ type: 'addFiles',
+ });
+ result.current.dispatchChatUploadFileList('topic-b', {
+ files: [fileB] as any,
+ type: 'addFiles',
+ });
+ });
+
+ expect(result.current.chatUploadFileListByContext).toEqual({
+ 'topic-a': [fileA],
+ 'topic-b': [fileB],
+ });
+
+ act(() => {
+ result.current.clearChatUploadFileList('topic-a');
});
- expect(result.current.chatUploadFileList).toEqual([newerFile, submittedFile]);
+ // Back on topic-b its upload is untouched; the emptied topic-a bucket is gone.
+ expect(result.current.chatUploadFileListByContext).toEqual({ 'topic-b': [fileB] });
+ });
+
+ it('moves staged uploads and context selections together to the new key', () => {
+ const { result } = renderHook(() => useStore());
+ const staged = { id: 'staged', status: 'success' };
+ const existing = { id: 'existing', status: 'success' };
+ const selection: ChatContextContent = { content: 'quote', id: 'sel', type: 'text' };
act(() => {
- result.current.restoreChatUploadFileList([]);
+ useStore.setState({
+ chatContextSelectionsByContext: { blank: [selection] },
+ chatUploadFileListByContext: { blank: [staged], topic: [existing] } as any,
+ });
+ result.current.moveChatComposerAttachments('blank', 'topic');
+ });
+
+ expect(result.current.chatUploadFileListByContext).toEqual({ topic: [existing, staged] });
+ expect(result.current.chatContextSelectionsByContext).toEqual({ topic: [selection] });
+ });
+
+ // Regression: a moved in-flight upload was found by its pending id (the file
+ // name), so a same-named upload staged later under the old key took its result.
+ it('reports a moved in-flight upload to its own chip, not a same-named later one', async () => {
+ mockAgentMode({ enableAgentMode: true, heterogeneous: false });
+ const { result } = renderHook(() => useStore());
+ const finishes: (() => void)[] = [];
+ vi.spyOn(result.current, 'uploadWithProgress').mockImplementation(
+ ({ file, onStatusUpdate }) =>
+ new Promise((resolve) => {
+ const n = finishes.length + 1;
+ finishes.push(() => {
+ onStatusUpdate?.({
+ id: file.name,
+ type: 'updateFile',
+ value: { fileUrl: `url-${n}`, id: `server-${n}`, status: 'success' },
+ });
+ resolve({ id: `server-${n}`, url: `url-${n}` } as any);
+ });
+ }),
+ );
+ useStore.setState({ chatUploadFileListByContext: {} });
+
+ let firstUpload!: Promise<void>;
+ let secondUpload!: Promise<void>;
+ await act(async () => {
+ firstUpload = result.current.uploadChatFiles(
+ 'blank',
+ [new File(['a'], 'notes.txt', { type: 'text/plain' })],
+ AGENT_ID,
+ );
+ await vi.waitFor(() => expect(finishes).toHaveLength(1));
+ });
+
+ // The blank conversation becomes a topic mid-upload; the user then stages a
+ // same-named file in the next blank conversation.
+ await act(async () => {
+ result.current.moveChatUploadFileList('blank', 'topic');
+ secondUpload = result.current.uploadChatFiles(
+ 'blank',
+ [new File(['b'], 'notes.txt', { type: 'text/plain' })],
+ AGENT_ID,
+ );
+ await vi.waitFor(() => expect(finishes).toHaveLength(2));
+ });
+
+ await act(async () => {
+ finishes[0]();
+ await firstUpload;
+ });
+
+ const lists = useStore.getState().chatUploadFileListByContext;
+ expect(lists.topic).toEqual([
+ expect.objectContaining({ fileUrl: 'url-1', id: 'server-1', status: 'success' }),
+ ]);
+ expect(lists.blank).toEqual([expect.objectContaining({ id: 'notes.txt', status: 'pending' })]);
+
+ await act(async () => {
+ finishes[1]();
+ await secondUpload;
});
- expect(result.current.chatUploadFileList).toEqual([newerFile, submittedFile]);
});
it('uploadChatFiles should reject unsupported files before upload in chat mode', async () => {
@@ -258,13 +374,14 @@ describe('useFileStore:chat', () => {
act(() => {
useStore.setState({
- chatUploadFileList: [],
+ chatUploadFileListByContext: {},
uploadWithProgress: uploadWithProgress as any,
});
});
await act(async () => {
await result.current.uploadChatFiles(
+ CONTEXT_KEY,
[
new File(['<svg />'], 'icon.svg', { type: 'image/svg+xml' }),
new File(['zip'], 'archive.zip', { type: 'application/zip' }),
@@ -274,7 +391,7 @@ describe('useFileStore:chat', () => {
});
expect(uploadWithProgress).not.toHaveBeenCalled();
- expect(result.current.chatUploadFileList).toEqual([]);
+ expect(uploadList()).toEqual([]);
expect(toast.error).toHaveBeenCalledWith(expect.any(String));
});
@@ -286,13 +403,14 @@ describe('useFileStore:chat', () => {
act(() => {
useStore.setState({
- chatUploadFileList: [],
+ chatUploadFileListByContext: {},
uploadWithProgress: uploadWithProgress as any,
});
});
await act(async () => {
await result.current.uploadChatFiles(
+ CONTEXT_KEY,
[new File(['zip'], 'archive.zip', { type: 'application/zip' })],
AGENT_ID,
);
@@ -313,13 +431,14 @@ describe('useFileStore:chat', () => {
act(() => {
useStore.setState({
- chatUploadFileList: [],
+ chatUploadFileListByContext: {},
uploadWithProgress: uploadWithProgress as any,
});
});
await act(async () => {
await result.current.uploadChatFiles(
+ CONTEXT_KEY,
[new File(['profile'], 'Communication_Notifications.provisionprofile')],
AGENT_ID,
);
@@ -341,10 +460,10 @@ describe('useFileStore:chat', () => {
});
await act(async () => {
- await result.current.uploadChatFiles([file], AGENT_ID);
+ await result.current.uploadChatFiles(CONTEXT_KEY, [file], AGENT_ID);
});
- expect(result.current.chatUploadFileList).toEqual([
+ expect(uploadList()).toEqual([
expect.objectContaining({
agentId: AGENT_ID,
error: 'You do not have permission to upload files in this workspace.',
@@ -372,10 +491,10 @@ describe('useFileStore:chat', () => {
);
await act(async () => {
- await result.current.uploadChatFiles([file], AGENT_ID);
+ await result.current.uploadChatFiles(CONTEXT_KEY, [file], AGENT_ID);
});
- expect(result.current.chatUploadFileList).toEqual([
+ expect(uploadList()).toEqual([
expect.objectContaining({
error: 'The upload service is unavailable. (HTTP 502 · Request ID: a4f7-SJC)',
id: 'report.docx',
@@ -397,7 +516,7 @@ describe('useFileStore:chat', () => {
const file = new File(['test'], 'notes.pdf', { type: 'application/pdf' });
await act(async () => {
- await result.current.uploadChatFiles([file], AGENT_ID, { shareId: SHARE_ID });
+ await result.current.uploadChatFiles(CONTEXT_KEY, [file], AGENT_ID, { shareId: SHARE_ID });
});
expect(mockUploadShareVisitorFile).toHaveBeenCalledWith(
@@ -407,7 +526,7 @@ describe('useFileStore:chat', () => {
// Creator-owned row: the visitor's `document.parseFileContent` could not
// reach it; the run parses it on the creator's account instead.
expect(ragService.parseFileContent).not.toHaveBeenCalled();
- expect(result.current.chatUploadFileList).toEqual([
+ expect(uploadList()).toEqual([
expect.objectContaining({ agentId: AGENT_ID, id: 'notes.pdf', shareId: SHARE_ID }),
]);
});
@@ -418,12 +537,12 @@ describe('useFileStore:chat', () => {
const file = new File(['x'], 'tool.exe', { type: 'application/octet-stream' });
await act(async () => {
- await result.current.uploadChatFiles([file], AGENT_ID, { shareId: SHARE_ID });
+ await result.current.uploadChatFiles(CONTEXT_KEY, [file], AGENT_ID, { shareId: SHARE_ID });
});
expect(mockUploadShareVisitorFile).not.toHaveBeenCalled();
expect(toast.error).toHaveBeenCalled();
- expect(result.current.chatUploadFileList).toEqual([]);
+ expect(uploadList()).toEqual([]);
});
it('rejects a file over SHARE_VISITOR_MAX_FILE_SIZE before any request', async () => {
@@ -433,12 +552,12 @@ describe('useFileStore:chat', () => {
Object.defineProperty(big, 'size', { value: 33 * 1024 * 1024 });
await act(async () => {
- await result.current.uploadChatFiles([big], AGENT_ID, { shareId: SHARE_ID });
+ await result.current.uploadChatFiles(CONTEXT_KEY, [big], AGENT_ID, { shareId: SHARE_ID });
});
expect(mockUploadShareVisitorFile).not.toHaveBeenCalled();
expect(toast.error).toHaveBeenCalledWith('share.visitor.upload.fileTooLarge');
- expect(result.current.chatUploadFileList).toEqual([]);
+ expect(uploadList()).toEqual([]);
});
it("surfaces the creator's storage block as share copy, not the visitor's own plan", async () => {
@@ -448,10 +567,10 @@ describe('useFileStore:chat', () => {
const file = new File(['test'], 'notes.pdf', { type: 'application/pdf' });
await act(async () => {
- await result.current.uploadChatFiles([file], AGENT_ID, { shareId: SHARE_ID });
+ await result.current.uploadChatFiles(CONTEXT_KEY, [file], AGENT_ID, { shareId: SHARE_ID });
});
- expect(result.current.chatUploadFileList).toEqual([
+ expect(uploadList()).toEqual([
expect.objectContaining({
error: 'share.visitor.upload.creatorStorageBlocked',
id: 'notes.pdf',
@@ -468,15 +587,17 @@ describe('useFileStore:chat', () => {
act(() => {
useStore.setState({
- chatUploadFileList: [{ id: 'file-1', shareId: 'share-1', status: 'success' }] as any,
+ chatUploadFileListByContext: {
+ [CONTEXT_KEY]: [{ id: 'file-1', shareId: 'share-1', status: 'success' }],
+ } as any,
});
});
await act(async () => {
- await result.current.removeChatUploadFile('file-1');
+ await result.current.removeChatUploadFile(CONTEXT_KEY, 'file-1');
});
- expect(result.current.chatUploadFileList).toEqual([]);
+ expect(uploadList()).toEqual([]);
expect(shareChatService.removeFile).toHaveBeenCalledWith('share-1', 'file-1');
expect(removeFile).not.toHaveBeenCalled();
});
@@ -487,15 +608,17 @@ describe('useFileStore:chat', () => {
act(() => {
// Still keyed by file name: nothing exists server-side to delete.
useStore.setState({
- chatUploadFileList: [{ id: 'cat.png', shareId: 'share-1', status: 'error' }] as any,
+ chatUploadFileListByContext: {
+ [CONTEXT_KEY]: [{ id: 'cat.png', shareId: 'share-1', status: 'error' }],
+ } as any,
});
});
await act(async () => {
- await result.current.removeChatUploadFile('cat.png');
+ await result.current.removeChatUploadFile(CONTEXT_KEY, 'cat.png');
});
- expect(result.current.chatUploadFileList).toEqual([]);
+ expect(uploadList()).toEqual([]);
expect(shareChatService.removeFile).not.toHaveBeenCalled();
});
@@ -504,14 +627,16 @@ describe('useFileStore:chat', () => {
const { result } = renderHook(() => useStore());
act(() => {
- useStore.setState({ chatUploadFileList: [{ id: 'file-1' }] as any });
+ useStore.setState({
+ chatUploadFileListByContext: { [CONTEXT_KEY]: [{ id: 'file-1' }] } as any,
+ });
});
await act(async () => {
- await result.current.removeChatUploadFile('file-1');
+ await result.current.removeChatUploadFile(CONTEXT_KEY, 'file-1');
});
- expect(result.current.chatUploadFileList).toEqual([]);
+ expect(uploadList()).toEqual([]);
expect(removeFile).toHaveBeenCalledWith('file-1');
});
@@ -521,17 +646,19 @@ describe('useFileStore:chat', () => {
act(() => {
useStore.setState({
- chatUploadFileList: [{ id: 'file-1', skipRemoveFile: true }] as any,
+ chatUploadFileListByContext: {
+ [CONTEXT_KEY]: [{ id: 'file-1', skipRemoveFile: true }],
+ } as any,
});
});
await act(async () => {
- await result.current.removeChatUploadFile('file-1');
+ await result.current.removeChatUploadFile(CONTEXT_KEY, 'file-1');
});
// draft entry is dropped, but the persisted file backing the original
// message must NOT be deleted
- expect(result.current.chatUploadFileList).toEqual([]);
+ expect(uploadList()).toEqual([]);
expect(removeFile).not.toHaveBeenCalled();
});
});
diff --git a/src/store/file/slices/chat/action.ts b/src/store/file/slices/chat/action.ts
index 1cc077ed728..67e9b30bf4c 100644
--- a/src/store/file/slices/chat/action.ts
+++ b/src/store/file/slices/chat/action.ts
@@ -92,9 +92,18 @@ const getUploadErrorDescription = (error: unknown): string => {
: t('upload.unknownError', { ns: 'error', reason: getErrorMessage(error) });
};
+const EMPTY_CHAT_UPLOAD_FILE_LIST: UploadFileItem[] = [];
+
export class FileActionImpl {
readonly #get: () => FileStore;
readonly #set: Setter;
+ /**
+ * The key each in-flight upload's chip currently lives under. A move
+ * (`moveChatUploadFileList`) updates it, so an upload keeps reporting to its
+ * own chip instead of resolving by id — a pending id is only the file name,
+ * and a same-named upload may appear under the old key later.
+ */
+ readonly #inFlightUploads = new Set<{ contextKey: string }>();
constructor(set: Setter, get: () => FileStore, _api?: unknown) {
void _api;
@@ -102,6 +111,27 @@ export class FileActionImpl {
this.#get = get;
}
+ #getChatUploadFileList = (contextKey: string): UploadFileItem[] =>
+ this.#get().chatUploadFileListByContext[contextKey] ?? EMPTY_CHAT_UPLOAD_FILE_LIST;
+
+ #setChatUploadFileList = (contextKey: string, list: UploadFileItem[], action: string): void => {
+ const currentMap = this.#get().chatUploadFileListByContext;
+
+ // Drop emptied buckets so conversations visited once don't pile up keys.
+ if (list.length === 0) {
+ if (!(contextKey in currentMap)) return;
+ const { [contextKey]: _removed, ...nextMap } = currentMap;
+ this.#set({ chatUploadFileListByContext: nextMap }, false, action);
+ return;
+ }
+
+ this.#set(
+ { chatUploadFileListByContext: { ...currentMap, [contextKey]: list } },
+ false,
+ action,
+ );
+ };
+
addChatContextSelection = ({
contextKey,
selection,
@@ -128,11 +158,11 @@ export class FileActionImpl {
this.#set({ chatContextSelectionsByContext: nextMap }, false, n('clearChatContextSelections'));
};
- clearChatUploadFileList = (submittedIds?: string[]): void => {
- const chatUploadFileList = submittedIds
- ? this.#get().chatUploadFileList.filter((file) => !submittedIds.includes(file.id))
+ clearChatUploadFileList = (contextKey: string, submittedIds?: string[]): void => {
+ const next = submittedIds
+ ? this.#getChatUploadFileList(contextKey).filter((file) => !submittedIds.includes(file.id))
: [];
- this.#set({ chatUploadFileList }, false, n('clearChatUploadFileList'));
+ this.#setChatUploadFileList(contextKey, next, n('clearChatUploadFileList'));
};
/**
@@ -141,21 +171,57 @@ export class FileActionImpl {
* up front). Items already in the list are skipped by id so a concurrent
* draft does not end up with duplicates.
*/
- restoreChatUploadFileList = (files: UploadFileItem[]): void => {
+ restoreChatUploadFileList = (contextKey: string, files: UploadFileItem[]): void => {
if (files.length === 0) return;
- const currentIds = new Set(this.#get().chatUploadFileList.map((file) => file.id));
+ const currentIds = new Set(this.#getChatUploadFileList(contextKey).map((file) => file.id));
const restored = files.filter((file) => !currentIds.has(file.id));
if (restored.length === 0) return;
- this.#get().dispatchChatUploadFileList({ files: restored, type: 'addFiles' });
+ this.#get().dispatchChatUploadFileList(contextKey, { files: restored, type: 'addFiles' });
};
- dispatchChatUploadFileList = (payload: UploadFileListDispatch): void => {
- const nextValue = uploadFileListReducer(this.#get().chatUploadFileList, payload);
- if (nextValue === this.#get().chatUploadFileList) return;
+ dispatchChatUploadFileList = (contextKey: string, payload: UploadFileListDispatch): void => {
+ const current = this.#getChatUploadFileList(contextKey);
+ const nextValue = uploadFileListReducer(current, payload);
+ if (nextValue === current) return;
- this.#set({ chatUploadFileList: nextValue }, false, `dispatchChatFileList/${payload.type}`);
+ this.#setChatUploadFileList(contextKey, nextValue, `dispatchChatFileList/${payload.type}`);
+ };
+
+ /** Upload half of `moveChatComposerAttachments`. */
+ moveChatUploadFileList = (fromContextKey: string, toContextKey: string): void => {
+ if (fromContextKey === toContextKey) return;
+
+ // Uploads still being prepared follow the composer even before their chip exists.
+ for (const upload of this.#inFlightUploads) {
+ if (upload.contextKey === fromContextKey) upload.contextKey = toContextKey;
+ }
+
+ const source = this.#getChatUploadFileList(fromContextKey);
+ if (source.length === 0) return;
+
+ const sourceIds = new Set(source.map((file) => file.id));
+ const target = this.#getChatUploadFileList(toContextKey).filter(
+ (file) => !sourceIds.has(file.id),
+ );
+ const { [fromContextKey]: _removed, ...nextMap } = this.#get().chatUploadFileListByContext;
+
+ this.#set(
+ { chatUploadFileListByContext: { ...nextMap, [toContextKey]: [...target, ...source] } },
+ false,
+ n('moveChatUploadFileList'),
+ );
+ };
+
+ /**
+ * Carry everything a composer has staged — context selections and uploads —
+ * to another key, e.g. when a blank conversation becomes a real topic
+ * mid-send, so the composer at the new key still shows them.
+ */
+ moveChatComposerAttachments = (fromContextKey: string, toContextKey: string): void => {
+ this.moveChatContextSelections(fromContextKey, toContextKey);
+ this.moveChatUploadFileList(fromContextKey, toContextKey);
};
moveChatContextSelections = (fromContextKey: string, toContextKey: string): void => {
@@ -215,14 +281,12 @@ export class FileActionImpl {
);
};
- removeChatUploadFile = async (id: string): Promise<void> => {
- const { chatUploadFileList, dispatchChatUploadFileList } = this.#get();
-
+ removeChatUploadFile = async (contextKey: string, id: string): Promise<void> => {
// Restored entries reference an already-persisted file that still backs the
// original message — only drop the draft item, never delete the file itself.
- const item = chatUploadFileList.find((entry) => entry.id === id);
+ const item = this.#getChatUploadFileList(contextKey).find((entry) => entry.id === id);
- dispatchChatUploadFileList({ id, type: 'removeFile' });
+ this.#get().dispatchChatUploadFileList(contextKey, { id, type: 'removeFile' });
if (item?.skipRemoveFile) return;
@@ -240,13 +304,12 @@ export class FileActionImpl {
await fileService.removeFile(id);
};
- retryChatUploadFile = async (id: string): Promise<void> => {
- const { chatUploadFileList, dispatchChatUploadFileList } = this.#get();
- const item = chatUploadFileList.find((file) => file.id === id);
+ retryChatUploadFile = async (contextKey: string, id: string): Promise<void> => {
+ const item = this.#getChatUploadFileList(contextKey).find((file) => file.id === id);
if (!item?.agentId) return;
- dispatchChatUploadFileList({ id, type: 'removeFile' });
- await this.uploadChatFiles([item.file], item.agentId, { shareId: item.shareId });
+ this.#get().dispatchChatUploadFileList(contextKey, { id, type: 'removeFile' });
+ await this.uploadChatFiles(contextKey, [item.file], item.agentId, { shareId: item.shareId });
};
startAsyncTask = async (
@@ -288,12 +351,30 @@ export class FileActionImpl {
};
uploadChatFiles = async (
+ contextKey: string,
rawFiles: File[],
agentId: string,
options: ChatUploadOptions = {},
): Promise<void> => {
- const { dispatchChatUploadFileList } = this.#get();
const { shareId } = options;
+ const upload = { contextKey };
+ this.#inFlightUploads.add(upload);
+ try {
+ await this.#uploadChatFilesTo(upload, rawFiles, agentId, shareId);
+ } finally {
+ this.#inFlightUploads.delete(upload);
+ }
+ };
+
+ #uploadChatFilesTo = async (
+ upload: { contextKey: string },
+ rawFiles: File[],
+ agentId: string,
+ shareId: string | undefined,
+ ): Promise<void> => {
+ // The chip may be handed to another key mid-upload; dispatch to wherever it is now.
+ const dispatchChatUploadFileList = (payload: UploadFileListDispatch) =>
+ this.#get().dispatchChatUploadFileList(upload.contextKey, payload);
// 0. skip file in blacklist
const filteredFiles = rawFiles.filter((file) => !FILE_UPLOAD_BLACKLIST.includes(file.name));
diff --git a/src/store/file/slices/chat/initialState.ts b/src/store/file/slices/chat/initialState.ts
index ff1b2579cf1..5a5060f4d26 100644
--- a/src/store/file/slices/chat/initialState.ts
+++ b/src/store/file/slices/chat/initialState.ts
@@ -4,12 +4,16 @@ import { type UploadFileItem } from '@/types/files/upload';
export interface ImageFileState {
chatContextSelectionsByContext: Record<string, ChatContextContent[]>;
- chatUploadFileList: UploadFileItem[];
+ /**
+ * Composer uploads, one list per conversation (keyed like the composer's
+ * draft), so an attachment stays with the conversation it was added to.
+ */
+ chatUploadFileListByContext: Record<string, UploadFileItem[]>;
uploadingIds: string[];
}
export const initialImageFileState: ImageFileState = {
chatContextSelectionsByContext: {},
- chatUploadFileList: [],
+ chatUploadFileListByContext: {},
uploadingIds: [],
};
diff --git a/src/store/file/slices/chat/selectors.test.ts b/src/store/file/slices/chat/selectors.test.ts
index 7a28aec910a..f705844d384 100644
--- a/src/store/file/slices/chat/selectors.test.ts
+++ b/src/store/file/slices/chat/selectors.test.ts
@@ -8,17 +8,9 @@ import { UPLOAD_STATUS_SET } from '@/types/files/upload';
import { fileChatSelectors, filesSelectors } from './selectors';
-describe('filesSelectors', () => {
- describe('chatUploadFileList', () => {
- it('should return the chatUploadFileList from state', () => {
- const state = {
- ...initialState,
- chatUploadFileList: [{ id: '1' }] as UploadFileItem[],
- } as FilesStoreState;
- expect(filesSelectors.chatUploadFileList(state)).toEqual([{ id: '1' }]);
- });
- });
+const CONTEXT_KEY = 'main_agent-1_new';
+describe('filesSelectors', () => {
describe('isImageUploading', () => {
it('should return true if there are uploading ids', () => {
const state = { uploadingIds: ['1', '2'] } as FilesStoreState;
@@ -72,13 +64,15 @@ describe('fileChatSelectors', () => {
describe('chatRawFileList', () => {
it('should return a list of raw files', () => {
const state = {
- chatUploadFileList: [
- { file: { name: 'test1.jpg' } },
- { file: { name: 'test2.jpg' } },
- ] as UploadFileItem[],
+ chatUploadFileListByContext: {
+ [CONTEXT_KEY]: [
+ { file: { name: 'test1.jpg' } },
+ { file: { name: 'test2.jpg' } },
+ ] as UploadFileItem[],
+ },
} as FilesStoreState;
- expect(fileChatSelectors.chatRawFileList(state)).toEqual([
+ expect(fileChatSelectors.chatRawFileList(CONTEXT_KEY)(state)).toEqual([
{ name: 'test1.jpg' },
{ name: 'test2.jpg' },
]);
@@ -88,53 +82,63 @@ describe('fileChatSelectors', () => {
describe('chatUploadFileList', () => {
it('should return the chatUploadFileList from state', () => {
const state = {
- chatUploadFileList: [{ id: '1' }] as UploadFileItem[],
+ chatUploadFileListByContext: { [CONTEXT_KEY]: [{ id: '1' }] as UploadFileItem[] },
} as FilesStoreState;
- expect(fileChatSelectors.chatUploadFileList(state)).toEqual([{ id: '1' }]);
+ expect(fileChatSelectors.chatUploadFileList(CONTEXT_KEY)(state)).toEqual([{ id: '1' }]);
});
});
describe('chatUploadFileListHasItem', () => {
it('should return true if chatUploadFileList has items', () => {
- const state = { chatUploadFileList: [{ id: '1' }] as UploadFileItem[] } as FilesStoreState;
- expect(fileChatSelectors.chatUploadFileListHasItem(state)).toBe(true);
+ const state = {
+ chatUploadFileListByContext: { [CONTEXT_KEY]: [{ id: '1' }] as UploadFileItem[] },
+ } as FilesStoreState;
+ expect(fileChatSelectors.chatUploadFileListHasItem(CONTEXT_KEY)(state)).toBe(true);
});
it('should return false if chatUploadFileList is empty', () => {
- const state = { chatUploadFileList: [] as UploadFileItem[] } as FilesStoreState;
- expect(fileChatSelectors.chatUploadFileListHasItem(state)).toBe(false);
+ const state = {
+ chatUploadFileListByContext: { [CONTEXT_KEY]: [] as UploadFileItem[] },
+ } as FilesStoreState;
+ expect(fileChatSelectors.chatUploadFileListHasItem(CONTEXT_KEY)(state)).toBe(false);
});
});
describe('isUploadingFiles', () => {
it('should return true if any file is in uploading status', () => {
const state = {
- chatUploadFileList: [
- { status: Array.from(UPLOAD_STATUS_SET)[0] },
- { status: 'completed' },
- ] as UploadFileItem[],
+ chatUploadFileListByContext: {
+ [CONTEXT_KEY]: [
+ { status: Array.from(UPLOAD_STATUS_SET)[0] },
+ { status: 'completed' },
+ ] as UploadFileItem[],
+ },
} as FilesStoreState;
- expect(fileChatSelectors.isUploadingFiles(state)).toBe(true);
+ expect(fileChatSelectors.isUploadingFiles(CONTEXT_KEY)(state)).toBe(true);
});
it('should return true if any file has unfinished embedding tasks', () => {
const state = {
- chatUploadFileList: [
- { status: 'success', tasks: { finishEmbedding: false } },
- { status: 'success', tasks: { finishEmbedding: true } },
- ] as UploadFileItem[],
+ chatUploadFileListByContext: {
+ [CONTEXT_KEY]: [
+ { status: 'success', tasks: { finishEmbedding: false } },
+ { status: 'success', tasks: { finishEmbedding: true } },
+ ] as UploadFileItem[],
+ },
} as FilesStoreState;
- expect(fileChatSelectors.isUploadingFiles(state)).toBe(true);
+ expect(fileChatSelectors.isUploadingFiles(CONTEXT_KEY)(state)).toBe(true);
});
it('should return false if no files are uploading or have unfinished tasks', () => {
const state: FilesStoreState = {
- chatUploadFileList: [
- { status: 'success', tasks: { finishEmbedding: true } },
- { status: 'success' },
- ] as UploadFileItem[],
+ chatUploadFileListByContext: {
+ [CONTEXT_KEY]: [
+ { status: 'success', tasks: { finishEmbedding: true } },
+ { status: 'success' },
+ ] as UploadFileItem[],
+ },
} as FilesStoreState;
- expect(fileChatSelectors.isUploadingFiles(state)).toBe(false);
+ expect(fileChatSelectors.isUploadingFiles(CONTEXT_KEY)(state)).toBe(false);
});
});
});
diff --git a/src/store/file/slices/chat/selectors.ts b/src/store/file/slices/chat/selectors.ts
index f1af3e046d7..856ec75dd72 100644
--- a/src/store/file/slices/chat/selectors.ts
+++ b/src/store/file/slices/chat/selectors.ts
@@ -1,25 +1,31 @@
import { type ChatContextContent } from '@lobechat/types';
-import { UPLOAD_STATUS_SET } from '@/types/files/upload';
+import { UPLOAD_STATUS_SET, type UploadFileItem } from '@/types/files/upload';
import { type FilesStoreState } from '../../initialState';
const EMPTY_CHAT_CONTEXT_SELECTIONS: ChatContextContent[] = [];
+const EMPTY_CHAT_UPLOAD_FILE_LIST: UploadFileItem[] = [];
-const chatUploadFileList = (s: FilesStoreState) => s.chatUploadFileList;
+const chatUploadFileList = (contextKey?: string) => (s: FilesStoreState) =>
+ contextKey
+ ? (s.chatUploadFileListByContext[contextKey] ?? EMPTY_CHAT_UPLOAD_FILE_LIST)
+ : EMPTY_CHAT_UPLOAD_FILE_LIST;
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 chatRawFileList = (contextKey?: string) => (s: FilesStoreState) =>
+ chatUploadFileList(contextKey)(s).map((item) => item.file);
+const chatUploadFileListHasItem = (contextKey?: string) => (s: FilesStoreState) =>
+ chatUploadFileList(contextKey)(s).length > 0;
const chatContextSelectionHasItem = (contextKey?: string) => (s: FilesStoreState) =>
contextKey ? (s.chatContextSelectionsByContext[contextKey]?.length ?? 0) > 0 : false;
-const isUploadingFiles = (s: FilesStoreState) =>
- s.chatUploadFileList.some(
+const isUploadingFiles = (contextKey?: string) => (s: FilesStoreState) =>
+ chatUploadFileList(contextKey)(s).some(
(file) =>
// is file status in uploading
UPLOAD_STATUS_SET.has(file.status) ||
@@ -28,7 +34,6 @@ const isUploadingFiles = (s: FilesStoreState) =>
);
export const filesSelectors = {
- chatUploadFileList,
isImageUploading,
};