π€― 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): animate image attachments and skip duplicate pastes (#23098)
YuTengjing4f996f1172f9
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.clientIds.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.clientIds.test.tsindex b839e33d880..b2ded6e8b21 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.clientIds.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.clientIds.test.ts@@ -283,6 +283,20 @@ describe('AiAgentService.execAgent - client-minted ids', () => {hintsSpy.mockRestore();});+ it('leaves inline image references out of a new topic fallback title', async () => {+ await service.execAgent({ agentId: 'agent-1', prompt: '[Image #1] [Image #1] dup test' });+ expect(mockTopicCreate.mock.calls[0][0]).toMatchObject({ title: 'dup test' });+ });++ it('leaves inline image references out of a scheduled topic title', async () => {+ await service.scheduleAgentRun({+ agentId: 'agent-1',+ prompt: '[Image #1] dup test',+ runAt: new Date(Date.now() + 60000).toISOString(),+ });+ expect(mockTopicCreate.mock.calls[0][0]).toMatchObject({ title: 'dup test' });+ });+it('does not recreate or snapshot an existing group topic', async () => {const runSpy = vi.spyOn(service, 'execAgent')diff --git a/apps/server/src/services/aiAgent/__tests__/precreatedTopic.test.ts b/apps/server/src/services/aiAgent/__tests__/precreatedTopic.test.tsindex 3dadd9ec26d..7395c9b394c 100644--- a/apps/server/src/services/aiAgent/__tests__/precreatedTopic.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/precreatedTopic.test.ts@@ -95,4 +95,17 @@ describe('createGroupAgentTopic', () => {}),);});++ // Regression: a message sent as "[Image #1] [Image #2] dup test" was titled+ // "Image #1 dup test".+ it('leaves inline image references out of the fallback title', async () => {+ const create = vi.fn().mockResolvedValue({ id: 'topic-new' });++ await createGroupAgentTopic(+ { ...deps(), topicRepo: { create } as never },+ { agentId: 'agent-a', groupId: 'group-1', message: '[Image #1] [Image #2] dup test' },+ );++ expect(create).toHaveBeenCalledWith(expect.objectContaining({ title: 'dup test' }));+ });});diff --git a/apps/server/src/services/aiAgent/pipeline/precreatedTopic.ts b/apps/server/src/services/aiAgent/pipeline/precreatedTopic.tsindex 4a4d08a3f51..d8d87546138 100644--- a/apps/server/src/services/aiAgent/pipeline/precreatedTopic.ts+++ b/apps/server/src/services/aiAgent/pipeline/precreatedTopic.ts@@ -5,7 +5,7 @@ import { TRPCError } from '@trpc/server';import type { TopicRepository } from '@/database/repositories/topic';import type { AgentConfigWithId } from '@/server/services/agent';import { AgentService } from '@/server/services/agent';-import { markdownToTxt } from '@/utils/markdownToTxt';+import { toTitleText } from '@/utils/markdownToTxt';import { resolveRunAgentConfig } from './resolveRunAgentConfig';import { resolveNewTopicSnapshot } from './turnSetup';@@ -77,7 +77,7 @@ export const createGroupAgentTopic = async (newTopic,}: Pick<ExecGroupAgentParams, 'agentId' | 'groupId' | 'message' | 'newTopic'>,): Promise<string> => {- const fallbackTitleSource = markdownToTxt(message);+ const fallbackTitleSource = toTitleText(message);const topicTitle =newTopic?.title ||fallbackTitleSource.slice(0, 50) + (fallbackTitleSource.length > 50 ? '...' : '');diff --git a/apps/server/src/services/aiAgent/pipeline/scheduleAgentRun.ts b/apps/server/src/services/aiAgent/pipeline/scheduleAgentRun.tsindex 572cdaaafc9..fd615413df0 100644--- a/apps/server/src/services/aiAgent/pipeline/scheduleAgentRun.ts+++ b/apps/server/src/services/aiAgent/pipeline/scheduleAgentRun.ts@@ -5,7 +5,7 @@ import debug from 'debug';import type { MessageModel } from '@/database/models/message';import type { TopicModel } from '@/database/models/topic';-import { markdownToTxt } from '@/utils/markdownToTxt';+import { toTitleText } from '@/utils/markdownToTxt';import { type PrecreatedTopicDeps, resolvePrecreatedTopicConfig } from './precreatedTopic';import { resolveNewTopicSnapshot } from './turnSetup';@@ -51,7 +51,7 @@ export const scheduleAgentRun = async (});const resolvedAgentId = agentConfig.id;- const titleSource = markdownToTxt(prompt);+ const titleSource = toTitleText(prompt);const snapshot = await resolveNewTopicSnapshot({ db: deps.db, userId: deps.userId, workspaceId: deps.workspaceId },agentConfig,diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.tsindex c532a9f9f98..591e882809c 100644--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts@@ -36,7 +36,7 @@ import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDeimport { DocumentService } from '@/server/services/document';import { FileService } from '@/server/services/file';import { resolveAttachmentsByFileIds } from '@/server/services/file/resolveAttachments';-import { markdownToTxt } from '@/utils/markdownToTxt';+import { toTitleText } from '@/utils/markdownToTxt';import type { DeviceAccessReason } from '../deviceAccessPolicy';import { resolveDeviceAccessPolicy } from '../deviceAccessPolicy';@@ -642,7 +642,7 @@ export const setupTurn = async (taskId: operationTaskId,});- const fallbackTitleSource = markdownToTxt(prompt);+ const fallbackTitleSource = toTitleText(prompt);const snapshot = await resolveNewTopicSnapshot(deps, agentConfig);const metadataWithSnapshot = await withProjectSandbox(deps, {agentId: resolvedAgentId,diff --git a/packages/const/package.json b/packages/const/package.jsonindex b815c1744af..4243cf3598d 100644--- a/packages/const/package.json+++ b/packages/const/package.json@@ -10,6 +10,7 @@"./desktopGlobalShortcuts": "./src/desktopGlobalShortcuts.ts","./goal": "./src/goal.ts","./hotkeys": "./src/hotkeys.ts",+ "./imageRef": "./src/imageRef.ts","./mcpApp": "./src/mcpApp.ts","./mediaRef": "./src/mediaRef.ts","./plugin": "./src/plugin.ts",diff --git a/packages/const/src/imageRef.test.ts b/packages/const/src/imageRef.test.tsnew file mode 100644index 00000000000..8ff736b380b--- /dev/null+++ b/packages/const/src/imageRef.test.ts@@ -0,0 +1,15 @@+import { describe, expect, it } from 'vitest';++import { formatImageRef, stripImageRefs } from './imageRef';++describe('stripImageRefs', () => {+ it('removes every reference written by formatImageRef with its trailing space', () => {+ const text = `${formatImageRef(1)} ${formatImageRef(2)} compare these logos`;++ expect(stripImageRefs(text)).toBe('compare these logos');+ });++ it('keeps text that only looks similar', () => {+ expect(stripImageRefs('see [Image] and Image #3')).toBe('see [Image] and Image #3');+ });+});diff --git a/packages/const/src/imageRef.ts b/packages/const/src/imageRef.tsnew file mode 100644index 00000000000..35ee66faaaf--- /dev/null+++ b/packages/const/src/imageRef.ts@@ -0,0 +1,11 @@+/** Text the model receives for an inline image reference in a chat message, e.g. `[Image #2]`. */+export const formatImageRef = (number: number) => `[Image #${number}]`;++const IMAGE_REF_PATTERN = /\[Image #\d+\] ?/g;++/**+ * Removes inline image references (and the space written after each) from message text.+ * They point the model at an attached image but carry no topic, so text derived from a+ * message for people, such as a topic title, leaves them out.+ */+export const stripImageRefs = (text: string) => text.replaceAll(IMAGE_REF_PATTERN, '');diff --git a/packages/prompts/src/chains/__tests__/summaryTitle.test.ts b/packages/prompts/src/chains/__tests__/summaryTitle.test.tsindex fe3ea547454..0b94a7e610e 100644--- a/packages/prompts/src/chains/__tests__/summaryTitle.test.ts+++ b/packages/prompts/src/chains/__tests__/summaryTitle.test.ts@@ -24,4 +24,16 @@ describe('chainSummaryTitle', () => {expect(TOPIC_TITLE_PROMPT_VERSION).toBe('v1');expect(TOPIC_TITLE_JSON_SCHEMA.name).toBe('topic_title');});++ // Regression: a message sent as "[Image #1] [Image #2] dup test" was titled+ // "Image #1 dup test".+ it('leaves inline image references out of the conversation text', () => {+ const result = chainSummaryTitle(+ [{ content: '[Image #1] [Image #2] compare these logos', role: 'user' }],+ 'en-US',+ );++ expect(result.messages[1].content).toContain('<user>\ncompare these logos\n</user>');+ expect(result.messages[1].content).not.toContain('Image #');+ });});diff --git a/packages/prompts/src/chains/summaryTitle.ts b/packages/prompts/src/chains/summaryTitle.tsindex cc24fb2baa2..f8194b9dfde 100644--- a/packages/prompts/src/chains/summaryTitle.ts+++ b/packages/prompts/src/chains/summaryTitle.ts@@ -1,3 +1,4 @@+import { stripImageRefs } from '@lobechat/const/imageRef';import type { OpenAIChatMessage, UIChatMessage } from '@lobechat/types';export const TOPIC_TITLE_PROMPT_VERSION = 'v1';@@ -20,7 +21,10 @@ export const chainSummaryTitle = (locale: string,): { messages: Array<{ content: string; role: 'system' | 'user' }> } => {const conversationText = messages- .map((message) => `<${message.role}>\n${String(message.content ?? '')}\n</${message.role}>`)+ .map(+ (message) =>+ `<${message.role}>\n${stripImageRefs(String(message.content ?? ''))}\n</${message.role}>`,+ ).join('\n');return {diff --git a/packages/types/src/files/upload.ts b/packages/types/src/files/upload.tsindex 29be1b0ec81..795450be93e 100644--- a/packages/types/src/files/upload.ts+++ b/packages/types/src/files/upload.ts@@ -53,6 +53,11 @@ export interface UploadFileItem {* base64 data, it will use in other data*/base64Url?: string;+ /**+ * SHA-256 of the image as it was attached, before compression. A chat draft attaches an+ * image with the same content only once: pasting it again adds nothing.+ */+ contentHash?: string;/** Intrinsic dimensions captured for image uploads. */dimensions?: {height: number;@@ -77,6 +82,11 @@ export interface UploadFileItem {* it will use in the file preview before send the message*/previewUrl?: string;+ /**+ * When the same image was last attached again. No second card is added, so the existing+ * card pulses to show the paste was received.+ */+ repastedAt?: number;/*** Set when the draft was uploaded as an agent-share VISITOR: the file lives* under the creator's account, so remove/retry must go through thediff --git a/src/components/GalleyGrid/Grid.tsx b/src/components/GalleyGrid/Grid.tsxindex 607184388de..bf26569fd18 100644--- a/src/components/GalleyGrid/Grid.tsx+++ b/src/components/GalleyGrid/Grid.tsx@@ -13,22 +13,26 @@ const fallback = createStaticStyles(({ css }) => ({container: css`display: grid;grid-gap: var(--galley-grid-gap, 6px);- grid-template-columns: repeat(var(--galley-grid-col, 3), 1fr);+ /* minmax(0, β¦): an image sized to its intrinsic width must not widen its column */+ grid-template-columns: repeat(var(--galley-grid-col, 3), minmax(0, 1fr));width: 100%;max-width: var(--galley-grid-max, 200px);+ /* a cell's height cap; also read by ImageItem to narrow a tall image to fit it */+ --galley-grid-cell-max: calc(+ (+ var(--galley-grid-max, 200px) - var(--galley-grid-gap, 6px) *+ (var(--galley-grid-col, 3) - 1)+ ) /+ var(--galley-grid-col, 3)+ );+> div {width: 100%;min-width: var(--galley-grid-min, 64px);min-height: var(--galley-grid-min, 64px);- max-height: calc(- (- var(--galley-grid-max, 200px) - var(--galley-grid-gap, 6px) *- (var(--galley-grid-col, 3) - 1)- ) /- var(--galley-grid-col, 3)- );+ max-height: var(--galley-grid-cell-max);}`,}));diff --git a/src/components/ImageItem/index.tsx b/src/components/ImageItem/index.tsxindex c9b51358d59..800a88239a9 100644--- a/src/components/ImageItem/index.tsx+++ b/src/components/ImageItem/index.tsx@@ -64,6 +64,18 @@ const ImageItem = memo<ImageItemProps>(: width && width > 0 && height && height > 0? width / height: undefined;+ /**+ * A message bubble is as wide as its content, and an image that has not loaded yet has no+ * width, so the box would show as a small grey strip and then jump to the image's size.+ * The known intrinsic width sizes it up front (the grid still caps it), and the ratio on the+ * `<img>` itself gives it that box while loading. Inside a grid the width is also capped by+ * the cell's height cap times the ratio, so a tall image stays whole instead of being+ * cropped to a square. Editable thumbnails keep their fixed square.+ */+ const placeholderWidth =+ !editable && aspectRatio && width && width > 0+ ? `min(${width}px, calc(var(--galley-grid-cell-max, ${width / aspectRatio}px) * ${aspectRatio}))`+ : undefined;return (<Image@@ -74,6 +86,7 @@ const ImageItem = memo<ImageItemProps>(preview={preview}size={IMAGE_SIZE}src={url}+ styles={placeholderWidth ? { image: { aspectRatio } } : undefined}actions={editable && (<ActionIcon@@ -97,7 +110,7 @@ const ImageItem = memo<ImageItemProps>(// the grid's min-height and row stretch would push wide images past their ratio, leaving a blank stripalignSelf: aspectRatio ? 'start' : undefined,minHeight: aspectRatio ? 'auto' : undefined,- width: '100%',+ ...(placeholderWidth ? { maxWidth: '100%', width: placeholderWidth } : { width: '100%' }),...style,}}/>diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/ImageCard.tsx b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/ImageCard.tsxindex 1507c14d5f9..8c142554ecd 100644--- a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/ImageCard.tsx+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/ImageCard.tsx@@ -2,7 +2,7 @@ import { ActionIcon, Icon, Tooltip } from '@lobehub/ui';import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';import { CircleAlertIcon, RotateCwIcon, XIcon } from 'lucide-react';-import { memo } from 'react';+import { memo, useRef } from 'react';import { useTranslation } from 'react-i18next';import { FileUploadErrorActions } from '@/business/client/features/FileUploadErrorActions';@@ -14,15 +14,11 @@ import { type UploadFileItem } from '@/types/files/upload';import { openFilePreviewModal } from './FilePreviewModal.loader';import UploadIndicator from './UploadIndicator';import UploadTooltipContent from './UploadTooltipContent';+import { useRepastePulse } from './useRepastePulse';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',@@ -35,12 +31,6 @@ const styles = stylex.create({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: {@@ -101,6 +91,8 @@ const ImageCard = memo<UploadFileItem>((item) => {const retryChatUploadFile = useFileStore((s) => s.retryChatUploadFile);const { busy, canRetry, indicator } = getUploadChipState(item);const src = previewUrl || item.fileUrl || item.base64Url;+ const cardRef = useRef<HTMLDivElement>(null);+ useRepastePulse(cardRef, item.repastedAt);const handlePreview = useEventCallback(() => {void openFilePreviewModal(item);@@ -113,7 +105,11 @@ const ImageCard = memo<UploadFileItem>((item) => {});return (- <div aria-busy={busy} {...stylex.props(styles.card, canRetry && styles.cardError)}>+ <div+ aria-busy={busy}+ ref={cardRef}+ {...stylex.props(styles.card, canRetry && styles.cardError)}+ >{src && <img alt={file.name} draggable={false} src={src} {...stylex.props(styles.image)} />}<Tooltip title={<UploadTooltipContent {...item} />}><buttondiff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/useRepastePulse.test.ts b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/useRepastePulse.test.tsnew file mode 100644index 00000000000..924e31244cd--- /dev/null+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/useRepastePulse.test.ts@@ -0,0 +1,51 @@+import { renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { useRepastePulse } from './useRepastePulse';++describe('useRepastePulse', () => {+ let element: HTMLDivElement;+ let animate: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ element = document.createElement('div');+ animate = vi.fn(() => ({ cancel: vi.fn() }));+ element.animate = animate as any;+ window.matchMedia = vi.fn().mockReturnValue({ matches: false }) as any;+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ const render = (repastedAt?: number) =>+ renderHook(({ at }) => useRepastePulse({ current: element }, at), {+ initialProps: { at: repastedAt },+ });++ it('pulses the card each time the same image is pasted again', () => {+ const { rerender } = render();+ expect(animate).not.toHaveBeenCalled();++ rerender({ at: 1 });+ rerender({ at: 2 });++ expect(animate).toHaveBeenCalledTimes(2);+ expect(animate.mock.calls[0][0][1]).toMatchObject({ transform: 'scale(1.04)' });+ });++ it('stays still when a restored draft mounts with an earlier paste', () => {+ render(1);+ expect(animate).not.toHaveBeenCalled();+ });++ it('only lights the border under reduced motion', () => {+ window.matchMedia = vi.fn().mockReturnValue({ matches: true }) as any;+ const { rerender } = render();++ rerender({ at: 1 });++ expect(animate.mock.calls[0][0][1]).not.toHaveProperty('transform');+ expect(animate.mock.calls[0][0][1]).toHaveProperty('borderColor');+ });+});diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextItem/useRepastePulse.ts b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/useRepastePulse.tsnew file mode 100644index 00000000000..3c1d05346e0--- /dev/null+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextItem/useRepastePulse.ts@@ -0,0 +1,34 @@+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import { type RefObject, useEffect, useRef } from 'react';++const PULSE_MS = 480;++const prefersReducedMotion = () =>+ typeof window.matchMedia === 'function' &&+ window.matchMedia('(prefers-reduced-motion: reduce)').matches;++/**+ * Pulses an image card when the same image is pasted again. The duplicate adds no card, so+ * without this the paste looks like it failed. Only a change after mount pulses: a draft+ * restored with an old `repastedAt` stays still. Under reduced motion only the border lights up.+ */+export const useRepastePulse = (+ ref: RefObject<HTMLElement | null>,+ repastedAt: number | undefined,+) => {+ const mountedWith = useRef(repastedAt);++ useEffect(() => {+ const element = ref.current;+ if (!element || repastedAt === undefined || repastedAt === mountedWith.current) return;+ mountedWith.current = undefined;++ const highlight = { borderColor: cssVar.colorPrimary };+ const keyframes: Keyframe[] = prefersReducedMotion()+ ? [{}, { ...highlight, offset: 0.3 }, {}]+ : [{}, { ...highlight, offset: 0.3, transform: 'scale(1.04)' }, {}];+ const animation = element.animate?.(keyframes, { duration: PULSE_MS, easing: 'ease-out' });++ return () => animation?.cancel();+ }, [ref, repastedAt]);+};diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextList.tsx b/src/features/ChatInput/Desktop/ContextContainer/ContextList.tsxindex f3b2c5ac7c7..deee0ed566c 100644--- a/src/features/ChatInput/Desktop/ContextContainer/ContextList.tsx+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextList.tsx@@ -1,14 +1,16 @@import { Flexbox, ScrollShadow } from '@lobehub/ui';import * as stylex from '@stylexjs/stylex';+import { AnimatePresence } from 'motion/react';import { memo } from 'react';import { useChatInputUploadKey } from '@/features/ChatInput/hooks/useChatInputUpload';import { useChatInputStore } from '@/features/ChatInput/store';-import { isImageUpload } from '@/features/ChatInput/utils/imageUploads';+import { getChatInputImageKey, isImageUpload } from '@/features/ChatInput/utils/imageUploads';import { fileChatSelectors, useFileStore } from '@/store/file';import ContextItem from './ContextItem';import ImageCard from './ContextItem/ImageCard';+import ContextMotionItem, { CONTEXT_ITEM_GAP } from './ContextMotionItem';import ElementItem from './ElementItem';import SelectionItem from './SelectionItem';@@ -18,7 +20,6 @@ const ContextList = memo(() => {const contextSelectionKey = useChatInputStore((s) => s.contextSelectionKey);const uploadContextKey = useChatInputUploadKey();const inputFilesList = useFileStore(fileChatSelectors.chatUploadFileList(uploadContextKey));- const showFileList = useFileStore(fileChatSelectors.chatUploadFileListHasItem(uploadContextKey));const rawSelectionList = useFileStore(fileChatSelectors.chatContextSelections(contextSelectionKey),);@@ -33,8 +34,9 @@ const ContextList = memo(() => {const hasSelections = showSelectionList && selectionList.length > 0;- if (!showFileList && !showSelectionList) return null;- if (inputFilesList.length === 0 && !hasSelections) return null;+ // Stays mounted while empty, so the last attachment can animate out and the container's+ // height can collapse after it.+ const hasItems = inputFilesList.length > 0 || hasSelections;return (<ScrollShadow@@ -47,29 +49,29 @@ const ContextList = memo(() => {<Flexboxhorizontalalign={'flex-end'}- gap={8}+ gap={CONTEXT_ITEM_GAP}paddingInline={0}- style={{ paddingBlockStart: 8 }}+ style={{ paddingBlockStart: hasItems ? 8 : 0 }}wrap={'wrap'}>- {selectionList.map((item) =>- item.source === 'element' ? (- <ElementItem key={item.id} {...item} />- ) : (- <SelectionItem key={item.id} {...item} />- ),- )}- {inputFilesList.map((item) => {- // 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;+ <AnimatePresence initial={false}>+ {selectionList.map((item) => (+ <ContextMotionItem key={`selection:${item.id}`}>+ {item.source === 'element' ? <ElementItem {...item} /> : <SelectionItem {...item} />}+ </ContextMotionItem>+ ))}+ {inputFilesList.map((item) => {+ // 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 = getChatInputImageKey(item);- return isImageUpload(item) ? (- <ImageCard key={key} {...item} />- ) : (- <ContextItem key={key} {...item} />- );- })}+ return (+ <ContextMotionItem key={`file:${key}`}>+ {isImageUpload(item) ? <ImageCard {...item} /> : <ContextItem {...item} />}+ </ContextMotionItem>+ );+ })}+ </AnimatePresence></Flexbox></ScrollShadow>);diff --git a/src/features/ChatInput/Desktop/ContextContainer/ContextMotionItem.tsx b/src/features/ChatInput/Desktop/ContextContainer/ContextMotionItem.tsxnew file mode 100644index 00000000000..10cd4c08395--- /dev/null+++ b/src/features/ChatInput/Desktop/ContextContainer/ContextMotionItem.tsx@@ -0,0 +1,49 @@+import { useReducedMotion } from 'motion/react';+import * as m from 'motion/react-m';+import { memo, type ReactNode } from 'react';++/** The gap between attachments, which a leaving attachment gives back as its width collapses. */+export const CONTEXT_ITEM_GAP = 8;++const ENTER = { duration: 0.16, ease: [0.2, 0, 0, 1] as const };+const EXIT = { duration: 0.16, ease: [0.3, 0, 1, 1] as const };++/**+ * One attachment in the composer: it fades in from slightly smaller when attached, and when+ * removed fades out while its width and trailing gap collapse, so the attachments after it+ * slide into its place instead of jumping. Attachments present when the composer mounts (a+ * restored draft) appear without motion, through `AnimatePresence initial={false}`.+ */+const ContextMotionItem = memo<{ children: ReactNode }>(({ children }) => {+ const reduceMotion = useReducedMotion();++ return (+ <m.div+ initial={{ opacity: 0, scale: 0.92 }}+ animate={{+ opacity: 1,+ scale: 1,+ transition: reduceMotion ? { duration: 0 } : ENTER,+ }}+ // A removed attachment gives back its width so the ones after it slide over; a+ // transform alone would leave its space empty and then jump.+ exit={{+ marginInlineEnd: -CONTEXT_ITEM_GAP,+ opacity: 0,+ // Set at once rather than animated: the leaving item takes no clicks and its content+ // does not spill over the attachments sliding into its place.+ overflow: 'hidden',+ pointerEvents: 'none',+ scale: 0.92,+ transition: reduceMotion ? { duration: 0 } : EXIT,+ width: 0,+ }}+ >+ {children}+ </m.div>+ );+});++ContextMotionItem.displayName = 'ContextMotionItem';++export default ContextMotionItem;diff --git a/src/features/ChatInput/Desktop/ContextContainer/index.tsx b/src/features/ChatInput/Desktop/ContextContainer/index.tsxindex 8aafcc9d710..e53923e6ae7 100644--- a/src/features/ChatInput/Desktop/ContextContainer/index.tsx+++ b/src/features/ChatInput/Desktop/ContextContainer/index.tsx@@ -1,16 +1,48 @@import { Flexbox } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';++import { useChatInputUploadKey } from '@/features/ChatInput/hooks/useChatInputUpload';+import { useChatInputStore } from '@/features/ChatInput/store';+import { fileChatSelectors, useFileStore } from '@/store/file';import ContextList from './ContextList';+import { useContentHeightTransition } from './useContentHeightTransition';++const styles = stylex.create({+ outer: {+ overflow: 'hidden',+ transitionProperty: {+ 'default': 'height',+ '@media (prefers-reduced-motion: reduce)': 'none',+ },+ },+});/*** Contains the context item to be attached, such as file, image, text, etc.* Note: Drag upload is now handled by DragUploadZone in the parent Desktop component.+ *+ * Its height follows the attachments with a transition, so adding the first one or removing+ * the last one does not make the input jump.*/const ContextContainer = () => {+ const contextSelectionKey = useChatInputStore((s) => s.contextSelectionKey);+ const uploadContextKey = useChatInputUploadKey();+ const itemCount = useFileStore(+ (s) =>+ fileChatSelectors.chatUploadFileList(uploadContextKey)(s).length ++ fileChatSelectors.chatContextSelections(contextSelectionKey)(s).length,+ );+ const [outerRef, innerRef] = useContentHeightTransition<HTMLDivElement, HTMLDivElement>(+ itemCount,+ );+return (- <Flexbox paddingInline={8}>- <ContextList />- </Flexbox>+ <div ref={outerRef} {...stylex.props(styles.outer)}>+ <Flexbox paddingInline={8} ref={innerRef}>+ <ContextList />+ </Flexbox>+ </div>);};diff --git a/src/features/ChatInput/Desktop/ContextContainer/useContentHeightTransition.test.ts b/src/features/ChatInput/Desktop/ContextContainer/useContentHeightTransition.test.tsnew file mode 100644index 00000000000..a95f65a05b6--- /dev/null+++ b/src/features/ChatInput/Desktop/ContextContainer/useContentHeightTransition.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from 'vitest';++import { createHeightMotionGate } from './useContentHeightTransition';++describe('createHeightMotionGate', () => {+ it('animates every resize shortly after the content changed', () => {+ const gate = createHeightMotionGate(0);+ gate.contentChanged(2000);++ // A removed card shrinks while it exits, then the row collapses once it is gone.+ expect(gate.shouldAnimate(2080)).toBe(true);+ expect(gate.shouldAnimate(2180)).toBe(true);+ });++ it('does not animate a restored draft that fills in right after mount', () => {+ const gate = createHeightMotionGate(1000);+ gate.contentChanged(1050);++ expect(gate.shouldAnimate(1066)).toBe(false);+ });++ it('does not animate resizes that are not near a content change', () => {+ const gate = createHeightMotionGate(0);+ expect(gate.shouldAnimate(2000)).toBe(false);++ gate.contentChanged(2000);+ expect(gate.shouldAnimate(5000)).toBe(false);+ });+});diff --git a/src/features/ChatInput/Desktop/ContextContainer/useContentHeightTransition.ts b/src/features/ChatInput/Desktop/ContextContainer/useContentHeightTransition.tsnew file mode 100644index 00000000000..8475601a701--- /dev/null+++ b/src/features/ChatInput/Desktop/ContextContainer/useContentHeightTransition.ts@@ -0,0 +1,86 @@+import { type RefObject, useLayoutEffect, useRef } from 'react';++/** Growing uses a decelerating curve; shrinking is quicker and accelerates out. */+const EXPAND = { duration: '200ms', easing: 'cubic-bezier(0.2, 0, 0, 1)' };+const COLLAPSE = { duration: '160ms', easing: 'cubic-bezier(0.3, 0, 1, 1)' };++/**+ * How long after mounting content changes apply at once. A composer remounted with a draft+ * restores its attachments a few frames after mount; they were already there for the user.+ */+const MOUNT_SETTLE_MS = 500;+/**+ * How long after a content change height changes animate. One change resizes several times:+ * a removed card first shrinks while it exits, then the row collapses once it is gone.+ */+const CHANGE_WINDOW_MS = 600;++/**+ * Decides which height changes animate: those shortly after the content changed, except+ * right after mount. Times are `performance.now()` milliseconds.+ */+export const createHeightMotionGate = (mountedAt: number) => {+ let animateUntil = 0;+ return {+ contentChanged: (now: number) => {+ animateUntil = now - mountedAt < MOUNT_SETTLE_MS ? 0 : now + CHANGE_WINDOW_MS;+ },+ shouldAnimate: (now: number) => now < animateUntil,+ };+};++/**+ * Makes an outer element's height follow its content with a CSS transition instead of+ * jumping, so the composer grows when the first attachment arrives and shrinks when the last+ * one leaves. The outer element needs `overflow: hidden` and a `height` transition.+ *+ * The content is measured with a `ResizeObserver`, which runs after layout and before+ * paint, so content that just grew is clipped by the old height for that frame instead of+ * showing at full size first.+ *+ * Only height changes shortly after `contentKey` (the attachments themselves) changes+ * animate. Others apply at once: a window resize that wraps the cards onto another row is not+ * something the user just did to them.+ */+export const useContentHeightTransition = <Outer extends HTMLElement, Inner extends HTMLElement>(+ contentKey: unknown,+): readonly [RefObject<Outer | null>, RefObject<Inner | null>] => {+ const outerRef = useRef<Outer>(null);+ const innerRef = useRef<Inner>(null);+ const gate = useRef<ReturnType<typeof createHeightMotionGate>>(null);++ useLayoutEffect(() => {+ gate.current = createHeightMotionGate(performance.now());+ }, []);++ const previousKey = useRef(contentKey);+ useLayoutEffect(() => {+ if (Object.is(previousKey.current, contentKey)) return;+ previousKey.current = contentKey;+ gate.current?.contentChanged(performance.now());+ }, [contentKey]);++ useLayoutEffect(() => {+ const outer = outerRef.current;+ const inner = innerRef.current;+ if (!outer || !inner) return;++ let height = inner.offsetHeight;+ outer.style.height = `${height}px`;++ const observer = new ResizeObserver(() => {+ const next = inner.offsetHeight;+ if (next === height) return;+ const animate = !!gate.current?.shouldAnimate(performance.now());+ const motion = next > height ? EXPAND : COLLAPSE;+ outer.style.transitionDuration = animate ? motion.duration : '0s';+ outer.style.transitionTimingFunction = motion.easing;+ outer.style.height = `${next}px`;+ height = next;+ });+ observer.observe(inner);+ return () => observer.disconnect();+ }, []);++ return [outerRef, innerRef] as const;+};diff --git a/src/features/ChatInput/Desktop/index.tsx b/src/features/ChatInput/Desktop/index.tsxindex 11af7226f25..47c579dd50e 100644--- a/src/features/ChatInput/Desktop/index.tsx+++ b/src/features/ChatInput/Desktop/index.tsx@@ -12,12 +12,10 @@ import { useTranslation } from 'react-i18next';import ChatInputNotice from '@/features/ChatInput/ChatInputNotice';import ComposerExpandButton from '@/features/ChatInput/components/ComposerExpandButton';-import { useChatInputUploadKey } from '@/features/ChatInput/hooks/useChatInputUpload';import { useChatInputStore } from '@/features/ChatInput/store';import { LayoutContainerContext } from '@/features/DesktopLayoutContainer/LayoutContainerContext';import { useChatStore } from '@/store/chat';import { chatSelectors } from '@/store/chat/selectors';-import { fileChatSelectors, useFileStore } from '@/store/file';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';@@ -127,18 +125,11 @@ const DesktopChatInput = memo<DesktopChatInputProps>(systemStatusSelectors.chatInputHeight(s),s.updateSystemStatus,]);- const contextSelectionKey = useChatInputStore((s) => s.contextSelectionKey);- const hasContextSelections = useFileStore(- fileChatSelectors.chatContextSelectionHasItem(contextSelectionKey),- );- const uploadContextKey = useChatInputUploadKey();- const hasFiles = useFileStore(fileChatSelectors.chatUploadFileListHasItem(uploadContextKey));- const [slashMenuRef, expand, showTypoBar, editor, leftActions] = useChatInputStore((s) => [+ const [slashMenuRef, expand, showTypoBar, editor] = useChatInputStore((s) => [s.slashMenuRef,s.expand,s.showTypoBar,s.editor,- s.leftActions,]);const chatKey = useChatStore(chatSelectors.currentChatKey);@@ -173,12 +164,13 @@ const DesktopChatInput = memo<DesktopChatInputProps>(setExpand(false);}, [chatKey, editor, setExpand]);- const shouldShowContextContainer =- leftActions.flat().includes('fileUpload') || hasContextSelections || hasFiles;+ // Always mounted, at zero height while empty: mounting it with the first attachment+ // would skip its height transition (its first measurement never animates), and+ // unmounting it with the last would cut the card's exit and the collapse.const contextContainerNode = (<><McpAppContextChips />- {shouldShowContextContainer && <ContextContainer />}+ <ContextContainer /></>);diff --git a/src/features/ChatInput/InputEditor/ImageRefTag/ImageRefTagNode.ts b/src/features/ChatInput/InputEditor/ImageRefTag/ImageRefTagNode.tsindex 9497f60da89..6ed88386ddc 100644--- a/src/features/ChatInput/InputEditor/ImageRefTag/ImageRefTagNode.ts+++ b/src/features/ChatInput/InputEditor/ImageRefTag/ImageRefTagNode.ts@@ -1,4 +1,5 @@import { addClassNamesToElement } from '@lexical/utils';+import { formatImageRef } from '@lobechat/const/imageRef';import { getKernelFromEditor } from '@lobehub/editor';import type { HeadlessRenderableNode, HeadlessRenderContext } from '@lobehub/editor/renderer';import {@@ -21,8 +22,7 @@ export type SerializedImageRefTagNode = Spread<SerializedLexicalNode>;-/** Text the model receives for an inline image reference, e.g. `[Image #2]`. */-export const formatImageRef = (number: number) => `[Image #${number}]`;+export { formatImageRef };/*** An inline reference to one of the draft's image uploads, rendered as a smalldiff --git a/src/features/ChatInput/utils/imageUploads.ts b/src/features/ChatInput/utils/imageUploads.tsindex 3d6c6c667cb..38b36ad4b5b 100644--- a/src/features/ChatInput/utils/imageUploads.ts+++ b/src/features/ChatInput/utils/imageUploads.ts@@ -3,6 +3,10 @@ import type { UploadFileItem } from '@/types/files/upload';export const isImageUpload = (item: Pick<UploadFileItem, 'file'>): boolean =>item.file.type.startsWith('image');+/** Key a composer card renders under: the preview URL outlives the id change on upload. */+export const getChatInputImageKey = (item: Pick<UploadFileItem, 'id' | 'previewUrl'>) =>+ item.previewUrl ?? item.id;+/** 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';diff --git a/src/features/Conversation/Messages/User/components/ImageFileListViewer.test.tsx b/src/features/Conversation/Messages/User/components/ImageFileListViewer.test.tsxnew file mode 100644index 00000000000..49c11379912--- /dev/null+++ b/src/features/Conversation/Messages/User/components/ImageFileListViewer.test.tsx@@ -0,0 +1,26 @@+import { render } from '@testing-library/react';+import { describe, expect, it } from 'vitest';++import { rememberLocalImagePreview } from '@/utils/localImagePreview';++import ImageFileListViewer from './ImageFileListViewer';++const srcs = (container: HTMLElement) =>+ [...container.querySelectorAll('img')].map((img) => img.getAttribute('src'));++describe('ImageFileListViewer', () => {+ it('shows an image this tab uploaded from its local copy', () => {+ rememberLocalImagePreview('file-local', 'blob:local');++ const { container } = render(+ <ImageFileListViewer+ items={[+ { alt: 'a', id: 'file-local', url: 'https://cdn/a.png' },+ { alt: 'b', id: 'file-remote', url: 'https://cdn/b.png' },+ ]}+ />,+ );++ expect(srcs(container)).toEqual(['blob:local', 'https://cdn/b.png']);+ });+});diff --git a/src/features/Conversation/Messages/User/components/ImageFileListViewer.tsx b/src/features/Conversation/Messages/User/components/ImageFileListViewer.tsxindex 39151f6830b..1a3593efac6 100644--- a/src/features/Conversation/Messages/User/components/ImageFileListViewer.tsx+++ b/src/features/Conversation/Messages/User/components/ImageFileListViewer.tsx@@ -1,9 +1,10 @@import { type ChatImageItem } from '@lobechat/types';import { PreviewGroup } from '@lobehub/ui';-import { memo } from 'react';+import { memo, useMemo } from 'react';import GalleyGrid from '@/components/GalleyGrid';import ImageItem from '@/components/ImageItem';+import { getLocalImagePreview } from '@/utils/localImagePreview';import { downloadPreviewImage } from '../../components/downloadPreviewImage';@@ -12,9 +13,24 @@ interface FileListProps {}const ImageFileListViewer = memo<FileListProps>(({ items }) => {+ // Images this tab just uploaded show from their local copy, so a sent message does not+ // wait for its images to download.+ const { shown, preview } = useMemo(() => {+ const uploadedUrls = new Map<string, string>();+ const shown = items.map((item) => {+ const local = getLocalImagePreview(item.id);+ if (!local) return item;+ uploadedUrls.set(local, item.url);+ return { ...item, url: local };+ });+ // Downloads still go through the uploaded file, which carries its stored name.+ const onDownload = (source: string) => downloadPreviewImage(uploadedUrls.get(source) ?? source);+ return { preview: { onDownload }, shown };+ }, [items]);+return (- <PreviewGroup preview={{ onDownload: downloadPreviewImage }}>- <GalleyGrid items={items} renderItem={ImageItem} />+ <PreviewGroup preview={preview}>+ <GalleyGrid items={shown} renderItem={ImageItem} /></PreviewGroup>);});diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.tsindex 8cce8f77e1f..2d91fbb74e1 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle/index.ts@@ -109,7 +109,8 @@ import { type StoreSetter } from '@/store/types';import { getUserStoreState } from '@/store/user';import { userProfileSelectors } from '@/store/user/selectors';import { useUserMemoryStore } from '@/store/userMemory';-import { markdownToTxt } from '@/utils/markdownToTxt';+import { rememberLocalImagePreview } from '@/utils/localImagePreview';+import { toTitleText } from '@/utils/markdownToTxt';import { aggregateSubagentMetrics } from '@/utils/subagentMetrics';import { materializeLocalSystemToolSnapshots } from '../../transports/client/localSystemToolSnapshots';@@ -621,7 +622,7 @@ export class ConversationLifecycleActionImpl {return;}- const newTopicTitle = markdownToTxt(message).slice(0, 80) || t('defaultTitle', { ns: 'topic' });+ const newTopicTitle = toTitleText(message).slice(0, 80) || t('defaultTitle', { ns: 'topic' });// βββ Message Queue: enqueue if this context is already busy βββ// Include the initial `sendMessage` persist/create-topic phase: while a first@@ -927,14 +928,18 @@ export class ConversationLifecycleActionImpl {// Use the captured `files` param (not the global file store) so the optimistic preview// also works on the queue-drain path, where chatUploadFileList has already been cleared.const filesForPreview = files ?? [];- const tempImages: ChatImageItem[] = filesForPreview- .filter((f) => f.file?.type?.startsWith('image'))- .map((f) => ({- ...f.dimensions,- id: f.id,- url: f.fileUrl || f.base64Url || f.previewUrl || '',- alt: f.file?.name || f.id,- }));+ const imageFiles = filesForPreview.filter((f) => f.file?.type?.startsWith('image'));+ // The message, optimistic and saved alike, shows these from the local copy (see+ // `localImagePreview`); an upload's id is its server file id once it has finished.+ for (const f of imageFiles) {+ if (f.status === 'success' && f.previewUrl) rememberLocalImagePreview(f.id, f.previewUrl);+ }+ const tempImages: ChatImageItem[] = imageFiles.map((f) => ({+ ...f.dimensions,+ id: f.id,+ url: f.fileUrl || f.base64Url || f.previewUrl || '',+ alt: f.file?.name || f.id,+ }));const tempVideos: ChatVideoItem[] = filesForPreview.filter((f) => f.file?.type?.startsWith('video')).map((f) => ({diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.tsindex 007302d9083..68fd1248686 100644--- a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts@@ -696,6 +696,30 @@ describe('buildRunLifecycle.afterUserMessagePersisted β topic title (all runti}});+ it('dev-slice title leaves inline image references out', async () => {+ const previous = process.env.NEXT_PUBLIC_DEV_DISABLE_AUTO_TOPIC;+ process.env.NEXT_PUBLIC_DEV_DISABLE_AUTO_TOPIC = '1';++ try {+ const { get, store } = makeStore();+ const messages = [+ { content: '[Image #1] [Image #1] dup test', id: 'm1', role: 'user' } as any,+ ];++ await lifecycle('client', get, 'top_level').afterUserMessagePersisted(+ persistedEvent('client', 'top_level', { isCreateNewTopic: true, messages, topicId: 't1' }),+ );++ expect(store.internal_updateTopic).toHaveBeenCalledWith('t1', { title: 'dup test' });+ } finally {+ if (previous === undefined) {+ delete process.env.NEXT_PUBLIC_DEV_DISABLE_AUTO_TOPIC;+ } else {+ process.env.NEXT_PUBLIC_DEV_DISABLE_AUTO_TOPIC = previous;+ }+ }+ });+it('loads the topic first when it is absent from the store (gateway fire-and-forget refreshTopic race)', async () => {const { get, store } = makeStore(); // topicMaps empty β getTopicById returns undefinedconst messages = [{ content: 'hi', id: 'm1', role: 'user' } as any];diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.tsindex 3080158ad8d..9a49b125732 100644--- a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts@@ -18,7 +18,7 @@ import {hasCompletedAssistantText,isAudioOnlyFirstUserMessage,} from '@/store/chat/utils/topicTitle';-import { markdownToTxt } from '@/utils/markdownToTxt';+import { toTitleText } from '@/utils/markdownToTxt';import { messageMapKey } from '../../../../utils/messageMapKey';import { displayMessageSelectors } from '../../../message/selectors/displayMessage';@@ -260,7 +260,7 @@ export const buildRunLifecycle = (return;}const firstUserText = messages.find((m) => m.role === 'user')?.content?.trim() ?? '';- const title = markdownToTxt(firstUserText).slice(0, 80) || 'New Topic';+ const title = toTitleText(firstUserText).slice(0, 80) || 'New Topic';// `internal_updateTopic` already balances its own loading owner. For a// new client-runtime topic like "ι θ―»δΈι’...", an extra `false` here would// consume the runtime's loading owner and hide the sidebar spinner early.diff --git a/src/store/file/slices/chat/action.test.ts b/src/store/file/slices/chat/action.test.tsindex acbcdfb9b73..517d37014cb 100644--- a/src/store/file/slices/chat/action.test.ts+++ b/src/store/file/slices/chat/action.test.ts@@ -563,6 +563,86 @@ describe('useFileStore:chat', () => {]);});+ // Regression: pasting the same image twice showed two cards and uploaded it twice, but+ // the server kept one file, so the message said [Image #1] [Image #2] with one image.+ describe('uploadChatFiles with an image already in the draft', () => {+ const gif = (name = 'image.gif') => new File(['same-pixels'], name, { type: 'image/gif' });++ beforeEach(() => {+ mockAgentMode({ enableAgentMode: true, heterogeneous: false });+ useStore.setState({ chatUploadFileListByContext: {} });+ });++ it('does not add or upload the same image again', async () => {+ const { result } = renderHook(() => useStore());+ const uploadWithProgress = vi+ .spyOn(result.current, 'uploadWithProgress')+ .mockResolvedValue({ id: 'file-1', url: 'url-1' } as any);++ await act(async () => {+ await result.current.uploadChatFiles(CONTEXT_KEY, [gif()], AGENT_ID);+ });+ await act(async () => {+ await result.current.uploadChatFiles(CONTEXT_KEY, [gif()], AGENT_ID);+ });++ expect(uploadWithProgress).toHaveBeenCalledTimes(1);+ expect(uploadList()).toEqual([+ expect.objectContaining({+ contentHash: expect.any(String),+ repastedAt: expect.any(Number),+ }),+ ]);+ });++ it('keeps one card for the same image pasted twice at once', async () => {+ const { result } = renderHook(() => useStore());+ const uploadWithProgress = vi+ .spyOn(result.current, 'uploadWithProgress')+ .mockResolvedValue({ id: 'file-1', url: 'url-1' } as any);++ await act(async () => {+ await result.current.uploadChatFiles(CONTEXT_KEY, [gif('a.gif'), gif('b.gif')], AGENT_ID);+ });++ expect(uploadWithProgress).toHaveBeenCalledTimes(1);+ expect(uploadList()).toHaveLength(1);+ });++ it('still uploads images where hashing is unavailable (insecure context)', async () => {+ const { result } = renderHook(() => useStore());+ const uploadWithProgress = vi+ .spyOn(result.current, 'uploadWithProgress')+ .mockResolvedValue({ id: 'file-1', url: 'url-1' } as any);+ vi.spyOn(crypto.subtle, 'digest').mockRejectedValue(new TypeError('no subtle'));++ await act(async () => {+ await result.current.uploadChatFiles(CONTEXT_KEY, [gif()], AGENT_ID);+ });++ expect(uploadWithProgress).toHaveBeenCalledTimes(1);+ expect(uploadList()).toEqual([expect.objectContaining({ contentHash: undefined })]);+ });++ it('uploads the image again when its earlier upload failed', async () => {+ const { result } = renderHook(() => useStore());+ const uploadWithProgress = vi+ .spyOn(result.current, 'uploadWithProgress')+ .mockRejectedValueOnce(new Error('offline'))+ .mockResolvedValue({ id: 'file-1', url: 'url-1' } as any);++ await act(async () => {+ await result.current.uploadChatFiles(CONTEXT_KEY, [gif()], AGENT_ID);+ });+ await act(async () => {+ await result.current.uploadChatFiles(CONTEXT_KEY, [gif()], AGENT_ID);+ });++ expect(uploadWithProgress).toHaveBeenCalledTimes(2);+ expect(uploadList()).toHaveLength(2);+ });+ });+describe('uploadChatFiles as an agent-share visitor', () => {const SHARE_ID = 'share-1';diff --git a/src/store/file/slices/chat/action.ts b/src/store/file/slices/chat/action.tsindex 02cc896b431..8ef6df2b4af 100644--- a/src/store/file/slices/chat/action.ts+++ b/src/store/file/slices/chat/action.ts@@ -73,6 +73,55 @@ export interface ChatUploadOptions {*/const createPendingUploadId = (file: File) => `${file.name}#${createNanoId(8)()}`;+/**+ * Best-effort: `crypto.subtle` is missing outside a secure context (a self-hosted page over+ * plain HTTP from a non-localhost address), where the image is uploaded without dedupe.+ */+const hashImageContent = async (file: File): Promise<string | undefined> => {+ try {+ const digest = await crypto.subtle.digest('SHA-256', await file.arrayBuffer());+ return Buffer.from(digest).toString('hex');+ } catch {+ return undefined;+ }+};++/** A failed or cancelled upload is not sent, so a new copy of its image is uploaded again. */+const isLiveUpload = (item: UploadFileItem) =>+ item.status !== 'error' && item.status !== 'cancelled';++/**+ * Drops newly prepared uploads whose content matches an image already in the draft (or+ * earlier in the same batch). A second card would upload the same file again, the server+ * keeps one copy, and the message would name an `[Image #2]` the model never receives.+ * `repastedIds` are the draft cards that matched, so they can show the paste landed.+ */+const withoutDuplicateImages = (+ current: UploadFileItem[],+ prepared: UploadFileItem[],+): { added: UploadFileItem[]; repastedIds: string[] } => {+ const existing = new Map<string, string>();+ for (const item of current) {+ if (item.contentHash && isLiveUpload(item)) existing.set(item.contentHash, item.id);+ }+ const seen = new Set<string>();+ const repastedIds = new Set<string>();++ const added = prepared.filter((item) => {+ if (!item.contentHash) return true;+ const existingId = existing.get(item.contentHash);+ if (existingId !== undefined || seen.has(item.contentHash)) {+ if (existingId !== undefined) repastedIds.add(existingId);+ if (item.previewUrl) URL.revokeObjectURL(item.previewUrl);+ return false;+ }+ seen.add(item.contentHash);+ return true;+ });++ return { added, repastedIds: [...repastedIds] };+};+const formatShareUploadLimit = () => `${Math.round(SHARE_VISITOR_MAX_FILE_SIZE / 1024 / 1024)} MB`;const getUploadErrorDescription = (error: unknown): string => {@@ -434,16 +483,22 @@ export class FileActionImpl {if (admittedFiles.length === 0) return;- // 1. compress images and add files with base64- const files = await Promise.all(- admittedFiles.map((file) =>- COMPRESSIBLE_IMAGE_TYPES.has(file.type) ? compressImageFile(file) : file,- ),+ // 1. compress images and add files with base64. Images are hashed first, since+ // compression re-encodes them and the same picture must hash the same every time.+ const prepared = await Promise.all(+ admittedFiles.map(async (rawFile) => {+ const contentHash = rawFile.type.startsWith('image')+ ? await hashImageContent(rawFile)+ : undefined;+ const file = COMPRESSIBLE_IMAGE_TYPES.has(rawFile.type)+ ? await compressImageFile(rawFile)+ : rawFile;+ return { contentHash, file };+ }),);- const uploadIds = new Map(files.map((file) => [file, createPendingUploadId(file)]));- const uploadFiles: UploadFileItem[] = await Promise.all(- files.map(async (file) => {+ const preparedItems: UploadFileItem[] = await Promise.all(+ prepared.map(async ({ contentHash, file }) => {let previewUrl: string | undefined = undefined;let base64Url: string | undefined = undefined;@@ -460,8 +515,9 @@ export class FileActionImpl {return {agentId,base64Url,+ contentHash,file,- id: uploadIds.get(file)!,+ id: createPendingUploadId(file),previewUrl,shareId,status: 'pending',@@ -469,7 +525,21 @@ export class FileActionImpl {}),);- dispatchChatUploadFileList({ files: uploadFiles, type: 'addFiles' });+ // Read the list and add to it in one synchronous step, so concurrent pastes of the+ // same image see each other.+ const { added: uploadFiles, repastedIds } = withoutDuplicateImages(+ this.#getChatUploadFileList(upload.contextKey),+ preparedItems,+ );++ if (uploadFiles.length > 0)+ dispatchChatUploadFileList({ files: uploadFiles, type: 'addFiles' });+ const repastedAt = Date.now();+ for (const id of repastedIds)+ dispatchChatUploadFileList({ id, type: 'updateFile', value: { repastedAt } });++ const files = uploadFiles.map((item) => item.file);+ const uploadIds = new Map(uploadFiles.map((item) => [item.file, item.id]));// upload files and process itconst pools = files.map(async (file) => {diff --git a/src/utils/localImagePreview.test.ts b/src/utils/localImagePreview.test.tsnew file mode 100644index 00000000000..383e7aa2cb3--- /dev/null+++ b/src/utils/localImagePreview.test.ts@@ -0,0 +1,12 @@+import { describe, expect, it } from 'vitest';++import { getLocalImagePreview, rememberLocalImagePreview } from './localImagePreview';++describe('localImagePreview', () => {+ it('returns the local copy remembered for an uploaded file', () => {+ rememberLocalImagePreview('file-1', 'blob:a');++ expect(getLocalImagePreview('file-1')).toBe('blob:a');+ expect(getLocalImagePreview('file-2')).toBeUndefined();+ });+});diff --git a/src/utils/localImagePreview.ts b/src/utils/localImagePreview.tsnew file mode 100644index 00000000000..f1fc4650508--- /dev/null+++ b/src/utils/localImagePreview.ts@@ -0,0 +1,16 @@+/**+ * Local previews of images this tab uploaded, keyed by uploaded file id.+ *+ * A sent message shows its images from their uploaded URL, which the browser has not+ * downloaded yet, so they would show as empty boxes until it does, although the composer+ * still holds each image as a local object URL. Message images look their file id up here+ * and show that copy instead. It lasts for the page's lifetime; after a reload, messages+ * fall back to the uploaded URL.+ */+const previews = new Map<string, string>();++export const rememberLocalImagePreview = (fileId: string, previewUrl: string) => {+ previews.set(fileId, previewUrl);+};++export const getLocalImagePreview = (fileId: string): string | undefined => previews.get(fileId);diff --git a/src/utils/markdownToTxt.test.ts b/src/utils/markdownToTxt.test.tsindex f17cce59c9b..928a90c3121 100644--- a/src/utils/markdownToTxt.test.ts+++ b/src/utils/markdownToTxt.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { markdownToTxt } from './markdownToTxt';+import { markdownToTxt, toTitleText } from './markdownToTxt';describe('markdownToTxt', () => {describe('basic markdown conversion', () => {@@ -244,3 +244,9 @@ npm install package});});});++describe('toTitleText', () => {+ it('leaves inline image references out of the title text', () => {+ expect(toTitleText('[Image #1] dup **test**')).toBe('dup test');+ });+});diff --git a/src/utils/markdownToTxt.ts b/src/utils/markdownToTxt.tsindex d562be2c743..243b8f84dec 100644--- a/src/utils/markdownToTxt.ts+++ b/src/utils/markdownToTxt.ts@@ -1,3 +1,4 @@+import { stripImageRefs } from '@lobechat/const/imageRef';import removeMarkdown from 'remove-markdown';/**@@ -17,4 +18,10 @@ export const markdownToTxt = (markdown: string): string => {}};+/**+ * Plain text of a user prompt for a topic title. Inline image references such as `[Image #1]`+ * point at attachments and say nothing about the topic, so they are left out.+ */+export const toTitleText = (prompt: string): string => markdownToTxt(stripImageRefs(prompt)).trim();+export default markdownToTxt;