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): load group previews only for visible history

xd9f42d1298f94
diff --git a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
index 49be279284..55d3022cad 100644
--- a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
+++ b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
@@ -33,8 +33,9 @@ const h = vi.hoisted(() => ({
vi.mock('expo-web-browser', () => ({ openBrowserAsync: vi.fn(async () => ({})) }));
vi.mock('@/components/ChatReplyIcon', () => ({ ChatReplyIcon: () => null }));
vi.mock('react-native', () => {
- const box = (tag: string) => ({ children, testID, accessibilityLabel, style }: any) =>
+ const box = (tag: string) => ({ children, testID, accessibilityLabel, style, onLayout }: any) =>
el(tag, { 'data-testid': testID, 'aria-label': accessibilityLabel,
+ ref: (node: any) => { if (node) node.nativeLayout = onLayout; },
style: { opacity: [style].flat().filter(Boolean).findLast((item: any) => item.opacity !== undefined)?.opacity } }, children);
return {
View: box('div'), ScrollView: ({ ref, children, ...props }: any) => {
@@ -1378,6 +1379,17 @@ describe('direct server group presentation', () => {
const attachment = { id: 'media', name: 'picture.png', mimeType: 'image/png', size: 10, category: 'image' as const, url: 'https://media.example.invalid/one-use', path: null };
h.chat = { ...h.chat, server: true, media: vi.fn(async () => attachment) };
await render(group({ messages: [message('picture', 1, { authorKind: 'user', isSelf: false, attachments: [{ ...attachment, url: null, category: 'file' }] })], plans: [], openPlan: null }));
+ expect(h.chat.media).not.toHaveBeenCalled();
+ let row = byId('attachmentStrip') as HTMLElement & { nativeLayout?: (event: unknown) => void };
+ while (!row.nativeLayout) row = row.parentElement as typeof row;
+ await act(async () => {
+ row.nativeLayout!({ nativeEvent: { layout: { y: 800, height: 200 } } });
+ h.scroll.onLayout({ nativeEvent: { layout: { height: 500 } } });
+ });
+ expect(h.chat.media).not.toHaveBeenCalled();
+ await act(async () => h.scroll.onScroll({ nativeEvent: {
+ contentOffset: { y: 700 }, contentSize: { height: 1000 }, layoutMeasurement: { height: 500 },
+ } }));
expect(h.chat.media).toHaveBeenCalledExactlyOnceWith('media');
expect(byId('attachment.image')?.getAttribute('data-uri')).toBe(attachment.url);
await click('attachment.image'); expect(h.chat.media).toHaveBeenCalledTimes(2);
diff --git a/apps/mobile/src/__tests__/CloudCompanionScreenAttachments.test.tsx b/apps/mobile/src/__tests__/CloudCompanionScreenAttachments.test.tsx
index 6e6586682c..2fde283d9b 100644
--- a/apps/mobile/src/__tests__/CloudCompanionScreenAttachments.test.tsx
+++ b/apps/mobile/src/__tests__/CloudCompanionScreenAttachments.test.tsx
@@ -6,7 +6,7 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest';
const h = vi.hoisted(() => ({
stub: (_name: string) => () => null,
room: { status: 'ready', messages: [] as unknown[], before: null, loadingOlder: false, reload: vi.fn(), loadOlder: vi.fn(), media: vi.fn() },
- strips: [] as Array<{ messageId: string; align: string; names: string[]; resolve: unknown }>,
+ strips: [] as Array<{ messageId: string; align: string; names: string[]; resolve: unknown; previewServerImages: boolean }>,
}));
vi.mock('react-native', async () => {
const { createElement: el } = await import('react');
@@ -51,7 +51,7 @@ vi.mock('@/session/useTeammateRoster', () => ({ TEAMMATE_COLLECTION_ID: 'teammat
vi.mock('@/session/BotGroupMessageAttachments', async () => {
const { createElement: el } = await import('react');
return { BotGroupMessageAttachments: (props: any) => {
- h.strips.push({ messageId: props.messageId, align: props.align, names: props.attachments.map((a: any) => a.name), resolve: props.resolveServerMedia });
+ h.strips.push({ messageId: props.messageId, align: props.align, names: props.attachments.map((a: any) => a.name), resolve: props.resolveServerMedia, previewServerImages: props.previewServerImages });
return el('div', { 'data-kind': 'strip', 'data-message': props.messageId });
} };
});
@@ -89,6 +89,8 @@ it('shows the owner\'s and the companion\'s attachments under their messages, in
]);
// Each strip fetches its addresses from the room hook.
expect(h.strips.every(strip => strip.resolve === h.room.media)).toBe(true);
+ // cloud-companions.md §3.1: signed private URLs are acquired only on an explicit tap.
+ expect(h.strips.every(strip => strip.previewServerImages === false)).toBe(true);
expect(container.querySelectorAll('[data-testid="cloudCompanion.message.user"]')).toHaveLength(2);
expect(container.querySelectorAll('[data-testid="cloudCompanion.message.companion"]')).toHaveLength(3);
// Captions are the attachments' names, not text repeated beside them; an attachment-only message has no empty bubble.
diff --git a/apps/mobile/src/__tests__/botGroupAttachmentLightbox.test.tsx b/apps/mobile/src/__tests__/botGroupAttachmentLightbox.test.tsx
index de5b2bb9c0..c164b005ed 100644
--- a/apps/mobile/src/__tests__/botGroupAttachmentLightbox.test.tsx
+++ b/apps/mobile/src/__tests__/botGroupAttachmentLightbox.test.tsx
@@ -120,6 +120,7 @@ vi.mock('react-native-reanimated', async () => {
});
import { BotGroupMessageAttachments } from '@/session/BotGroupMessageAttachments';
+import { MessageListVisibility, MessageListVisibilityContext } from '@/session/messageListVisibility';
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
let root: Root | undefined;
@@ -131,14 +132,14 @@ beforeEach(() => { runtime.alerts = []; runtime.imageEvents.clear(); openBrowser
const signedImageUrl = 'https://chat.example.invalid/media/group-picture.png?signature=placeholder';
const serverAttachment: BotGroupAttachment = { id: 'media-1', name: '1.png', category: 'file', mimeType: '', size: 0, url: null, path: null };
-async function render(props: Partial<Parameters<typeof BotGroupMessageAttachments>[0]>) {
+async function render(props: Partial<Parameters<typeof BotGroupMessageAttachments>[0]>, visibility?: MessageListVisibility) {
host = document.createElement('div');
document.body.append(host);
root = createRoot(host);
- await act(async () => root!.render(createElement(BotGroupMessageAttachments, {
+ await act(async () => root!.render(createElement(MessageListVisibilityContext.Provider, { value: visibility ?? null }, createElement(BotGroupMessageAttachments, {
messageId: 'message-1', align: 'right', attachments: [serverAttachment],
onResolveRemoteMedia: vi.fn<ResolveRemoteMediaFn>(), ...props,
- })));
+ }))));
return host;
}
@@ -146,6 +147,23 @@ const click = (element: Element | null | undefined) => act(async () => { (elemen
const loadFailedKey = 'message.lightbox.loadFailed';
describe('Chat Server group image attachments (#5875)', () => {
+ // PR #7145: ScrollView mounts offscreen history too. Existing tests had no viewport.
+ // The real strip must not mount an image (or request its URL) until its row is visible.
+ it('loads only visible messages and preserves loaded previews when scrolling back', async () => {
+ const visibility = new MessageListVisibility();
+ const resolveServerMedia = vi.fn(async () => ({ ...serverAttachment, category: 'image' as const, url: signedImageUrl }));
+ const container = await render({ resolveServerMedia }, visibility);
+ expect(resolveServerMedia).not.toHaveBeenCalled();
+ expect(container.querySelector('img')).toBeNull();
+ await act(async () => visibility.update([{ key: 'message-1', isViewable: true }]));
+ expect(resolveServerMedia).toHaveBeenCalledTimes(1);
+ expect(container.querySelector('img')?.getAttribute('src')).toBe(signedImageUrl);
+ await act(async () => visibility.update([]));
+ await act(async () => visibility.update([{ key: 'message-1', isViewable: true }]));
+ expect(resolveServerMedia).toHaveBeenCalledTimes(1);
+ expect(container.querySelector('img')?.getAttribute('src')).toBe(signedImageUrl);
+ });
+
it('shows an authorized HTTPS image in the real lightbox, re-authorizing on every tap', async () => {
const resolveServerMedia = vi.fn(async (id: string): Promise<BotGroupAttachment> => ({
id, name: '1.png', category: 'image', mimeType: 'image/png', size: 10, url: signedImageUrl, path: null,
@@ -173,6 +191,21 @@ describe('Chat Server group image attachments (#5875)', () => {
expect(container.querySelector('[data-testid="message.imageLightbox"] img')?.getAttribute('src')).toBe(signedImageUrl);
});
+ // 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 }));
+ const container = await render({ resolveServerMedia, previewServerImages: false });
+ expect(resolveServerMedia).not.toHaveBeenCalled();
+ expect(container.querySelector('img')).toBeNull();
+ await click(container.querySelector('[data-testid="message.filePreviewButton"]'));
+ expect(resolveServerMedia).toHaveBeenCalledTimes(1);
+ expect(container.querySelector('[data-testid="message.imageLightbox"] img')?.getAttribute('src')).toBe(signedImageUrl);
+ await click(container.querySelector('[data-testid="message.imageLightboxCloseButton"]'));
+ expect(container.querySelector('img')).toBeNull();
+ await click(container.querySelector('[data-testid="message.filePreviewButton"]'));
+ expect(resolveServerMedia).toHaveBeenCalledTimes(2);
+ });
+
it('opens a non-image server file through its short-lived download address, not the viewer', async () => {
const fileUrl = 'https://chat.example.invalid/media/report.pdf?signature=placeholder';
const resolveServerMedia = vi.fn(async (id: string): Promise<BotGroupAttachment> => ({
@@ -195,6 +228,20 @@ describe('Chat Server group image attachments (#5875)', () => {
expect(container.querySelector('[data-testid="message.imageLightbox"] img')?.getAttribute('src')).toBe(signedImageUrl);
});
+ it('cancels queued offscreen previews and does not mount late image results', async () => {
+ const visibility = new MessageListVisibility();
+ visibility.update([{ key: 'message-1', isViewable: true }]);
+ const pending: Array<(value: BotGroupAttachment) => void> = [];
+ const resolveServerMedia = vi.fn(() => new Promise<BotGroupAttachment>(resolve => pending.push(resolve)));
+ const attachments = Array.from({ length: 4 }, (_, index) => ({ ...serverAttachment, id: `media-${index}` }));
+ const container = await render({ resolveServerMedia, attachments }, visibility);
+ expect(resolveServerMedia).toHaveBeenCalledTimes(3);
+ await act(async () => visibility.update([]));
+ await act(async () => pending.forEach(resolve => resolve({ ...serverAttachment, category: 'image', url: signedImageUrl })));
+ expect(resolveServerMedia).toHaveBeenCalledTimes(3);
+ expect(container.querySelector('img')).toBeNull();
+ });
+
it('bounds preview authorization and ignores late results when the message changes', async () => {
const pending: Array<(value: BotGroupAttachment) => void> = [];
const resolveServerMedia = vi.fn((id: string) => new Promise<BotGroupAttachment>(resolve => {
diff --git a/apps/mobile/src/__tests__/messageListVisibility.test.tsx b/apps/mobile/src/__tests__/messageListVisibility.test.tsx
index 3b3b7f82a2..e884a7e682 100644
--- a/apps/mobile/src/__tests__/messageListVisibility.test.tsx
+++ b/apps/mobile/src/__tests__/messageListVisibility.test.tsx
@@ -3,7 +3,7 @@ import { act, createElement, useLayoutEffect } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import {
- MessageListVisibility, MessageListVisibilityContext, useMessageListItemVisible,
+ MessageListVisibility, MessageListVisibilityContext, ScrollViewMessageVisibility, useMessageListItemVisible,
} from '@/session/messageListVisibility';
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
@@ -91,3 +91,26 @@ it('removes subscriptions and clears visibility absent from the current list sna
store.update([{ key: 'a', isViewable: false }]);
expect(store.isVisible('a')).toBe(false);
});
+
+// PR #7145: native ScrollView layout/scroll events must gate mounted history rows.
+// Existing LegendList tests only published visibility directly, without geometry.
+it('tracks ScrollView intersections through scroll, resize, history prepend and removal', () => {
+ const scroll = new ScrollViewMessageVisibility();
+ scroll.setLayout('a', { y: 0, height: 200 });
+ scroll.setLayout('b', { y: 800, height: 200 });
+ expect(scroll.isVisible('a')).toBe(false); // no measured viewport yet
+ scroll.setViewport(0, 500);
+ expect(scroll.isVisible('a')).toBe(true);
+ expect(scroll.isVisible('b')).toBe(false);
+ scroll.setViewport(500, 300); // b is exactly outside the bottom edge
+ expect(scroll.isVisible('a')).toBe(false);
+ expect(scroll.isVisible('b')).toBe(false);
+ scroll.setHeight(301);
+ expect(scroll.isVisible('b')).toBe(true);
+ scroll.setLayout('b', { y: 1200, height: 200 }); // prepended history moves content
+ expect(scroll.isVisible('b')).toBe(false);
+ scroll.setViewport(1200, 500);
+ expect(scroll.isVisible('b')).toBe(true);
+ scroll.retain(['a']);
+ expect(scroll.isVisible('b')).toBe(false);
+});
diff --git a/apps/mobile/src/session/BotGroupChatScreen.tsx b/apps/mobile/src/session/BotGroupChatScreen.tsx
index b7cdd303b8..57c47ac85e 100644
--- a/apps/mobile/src/session/BotGroupChatScreen.tsx
+++ b/apps/mobile/src/session/BotGroupChatScreen.tsx
@@ -77,6 +77,7 @@ import { SessionHeaderNativeBlur } from './SessionHeaderNativeControls';
import { CompanionEntering, CompanionFadeIn } from './CompanionEntering';
import { BotGroupComposer, type BotGroupSendInput } from './BotGroupComposer';
import { BotGroupMessageAttachments } from './BotGroupMessageAttachments';
+import { MessageListVisibilityContext, useScrollViewMessageVisibility } from './messageListVisibility';
import { BotGroupTaskCard } from './BotGroupTaskCard';
import { BotGroupMarkdownText, BotGroupUserText } from './BotGroupMessageText';
import { BotGroupQuote } from './BotGroupQuote';
@@ -148,6 +149,10 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId, messageId, n
const jumpAttempts = useRef(0);
const messagePositions = useRef(new Map<string, number>());
const group = chat.state.kind === 'ready' ? chat.state.group : null;
+ const previewVisibility = useScrollViewMessageVisibility(
+ `${accountGeneration}:${deviceId}:${groupId}:${threadRootId ?? ''}`,
+ useMemo(() => group?.messages.map(message => message.id) ?? [], [group?.messages]),
+ );
const focused = useIsFocused();
const viewportOwner = `${user?.id ?? ''}:${accountGeneration}:${deviceId}:${groupId}:${threadRootId ?? 'main'}`;
const [seen, setSeen] = useState<{ owner: string; sequence: string } | null>(null);
@@ -352,6 +357,7 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId, messageId, n
const onScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
const { contentOffset, contentSize, layoutMeasurement } = event.nativeEvent;
+ previewVisibility.setViewport(contentOffset.y, layoutMeasurement.height);
if (stickToBottom.current) setSeen(previous => previous?.owner === viewportOwner && previous.sequence === latestSequence
? previous : { owner: viewportOwner, sequence: latestSequence });
Object.assign(viewport.current, { measuredGroup: group, contentHeight: contentSize.height,
@@ -421,12 +427,13 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId, messageId, n
{floatingHeader ? null : offlineNote}
{group.dissolvedAt ? <Text style={styles.offline}>{t('groupChat.lifecycle.dissolved')}</Text> : null}
<View style={styles.flex}>
+ <MessageListVisibilityContext.Provider value={previewVisibility}>
<ScrollView ref={scrollRef} style={styles.flex} contentContainerStyle={[styles.timeline, floatingHeader && { paddingTop: headerHeight + spacing.md }]}
scrollIndicatorInsets={floatingHeader ? { top: headerHeight } : undefined} keyboardShouldPersistTaps="handled"
keyboardDismissMode="interactive"
maintainVisibleContentPosition={chat.server ? { minIndexForVisible: group.hasMoreBefore ? 1 : 0 } : undefined}
onScroll={onScroll} scrollEventThrottle={64}
- onLayout={event => { viewport.current.viewportHeight = event.nativeEvent.layout.height; acknowledge(); }}
+ onLayout={event => { viewport.current.viewportHeight = event.nativeEvent.layout.height; previewVisibility.setHeight(event.nativeEvent.layout.height); acknowledge(); }}
onContentSizeChange={(_width, height) => {
viewport.current.contentHeight = height;
viewport.current.measuredGroup = group;
@@ -437,7 +444,8 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId, messageId, n
<BotGroupTimeline group={group} deviceId={deviceId} online={chat.online} identityFor={identityFor}
highlightId={highlightId} onLocateMessage={locateMessage}
onReply={(chat.server || group.serverBacked) && !group.archived && !group.dissolvedAt ? message => setReplyTo(botGroupQuoteFromMessage(message)) : undefined}
- onMessageLayout={(id, y) => {
+ onMessageLayout={(id, y, height) => {
+ previewVisibility.setLayout(id, { y, height });
messagePositions.current.set(id, y);
if (jumpTarget === id) positionAtMessage(id, y);
}}
@@ -449,6 +457,7 @@ export function BotGroupChatScreen({ deviceId, deviceName, groupId, messageId, n
onEditStep={(planId, step, action, botId) => void editPlanStep(planId, step, action, botId)}
onInteractionError={(message) => { if (message) Alert.alert(message); }} />
</ScrollView>
+ </MessageListVisibilityContext.Provider>
{newMessageCount > 0 ? <View style={styles.newMessages} accessibilityLiveRegion="polite">
<CompanionFadeIn play distance={spacing.xs}>
<MainWindowActionButton density="compact" style={styles.newMessagesButton} action={{
@@ -519,7 +528,7 @@ export function BotGroupTimeline({
onPlanAction(action: BotGroupPlanAction, planId: string): void;
onEditStep(planId: string, step: BotGroupPlanStepView, action: 'reassign' | 'remove', botId?: string): void;
onInteractionError(message: string | null): void;
- onMessageLayout?: (id: string, y: number) => void;
+ onMessageLayout?: (id: string, y: number, height: number) => void;
onLocateMessage?: (id: string) => void;
highlightId?: string;
onReply?: (message: BotGroupMessageView) => void;
@@ -551,7 +560,7 @@ export function BotGroupTimeline({
const continued = groupTime === undefined && message.kind === 'message' && message.authorKind === 'bot'
&& previous?.kind === 'message' && previous.authorKind === 'bot' && previous.authorBotId === message.authorBotId;
return <View key={message.id} style={[styles.item, highlightId === message.id && styles.locatedMessage]}
- onLayout={event => onMessageLayout?.(message.id, event.nativeEvent.layout.y)}>
+ onLayout={event => onMessageLayout?.(message.id, event.nativeEvent.layout.y, event.nativeEvent.layout.height)}>
{groupTime !== undefined ? <Text style={styles.time}>{formatBotMessageGroupTime(groupTime, i18n.language)}</Text> : null}
<CompanionEntering id={message.id} createdAt={message.createdAt} kind={message.authorKind === 'user' ? 'send' : 'reply'}>
<BotGroupTimelineItem message={message} continued={continued} member={message.authorBotId ? memberById.get(message.authorBotId) : undefined}
diff --git a/apps/mobile/src/session/BotGroupMessageAttachments.tsx b/apps/mobile/src/session/BotGroupMessageAttachments.tsx
index f15f2c4f15..e7be21b3b6 100644
--- a/apps/mobile/src/session/BotGroupMessageAttachments.tsx
+++ b/apps/mobile/src/session/BotGroupMessageAttachments.tsx
@@ -9,11 +9,12 @@ import { useAuth } from '@/auth/AuthContext';
import { openBrowserAsync } from 'expo-web-browser';
import { Text } from '@/components/AppText';
import { spacing, textStyles, useTheme } from '@/theme';
-import { useEffect, useMemo, useRef, useState } from 'react';
+import { useContext, useEffect, useMemo, useRef, useState } from 'react';
import { ActivityIndicator, Alert, StyleSheet, View, useWindowDimensions } from 'react-native';
import { useTranslation } from 'react-i18next';
import type { BotGroupAttachment } from '@cindy/maker-shared/botGroupChat';
import { ImageLightbox } from './ImageLightbox';
+import { MessageListVisibilityContext, useMessageListItemVisible } from './messageListVisibility';
import { AttachmentStrip } from './MessageRenderer';
import { buildMessageContentLayout } from './messageContentLayout';
import type { MobileMessageGalleryImage } from './messageGallery';
@@ -43,22 +44,27 @@ export function botGroupAttachmentGallery(messageId: string, attachments: readon
});
}
-export function BotGroupMessageAttachments({ messageId, attachments, align, onResolveRemoteMedia, resolveServerMedia }: {
+export function BotGroupMessageAttachments({ messageId, attachments, align, onResolveRemoteMedia, resolveServerMedia, previewServerImages = true }: {
messageId: string;
attachments: readonly BotGroupAttachment[];
align: 'left' | 'right';
onResolveRemoteMedia: ResolveRemoteMediaFn;
resolveServerMedia?: (id: string) => Promise<BotGroupAttachment>;
+ /** Cloud transcripts keep the tap-only contract in cloud-companions.md §3.1. */
+ previewServerImages?: boolean;
}) {
const { t } = useTranslation();
const { width } = useWindowDimensions();
const { accountGeneration } = useAuth();
+ const visibility = useContext(MessageListVisibilityContext);
+ const rowVisible = useMessageListItemVisible(messageId);
+ const previewVisible = previewServerImages && (!visibility || rowVisible);
const layout = useMemo(() => buildMessageContentLayout({ screenWidth: width }), [width]);
const items = useMemo(() => attachments.filter(attachment => !attachment.state).map(botGroupAttachmentForDisplay), [attachments]);
const gallery = useMemo(() => botGroupAttachmentGallery(messageId, items), [items, messageId]);
const runs = useMemo(() => botGroupAttachmentRuns(attachments), [attachments]);
const [openUrl, setOpenUrl] = useState<string | null>(null);
- if (resolveServerMedia) return <ServerAttachments key={`${accountGeneration}:${messageId}`} runs={runs} align={align} layout={layout} resolve={resolveServerMedia} />;
+ if (resolveServerMedia) return <ServerAttachments key={`${accountGeneration}:${messageId}`} runs={runs} visible={previewVisible} align={align} layout={layout} resolve={resolveServerMedia} />;
const open = (payload: MessagePayload) => {
if (payload.kind === 'media' && payload.media.kind === 'image') {
setOpenUrl(payload.media.url);
@@ -135,7 +141,8 @@ function drainPreviews() {
}
/** Image preview URLs live only in this mounted message; opening always re-authorizes. */
-function ServerAttachments({ runs, align, layout, resolve }: {
+function ServerAttachments({ runs, visible, align, layout, resolve }: {
+ visible: boolean;
align: 'left' | 'right';
runs: ReturnType<typeof botGroupAttachmentRuns>;
layout: ReturnType<typeof buildMessageContentLayout>;
@@ -145,23 +152,28 @@ function ServerAttachments({ runs, align, layout, resolve }: {
const { colors } = useTheme();
const [previews, setPreviews] = useState<Record<string, BotGroupAttachment>>({});
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) : []));
useEffect(() => {
let cancelled = false;
+ if (!visible) return;
for (const id of JSON.parse(previewIds) as string[]) {
authorizePreview(async () => {
- if (cancelled) return;
+ if (cancelled || previewsRef.current[id]) return;
try {
const value = await resolveRef.current(id);
const preview = value.category === 'image' ? value : { ...value, url: null };
- if (!cancelled) setPreviews(old => ({ ...old, [id]: preview }));
+ if (!cancelled) {
+ previewsRef.current = { ...previewsRef.current, [id]: preview };
+ setPreviews(previewsRef.current);
+ }
} catch { /* Keep the chip available for an explicit retry on tap. */ }
});
}
return () => { cancelled = true; };
- }, [previewIds]);
+ }, [previewIds, visible]);
const displayRuns = botGroupAttachmentRuns(runs.flatMap(run => run.kind === 'pending'
- ? [run.attachment] : run.attachments.map(item => previews[item.id] ?? item)));
+ ? [run.attachment] : run.attachments.map(item => previews[item.id] ?? { ...item, url: null })));
const [image, setImage] = useState<BotGroupAttachment | null>(null);
const [busy, setBusy] = useState<string | null>(null);
const pending = useRef(false);
diff --git a/apps/mobile/src/session/CloudCompanionScreen.tsx b/apps/mobile/src/session/CloudCompanionScreen.tsx
index 6a003f2e19..7f22532f3f 100644
--- a/apps/mobile/src/session/CloudCompanionScreen.tsx
+++ b/apps/mobile/src/session/CloudCompanionScreen.tsx
@@ -216,7 +216,7 @@ export function CloudCompanionScreen({ actorId, botId, deviceId, deviceName, tit
{messages.map((message, index) => {
const attachments = message.attachments.length
? <BotGroupMessageAttachments messageId={message.id} attachments={message.attachments} align={message.fromCompanion ? 'left' : 'right'}
- onResolveRemoteMedia={noRemoteMedia} resolveServerMedia={room.media} /> : null;
+ onResolveRemoteMedia={noRemoteMedia} resolveServerMedia={room.media} previewServerImages={false} /> : null;
if (!message.fromCompanion) return <View key={message.id} style={styles.userRow} testID="cloudCompanion.message.user">
<View style={styles.userColumn}>
{message.text ? <View style={[styles.userBubble, userBubbleColors && { backgroundColor: userBubbleColors.background, borderColor: userBubbleColors.border }]}>
diff --git a/apps/mobile/src/session/messageListVisibility.ts b/apps/mobile/src/session/messageListVisibility.ts
index 7a2e6caf3b..54e14034b7 100644
--- a/apps/mobile/src/session/messageListVisibility.ts
+++ b/apps/mobile/src/session/messageListVisibility.ts
@@ -1,4 +1,4 @@
-import { createContext, useCallback, useContext, useSyncExternalStore } from 'react';
+import { createContext, useCallback, useContext, useEffect, useMemo, useSyncExternalStore } from 'react';
/** One store per LegendList lifetime; only rows whose visibility changes are notified. */
export class MessageListVisibility {
@@ -46,3 +46,46 @@ export function useMessageListItemVisible(key: string): boolean {
// including the first layout notification arriving before this row subscribes.
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
}
+
+/** ScrollView rows report content coordinates; reuse the list's per-row subscriptions. */
+export class ScrollViewMessageVisibility extends MessageListVisibility {
+ private layouts = new Map<string, { y: number; height: number }>();
+ private offsetY = 0;
+ private height = 0;
+
+ setViewport(offsetY: number, height: number): void {
+ this.offsetY = offsetY;
+ this.height = height;
+ this.refresh();
+ }
+
+ setHeight(height: number): void {
+ this.height = height;
+ this.refresh();
+ }
+
+ setLayout(key: string, layout: { y: number; height: number }): void {
+ this.layouts.set(key, layout);
+ this.refresh();
+ }
+
+ retain(keys: readonly string[]): void {
+ const retained = new Set(keys);
+ for (const key of this.layouts.keys()) if (!retained.has(key)) this.layouts.delete(key);
+ this.refresh();
+ }
+
+ private refresh(): void {
+ this.update([...this.layouts].map(([key, layout]) => ({
+ key,
+ isViewable: this.height > 0 && layout.height > 0
+ && layout.y < this.offsetY + this.height && layout.y + layout.height > this.offsetY,
+ })));
+ }
+}
+
+export function useScrollViewMessageVisibility(scope: string, keys: readonly string[]): ScrollViewMessageVisibility {
+ const store = useMemo(() => new ScrollViewMessageVisibility(), [scope]);
+ useEffect(() => store.retain(keys), [store, keys]);
+ return store;
+}