Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(mobile): 支持 SVG 图片预览和消息缩略图 (#4820)

Dash5506e4bf229f
diff --git a/apps/mobile/app/files/preview/[sessionId].tsx b/apps/mobile/app/files/preview/[sessionId].tsx
index 5b55a94cee..7487828120 100644
--- a/apps/mobile/app/files/preview/[sessionId].tsx
+++ b/apps/mobile/app/files/preview/[sessionId].tsx
@@ -20,6 +20,7 @@
* (fetchRemoteAbsFileToUrl);无同目录翻页、无缩略图(直接取原图)。
*/
import * as Clipboard from 'expo-clipboard';
+import { Image } from 'expo-image';
import { useIsFocused, useLocalSearchParams, useRouter } from 'expo-router';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -28,7 +29,6 @@ import {
ActivityIndicator,
Alert,
FlatList,
- Image,
Pressable,
StyleSheet,
View,
@@ -1266,7 +1266,7 @@ function ImagePreviewPage({
testID="filePreview.imagePage"
>
{displayUri ? (
- <Image resizeMode="contain" source={{ uri: displayUri }} style={styles.imageFull} />
+ <Image contentFit="contain" recyclingKey={displayUri} source={{ uri: displayUri }} style={styles.imageFull} />
) : failure ? (
<View style={styles.imageStateWrap} testID="filePreview.imageError">
<GenericGlyph name={item.name} />
diff --git a/apps/mobile/src/__tests__/imageLightboxInteraction.test.tsx b/apps/mobile/src/__tests__/imageLightboxInteraction.test.tsx
index eb5762494d..a1dca5d9cc 100644
--- a/apps/mobile/src/__tests__/imageLightboxInteraction.test.tsx
+++ b/apps/mobile/src/__tests__/imageLightboxInteraction.test.tsx
@@ -2,6 +2,8 @@
import { act, type ReactNode } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { buildAttachmentPayload } from '@/session/messagePayload';
+import { svgAttachmentForDisplay } from '@/session/messageAttachments';
import {
ImageLightbox,
type ImageLightboxProps,
@@ -28,7 +30,8 @@ const runtime = vi.hoisted(() => ({
vi.mock("expo-router", () => ({
useNavigation: () => ({ setOptions: () => undefined }),
}));
-vi.mock("react-i18next", () => ({
+vi.mock("react-i18next", async (importOriginal) => ({
+ ...await importOriginal<typeof import('react-i18next')>(),
useTranslation: () => ({ t: (key: string) => key }),
}));
vi.mock("@/session/remoteMedia", () => ({
@@ -81,6 +84,9 @@ vi.mock("react-native", async () => {
vi.mock("@/components/AppText", async () => ({
Text: (await import("react-native")).Text,
}));
+vi.mock("expo-image", async () => ({
+ Image: (await import("react-native")).Image,
+}));
vi.mock("@/platform/gestureHandler", async () => {
const { View } = await import("react-native");
const make = (kind: string) => {
@@ -141,7 +147,7 @@ vi.mock("react-native-reanimated", async () => {
done?: Animation["done"],
) => ({ target, done });
return {
- default: { View: native.View, Image: native.Image },
+ default: { View: native.View, createAnimatedComponent: (component: unknown) => component },
useSharedValue: (initial: number) => {
const ref = useRef<Value | null>(null);
if (!ref.current) {
@@ -214,6 +220,50 @@ function mount(overrides: Partial<ImageLightboxProps> = {}) {
render();
return { props, render };
}
+
+describe('SVG images in the shared lightbox', () => {
+ it.each([
+ { name: 'diagram', mimeType: 'image/svg+xml; charset=utf-8' },
+ { name: 'diagram.svg' },
+ ])('keeps opaque SVG attachment URLs unannotatable: %j', async (metadata) => {
+ const url = 'https://example.invalid/download?id=1';
+ const attachment = svgAttachmentForDisplay({
+ kind: 'file', path: url, previewable: false, ...metadata,
+ });
+ const payload = buildAttachmentPayload(attachment);
+ if (payload.kind !== 'media') throw new Error('Expected an image payload');
+ const onShareImage = vi.fn();
+ mount({
+ images: [{ key: 'svg', title: attachment.name, url, payload }], initialUrl: url,
+ annotation: { submitLabel: 'Send', onSubmit: vi.fn() }, onShareImage,
+ });
+ expect(runtime.nodes.has('message.imageLightboxAnnotateButton')).toBe(false);
+ await act(async () => runtime.nodes.get('message.imageLightboxShareButton').onPress());
+ expect(onShareImage).toHaveBeenCalledWith(payload.media, url, 'image/svg+xml', undefined);
+ });
+
+ it.each([
+ 'https://example.invalid/diagram.svg?version=2',
+ 'data:image/svg+xml;base64,PHN2Zy8+',
+ 'file:///cache/diagram.svg',
+ ])('loads %s with image gestures and without raster annotation', (url) => {
+ const image = {
+ key: 'svg', title: 'Diagram', url,
+ payload: { kind: 'media', media: { kind: 'image', url, previewable: true } },
+ } as ImageLightboxProps['images'][number];
+ mount({ images: [image], initialUrl: url, annotation: { submitLabel: 'Send', onSubmit: vi.fn() } });
+ const props = runtime.nodes.get('Image');
+ expect(props.source.uri).toBe(url);
+ expect(props.contentFit).toBe('contain');
+ act(() => props.onLoad({ source: { width: 1600, height: 900 } }));
+ doubleTapAtCorner();
+ finishAnimations();
+ expect(transform().scale).toBe(2.5);
+ expect(transform().y).toBe(0);
+ expect(runtime.nodes.has('message.imageLightboxAnnotateButton')).toBe(false);
+ });
+});
+
function gestures(node = runtime.gesture!): GestureNode[] {
return node.children ? node.children.flatMap(gestures) : [node];
}
@@ -319,7 +369,7 @@ describe("image viewer gesture lifecycle", () => {
act(() =>
runtime.nodes
.get("Image")
- .onLoad({ nativeEvent: { source: { width: 1600, height: 900 } } }),
+ .onLoad({ source: { width: 1600, height: 900 } }),
);
finishAnimations();
expect(transform().y).toBe(0);
@@ -348,7 +398,7 @@ describe("image viewer actions", () => {
it('reclamps zoom after rotation and still returns to the centered image', () => {
const harness = mount();
- act(() => runtime.nodes.get('Image').onLoad({ nativeEvent: { source: { width: 400, height: 800 } } }));
+ act(() => runtime.nodes.get('Image').onLoad({ source: { width: 400, height: 800 } }));
doubleTapAtCorner(); finishAnimations();
runtime.dimensions = { width: 800, height: 400 };
runtime.insets = { top: 0, bottom: 20, left: 59, right: 0 };
@@ -375,7 +425,7 @@ describe("image viewer actions", () => {
let complete!: () => void;
const onSubmit = vi.fn(() => new Promise<void>((resolve) => { complete = resolve; }));
mount({ annotation: { submitLabel: 'Send', onSubmit } });
- act(() => runtime.nodes.get('Image').onLoad({ nativeEvent: { source: { width: 400, height: 800 } } }));
+ act(() => runtime.nodes.get('Image').onLoad({ source: { width: 400, height: 800 } }));
press('message.imageLightboxAnnotateButton');
const draw = gestures().find(g => g.kind === 'Pan' && g.options.minDistance === 0)!;
fire(draw, 'onStart', { x: 100, y: 200 });
@@ -393,7 +443,7 @@ describe("image viewer actions", () => {
let reject!: (error: Error) => void;
const onSubmit = vi.fn(() => new Promise<void>((_resolve, fail) => { reject = fail; }));
mount({ annotation: { submitLabel: 'Send', onSubmit } });
- act(() => runtime.nodes.get('Image').onLoad({ nativeEvent: { source: { width: 400, height: 800 } } }));
+ act(() => runtime.nodes.get('Image').onLoad({ source: { width: 400, height: 800 } }));
press('message.imageLightboxAnnotateButton');
const draw = () => gestures().find(g => g.kind === 'Pan' && g.options.minDistance === 0)!;
fire(draw(), 'onStart', { x: 100, y: 200 });
@@ -433,7 +483,7 @@ describe("image viewer actions", () => {
act(() =>
runtime.nodes
.get("Image")
- .onLoad({ nativeEvent: { source: { width: 400, height: 800 } } }),
+ .onLoad({ source: { width: 400, height: 800 } }),
);
expect(props.onClose).not.toHaveBeenCalled();
expect(runtime.nodes.get("Image").source.uri).toBe(props.initialUrl);
diff --git a/apps/mobile/src/__tests__/messageAttachments.test.ts b/apps/mobile/src/__tests__/messageAttachments.test.ts
index b0ec34c17e..2c8e06f686 100644
--- a/apps/mobile/src/__tests__/messageAttachments.test.ts
+++ b/apps/mobile/src/__tests__/messageAttachments.test.ts
@@ -1,8 +1,37 @@
import { describe, expect, it } from 'vitest';
-import { partitionMessageAttachments } from '@/session/messageAttachments';
+import { partitionMessageAttachments, svgAttachmentForDisplay } from '@/session/messageAttachments';
import type { NormalizedAttachment } from '@/session/messageNormalize';
describe('partitionMessageAttachments', () => {
+ it('displays persisted SVG files as images using the existing SSH media route', () => {
+ const attachment: NormalizedAttachment = {
+ kind: 'file', name: 'diagram.SVG', path: '/repo/diagram.SVG', previewable: false,
+ };
+ const display = svgAttachmentForDisplay(attachment, '/repo', 'm1', 'ssh-host', 'session-1');
+ expect(display).toMatchObject({ kind: 'image', previewable: false, path: attachment.path });
+ const url = new URL(display.uri!);
+ expect(url.protocol).toBe('xdt-file:');
+ expect(Object.fromEntries(url.searchParams)).toEqual({
+ path: attachment.path, v: 'm1', workdir: '/repo', remoteHostId: 'ssh-host', sessionId: 'session-1',
+ });
+ expect(partitionMessageAttachments([display]).imageAttachments).toEqual([display]);
+ expect(attachment.kind).toBe('file');
+ expect(svgAttachmentForDisplay(attachment, '/repo', 'm1', 'ssh-host')).toBe(attachment);
+ expect(svgAttachmentForDisplay(attachment)).toBe(attachment);
+ });
+
+ it('recognizes SVG MIME without changing other files or trusting unsupported URLs', () => {
+ const svg: NormalizedAttachment = {
+ kind: 'file', name: 'diagram', path: 'https://example.com/download?id=1',
+ mimeType: 'image/svg+xml; charset=utf-8', previewable: false,
+ };
+ expect(svgAttachmentForDisplay(svg)).toMatchObject({ kind: 'image', uri: svg.path, previewable: true });
+ const unsupported = { ...svg, path: 'javascript:alert(1)' };
+ expect(svgAttachmentForDisplay(unsupported, '/repo')).toBe(unsupported);
+ const text = { ...svg, name: 'diagram.svg.txt', mimeType: 'text/plain' };
+ expect(svgAttachmentForDisplay(text)).toBe(text);
+ });
+
it('separates images from files while preserving order within each presentation group', () => {
const attachments: NormalizedAttachment[] = [
{ kind: 'file', name: 'brief.pdf', path: '/repo/brief.pdf', previewable: false },
diff --git a/apps/mobile/src/__tests__/messageGallery.test.ts b/apps/mobile/src/__tests__/messageGallery.test.ts
index a5c4d98217..a0a099f261 100644
--- a/apps/mobile/src/__tests__/messageGallery.test.ts
+++ b/apps/mobile/src/__tests__/messageGallery.test.ts
@@ -25,6 +25,17 @@ function messageItem(key: string, message: Partial<MobileMessageRenderItem & { m
}
describe('message gallery', () => {
+ it('uses the same SVG file attachment URL as the thumbnail and includes it in the image gallery', () => {
+ const gallery = collectMobileMessageGalleryImages([
+ messageItem('m-svg', { attachments: [
+ { kind: 'file', name: 'diagram.svg', path: '/repo/diagram.svg', previewable: false },
+ ] }),
+ ], '/repo', 'ssh-host', 'session-1');
+ expect(gallery).toHaveLength(1);
+ expect(gallery[0].payload.media).toMatchObject({ kind: 'image', previewable: false });
+ expect(gallery[0].url).toBe('xdt-file://open?path=%2Frepo%2Fdiagram.svg&sessionId=session-1&remoteHostId=ssh-host&workdir=%2Frepo&v=m-svg');
+ });
+
it('resolves relative markdown images against the remote session workdir', () => {
const gallery = collectMobileMessageGalleryImages([
messageItem('m-local', { body: '![构建图](artifacts/build result.png)' }),
diff --git a/apps/mobile/src/__tests__/messageImageHandoff.test.tsx b/apps/mobile/src/__tests__/messageImageHandoff.test.tsx
index bd35cc3338..a2847358f8 100644
--- a/apps/mobile/src/__tests__/messageImageHandoff.test.tsx
+++ b/apps/mobile/src/__tests__/messageImageHandoff.test.tsx
@@ -30,7 +30,7 @@ function fixture() {
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)} />;
+ return <div data-image={imageSource.uri} data-decoder="expo" style={flatten(style)} />;
};
const Image = Object.assign(ExpoImage, { getSize: vi.fn() });
const bindings = { React, View, Text: View, ExpoImage, Image,
@@ -60,6 +60,21 @@ function fixture() {
}
describe('image frame continuity', () => {
+ it('uses the SVG-capable decoder for thumbnails, measures from load and opens the existing viewer', () => {
+ const f = fixture();
+ const uri = 'https://example.com/diagram.svg';
+ const onOpen = vi.fn();
+ f.render(<f.MediaPreview layout={f.layout} label="diagram.svg" variant="attachment"
+ media={{ kind: 'image', url: uri, previewable: true }} onOpen={onOpen} />);
+ expect(f.host.querySelector('[data-image]')?.getAttribute('data-decoder')).toBe('expo');
+ act(() => f.handlers.get(uri)!.onLoad({ source: { width: 800, height: 400 } }));
+ const size = attachmentImageDisplaySize({ width: 800, height: 400 }, f.layout.attachmentImageMaxWidth, f.layout.attachmentImageMaxHeight);
+ expect(f.frame()).toEqual([`${size.width}px`, `${size.height}px`]);
+ expect(f.Image.getSize).not.toHaveBeenCalled();
+ act(() => (f.host.querySelector('[data-testid="message.mediaPreviewButton"]') as HTMLElement).click());
+ expect(onOpen).toHaveBeenCalledOnce();
+ });
+
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>;
diff --git a/apps/mobile/src/session/ImageLightbox.tsx b/apps/mobile/src/session/ImageLightbox.tsx
index 2cebe6d42c..c5891e7cad 100644
--- a/apps/mobile/src/session/ImageLightbox.tsx
+++ b/apps/mobile/src/session/ImageLightbox.tsx
@@ -14,6 +14,7 @@
* lightbox 是常黑沉浸语境,黑白系颜色为刻意豁免(对齐桌面 docs/design-rules/cindy-design-system.md overlay/lightbox 语义豁免),不走主题 token。
*/
import { useNavigation } from 'expo-router';
+import { Image } from 'expo-image';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
@@ -85,6 +86,10 @@ import {
type AnnotationStroke,
} from '@/session/imageAnnotationModel';
+// Use the existing SVG-capable decoder for both the preview and full image,
+// retaining the lightbox's native gesture transforms.
+const AnimatedImage = Animated.createAnimatedComponent(Image);
+
// 缩略图垫底**不**挂在取件态里:它要跨过 loading → ready 的边界继续垫住原图
// 下载那一段(见 lightboxImageLayers),挂进 loading 分支会在取件完成的瞬间
// 结构性丢失,把第二段空档裸露成纯黑。垫底地址单独存 previewMap。
@@ -417,7 +422,8 @@ export const ImageLightbox = memo(function ImageLightbox({
const handleShare = useCallback(() => {
if (!activeImage || !activeUri || !onShareImage || sharingRef.current || submittingRef.current) return;
const state = resolveMap[activeImage.url];
- const mimeType = state?.status === 'ready' ? state.media.mimeType : undefined;
+ const mimeType = (state?.status === 'ready' ? state.media.mimeType : undefined)
+ ?? activeImage.payload.media.mimeType;
const sizeBytes = state?.status === 'ready' ? state.media.size : undefined;
sharingRef.current = true;
setSharing(true);
@@ -434,17 +440,19 @@ export const ImageLightbox = memo(function ImageLightbox({
});
}, [activeImage, activeUri, onShareImage, resolveMap]);
- // 活跃页 mime(取件结果优先,兜底 uri 后缀):gif / svg 不开放画笔(烧录只留首帧)。
+ // 活跃页 MIME:取件结果优先,保留附件已知类型,最后兜底 URI 后缀。
const activeResolveState = activeImage ? resolveMap[activeImage.url] : undefined;
- const activeMimeType = activeResolveState?.status === 'ready'
+ const activeMimeType = ((activeResolveState?.status === 'ready'
? activeResolveState.media.mimeType
- : undefined;
+ : undefined) ?? activeImage?.payload.media.mimeType)?.split(';', 1)[0].trim().toLowerCase();
const activeLooksGif = !!activeUri && /\.gif(?:[?#]|$)/i.test(activeUri.split('?')[0] ?? activeUri);
+ const activeLooksSvg = !!activeUri && (/\.svg(?:[?#]|$)/i.test(activeUri) || /^data:image\/svg\+xml[;,]/i.test(activeUri));
const annotateVisible = !!annotation
&& !!activeImage
&& !!activeUri
&& canAnnotateImageMime(activeMimeType)
- && !activeLooksGif;
+ && !activeLooksGif
+ && !activeLooksSvg;
// 独立直发(发送到对话):不要求可标注——gif 等不可画的图同样能转发。
const directSubmitVisible = !!annotation?.allowDirectSubmit && !!activeImage && !!activeUri;
@@ -1299,19 +1307,20 @@ const LightboxPage = memo(function LightboxPage({
绝对定位而非参与 flex:与原图同为 flex 子节点会被 Yoga 各分一半高度。
*/}
{layers.showPreview && previewUri ? (
- <Animated.Image
+ <AnimatedImage
// 垫底图画不出来时必须撤掉并让 spinner 回来,不能停在纯黑(见
// failedPreviewUri)。乐观先渲染而不是等它 onLoad:本地文件解码只要
// 一两帧,为它先挂一帧 spinner 反而每次打开都闪一下,与本次「让用户
// 感知不到」的目标相反。
onError={() => setFailedPreviewUri(previewUri)}
- resizeMode="contain"
+ contentFit="contain"
+ recyclingKey={previewUri}
source={{ uri: previewUri }}
style={[styles.pagePreviewLayer, imageStyle]}
testID="message.imageLightboxPreviewLayer"
/>
) : null}
- <Animated.Image
+ <AnimatedImage
// 两条失败路径都要接:可重取的图交父层做一次 forceRefresh 自愈(再失败
// 落父层 error 态给重试按钮);直连图在本页落失败态,提供原地重试。
onError={() => {
@@ -1322,12 +1331,13 @@ const LightboxPage = memo(function LightboxPage({
// 撤垫底的唯一依据:原图真的有像素了。早于此撤(例如取件一完成
// 就撤)就会把下载窗口裸露成黑屏,正是本次修复的起因。
setLoadedUri(uri);
- const source = event.nativeEvent?.source;
+ const source = event.source;
if (source && source.width > 0 && source.height > 0) {
onNaturalSize(image.key, { width: source.width, height: source.height });
}
}}
- resizeMode="contain"
+ contentFit="contain"
+ recyclingKey={uri}
source={{ uri }}
style={[styles.pageFill, imageStyle]}
/>
@@ -1429,10 +1439,11 @@ const LightboxPage = memo(function LightboxPage({
// 取件在途时垫列表缩略图(静态 contain,无缩放手势,点击仍由外层
// Pressable 单击关闭接管):首开不黑屏,原图到达切上面手势分支时
// 那边继续垫同一张图,两段之间不留空档。
- <Animated.Image
+ <AnimatedImage
// 同上:垫底失败要退回 spinner,不能让取件在途这段变成纯黑。
onError={() => setFailedPreviewUri(previewUri)}
- resizeMode="contain"
+ contentFit="contain"
+ recyclingKey={previewUri}
source={{ uri: previewUri }}
style={StyleSheet.absoluteFill}
testID="message.imageLightboxPreviewLayer"
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index 72cc327dc5..a259f8e732 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -46,7 +46,6 @@ import {
Alert,
Animated,
Easing,
- Image,
Linking,
Modal,
Platform,
@@ -150,7 +149,7 @@ import {
type MessagePayload,
type MessagePayloadPreview,
} from '@/session/messagePayload';
-import { partitionMessageAttachments } from '@/session/messageAttachments';
+import { partitionMessageAttachments, svgAttachmentForDisplay } from '@/session/messageAttachments';
import {
AUTOMATION_USER_MESSAGE_COLLAPSED_LINES,
AUTOMATION_USER_MESSAGE_VISUAL_LINE_THRESHOLD,
@@ -3268,6 +3267,7 @@ function MessageBubble({
<AttachmentStrip
align={isUser ? 'right' : 'left'}
attachments={item.message.attachments}
+ messageKey={item.message.key}
clientId={item.message.source.clientId ?? item.message.source.id}
getImagePreview={actions.getSentImagePreview}
layout={contentLayout}
@@ -5768,9 +5768,10 @@ function renderInline(
testID="message.markdownInlineImage"
>
<View style={size}>
- <Image
+ <ExpoImage
accessibilityLabel={inline.alt || i18n.t('message.renderer.imageFallbackTitle')}
- resizeMode="cover"
+ contentFit="cover"
+ recyclingKey={inline.url}
source={{ uri: inline.url }}
style={[styles.markdownInlineImage, size]}
/>
@@ -5832,6 +5833,7 @@ function MarkdownSessionLinkSpan({
function AttachmentStrip({
attachments,
+ messageKey,
clientId,
getImagePreview,
align,
@@ -5840,6 +5842,7 @@ function AttachmentStrip({
onResolveRemoteMedia,
}: {
attachments: readonly NormalizedAttachment[];
+ messageKey: string;
clientId?: string;
getImagePreview?: GetSentMessageImagePreview;
align: 'left' | 'right';
@@ -5851,7 +5854,10 @@ function AttachmentStrip({
// 订阅本地缩略兜底版本:hydrate / 新注册落盘后,已渲染的 cindy-oss-attach:// 气泡
// 自动从占位卡切到本地图(返回值不消费,订阅本身驱动重渲染)。
useSentAttachmentThumbsVersion();
- const { imageAttachments, fileAttachments } = partitionMessageAttachments(attachments);
+ const fileContext = useContext(ChatFilePathContext);
+ const { imageAttachments, fileAttachments } = partitionMessageAttachments(attachments.map((attachment) =>
+ svgAttachmentForDisplay(attachment, fileContext?.workdir, messageKey, fileContext?.remoteHostId, fileContext?.sessionId),
+ ));
const alignStyle = align === 'right' ? styles.attachmentStripRight : styles.attachmentStripLeft;
return (
@@ -5985,7 +5991,7 @@ function PluginResultCard({ callId, sessionId, excludedUrls, actions }: {
/**
* 附件图原图尺寸的模块级缓存(键 = 源 media.url,跨 presign 刷新稳定)。
* FlatList 虚拟化反复 unmount/remount MediaPreview,组件态存不住尺寸;
- * 上限兜底防长会话无界增长(整表清空即可,丢了只是多一次 getSize)。
+ * 上限兜底防长会话无界增长(整表清空即可,下次解码时重新记录)。
*/
const attachmentIntrinsicSizeCache = new Map<string, AttachmentImageIntrinsicSize>();
const ATTACHMENT_INTRINSIC_CACHE_MAX = 500;
@@ -6129,28 +6135,16 @@ function MediaPreview({
resolveThumbnail(true);
}, [resolveThumbnail]);
- // attachment 变体:异步量原图宽高并写入模块级缓存;失败置 -1 走 max 框回落帧,
- // 图仍照常渲染(不作为出图门控,见下)。已有尺寸(含缓存命中)不重复测量。
- useEffect(() => {
- if (variant !== 'attachment' || localUri || !thumbUri || intrinsicSize) return;
- let cancelled = false;
- Image.getSize(
- thumbUri,
- (width, height) => {
- if (attachmentIntrinsicSizeCache.size >= ATTACHMENT_INTRINSIC_CACHE_MAX) {
- attachmentIntrinsicSizeCache.clear();
- }
- attachmentIntrinsicSizeCache.set(media.url, { height, width });
- if (!cancelled) setIntrinsicSize({ height, width });
- },
- () => {
- if (!cancelled) setIntrinsicSize({ height: -1, width: -1 });
- },
- );
- return () => {
- cancelled = true;
- };
- }, [variant, localUri, thumbUri, intrinsicSize, media.url]);
+ // Measure with the same decoder that displays the image: RN getSize cannot
+ // decode SVG. Reuse the decoded dimensions without a second image request.
+ const handleImageLoad = useCallback(({ source: { width, height } }: { source: AttachmentImageIntrinsicSize }) => {
+ if (!(width > 0 && height > 0)) return;
+ if (attachmentIntrinsicSizeCache.size >= ATTACHMENT_INTRINSIC_CACHE_MAX) {
+ attachmentIntrinsicSizeCache.clear();
+ }
+ attachmentIntrinsicSizeCache.set(media.url, { width, height });
+ setIntrinsicSize({ width, height });
+ }, [media.url, setIntrinsicSize]);
if (localUri) {
return (
@@ -6189,13 +6183,12 @@ function MediaPreview({
<Text style={styles.mediaHint} numberOfLines={2}>{preview.detail}</Text>
</View>
) : thumbUri ? (
- <Image
- // 有 uri 立即渲染真图,不等 getSize(direct 图有立即可用的 URI,
- // 门控只会平白多一帧灰底占位;尺寸未知时先 max 框 contain letterbox,
- // getSize 返回后收敛到真实比例)。contain 而非 cover:帧比例与原图
- // 一致时两者等价;max 框帧时保证不裁内容。
- resizeMode="contain"
+ <ExpoImage
+ // 尺寸未知时先 contain 进最大框,解码后收敛到真实比例。
+ contentFit="contain"
+ recyclingKey={thumbUri}
source={{ uri: thumbUri }}
+ onLoad={handleImageLoad}
onError={phase.kind === 'resolved' ? handleImageError : undefined}
style={[styles.attachmentImage, displaySize]}
/>
@@ -6222,8 +6215,9 @@ function MediaPreview({
testID="message.mediaPreviewButton"
>
{uri ? (
- <Image
- resizeMode="cover"
+ <ExpoImage
+ contentFit="cover"
+ recyclingKey={uri}
source={{ uri }}
onError={phase.kind === 'resolved' ? handleImageError : undefined}
style={[styles.imagePreview, frameSize]}
diff --git a/apps/mobile/src/session/messageAttachments.ts b/apps/mobile/src/session/messageAttachments.ts
index f74847a0de..9e13962516 100644
--- a/apps/mobile/src/session/messageAttachments.ts
+++ b/apps/mobile/src/session/messageAttachments.ts
@@ -1,4 +1,24 @@
import type { NormalizedAttachment } from '@/session/messageNormalize';
+import { isMobileMarkdownImageDirectUrl, mobileMarkdownImageUrlForWorkdir } from '@/session/messageMarkdown';
+
+/** Persisted SVGs may live in files[], but their presentation is an image.
+ * Keep the original attachment untouched and use the existing remote/SSH resolver. */
+export function svgAttachmentForDisplay(
+ attachment: NormalizedAttachment,
+ workdir?: string,
+ messageKey?: string,
+ remoteHostId?: string,
+ sessionId?: string,
+): NormalizedAttachment {
+ if (attachment.kind !== 'file') return attachment;
+ const mime = attachment.mimeType?.split(';', 1)[0].trim().toLowerCase();
+ if (mime !== 'image/svg+xml' && !/\.svg$/i.test(attachment.name)) return attachment;
+ const source = attachment.path || attachment.uri;
+ if (!source) return attachment;
+ const uri = mobileMarkdownImageUrlForWorkdir(source, workdir, messageKey, remoteHostId, sessionId);
+ if (!uri) return attachment;
+ return { ...attachment, kind: 'image', mimeType: 'image/svg+xml', uri, previewable: isMobileMarkdownImageDirectUrl(uri) };
+}
export interface PartitionedMessageAttachments {
imageAttachments: NormalizedAttachment[];
diff --git a/apps/mobile/src/session/messageGallery.ts b/apps/mobile/src/session/messageGallery.ts
index 3e5a1e1028..07c9bf2d75 100644
--- a/apps/mobile/src/session/messageGallery.ts
+++ b/apps/mobile/src/session/messageGallery.ts
@@ -11,6 +11,7 @@ import type { MobileMessageRenderItem, MobileWorkChildItem } from '@/session/mes
import { logUnhandledRenderItem } from '@/session/assertNever';
import { applySentAttachmentThumbOverlay } from '@/session/sentAttachmentThumbStore';
import { i18n } from '@/i18n';
+import { svgAttachmentForDisplay } from '@/session/messageAttachments';
export interface MobileMessageGalleryImage {
key: string;
@@ -60,10 +61,11 @@ export function collectMobileMessageGalleryImages(
const visitMessage = (message: NormalizedRemoteMessage, keyPrefix: string, includeBodyImages: boolean) => {
message.attachments?.forEach((rawAttachment, index) => {
- if (rawAttachment.kind !== 'image' || !rawAttachment.uri) return;
+ const displayAttachment = svgAttachmentForDisplay(rawAttachment, workdir, message.key, remoteHostId, sessionId);
+ if (displayAttachment.kind !== 'image' || !displayAttachment.uri) return;
// 与 AttachmentStrip 同源 overlay(cindy-oss-attach:// → 本地缩略兜底):气泡
// 点开时 initialUrl 是替换后的 file://,图集条目必须同步替换才能匹配进翻页组。
- const attachment = applySentAttachmentThumbOverlay(rawAttachment);
+ const attachment = applySentAttachmentThumbOverlay(displayAttachment);
const payload = buildAttachmentPayload(attachment);
if (payload.kind === 'media') push(`${keyPrefix}:attachment:${index}`, attachment.name, payload);
});
diff --git a/apps/mobile/src/session/messageNormalize.ts b/apps/mobile/src/session/messageNormalize.ts
index d5ed3faf16..7bb2a40143 100644
--- a/apps/mobile/src/session/messageNormalize.ts
+++ b/apps/mobile/src/session/messageNormalize.ts
@@ -164,6 +164,7 @@ export interface NormalizedAttachment {
export interface NormalizedToolMedia {
kind: 'image' | 'video' | 'audio';
url: string;
+ mimeType?: string;
title?: string;
previewable: boolean;
actions?: NormalizedToolMediaActions;
diff --git a/apps/mobile/src/session/messagePayload.ts b/apps/mobile/src/session/messagePayload.ts
index 262e879870..6814cdd540 100644
--- a/apps/mobile/src/session/messagePayload.ts
+++ b/apps/mobile/src/session/messagePayload.ts
@@ -81,7 +81,11 @@ export function buildMediaPayload(
}
export function buildAttachmentPayload(attachment: NormalizedAttachment): MessagePayload {
- return buildSharedAttachmentPayload(attachment, mobilePresentationLocalizer);
+ const payload = buildSharedAttachmentPayload(attachment, mobilePresentationLocalizer);
+ if (payload.kind === 'media' && attachment.mimeType) {
+ return { ...payload, media: { ...payload.media, mimeType: attachment.mimeType } };
+ }
+ return payload;
}
export function buildFilePayload(title: string, sourcePath: string): Extract<MessagePayload, { kind: 'file' }> {
diff --git a/packages/maker-shared/src/__tests__/fileBrowserGrid.test.ts b/packages/maker-shared/src/__tests__/fileBrowserGrid.test.ts
index 39a990a17a..8260d7fed3 100644
--- a/packages/maker-shared/src/__tests__/fileBrowserGrid.test.ts
+++ b/packages/maker-shared/src/__tests__/fileBrowserGrid.test.ts
@@ -133,6 +133,9 @@ describe('parentRelPath / joinRelPath', () => {
describe('fileThumbKind', () => {
it('图片/文本/其它分派', () => {
expect(fileThumbKind('a.PNG')).toBe('image');
+ expect(fileThumbKind('diagram.SVG')).toBe('image');
+ expect(fileThumbKind('diagram.drawio.svg')).toBe('image');
+ expect(fileThumbKind('diagram.svg.txt')).toBe('doc');
expect(fileThumbKind('b.ts')).toBe('doc');
expect(fileThumbKind('noext')).toBe('generic');
expect(fileThumbKind('c.db')).toBe('generic');
diff --git a/packages/maker-shared/src/fileBrowserGrid.ts b/packages/maker-shared/src/fileBrowserGrid.ts
index 4da6dfe779..8d1a8501d6 100644
--- a/packages/maker-shared/src/fileBrowserGrid.ts
+++ b/packages/maker-shared/src/fileBrowserGrid.ts
@@ -51,7 +51,7 @@ export interface FileBrowserNameMatch {
relPath: string;
}
-const IMAGE_THUMB_EXT = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'heic', 'heif', 'avif']);
+const IMAGE_THUMB_EXT = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'heic', 'heif', 'avif', 'svg']);
/** 防御性归一化 remote-op listDir 的返回(跨版本被控端可能缺字段)。 */
export function normalizeRemoteOpDirEntries(value: unknown): FileBrowserRemoteOpEntry[] {