Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(mobile): recover failed group image previews
xd1ca5ff0615b5
diff --git a/apps/mobile/src/__tests__/botGroupAttachmentLightbox.test.tsx b/apps/mobile/src/__tests__/botGroupAttachmentLightbox.test.tsxindex c56e8fa8ff..089647e8b4 100644--- a/apps/mobile/src/__tests__/botGroupAttachmentLightbox.test.tsx+++ b/apps/mobile/src/__tests__/botGroupAttachmentLightbox.test.tsx@@ -213,6 +213,90 @@ describe('Chat Server group image attachments (#5875)', () => {expect(container.querySelector('[data-testid="message.imageLightbox"] img')?.getAttribute('src')).toBe(signedImageUrl);});+ // PR #7145 review r4371267451 / media-storage-and-protocols: a native image+ // failure after successful authorization was not covered by authorization errors.+ // Unit: one signed image + onError must refresh once, then allow manual recovery.+ it('refreshes a failed native preview once, then repairs the list on an explicit tap', async () => {+ const refreshedUrl = `${signedImageUrl}&refreshed=1`;+ const tappedUrl = `${signedImageUrl}&refreshed=2`;+ const resolveServerMedia = vi.fn<() => Promise<BotGroupAttachment>>()+ .mockResolvedValueOnce({ ...serverAttachment, category: 'image', url: signedImageUrl })+ .mockResolvedValueOnce({ ...serverAttachment, category: 'image', url: refreshedUrl })+ .mockResolvedValue({ ...serverAttachment, category: 'image', url: tappedUrl });+ const container = await render({ resolveServerMedia });+ await act(async () => runtime.imageEvents.get(signedImageUrl)!.onError?.());+ expect(resolveServerMedia).toHaveBeenCalledTimes(2);+ expect(container.querySelector('img')?.getAttribute('src')).toBe(refreshedUrl);+ await act(async () => runtime.imageEvents.get(refreshedUrl)!.onError?.());+ expect(resolveServerMedia).toHaveBeenCalledTimes(2);+ expect(container.querySelector('[data-testid="message.mediaThumbFallback"]')).not.toBeNull();+ await click(container.querySelector('[data-testid="message.mediaPreviewButton"]'));+ expect(resolveServerMedia).toHaveBeenCalledTimes(3);+ await click(container.querySelector('[data-testid="message.imageLightboxCloseButton"]'));+ expect(container.querySelector('img')?.getAttribute('src')).toBe(tappedUrl);+ expect(runtime.alerts).toEqual([]);+ });++ it('retries the same signed URL after a transient native failure', async () => {+ const resolveServerMedia = vi.fn(async () => ({ ...serverAttachment, category: 'image' as const, url: signedImageUrl }));+ const container = await render({ resolveServerMedia });+ await act(async () => runtime.imageEvents.get(signedImageUrl)!.onError?.());+ expect(resolveServerMedia).toHaveBeenCalledTimes(2);+ expect(container.querySelector('img')?.getAttribute('src')).toBe(signedImageUrl);+ await act(async () => runtime.imageEvents.get(signedImageUrl)!.onError?.());+ expect(resolveServerMedia).toHaveBeenCalledTimes(2);+ expect(container.querySelector('img')).toBeNull();+ });++ it('defers native-error refresh offscreen and ignores its late result after leaving', async () => {+ const visibility = new MessageListVisibility();+ visibility.update([{ key: 'message-1', isViewable: true }]);+ let finishRefresh!: (value: BotGroupAttachment) => void;+ const resolveServerMedia = vi.fn<() => Promise<BotGroupAttachment>>()+ .mockResolvedValueOnce({ ...serverAttachment, category: 'image', url: signedImageUrl })+ .mockImplementationOnce(() => new Promise(resolve => { finishRefresh = resolve; }));+ const container = await render({ resolveServerMedia }, visibility);+ await act(async () => visibility.update([]));+ await act(async () => runtime.imageEvents.get(signedImageUrl)!.onError?.());+ expect(resolveServerMedia).toHaveBeenCalledTimes(1);+ await act(async () => visibility.update([{ key: 'message-1', isViewable: true }]));+ expect(resolveServerMedia).toHaveBeenCalledTimes(2);+ await act(async () => visibility.update([]));+ await act(async () => finishRefresh({ ...serverAttachment, category: 'image', url: `${signedImageUrl}&late=1` }));+ expect(container.querySelector('img')).toBeNull();+ });++ it('does not let a late automatic refresh replace a newer explicit authorization', async () => {+ let finishRefresh!: (value: BotGroupAttachment) => void;+ const tappedUrl = `${signedImageUrl}&tap=1`;+ const resolveServerMedia = vi.fn<() => Promise<BotGroupAttachment>>()+ .mockResolvedValueOnce({ ...serverAttachment, category: 'image', url: signedImageUrl })+ .mockImplementationOnce(() => new Promise(resolve => { finishRefresh = resolve; }))+ .mockResolvedValueOnce({ ...serverAttachment, category: 'image', url: tappedUrl });+ const container = await render({ resolveServerMedia });+ await act(async () => runtime.imageEvents.get(signedImageUrl)!.onError?.());+ await click(container.querySelector('[data-testid="message.mediaPreviewButton"]'));+ await act(async () => finishRefresh({ ...serverAttachment, category: 'image', url: `${signedImageUrl}&late=1` }));+ await click(container.querySelector('[data-testid="message.imageLightboxCloseButton"]'));+ expect(container.querySelector('img')?.getAttribute('src')).toBe(tappedUrl);+ expect(resolveServerMedia).toHaveBeenCalledTimes(3);+ });++ it('reloads only the failed image and preserves its loaded neighbour', async () => {+ const neighbour = { ...serverAttachment, id: 'media-2', name: '2.png' };+ const neighbourUrl = `${signedImageUrl}&neighbour=1`;+ const resolveServerMedia = vi.fn(async (id: string) => ({+ ...serverAttachment, id, category: 'image' as const,+ url: id === neighbour.id ? neighbourUrl : signedImageUrl,+ }));+ const container = await render({ resolveServerMedia, attachments: [serverAttachment, neighbour] });+ const loadedNeighbour = container.querySelector(`img[src="${neighbourUrl}"]`);+ await act(async () => runtime.imageEvents.get(signedImageUrl)!.onError?.());+ expect(resolveServerMedia.mock.calls.map(([id]) => id)).toEqual(['media-1', 'media-2', 'media-1']);+ expect(container.querySelector(`img[src="${signedImageUrl}"]`)).not.toBeNull();+ expect(container.querySelector(`img[src="${neighbourUrl}"]`)).toBe(loadedNeighbour);+ });+// CloudCompanionScreen selects this policy even if its row is visible.it('keeps cloud transcript media tap-only, including after returning from the viewer', async () => {const resolveServerMedia = vi.fn(async () => ({ ...serverAttachment, category: 'image' as const, url: signedImageUrl }));diff --git a/apps/mobile/src/session/BotGroupMessageAttachments.tsx b/apps/mobile/src/session/BotGroupMessageAttachments.tsxindex e7be21b3b6..51916b849c 100644--- a/apps/mobile/src/session/BotGroupMessageAttachments.tsx+++ b/apps/mobile/src/session/BotGroupMessageAttachments.tsx@@ -151,6 +151,10 @@ function ServerAttachments({ runs, visible, align, layout, resolve }: {const { t } = useTranslation();const { colors } = useTheme();const [previews, setPreviews] = useState<Record<string, BotGroupAttachment>>({});+ const failedPreviewIds = useRef(new Set<string>());+ const retriedPreviewIds = useRef(new Set<string>());+ const [retryRequest, setRetryRequest] = useState(0);+ const [previewVersions, setPreviewVersions] = useState<Record<string, number>>({});const resolveRef = useRef(resolve); resolveRef.current = resolve;const previewsRef = useRef(previews); previewsRef.current = previews;const previewIds = JSON.stringify(runs.flatMap(run => run.kind === 'ready' ? run.attachments.map(item => item.id) : []));@@ -159,19 +163,28 @@ function ServerAttachments({ runs, visible, align, layout, resolve }: {if (!visible) return;for (const id of JSON.parse(previewIds) as string[]) {authorizePreview(async () => {- if (cancelled || previewsRef.current[id]) return;+ if (cancelled || (previewsRef.current[id] && !failedPreviewIds.current.has(id))) return;+ const refreshing = failedPreviewIds.current.has(id);+ const previousPreview = previewsRef.current[id];try {const value = await resolveRef.current(id);const preview = value.category === 'image' ? value : { ...value, url: null };- if (!cancelled) {+ if (!cancelled && previewsRef.current[id] === previousPreview) {previewsRef.current = { ...previewsRef.current, [id]: preview };setPreviews(previewsRef.current);+ failedPreviewIds.current.delete(id);+ // A renewed authorization can return the same URL after a transient CDN failure.+ // Remount only the failed image too, resetting its native error state.+ if (refreshing) setPreviewVersions(versions => ({ ...versions, [id]: (versions[id] ?? 0) + 1 }));}- } catch { /* Keep the chip available for an explicit retry on tap. */ }+ } catch {+ if (!cancelled) failedPreviewIds.current.delete(id);+ // Keep the chip / fallback available for an explicit retry on tap.+ }});}return () => { cancelled = true; };- }, [previewIds, visible]);+ }, [previewIds, visible, retryRequest]);const displayRuns = botGroupAttachmentRuns(runs.flatMap(run => run.kind === 'pending'? [run.attachment] : run.attachments.map(item => previews[item.id] ?? { ...item, url: null })));const [image, setImage] = useState<BotGroupAttachment | null>(null);@@ -186,7 +199,16 @@ function ServerAttachments({ runs, visible, align, layout, resolve }: {const value = await resolve(id);if (!mounted.current) return;if (!value.url) throw new Error('MEDIA_NOT_FOUND');- if (value.category === 'image') setImage(value);+ if (value.category === 'image') {+ setImage(value);+ // Cloud transcripts never populate this cache: their media remains tap-only.+ if (previewsRef.current[id]) {+ previewsRef.current = { ...previewsRef.current, [id]: value };+ setPreviews(previewsRef.current);+ failedPreviewIds.current.delete(id);+ setPreviewVersions(versions => ({ ...versions, [id]: (versions[id] ?? 0) + 1 }));+ }+ }else await openBrowserAsync(value.url);} catch { if (mounted.current) Alert.alert(t('groupChat.server.attachmentFailed')); }finally { pending.current = false; if (mounted.current) setBusy(null); }@@ -197,6 +219,7 @@ function ServerAttachments({ runs, visible, align, layout, resolve }: {? <PendingAttachment key={run.attachment.id} attachment={run.attachment} align={align} layout={layout} />: <View key={run.attachments[0]!.id} style={styles.serverAttachment}><AttachmentStrip attachments={run.attachments.map(botGroupAttachmentForDisplay)}+ imageReloadKeys={run.attachments.map(item => previewVersions[item.id] ?? 0)}messageKey={run.attachments[0]!.id} align={align} layout={layout}onOpen={payload => {if (payload.kind === 'media') {@@ -204,6 +227,14 @@ function ServerAttachments({ runs, visible, align, layout, resolve }: {if (attachment) void open(attachment.id);}}}+ onImageError={index => {+ const attachment = run.attachments[index];+ if (!attachment || retriedPreviewIds.current.has(attachment.id)+ || previewsRef.current[attachment.id]?.url !== attachment.url) return;+ retriedPreviewIds.current.add(attachment.id);+ failedPreviewIds.current.add(attachment.id);+ setRetryRequest(request => request + 1);+ }}onOpenFile={index => { void open(run.attachments[index]!.id); }} usePreviewState={useState} />{run.attachments.some(attachment => busy === attachment.id)? <ActivityIndicator color={colors.textSecondary} style={align === 'right' ? styles.busyRight : styles.busyLeft} />diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsxindex bdbaa9978c..5293111879 100644--- a/apps/mobile/src/session/MessageRenderer.tsx+++ b/apps/mobile/src/session/MessageRenderer.tsx@@ -6628,6 +6628,8 @@ export function AttachmentStrip({layout,onOpen,onOpenFile,+ onImageError,+ imageReloadKeys,onResolveRemoteMedia,usePreviewState = useRecyclingState,}: {@@ -6640,6 +6642,10 @@ export function AttachmentStrip({onOpen?: (payload: MessagePayload) => void;/** Index within this strip's file chips, for callers that resolve files by ID on tap. */onOpenFile?: (index: number) => void;+ /** Index within this strip's images, for owners that refresh short-lived authorization. */+ onImageError?: (index: number) => void;+ /** Reset only the failed image when authorization returns the same URL. */+ imageReloadKeys?: readonly number[];onResolveRemoteMedia?: ResolveRemoteMediaFn;usePreviewState?: MediaPreviewStateHook;}) {@@ -6660,13 +6666,14 @@ export function AttachmentStrip({兜底命中时替换成 file:// 直接渲染(payload 同源替换,点开查看器同图)。 */}{imageAttachments.map((item, index) => (<MediaPreview- key={`${item.kind}:${item.uri ?? item.name}:${index}`}+ key={`${item.kind}:${item.uri ?? item.name}:${index}:${imageReloadKeys?.[index] ?? 0}`}label={item.name}layout={layout}media={{ kind: 'image', url: item.uri ?? '', previewable: item.previewable }}localPreview={clientId ? getImagePreview?.(clientId, index, item.name, undefined, item.sha256, item.uri) : undefined}onOpen={onOpen ? () => onOpen(buildAttachmentPayload(applySentAttachmentThumbOverlay(item))) : undefined}onResolveRemoteMedia={onResolveRemoteMedia}+ onImageError={onImageError ? () => onImageError(index) : undefined}variant="attachment"usePreviewState={usePreviewState}/>@@ -6855,6 +6862,7 @@ function MediaPreview({label,onOpen,onResolveRemoteMedia,+ onImageError,variant = 'card',presentationOnly = false,localPreview,@@ -6865,6 +6873,7 @@ function MediaPreview({label: string;onOpen?: () => void;onResolveRemoteMedia?: ResolveRemoteMediaFn;+ onImageError?: () => void;variant?: 'card' | 'attachment';presentationOnly?: boolean;localPreview?: SentMessageImagePreview;@@ -6932,6 +6941,7 @@ function MediaPreview({const handleImageError = useCallback(() => {if (media.previewable) {setResolveState({ status: 'error' });+ onImageError?.();return;}if (imageRetryUsedRef.current) {@@ -6940,7 +6950,7 @@ function MediaPreview({}imageRetryUsedRef.current = true;resolveThumbnail(true);- }, [media.previewable, resolveThumbnail]);+ }, [media.previewable, onImageError, resolveThumbnail]);// Measure with the same decoder that displays the image: RN getSize cannot// decode SVG. Reuse the decoded dimensions without a second image request.