🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(chat-input): image cards, inline image references, and quote selection (#23080)
YuTengjing3b4c82551c88
diff --git a/locales/ar/chat.json b/locales/ar/chat.jsonindex 273d506dde9..4b94debe0be 100644--- a/locales/ar/chat.json+++ b/locales/ar/chat.json@@ -2925,9 +2925,6 @@"terminalPanel.split": "تقسيم الطرفية","terminalPanel.targetLocal": "هذا الكمبيوتر","terminalPanel.title": "الطرفية",- "textSelection.addToConversation": "إضافة إلى المحادثة",- "textSelection.added": "تمت الإضافة إلى سياق المحادثة",- "textSelection.title": "اختيار الرسالة","thread.closeSubagentThread": "طي محادثة الوكيل الفرعي","thread.dividerContinuation": "تم التشعب هنا، مع وراثة سياق الدردشة الرئيسي حتى الآن","thread.dividerStandalone": "تم التشعب هنا، مع وراثة الرسالة أعلاه فقط",diff --git a/locales/bg-BG/chat.json b/locales/bg-BG/chat.jsonindex 0ce0a69b4d6..1a88c4aea40 100644--- a/locales/bg-BG/chat.json+++ b/locales/bg-BG/chat.json@@ -2927,9 +2927,6 @@"terminalPanel.split": "Раздели терминала","terminalPanel.targetLocal": "Този компютър","terminalPanel.title": "Терминал",- "textSelection.addToConversation": "Добавяне към разговора",- "textSelection.added": "Добавено към контекста на разговора",- "textSelection.title": "Избор на съобщение","thread.closeSubagentThread": "Свиване на разговора със субагента","thread.dividerContinuation": "Разклонено тук, наследявайки основния контекст на чата досега","thread.dividerStandalone": "Разклонено тук, наследявайки само горното съобщение",diff --git a/locales/de-DE/chat.json b/locales/de-DE/chat.jsonindex 33b642efaa5..7aabaa039fd 100644--- a/locales/de-DE/chat.json+++ b/locales/de-DE/chat.json@@ -2925,9 +2925,6 @@"terminalPanel.split": "Terminal teilen","terminalPanel.targetLocal": "Dieser Computer","terminalPanel.title": "Terminal",- "textSelection.addToConversation": "Zur Unterhaltung hinzufügen",- "textSelection.added": "Zum Unterhaltungskontext hinzugefügt",- "textSelection.title": "Nachrichtenauswahl","thread.closeSubagentThread": "Unteragenten-Unterhaltung einklappen","thread.dividerContinuation": "Hier verzweigt, wobei der bisherige Hauptchat-Kontext übernommen wird","thread.dividerStandalone": "Hier verzweigt, wobei nur die obige Nachricht übernommen wird",diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 7fe72f8d8e4..fde849264bd 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -2996,9 +2996,9 @@"terminalPanel.split": "Split terminal","terminalPanel.targetLocal": "This computer","terminalPanel.title": "Terminal",- "textSelection.addToConversation": "Add to conversation",- "textSelection.added": "Added to conversation context",- "textSelection.title": "Message selection",+ "textSelection.copied": "Copied",+ "textSelection.copy": "Copy",+ "textSelection.quote": "Quote","thread.closeSubagentThread": "Hide Detail","thread.dividerContinuation": "Forked here, inheriting the main chat context so far","thread.dividerStandalone": "Forked here, inheriting only the message above",@@ -3164,6 +3164,9 @@"upload.clientMode.disabled": "The current model does not support visual recognition and file analysis. Please switch models to use this feature.","upload.clientMode.fileNotSupported": "File uploads are not supported in browser mode; only images are allowed.","upload.clientMode.visionNotSupported": "The current model does not support visual recognition. Please switch to a different model to use this feature.",+ "upload.image.label": "Image {{number}}",+ "upload.image.preview": "Preview {{name}}",+ "upload.image.remove": "Remove {{name}}","upload.localPathReference": "Large files are referenced by their local path instead of uploaded, so the agent reads the original file directly.","upload.preview.prepareTasks": "Preparing chunks...","upload.preview.status.cancelled": "Upload cancelled",diff --git a/locales/en-US/labs.json b/locales/en-US/labs.jsonindex 22147dec1f5..b4b5fa91135 100644--- a/locales/en-US/labs.json+++ b/locales/en-US/labs.json@@ -30,7 +30,7 @@"features.imessage.title": "iMessage Channel","features.inAppBrowser.desc": "Show the Browser tab in the conversation side panel: an embedded browser that opens search results in place and lets agents browse visibly.","features.inAppBrowser.title": "In-App Browser",- "features.messageTextSelectionActions.desc": "Show a quick action when selecting text in chat messages so the selected text can be added to the next conversation context.",+ "features.messageTextSelectionActions.desc": "Show Quote and Copy actions when selecting text in chat messages. Quote adds the selected text to your message as a quote.","features.messageTextSelectionActions.title": "Message Text Selection Actions","features.oauthApps.desc": "Show OAuth app management in personal and workspace settings. This feature is hidden by default.","features.oauthApps.title": "OAuth Apps",diff --git a/locales/es-ES/chat.json b/locales/es-ES/chat.jsonindex 2acd618b255..b7b071476ae 100644--- a/locales/es-ES/chat.json+++ b/locales/es-ES/chat.json@@ -2925,9 +2925,6 @@"terminalPanel.split": "Dividir terminal","terminalPanel.targetLocal": "Este ordenador","terminalPanel.title": "Terminal",- "textSelection.addToConversation": "Agregar a la conversación",- "textSelection.added": "Agregado al contexto de la conversación",- "textSelection.title": "Selección de mensaje","thread.closeSubagentThread": "Contraer conversación del subagente","thread.dividerContinuation": "Dividido aquí, heredando el contexto principal del chat hasta ahora","thread.dividerStandalone": "Dividido aquí, heredando solo el mensaje anterior",diff --git a/locales/fa-IR/chat.json b/locales/fa-IR/chat.jsonindex 2d3f5edf5cb..8ba3f757ea9 100644--- a/locales/fa-IR/chat.json+++ b/locales/fa-IR/chat.json@@ -2927,9 +2927,6 @@"terminalPanel.split": "تقسیم ترمینال","terminalPanel.targetLocal": "این کامپیوتر","terminalPanel.title": "ترمینال",- "textSelection.addToConversation": "اضافه کردن به مکالمه",- "textSelection.added": "به زمینه مکالمه اضافه شد",- "textSelection.title": "انتخاب پیام","thread.closeSubagentThread": "بستن گفتگوی عامل فرعی","thread.dividerContinuation": "اینجا منشعب شده است و زمینه اصلی گفتگو تا اینجا به ارث برده شده است","thread.dividerStandalone": "اینجا منشعب شده است و فقط پیام بالا به ارث برده شده است",diff --git a/locales/fr-FR/chat.json b/locales/fr-FR/chat.jsonindex 9f84831c280..43c9b0bb8a3 100644--- a/locales/fr-FR/chat.json+++ b/locales/fr-FR/chat.json@@ -2927,9 +2927,6 @@"terminalPanel.split": "Diviser le terminal","terminalPanel.targetLocal": "Cet ordinateur","terminalPanel.title": "Terminal",- "textSelection.addToConversation": "Ajouter à la conversation",- "textSelection.added": "Ajouté au contexte de la conversation",- "textSelection.title": "Sélection de message","thread.closeSubagentThread": "Réduire la conversation du sous-agent","thread.dividerContinuation": "Divisé ici, en héritant du contexte principal du chat jusqu'à présent","thread.dividerStandalone": "Divisé ici, en héritant uniquement du message ci-dessus",diff --git a/locales/it-IT/chat.json b/locales/it-IT/chat.jsonindex 7bb4479dffe..59be87429d2 100644--- a/locales/it-IT/chat.json+++ b/locales/it-IT/chat.json@@ -2927,9 +2927,6 @@"terminalPanel.split": "Dividi terminale","terminalPanel.targetLocal": "Questo computer","terminalPanel.title": "Terminale",- "textSelection.addToConversation": "Aggiungi alla conversazione",- "textSelection.added": "Aggiunto al contesto della conversazione",- "textSelection.title": "Selezione del messaggio","thread.closeSubagentThread": "Comprimi conversazione subagente","thread.dividerContinuation": "Derivato qui, ereditando il contesto principale della chat fino ad ora","thread.dividerStandalone": "Derivato qui, ereditando solo il messaggio sopra",diff --git a/locales/ja-JP/chat.json b/locales/ja-JP/chat.jsonindex 0d4dcb0b09a..b43108ffb65 100644--- a/locales/ja-JP/chat.json+++ b/locales/ja-JP/chat.json@@ -2927,9 +2927,6 @@"terminalPanel.split": "ターミナルを分割","terminalPanel.targetLocal": "このコンピュータ","terminalPanel.title": "ターミナル",- "textSelection.addToConversation": "会話に追加",- "textSelection.added": "会話コンテキストに追加されました",- "textSelection.title": "メッセージ選択","thread.closeSubagentThread": "サブエージェント会話を折りたたむ","thread.dividerContinuation": "ここで分岐しました。これまでのメインチャットコンテキストを継承しています。","thread.dividerStandalone": "ここで分岐しました。上記のメッセージのみを継承しています。",diff --git a/locales/ko-KR/chat.json b/locales/ko-KR/chat.jsonindex 7e504044e41..876f18ffd65 100644--- a/locales/ko-KR/chat.json+++ b/locales/ko-KR/chat.json@@ -2925,9 +2925,6 @@"terminalPanel.split": "터미널 분할","terminalPanel.targetLocal": "이 컴퓨터","terminalPanel.title": "터미널",- "textSelection.addToConversation": "대화에 추가",- "textSelection.added": "대화 컨텍스트에 추가됨",- "textSelection.title": "메시지 선택","thread.closeSubagentThread": "하위 에이전트 대화 숨기기","thread.dividerContinuation": "여기서 분기되었습니다. 지금까지의 주요 채팅 컨텍스트를 계승합니다.","thread.dividerStandalone": "여기서 분기되었습니다. 위의 메시지만 계승합니다.",diff --git a/locales/nl-NL/chat.json b/locales/nl-NL/chat.jsonindex 33df605bc2c..cd5a9e149fc 100644--- a/locales/nl-NL/chat.json+++ b/locales/nl-NL/chat.json@@ -2927,9 +2927,6 @@"terminalPanel.split": "Terminal splitsen","terminalPanel.targetLocal": "Deze computer","terminalPanel.title": "Terminal",- "textSelection.addToConversation": "Toevoegen aan gesprek",- "textSelection.added": "Toegevoegd aan gesprekscontext",- "textSelection.title": "Berichtselectie","thread.closeSubagentThread": "Subagentgesprek samenvouwen","thread.dividerContinuation": "Hier vertakt, waarbij de hoofdchatcontext tot nu toe wordt overgenomen","thread.dividerStandalone": "Hier vertakt, waarbij alleen het bovenstaande bericht wordt overgenomen",diff --git a/locales/pl-PL/chat.json b/locales/pl-PL/chat.jsonindex 73f95e0124f..c602c18ae07 100644--- a/locales/pl-PL/chat.json+++ b/locales/pl-PL/chat.json@@ -2925,9 +2925,6 @@"terminalPanel.split": "Podziel terminal","terminalPanel.targetLocal": "Ten komputer","terminalPanel.title": "Terminal",- "textSelection.addToConversation": "Dodaj do rozmowy",- "textSelection.added": "Dodano do kontekstu rozmowy",- "textSelection.title": "Wybór wiadomości","thread.closeSubagentThread": "Zwiń rozmowę subagenta","thread.dividerContinuation": "Rozpoczęto tutaj, dziedzicząc dotychczasowy główny kontekst czatu","thread.dividerStandalone": "Rozpoczęto tutaj, dziedzicząc tylko powyższą wiadomość",diff --git a/locales/pt-BR/chat.json b/locales/pt-BR/chat.jsonindex 7ad84293973..f3382e4abb5 100644--- a/locales/pt-BR/chat.json+++ b/locales/pt-BR/chat.json@@ -2925,9 +2925,6 @@"terminalPanel.split": "Dividir terminal","terminalPanel.targetLocal": "Este computador","terminalPanel.title": "Terminal",- "textSelection.addToConversation": "Adicionar à conversa",- "textSelection.added": "Adicionado ao contexto da conversa",- "textSelection.title": "Seleção de mensagem","thread.closeSubagentThread": "Recolher conversa do subagente","thread.dividerContinuation": "Ramal iniciado aqui, herdando o contexto principal do chat até agora","thread.dividerStandalone": "Ramal iniciado aqui, herdando apenas a mensagem acima",diff --git a/locales/ru-RU/chat.json b/locales/ru-RU/chat.jsonindex d670986cef8..890109d14da 100644--- a/locales/ru-RU/chat.json+++ b/locales/ru-RU/chat.json@@ -2925,9 +2925,6 @@"terminalPanel.split": "Разделить терминал","terminalPanel.targetLocal": "Этот компьютер","terminalPanel.title": "Терминал",- "textSelection.addToConversation": "Добавить в беседу",- "textSelection.added": "Добавлено в контекст беседы",- "textSelection.title": "Выбор сообщения","thread.closeSubagentThread": "Свернуть диалог с субагентом","thread.dividerContinuation": "Разделено здесь, наследуя основной контекст чата до этого момента","thread.dividerStandalone": "Разделено здесь, наследуя только сообщение выше",diff --git a/locales/tr-TR/chat.json b/locales/tr-TR/chat.jsonindex 80d0316c096..6e3d5ed1f49 100644--- a/locales/tr-TR/chat.json+++ b/locales/tr-TR/chat.json@@ -2927,9 +2927,6 @@"terminalPanel.split": "Terminali böl","terminalPanel.targetLocal": "Bu bilgisayar","terminalPanel.title": "Terminal",- "textSelection.addToConversation": "Sohbete ekle",- "textSelection.added": "Sohbet bağlamına eklendi",- "textSelection.title": "Mesaj seçimi","thread.closeSubagentThread": "Alt ajan konuşmasını daralt","thread.dividerContinuation": "Buradan çatallandı, şu ana kadar ana sohbet bağlamını devralıyor","thread.dividerStandalone": "Buradan çatallandı, yalnızca yukarıdaki mesajı devralıyor",diff --git a/locales/vi-VN/chat.json b/locales/vi-VN/chat.jsonindex 782d22f0cee..df968db190e 100644--- a/locales/vi-VN/chat.json+++ b/locales/vi-VN/chat.json@@ -2925,9 +2925,6 @@"terminalPanel.split": "Chia màn hình terminal","terminalPanel.targetLocal": "Máy tính này","terminalPanel.title": "Terminal",- "textSelection.addToConversation": "Thêm vào cuộc trò chuyện",- "textSelection.added": "Đã thêm vào ngữ cảnh cuộc trò chuyện",- "textSelection.title": "Chọn tin nhắn","thread.closeSubagentThread": "Thu gọn hội thoại tác tử phụ","thread.dividerContinuation": "Được tách ra tại đây, kế thừa ngữ cảnh chính của cuộc trò chuyện cho đến nay","thread.dividerStandalone": "Được tách ra tại đây, chỉ kế thừa tin nhắn phía trên",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 8f473329183..cefd9486ea3 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -2996,9 +2996,9 @@"terminalPanel.split": "拆分终端","terminalPanel.targetLocal": "本机","terminalPanel.title": "终端",- "textSelection.addToConversation": "添加到对话",- "textSelection.added": "已添加到对话上下文",- "textSelection.title": "消息选区",+ "textSelection.copied": "已复制",+ "textSelection.copy": "复制",+ "textSelection.quote": "引用","thread.closeSubagentThread": "隐藏详情","thread.dividerContinuation": "从此消息分叉,已继承至此的主对话上下文","thread.dividerStandalone": "从此消息分叉,仅继承上方这条消息",@@ -3164,6 +3164,9 @@"upload.clientMode.disabled": "当前模型不支持视觉识别和文件分析。请切换模型后使用","upload.clientMode.fileNotSupported": "浏览器模式暂不支持上传文件。仅支持图片","upload.clientMode.visionNotSupported": "当前模型不支持视觉识别。请切换模型后使用",+ "upload.image.label": "图片 {{number}}",+ "upload.image.preview": "预览 {{name}}",+ "upload.image.remove": "移除 {{name}}","upload.localPathReference": "大文件改为引用本地路径,不再上传,助手会直接读取原文件。","upload.preview.prepareTasks": "正在准备分块…","upload.preview.status.cancelled": "已取消上传",diff --git a/locales/zh-CN/labs.json b/locales/zh-CN/labs.jsonindex fe587c64252..c08e820ff34 100644--- a/locales/zh-CN/labs.json+++ b/locales/zh-CN/labs.json@@ -30,7 +30,7 @@"features.imessage.title": "iMessage 渠道","features.inAppBrowser.desc": "在会话侧边栏显示「浏览器」标签页:内嵌浏览器可就地打开搜索结果,并让 Agent 的浏览操作实时可见。","features.inAppBrowser.title": "内置浏览器",- "features.messageTextSelectionActions.desc": "在聊天消息中选中文本时显示快捷操作,可将选中的文本加入下一次对话上下文。",+ "features.messageTextSelectionActions.desc": "在聊天消息中选中文本时显示「引用」和「复制」。引用会把选中的文本作为引用块加入你正在输入的消息。","features.messageTextSelectionActions.title": "消息文本选择操作","features.oauthApps.desc": "在个人和工作区设置中显示 OAuth 应用管理入口。此功能默认隐藏。","features.oauthApps.title": "OAuth 应用",diff --git a/locales/zh-TW/chat.json b/locales/zh-TW/chat.jsonindex 566ed377f5e..03bd0816ab9 100644--- a/locales/zh-TW/chat.json+++ b/locales/zh-TW/chat.json@@ -2927,9 +2927,6 @@"terminalPanel.split": "分割終端","terminalPanel.targetLocal": "這台電腦","terminalPanel.title": "終端",- "textSelection.addToConversation": "添加到對話",- "textSelection.added": "已添加到對話上下文",- "textSelection.title": "訊息選擇","thread.closeSubagentThread": "收合子代理對話","thread.dividerContinuation": "從這裡分叉,繼承至今的主要聊天上下文","thread.dividerStandalone": "從這裡分叉,只繼承上方的訊息",diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 4f3d9957d23..9f64d2d1a84 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1679,9 +1679,9 @@ export default {'pageCopilot.title': 'Page Agent','pageSelection.lines': 'Lines {{start}}-{{end}}','pageSelection.reference': 'Selected Text',- 'textSelection.added': 'Added to conversation context',- 'textSelection.addToConversation': 'Add to conversation',- 'textSelection.title': 'Message selection',+ 'textSelection.copied': 'Copied',+ 'textSelection.copy': 'Copy',+ 'textSelection.quote': 'Quote','pin': 'Pin','pinOff': 'Unpin','pinForTeam': 'Pin for team',@@ -3607,6 +3607,9 @@ export default {'File uploads are not supported in browser mode; only images are allowed.','upload.clientMode.visionNotSupported':'The current model does not support visual recognition. Please switch to a different model to use this feature.',+ 'upload.image.label': 'Image {{number}}',+ 'upload.image.preview': 'Preview {{name}}',+ 'upload.image.remove': 'Remove {{name}}','upload.localPathReference':'Large files are referenced by their local path instead of uploaded, so the agent reads the original file directly.','upload.preview.prepareTasks': 'Preparing chunks...',diff --git a/packages/locales/src/default/labs.ts b/packages/locales/src/default/labs.tsindex 51f77766299..05c9fb89bfd 100644--- a/packages/locales/src/default/labs.ts+++ b/packages/locales/src/default/labs.ts@@ -46,7 +46,7 @@ export default {'features.groupChat.desc': 'Enable multi-agent group chat coordination.','features.groupChat.title': 'Group Chat (Multi-Agent)','features.messageTextSelectionActions.desc':- 'Show a quick action when selecting text in chat messages so the selected text can be added to the next conversation context.',+ 'Show Quote and Copy actions when selecting text in chat messages. Quote adds the selected text to your message as a quote.','features.messageTextSelectionActions.title': 'Message Text Selection Actions','features.oauthApps.desc':'Show OAuth app management in personal and workspace settings. This feature is hidden by default.',diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/ImageCard.tsx b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/ImageCard.tsxnew file mode 100644index 00000000000..b8cff22b7fd--- /dev/null+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/ImageCard.tsx@@ -0,0 +1,215 @@+import { ActionIcon, Icon, Progress, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { CircleAlertIcon, Loader2Icon, RotateCwIcon, XIcon } from 'lucide-react';+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';++import { openFilePreviewModal } from './FilePreviewModal.loader';+import UploadTooltipContent from './UploadTooltipContent';+import { getUploadChipState } from './utils';++const IMAGE_CARD_SIZE = 112;++const enter = stylex.keyframes({+ from: { opacity: 0, transform: 'scale(0.92)' },+ to: { opacity: 1, transform: 'scale(1)' },+});++const styles = stylex.create({+ card: {+ position: 'relative',+ overflow: 'hidden',+ flexShrink: 0,+ width: `${IMAGE_CARD_SIZE}px`,+ height: `${IMAGE_CARD_SIZE}px`,+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadiusLG,+ backgroundColor: cssVar.colorFillQuaternary,+ animationName: {+ 'default': enter,+ '@media (prefers-reduced-motion: reduce)': 'none',+ },+ animationDuration: '160ms',+ animationTimingFunction: 'ease-out',+ },+ cardError: { borderColor: cssVar.colorErrorBorder },+ image: {+ display: 'block',+ width: '100%',+ height: '100%',+ objectFit: 'cover',+ },+ previewButton: {+ cursor: 'zoom-in',+ position: 'absolute',+ inset: 0,+ padding: 0,+ borderWidth: 0,+ backgroundColor: 'transparent',+ },+ badge: {+ pointerEvents: 'none',+ position: 'absolute',+ insetBlockStart: '4px',+ insetInlineStart: '4px',+ paddingInline: '4px',+ borderRadius: cssVar.borderRadiusSM,+ fontSize: '11px',+ fontVariantNumeric: 'tabular-nums',+ fontWeight: 500,+ lineHeight: '16px',+ color: cssVar.colorText,+ backgroundColor: `color-mix(in srgb, ${cssVar.colorBgContainer} 85%, transparent)`,+ },+ close: {+ cursor: 'pointer',+ position: 'absolute',+ insetBlockStart: '4px',+ insetInlineEnd: '4px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ width: '20px',+ height: '20px',+ padding: 0,+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: '50%',+ color: {+ 'default': cssVar.colorTextSecondary,+ ':hover': cssVar.colorText,+ },+ backgroundColor: cssVar.colorBgElevated,+ boxShadow: cssVar.boxShadowTertiary,+ },+ overlay: {+ pointerEvents: 'none',+ position: 'absolute',+ inset: 0,+ display: 'flex',+ flexDirection: 'column',+ gap: '6px',+ alignItems: 'center',+ justifyContent: 'center',+ backgroundColor: `color-mix(in srgb, ${cssVar.colorBgContainer} 60%, transparent)`,+ },+ overlayActions: { pointerEvents: 'auto' },+});++interface ImageCardProps extends UploadFileItem {+ /** Position among the draft's images; matches the inline `[Image #N]` references. */+ number?: number;+}++const ImageCard = memo<ImageCardProps>(({ number, ...item }) => {+ const { errorCode, file, id, previewUrl, status } = item;+ const { t } = useTranslation(['chat', 'common']);+ const contextKey = useChatInputUploadKey();+ const removeChatUploadFile = useFileStore((s) => s.removeChatUploadFile);+ const retryChatUploadFile = useFileStore((s) => s.retryChatUploadFile);+ const { busy, canRetry, indicator, progress } = getUploadChipState(item);+ const src = previewUrl || item.fileUrl || item.base64Url;++ const handlePreview = useEventCallback(() => {+ void openFilePreviewModal(item);+ });+ const handleRemove = useEventCallback(() => {+ if (contextKey) void removeChatUploadFile(contextKey, id);+ });+ const handleRetry = useEventCallback(() => {+ if (contextKey) void retryChatUploadFile(contextKey, id);+ });++ return (+ <div aria-busy={busy} {...stylex.props(styles.card, canRetry && styles.cardError)}>+ {src && <img alt={file.name} draggable={false} src={src} {...stylex.props(styles.image)} />}+ <Tooltip title={<UploadTooltipContent {...item} />}>+ <button+ aria-label={t('upload.image.preview', { name: file.name })}+ disabled={!src}+ type={'button'}+ onClick={handlePreview}+ {...stylex.props(styles.previewButton)}+ />+ </Tooltip>+ {(busy || canRetry) && (+ <div {...stylex.props(styles.overlay)}>+ {indicator === 'progress' ? (+ <span+ aria-label={t('upload.preview.status.uploading')}+ aria-valuemax={100}+ aria-valuemin={0}+ aria-valuenow={progress}+ role={'progressbar'}+ >+ <Progress+ percent={progress ?? 0}+ showInfo={false}+ size={24}+ status={'normal'}+ type={'circle'}+ />+ </span>+ ) : indicator === 'loading' ? (+ <Icon+ spin+ icon={Loader2Icon}+ size={20}+ aria-label={t(+ status === 'processing'+ ? 'upload.preview.status.processing'+ : status === 'pending'+ ? 'upload.preview.status.pending'+ : 'upload.preview.status.uploading',+ )}+ />+ ) : (+ <>+ <Icon+ aria-label={t('upload.preview.status.error')}+ icon={CircleAlertIcon}+ size={20}+ style={{ color: cssVar.colorError }}+ />+ <div {...stylex.props(styles.overlayActions)}>+ {errorCode ? (+ <FileUploadErrorActions compact code={errorCode} />+ ) : (+ <ActionIcon+ icon={RotateCwIcon}+ size={'small'}+ title={t('retry', { ns: 'common' })}+ onClick={handleRetry}+ />+ )}+ </div>+ </>+ )}+ </div>+ )}+ {number !== undefined && <span {...stylex.props(styles.badge)}>#{number}</span>}+ <button+ aria-label={t('upload.image.remove', { name: file.name })}+ type={'button'}+ onClick={handleRemove}+ {...stylex.props(styles.close)}+ >+ <Icon icon={XIcon} size={12} />+ </button>+ </div>+ );+});++ImageCard.displayName = 'ImageCard';++export default ImageCard;diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/UploadTooltipContent.tsx b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/UploadTooltipContent.tsxnew file mode 100644index 00000000000..debc4f094aa--- /dev/null+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/UploadTooltipContent.tsx@@ -0,0 +1,34 @@+import { Flexbox, Icon } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { CircleAlertIcon } from 'lucide-react';+import { memo } from 'react';++import { type UploadFileItem } from '@/types/files/upload';++import UploadDetail from '../../../components/UploadDetail';++const styles = stylex.create({+ errorText: { userSelect: 'text' },+});++/** File name plus upload progress, or the failure reason, shown on hover of an upload. */+const UploadTooltipContent = memo<UploadFileItem>(({ error, file, status, tasks, uploadState }) => (+ <Flexbox gap={4}>+ <span>{file.name}</span>+ {status === 'error' && error ? (+ <Flexbox horizontal align={'flex-start'} gap={4} style={{ color: cssVar.colorError }}>+ <Flexbox align={'center'} justify={'center'} style={{ height: '1lh' }}>+ <Icon icon={CircleAlertIcon} size={12} />+ </Flexbox>+ <span {...stylex.props(styles.errorText)}>{error}</span>+ </Flexbox>+ ) : (+ <UploadDetail size={file.size} status={status} tasks={tasks} uploadState={uploadState} />+ )}+ </Flexbox>+));++UploadTooltipContent.displayName = 'UploadTooltipContent';++export default UploadTooltipContent;diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsxindex a35ac5c64e0..40926c428cf 100644--- a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/index.tsx@@ -11,9 +11,9 @@ import { useEventCallback } from '@/hooks/useEventCallback';import { useFileStore } from '@/store/file';import { type UploadFileItem } from '@/types/files/upload';-import UploadDetail from '../../../components/UploadDetail';import Content from './Content';import { openFilePreviewModal } from './FilePreviewModal.loader';+import UploadTooltipContent from './UploadTooltipContent';import { useUploadCompletion } from './useUploadCompletion';import { getFileBasename, getUploadChipSize, getUploadChipState } from './utils';@@ -37,7 +37,6 @@ const styles = stylex.create({height: '12px',lineHeight: 0,},- errorText: { userSelect: 'text' },name: {overflow: 'hidden',flex: '1',@@ -51,7 +50,7 @@ const styles = stylex.create({type FileItemProps = UploadFileItem;const ContextItem = memo<FileItemProps>((props) => {- const { error, errorCode, file, id, status, tasks, uploadState } = props;+ const { errorCode, file, id, status } = props;const { t } = useTranslation(['chat', 'common']);const contextKey = useChatInputUploadKey();const removeChatUploadFile = useFileStore((s) => s.removeChatUploadFile);@@ -68,21 +67,7 @@ const ContextItem = memo<FileItemProps>((props) => {if (contextKey) void removeChatUploadFile(contextKey, id);});- const detail = (- <Flexbox gap={4}>- <span>{file.name}</span>- {status === 'error' && error ? (- <Flexbox horizontal align={'flex-start'} gap={4} style={{ color: cssVar.colorError }}>- <Flexbox align={'center'} justify={'center'} style={{ height: '1lh' }}>- <Icon icon={CircleAlertIcon} size={12} />- </Flexbox>- <span {...stylex.props(styles.errorText)}>{error}</span>- </Flexbox>- ) : (- <UploadDetail size={file.size} status={status} tasks={tasks} uploadState={uploadState} />- )}- </Flexbox>- );+ const detail = <UploadTooltipContent {...props} />;return (<Tagdiff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextList.tsx b/src/features/ChatInput/Desktop/ContextContainer/ContextList.tsxindex 081ad06324b..aaaa67ebe23 100644--- a/src/features/ChatInput/Desktop/ContextContainer/ContextList.tsx+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextList.tsx@@ -1,12 +1,14 @@import { Flexbox, ScrollShadow } from '@lobehub/ui';import * as stylex from '@stylexjs/stylex';-import { memo } from 'react';+import { memo, useMemo } from 'react';import { useChatInputUploadKey } from '@/features/ChatInput/hooks/useChatInputUpload';import { useChatInputStore } from '@/features/ChatInput/store';+import { getImageUploadNumbers, isImageUpload } from '@/features/ChatInput/utils/imageUploads';import { fileChatSelectors, useFileStore } from '@/store/file';import ContextItem from './ContextItem';+import ImageCard from './ContextItem/ImageCard';import ElementItem from './ElementItem';import SelectionItem from './SelectionItem';@@ -30,6 +32,7 @@ const ContextList = memo(() => {);const hasSelections = showSelectionList && selectionList.length > 0;+ const imageNumbers = useMemo(() => getImageUploadNumbers(inputFilesList), [inputFilesList]);if (!showFileList && !showSelectionList) return null;if (inputFilesList.length === 0 && !hasSelections) return null;@@ -42,7 +45,14 @@ const ContextList = memo(() => {orientation={'horizontal'}size={8}>- <Flexbox horizontal gap={4} paddingInline={0} style={{ paddingBlockStart: 8 }} wrap={'wrap'}>+ <Flexbox+ horizontal+ align={'flex-end'}+ gap={8}+ paddingInline={0}+ style={{ paddingBlockStart: 8 }}+ wrap={'wrap'}+ >{selectionList.map((item) =>item.source === 'element' ? (<ElementItem key={item.id} {...item} />@@ -50,9 +60,17 @@ const ContextList = memo(() => {<SelectionItem key={item.id} {...item} />),)}- {inputFilesList.map((item) => (- <ContextItem key={item.id} {...item} />- ))}+ {inputFilesList.map((item, index) => {+ // Keyed by the preview URL when there is one: the id changes from the file name to+ // the server id once the upload finishes, which would remount the card.+ const key = item.previewUrl ?? item.id;++ return isImageUpload(item) ? (+ <ImageCard key={key} number={imageNumbers[index]} {...item} />+ ) : (+ <ContextItem key={key} {...item} />+ );+ })}</Flexbox></ScrollShadow>);diff --git a/src/features/ChatInput/InputEditor/ImageRefTag/ImageRefLabel.tsx b/src/features/ChatInput/InputEditor/ImageRefTag/ImageRefLabel.tsxnew file mode 100644index 00000000000..cb2516b56f8--- /dev/null+++ b/src/features/ChatInput/InputEditor/ImageRefTag/ImageRefLabel.tsx@@ -0,0 +1,38 @@+import { Icon } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { ImageIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++const styles = stylex.create({+ label: {+ display: 'inline-flex',+ gap: '4px',+ alignItems: 'center',+ height: '20px',+ marginInline: '1px',+ paddingInline: '6px',+ borderRadius: cssVar.borderRadiusSM,+ fontSize: '12px',+ lineHeight: '20px',+ color: cssVar.colorTextSecondary,+ whiteSpace: 'nowrap',+ verticalAlign: 'text-bottom',+ backgroundColor: cssVar.colorFillTertiary,+ },+});++/** A sent message's `[Image #N]` reference; the image itself is shown below the text. */+export const ImageRefLabel = memo<{ number: number }>(({ number }) => {+ const { t } = useTranslation('chat');++ return (+ <span {...stylex.props(styles.label)}>+ <Icon icon={ImageIcon} size={12} />+ {t('upload.image.label', { number })}+ </span>+ );+});++ImageRefLabel.displayName = 'ImageRefLabel';diff --git a/src/features/ChatInput/InputEditor/ImageRefTag/ImageRefTag.tsx b/src/features/ChatInput/InputEditor/ImageRefTag/ImageRefTag.tsxnew file mode 100644index 00000000000..e9bea5870dc--- /dev/null+++ b/src/features/ChatInput/InputEditor/ImageRefTag/ImageRefTag.tsx@@ -0,0 +1,86 @@+import { Icon } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { ImageIcon } from 'lucide-react';+import type { MouseEvent } from 'react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { openFilePreviewModal } from '@/features/ChatInput/Desktop/ContextContainer/ContextItem/FilePreviewModal.loader';++import { useImageRefUpload } from './useImageRefUpload';++const styles = stylex.create({+ tag: {+ cursor: 'zoom-in',+ userSelect: 'none',+ display: 'inline-flex',+ gap: '4px',+ alignItems: 'center',+ height: '20px',+ marginInline: '1px',+ paddingInlineStart: '2px',+ paddingInlineEnd: '6px',+ borderRadius: cssVar.borderRadiusSM,+ fontSize: '12px',+ lineHeight: '20px',+ color: cssVar.colorTextSecondary,+ whiteSpace: 'nowrap',+ verticalAlign: 'text-bottom',+ backgroundColor: {+ 'default': cssVar.colorFillTertiary,+ ':hover': cssVar.colorFillSecondary,+ },+ },+ orphan: { cursor: 'default', opacity: 0.5, textDecorationLine: 'line-through' },+ thumbnail: {+ flexShrink: 0,+ width: '16px',+ height: '16px',+ borderRadius: cssVar.borderRadiusXS,+ objectFit: 'cover',+ backgroundColor: cssVar.colorFillQuaternary,+ },+});++interface ImageRefTagProps {+ number: number;+ src: string;+}++/** Inline chip for a `[Image #N]` reference; a click opens the referenced image. */+export const ImageRefTag = memo<ImageRefTagProps>(({ number, src }) => {+ const { t } = useTranslation('chat');+ const live = useImageRefUpload(src);+ // The live number follows removals even through undo; a reference whose image is gone+ // keeps its last number, shows no thumbnail, and is left out of the sent text.+ const upload = live.upload;+ const label = t('upload.image.label', { number: live.number ?? number });++ const handleMouseDown = (event: MouseEvent) => {+ // Keep the caret where it is; the click opens the preview instead.+ event.preventDefault();+ };+ const handleClick = () => {+ if (upload) void openFilePreviewModal(upload);+ };++ return (+ <span+ aria-label={t('upload.image.preview', { name: label })}+ role={'button'}+ onClick={handleClick}+ onMouseDown={handleMouseDown}+ {...stylex.props(styles.tag, !upload && styles.orphan)}+ >+ {upload ? (+ <img alt={''} draggable={false} src={src} {...stylex.props(styles.thumbnail)} />+ ) : (+ <Icon icon={ImageIcon} size={14} />+ )}+ {label}+ </span>+ );+});++ImageRefTag.displayName = 'ImageRefTag';diff --git a/src/features/ChatInput/InputEditor/ImageRefTag/ImageRefTagNode.ts b/src/features/ChatInput/InputEditor/ImageRefTag/ImageRefTagNode.tsnew file mode 100644index 00000000000..0da89807b90--- /dev/null+++ b/src/features/ChatInput/InputEditor/ImageRefTag/ImageRefTagNode.ts@@ -0,0 +1,161 @@+import { addClassNamesToElement } from '@lexical/utils';+import { getKernelFromEditor } from '@lobehub/editor';+import type { HeadlessRenderableNode, HeadlessRenderContext } from '@lobehub/editor/renderer';+import {+ $applyNodeReplacement,+ DecoratorNode,+ type DOMExportOutput,+ type EditorConfig,+ type LexicalEditor,+ type LexicalNode,+ type LexicalUpdateJSON,+ type SerializedLexicalNode,+ type Spread,+} from 'lexical';+import { createElement } from 'react';++import { ImageRefLabel } from './ImageRefLabel';++export type SerializedImageRefTagNode = Spread<+ { fileId?: string; number: number; src: string },+ SerializedLexicalNode+>;++/** Text the model receives for an inline image reference, e.g. `[Image #2]`. */+export const formatImageRef = (number: number) => `[Image #${number}]`;++/**+ * An inline reference to one of the draft's image uploads, rendered as a small+ * "thumbnail + Image N" chip.+ *+ * `src` is the upload's local preview URL, which identifies the upload for its whole+ * lifetime. `number` is the image's position among the draft's images; it is kept in sync+ * with the attachment list, so the chip, the thumbnail badge and the `[Image #N]` text the+ * model receives always agree.+ *+ * `fileId` is the uploaded file's id, recorded once the upload finishes. It survives in the+ * sent message's editor data, so a reference restored into the composer, whose image now has+ * a server URL instead of the old preview URL, can be bound to that image again.+ */+export class ImageRefTagNode extends DecoratorNode<any> implements HeadlessRenderableNode {+ __src: string;+ __number: number;+ __fileId?: string;++ static getType(): string {+ return 'image-ref-tag';+ }++ static clone(node: ImageRefTagNode): ImageRefTagNode {+ return new ImageRefTagNode(node.__src, node.__number, node.__key, node.__fileId);+ }++ static importJSON(serializedNode: SerializedImageRefTagNode): ImageRefTagNode {+ return $createImageRefTagNode(+ serializedNode.src,+ serializedNode.number,+ serializedNode.fileId,+ ).updateFromJSON(serializedNode);+ }++ static importDOM(): null {+ return null;+ }++ constructor(src: string, number: number, key?: string, fileId?: string) {+ super(key);+ this.__src = src;+ this.__number = number;+ this.__fileId = fileId;+ }++ get src(): string {+ return this.__src;+ }++ get number(): number {+ return this.__number;+ }++ get fileId(): string | undefined {+ return this.__fileId;+ }++ setNumber(number: number): this {+ const writable = this.getWritable();+ writable.__number = number;+ return writable;+ }++ /** Points the reference at another upload of the same file, e.g. a restored attachment. */+ setUpload(src: string, fileId: string | undefined): this {+ const writable = this.getWritable();+ writable.__src = src;+ writable.__fileId = fileId;+ return writable;+ }++ exportDOM(): DOMExportOutput {+ const element = document.createElement('span');+ element.textContent = this.getTextContent();+ return { element };+ }++ createDOM(config: EditorConfig): HTMLElement {+ const element = document.createElement('span');+ addClassNamesToElement(element, config.theme.imageRefTag);+ return element;+ }++ getTextContent(): string {+ return formatImageRef(this.__number);+ }++ isInline(): true {+ return true;+ }++ updateDOM(): boolean {+ return false;+ }++ decorate(editor: LexicalEditor): any {+ const decorator = getKernelFromEditor(editor)?.getDecorator(ImageRefTagNode.getType());+ if (!decorator) return null;+ if (typeof decorator === 'function') return decorator(this, editor);+ return {+ queryDOM: decorator.queryDOM,+ render: decorator.render(this, editor),+ };+ }++ /** Rendering inside a sent message, where the local preview URL no longer exists. */+ renderHeadless({ key }: HeadlessRenderContext) {+ return createElement(ImageRefLabel, { key, number: this.__number });+ }++ exportJSON(): SerializedImageRefTagNode {+ return {+ ...super.exportJSON(),+ ...(this.__fileId && { fileId: this.__fileId }),+ number: this.__number,+ src: this.__src,+ };+ }++ updateFromJSON(serializedNode: LexicalUpdateJSON<SerializedImageRefTagNode>): this {+ return super.updateFromJSON(serializedNode);+ }+}++export function $createImageRefTagNode(+ src: string,+ number: number,+ fileId?: string,+): ImageRefTagNode {+ return $applyNodeReplacement(new ImageRefTagNode(src, number, undefined, fileId));+}++export function $isImageRefTagNode(node: LexicalNode | null | undefined): node is ImageRefTagNode {+ return node instanceof ImageRefTagNode;+}diff --git a/src/features/ChatInput/InputEditor/ImageRefTag/ImageRefTagPlugin.test.ts b/src/features/ChatInput/InputEditor/ImageRefTag/ImageRefTagPlugin.test.tsnew file mode 100644index 00000000000..2d638e4eb5e--- /dev/null+++ b/src/features/ChatInput/InputEditor/ImageRefTag/ImageRefTagPlugin.test.ts@@ -0,0 +1,209 @@+import { $dfs } from '@lexical/utils';+import type { IEditor } from '@lobehub/editor';+import { CommonPlugin, Kernel, MarkdownPlugin, moment } from '@lobehub/editor';+import { $createParagraphNode, $createTextNode, $getRoot, HISTORIC_TAG } from 'lexical';+import { describe, expect, it, vi } from 'vitest';++import type { ImageUploadRef } from '../../utils/imageUploads';+import { $isImageRefTagNode, type ImageRefTagNode } from './ImageRefTagNode';+import {+ ImageRefTagPlugin,+ PRUNE_UNATTACHED_IMAGE_REFS_COMMAND,+ SYNC_IMAGE_REF_TAGS_COMMAND,+} from './ImageRefTagPlugin';++const createEditor = (decorator: (node: ImageRefTagNode) => unknown = () => null) => {+ const editor = new Kernel() as unknown as IEditor;+ editor.registerPlugins([CommonPlugin, MarkdownPlugin]);+ editor.registerPlugin(ImageRefTagPlugin, { decorator });+ editor.initNodeEditor();+ return editor;+};++const refsOf = (...srcs: string[]) =>+ new Map<string, ImageUploadRef>(srcs.map((src, index) => [src, { number: index + 1, src }]));++const sync = async (+ editor: IEditor,+ refs: Map<string, ImageUploadRef>,+ { insert, removed }: { insert?: string[]; removed?: string[] } = {},+) => {+ editor.dispatchCommand(SYNC_IMAGE_REF_TAGS_COMMAND, { insert, refs, removed });+ await moment();+};++// The exported markdown escapes `[`, which still reads as the literal text `[Image #N]`.+const markdown = (editor: IEditor) =>+ String(editor.getDocument('markdown')).trim().replaceAll('\\[', '[');++/** Replaces the editor state the way undo does. */+const undoTo = async (editor: IEditor, json: unknown) => {+ const lexical = editor.getLexicalEditor()!;+ lexical.setEditorState(lexical.parseEditorState(json as any), { tag: HISTORIC_TAG });+ await moment();+};++/** The references as stored in the editor data a sent message keeps. */+const referencesOf = (editor: IEditor) => {+ const found: { fileId?: string; number: number; src: string }[] = [];+ const walk = (node: any) => {+ if (node?.type === 'image-ref-tag') {+ const { fileId, number, src } = node;+ found.push({ ...(fileId && { fileId }), number, src });+ }+ node?.children?.forEach(walk);+ };+ walk((editor.getDocument('json') as any)?.root);+ return found;+};++const setText = async (editor: IEditor, text: string) => {+ editor.getLexicalEditor()!.update(() => {+ const paragraph = $createParagraphNode().append($createTextNode(text));+ $getRoot().clear().append(paragraph);+ paragraph.selectEnd();+ });+ await moment();+};++describe('ImageRefTagPlugin', () => {+ it('renders each reference through the registered decorator', async () => {+ const decorator = vi.fn((node: ImageRefTagNode) => `chip ${node.number}`);+ const editor = createEditor(decorator);+ await setText(editor, '');+ await sync(editor, refsOf('blob:a'), { insert: ['blob:a'] });++ const lexical = editor.getLexicalEditor()!;+ const rendered = lexical.getEditorState().read(() =>+ $dfs()+ .map(({ node }) => node)+ .filter($isImageRefTagNode)+ .map((node) => node.decorate(lexical)),+ );++ expect(rendered).toEqual(['chip 1']);+ });++ it('references newly attached images at the caret as [Image #N]', async () => {+ const editor = createEditor();+ await setText(editor, 'compare');++ await sync(editor, refsOf('blob:a', 'blob:b'), { insert: ['blob:a', 'blob:b'] });++ expect(markdown(editor)).toBe('compare[Image #1] [Image #2]');+ });++ it('renumbers references when an earlier image is removed', async () => {+ const editor = createEditor();+ await setText(editor, 'see ');+ await sync(editor, refsOf('blob:a', 'blob:b'), { insert: ['blob:a', 'blob:b'] });++ await sync(editor, refsOf('blob:b'), { removed: ['blob:a'] });++ expect(markdown(editor)).toBe('see [Image #1]');+ });++ it('removes references to images that are no longer attached', async () => {+ const editor = createEditor();+ await setText(editor, 'look ');+ await sync(editor, refsOf('blob:a'), { insert: ['blob:a'] });++ await sync(editor, refsOf(), { removed: ['blob:a'] });++ expect(markdown(editor)).toBe('look');+ });++ it('leaves references to unlisted images out of the text, even after undo', async () => {+ const editor = createEditor();+ await setText(editor, 'a ');+ await sync(editor, refsOf('blob:a', 'blob:b'), { insert: ['blob:a', 'blob:b'] });+ const beforeRemoval = editor.getDocument('json');++ // Removing image #1 and then undoing brings its reference and the old numbers back.+ await sync(editor, refsOf('blob:b'), { removed: ['blob:a'] });+ editor.setDocument('json', beforeRemoval);+ await moment();++ // The removed image's reference writes nothing; only its trailing space remains.+ expect(markdown(editor).replaceAll(/\s+/g, ' ')).toBe('a [Image #1]');+ });++ it('stores the current numbers in the editor data after undo brings old ones back', async () => {+ const editor = createEditor();+ await setText(editor, 'a ');+ await sync(editor, refsOf('blob:a', 'blob:b'), { insert: ['blob:a', 'blob:b'] });+ const beforeRemoval = editor.getDocument('json');++ await sync(editor, refsOf('blob:b'), { removed: ['blob:a'] });+ await undoTo(editor, beforeRemoval);++ // The sent message renders its chips from these numbers, so they must match the text.+ expect(referencesOf(editor)).toEqual([{ number: 1, src: 'blob:b' }]);+ });++ it('binds a reference restored from a sent message to its image by file id', async () => {+ const editor = createEditor();+ await setText(editor, 'what is ');+ await sync(editor, refsOf('blob:a', 'blob:b'), { insert: ['blob:a', 'blob:b'] });+ // Both uploads finish, so the references record the uploaded files' ids.+ await sync(+ editor,+ new Map([+ ['blob:a', { fileId: 'file-a', number: 1, src: 'blob:a' }],+ ['blob:b', { fileId: 'file-b', number: 2, src: 'blob:b' }],+ ]),+ );+ const sentEditorData = editor.getDocument('json');++ // Restoring the message brings back its editor data, and its images under server URLs.+ await sync(editor, refsOf(), { removed: ['blob:a', 'blob:b'] });+ editor.setDocument('json', sentEditorData);+ await moment();+ await sync(+ editor,+ new Map([+ ['https://cdn/a.png', { fileId: 'file-a', number: 1, src: 'https://cdn/a.png' }],+ ['https://cdn/b.png', { fileId: 'file-b', number: 2, src: 'https://cdn/b.png' }],+ ]),+ );++ expect(markdown(editor).replaceAll(/\s+/g, ' ')).toBe('what is [Image #1] [Image #2]');+ expect(referencesOf(editor)).toEqual([+ { fileId: 'file-a', number: 1, src: 'https://cdn/a.png' },+ { fileId: 'file-b', number: 2, src: 'https://cdn/b.png' },+ ]);+ });++ it('keeps a restored reference whose image is not listed yet', async () => {+ const editor = createEditor();+ await setText(editor, 'old ');+ await sync(editor, refsOf('blob:a'), { insert: ['blob:a'] });+ const restored = editor.getDocument('json');++ // Another conversation's list, then the draft comes back before its uploads.+ await sync(editor, refsOf('blob:b'));+ editor.setDocument('json', restored);+ await moment();+ expect(markdown(editor)).toBe('old');++ await sync(editor, refsOf('blob:a'));+ expect(markdown(editor)).toBe('old [Image #1]');+ });++ it('drops references to unattached images before sending', async () => {+ const editor = createEditor();+ await setText(editor, 'see ');+ await sync(editor, refsOf('blob:a', 'blob:b'), { insert: ['blob:a', 'blob:b'] });+ const restored = editor.getDocument('json');++ // After a reload only image b came back; the draft still references both.+ await sync(editor, refsOf('blob:b'));+ editor.setDocument('json', restored);+ await moment();++ editor.dispatchCommand(PRUNE_UNATTACHED_IMAGE_REFS_COMMAND, undefined);++ // Read synchronously, the way sending reads the editor data right after.+ expect(referencesOf(editor)).toEqual([{ number: 1, src: 'blob:b' }]);+ });+});diff --git a/src/features/ChatInput/InputEditor/ImageRefTag/ImageRefTagPlugin.ts b/src/features/ChatInput/InputEditor/ImageRefTag/ImageRefTagPlugin.tsnew file mode 100644index 00000000000..01bb16fef8f--- /dev/null+++ b/src/features/ChatInput/InputEditor/ImageRefTag/ImageRefTagPlugin.ts@@ -0,0 +1,260 @@+import { $dfs } from '@lexical/utils';+import { type getKernelFromEditor, IMarkdownShortCutService } from '@lobehub/editor';+import {+ $createParagraphNode,+ $createTextNode,+ $getRoot,+ $getSelection,+ $isElementNode,+ $isRangeSelection,+ $isTextNode,+ COMMAND_PRIORITY_HIGH,+ createCommand,+ HISTORIC_TAG,+ HISTORY_MERGE_TAG,+ type LexicalEditor,+ type LexicalNode,+} from 'lexical';++import type { ImageUploadRef } from '../../utils/imageUploads';+import {+ $createImageRefTagNode,+ $isImageRefTagNode,+ formatImageRef,+ ImageRefTagNode,+} from './ImageRefTagNode';++export interface SyncImageRefTagsPayload {+ /** Preview URLs of newly attached images to reference at the caret, in attachment order. */+ insert?: string[];+ /** The draft's current image uploads, keyed by preview URL. */+ refs: Map<string, ImageUploadRef>;+ /** Preview URLs of images the user just removed from the attachment list. */+ removed?: string[];+}++/**+ * Brings the inline references in line with the attachment list: references to `removed`+ * images are deleted, references to attached images take the image's current number, and+ * `insert` adds references for newly attached images at the caret.+ *+ * A reference to an image that is neither attached nor removed — a draft restored before+ * its uploads, or after a reload — is left in place, since its image may still be listed+ * once the conversation's uploads arrive; until then it is shown as unavailable and left+ * out of the markdown.+ */+export const SYNC_IMAGE_REF_TAGS_COMMAND = createCommand<SyncImageRefTagsPayload>(+ 'SYNC_IMAGE_REF_TAGS_COMMAND',+);++/**+ * Removes every reference whose image is not attached, so a message sent from a draft whose+ * uploads never came back (e.g. after a reload) does not show a chip for an image it lacks.+ * The update is flushed synchronously, so the editor data read right after includes it.+ */+export const PRUNE_UNATTACHED_IMAGE_REFS_COMMAND = createCommand<void>(+ 'PRUNE_UNATTACHED_IMAGE_REFS_COMMAND',+);++type IEditorKernel = ReturnType<typeof getKernelFromEditor>;++export interface ImageRefTagPluginOptions {+ decorator: (node: ImageRefTagNode, editor: LexicalEditor) => any;+ theme?: { imageRefTag?: string };+}++/** Removes a reference together with the space inserted after it. */+const $removeImageRefTag = (node: ImageRefTagNode) => {+ const next = node.getNextSibling();+ if ($isTextNode(next) && next.getTextContent().startsWith(' ')) {+ const rest = next.getTextContent().slice(1);+ if (rest) next.setTextContent(rest);+ else next.remove();+ }+ node.remove();+};++/** Preview URLs whose references are removed when they match no attached image. */+type RemovedSrcs = Pick<ReadonlySet<string>, 'has'>;++type SyncAction = 'remove' | { ref: ImageUploadRef } | undefined;++/**+ * What a reference needs to match the attachment list. A reference whose preview URL is+ * not listed is matched by its file id, which is how a reference restored from a sent+ * message finds its image again under the image's server URL. Only a reference matching+ * no listed image is removed, since sending a message also clears its preview URLs.+ */+const planReference = (+ node: ImageRefTagNode,+ refs: Map<string, ImageUploadRef>,+ removed: RemovedSrcs,+): SyncAction => {+ const ref =+ refs.get(node.src) ??+ (node.fileId ? [...refs.values()].find((item) => item.fileId === node.fileId) : undefined);+ if (!ref) return removed.has(node.src) ? 'remove' : undefined;++ const stale =+ ref.src !== node.src ||+ ref.number !== node.number ||+ (ref.fileId !== undefined && ref.fileId !== node.fileId);+ return stale ? { ref } : undefined;+};++const NOTHING_REMOVED: RemovedSrcs = new Set();+const EVERYTHING_REMOVED: RemovedSrcs = { has: () => true };++const $syncImageRefTags = (refs: Map<string, ImageUploadRef>, removed: RemovedSrcs) => {+ for (const { node } of $dfs()) {+ if (!$isImageRefTagNode(node)) continue;+ const action = planReference(node, refs, removed);+ if (action === 'remove') {+ $removeImageRefTag(node);+ } else if (action) {+ const { ref } = action;+ const writable = node.setNumber(ref.number);+ if (ref.src !== node.src || ref.fileId !== node.fileId) {+ writable.setUpload(ref.src, ref.fileId ?? node.fileId);+ }+ }+ }+};++/** Marks the follow-up update that re-syncs references, so it does not trigger itself. */+const IMAGE_REF_RESYNC_TAG = 'image-ref-resync';++const $insertImageRefTags = (refs: ImageUploadRef[]) => {+ const nodes: LexicalNode[] = refs.flatMap((ref) => [+ $createImageRefTagNode(ref.src, ref.number),+ // Trailing space so the user can keep typing without adding one manually.+ $createTextNode(' '),+ ]);++ const selection = $getSelection();+ if ($isRangeSelection(selection)) {+ selection.insertNodes(nodes);+ return;+ }++ const root = $getRoot();+ const last = root.getLastChild();+ const paragraph = $isElementNode(last) && last.canBeEmpty() ? last : $createParagraphNode();+ if (paragraph !== last) root.append(paragraph);+ paragraph.append(...nodes);+ nodes.at(-1)?.selectEnd();+};++/**+ * Owns the `image-ref-tag` node: its decorator, its `[Image #N]` markdown writer, and+ * keeping references in sync with the draft's image uploads.+ */+export class ImageRefTagPlugin {+ static pluginName = 'ImageRefTagPlugin';++ config?: ImageRefTagPluginOptions;+ private kernel: IEditorKernel;+ /**+ * The composer's latest attachment snapshot; `undefined` in editors without one (e.g.+ * editing a sent message), where references keep their stored number.+ */+ private refs?: Map<string, ImageUploadRef>;+ /** Preview URLs of images removed from the attachment list and not attached again. */+ private removed = new Set<string>();++ constructor(kernel: IEditorKernel, config?: ImageRefTagPluginOptions) {+ this.kernel = kernel;+ this.config = config;++ kernel.registerNodes([ImageRefTagNode]);++ if (config?.theme) {+ kernel.registerThemes(config.theme);+ }++ kernel.registerDecorator(ImageRefTagNode.getType(), (node, editor) => {+ return config?.decorator ? config.decorator(node as ImageRefTagNode, editor) : null;+ });+ }++ onInit(editor: LexicalEditor): void {+ this.registerMarkdown();+ this.registerSync(editor);+ }++ private registerMarkdown(): void {+ const mdService = this.kernel.requireService(IMarkdownShortCutService);++ mdService?.registerMarkdownWriter(ImageRefTagNode.getType(), (ctx: any, node: any) => {+ if (!$isImageRefTagNode(node)) return;+ // Written from the snapshot rather than the node, so a reference brought back by undo+ // or a restored draft never claims an image the message does not carry.+ const number = this.refs ? this.refs.get(node.src)?.number : node.number;+ if (number !== undefined) ctx.appendLine(formatImageRef(number));+ });+ }++ private registerSync(editor: LexicalEditor): void {+ editor.registerCommand(+ SYNC_IMAGE_REF_TAGS_COMMAND,+ ({ insert, refs, removed }) => {+ this.refs = refs;+ for (const src of refs.keys()) this.removed.delete(src);+ for (const src of removed ?? []) this.removed.add(src);+ const inserted = (insert ?? []).flatMap((src) => refs.get(src) ?? []);++ editor.update(+ () => {+ $syncImageRefTags(refs, this.removed);+ if (inserted.length > 0) $insertImageRefTags(inserted);+ },+ // Renumbering after a removal belongs to that removal, not to its own undo step.+ inserted.length > 0 ? undefined : { tag: HISTORY_MERGE_TAG },+ );+ return true;+ },+ COMMAND_PRIORITY_HIGH,+ );++ editor.registerCommand(+ PRUNE_UNATTACHED_IMAGE_REFS_COMMAND,+ () => {+ const refs = this.refs;+ if (!refs) return false;+ editor.update(() => $syncImageRefTags(refs, EVERYTHING_REMOVED), {+ discrete: true,+ tag: HISTORY_MERGE_TAG,+ });+ return true;+ },+ COMMAND_PRIORITY_HIGH,+ );++ // Undo and restored editor data replace the editor state without a sync, bringing back+ // references with old numbers or to removed images. The markdown writer already reads+ // the snapshot, but the editor data sent with the message stores each node's number, so+ // the nodes themselves are brought back in line. Only undo/redo removes references: a+ // draft restored from a sent message lists its images after its text, under new URLs.+ editor.registerUpdateListener(({ editorState, tags }) => {+ const refs = this.refs;+ if (!refs || tags.has(IMAGE_REF_RESYNC_TAG)) return;+ const removed = tags.has(HISTORIC_TAG) ? this.removed : NOTHING_REMOVED;++ const stale = editorState.read(() =>+ $dfs().some(+ ({ node }) =>+ $isImageRefTagNode(node) && planReference(node, refs, removed) !== undefined,+ ),+ );+ if (!stale) return;++ editor.update(() => $syncImageRefTags(refs, removed), {+ tag: [HISTORY_MERGE_TAG, IMAGE_REF_RESYNC_TAG],+ });+ });+ }++ destroy(): void {+ this.kernel.unregisterDecorator?.(ImageRefTagNode.getType());+ }+}diff --git a/src/features/ChatInput/InputEditor/ImageRefTag/ReactImageRefTagPlugin.tsx b/src/features/ChatInput/InputEditor/ImageRefTag/ReactImageRefTagPlugin.tsxnew file mode 100644index 00000000000..babc38d52b5--- /dev/null+++ b/src/features/ChatInput/InputEditor/ImageRefTag/ReactImageRefTagPlugin.tsx@@ -0,0 +1,21 @@+import { useLexicalComposerContext } from '@lobehub/editor';+import { type FC, useLayoutEffect } from 'react';++import { ImageRefTag } from './ImageRefTag';+import { ImageRefTagPlugin } from './ImageRefTagPlugin';++const ReactImageRefTagPlugin: FC = () => {+ const [editor] = useLexicalComposerContext();++ useLayoutEffect(() => {+ editor.registerPlugin(ImageRefTagPlugin, {+ decorator: (node) => <ImageRefTag number={node.number} src={node.src} />,+ });+ }, [editor]);++ return null;+};++ReactImageRefTagPlugin.displayName = 'ReactImageRefTagPlugin';++export default ReactImageRefTagPlugin;diff --git a/src/features/ChatInput/InputEditor/ImageRefTag/index.ts b/src/features/ChatInput/InputEditor/ImageRefTag/index.tsnew file mode 100644index 00000000000..efd788f1b29--- /dev/null+++ b/src/features/ChatInput/InputEditor/ImageRefTag/index.ts@@ -0,0 +1,2 @@+export { default as ReactImageRefTagPlugin } from './ReactImageRefTagPlugin';+export { useImageRefTagSync } from './useImageRefTagSync';diff --git a/src/features/ChatInput/InputEditor/ImageRefTag/useImageRefTagSync.test.ts b/src/features/ChatInput/InputEditor/ImageRefTag/useImageRefTagSync.test.tsnew file mode 100644index 00000000000..c7c8991ec23--- /dev/null+++ b/src/features/ChatInput/InputEditor/ImageRefTag/useImageRefTagSync.test.ts@@ -0,0 +1,89 @@+import { describe, expect, it, vi } from 'vitest';++import type { UploadFileItem } from '@/types/files/upload';++import { planImageRefSync } from './useImageRefTagSync';++vi.mock('@/features/ChatInput/hooks/useChatInputUpload', () => ({+ useChatInputUploadKey: () => 'key',+}));++const upload = (+ previewUrl: string,+ status: UploadFileItem['status'],+ type = 'image/png',+): UploadFileItem =>+ ({+ file: new File(['x'], 'image.png', { type }),+ id: 'image.png',+ previewUrl,+ status,+ }) as UploadFileItem;++describe('planImageRefSync', () => {+ it('adopts the images already attached when the composer mounts', () => {+ const { payload } = planImageRefSync([upload('blob:a', 'pending')], 'topic-a', null);++ expect(payload.insert).toBeUndefined();+ expect(payload.removed).toBeUndefined();+ });++ it('inserts references for images that just started uploading, in attachment order', () => {+ const { state } = planImageRefSync([], 'topic-a', null);+ const files = [upload('blob:a', 'pending'), upload('blob:b', 'uploading')];++ expect(planImageRefSync(files, 'topic-a', state).payload.insert).toEqual(['blob:a', 'blob:b']);+ });++ it('still removes and renumbers references when new ones are not inserted (mobile)', () => {+ const mobile = { insertNew: false };+ const { state } = planImageRefSync(+ [upload('blob:a', 'success'), upload('blob:b', 'success')],+ 'topic-a',+ null,+ mobile,+ );+ const files = [upload('blob:b', 'success'), upload('blob:new', 'pending')];++ const { payload } = planImageRefSync(files, 'topic-a', state, mobile);++ expect(payload.insert).toEqual([]);+ expect(payload.removed).toEqual(['blob:a']);+ expect(payload.refs.get('blob:b')?.number).toBe(1);+ });++ it('does not reference attachments restored from a message or seen before', () => {+ const { state } = planImageRefSync([upload('blob:seen', 'pending')], 'topic-a', null);+ const files = [+ upload('blob:seen', 'success'),+ upload('blob:restored', 'success'),+ upload('blob:new', 'pending'),+ ];++ expect(planImageRefSync(files, 'topic-a', state).payload.insert).toEqual(['blob:new']);+ });++ it('removes references only for images removed from the same list', () => {+ const { state } = planImageRefSync(+ [upload('blob:a', 'success'), upload('blob:b', 'success')],+ 'topic-a',+ null,+ );++ const sameList = planImageRefSync([upload('blob:b', 'success')], 'topic-a', state);+ expect(sameList.payload.removed).toEqual(['blob:a']);+ expect(sameList.payload.refs.get('blob:b')?.number).toBe(1);++ // Switching conversations leaves the restored draft's references alone.+ const otherList = planImageRefSync([], 'topic-b', state);+ expect(otherList.payload.removed).toBeUndefined();+ });++ it('drops the references of an image whose upload failed', () => {+ const { state } = planImageRefSync([upload('blob:a', 'uploading')], 'topic-a', null);++ expect(planImageRefSync([upload('blob:a', 'error')], 'topic-a', state).payload.removed).toEqual(+ ['blob:a'],+ );+ });+});diff --git a/src/features/ChatInput/InputEditor/ImageRefTag/useImageRefTagSync.ts b/src/features/ChatInput/InputEditor/ImageRefTag/useImageRefTagSync.tsnew file mode 100644index 00000000000..d036524e5c8--- /dev/null+++ b/src/features/ChatInput/InputEditor/ImageRefTag/useImageRefTagSync.ts@@ -0,0 +1,90 @@+import type { IEditor } from '@lobehub/editor';+import { useEffect, useRef } from 'react';++import { useChatInputUploadKey } from '@/features/ChatInput/hooks/useChatInputUpload';+import { fileChatSelectors, useFileStore } from '@/store/file';+import type { UploadFileItem } from '@/types/files/upload';++import { getImageUploadRefs } from '../../utils/imageUploads';+import type { SyncImageRefTagsPayload } from './ImageRefTagPlugin';+import { SYNC_IMAGE_REF_TAGS_COMMAND } from './ImageRefTagPlugin';++/** Uploads that started in this composer, as opposed to attachments restored from a message. */+const isNewUpload = (item: UploadFileItem | undefined) =>+ item?.status === 'pending' || item?.status === 'uploading' || item?.status === 'processing';++export interface ImageRefSyncOptions {+ /**+ * Whether newly attached images are referenced at the caret. Off on mobile, which has no+ * numbered image cards; existing references (e.g. from a restored message) still follow+ * removals and renumbering there.+ */+ insertNew?: boolean;+}++export interface ImageRefSyncState {+ /** Preview URLs of the images attached at the last sync. */+ attached: Set<string>;+ /** Upload list the state belongs to. */+ key?: string;+ /** Preview URLs ever attached to this list, so a reference is inserted at most once. */+ seen: Set<string>;+}++/**+ * What to change after the attachment list changed from `previous` to `files`.+ *+ * Only a change within the same upload list inserts or removes references. Moving to+ * another list (switching conversations) only adopts its images: the draft restored there+ * keeps its references, and they are renumbered once those images are listed.+ */+export const planImageRefSync = (+ files: UploadFileItem[],+ key: string | undefined,+ previous: ImageRefSyncState | null,+ { insertNew = true }: ImageRefSyncOptions = {},+): { payload: SyncImageRefTagsPayload; state: ImageRefSyncState } => {+ const refs = getImageUploadRefs(files);+ const attached = new Set(refs.keys());++ if (!previous || previous.key !== key) {+ return { payload: { refs }, state: { attached, key, seen: new Set(attached) } };+ }++ const removed = [...previous.attached].filter((src) => !attached.has(src));+ const insert = [...attached].filter(+ (src) =>+ insertNew &&+ !previous.seen.has(src) &&+ isNewUpload(files.find((file) => file.previewUrl === src)),+ );++ return {+ payload: { insert, refs, removed },+ state: { attached, key, seen: new Set([...previous.seen, ...attached]) },+ };+};++/**+ * Keeps the editor's inline image references in step with the draft's image uploads: a+ * newly attached image is referenced at the caret, a removed image takes its references+ * with it, and the remaining references follow the images' new numbers.+ */+export const useImageRefTagSync = (+ editor: IEditor | undefined,+ { insertNew = true }: ImageRefSyncOptions = {},+) => {+ const key = useChatInputUploadKey();+ const files = useFileStore(fileChatSelectors.chatUploadFileList(key));+ const stateRef = useRef<ImageRefSyncState | null>(null);++ useEffect(() => {+ if (!editor) return;++ const { payload, state } = planImageRefSync(files, key, stateRef.current, {+ insertNew,+ });+ stateRef.current = state;+ editor.dispatchCommand(SYNC_IMAGE_REF_TAGS_COMMAND, payload);+ }, [editor, files, insertNew, key]);+};diff --git a/src/features/ChatInput/InputEditor/ImageRefTag/useImageRefUpload.test.ts b/src/features/ChatInput/InputEditor/ImageRefTag/useImageRefUpload.test.tsnew file mode 100644index 00000000000..bc9e01d1c15--- /dev/null+++ b/src/features/ChatInput/InputEditor/ImageRefTag/useImageRefUpload.test.ts@@ -0,0 +1,17 @@+/**+ * @vitest-environment happy-dom+ */+import { renderHook } from '@testing-library/react';+import { describe, expect, it } from 'vitest';++import { useImageRefUpload } from './useImageRefUpload';++describe('useImageRefUpload', () => {+ // Regression: the reference loads in every editor built from the chat input plugins,+ // such as the modal for editing a sent message, which has no chat input store above it.+ it('finds no upload outside a chat input instead of throwing', () => {+ const { result } = renderHook(() => useImageRefUpload('blob:gone'));++ expect(result.current).toEqual({ number: undefined, upload: undefined });+ });+});diff --git a/src/features/ChatInput/InputEditor/ImageRefTag/useImageRefUpload.ts b/src/features/ChatInput/InputEditor/ImageRefTag/useImageRefUpload.tsnew file mode 100644index 00000000000..7edeef7bf3d--- /dev/null+++ b/src/features/ChatInput/InputEditor/ImageRefTag/useImageRefUpload.ts@@ -0,0 +1,42 @@+import { useMemo, useSyncExternalStore } from 'react';+import type { StoreApi } from 'zustand';++import { useChatInputStoreApiOptional } from '@/features/ChatInput/store/apiContext';+import type { State } from '@/features/ChatInput/store/initialState';+import { fileChatSelectors, useFileStore } from '@/store/file';+import type { UploadFileItem } from '@/types/files/upload';++import { getImageUploadRefs } from '../../utils/imageUploads';++const EMPTY_SUBSCRIBE = () => () => {};++/**+ * The upload an inline image reference points at and its current number, both `undefined`+ * when the image is not in this composer's attachment list (removed, failed, or a draft+ * restored without its uploads).+ *+ * The reference also loads in editors outside a composer (e.g. editing a sent message),+ * where there is no chat input store and no upload list, so the store is read optionally —+ * reactively when it exists, like `useChatInputAgentId`.+ */+export const useImageRefUpload = (src: string): { number?: number; upload?: UploadFileItem } => {+ const storeApi = useChatInputStoreApiOptional() as StoreApi<State> | undefined;+ const contextKey = useSyncExternalStore(+ storeApi ? storeApi.subscribe : EMPTY_SUBSCRIBE,+ () => {+ const state = storeApi?.getState();+ return state?.uploadContextKey ?? state?.contextSelectionKey;+ },+ () => undefined,+ );++ const files = useFileStore(fileChatSelectors.chatUploadFileList(contextKey));++ return useMemo(+ () => ({+ number: getImageUploadRefs(files).get(src)?.number,+ upload: files.find((item) => item.previewUrl === src),+ }),+ [files, src],+ );+};diff --git a/src/features/ChatInput/InputEditor/index.test.tsx b/src/features/ChatInput/InputEditor/index.test.tsxindex 56f8daec55f..e065871959c 100644--- a/src/features/ChatInput/InputEditor/index.test.tsx+++ b/src/features/ChatInput/InputEditor/index.test.tsx@@ -1,5 +1,5 @@import { RequestTrigger } from '@lobechat/types';-import { render, screen } from '@testing-library/react';+import { render, screen, waitFor } from '@testing-library/react';import { beforeEach, describe, expect, it, vi } from 'vitest';import InputEditor from './index';@@ -252,6 +252,7 @@ vi.mock('./ActionTag', () => ({INSERT_ACTION_TAG_COMMAND: 'insert-action-tag',useSlashActionItems: () => [],}));+vi.mock('./ImageRefTag', () => ({ useImageRefTagSync: vi.fn() }));vi.mock('./MentionMenu', () => ({ createMentionMenu: vi.fn(() => vi.fn(() => null)) }));vi.mock('./Placeholder', () => ({default: () => <span>placeholder</span>,@@ -363,6 +364,17 @@ describe('ChatInput InputEditor', () => {expect((await getEditorStyle())?.fontSize).toBe(16);});+ it('keeps restored image references in sync on mobile without inserting new ones', async () => {+ const { useImageRefTagSync } = await import('./ImageRefTag');+ platform.isMobile = true;++ render(<InputEditor />);++ await waitFor(() =>+ expect(useImageRefTagSync).toHaveBeenLastCalledWith(expect.anything(), { insertNew: false }),+ );+ });+it('keeps the editor font size unchanged on desktop', async () => {permission.allowed = true;diff --git a/src/features/ChatInput/InputEditor/index.tsx b/src/features/ChatInput/InputEditor/index.tsxindex c1abd5ee332..0ed97806f3d 100644--- a/src/features/ChatInput/InputEditor/index.tsx+++ b/src/features/ChatInput/InputEditor/index.tsx@@ -55,6 +55,7 @@ import {type InsertActionTagPayload,useSlashActionItems,} from './ActionTag';+import { useImageRefTagSync } from './ImageRefTag';import { createInputCompletionError, isInputCompletionAbortError } from './inputCompletionError';import InputHistoryPopup, { getHistoryPreviewText } from './InputHistoryPopup';import { INSERT_LOCAL_FILE_TAG_COMMAND } from './LocalFileTag';@@ -292,6 +293,10 @@ const InputEditor = memo<{// Listen to editor's paste event for file uploadsusePasteFile(editor, handlePasteFiles);+ // Reference each attached image inline and keep the references numbered like the images.+ // New references are desktop only, since the numbered image cards are a desktop composer UI;+ // references restored from a message still follow removals and renumbering on mobile.+ useImageRefTagSync(editor, { insertNew: !mobile });useEffect(() => {const fn = (e: BeforeUnloadEvent) => {diff --git a/src/features/ChatInput/InputEditor/plugins.ts b/src/features/ChatInput/InputEditor/plugins.tsindex 116b655625b..224608a3ff3 100644--- a/src/features/ChatInput/InputEditor/plugins.ts+++ b/src/features/ChatInput/InputEditor/plugins.ts@@ -11,6 +11,7 @@ import {import { type Editor } from '@lobehub/editor/react';import { ReactActionTagPlugin } from './ActionTag';+import { ReactImageRefTagPlugin } from './ImageRefTag';import { ReactLocalFileTagPlugin } from './LocalFileTag';import { ReactReferDocumentPlugin } from './ReferDocument';import { ReactReferTopicPlugin } from './ReferTopic';@@ -27,6 +28,7 @@ export const CHAT_INPUT_EMBED_PLUGINS: EditorPlugins = [ReactReferTopicPlugin,ReactReferDocumentPlugin,ReactLocalFileTagPlugin,+ ReactImageRefTagPlugin,ReactMentionPlugin,];diff --git a/src/features/ChatInput/store/action.test.ts b/src/features/ChatInput/store/action.test.tsindex cbb7f6bf0d3..791be9c5b02 100644--- a/src/features/ChatInput/store/action.test.ts+++ b/src/features/ChatInput/store/action.test.ts@@ -19,6 +19,7 @@ vi.mock('@/services/mentionMarketInstall', async (importOriginal) => ({const createHelloEditor = () => ({cleanDocument: vi.fn(),+ dispatchCommand: vi.fn(),focus: vi.fn(),getLexicalEditor: () => ({}),getDocument: vi.fn((type: string) => (type === 'markdown' ? 'Hello' : { root: {} })),@@ -56,6 +57,7 @@ describe('ChatInput store actions', () => {const editorData = { root: { children: [{ text: 'Hello' }] } };const editor = {cleanDocument: vi.fn(),+ dispatchCommand: vi.fn(),focus: vi.fn(),getLexicalEditor: () => ({}),getDocument: vi.fn((type: string) => (type === 'markdown' ? 'Hello' : editorData)),@@ -79,6 +81,7 @@ describe('ChatInput store actions', () => {it('drops the stored draft once the send handler clears the composer', () => {const editor = {cleanDocument: vi.fn(),+ dispatchCommand: vi.fn(),focus: vi.fn(),getLexicalEditor: () => ({}),getDocument: vi.fn((type: string) => (type === 'markdown' ? 'Hello' : { text: 'Hello' })),@@ -100,6 +103,7 @@ describe('ChatInput store actions', () => {it('keeps the stored draft when the send handler declines to clear the composer', () => {const editor = {cleanDocument: vi.fn(),+ dispatchCommand: vi.fn(),focus: vi.fn(),getLexicalEditor: () => ({}),getDocument: vi.fn((type: string) => (type === 'markdown' ? 'Hello' : { text: 'Hello' })),@@ -124,6 +128,7 @@ describe('ChatInput store actions', () => {const editorData = { root: { children: [{ text: 'Hello' }] } };const editor = {cleanDocument: vi.fn(),+ dispatchCommand: vi.fn(),focus: vi.fn(),getLexicalEditor: () => ({}),getDocument: vi.fn((type: string) => (type === 'markdown' ? 'Hello' : editorData)),@@ -151,6 +156,7 @@ describe('ChatInput store actions', () => {});const editor = {cleanDocument: vi.fn(),+ dispatchCommand: vi.fn(),focus: vi.fn(),getLexicalEditor: () => ({}),getDocument: vi.fn((type: string) =>@@ -218,7 +224,7 @@ describe('ChatInput store actions', () => {store.getState().handleSendButton();- expect(dispatchCommand).not.toHaveBeenCalled();+ expect(dispatchCommand).not.toHaveBeenCalledWith(KEY_ESCAPE_COMMAND, expect.anything());});// Regression: sendButtonProps.disabled mirrors editor content through thediff --git a/src/features/ChatInput/store/action.ts b/src/features/ChatInput/store/action.tsindex fa35cc5b786..9ac590d8fca 100644--- a/src/features/ChatInput/store/action.ts+++ b/src/features/ChatInput/store/action.ts@@ -11,6 +11,7 @@ import { systemAgentSelectors, userProfileSelectors } from '@/store/user/selectoimport { removeDraft } from '../draftStorage';import { readDocument, writeDocument } from '../editorDocument';import { getInstalledSkillIdentifiers } from '../InputEditor/ActionTag/useInstalledSkillsAndTools';+import { PRUNE_UNATTACHED_IMAGE_REFS_COMMAND } from '../InputEditor/ImageRefTag/ImageRefTagPlugin';import {applyInstalledMarketAgents,collectPendingMarketAgents,@@ -88,6 +89,10 @@ export const store: CreateStore = (publicState) => (set, get) => ({editor.dispatchCommand(KEY_ESCAPE_COMMAND, new KeyboardEvent('keydown', { key: 'Escape' }));}+ // A chip whose image is not attached (a draft restored after a reload) is not sent as+ // [Image #N]; drop it so the sent bubble does not show it either.+ editor.dispatchCommand(PRUNE_UNATTACHED_IMAGE_REFS_COMMAND, undefined);+const commit = (installedAgentIds: ReadonlyMap<string, string> = new Map()) => {// Market chips picked from the @ menu were installed just before this// commit: every read of the content sees the installed agent ids.diff --git a/src/features/ChatInput/utils/imageUploads.test.ts b/src/features/ChatInput/utils/imageUploads.test.tsnew file mode 100644index 00000000000..4a891a8bfa8--- /dev/null+++ b/src/features/ChatInput/utils/imageUploads.test.ts@@ -0,0 +1,78 @@+import { describe, expect, it } from 'vitest';++import type { UploadFileItem } from '@/types/files/upload';++import { getImageUploadNumbers, getImageUploadRefs } from './imageUploads';++const upload = (+ name: string,+ type: string,+ previewUrl?: string,+ status: UploadFileItem['status'] = 'success',+): UploadFileItem =>+ ({+ file: new File(['x'], name, { type }),+ id: name,+ previewUrl,+ status,+ }) as UploadFileItem;++describe('getImageUploadNumbers', () => {+ it('numbers images by their position among images only', () => {+ const files = [+ upload('a.png', 'image/png', 'blob:a'),+ upload('notes.pdf', 'application/pdf'),+ upload('b.jpg', 'image/jpeg', 'blob:b'),+ ];++ expect(getImageUploadNumbers(files)).toEqual([1, undefined, 2]);+ });++ it('skips images that failed to upload, since they are not sent', () => {+ const files = [+ upload('a.png', 'image/png', 'blob:a', 'error'),+ upload('b.png', 'image/png', 'blob:b'),+ upload('c.png', 'image/png', 'blob:c', 'cancelled'),+ ];++ expect(getImageUploadNumbers(files)).toEqual([undefined, 1, undefined]);+ expect([...getImageUploadRefs(files).keys()]).toEqual(['blob:b']);+ });++ it('numbers pasted images that share a file name separately', () => {+ const files = [+ upload('image.png', 'image/png', 'blob:1'),+ upload('image.png', 'image/png', 'blob:2'),+ ];++ expect(getImageUploadNumbers(files)).toEqual([1, 2]);+ });+});++describe('getImageUploadRefs', () => {+ it('keys image uploads by preview URL with their current number', () => {+ const files = [+ upload('a.png', 'image/png', 'blob:a', 'uploading'),+ upload('clip.mp4', 'video/mp4', 'blob:v'),+ upload('b.png', 'image/png', 'blob:b', 'uploading'),+ ];++ expect([...getImageUploadRefs(files)]).toEqual([+ ['blob:a', { number: 1, src: 'blob:a' }],+ ['blob:b', { number: 2, src: 'blob:b' }],+ ]);+ });++ it('records the file id only once an upload finished', () => {+ // Until then the id is the file name, which two pasted images can share.+ const files = [+ upload('image.png', 'image/png', 'blob:a', 'uploading'),+ { ...upload('image.png', 'image/png', 'blob:b'), id: 'file-b' },+ ];++ expect([...getImageUploadRefs(files)]).toEqual([+ ['blob:a', { number: 1, src: 'blob:a' }],+ ['blob:b', { fileId: 'file-b', number: 2, src: 'blob:b' }],+ ]);+ });+});diff --git a/src/features/ChatInput/utils/imageUploads.ts b/src/features/ChatInput/utils/imageUploads.tsnew file mode 100644index 00000000000..1e5f0a74dbd--- /dev/null+++ b/src/features/ChatInput/utils/imageUploads.ts@@ -0,0 +1,54 @@+import type { UploadFileItem } from '@/types/files/upload';++export const isImageUpload = (item: Pick<UploadFileItem, 'file'>): boolean =>+ item.file.type.startsWith('image');++/** A failed or cancelled upload is not sent with the message, so it takes no number. */+const isSendableImageUpload = (item: Pick<UploadFileItem, 'file' | 'status'>): boolean =>+ isImageUpload(item) && item.status !== 'error' && item.status !== 'cancelled';++/**+ * 1-based position of each upload among the draft's image uploads, aligned with `files`+ * (`undefined` for non-image uploads and for images that failed to upload).+ *+ * The number shown on the thumbnail badge and on inline `[Image #N]` references is the+ * image's position in the message's image list, so the model can match a reference with+ * the N-th image it receives. Removing an image renumbers the rest, and the badges and+ * references follow together. Positions are used instead of ids because an upload's id is+ * its file name until the upload finishes, and pasted images often share one.+ */+export const getImageUploadNumbers = (files: UploadFileItem[]): (number | undefined)[] => {+ let count = 0;+ return files.map((item) => (isSendableImageUpload(item) ? ++count : undefined));+};++export interface ImageUploadRef {+ /**+ * The uploaded file's id, only once the upload finished: until then an upload's id is its+ * file name, which pasted images often share.+ */+ fileId?: string;+ number: number;+ src: string;+}++/**+ * Image uploads addressable by an inline reference, keyed by their local preview URL.+ *+ * The object URL created for the preview is unique per upload and stays the same while+ * the upload's id changes from the file name to the server id.+ */+export const getImageUploadRefs = (files: UploadFileItem[]): Map<string, ImageUploadRef> => {+ const numbers = getImageUploadNumbers(files);+ const refs = new Map<string, ImageUploadRef>();+ files.forEach((item, index) => {+ const number = numbers[index];+ if (!number || !item.previewUrl) return;+ refs.set(item.previewUrl, {+ ...(item.status === 'success' && { fileId: item.id }),+ number,+ src: item.previewUrl,+ });+ });+ return refs;+};diff --git a/src/features/Conversation/Messages/User/components/RichTextMessage.test.tsx b/src/features/Conversation/Messages/User/components/RichTextMessage.test.tsxindex 92bff6cc5fb..474364fcfd5 100644--- a/src/features/Conversation/Messages/User/components/RichTextMessage.test.tsx+++ b/src/features/Conversation/Messages/User/components/RichTextMessage.test.tsx@@ -95,6 +95,37 @@ afterEach(() => {cleanup();});+const imageRefEditorState = {+ root: {+ children: [+ {+ children: [+ {+ detail: 0,+ format: 0,+ mode: 'normal',+ style: '',+ text: 'compare ',+ type: 'text',+ version: 1,+ },+ { number: 2, src: 'blob:gone', type: 'image-ref-tag', version: 1 },+ ],+ direction: null,+ format: '',+ indent: 0,+ type: 'paragraph',+ version: 1,+ },+ ],+ direction: null,+ format: '',+ indent: 0,+ type: 'root',+ version: 1,+ },+};+describe('RichTextMessage', () => {it('should allow document comments to use the default 16px renderer scale', async () => {const { container } = render(@@ -146,6 +177,19 @@ describe('RichTextMessage', () => {expect(container.textContent).toContain('report.md');});+ // Regression: an image pasted into the composer serializes to an `image-ref-tag`+ // node. Unregistered on the renderer, it made the sent message drop all its text.+ it('should render image-ref-tag nodes with the surrounding text', async () => {+ const { container } = render(<RichTextMessage editorState={imageRefEditorState} />);++ await act(async () => {+ await moment();+ });++ expect(container.textContent).toContain('compare');+ expect(container.textContent).toContain('upload.image.label');+ });+// Regression: the renderer's stock image node is a bare <img>,// so an image inside a published comment could not be enlarged.it('should open the image viewer when a rendered image is clicked', async () => {diff --git a/src/features/Conversation/Messages/User/components/RichTextMessage.tsx b/src/features/Conversation/Messages/User/components/RichTextMessage.tsxindex e291f33e2e2..792d46ccb92 100644--- a/src/features/Conversation/Messages/User/components/RichTextMessage.tsx+++ b/src/features/Conversation/Messages/User/components/RichTextMessage.tsx@@ -5,6 +5,7 @@ import type { CSSProperties } from 'react';import { memo, useMemo } from 'react';import { ActionTagNode } from '@/features/ChatInput/InputEditor/ActionTag/ActionTagNode';+import { ImageRefTagNode } from '@/features/ChatInput/InputEditor/ImageRefTag/ImageRefTagNode';import { LocalFileTagNode } from '@/features/ChatInput/InputEditor/LocalFileTag';import { mentionPlainClassName } from '@/features/ChatInput/InputEditor/mentionStyle';import { ReferDocumentNode } from '@/features/ChatInput/InputEditor/ReferDocument/ReferDocumentNode';@@ -21,7 +22,13 @@ interface RichTextMessageProps {const LINE_HEIGHT = 1.6;const style: CSSProperties = { '--common-line-height': LINE_HEIGHT } as CSSProperties;-const EXTRA_NODES = [ActionTagNode, ReferTopicNode, ReferDocumentNode, LocalFileTagNode];+const EXTRA_NODES = [+ ActionTagNode,+ ReferTopicNode,+ ReferDocumentNode,+ LocalFileTagNode,+ ImageRefTagNode,+];const PREVIEW_OPTIONS = { onDownload: downloadPreviewImage };const RENDERERS = { ...richTextImageRenderers, ...richTextMentionRenderers };diff --git a/src/features/Conversation/Messages/components/TextSelectionActionLayer/helpers.test.ts b/src/features/Conversation/Messages/components/TextSelectionActionLayer/helpers.test.tsindex c21aca6c657..aaa3d13ee66 100644--- a/src/features/Conversation/Messages/components/TextSelectionActionLayer/helpers.test.ts+++ b/src/features/Conversation/Messages/components/TextSelectionActionLayer/helpers.test.ts@@ -1,54 +1,8 @@import { describe, expect, it } from 'vitest';-import {- createTextSelectionContext,- getRangeFirstLineRect,- getSelectionPreview,- getSelectionToolbarPosition,- isSameTextSelectionContext,-} from './helpers';+import { getRangeFirstLineRect, getSelectionToolbarPosition } from './helpers';describe('TextSelectionActionLayer helpers', () => {- it('builds a text context selection from selected rendered text', () => {- const context = createTextSelectionContext({- id: 'selection-1',- selectedText: ' selected\ntext ',- title: 'Message selection',- });-- expect(context).toEqual({- content: 'selected\ntext',- format: 'text',- id: 'selection-1',- preview: 'selected text',- source: 'text',- title: 'Message selection',- type: 'text',- });- });-- it('dedupes only plain text selections with the same content', () => {- const textContext = createTextSelectionContext({- id: 'selection-1',- selectedText: 'selected text',- title: 'Message selection',- });-- expect(isSameTextSelectionContext(textContext, ' selected text ')).toBe(true);- expect(- isSameTextSelectionContext({ ...textContext, filePath: 'src/a.ts' }, 'selected text'),- ).toBe(false);- expect(isSameTextSelectionContext({ ...textContext, pageId: 'page-1' }, 'selected text')).toBe(- false,- );- });-- it('clips long previews without changing the selected content', () => {- const selectedText = 'a'.repeat(90);-- expect(getSelectionPreview(selectedText)).toBe(`${'a'.repeat(80)}...`);- });-it('keeps toolbar position inside viewport margins', () => {const rect = DOMRect.fromRect({ height: 18, width: 30, x: -20, y: 4 });diff --git a/src/features/Conversation/Messages/components/TextSelectionActionLayer/helpers.ts b/src/features/Conversation/Messages/components/TextSelectionActionLayer/helpers.tsindex 0d8bfbd6e9f..01c6ac2d976 100644--- a/src/features/Conversation/Messages/components/TextSelectionActionLayer/helpers.ts+++ b/src/features/Conversation/Messages/components/TextSelectionActionLayer/helpers.ts@@ -1,50 +1,12 @@-import type { ChatContextContent } from '@lobechat/types';-export interface SelectionToolbarPosition {left: number;top: number;}-export interface TextSelectionContextParams {- id: string;- selectedText: string;- title: string;-}-const TOOLBAR_OFFSET = 12;const VIEWPORT_MARGIN = 12;const LINE_TOP_TOLERANCE = 3;-export const getSelectionPreview = (selectedText: string): string | undefined => {- const preview = selectedText.replaceAll(/\s+/g, ' ').trim();- if (!preview) return;-- return preview.length > 80 ? `${preview.slice(0, 80)}...` : preview;-};--export const createTextSelectionContext = ({- id,- selectedText,- title,-}: TextSelectionContextParams): ChatContextContent => ({- content: selectedText.trim(),- format: 'text',- id,- preview: getSelectionPreview(selectedText),- source: 'text',- title,- type: 'text',-});--export const isSameTextSelectionContext = (- item: ChatContextContent,- selectedText: string,-): boolean =>- item.source === 'text' &&- !item.filePath &&- !item.pageId &&- item.content.trim() === selectedText.trim();-export const getSelectionToolbarPosition = (rect: DOMRect,viewportWidth: number,diff --git a/src/features/Conversation/Messages/components/TextSelectionActionLayer/index.tsx b/src/features/Conversation/Messages/components/TextSelectionActionLayer/index.tsxindex 740e91f6c6f..c25eb7aa1bd 100644--- a/src/features/Conversation/Messages/components/TextSelectionActionLayer/index.tsx+++ b/src/features/Conversation/Messages/components/TextSelectionActionLayer/index.tsx@@ -1,25 +1,20 @@'use client';-import { nanoid } from '@lobechat/utils';-import { Button, Flexbox, toast } from '@lobehub/ui';+import { Button, copyToClipboard, Flexbox } from '@lobehub/ui';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';-import { MessageCirclePlusIcon } from 'lucide-react';+import { CheckIcon, CopyIcon, TextQuoteIcon } from 'lucide-react';import type { CSSProperties, PointerEvent, ReactNode } from 'react';import { memo, useCallback, useEffect, useRef, useState } from 'react';import { createPortal } from 'react-dom';import { useTranslation } from 'react-i18next';+import type { ChatInputEditor } from '@/features/ChatInput/hooks/useChatInputEditor';import { useChatStore } from '@/store/chat';-import { fileChatSelectors, useFileStore } from '@/store/file';import { useConversationStore } from '../../../store';-import {- createTextSelectionContext,- getRangeFirstLineRect,- getSelectionToolbarPosition,- isSameTextSelectionContext,-} from './helpers';+import { getRangeFirstLineRect, getSelectionToolbarPosition } from './helpers';+import { quoteIntoEditor } from './quote';interface ActiveSelection {position: {@@ -54,25 +49,30 @@ const styles = stylex.create({},});-const focusChatInputSoon = () => {- window.setTimeout(() => {- // The Conversation ChatInput syncs the active editor here. In a portal- // thread, the newly mounted input becomes the latest registered editor.- useChatStore.getState().mainInputEditor?.focus();- }, 160);-};+/** How long the Copy button reads "Copied" before it can be used again. */+const COPIED_FEEDBACK_MS = 1500;++/**+ * The composer that receives a quote: this conversation's own ChatInput when it has one,+ * otherwise the most recently registered chat input.+ */+const getComposerEditor = (conversationEditor: ChatInputEditor | null) =>+ (conversationEditor ?? useChatStore.getState().mainInputEditor)?.instance?.getLexicalEditor?.() ??+ undefined;const TextSelectionActionLayer = memo<TextSelectionActionLayerProps>(({ children, disabled }) => {const { t } = useTranslation('chat');const rootRef = useRef<HTMLDivElement | null>(null);const toolbarRef = useRef<HTMLDivElement | null>(null);const [activeSelection, setActiveSelection] = useState<ActiveSelection | null>(null);+ const [copied, setCopied] = useState(false);const composerTarget = useConversationStore((s) => s.composerTarget);- const addChatContextSelection = useFileStore((s) => s.addChatContextSelection);+ const conversationEditor = useConversationStore((s) => s.editor as ChatInputEditor | null);const hideToolbar = useCallback(() => {setActiveSelection(null);+ setCopied(false);}, []);const clearNativeSelection = useCallback(() => {@@ -100,8 +100,8 @@ const TextSelectionActionLayer = memo<TextSelectionActionLayerProps>(({ childrenreturn;}- const text = selection.toString().trim();- if (!text) {+ const text = selection.toString();+ if (!text.trim()) {hideToolbar();return;}@@ -112,9 +112,9 @@ const TextSelectionActionLayer = memo<TextSelectionActionLayerProps>(({ childrenreturn;}- setActiveSelection({- position: getSelectionToolbarPosition(rect, window.innerWidth),- text,+ setActiveSelection((previous) => {+ if (previous?.text !== text) setCopied(false);+ return { position: getSelectionToolbarPosition(rect, window.innerWidth), text };});}, [composerTarget.writable, disabled, hideToolbar]);@@ -133,42 +133,49 @@ const TextSelectionActionLayer = memo<TextSelectionActionLayerProps>(({ childrenhideToolbar();};+ // Escape closes only the toolbar, and only while it is showing.+ const handleKeyDown = (event: KeyboardEvent) => {+ if (event.key !== 'Escape') return;+ event.stopPropagation();+ hideToolbar();+ };+window.addEventListener('pointerdown', handlePointerDown, true);+ window.addEventListener('keydown', handleKeyDown, true);window.addEventListener('resize', hideToolbar);window.addEventListener('scroll', hideToolbar, true);return () => {window.removeEventListener('pointerdown', handlePointerDown, true);+ window.removeEventListener('keydown', handleKeyDown, true);window.removeEventListener('resize', hideToolbar);window.removeEventListener('scroll', hideToolbar, true);};}, [activeSelection, hideToolbar]);- const addSelectionToConversation = useCallback(() => {+ // The quote goes into the draft itself, where the user sees it, can edit it, and keeps+ // typing below it; focusing the composer there is the confirmation.+ const handleQuote = useCallback(() => {const text = activeSelection?.text;- if (!text || !composerTarget.writable) return;-- const currentSelections = fileChatSelectors.chatContextSelections(composerTarget.contextKey)(- useFileStore.getState(),- );- const existing = currentSelections.find((item) => isSameTextSelectionContext(item, text));- const context =- existing ??- createTextSelectionContext({- id: `selection-${nanoid(6)}`,- selectedText: text,- title: t('textSelection.title'),- });-- addChatContextSelection({ contextKey: composerTarget.contextKey, selection: context });- toast.success(t('textSelection.added'));- }, [activeSelection?.text, addChatContextSelection, composerTarget, t]);-- const handleAddToConversation = useCallback(() => {- addSelectionToConversation();- clearNativeSelection();- focusChatInputSoon();- }, [addSelectionToConversation, clearNativeSelection]);+ const editor = getComposerEditor(conversationEditor);+ if (!text || !editor || !composerTarget.writable) return;++ if (quoteIntoEditor(editor, text)) clearNativeSelection();+ }, [activeSelection?.text, clearNativeSelection, composerTarget.writable, conversationEditor]);++ const handleCopy = useCallback(async () => {+ const text = activeSelection?.text;+ if (!text) return;++ await copyToClipboard(text.trim());+ setCopied(true);+ }, [activeSelection?.text]);++ useEffect(() => {+ if (!copied) return;+ const timer = window.setTimeout(() => setCopied(false), COPIED_FEEDBACK_MS);+ return () => window.clearTimeout(timer);+ }, [copied]);const handleToolbarPointerDown = useCallback((event: PointerEvent<HTMLDivElement>) => {event.preventDefault();@@ -202,12 +209,20 @@ const TextSelectionActionLayer = memo<TextSelectionActionLayerProps>(({ childrenonPointerDown={handleToolbarPointerDown}><Button- icon={<MessageCirclePlusIcon size={14} />}+ icon={<TextQuoteIcon size={14} />}+ size={'small'}+ type={'text'}+ onClick={handleQuote}+ >+ {t('textSelection.quote')}+ </Button>+ <Button+ icon={copied ? <CheckIcon size={14} /> : <CopyIcon size={14} />}size={'small'}type={'text'}- onClick={handleAddToConversation}+ onClick={handleCopy}>- {t('textSelection.addToConversation')}+ {t(copied ? 'textSelection.copied' : 'textSelection.copy')}</Button></Flexbox>,document.body,diff --git a/src/features/Conversation/Messages/components/TextSelectionActionLayer/quote.test.ts b/src/features/Conversation/Messages/components/TextSelectionActionLayer/quote.test.tsnew file mode 100644index 00000000000..955c73069f0--- /dev/null+++ b/src/features/Conversation/Messages/components/TextSelectionActionLayer/quote.test.ts@@ -0,0 +1,86 @@+import type { IEditor } from '@lobehub/editor';+import { CommonPlugin, Kernel, MarkdownPlugin, moment } from '@lobehub/editor';+import { $createParagraphNode, $createTextNode, $getRoot, $getSelection } from 'lexical';+import { describe, expect, it } from 'vitest';++import { $appendQuote, getQuoteLines } from './quote';++const createEditor = () => {+ const editor = new Kernel() as unknown as IEditor;+ editor.registerPlugins([CommonPlugin, MarkdownPlugin]);+ editor.initNodeEditor();+ return editor;+};++const run = async (editor: IEditor, fn: () => void) => {+ editor.getLexicalEditor()!.update(fn);+ await moment();+};++const markdown = (editor: IEditor) => String(editor.getDocument('markdown')).trim();++describe('getQuoteLines', () => {+ it('drops surrounding blank lines and trailing spaces but keeps inner blank lines', () => {+ expect(getQuoteLines('\r\n\nfirst \r\n\nsecond\n\n')).toEqual(['first', '', 'second']);+ });++ it('returns nothing for whitespace', () => {+ expect(getQuoteLines(' \n\t\n')).toEqual([]);+ });+});++describe('$appendQuote', () => {+ it('quotes into an empty draft and leaves the caret on the line after it', async () => {+ const editor = createEditor();+ let caretText: string | undefined;++ await run(editor, () => {+ $getRoot().clear().append($createParagraphNode());+ $appendQuote('line one\nline two');+ caretText = $getSelection()?.getNodes()[0]?.getTextContent();+ });++ expect(markdown(editor)).toMatch(/^> line one\n> line two$/m);+ expect($getRootChildTypes(editor)).toEqual(['quote', 'paragraph']);+ expect(caretText).toBe('');+ });++ it('appends after an existing draft instead of replacing it', async () => {+ const editor = createEditor();++ await run(editor, () => {+ $getRoot()+ .clear()+ .append($createParagraphNode().append($createTextNode('my question')));+ $appendQuote('quoted');+ });++ expect(markdown(editor).startsWith('my question')).toBe(true);+ expect(markdown(editor)).toContain('> quoted');+ expect($getRootChildTypes(editor)).toEqual(['paragraph', 'quote', 'paragraph']);+ });++ it('does nothing for a blank selection', async () => {+ const editor = createEditor();+ let key: string | undefined = 'unset';++ await run(editor, () => {+ $getRoot().clear().append($createParagraphNode());+ key = $appendQuote(' \n ');+ });++ expect(key).toBeUndefined();+ expect($getRootChildTypes(editor)).toEqual(['paragraph']);+ });+});++function $getRootChildTypes(editor: IEditor) {+ return editor+ .getLexicalEditor()!+ .getEditorState()+ .read(() =>+ $getRoot()+ .getChildren()+ .map((node) => node.getType()),+ );+}diff --git a/src/features/Conversation/Messages/components/TextSelectionActionLayer/quote.ts b/src/features/Conversation/Messages/components/TextSelectionActionLayer/quote.tsnew file mode 100644index 00000000000..52cad20ad5d--- /dev/null+++ b/src/features/Conversation/Messages/components/TextSelectionActionLayer/quote.ts@@ -0,0 +1,82 @@+import { $createQuoteNode } from '@lexical/rich-text';+import {+ $createLineBreakNode,+ $createParagraphNode,+ $createTextNode,+ $getRoot,+ $isParagraphNode,+ type LexicalEditor,+} from 'lexical';++/**+ * Lines of a selection as they go into a quote: line endings normalized, blank lines+ * around the selection dropped, trailing spaces trimmed. Blank lines inside stay, so the+ * selection remains one quote.+ */+export const getQuoteLines = (text: string): string[] => {+ const lines = text+ .replaceAll('\r\n', '\n')+ .split('\n')+ .map((line) => line.trimEnd());+ const start = lines.findIndex((line) => line.length > 0);+ if (start === -1) return [];+ const end = lines.findLastIndex((line) => line.length > 0);+ return lines.slice(start, end + 1);+};++/**+ * Appends `text` to the end of the draft as a quote, followed by an empty paragraph that+ * receives the caret so the user's next words are their own and not part of the quote.+ * Returns the key of that paragraph, or `undefined` when there is nothing to quote.+ */+export const $appendQuote = (text: string): string | undefined => {+ const lines = getQuoteLines(text);+ if (lines.length === 0) return;++ const quote = $createQuoteNode();+ lines.forEach((line, index) => {+ if (index > 0) quote.append($createLineBreakNode());+ if (line) quote.append($createTextNode(line));+ });++ const root = $getRoot();+ const last = root.getLastChild();+ // An empty last paragraph (an empty draft, or the line left after an earlier quote)+ // becomes the line after this quote instead of a blank line above it.+ let after;+ if ($isParagraphNode(last) && last.isEmpty()) {+ last.insertBefore(quote);+ after = last;+ } else {+ root.append(quote);+ after = $createParagraphNode();+ root.append(after);+ }+ after.selectEnd();+ return after.getKey();+};++/**+ * Quotes `text` at the end of the composer's draft, then focuses the composer with the+ * caret on the line after the quote, scrolled into view below a long draft.+ */+export const quoteIntoEditor = (editor: LexicalEditor, text: string): boolean => {+ if (getQuoteLines(text).length === 0) return false;++ let caretKey: string | undefined;++ editor.update(+ () => {+ caretKey = $appendQuote(text);+ },+ {+ onUpdate: () => {+ if (!caretKey) return;+ editor.focus();+ editor.getElementByKey(caretKey)?.scrollIntoView({ block: 'nearest' });+ },+ },+ );++ return true;+};diff --git a/src/store/file/slices/chat/action.test.ts b/src/store/file/slices/chat/action.test.tsindex 1891ed334aa..acbcdfb9b73 100644--- a/src/store/file/slices/chat/action.test.ts+++ b/src/store/file/slices/chat/action.test.ts@@ -310,12 +310,12 @@ describe('useFileStore:chat', () => {const { result } = renderHook(() => useStore());const finishes: (() => void)[] = [];vi.spyOn(result.current, 'uploadWithProgress').mockImplementation(- ({ file, onStatusUpdate }) =>+ ({ file, onStatusUpdate, uploadId }) =>new Promise((resolve) => {const n = finishes.length + 1;finishes.push(() => {onStatusUpdate?.({- id: file.name,+ id: uploadId ?? file.name,type: 'updateFile',value: { fileUrl: `url-${n}`, id: `server-${n}`, status: 'success' },});@@ -357,7 +357,7 @@ describe('useFileStore:chat', () => {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' })]);+ expect(lists.blank).toEqual([expect.objectContaining({ status: 'pending' })]);await act(async () => {finishes[1]();@@ -365,6 +365,66 @@ describe('useFileStore:chat', () => {});});+ // Regression: pasted images are all named `image.png`. Both pending chips had that name as+ // their id, so whichever upload finished first claimed the first chip, and a chip could+ // show one image while sending the other.+ it('reports each same-named upload to its own chip when they finish out of order', async () => {+ mockAgentMode({ enableAgentMode: true, heterogeneous: false });+ const { result } = renderHook(() => useStore());+ const finishes: (() => void)[] = [];+ vi.spyOn(result.current, 'uploadWithProgress').mockImplementation(+ ({ file, onStatusUpdate, uploadId }) =>+ new Promise((resolve) => {+ const n = finishes.length + 1;+ finishes.push(() => {+ onStatusUpdate?.({+ id: uploadId ?? 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(+ CONTEXT_KEY,+ [new File(['a'], 'image.png', { type: 'text/plain' })],+ AGENT_ID,+ );+ await vi.waitFor(() => expect(finishes).toHaveLength(1));+ secondUpload = result.current.uploadChatFiles(+ CONTEXT_KEY,+ [new File(['b'], 'image.png', { type: 'text/plain' })],+ AGENT_ID,+ );+ await vi.waitFor(() => expect(finishes).toHaveLength(2));+ });++ // The second paste finishes first.+ await act(async () => {+ finishes[1]();+ await secondUpload;+ });+ expect(uploadList()).toEqual([+ expect.objectContaining({ status: 'pending' }),+ expect.objectContaining({ fileUrl: 'url-2', id: 'server-2', status: 'success' }),+ ]);++ await act(async () => {+ finishes[0]();+ await firstUpload;+ });+ expect(uploadList()).toEqual([+ expect.objectContaining({ fileUrl: 'url-1', id: 'server-1', status: 'success' }),+ expect.objectContaining({ fileUrl: 'url-2', id: 'server-2', status: 'success' }),+ ]);+ });+it('uploadChatFiles should reject unsupported files before upload in chat mode', async () => {// chat mode: agent mode disabled and not a heterogeneous agentmockAgentMode({ enableAgentMode: false, heterogeneous: false });@@ -467,7 +527,7 @@ describe('useFileStore:chat', () => {expect.objectContaining({agentId: AGENT_ID,error: 'You do not have permission to upload files in this workspace.',- id: 'test.txt',+ id: expect.stringMatching(/^test\.txt#/),status: 'error',}),]);@@ -497,7 +557,7 @@ describe('useFileStore:chat', () => {expect(uploadList()).toEqual([expect.objectContaining({error: 'The upload service is unavailable. (HTTP 502 · Request ID: a4f7-SJC)',- id: 'report.docx',+ id: expect.stringMatching(/^report\.docx#/),status: 'error',}),]);@@ -527,7 +587,11 @@ describe('useFileStore:chat', () => {// reach it; the run parses it on the creator's account instead.expect(ragService.parseFileContent).not.toHaveBeenCalled();expect(uploadList()).toEqual([- expect.objectContaining({ agentId: AGENT_ID, id: 'notes.pdf', shareId: SHARE_ID }),+ expect.objectContaining({+ agentId: AGENT_ID,+ id: expect.stringMatching(/^notes\.pdf#/),+ shareId: SHARE_ID,+ }),]);});@@ -573,7 +637,7 @@ describe('useFileStore:chat', () => {expect(uploadList()).toEqual([expect.objectContaining({error: 'share.visitor.upload.creatorStorageBlocked',- id: 'notes.pdf',+ id: expect.stringMatching(/^notes\.pdf#/),status: 'error',}),]);diff --git a/src/store/file/slices/chat/action.ts b/src/store/file/slices/chat/action.tsindex 67e9b30bf4c..02cc896b431 100644--- a/src/store/file/slices/chat/action.ts+++ b/src/store/file/slices/chat/action.ts@@ -1,5 +1,6 @@import { SHARE_VISITOR_MAX_FILE_SIZE } from '@lobechat/const';import { type ChatContextContent } from '@lobechat/types';+import { createNanoId } from '@lobechat/utils';import { COMPRESSIBLE_IMAGE_TYPES, compressImageFile } from '@lobechat/utils/compressImage';import { toast } from '@lobehub/ui';import { Buffer } from 'buffer.js';@@ -65,6 +66,13 @@ export interface ChatUploadOptions {shareId?: string;}+/**+ * Id of a chip while its upload is pending, replaced by the file's id once it finishes.+ * Pasted images are all named `image.png`, so the file name alone would let concurrent+ * uploads report to each other's chips and send an image the chip does not show.+ */+const createPendingUploadId = (file: File) => `${file.name}#${createNanoId(8)()}`;+const formatShareUploadLimit = () => `${Math.round(SHARE_VISITOR_MAX_FILE_SIZE / 1024 / 1024)} MB`;const getUploadErrorDescription = (error: unknown): string => {@@ -433,6 +441,7 @@ export class FileActionImpl {),);+ const uploadIds = new Map(files.map((file) => [file, createPendingUploadId(file)]));const uploadFiles: UploadFileItem[] = await Promise.all(files.map(async (file) => {let previewUrl: string | undefined = undefined;@@ -452,7 +461,7 @@ export class FileActionImpl {agentId,base64Url,file,- id: file.name,+ id: uploadIds.get(file)!,previewUrl,shareId,status: 'pending',@@ -464,6 +473,7 @@ export class FileActionImpl {// upload files and process itconst pools = files.map(async (file) => {+ const uploadId = uploadIds.get(file)!;let fileResult: { id: string; url: string } | undefined;try {@@ -472,18 +482,20 @@ export class FileActionImpl {file,onStatusUpdate: dispatchChatUploadFileList,shareId,+ uploadId,}): await this.#get().uploadWithProgress({conversationAgentId: agentId,file,onStatusUpdate: dispatchChatUploadFileList,+ uploadId,});} catch (error) {if (getErrorMessage(error) === 'UNAUTHORIZED') {- dispatchChatUploadFileList({ id: file.name, type: 'removeFile' });+ dispatchChatUploadFileList({ id: uploadId, type: 'removeFile' });} else {dispatchChatUploadFileList({- id: file.name,+ id: uploadId,type: 'updateFile',value: {error: getUploadErrorDescription(error),diff --git a/src/store/file/slices/chat/shareVisitorUpload.ts b/src/store/file/slices/chat/shareVisitorUpload.tsindex 12023c53312..0ca98395f83 100644--- a/src/store/file/slices/chat/shareVisitorUpload.ts+++ b/src/store/file/slices/chat/shareVisitorUpload.ts@@ -42,13 +42,16 @@ export const uploadShareVisitorFile = async ({file,onStatusUpdate,shareId,+ uploadId,}: {abortController?: AbortController;file: File;onStatusUpdate?: OnStatusUpdate;shareId: string;+ /** Id of the chip this upload reports to; defaults to the file name. */+ uploadId?: string;}): Promise<{ id: string; url: string }> => {- const statusId = file.name;+ const statusId = uploadId ?? file.name;const { detectedMimeType, file: normalizedFile } = await normalizeUploadedFileType(file);const extensionAudioMime = audioMimeFromExtension(normalizedFile.name);