Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): 保持消息发送交接时的预览与布局连续 (#4149)
Dash656858302149
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsxindex 3df979970d..647156d527 100644--- a/apps/mobile/app/sessions/[sessionId].tsx+++ b/apps/mobile/app/sessions/[sessionId].tsx@@ -335,6 +335,7 @@ import {type QueueEditTextState,} from '@/session/inputProjection';import {+ appendPendingSendItems,buildPendingSendItems,type MobilePendingSendActions,} from '@/session/pendingSendItems';@@ -376,6 +377,11 @@ import { buildSessionComposerLayout } from '@/session/sessionComposerLayout';import { discardMobileUploadedAttachment } from '@/session/mobileAttachmentUpload';import { buildMobileImageAttachmentCandidate } from '@/session/mobileImageAttachment';import { useMobileLocalAttachments } from '@/session/useMobileLocalAttachments';+import {+ getSentMessageImagePreview,+ rememberSentMessageImagePreviews,+ type SentMessageImagePreviews,+} from '@/session/sentMessageImagePreviews';import {buildOutboxItem,createOutboxClientId,@@ -1473,31 +1479,24 @@ export default function SessionScreen() {}, [sessionId]);const settlingAddedAtRef = useRef<Map<string, number>>(new Map());/**- * 「附件 ossRef → 发送时刻的本地预览 file://」。+ * 按任务、消息和图片顺序保存发送预览,跨桌面端媒体地址物化继续使用。** 排队气泡里的图不能等 sentAttachmentThumbStore 那条链(上传落定 → 拷进自有目录 →* AsyncStorage hydrate)——期间查询一律返回 null,气泡只能画空占位格。发送时手边就有* 预览,记下来直接用;store 仍是重开会话 / 预览失效后的后备。- * 上限防无界:窗口本来就短(消息回流即不再需要),留 64 条覆盖极端连发。+ * 最多保留 64 条消息的预览;正式内容还会核对图片指纹,防止同名替换误用旧图。*/- const sentPreviewByOssRefRef = useRef<Map<string, string>>(new Map());+ const sentImagePreviewsRef = useRef<SentMessageImagePreviews>(new Map());const rememberSentAttachmentPreviews = useCallback((+ clientId: string,attachments: readonly RemoteSerializedAttachment[],previewOf: (attachment: RemoteSerializedAttachment) => string | null | undefined,) => {- const map = sentPreviewByOssRefRef.current;- for (const attachment of attachments) {- const ossRef = attachment.url ?? attachment.path;- const preview = previewOf(attachment);- if (!ossRef || !preview) continue;- map.set(ossRef, preview);- }- while (map.size > 64) {- const oldest = map.keys().next();- if (oldest.done) break;- map.delete(oldest.value);- }- }, []);+ rememberSentMessageImagePreviews(sentImagePreviewsRef.current, sessionId, clientId, attachments, previewOf);+ }, [sessionId]);+ const getSentImagePreview = useCallback((clientId: string, imageIndex: number, name: string, attachmentId?: string, sha256?: string, sourceRef?: string) => (+ getSentMessageImagePreview(sentImagePreviewsRef.current, sessionId, clientId, imageIndex, name, attachmentId, sha256, sourceRef)+ ), [sessionId]);// 「乐观气泡已上屏、enqueue RPC 尚未落定」的 clientId:这段窗口消息是否真的发出// 还没有答案(弱网可达数秒,且失败会回滚摘除气泡),徽标必须是转圈而不是「排入// 队尾」——后者是已确认入队的语义。成功 / 回滚 / 转失败任一落定即移除。@@ -5439,6 +5438,7 @@ export default function SessionScreen() {updateOutbox((items) => items.filter((entry) => entry.clientId !== item.clientId));// outbox 条目的槽位预览接着给排队气泡用:交接后图不能因为换了数据源就消失。rememberSentAttachmentPreviews(+ item.clientId,outboxItemAttachments(item),(attachment) => {const slotIndex = item.attachmentSlots.findIndex((slot) => slot?.id === attachment.id);@@ -5664,11 +5664,12 @@ export default function SessionScreen() {editingClientId: queueEditing?.clientId ?? null,steeringClientIds: new Set(inputProjection.steeringQueueClientIds),presentationByClientId,- previewByOssRef: sentPreviewByOssRefRef.current,+ getImagePreview: getSentImagePreview,});},[i18nInstance.language,+ getSentImagePreview,inputProjection,outboxDisplayItems,queueBusy,@@ -5680,7 +5681,7 @@ export default function SessionScreen() {],);const messageListItems = useMemo(- () => (pendingSendItems.length === 0 ? renderItems : [...renderItems, ...pendingSendItems]),+ () => appendPendingSendItems(renderItems, pendingSendItems),[pendingSendItems, renderItems],);const messageListStructureKey = useMemo(@@ -6241,6 +6242,8 @@ export default function SessionScreen() {const projectionEpochAtRequestStart =remoteSessionStore.captureInputProjectionAuthorityEpoch(sessionId);const projection = await maker.input.updateContent(sessionId, editingQueueItem.clientId, updated);+ rememberSentAttachmentPreviews(editingQueueItem.clientId, sendAttachments,+ (attachment) => attachmentPreviews[attachment.id]);applyProjectionIfCurrent(projection, projectionEpochAtRequestStart);} catch (err) {if (@@ -6429,6 +6432,7 @@ export default function SessionScreen() {});// 排队气泡的图立刻可见(先记预览,再让 projection 变化触发重算)。rememberSentAttachmentPreviews(+ queued.clientId,sendAttachments,(attachment) => attachmentPreviews[attachment.id],);@@ -9212,6 +9216,7 @@ export default function SessionScreen() {items={messageListItems}itemsStructureKey={messageListStructureKey}pendingSend={pendingSendActions}+ getSentImagePreview={getSentImagePreview}loadingEarlier={historyView.snapshot.ready ? historyView.snapshot.loading : loadingEarlier}loadEarlierProgressKey={oldestLoadedMessageCursor}onCopyMessageLink={copyMessageLink}diff --git a/apps/mobile/src/__tests__/messageImageHandoff.test.tsx b/apps/mobile/src/__tests__/messageImageHandoff.test.tsxnew file mode 100644index 0000000000..bd35cc3338--- /dev/null+++ b/apps/mobile/src/__tests__/messageImageHandoff.test.tsx@@ -0,0 +1,131 @@+// @vitest-environment jsdom+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';+import * as React from 'react';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import ts from 'typescript';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { buildMessageContentLayout } from '@/session/messageContentLayout';+import { attachmentImageDisplaySize, mediaThumbnailPhase, shouldAutoResolveMediaThumbnail } from '@/session/mediaThumbnail';+import { isDesktopLocalMediaUrl } from '@/session/remoteMedia';+import { spacing } from '@/theme/tokens';++// Run the production components with real React effects; only native image decoding is controlled.+const source = ts.createSourceFile('renderer.tsx', readFileSync(resolve(process.cwd(), 'src/session/MessageRenderer.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+const names = new Set(['PendingAttachmentImage', 'MediaPreview']);+const pendingSource = ts.createSourceFile('pending.tsx', readFileSync(resolve(process.cwd(), 'src/session/PendingSendBubble.tsx'), 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);+const hookCode = pendingSource.statements.find((node) => ts.isFunctionDeclaration(node) && node.name?.text === 'useThumbCellUri')!.getText(pendingSource);+const componentCode = source.statements.filter((node) => ts.isFunctionDeclaration(node) && names.has(node.name?.text ?? '')).map((node) => node.getText(source)).join('\n') + '\n' + hookCode;+const compiled = ts.transpileModule(componentCode, { compilerOptions: { jsx: ts.JsxEmit.React, target: ts.ScriptTarget.ES2022 } }).outputText;+const cleanups: Array<() => void> = [];+afterEach(() => { for (const cleanup of cleanups.splice(0)) cleanup(); });++function fixture() {+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+ const cache = new Map();+ const handlers = new Map<string, { onLoad: (event: unknown) => void; onError: () => void }>();+ const durable = new Map<string, string>();+ const flatten = (style: unknown): React.CSSProperties => Object.assign({}, ...[style].flat(Infinity).filter(Boolean));+ const View = ({ children, style, testID, onPress }: any) => <div style={flatten(style)} data-testid={testID} onClick={onPress}>{children}</div>;+ const ExpoImage = ({ source: imageSource, style, onLoad, onError }: any) => {+ handlers.set(imageSource.uri, { onLoad, onError });+ return <div data-image={imageSource.uri} style={flatten(style)} />;+ };+ const Image = Object.assign(ExpoImage, { getSize: vi.fn() });+ const bindings = { React, View, Text: View, ExpoImage, Image,+ useThemedStyles: () => ({}), makeStyles: () => ({}),+ useRecyclingState: React.useState, useState: React.useState, useLayoutEffect: React.useLayoutEffect,+ useEffect: React.useEffect, useRef: React.useRef, useCallback: React.useCallback,+ attachmentIntrinsicSizeCache: cache, ATTACHMENT_INTRINSIC_CACHE_MAX: 500,+ attachmentImageDisplaySize, mediaThumbnailPhase, shouldAutoResolveMediaThumbnail, isDesktopLocalMediaUrl,+ getSentAttachmentThumbUri: (ref: string) => durable.get(ref) ?? null,+ MessageContentOpenButton: View,+ buildMediaPayload: (media: unknown) => media,+ summarizeMessagePayloadPreview: () => ({ actionLabel: 'Open', title: 'Image', meta: ['Image'], detail: 'Preview' }),+ payloadMediaKindLabel: () => 'Image',+ };+ const components = new Function(...Object.keys(bindings), `${compiled}; return { PendingAttachmentImage, MediaPreview, useThumbCellUri };`)(...Object.values(bindings));+ const host = document.createElement('div');+ document.body.append(host);+ const root = createRoot(host);+ cleanups.push(() => { act(() => root.unmount()); host.remove(); });+ const layout = buildMessageContentLayout({ screenWidth: 390 });+ const render = (node: React.ReactNode) => act(() => root.render(node));+ const frame = () => {+ const image = host.querySelector('[data-image]') as HTMLElement;+ return [image.style.width, image.style.height];+ };+ return { ...components, host, render, layout, handlers, frame, durable, Image };+}++describe('image frame continuity', () => {+ it('keeps the displayed pending source when upload completes, but releases it on attachment replacement', () => {+ const f = fixture();+ const Probe = ({ thumb }: any) => <span>{f.useThumbCellUri(thumb)}</span>;+ const thumb = { key: 'message-slot-0', uri: 'file:///original.jpg', ossRef: null };+ f.render(<Probe thumb={thumb} />);+ f.durable.set('cindy-oss-attach://m/a', 'file:///durable.jpg');+ f.render(<Probe thumb={{ ...thumb, ossRef: 'cindy-oss-attach://m/a' }} />);+ expect(f.host.textContent).toBe(thumb.uri);+ f.render(<Probe thumb={{ ...thumb, uri: 'file:///replacement.jpg' }} />);+ expect(f.host.textContent).toBe('file:///replacement.jpg');+ });+ it.each([[900, 1600], [1600, 900]])('keeps the loaded %s x %s frame on the first formal render before any new decode', (width, height) => {+ const f = fixture();+ const localPreview = { uri: 'ph://photo', sourceRef: 'cindy-oss-attach://m/a' };+ f.render(<f.PendingAttachmentImage uri={localPreview.uri} layout={f.layout} />);+ act(() => f.handlers.get(localPreview.uri)!.onLoad({ source: { width, height } }));+ const pendingFrame = f.frame();+ const resolveRemote = vi.fn();+ const formal = <f.MediaPreview layout={f.layout} label="photo" variant="attachment" localPreview={localPreview}+ media={{ kind: 'image', url: 'cindy-media://blobs/a.jpg', previewable: false }} onResolveRemoteMedia={resolveRemote} />;+ f.render(formal);+ expect(f.frame()).toEqual(pendingFrame);+ expect(f.host.querySelector('[data-testid="message.mediaThumbLoading"]')).toBeNull();+ expect(resolveRemote).not.toHaveBeenCalled();+ expect(f.Image.getSize).not.toHaveBeenCalled();+ // Registration finishing later must not replace the already visible local source.+ f.durable.set(localPreview.sourceRef, 'file:///durable.jpg');+ f.render(React.cloneElement(formal));+ expect(f.host.querySelector('[data-image]')?.getAttribute('data-image')).toBe(localPreview.uri);+ expect(f.frame()).toEqual(pendingFrame);+ // A deleted paste source can switch to its durable copy, retaining the same geometry.+ act(() => f.handlers.get(localPreview.uri)!.onError());+ expect(f.host.querySelector('[data-image]')?.getAttribute('data-image')).toBe('file:///durable.jpg');+ expect(f.frame()).toEqual(pendingFrame);+ });++ it('keeps an unavailable OSS image inside the attachment frame rather than a small file card', () => {+ const f = fixture();+ f.render(<f.MediaPreview layout={f.layout} label="photo" variant="attachment"+ media={{ kind: 'image', url: 'cindy-oss-attach://m/missing', previewable: false }} />);+ const fallback = f.host.querySelector('[data-testid="message.mediaThumbFallback"]') as HTMLElement;+ expect(fallback.style.width).toBe(`${f.layout.attachmentImageMaxWidth}px`);+ expect(fallback.style.height).toBe(`${f.layout.attachmentImageMaxHeight}px`);+ });++ it('uses the same top spacing and attachment-to-body gap in both row layouts', () => {+ function styles(file: ts.SourceFile, selected: string[]) {+ const properties: string[] = [];+ function visit(node: ts.Node) {+ if (ts.isVariableDeclaration(node) && node.name.getText(file) === 'makeStyles') {+ const body = (node.initializer as ts.ArrowFunction).body as ts.CallExpression;+ for (const property of (body.arguments[0] as ts.ObjectLiteralExpression).properties) {+ if (property.name && selected.includes(property.name.getText(file))) properties.push(property.getText(file));+ }+ }+ ts.forEachChild(node, visit);+ }+ visit(file);+ expect(properties).toHaveLength(selected.length);+ return new Function('spacing', 'MOBILE_MESSAGE_LIST_BOTTOM_PADDING', `return ({${properties.join(',')}});`)(spacing, 0);+ }+ const pending = styles(pendingSource, ['rowWrap', 'bubbleRow', 'content', 'attachmentStrip']);+ const formal = styles(source, ['messages', 'messageItem', 'userMessageItem', 'attachmentStrip']);+ const top = (rows: any[]) => rows.reduce((sum, row) => sum + (row.marginTop ?? 0) + (row.paddingTop ?? 0), formal.messages.gap);+ expect(top([pending.rowWrap, pending.bubbleRow, pending.content])).toBe(top([formal.messageItem, formal.userMessageItem]));+ expect(formal.messages.gap).toBe(spacing.lg);+ expect(pending.content.gap + pending.attachmentStrip.marginBottom).toBe(formal.messageItem.gap + formal.attachmentStrip.marginBottom);+ });+});diff --git a/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts b/apps/mobile/src/__tests__/optimisticSessionComposer.test.tsindex dd43884a2b..ebc782869b 100644--- a/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts+++ b/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts@@ -447,9 +447,10 @@ describe('mobile optimistic composer while session is not ready', () => {expect(screen).toContain('const showComposerActivity = isSessionStreaming || streamingSticky === sessionId;');const bubble = readSource('src/session/PendingSendBubble.tsx');- expect(bubble).toContain("const identity = `${thumb.uri ?? ''}|${thumb.ossRef ?? ''}`;");- expect(bubble).toContain("const shown = shownRef.current?.identity === identity ? shownRef.current.uri : null;");- expect(bubble).toContain('remoteState?.identity === identity ? remoteState.uri : null');+ // 上传补齐 ossRef 不改变本地图片身份;附件替换仍重置预览。+ expect(bubble).toContain('const identity = thumb.uri ?? thumb.ossRef ?? thumb.key;');+ expect(bubble).toContain('shownRef.current?.identity === identity && !failedUris.includes(shownRef.current.uri)');+ expect(bubble).toContain('remoteState?.identity === identity && !failedUris.includes(remoteState.uri)');});it('routes every remote-session-dependent entry through one judgement', () => {diff --git a/apps/mobile/src/__tests__/pendingSendItems.test.ts b/apps/mobile/src/__tests__/pendingSendItems.test.tsindex e26be794f6..41de33dd6b 100644--- a/apps/mobile/src/__tests__/pendingSendItems.test.ts+++ b/apps/mobile/src/__tests__/pendingSendItems.test.ts@@ -9,6 +9,7 @@import { describe, expect, it } from 'vitest';import { formatQuoteForSend } from '@cindy/maker-shared/chat-quotes';import {+ appendPendingSendItems,buildMobileMessageListExtraData,buildPendingSendItems,isPendingSendItemSelected,@@ -71,6 +72,29 @@ function build(overrides: Partial<Parameters<typeof buildPendingSendItems>[0]> =});}+describe('appendPendingSendItems', () => {+ it.each(['text', 'image'])('replaces %s pending rows when history arrives before queue reconciliation', (kind) => {+ const pending = build({ outbox: [outboxItem('sent', kind === 'image' ? {+ text: '', attachmentCount: 1, uploadedCount: 1,+ thumbnails: [{ key: 'sent-slot-0', uri: 'file:///image.png', ossRef: null, uploading: false }],+ } : {}), outboxItem('next')] });+ const previous = { key: 'message-previous', type: 'message' };+ const delivered = { key: pendingSendItemKey('sent'), type: 'message' };+ expect(appendPendingSendItems([previous], pending)).toEqual([previous, ...pending]);+ // The history snapshot advanced, but raw-store token / pending snapshot did not.+ const during = appendPendingSendItems([previous, delivered], pending);+ expect(during).toEqual([previous, delivered, pending[1]]);+ expect(new Set(during.map((row) => row.key)).size).toBe(during.length);+ expect(appendPendingSendItems([previous, delivered], pending.slice(1))).toEqual(during);+ });++ it('retains the rendered list when no optimistic rows remain', () => {+ const rendered = [{ key: pendingSendItemKey('sent') }];+ expect(appendPendingSendItems(rendered, [])).toBe(rendered);+ expect(appendPendingSendItems(rendered, build({ queue: [queued('sent')] }))).toBe(rendered);+ });+});+describe('buildPendingSendItems', () => {it('shares the message item key so the bubble and the real message land in one place', () => {const [item] = build({ queue: [queued('abc')] });diff --git a/apps/mobile/src/__tests__/sentMessageImagePreviews.test.ts b/apps/mobile/src/__tests__/sentMessageImagePreviews.test.tsnew file mode 100644index 0000000000..57f819316f--- /dev/null+++ b/apps/mobile/src/__tests__/sentMessageImagePreviews.test.ts@@ -0,0 +1,66 @@+import { describe, expect, it } from 'vitest';+import {+ getSentMessageImagePreview, rememberSentMessageImagePreviews, type SentMessageImagePreviews,+} from '@/session/sentMessageImagePreviews';+import { buildPendingSendItems } from '@/session/pendingSendItems';+import type { QueuedRemoteMessage, RemoteSerializedAttachment } from '@/session/types';++const image = (id: string, name = `${id}.jpg`): RemoteSerializedAttachment => ({+ id, name, category: 'image', path: `cindy-oss-attach://m/${id}`, url: `cindy-oss-attach://m/${id}`,+ mimeType: 'image/jpeg', size: 100, ext: 'jpg', sha256: id.repeat(64),+});++describe('sent image preview handoff', () => {+ it('keeps image order through mixed files and host URL materialization, including the formal message', () => {+ const previews: SentMessageImagePreviews = new Map();+ const files = [image('a'), { ...image('pdf'), category: 'pdf' as const }, image('b')];+ rememberSentMessageImagePreviews(previews, 'session', 'message', files, (file) => `file:///${file.id}.jpg`);+ const getPreview = (clientId: string, index: number, name: string, id?: string, sha256?: string) => (+ getSentMessageImagePreview(previews, 'session', clientId, index, name, id, sha256)+ );+ const queued = {+ clientId: 'message', text: '', chatMessage: {},+ files: files.map((file) => ({ ...file, url: `cindy-media://blobs/${file.id}.jpg` })),+ } as unknown as QueuedRemoteMessage;+ const [pending] = buildPendingSendItems({ queue: [queued], settling: [], outbox: [],+ hiddenClientIds: new Set(), sendingClientIds: new Set(), editingClientId: null,+ steeringClientIds: new Set(), presentationByClientId: new Map(), getImagePreview: getPreview });+ expect(pending.thumbs.map((thumb) => [thumb.key, thumb.uri])).toEqual([+ ['message-slot-0', 'file:///a.jpg'], ['message-slot-2', 'file:///b.jpg'],+ ]);+ expect(pending.thumbs[0].previewRef).toBe(files[0].url);+ // Formal messages have no file ID; the accepted message and image position remain stable.+ expect(getPreview('message', 1, 'b.jpg', undefined, files[2].sha256)?.uri).toBe(pending.thumbs[1].uri);+ expect(getPreview('message', 1, 'b.jpg', undefined, 'changed-fingerprint')).toBeUndefined();+ expect(getSentMessageImagePreview(previews, 'other-session', 'message', 1, 'b.jpg')).toBeUndefined();+ });++ it('replaces all image slots on edit, including same-name replacements and absent previews', () => {+ const previews: SentMessageImagePreviews = new Map();+ rememberSentMessageImagePreviews(previews, 's', 'm', [image('a', 'same.jpg'), image('b')], () => 'file:///old.jpg');+ expect(getSentMessageImagePreview(previews, 's', 'm', 0, 'same.jpg', 'changed-on-desktop')).toBeUndefined();+ rememberSentMessageImagePreviews(previews, 's', 'm', [image('new', 'same.jpg')], () => 'file:///new.jpg');+ expect(getSentMessageImagePreview(previews, 's', 'm', 0, 'same.jpg', 'new')?.uri).toBe('file:///new.jpg');+ expect(getSentMessageImagePreview(previews, 's', 'm', 1, 'b.jpg')).toBeUndefined();+ rememberSentMessageImagePreviews(previews, 's', 'm', [image('missing', 'same.jpg')], () => null);+ expect(getSentMessageImagePreview(previews, 's', 'm', 0, 'same.jpg')).toBeUndefined();+ });++ it('bounds retained message previews', () => {+ const previews: SentMessageImagePreviews = new Map();+ for (let n = 0; n < 65; n++) rememberSentMessageImagePreviews(previews, 's', String(n), [image('a')], () => 'file:///a.jpg');+ expect(previews.size).toBe(64);+ expect(getSentMessageImagePreview(previews, 's', '0', 0, 'a.jpg')).toBeUndefined();+ });++ it('preserves previews on text-only edits and matches the persisted original name', () => {+ const previews: SentMessageImagePreviews = new Map();+ const attachment = { ...image('a', 'upload.jpg'), originalName: 'photo.jpg' };+ rememberSentMessageImagePreviews(previews, 's', 'm', [attachment], () => 'ph://original');+ rememberSentMessageImagePreviews(previews, 's', 'm', [{ ...attachment, url: 'cindy-media://blobs/a.jpg' }], () => undefined);+ const formal = getSentMessageImagePreview(previews, 's', 'm', 0, 'photo.jpg', undefined, attachment.sha256);+ expect(formal?.uri).toBe('ph://original');+ expect(formal?.sourceRef).toBe(attachment.url);+ expect(getSentMessageImagePreview(previews, 's', 'm', 0, 'upload.jpg', 'a')).toEqual(formal);+ });+});diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsxindex 5f50bde200..10404d725b 100644--- a/apps/mobile/src/session/MessageRenderer.tsx+++ b/apps/mobile/src/session/MessageRenderer.tsx@@ -158,8 +158,10 @@ import {} from '@/session/messageGallery';import {applySentAttachmentThumbOverlay,+ getSentAttachmentThumbUri,useSentAttachmentThumbsVersion,} from '@/session/sentAttachmentThumbStore';+import type { GetSentMessageImagePreview, SentMessageImagePreview } from '@/session/sentMessageImagePreviews';import {buildMobileMessageCopyText,copyMessageText,@@ -613,6 +615,7 @@ interface MessageActions {shareSelectionBusy?: boolean;/** 待发送气泡(pending_send 项)的展开态与队列操作回调。 */pendingSend?: PendingSendBubbleActions;+ getSentImagePreview?: GetSentMessageImagePreview;onReadTextFilePreview?: (filePath: string) => Promise<RemoteTextFilePreviewResult>;onReleaseRemoteMedia?: (sourceUrl: string, media: MobileResolvedRemoteMedia) => void;onResolveRemoteMedia?: ResolveRemoteMediaFn;@@ -655,6 +658,7 @@ export function MessageRenderer({shareSelectionBusy,onQuoteSelection,pendingSend,+ getSentImagePreview,onReadTextFilePreview,onReleaseRemoteMedia,onResolveRemoteMedia,@@ -1546,6 +1550,7 @@ export function MessageRenderer({// 待发送气泡(pending_send 项)的展开态与队列操作:漏了这一项 actions.pendingSend 就是// undefined,渲染分支直接 null —— 气泡整个不画,乐观显示消失。pendingSend,+ getSentImagePreview,shareSelectionActive,shareSelectionBusy,busyClientId,@@ -1579,6 +1584,7 @@ export function MessageRenderer({handleMessageActionSheetOpenChange,onResolveRemoteMedia,pendingSend,+ getSentImagePreview,shareSelectionActive,shareSelectionBusy,viewportLayout.contentWidth,@@ -2675,10 +2681,12 @@ const RenderItemView = memo(function RenderItemView({actions={actions.pendingSend}item={item}screenWidth={actions.screenWidth}- renderImage={(uri) => uri ? (- <PendingAttachmentImage key={uri}+ renderImage={(uri, sourceUri, onError) => uri ? (+ <PendingAttachmentImage key={sourceUri ?? uri}layout={buildMessageContentLayout({ screenWidth: actions.screenWidth })}uri={uri}+ sourceUri={sourceUri ?? uri}+ onError={onError}/>) : (<View style={[styles.attachmentImagePending, {@@ -3222,6 +3230,8 @@ function MessageBubble({<AttachmentStripalign={isUser ? 'right' : 'left'}attachments={item.message.attachments}+ clientId={item.message.source.clientId ?? item.message.source.id}+ getImagePreview={actions.getSentImagePreview}layout={contentLayout}onOpen={actions.onOpenPayload}onResolveRemoteMedia={actions.onResolveRemoteMedia}@@ -5746,12 +5756,16 @@ function MarkdownSessionLinkSpan({function AttachmentStrip({attachments,+ clientId,+ getImagePreview,align,layout,onOpen,onResolveRemoteMedia,}: {attachments: readonly NormalizedAttachment[];+ clientId?: string;+ getImagePreview?: GetSentMessageImagePreview;align: 'left' | 'right';layout: MessageContentLayout;onOpen?: (payload: MessagePayload) => void;@@ -5769,13 +5783,14 @@ function AttachmentStrip({{/* 图片附件对齐桌面版:逐张竖排(不换行拼贴),各自按原始宽高比 contain。overlay:本机上传的图在被控端物化改写前 url 仍是 cindy-oss-attach://,本地兜底命中时替换成 file:// 直接渲染(payload 同源替换,点开查看器同图)。 */}- {imageAttachments.map(applySentAttachmentThumbOverlay).map((item, index) => (+ {imageAttachments.map((item, index) => (<MediaPreviewkey={`${item.kind}:${item.uri ?? item.name}:${index}`}label={item.name}layout={layout}media={{ kind: 'image', url: item.uri ?? '', previewable: item.previewable }}- onOpen={onOpen ? () => onOpen(buildAttachmentPayload(item)) : undefined}+ localPreview={clientId ? getImagePreview?.(clientId, index, item.name, undefined, item.sha256, item.uri) : undefined}+ onOpen={onOpen ? () => onOpen(buildAttachmentPayload(applySentAttachmentThumbOverlay(item))) : undefined}onResolveRemoteMedia={onResolveRemoteMedia}variant="attachment"/>@@ -5860,11 +5875,21 @@ const ATTACHMENT_INTRINSIC_CACHE_MAX = 500;// 相册候选仍可能是 ph://,必须由 expo-image 加载;只复用正式附件的布局,// 不把本地相册地址声明为 RN Image / 远端查看器可直接预览的媒体。-function PendingAttachmentImage({ layout, uri }: { layout: MessageContentLayout; uri: string }) {+function PendingAttachmentImage({ layout, uri, sourceUri = uri, onError, onSize }: {+ layout: MessageContentLayout; uri: string; sourceUri?: string; onError?: () => void;+ onSize?: (size: AttachmentImageIntrinsicSize) => void;+}) {const styles = useThemedStyles(makeStyles);const [intrinsicSize, setIntrinsicSize] = useRecyclingState<AttachmentImageIntrinsicSize | null>(- () => attachmentIntrinsicSizeCache.get(uri) ?? null,+ () => attachmentIntrinsicSizeCache.get(sourceUri) ?? attachmentIntrinsicSizeCache.get(uri) ?? null,);+ // The upload copy and materialized reference describe the same pixels. Carry their measured frame.+ useLayoutEffect(() => {+ if (!intrinsicSize) return;+ if (attachmentIntrinsicSizeCache.size >= ATTACHMENT_INTRINSIC_CACHE_MAX) attachmentIntrinsicSizeCache.clear();+ attachmentIntrinsicSizeCache.set(sourceUri, intrinsicSize);+ attachmentIntrinsicSizeCache.set(uri, intrinsicSize);+ }, [intrinsicSize, sourceUri, uri]);const displaySize = attachmentImageDisplaySize(intrinsicSize, layout.attachmentImageMaxWidth, layout.attachmentImageMaxHeight,);@@ -5874,13 +5899,16 @@ function PendingAttachmentImage({ layout, uri }: { layout: MessageContentLayout;source={{ uri }}recyclingKey={uri}contentFit="contain"+ onError={onError}onLoad={({ source: { width, height } }) => {if (!(width > 0 && height > 0)) return;if (attachmentIntrinsicSizeCache.size >= ATTACHMENT_INTRINSIC_CACHE_MAX) {attachmentIntrinsicSizeCache.clear();}attachmentIntrinsicSizeCache.set(uri, { width, height });+ attachmentIntrinsicSizeCache.set(sourceUri, { width, height });setIntrinsicSize({ width, height });+ onSize?.({ width, height });}}style={[styles.attachmentImage, displaySize]}/>@@ -5908,6 +5936,7 @@ function MediaPreview({onResolveRemoteMedia,variant = 'card',presentationOnly = false,+ localPreview,}: {layout: MessageContentLayout;media: NormalizedToolMedia;@@ -5916,16 +5945,25 @@ function MediaPreview({onResolveRemoteMedia?: ResolveRemoteMediaFn;variant?: 'card' | 'attachment';presentationOnly?: boolean;+ localPreview?: SentMessageImagePreview;}) {const styles = useThemedStyles(makeStyles);const preview = summarizeMessagePayloadPreview(buildMediaPayload(media, label));- const autoResolve = shouldAutoResolveMediaThumbnail(media, !!onResolveRemoteMedia);+ const durableUri = media.kind === 'image' && variant === 'attachment'+ ? getSentAttachmentThumbUri(localPreview?.sourceRef ?? media.url)+ : null;+ const localCandidate = localPreview?.uri ?? durableUri;+ const [failedLocalUris, setFailedLocalUris] = useRecyclingState<readonly string[]>([]);+ // Keep the sent source when a durable copy appears later; switch only after an actual load error.+ const localUri = [localCandidate, durableUri].find((uri) => uri && !failedLocalUris.includes(uri)) ?? null;+ const autoResolve = !localUri && shouldAutoResolveMediaThumbnail(media, !!onResolveRemoteMedia);const [resolveState, setResolveState] = useRecyclingState<MediaThumbnailResolveState>({ status: 'idle' });// attachment 变体的原图尺寸。初值走模块级缓存:FlatList 虚拟化会反复// unmount/remount 本组件,不缓存的话每次划回都重新 getSize、重演一次// 占位帧 → 真图尺寸的切换(规则 7 的跳变)。const [intrinsicSize, setIntrinsicSize] = useRecyclingState<AttachmentImageIntrinsicSize | null>(- () => attachmentIntrinsicSizeCache.get(media.url) ?? null,+ () => attachmentIntrinsicSizeCache.get(localPreview?.uri ?? media.url)+ ?? attachmentIntrinsicSizeCache.get(localCandidate ?? media.url) ?? null,);// Image 加载失败(典型:presign 过期)只强制重取一次,防 onError↔重取死循环。const imageRetryUsedRef = useRef(false);@@ -5977,7 +6015,7 @@ function MediaPreview({// attachment 变体:异步量原图宽高并写入模块级缓存;失败置 -1 走 max 框回落帧,// 图仍照常渲染(不作为出图门控,见下)。已有尺寸(含缓存命中)不重复测量。useEffect(() => {- if (variant !== 'attachment' || !thumbUri || intrinsicSize) return;+ if (variant !== 'attachment' || localUri || !thumbUri || intrinsicSize) return;let cancelled = false;Image.getSize(thumbUri,@@ -5995,11 +6033,22 @@ function MediaPreview({return () => {cancelled = true;};- }, [variant, thumbUri, intrinsicSize, media.url]);+ }, [variant, localUri, thumbUri, intrinsicSize, media.url]);++ if (localUri) {+ return (+ <MessageContentOpenButton presentationOnly={presentationOnly}+ accessibilityLabel={`${preview.actionLabel} ${preview.title}`} onPress={onOpen}+ style={styles.attachmentImageWrap} testID="message.mediaPreviewButton">+ <PendingAttachmentImage key={localPreview?.uri ?? localUri} layout={layout}+ uri={localUri} sourceUri={localPreview?.uri ?? localUri}+ onSize={setIntrinsicSize}+ onError={() => setFailedLocalUris((failed) => failed.includes(localUri) ? failed : [...failed, localUri])} />+ </MessageContentOpenButton>+ );+ }- if (variant === 'attachment'- && (phase.kind === 'direct' || phase.kind === 'resolving' || phase.kind === 'resolved'- || (phase.kind === 'fallback' && (phase.reason === 'error' || phase.reason === 'unsupported-mime')))) {+ if (variant === 'attachment' && media.kind === 'image') {const displaySize = attachmentImageDisplaySize(intrinsicSize,layout.attachmentImageMaxWidth,diff --git a/apps/mobile/src/session/PendingSendBubble.tsx b/apps/mobile/src/session/PendingSendBubble.tsxindex bc5eb30c77..d94df86f90 100644--- a/apps/mobile/src/session/PendingSendBubble.tsx+++ b/apps/mobile/src/session/PendingSendBubble.tsx@@ -82,15 +82,17 @@ export interface PendingSendBubbleActions {function useThumbCellUri(thumb: MobileOutboxThumb,resolveRemoteMedia?: ResolveRemoteMediaFn,+ failedUris: readonly string[] = [],): string | null {// 「这一格现在指的是哪张图」。排队消息被编辑、同一附件下标换成另一张图时,ThumbCell 的// key(clientId-file-index)不变、hook 实例被复用 —— 所有缓存都必须绑定这个身份,否则旧图// 会一直压住新图直到整行卸载,编辑后的气泡显示的是已被移除的附件(review P1)。- const identity = `${thumb.uri ?? ''}|${thumb.ossRef ?? ''}`;- const durableUri = thumb.ossRef ? getSentAttachmentThumbUri(thumb.ossRef) : null;- const localUri = durableUri ?? thumb.uri ?? null;+ const identity = thumb.uri ?? thumb.ossRef ?? thumb.key;+ const previewRef = thumb.previewRef ?? thumb.ossRef;+ const durableUri = previewRef ? getSentAttachmentThumbUri(previewRef) : null;+ const localUri = [durableUri, thumb.uri].find((uri) => uri && !failedUris.includes(uri)) ?? null;const [remoteState, setRemoteState] = useState<{ uri: string; identity: string } | null>(null);- const remoteUri = remoteState?.identity === identity ? remoteState.uri : null;+ const remoteUri = remoteState?.identity === identity && !failedUris.includes(remoteState.uri) ? remoteState.uri : null;const remoteCandidate = localUri ? null : thumb.ossRef;useEffect(() => {if (!remoteCandidate || !resolveRemoteMedia || !isDesktopLocalMediaUrl(remoteCandidate)) {@@ -119,13 +121,13 @@ function useThumbCellUri(// 等 store hydrate、远端取件更晚),换 uri 会让 Image 重新加载、中间露出底色(闪白)。// 锁同样绑身份:身份变了就解锁,重新按新图取。const shownRef = useRef<{ uri: string; identity: string } | null>(null);- const shown = shownRef.current?.identity === identity ? shownRef.current.uri : null;+ const shown = shownRef.current?.identity === identity && !failedUris.includes(shownRef.current.uri) ? shownRef.current.uri : null;// 写 ref 放 layout effect(render 阶段不碰 ref:Concurrent 下被丢弃的 render 会污染它)。useLayoutEffect(() => {- if (candidate && shownRef.current?.identity !== identity) {+ if (candidate && !shown) {shownRef.current = { uri: candidate, identity };}- }, [candidate, identity]);+ }, [candidate, identity, shown]);return shown ?? candidate;}@@ -134,16 +136,19 @@ function ThumbCell({resolveRemoteMedia,renderImage,}: {- renderImage: (uri: string | null) => ReactNode;+ renderImage: (uri: string | null, sourceUri: string | null, onError: () => void) => ReactNode;thumb: MobileOutboxThumb;resolveRemoteMedia?: ResolveRemoteMediaFn;}) {const styles = useThemedStyles(makeStyles);const { colors } = useTheme();- const uri = useThumbCellUri(thumb, resolveRemoteMedia);+ const [failedUris, setFailedUris] = useState<readonly string[]>([]);+ const uri = useThumbCellUri(thumb, resolveRemoteMedia, failedUris);return (<View style={styles.thumbCell}>- {renderImage(uri)}+ {renderImage(uri, thumb.uri, () => {+ if (uri) setFailedUris((failed) => failed.includes(uri) ? failed : [...failed, uri]);+ })}{thumb.uploading ? (<View style={styles.thumbUploadingOverlay}><ActivityIndicator color={colors.ctaText} size="small" />@@ -159,7 +164,7 @@ function AttachmentThumbStrip({renderImage,gap,}: {- renderImage: (uri: string | null) => ReactNode;+ renderImage: (uri: string | null, sourceUri: string | null, onError: () => void) => ReactNode;gap: number;thumbs: readonly MobileOutboxThumb[];resolveRemoteMedia?: ResolveRemoteMediaFn;@@ -185,7 +190,7 @@ export function PendingSendBubble({renderFile,screenWidth,}: {- renderImage: (uri: string | null) => ReactNode;+ renderImage: (uri: string | null, sourceUri: string | null, onError: () => void) => ReactNode;renderText: (text: string, index: number) => ReactNode;renderFile: (name: string, index: number) => ReactNode;screenWidth?: number;diff --git a/apps/mobile/src/session/messageNormalize.ts b/apps/mobile/src/session/messageNormalize.tsindex 82ae07cbc2..d9f347f536 100644--- a/apps/mobile/src/session/messageNormalize.ts+++ b/apps/mobile/src/session/messageNormalize.ts@@ -151,6 +151,7 @@ export interface NormalizedAttachment {uri?: string;path?: string;mimeType?: string;+ sha256?: string;previewable: boolean;}@@ -603,6 +604,7 @@ function readImageAttachments(value: unknown): NormalizedAttachment[] {const base64 = readString(record.base64);const mimeType = readString(record.mimeType) ?? readString(record.type) ?? 'image/png';const name = readString(record.originalName) ?? readString(record.name) ?? `image-${index + 1}`;+ const sha256 = readString(record.sha256);const uri = url ?? (base64 ? `data:${mimeType};base64,${base64}` : undefined);if (!uri) return [];return [{@@ -610,6 +612,7 @@ function readImageAttachments(value: unknown): NormalizedAttachment[] {name,uri,mimeType,+ ...(sha256 ? { sha256 } : {}),previewable: isPreviewableUri(uri),}];});diff --git a/apps/mobile/src/session/pendingSendItems.ts b/apps/mobile/src/session/pendingSendItems.tsindex 4ee48aa836..dba595d97b 100644--- a/apps/mobile/src/session/pendingSendItems.ts+++ b/apps/mobile/src/session/pendingSendItems.ts@@ -27,6 +27,7 @@ import {type SentInlineToken,} from '@/session/sentMessageAtoms';import type { QueuedRemoteMessage } from '@/session/types';+import type { GetSentMessageImagePreview } from '@/session/sentMessageImagePreviews';export type MobilePendingSendPhase =/** 已确认入队,等被控端派发。 */@@ -103,6 +104,21 @@ export function pendingSendItemKey(clientId: string): string {return `message-${clientId}`;}+/**+ * History and queue snapshots can arrive independently. Deduplicate against the+ * rows actually being rendered, even when the queue's hidden-id snapshot is stale.+ * Duplicate keys reserve two list positions while mounting only one bubble.+ */+export function appendPendingSendItems<T extends { key: string }>(+ rendered: readonly T[],+ pending: readonly MobilePendingSendItem[],+): readonly (T | MobilePendingSendItem)[] {+ if (pending.length === 0) return rendered;+ const renderedKeys = new Set(rendered.map((item) => item.key));+ const remaining = pending.filter((item) => !renderedKeys.has(item.key));+ return remaining.length === 0 ? rendered : [...rendered, ...remaining];+}+/*** 气泡显示文本:合成 UI 指令行(桌面「失败后继续」等隐藏 prompt)用遮蔽标签替代原文* —— 裸英文指令不能给用户看(对齐桌面 PendingQueuePanel 的 i18n 遮蔽标签)。@@ -152,6 +168,7 @@ function buildPendingSentInlineTokens(input: {function queuedAttachmentThumbs(item: Pick<QueuedRemoteMessage, 'clientId' | 'files'>,previewByOssRef?: ReadonlyMap<string, string>,+ getImagePreview?: GetSentMessageImagePreview,): { thumbs: MobileOutboxThumb[]; fileCount: number } {const thumbs: MobileOutboxThumb[] = [];let fileCount = 0;@@ -161,14 +178,16 @@ function queuedAttachmentThumbs(return;}const ossRef = file.url ?? file.path;+ const preview = getImagePreview?.(item.clientId, thumbs.length, file.name, file.id);thumbs.push({- key: `${item.clientId}-file-${index}`,+ key: `${item.clientId}-slot-${index}`,// 发送时刻抓下的本地预览优先:sentAttachmentThumbStore 那条兜底链要等「上传落定 →// 拷进自有目录 → AsyncStorage hydrate」全部完成才查得到,期间 getSentAttachmentThumbUri// 一律返回 null,排队气泡只能画空占位格(实测:兜底文件已生成,气泡仍是空方块)。// 乐观语义下图必须从第一帧就在,所以直接用手边的 file:// 预览,store 只作为// 「重开会话 / 预览已失效」时的后备。- uri: (ossRef && previewByOssRef?.get(ossRef)) || null,+ uri: preview?.uri ?? ((ossRef && previewByOssRef?.get(ossRef)) || null),+ ...(preview ? { previewRef: preview.sourceRef } : {}),ossRef,uploading: false,});@@ -198,6 +217,7 @@ export interface BuildPendingSendItemsInput {* 排队气泡的图靠它即时显示,不等 sentAttachmentThumbStore 的拷贝 + hydrate 链。*/previewByOssRef?: ReadonlyMap<string, string>;+ getImagePreview?: GetSentMessageImagePreview;}/**@@ -213,7 +233,7 @@ export function buildPendingSendItems(input: BuildPendingSendItemsInput): Mobileconst pushQueued = (item: QueuedRemoteMessage, phase: MobilePendingSendPhase, queueIndex: number | null) => {if (seen.has(item.clientId) || input.hiddenClientIds.has(item.clientId)) return;seen.add(item.clientId);- const attachments = queuedAttachmentThumbs(item, input.previewByOssRef);+ const attachments = queuedAttachmentThumbs(item, input.previewByOssRef, input.getImagePreview);const presentation = queueIndex === null? null: input.presentationByClientId.get(item.clientId) ?? null;diff --git a/apps/mobile/src/session/sentMessageImagePreviews.ts b/apps/mobile/src/session/sentMessageImagePreviews.tsnew file mode 100644index 0000000000..c41c65310a--- /dev/null+++ b/apps/mobile/src/session/sentMessageImagePreviews.ts@@ -0,0 +1,56 @@+import type { RemoteSerializedAttachment } from '@/session/types';++export interface SentMessageImagePreview {+ attachmentId: string;+ name: string;+ sourceRef: string;+ sha256?: string;+ uri: string;+}++export type SentMessageImagePreviews = Map<string, readonly (SentMessageImagePreview | null)[]>;+export type GetSentMessageImagePreview = (+ clientId: string, imageIndex: number, name: string, attachmentId?: string, sha256?: string, sourceRef?: string,+) => SentMessageImagePreview | undefined;++const messageKey = (sessionId: string, clientId: string) => JSON.stringify([sessionId, clientId]);++/** Presentation-only snapshot. Host materialization changes URLs, but preserves message/image order. */+export function rememberSentMessageImagePreviews(+ previews: SentMessageImagePreviews,+ sessionId: string,+ clientId: string,+ attachments: readonly RemoteSerializedAttachment[],+ previewOf: (attachment: RemoteSerializedAttachment) => string | null | undefined,+): void {+ const key = messageKey(sessionId, clientId);+ const previous = previews.get(key);+ const images = attachments.filter((attachment) => attachment.category === 'image').map((attachment) => {+ const uri = previewOf(attachment);+ return uri ? { attachmentId: attachment.id, name: attachment.originalName ?? attachment.name,+ sourceRef: attachment.url ?? attachment.path, sha256: attachment.sha256, uri }+ : previous?.find((entry) => entry?.attachmentId === attachment.id) ?? null;+ });+ // Replace the complete snapshot on edit, including removed images and missing previews.+ previews.delete(key);+ previews.set(key, images);+ while (previews.size > 64) previews.delete(previews.keys().next().value!);+}++export function getSentMessageImagePreview(+ previews: SentMessageImagePreviews,+ sessionId: string,+ clientId: string,+ imageIndex: number,+ name: string,+ attachmentId?: string,+ sha256?: string,+ sourceRef?: string,+): SentMessageImagePreview | undefined {+ const preview = previews.get(messageKey(sessionId, clientId))?.[imageIndex];+ if (!preview || (attachmentId ? preview.attachmentId !== attachmentId : preview.name !== name)) return undefined;+ // Formal content omits file IDs. Prove the pixels still match before reusing a local image;+ // a same-name queue edit on another device must never resurrect the old preview.+ if (!attachmentId && !(sha256 && preview.sha256 === sha256) && preview.sourceRef !== sourceRef) return undefined;+ return preview;+}diff --git a/apps/mobile/src/session/sessionOutbox.ts b/apps/mobile/src/session/sessionOutbox.tsindex 4d74558f19..705aa86a13 100644--- a/apps/mobile/src/session/sessionOutbox.ts+++ b/apps/mobile/src/session/sessionOutbox.ts@@ -152,6 +152,8 @@ export interface MobileOutboxThumb {uri: string | null;/** 已落定槽位的 OSS 引用(sentAttachmentThumbStore 兜底查询键);未落定为 null。 */ossRef: string | null;+ /** Original upload ref, retained when the host materializes ossRef. */+ previewRef?: string;/** 对应上传任务尚未落定(渲染转圈遮罩)。 */uploading: boolean;}