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): show authorized chat server image previews

xd3ae8a913d3f8
diff --git a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
index 973c7fa413..49be279284 100644
--- a/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
+++ b/apps/mobile/src/__tests__/BotGroupChatScreen.test.tsx
@@ -1378,8 +1378,9 @@ 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();
- await click('attachment.file'); expect(h.chat.media).toHaveBeenCalledExactlyOnceWith('media');
+ 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);
expect(byId('lightbox')?.getAttribute('data-url')).toBe(attachment.url);
});
});
diff --git a/apps/mobile/src/__tests__/BotGroupMessageAttachments.test.tsx b/apps/mobile/src/__tests__/BotGroupMessageAttachments.test.tsx
index bc9491692a..b8fd049553 100644
--- a/apps/mobile/src/__tests__/BotGroupMessageAttachments.test.tsx
+++ b/apps/mobile/src/__tests__/BotGroupMessageAttachments.test.tsx
@@ -233,10 +233,12 @@ describe('group attachments the computer has not fetched yet', () => {
pending('gone', 'gone.md', 'unavailable'), ready('photo', 'photo.png')],
})));
const chips = [...host.querySelectorAll<HTMLElement>('[data-testid^="message.filePreviewButton"]')];
- expect(chips).toHaveLength(4);
+ expect(chips).toHaveLength(3);
expect(chips[0]!.parentElement).toBe(chips[1]!.parentElement);
- expect(chips[1]!.parentElement).not.toBe(chips[3]!.parentElement);
- expect(resolveServerMedia).not.toHaveBeenCalled();
+ expect(chips[1]!.parentElement).not.toBe(chips[2]!.parentElement);
+ expect(resolveServerMedia.mock.calls.map(([id]) => id)).toEqual(['first', 'second', 'photo']);
+ expect(host.querySelector('img')?.getAttribute('src')).toBe('https://example.invalid/signed/photo');
+ resolveServerMedia.mockClear();
expect(resolveMedia).not.toHaveBeenCalled();
await act(async () => chips[1]!.click());
await act(async () => chips[0]!.click());
@@ -244,7 +246,7 @@ describe('group attachments the computer has not fetched yet', () => {
expect(vi.mocked(openBrowserAsync).mock.calls.map(([url]) => url)).toEqual([
'https://example.invalid/signed/second', 'https://example.invalid/signed/first',
]);
- await act(async () => chips[3]!.click());
+ await act(async () => host!.querySelector<HTMLElement>('[data-testid="message.mediaPreviewButton"]')!.click());
expect(resolveServerMedia).toHaveBeenLastCalledWith('photo');
expect(host.querySelector('[data-testid="lightbox"]')?.getAttribute('data-url')).toBe('https://example.invalid/signed/photo');
expect(openBrowserAsync).toHaveBeenCalledTimes(2);
diff --git a/apps/mobile/src/__tests__/botGroupAttachmentLightbox.test.tsx b/apps/mobile/src/__tests__/botGroupAttachmentLightbox.test.tsx
index 624d056811..de5b2bb9c0 100644
--- a/apps/mobile/src/__tests__/botGroupAttachmentLightbox.test.tsx
+++ b/apps/mobile/src/__tests__/botGroupAttachmentLightbox.test.tsx
@@ -151,11 +151,12 @@ describe('Chat Server group image attachments (#5875)', () => {
id, name: '1.png', category: 'image', mimeType: 'image/png', size: 10, url: signedImageUrl, path: null,
}));
const container = await render({ resolveServerMedia });
- // The timeline keeps a file chip and never holds the signed address.
- expect(container.querySelector('img')).toBeNull();
- expect(container.innerHTML).not.toContain(signedImageUrl);
+ // Unknown media becomes a real thumbnail after authorization, without a tap.
+ expect(container.querySelector('img')?.getAttribute('src')).toBe(signedImageUrl);
+ expect(container.querySelector('[data-testid="message.imageLightbox"]')).toBeNull();
+ expect(resolveServerMedia).toHaveBeenCalledTimes(1);
- await click(container.querySelector('[data-testid="message.filePreviewButton"]'));
+ await click(container.querySelector('[data-testid="message.mediaPreviewButton"]'));
expect(resolveServerMedia).toHaveBeenCalledWith('media-1');
const viewer = container.querySelector('[data-testid="message.imageLightbox"]');
expect(viewer?.querySelector('img')?.getAttribute('src')).toBe(signedImageUrl);
@@ -165,10 +166,10 @@ describe('Chat Server group image attachments (#5875)', () => {
await click(container.querySelector('[data-testid="message.imageLightboxCloseButton"]'));
expect(container.querySelector('[data-testid="message.imageLightbox"]')).toBeNull();
- expect(container.innerHTML).not.toContain(signedImageUrl);
+ expect(container.querySelector('img')?.getAttribute('src')).toBe(signedImageUrl);
- await click(container.querySelector('[data-testid="message.filePreviewButton"]'));
- expect(resolveServerMedia).toHaveBeenCalledTimes(2);
+ await click(container.querySelector('[data-testid="message.mediaPreviewButton"]'));
+ expect(resolveServerMedia).toHaveBeenCalledTimes(3);
expect(container.querySelector('[data-testid="message.imageLightbox"] img')?.getAttribute('src')).toBe(signedImageUrl);
});
@@ -182,6 +183,33 @@ describe('Chat Server group image attachments (#5875)', () => {
expect(openBrowserAsync).toHaveBeenCalledWith(fileUrl);
expect(container.querySelector('[data-testid="message.imageLightbox"]')).toBeNull();
});
+
+ it('keeps failed preview authorization retryable on tap without showing a background alert', async () => {
+ const resolveServerMedia = vi.fn<() => Promise<BotGroupAttachment>>()
+ .mockRejectedValueOnce(new Error('offline'))
+ .mockResolvedValue({ ...serverAttachment, category: 'image', mimeType: 'image/png', url: signedImageUrl });
+ const container = await render({ resolveServerMedia });
+ expect(runtime.alerts).toEqual([]);
+ expect(container.querySelector('img')).toBeNull();
+ await click(container.querySelector('[data-testid="message.filePreviewButton"]'));
+ expect(container.querySelector('[data-testid="message.imageLightbox"] img')?.getAttribute('src')).toBe(signedImageUrl);
+ });
+
+ 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 => {
+ pending.push(value => resolve({ ...value, id }));
+ }));
+ const attachments = Array.from({ length: 8 }, (_, index) => ({ ...serverAttachment, id: `media-${index}` }));
+ const container = await render({ resolveServerMedia, attachments });
+ expect(resolveServerMedia).toHaveBeenCalledTimes(3);
+ await act(async () => root!.render(createElement(BotGroupMessageAttachments, {
+ messageId: 'replacement', align: 'right', attachments: [], onResolveRemoteMedia: vi.fn(), resolveServerMedia,
+ })));
+ await act(async () => pending.forEach(resolve => resolve({ ...serverAttachment, category: 'image', url: signedImageUrl })));
+ expect(resolveServerMedia).toHaveBeenCalledTimes(3);
+ expect(container.querySelector('img')).toBeNull();
+ });
});
describe('computer-hosted group image attachments', () => {
diff --git a/apps/mobile/src/__tests__/fileChipNameWidth.test.tsx b/apps/mobile/src/__tests__/fileChipNameWidth.test.tsx
index 6273d442ba..c256b5ccc8 100644
--- a/apps/mobile/src/__tests__/fileChipNameWidth.test.tsx
+++ b/apps/mobile/src/__tests__/fileChipNameWidth.test.tsx
@@ -129,7 +129,7 @@ async function renderServerGroup(align: 'left' | 'right', name: string) {
root = createRoot(host);
await act(async () => root!.render(createElement(BotGroupMessageAttachments, {
messageId: 'message-1', align, attachments: [attachment],
- onResolveRemoteMedia: vi.fn<ResolveRemoteMediaFn>(), resolveServerMedia: vi.fn(),
+ onResolveRemoteMedia: vi.fn<ResolveRemoteMediaFn>(), resolveServerMedia: vi.fn(async () => attachment),
})));
return host.querySelector('[data-testid^="message.filePreviewButton"]')!;
}
diff --git a/apps/mobile/src/session/BotGroupMessageAttachments.tsx b/apps/mobile/src/session/BotGroupMessageAttachments.tsx
index 1722bc8e4c..f15f2c4f15 100644
--- a/apps/mobile/src/session/BotGroupMessageAttachments.tsx
+++ b/apps/mobile/src/session/BotGroupMessageAttachments.tsx
@@ -3,8 +3,9 @@
*
* 复用会话消息的附件条(MessageRenderer 的 AttachmentStrip):图片按原始比例显示缩略图,
* 经远程媒体从电脑取件,点开进入与聊天相同的看图器;文件是「类型图标 + 文件名」的小条。
- * 旧电脑文件仍提示在电脑打开;服务器附件点击时独立授权,图片复用看图器,文件使用短期下载地址。
+ * 旧电脑文件仍提示在电脑打开;服务器图片授权后显示预览,点击时重新授权;文件使用短期下载地址。
*/
+import { useAuth } from '@/auth/AuthContext';
import { openBrowserAsync } from 'expo-web-browser';
import { Text } from '@/components/AppText';
import { spacing, textStyles, useTheme } from '@/theme';
@@ -51,12 +52,13 @@ export function BotGroupMessageAttachments({ messageId, attachments, align, onRe
}) {
const { t } = useTranslation();
const { width } = useWindowDimensions();
+ const { accountGeneration } = useAuth();
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 runs={runs} align={align} layout={layout} resolve={resolveServerMedia} />;
+ if (resolveServerMedia) return <ServerAttachments key={`${accountGeneration}:${messageId}`} runs={runs} align={align} layout={layout} resolve={resolveServerMedia} />;
const open = (payload: MessagePayload) => {
if (payload.kind === 'media' && payload.media.kind === 'image') {
setOpenUrl(payload.media.url);
@@ -117,7 +119,22 @@ function PendingAttachment({ attachment, align, layout }: {
</View>;
}
-/** Signed download URLs are acquired on tap and kept only in the open viewer. */
+// Bound passive authorization across mounted messages; no account data or URLs are cached here.
+const previewJobs: Array<() => Promise<void>> = [];
+let activePreviews = 0;
+function authorizePreview(job: () => Promise<void>) {
+ previewJobs.push(job);
+ drainPreviews();
+}
+function drainPreviews() {
+ while (activePreviews < 3 && previewJobs.length) {
+ const job = previewJobs.shift()!;
+ activePreviews++;
+ void job().finally(() => { activePreviews--; drainPreviews(); });
+ }
+}
+
+/** Image preview URLs live only in this mounted message; opening always re-authorizes. */
function ServerAttachments({ runs, align, layout, resolve }: {
align: 'left' | 'right';
runs: ReturnType<typeof botGroupAttachmentRuns>;
@@ -126,6 +143,25 @@ function ServerAttachments({ runs, align, layout, resolve }: {
}) {
const { t } = useTranslation();
const { colors } = useTheme();
+ const [previews, setPreviews] = useState<Record<string, BotGroupAttachment>>({});
+ const resolveRef = useRef(resolve); resolveRef.current = resolve;
+ const previewIds = JSON.stringify(runs.flatMap(run => run.kind === 'ready' ? run.attachments.map(item => item.id) : []));
+ useEffect(() => {
+ let cancelled = false;
+ for (const id of JSON.parse(previewIds) as string[]) {
+ authorizePreview(async () => {
+ if (cancelled) return;
+ try {
+ const value = await resolveRef.current(id);
+ const preview = value.category === 'image' ? value : { ...value, url: null };
+ if (!cancelled) setPreviews(old => ({ ...old, [id]: preview }));
+ } catch { /* Keep the chip available for an explicit retry on tap. */ }
+ });
+ }
+ return () => { cancelled = true; };
+ }, [previewIds]);
+ const displayRuns = botGroupAttachmentRuns(runs.flatMap(run => run.kind === 'pending'
+ ? [run.attachment] : run.attachments.map(item => previews[item.id] ?? item)));
const [image, setImage] = useState<BotGroupAttachment | null>(null);
const [busy, setBusy] = useState<string | null>(null);
const pending = useRef(false);
@@ -145,12 +181,17 @@ function ServerAttachments({ runs, align, layout, resolve }: {
};
return <>
{/* Stretch like a session strip, so the chip keeps the same width as in a task message. */}
- {runs.map(run => run.kind === 'pending'
+ {displayRuns.map(run => run.kind === 'pending'
? <PendingAttachment key={run.attachment.id} attachment={run.attachment} align={align} layout={layout} />
: <View key={run.attachments[0]!.id} style={styles.serverAttachment}>
- {/* No URL before tapping: every entry is a file chip, addressed by position rather than name. */}
- <AttachmentStrip attachments={run.attachments.map(attachment => ({ kind: 'file', name: attachment.name, previewable: false }))}
+ <AttachmentStrip attachments={run.attachments.map(botGroupAttachmentForDisplay)}
messageKey={run.attachments[0]!.id} align={align} layout={layout}
+ onOpen={payload => {
+ if (payload.kind === 'media') {
+ const attachment = run.attachments.find(item => item.url === payload.media.url);
+ if (attachment) void open(attachment.id);
+ }
+ }}
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} />