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): 修复群聊图片脱离列表上下文导致的崩溃

zqchris40df5cc0edb7
diff --git a/apps/mobile/src/__tests__/BotGroupMessageAttachments.test.tsx b/apps/mobile/src/__tests__/BotGroupMessageAttachments.test.tsx
new file mode 100644
index 0000000000..2721468a73
--- /dev/null
+++ b/apps/mobile/src/__tests__/BotGroupMessageAttachments.test.tsx
@@ -0,0 +1,142 @@
+// @vitest-environment jsdom
+import { act, createElement, useState } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { ResolveRemoteMediaFn } from '@/session/remoteMedia';
+
+// Keep the real group attachment, AttachmentStrip, MediaPreview and LegendList hooks.
+// Only native surfaces and unrelated viewers are replaced for Node rendering.
+const imageEvents = vi.hoisted(() => new Map<string, { onLoad: (event: unknown) => void }>());
+vi.mock('react-native', async () => {
+ const React = await import('react');
+ const view = ({ children, testID, accessibilityLabel, onPress }: any) => React.createElement('div', { 'data-testid': testID, 'aria-label': accessibilityLabel, onClick: onPress }, children);
+ class Value { constructor(public value: number) {} interpolate() { return 0; } setValue() {} stopAnimation() {} }
+ return {
+ View: view, Text: view, Pressable: view, ScrollView: view, Modal: () => null,
+ Image: Object.assign(view, { getSize() {} }), ActivityIndicator: view,
+ Animated: { Value, View: view, Text: view, createAnimatedComponent: (c: any) => c,
+ timing: () => ({ start() {}, stop() {} }), loop: () => ({ start() {}, stop() {} }), sequence: () => ({ start() {}, stop() {} }) },
+ Platform: { OS: 'ios', select: (s: any) => s.ios ?? s.default },
+ StyleSheet: { create: (s: any) => s, flatten: (s: any) => s, hairlineWidth: 1 },
+ Easing: { linear: (n: number) => n, bezier: () => (n: number) => n },
+ AccessibilityInfo: {}, Alert: {}, Linking: {}, StatusBar: {},
+ useWindowDimensions: () => ({ width: 402, height: 874, scale: 3, fontScale: 1 }),
+ };
+});
+vi.mock('lucide-react-native', () => ({
+ Database: () => null, FileArchive: () => null, FileAudio: () => null, FileChartColumn: () => null,
+ FileCode: () => null, FileImage: () => null, FileSpreadsheet: () => null, FileText: () => null, FileVideo: () => null,
+ ArrowLeftRight: () => null, ArrowUp: () => null, Bot: () => null, Check: () => null, ChevronDown: () => null, ChevronRight: () => null, ChevronUp: () => null, Circle: () => null, CircleAlert: () => null, CircleCheck: () => null, CircleDashed: () => null, CircleStop: () => null, Copy: () => null, Ellipsis: () => null, ExternalLink: () => null, File: () => null, Ghost: () => null, Layers: () => null, ListTodo: () => null, LoaderCircle: () => null, PencilLine: () => null, RefreshCw: () => null, Send: () => null, Share: () => null, Sparkles: () => null, Split: () => null, Timer: () => null, Trash2: () => null, TriangleAlert: () => null, Undo2: () => null, X: () => null,
+}));
+vi.mock('react-native-svg', () => ({ default: () => null, Circle: () => null }));
+vi.mock('react-native-uitextview', () => ({ UITextView: () => null }));
+vi.mock('expo-image', async () => {
+ const { createElement } = await import('react');
+ return { Image: ({ source, onLoad, style }: any) => {
+ imageEvents.set(source.uri, { onLoad });
+ const frame = Object.assign({}, ...[style].flat().filter(Boolean));
+ return createElement('img', { src: source.uri, 'data-width': frame.width, 'data-height': frame.height });
+ } };
+});
+vi.mock('expo-router', () => ({ useRouter: () => ({ push: vi.fn() }), useFocusEffect: vi.fn(), useNavigation: () => ({ isFocused: () => true, addListener: () => () => {} }) }));
+vi.mock('@/device-link/DeviceLinkContext', () => ({
+ useDeviceLink: () => ({ status: 'offline', connectionEpoch: 0, getPresenceAvailability: () => false,
+ invoke: vi.fn(), openLink: vi.fn() }),
+ subscribeRemoteBotChanges: () => () => {},
+}));
+vi.mock('react-native-safe-area-context', () => ({ useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 }) }));
+vi.mock('@/theme', async () => {
+ const tokens = await import('@/theme/tokens');
+ const colors = new Proxy({}, { get: () => '#777777' });
+ return { ...tokens, monoFont: 'monospace', useTheme: () => ({ colors, mode: 'light' }), useThemedStyles: (make: any) => make(colors) };
+});
+vi.mock('@/components/AppText', async () => ({ Text: (await import('react-native')).Text, MAX_FONT_SIZE_MULTIPLIER: 2 }));
+vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ accountGeneration: 1 }) }));
+vi.mock('@/session/usePluginResultCard', () => ({ usePluginResultCard: () => ({}), useSessionPluginResource: () => ({ title: 'Art' }) }));
+vi.mock('@/session/remoteMediaDiskCacheExpo', () => ({ downloadRemoteMediaShareTemp: vi.fn() }));
+vi.mock('@/hooks/useReduceMotion', () => ({ useReduceMotionEnabled: () => true }));
+vi.mock('@/session/expandedBlockMemory', () => ({ useFoldableExpandedState: () => [false, vi.fn()] }));
+vi.mock('@/platform/chrome', () => ({ NativePullDownMenu: () => null, showActionMenu: vi.fn(), usesNativePullDownMenu: () => false, usesSystemActionMenu: () => false }));
+vi.mock('@/session/MobileComposerInputRow', () => ({ MobileComposerInputRow: () => null, MOBILE_COMPOSER_VOICE_ANCHOR_RIGHT: 0, MOBILE_COMPOSER_CONTROL_SIZE: 44 }));
+vi.mock('@/session/ImageLightbox', async () => {
+ const { createElement } = await import('react');
+ return { ImageLightbox: ({ initialUrl }: { initialUrl: string }) => createElement('div', { 'data-testid': 'lightbox', 'data-url': initialUrl }) };
+});
+vi.mock('@/session/mermaidWebView', () => ({ MermaidDiagram: () => null }));
+vi.mock('@/session/mathWebView', () => ({ MathFormulaWebView: () => null }));
+vi.mock('@/session/mediaPlayerWebView', () => ({ RemoteMediaPlayerWebView: () => null }));
+vi.mock('@/session/MarkdownBlockContent', () => ({ MarkdownBlockContent: () => null }));
+vi.mock('@/session/MessageActionSheet', () => ({ MessageActionSheet: () => null }));
+vi.mock('@/session/AuthorizationMessageCard', () => ({ AuthorizationMessageCard: () => null }));
+vi.mock('@/session/CompanionMessageActions', () => ({ CompanionMessageActions: () => null }));
+vi.mock('@/session/CompanionMessageCard', () => ({ CompanionMessageCard: () => null }));
+vi.mock('@/session/PendingSendBubble', () => ({ PendingSendBubble: () => null }));
+vi.mock('@/session/messageActions', async (original) => ({ ...await original<object>(), copyMessageText: vi.fn(), writeClipboardText: vi.fn() }));
+
+import { BotGroupMessageAttachments } from '@/session/BotGroupMessageAttachments';
+import { AttachmentStrip } from '@/session/MessageRenderer';
+import { buildMessageContentLayout } from '@/session/messageContentLayout';
+
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+let root: Root | undefined;
+let host: HTMLDivElement | undefined;
+afterEach(() => { act(() => root?.unmount()); root = undefined; host?.remove(); host = undefined; });
+
+const imageUrl = 'xdt-image://cache/group-picture.png';
+const thumbnailUrl = 'https://example.invalid/group-thumbnail.png';
+const resolveMedia = vi.fn<ResolveRemoteMediaFn>(async () => ({
+ url: thumbnailUrl, previewable: true, mimeType: 'image/png',
+ ossKey: 'thumbnail', size: 10, expiresAt: '',
+}));
+
+beforeEach(() => { resolveMedia.mockClear(); imageEvents.clear(); });
+
+async function renderAttachment(messageId: string) {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(async () => root!.render(createElement(BotGroupMessageAttachments, {
+ messageId,
+ attachments: [{ id: 'attachment', size: 10, path: null, category: 'image', name: 'group-picture.png', url: imageUrl, mimeType: 'image/png' }],
+ onResolveRemoteMedia: resolveMedia,
+ })));
+ return host;
+}
+
+describe('group image attachments outside LegendList (#5278)', () => {
+ it('renders the real image preview without a list provider and opens its gallery', async () => {
+ const container = await renderAttachment('new-message');
+ expect(container.querySelector('img')?.getAttribute('src')).toBe(thumbnailUrl);
+ expect(resolveMedia).toHaveBeenCalledWith(
+ expect.objectContaining({ url: imageUrl, thumbnail: true }), expect.anything(),
+ );
+ act(() => (container.querySelector('[data-testid="message.mediaPreviewButton"]') as HTMLElement).click());
+ expect(container.querySelector('[data-testid="lightbox"]')?.getAttribute('data-url')).toBe(imageUrl);
+ });
+
+ it('keeps local thumbnail sizing state outside the list, including the nested image component', async () => {
+ const uri = 'file:///group-local-thumbnail.png';
+ const layout = buildMessageContentLayout({ screenWidth: 402 });
+ host = document.createElement('div');
+ root = createRoot(host);
+ await act(async () => root!.render(createElement(AttachmentStrip, {
+ attachments: [{ kind: 'image', name: 'local.png', uri: imageUrl, previewable: false }],
+ messageKey: 'local-message', clientId: 'local-message', align: 'right', layout,
+ usePreviewState: useState,
+ getImagePreview: () => ({ attachmentId: 'local', name: 'local.png', sourceRef: imageUrl, uri }),
+ })));
+ expect(host.querySelector('img')?.getAttribute('src')).toBe(uri);
+ act(() => imageEvents.get(uri)!.onLoad({ source: { width: 100, height: 50 } }));
+ expect(host.querySelector('img')?.getAttribute('data-width')).toBe('100');
+ expect(host.querySelector('img')?.getAttribute('data-height')).toBe('50');
+ });
+
+ it('can reopen a group whose loaded history already contains an image', async () => {
+ await renderAttachment('historical-message');
+ act(() => root!.unmount());
+ root = undefined;
+ host!.remove();
+ const reopened = await renderAttachment('historical-message');
+ expect(reopened.querySelector('img')?.getAttribute('src')).toBe(thumbnailUrl);
+ });
+});
diff --git a/apps/mobile/src/session/BotGroupMessageAttachments.tsx b/apps/mobile/src/session/BotGroupMessageAttachments.tsx
index 1436c7c412..a09926fcf2 100644
--- a/apps/mobile/src/session/BotGroupMessageAttachments.tsx
+++ b/apps/mobile/src/session/BotGroupMessageAttachments.tsx
@@ -55,7 +55,7 @@ export function BotGroupMessageAttachments({ messageId, attachments, onResolveRe
};
return <>
<AttachmentStrip attachments={items} messageKey={messageId} align="right" layout={layout} onOpen={open}
- onResolveRemoteMedia={onResolveRemoteMedia} />
+ onResolveRemoteMedia={onResolveRemoteMedia} usePreviewState={useState} />
{openUrl ? <ImageLightbox images={gallery} initialUrl={openUrl} onClose={() => setOpenUrl(null)}
onResolveRemoteMedia={onResolveRemoteMedia} /> : null}
</>;
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index bcc124bba1..db0ab86882 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -20,7 +20,7 @@ import { CompanionMessageCard } from '@/session/CompanionMessageCard';
import { CompanionEntering } from '@/session/CompanionEntering';
import { mobileDebugEnabled, mobileDebugLog } from '@/debug/mobileDebugLog';
import { errorText, resolvedUrlKind } from '@/debug/fileDiagnostics';
-import { createContext, Fragment, memo, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type ComponentProps, type ReactNode } from 'react';
+import { createContext, Fragment, memo, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type ComponentProps, type Dispatch, type ReactNode, type SetStateAction } from 'react';
import { useTranslation } from 'react-i18next';
import { Image as ExpoImage } from 'expo-image';
import {
@@ -6260,6 +6260,10 @@ function MarkdownSessionLinkSpan({
);
}
+/** The caller selects this once for the strip's lifetime: recycled rows use list state,
+ * while ordinary ScrollView children use React state. Keep the choice fixed while mounted. */
+type MediaPreviewStateHook = <T>(initial: T | (() => T)) => readonly [T, Dispatch<SetStateAction<T>>];
+
/** 用户消息的附件条(图片缩略图 + 文件 chip);群聊时间线复用同一实现。 */
export function AttachmentStrip({
attachments,
@@ -6270,6 +6274,7 @@ export function AttachmentStrip({
layout,
onOpen,
onResolveRemoteMedia,
+ usePreviewState = useRecyclingState,
}: {
attachments: readonly NormalizedAttachment[];
messageKey: string;
@@ -6279,6 +6284,7 @@ export function AttachmentStrip({
layout: MessageContentLayout;
onOpen?: (payload: MessagePayload) => void;
onResolveRemoteMedia?: ResolveRemoteMediaFn;
+ usePreviewState?: MediaPreviewStateHook;
}) {
const styles = useThemedStyles(makeStyles);
// 订阅本地缩略兜底版本:hydrate / 新注册落盘后,已渲染的 cindy-oss-attach:// 气泡
@@ -6305,6 +6311,7 @@ export function AttachmentStrip({
onOpen={onOpen ? () => onOpen(buildAttachmentPayload(applySentAttachmentThumbOverlay(item))) : undefined}
onResolveRemoteMedia={onResolveRemoteMedia}
variant="attachment"
+ usePreviewState={usePreviewState}
/>
))}
{fileAttachments.length > 0 ? (
@@ -6428,12 +6435,13 @@ const ATTACHMENT_INTRINSIC_CACHE_MAX = 500;
// 相册候选仍可能是 ph://,必须由 expo-image 加载;只复用正式附件的布局,
// 不把本地相册地址声明为 RN Image / 远端查看器可直接预览的媒体。
-function PendingAttachmentImage({ layout, uri, sourceUri = uri, onError, onSize }: {
+function PendingAttachmentImage({ layout, uri, sourceUri = uri, onError, onSize, usePreviewState = useRecyclingState }: {
layout: MessageContentLayout; uri: string; sourceUri?: string; onError?: () => void;
onSize?: (size: AttachmentImageIntrinsicSize) => void;
+ usePreviewState?: MediaPreviewStateHook;
}) {
const styles = useThemedStyles(makeStyles);
- const [intrinsicSize, setIntrinsicSize] = useRecyclingState<AttachmentImageIntrinsicSize | null>(
+ const [intrinsicSize, setIntrinsicSize] = usePreviewState<AttachmentImageIntrinsicSize | null>(
() => attachmentIntrinsicSizeCache.get(sourceUri) ?? attachmentIntrinsicSizeCache.get(uri) ?? null,
);
// The upload copy and materialized reference describe the same pixels. Carry their measured frame.
@@ -6490,6 +6498,7 @@ function MediaPreview({
variant = 'card',
presentationOnly = false,
localPreview,
+ usePreviewState = useRecyclingState,
}: {
layout: MessageContentLayout;
media: NormalizedToolMedia;
@@ -6499,6 +6508,7 @@ function MediaPreview({
variant?: 'card' | 'attachment';
presentationOnly?: boolean;
localPreview?: SentMessageImagePreview;
+ usePreviewState?: MediaPreviewStateHook;
}) {
const styles = useThemedStyles(makeStyles);
const preview = summarizeMessagePayloadPreview(buildMediaPayload(media, label));
@@ -6506,15 +6516,15 @@ function MediaPreview({
? getSentAttachmentThumbUri(localPreview?.sourceRef ?? media.url)
: null;
const localCandidate = localPreview?.uri ?? durableUri;
- const [failedLocalUris, setFailedLocalUris] = useRecyclingState<readonly string[]>([]);
+ const [failedLocalUris, setFailedLocalUris] = usePreviewState<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' });
+ const [resolveState, setResolveState] = usePreviewState<MediaThumbnailResolveState>({ status: 'idle' });
// attachment 变体的原图尺寸。初值走模块级缓存:FlatList 虚拟化会反复
// unmount/remount 本组件,不缓存的话每次划回都重新 getSize、重演一次
// 占位帧 → 真图尺寸的切换(规则 7 的跳变)。
- const [intrinsicSize, setIntrinsicSize] = useRecyclingState<AttachmentImageIntrinsicSize | null>(
+ const [intrinsicSize, setIntrinsicSize] = usePreviewState<AttachmentImageIntrinsicSize | null>(
() => attachmentIntrinsicSizeCache.get(localPreview?.uri ?? media.url)
?? attachmentIntrinsicSizeCache.get(localCandidate ?? media.url) ?? null,
);
@@ -6590,6 +6600,7 @@ function MediaPreview({
style={styles.attachmentImageWrap} testID="message.mediaPreviewButton">
<PendingAttachmentImage key={localPreview?.uri ?? localUri} layout={layout}
uri={localUri} sourceUri={localPreview?.uri ?? localUri}
+ usePreviewState={usePreviewState}
onSize={setIntrinsicSize}
onError={() => setFailedLocalUris((failed) => failed.includes(localUri) ? failed : [...failed, localUri])} />
</MessageContentOpenButton>