Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(mobile): preview group text attachments
ylliuuu66eb08414760de
diff --git a/apps/mobile/src/__tests__/BotGroupMessageAttachments.test.tsx b/apps/mobile/src/__tests__/BotGroupMessageAttachments.test.tsxindex b8fd049553..a2e3121fb2 100644--- a/apps/mobile/src/__tests__/BotGroupMessageAttachments.test.tsx+++ b/apps/mobile/src/__tests__/BotGroupMessageAttachments.test.tsx@@ -78,6 +78,18 @@ vi.mock('@/session/McpAppCard', () => ({ McpAppCard: () => null }));vi.mock('@/session/mermaidWebView', () => ({ MermaidDiagram: () => null }));vi.mock('@/session/mathWebView', () => ({ MathFormulaWebView: () => null }));vi.mock('@/session/mediaPlayerWebView', () => ({ RemoteMediaPlayerWebView: () => null }));+vi.mock('@/session/BotGroupTextAttachmentPreview', async () => {+ const React = await import('react');+ return {+ ...await vi.importActual<object>('@/session/BotGroupTextAttachmentPreview'),+ BotGroupTextAttachmentPreview: ({ attachmentId, fileName, kind }: { attachmentId: string; fileName: string; kind: string }) =>+ React.createElement('div', {+ 'data-testid': 'groupChat.server.textAttachmentPreview',+ 'data-attachment-id': attachmentId,+ 'data-kind': kind,+ }, fileName),+ };+});vi.mock('@/session/MarkdownBlockContent', () => ({ MarkdownBlockContent: () => null }));vi.mock('@/session/MessageActionSheet', () => ({ MessageActionSheet: () => null }));vi.mock('@/session/AuthorizationMessageCard', () => ({ AuthorizationMessageCard: () => null }));@@ -252,6 +264,35 @@ describe('group attachments the computer has not fetched yet', () => {expect(openBrowserAsync).toHaveBeenCalledTimes(2);});+ it('opens HTML, Markdown and JSON server files in the in-app preview instead of the browser', async () => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ const names: Record<string, string> = { html: 'report.html', markdown: 'notes.md', json: 'summary.json' };+ const resolveServerMedia = vi.fn(async (id: string) => ({+ ...ready(id, names[id]!),+ url: 'https://example.invalid/signed/' + id,+ }));+ await act(async () => root!.render(createElement(BotGroupMessageAttachments, {+ messageId: 'text-files', align: 'left', onResolveRemoteMedia: resolveMedia, resolveServerMedia,+ attachments: Object.entries(names).map(([id, name]) => ready(id, name)),+ })));++ for (const [index, [id, name, kind]] of [+ ['html', names.html, 'html'],+ ['markdown', names.markdown, 'markdown'],+ ['json', names.json, 'json'],+ ].entries()) {+ const chip = host.querySelectorAll<HTMLElement>('[data-testid^="message.filePreviewButton"]')[index]!;+ await act(async () => chip.click());+ const preview = host.querySelector('[data-testid="groupChat.server.textAttachmentPreview"]');+ expect(preview?.textContent).toBe(name);+ expect(preview?.getAttribute('data-attachment-id')).toBe(id);+ expect(preview?.getAttribute('data-kind')).toBe(kind);+ }+ expect(openBrowserAsync).not.toHaveBeenCalled();+ });+it('keeps the sent order: neighbours of one kind share a strip, each pending one stands alone', () => {const runs = botGroupAttachmentRuns([ready('a', 'a.txt'), pending('b', 'b.png', 'loading'), ready('c', 'c.txt'), ready('d', 'd.txt'), pending('e', 'e.md', 'unavailable')]);expect(summary(runs)).toEqual(['a', 'b:loading', 'c+d', 'e:unavailable']);diff --git a/apps/mobile/src/__tests__/BotGroupTextAttachmentPreview.test.tsx b/apps/mobile/src/__tests__/BotGroupTextAttachmentPreview.test.tsxnew file mode 100644index 0000000000..d2e931d38e--- /dev/null+++ b/apps/mobile/src/__tests__/BotGroupTextAttachmentPreview.test.tsx@@ -0,0 +1,213 @@+// @vitest-environment jsdom+import { act, createElement } from 'react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { createRoot, type Root } from 'react-dom/client';+import type { BotGroupAttachment } from '@cindy/maker-shared/botGroupChat';+import { openBrowserAsync } from 'expo-web-browser';+import { withDownloadedRemoteMediaFile } from '@/session/remoteMediaDiskCacheExpo';+import {+ BotGroupTextAttachmentPreview,+ botGroupTextAttachmentPreviewKind,+} from '@/session/BotGroupTextAttachmentPreview';++const downloadState = vi.hoisted(() => ({ text: '', tooLargeCount: 0, failedCount: 0 }));++vi.mock('@/session/remoteMediaDiskCacheExpo', () => ({ withDownloadedRemoteMediaFile: vi.fn() }));+vi.mock('expo-web-browser', () => ({ openBrowserAsync: vi.fn(async () => ({})) }));+vi.mock('lucide-react-native', () => ({+ ExternalLink: () => null,+ X: () => null,+}));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('@/theme', () => ({+ fontWeight: { semibold: '600' },+ lineHeight: { bodySmall: 20 },+ monoFont: 'monospace',+ radius: { pill: 9999 },+ spacing: { xs: 4, sm: 8, md: 12, lg: 16, xl: 24 },+ textStyles: { body: {}, footnote: {}, bodySmall: {}, caption: {} },+ typeScale: { bodySmall: 15 },+ useTheme: () => ({ colors: {+ border: 'border',+ surface: 'surface',+ surfaceElevated: 'surface-elevated',+ textPrimary: 'primary',+ textSecondary: 'secondary',+ textTertiary: 'tertiary',+ } }),+}));+vi.mock('@/components/AppText', async () => {+ const React = await import('react');+ return { Text: ({ children, testID }: any) => React.createElement('span', { 'data-testid': testID }, children) };+});+vi.mock('@/session/HtmlFileReader', async () => {+ const React = await import('react');+ return {+ HtmlFileReader: ({ html, javaScriptEnabled, testID }: any) => React.createElement('div', {+ 'data-testid': testID,+ 'data-javascript-enabled': String(javaScriptEnabled),+ }, html),+ };+});+vi.mock('@/session/MarkdownFileReader', async () => {+ const React = await import('react');+ return {+ MarkdownFileReader: ({ markdown, imageSources, testID }: any) => React.createElement('div', {+ 'data-testid': testID,+ 'data-image-source-count': String(imageSources?.size ?? 'missing'),+ }, markdown),+ };+});+vi.mock('react-native-safe-area-context', async () => {+ const React = await import('react');+ return { SafeAreaView: ({ children }: any) => React.createElement('div', null, children) };+});+vi.mock('react-native', async () => {+ const React = await import('react');+ const render = (tag: string) => ({ children, testID, accessibilityLabel, onPress }: any) => React.createElement(tag, {+ 'data-testid': testID,+ 'aria-label': accessibilityLabel,+ onClick: onPress,+ }, children);+ return {+ ActivityIndicator: render('span'),+ FlatList: ({ data, renderItem, testID }: any) => React.createElement('div', {+ 'data-testid': testID,+ 'data-row-count': String(data.length),+ }, ...data.slice(0, 5).map((item: string, index: number) => React.createElement(React.Fragment, { key: String(index) }, renderItem({ item, index })))),+ Modal: ({ children, visible }: any) => visible ? React.createElement('div', { 'data-testid': 'modal' }, children) : null,+ Pressable: render('button'),+ StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 },+ View: render('div'),+ };+});++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;+});++beforeEach(() => {+ downloadState.text = '';+ downloadState.tooLargeCount = 0;+ downloadState.failedCount = 0;+ vi.mocked(openBrowserAsync).mockClear();+ vi.mocked(withDownloadedRemoteMediaFile).mockReset().mockImplementation(async (+ _url,+ _mimeType,+ _maxBytes,+ read,+ _signal,+ onTooLarge,+ ) => {+ if (downloadState.tooLargeCount > 0) {+ downloadState.tooLargeCount -= 1;+ onTooLarge?.();+ return null;+ }+ if (downloadState.failedCount > 0) {+ downloadState.failedCount -= 1;+ return null;+ }+ return read({ text: async () => downloadState.text } as never);+ });+});++function makeAttachment(id: string, name: string, url: string): BotGroupAttachment {+ return { id, name, category: 'file', mimeType: 'application/octet-stream', size: 32, path: null, url };+}++async function renderPreview(kind: 'html' | 'markdown' | 'json', fileName: string, text: string, url = 'https://files.example.test/' + fileName) {+ downloadState.text = text;+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ const resolve = vi.fn(async (id: string, _signal?: AbortSignal) => makeAttachment(id, fileName, url));+ const onClose = vi.fn();+ await act(async () => {+ root!.render(createElement(BotGroupTextAttachmentPreview, {+ attachmentId: 'attachment-id', fileName, kind, resolve, onClose,+ }));+ await new Promise(done => setTimeout(done, 0));+ });+ return { container: host, resolve, onClose, url };+}++describe('bot-group text attachment preview kinds', () => {+ it.each([+ ['report.html', 'html'],+ ['report.htm', 'html'],+ ['notes.md', 'markdown'],+ ['notes.markdown', 'markdown'],+ ['summary.json', 'json'],+ ['page.xhtml', null],+ ['source.ts', null],+ ['archive.zip', null],+ ] as const)('classifies %s as %s', (name, expected) => {+ expect(botGroupTextAttachmentPreviewKind(name)).toBe(expected);+ });+});++describe('BotGroupTextAttachmentPreview', () => {+ it('renders HTML with JavaScript disabled after resolving a fresh HTTPS attachment', async () => {+ const { container, resolve } = await renderPreview('html', 'report.html', '<script>steal()</script><p>Report</p>');+ const reader = container.querySelector('[data-testid="groupChat.server.attachmentHtmlPreview"]');+ expect(resolve).toHaveBeenCalledWith('attachment-id', expect.any(AbortSignal));+ expect(reader?.getAttribute('data-javascript-enabled')).toBe('false');+ expect(reader?.textContent).toContain('Report');+ expect(openBrowserAsync).not.toHaveBeenCalled();+ });++ it('sends Markdown through the existing reader without allowing remote image sources', async () => {+ const body = '';+ const { container } = await renderPreview('markdown', 'notes.md', body);+ const reader = container.querySelector('[data-testid="groupChat.server.attachmentMarkdownPreview"]');+ expect(reader?.getAttribute('data-image-source-count')).toBe('0');+ expect(reader?.textContent).toBe(body);+ });++ it('shows a size error, retries with fresh authorization, then displays numbered JSON lines', async () => {+ downloadState.tooLargeCount = 1;+ const { container, resolve } = await renderPreview('json', 'summary.json', '{"first":1}\n{"second":2}');+ expect(container.querySelector('[data-testid="groupChat.server.attachmentPreview.too-large"]')).not.toBeNull();+ expect(container.querySelector('[data-testid="groupChat.server.attachmentPreviewOpenOutside"]')).not.toBeNull();+ const retry = container.querySelector('[data-testid="groupChat.server.attachmentPreviewRetry"]') as HTMLButtonElement;+ await act(async () => {+ retry.click();+ await new Promise(done => setTimeout(done, 0));+ });+ expect(resolve).toHaveBeenCalledTimes(2);+ expect(container.querySelector('[data-testid="groupChat.server.attachmentJsonPreview"]')?.textContent).toBe('1{"first":1}2{"second":2}');+ });++ it('caps excessive JSON line lists and tells the user when the preview is truncated', async () => {+ const body = Array.from({ length: 10_001 }, (_, index) => String(index)).join('\n');+ const { container } = await renderPreview('json', 'large.json', body);+ expect(container.querySelector('[data-testid="groupChat.server.attachmentJsonPreview"]')?.getAttribute('data-row-count')).toBe('10000');+ expect(container.textContent).toContain('groupChat.server.attachmentPreviewTruncated');+ });++ it('rejects local file URLs and offers browser fallback only for a user-selected binary Markdown file', async () => {+ const local = await renderPreview('html', 'report.html', '<p>private</p>', 'file:///private/secret.html');+ expect(local.container.querySelector('[data-testid="groupChat.server.attachmentPreview.failed"]')).not.toBeNull();+ expect(withDownloadedRemoteMediaFile).not.toHaveBeenCalled();+ act(() => root?.unmount());+ root = undefined;+ local.container.remove();+ host = undefined;++ const binary = await renderPreview('markdown', 'notes.md', String.fromCharCode(0) + 'binary');+ expect(binary.container.querySelector('[data-testid="groupChat.server.attachmentPreview.binary"]')).not.toBeNull();+ const openOutside = binary.container.querySelector('[data-testid="groupChat.server.attachmentPreviewOpenOutside"]') as HTMLButtonElement;+ await act(async () => openOutside.click());+ expect(openBrowserAsync).toHaveBeenCalledWith(binary.url);+ expect(binary.onClose).toHaveBeenCalledOnce();+ });+});diff --git a/apps/mobile/src/__tests__/remoteMediaDiskCacheExpo.test.ts b/apps/mobile/src/__tests__/remoteMediaDiskCacheExpo.test.tsindex bff9d3f002..8f53003e7f 100644--- a/apps/mobile/src/__tests__/remoteMediaDiskCacheExpo.test.ts+++ b/apps/mobile/src/__tests__/remoteMediaDiskCacheExpo.test.ts@@ -120,6 +120,28 @@ describe('versioned cache with the Expo adapter', () => {});describe('bounded temporary media downloads', () => {+ it('reports an over-limit download after cancelling and cleaning its temporary file', async () => {+ io.resumable.mockReturnValue(new Promise(() => {}));+ const onTooLarge = vi.fn();+ const read = vi.fn(async () => 'unexpected');+ const result = withDownloadedRemoteMediaFile(+ 'https://example.com/large.txt',+ 'text/plain',+ 8,+ read,+ new AbortController().signal,+ onTooLarge,+ );+ await vi.waitFor(() => expect(io.resumable).toHaveBeenCalledOnce());+ io.progress({ totalBytesWritten: 9 });+ expect(await result).toBeNull();+ expect(onTooLarge).toHaveBeenCalledOnce();+ expect(read).not.toHaveBeenCalled();+ expect(io.cancel).toHaveBeenCalled();+ expect(io.deleteAsync).toHaveBeenCalled();+ expect(io.remove).toHaveBeenCalledOnce();+ });+it('keeps a preview copy alive after transport staging expires, until its owner releases it', async () => {const { recordPeerMedia, releasePeerMedia } = await import('@/device-link/peerFileRegistry');const dispose = vi.fn();diff --git a/apps/mobile/src/__tests__/selectableMarkdownHtml.test.ts b/apps/mobile/src/__tests__/selectableMarkdownHtml.test.tsindex 2d559f5da9..aaece41825 100644--- a/apps/mobile/src/__tests__/selectableMarkdownHtml.test.ts+++ b/apps/mobile/src/__tests__/selectableMarkdownHtml.test.ts@@ -240,3 +240,14 @@ describe('阅读器里「有下划线 = 可点」不得出现反例(DESIGN.md §.not.toContain('<a href="mailto:');});});++describe('buildSelectableMarkdownHtml remote images', () => {+ it('does not expose remote image URLs when an explicit empty image allowlist is supplied', () => {+ const html = buildSelectableMarkdownHtml(+ '',+ { imageSources: new Map() },+ );+ expect(html).not.toContain('https://tracker.example.test/pixel.png');+ expect(html).toContain('<span class="xdt-image-chip">tracking pixel</span>');+ });+});diff --git a/apps/mobile/src/i18n/locales/en/groupChat.json b/apps/mobile/src/i18n/locales/en/groupChat.jsonindex 347747cb3d..dfc79e4056 100644--- a/apps/mobile/src/i18n/locales/en/groupChat.json+++ b/apps/mobile/src/i18n/locales/en/groupChat.json@@ -251,6 +251,14 @@"loadFailed": "Can’t load this group chat right now. Try again.","loadOlder": "Load Earlier Messages","attachmentFailed": "Couldn’t open the attachment. Try again.",+ "attachmentPreviewLoading": "Loading attachment…",+ "attachmentPreviewFailed": "Couldn’t preview this attachment. Try again.",+ "attachmentPreviewTooLarge": "This file is larger than 10 MB and can’t be previewed here.",+ "attachmentPreviewBinary": "This attachment isn’t readable text and can’t be previewed here.",+ "attachmentPreviewTruncated": "Only the first 10,000 lines are shown.",+ "attachmentPreviewRetry": "Try again",+ "attachmentPreviewOpenOutside": "Open in browser",+ "attachmentPreviewClose": "Close attachment preview","previewUnavailable": "Preview unavailable","endpointUnavailable": "Group chat service configuration is unavailable. Please retry."},diff --git a/apps/mobile/src/i18n/locales/ja/groupChat.json b/apps/mobile/src/i18n/locales/ja/groupChat.jsonindex 4e52a682e4..0881c96ec2 100644--- a/apps/mobile/src/i18n/locales/ja/groupChat.json+++ b/apps/mobile/src/i18n/locales/ja/groupChat.json@@ -251,6 +251,14 @@"loadFailed": "グループチャットを読み込めません。もう一度お試しください。","loadOlder": "以前のメッセージを読み込む","attachmentFailed": "添付ファイルを開けませんでした。もう一度お試しください。",+ "attachmentPreviewLoading": "添付ファイルを読み込み中…",+ "attachmentPreviewFailed": "この添付ファイルをプレビューできません。もう一度お試しください。",+ "attachmentPreviewTooLarge": "ファイルが10 MBを超えているため、スマートフォンではプレビューできません。",+ "attachmentPreviewBinary": "この添付ファイルは読み取り可能なテキストではないため、プレビューできません。",+ "attachmentPreviewTruncated": "最初の10,000行のみ表示しています。",+ "attachmentPreviewRetry": "再試行",+ "attachmentPreviewOpenOutside": "ブラウザーで開く",+ "attachmentPreviewClose": "添付ファイルのプレビューを閉じる","previewUnavailable": "プレビューを読み込めません","endpointUnavailable": "グループチャットのサービス設定を利用できません。再試行してください。"},diff --git a/apps/mobile/src/i18n/locales/ko/groupChat.json b/apps/mobile/src/i18n/locales/ko/groupChat.jsonindex 067b616638..eebb47868a 100644--- a/apps/mobile/src/i18n/locales/ko/groupChat.json+++ b/apps/mobile/src/i18n/locales/ko/groupChat.json@@ -251,6 +251,14 @@"loadFailed": "그룹 채팅을 불러올 수 없습니다. 다시 시도해 주세요.","loadOlder": "이전 메시지 불러오기","attachmentFailed": "첨부 파일을 열지 못했습니다. 다시 시도해 주세요.",+ "attachmentPreviewLoading": "첨부 파일을 불러오는 중…",+ "attachmentPreviewFailed": "이 첨부 파일을 미리 볼 수 없습니다. 다시 시도하세요.",+ "attachmentPreviewTooLarge": "파일이 10MB를 초과해 모바일에서 미리 볼 수 없습니다.",+ "attachmentPreviewBinary": "이 첨부 파일은 읽을 수 있는 텍스트가 아니어서 미리 볼 수 없습니다.",+ "attachmentPreviewTruncated": "처음 10,000줄만 표시합니다.",+ "attachmentPreviewRetry": "다시 시도",+ "attachmentPreviewOpenOutside": "브라우저에서 열기",+ "attachmentPreviewClose": "첨부 파일 미리보기 닫기","previewUnavailable": "미리보기를 불러올 수 없습니다","endpointUnavailable": "그룹 채팅 서비스 설정을 사용할 수 없습니다. 다시 시도해 주세요."},diff --git a/apps/mobile/src/i18n/locales/zh-CN/groupChat.json b/apps/mobile/src/i18n/locales/zh-CN/groupChat.jsonindex 0a17639b97..faa018a16b 100644--- a/apps/mobile/src/i18n/locales/zh-CN/groupChat.json+++ b/apps/mobile/src/i18n/locales/zh-CN/groupChat.json@@ -251,6 +251,14 @@"loadFailed": "暂时无法读取群聊,请重试。","loadOlder": "加载更早的消息","attachmentFailed": "附件打开失败,请重试。",+ "attachmentPreviewLoading": "正在读取附件…",+ "attachmentPreviewFailed": "无法预览此附件,请重试。",+ "attachmentPreviewTooLarge": "附件超过 10 MB,手机上无法预览。",+ "attachmentPreviewBinary": "此附件不是可阅读的文本,无法预览。",+ "attachmentPreviewTruncated": "仅显示前 10,000 行。",+ "attachmentPreviewRetry": "重试",+ "attachmentPreviewOpenOutside": "在浏览器中打开",+ "attachmentPreviewClose": "关闭附件预览","previewUnavailable": "暂时无法读取消息预览","endpointUnavailable": "群聊服务配置暂不可用,请重试。"},diff --git a/apps/mobile/src/i18n/locales/zh-TW/groupChat.json b/apps/mobile/src/i18n/locales/zh-TW/groupChat.jsonindex 864a34666d..3f307d4559 100644--- a/apps/mobile/src/i18n/locales/zh-TW/groupChat.json+++ b/apps/mobile/src/i18n/locales/zh-TW/groupChat.json@@ -251,6 +251,14 @@"loadFailed": "暫時無法讀取群聊,請重試。","loadOlder": "載入更早的訊息","attachmentFailed": "附件開啟失敗,請重試。",+ "attachmentPreviewLoading": "正在讀取附件…",+ "attachmentPreviewFailed": "無法預覽此附件,請重試。",+ "attachmentPreviewTooLarge": "附件超過 10 MB,手機上無法預覽。",+ "attachmentPreviewBinary": "此附件不是可閱讀的文字,無法預覽。",+ "attachmentPreviewTruncated": "僅顯示前 10,000 行。",+ "attachmentPreviewRetry": "重試",+ "attachmentPreviewOpenOutside": "在瀏覽器中開啟",+ "attachmentPreviewClose": "關閉附件預覽","previewUnavailable": "暫時無法讀取訊息預覽","endpointUnavailable": "群聊服務設定暫時無法使用,請重試。"},diff --git a/apps/mobile/src/session/BotGroupChatScreen.tsx b/apps/mobile/src/session/BotGroupChatScreen.tsxindex e3f06e042e..fe879cfea0 100644--- a/apps/mobile/src/session/BotGroupChatScreen.tsx+++ b/apps/mobile/src/session/BotGroupChatScreen.tsx@@ -5,7 +5,7 @@ import type { DurableOutboxRecord } from './durableOutbox';/*** 手机上的群聊页(docs/product-rules/bot-group-chat.md §8,对照桌面 BotGroupChatView.tsx):* 顶栏(叠放头像、群名、成员名单、群设置)+ 多作者时间线 + 输入框。用户消息的附件见- * BotGroupMessageAttachments(图片从电脑取缩略图,文件只显示名字)。+ * BotGroupMessageAttachments(图片从电脑取缩略图,文件显示名称并按格式预览或交系统应用)。** 群在电脑上,电脑执行全部规则;这里整页读电脑给的群快照(最新 100 条消息与涉及的安排),* 每次电脑推送变化就重读,不在本地拼时间线。分工的安排卡、交接文件、「下一步 · 继续」diff --git a/apps/mobile/src/session/BotGroupMessageAttachments.tsx b/apps/mobile/src/session/BotGroupMessageAttachments.tsxindex e8fc93d8db..756806cd3b 100644--- a/apps/mobile/src/session/BotGroupMessageAttachments.tsx+++ b/apps/mobile/src/session/BotGroupMessageAttachments.tsx@@ -3,7 +3,7 @@** 复用会话消息的附件条(MessageRenderer 的 AttachmentStrip):图片按原始比例显示缩略图,* 经远程媒体从电脑取件,点开进入与聊天相同的看图器;文件是「类型图标 + 文件名」的小条。- * 旧电脑文件仍提示在电脑打开;服务器图片授权后显示预览,点击时重新授权;文件使用短期下载地址。+ * 旧电脑文件仍提示在电脑打开;服务器图片授权后显示预览,文本文件点击后在端内安全阅读。*/import { useAuth } from '@/auth/AuthContext';import { openBrowserAsync } from 'expo-web-browser';@@ -14,6 +14,7 @@ import { ActivityIndicator, Alert, StyleSheet, View, useWindowDimensions } fromimport { useTranslation } from 'react-i18next';import type { BotGroupAttachment } from '@cindy/maker-shared/botGroupChat';import { ImageLightbox } from './ImageLightbox';+import { BotGroupTextAttachmentPreview, botGroupTextAttachmentPreviewKind } from './BotGroupTextAttachmentPreview';import { MessageListVisibilityContext, useMessageListItemVisible } from './messageListVisibility';import { AttachmentStrip } from './MessageRenderer';import { buildMessageContentLayout } from './messageContentLayout';@@ -220,12 +221,19 @@ function ServerAttachments({ runs, visible, previewServerImages, align, layout,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);+ const [textPreview, setTextPreview] = useState<{ id: string; name: string; kind: NonNullable<ReturnType<typeof botGroupTextAttachmentPreviewKind>> } | null>(null);const [busy, setBusy] = useState<string | null>(null);const pending = useRef(false);const mounted = useRef(true);useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []);const open = async (id: string) => {if (pending.current) return;+ const attachment = runs.flatMap(run => run.kind === 'ready' ? run.attachments : []).find(item => item.id === id);+ const previewKind = attachment?.category === 'file' ? botGroupTextAttachmentPreviewKind(attachment.name) : null;+ if (attachment && previewKind) {+ setTextPreview({ id, name: attachment.name, kind: previewKind });+ return;+ }pending.current = true; setBusy(id);try {const value = await resolve(id);@@ -274,6 +282,8 @@ function ServerAttachments({ runs, visible, previewServerImages, align, layout,</View>)}{image?.url ? <ImageLightbox images={botGroupAttachmentGallery(image.id, [botGroupAttachmentForDisplay(image)])}initialUrl={image.url} onClose={() => setImage(null)} /> : null}+ {textPreview ? <BotGroupTextAttachmentPreview key={textPreview.id} attachmentId={textPreview.id}+ fileName={textPreview.name} kind={textPreview.kind} resolve={resolve} onClose={() => setTextPreview(null)} /> : null}</>;}diff --git a/apps/mobile/src/session/BotGroupTextAttachmentPreview.tsx b/apps/mobile/src/session/BotGroupTextAttachmentPreview.tsxnew file mode 100644index 0000000000..e72601d93e--- /dev/null+++ b/apps/mobile/src/session/BotGroupTextAttachmentPreview.tsx@@ -0,0 +1,223 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { ExternalLink, X } from 'lucide-react-native';+import { ActivityIndicator, FlatList, Modal, Pressable, StyleSheet, View } from 'react-native';+import { SafeAreaView } from 'react-native-safe-area-context';+import { openBrowserAsync } from 'expo-web-browser';+import type { BotGroupAttachment } from '@cindy/maker-shared/botGroupChat';+import { extractRemoteFileExt, isHtmlFilePreviewCandidate, remoteFilePreviewKind } from '@cindy/maker-shared/file-preview';+import { Text } from '@/components/AppText';+import { HtmlFileReader } from '@/session/HtmlFileReader';+import { MarkdownFileReader } from '@/session/MarkdownFileReader';+import { withDownloadedRemoteMediaFile } from '@/session/remoteMediaDiskCacheExpo';+import { fontWeight, lineHeight, monoFont, radius, spacing, textStyles, typeScale, useTheme } from '@/theme';++const TEXT_ATTACHMENT_PREVIEW_MAX_BYTES = 10 * 1024 * 1024;+const JSON_ATTACHMENT_PREVIEW_MAX_LINES = 10_000;+const NO_EXTERNAL_IMAGES: ReadonlyMap<string, { uri: string }> = new Map();++export type BotGroupTextAttachmentPreviewKind = 'html' | 'markdown' | 'json';++type PreviewState =+ | { status: 'loading' }+ | { status: 'ready'; text: string }+ | { status: 'failed' }+ | { status: 'too-large'; url: string }+ | { status: 'binary'; url: string };++type ResolveServerMedia = (id: string, signal?: AbortSignal) => Promise<BotGroupAttachment>;++type ReadResult = { kind: 'text'; text: string } | { kind: 'binary' };++export function botGroupTextAttachmentPreviewKind(name: string): BotGroupTextAttachmentPreviewKind | null {+ if (remoteFilePreviewKind(name) !== 'text') return null;+ if (isHtmlFilePreviewCandidate(name)) return 'html';+ const extension = extractRemoteFileExt(name);+ if (extension === '.md' || extension === '.markdown') return 'markdown';+ if (extension === '.json') return 'json';+ return null;+}++export function BotGroupTextAttachmentPreview({ attachmentId, fileName, kind, resolve, onClose }: {+ attachmentId: string;+ fileName: string;+ kind: BotGroupTextAttachmentPreviewKind;+ resolve: ResolveServerMedia;+ onClose(): void;+}) {+ const { t } = useTranslation();+ const { colors } = useTheme();+ const [state, setState] = useState<PreviewState>({ status: 'loading' });+ const controller = useRef<AbortController | null>(null);+ const resolveRef = useRef(resolve);+ resolveRef.current = resolve;++ const load = useCallback(async () => {+ controller.current?.abort();+ const request = new AbortController();+ controller.current = request;+ setState({ status: 'loading' });+ let tooLarge = false;+ try {+ const attachment = await resolveRef.current(attachmentId, request.signal);+ if (request.signal.aborted) return;+ if (attachment.category !== 'file' || !attachment.url || !isCredentialFreeHttpsUrl(attachment.url)) {+ throw new Error('ATTACHMENT_PREVIEW_URL_INVALID');+ }+ const result = await withDownloadedRemoteMediaFile<ReadResult>(+ attachment.url,+ attachment.mimeType || 'application/octet-stream',+ TEXT_ATTACHMENT_PREVIEW_MAX_BYTES,+ async file => {+ const text = await file.text();+ return isLikelyBinaryText(text) ? { kind: 'binary' } : { kind: 'text', text };+ },+ request.signal,+ () => { tooLarge = true; },+ );+ if (request.signal.aborted) return;+ if (!result) {+ setState(tooLarge ? { status: 'too-large', url: attachment.url } : { status: 'failed' });+ return;+ }+ setState(result.kind === 'binary' ? { status: 'binary', url: attachment.url } : { status: 'ready', text: result.text });+ } catch {+ if (!request.signal.aborted) setState({ status: 'failed' });+ }+ }, [attachmentId]);++ useEffect(() => {+ void load();+ return () => { controller.current?.abort(); };+ }, [load]);++ const jsonPreview = useMemo(+ () => state.status === 'ready' && kind === 'json' ? splitJsonPreviewLines(state.text) : null,+ [kind, state],+ );+ const message = state.status === 'too-large'+ ? t('groupChat.server.attachmentPreviewTooLarge')+ : state.status === 'binary'+ ? t('groupChat.server.attachmentPreviewBinary')+ : t('groupChat.server.attachmentPreviewFailed');+ const openOutside = async (url: string) => {+ try {+ await openBrowserAsync(url);+ onClose();+ } catch {+ setState({ status: 'failed' });+ }+ };++ return (+ <Modal visible animationType="slide" presentationStyle="fullScreen" onRequestClose={onClose}>+ <SafeAreaView edges={['top', 'bottom']} style={[styles.fill, { backgroundColor: colors.surface }]}>+ <View style={[styles.header, { borderBottomColor: colors.border }]}>+ <Pressable+ accessibilityRole="button"+ accessibilityLabel={t('groupChat.server.attachmentPreviewClose')}+ onPress={onClose}+ style={styles.closeButton}+ testID="groupChat.server.attachmentPreviewCloseButton"+ >+ <X color={colors.textSecondary} size={20} />+ </Pressable>+ <Text numberOfLines={1} style={[textStyles.body, styles.title, { color: colors.textPrimary }]}>{fileName}</Text>+ </View>+ {state.status === 'loading' ? (+ <View style={styles.messageState} testID="groupChat.server.attachmentPreviewLoading">+ <ActivityIndicator color={colors.textSecondary} />+ <Text style={[textStyles.footnote, { color: colors.textSecondary }]}>{t('groupChat.server.attachmentPreviewLoading')}</Text>+ </View>+ ) : null}+ {state.status === 'failed' || state.status === 'too-large' || state.status === 'binary' ? (+ <View style={styles.messageState} testID={'groupChat.server.attachmentPreview.' + state.status}>+ <Text style={[textStyles.footnote, styles.stateCopy, { color: colors.textSecondary }]}>{message}</Text>+ {state.status === 'failed' || state.status === 'too-large' ? (+ <Pressable accessibilityRole="button" onPress={() => { void load(); }} style={[styles.action, { backgroundColor: colors.surfaceElevated, borderColor: colors.border }]} testID="groupChat.server.attachmentPreviewRetry">+ <Text style={[textStyles.body, { color: colors.textPrimary }]}>{t('groupChat.server.attachmentPreviewRetry')}</Text>+ </Pressable>+ ) : null}+ {kind !== 'html' && (state.status === 'too-large' || state.status === 'binary') ? (+ <Pressable accessibilityRole="button" onPress={() => { void openOutside(state.url); }} style={[styles.action, { backgroundColor: colors.surfaceElevated, borderColor: colors.border }]} testID="groupChat.server.attachmentPreviewOpenOutside">+ <ExternalLink color={colors.textPrimary} size={16} />+ <Text style={[textStyles.body, { color: colors.textPrimary }]}>{t('groupChat.server.attachmentPreviewOpenOutside')}</Text>+ </Pressable>+ ) : null}+ </View>+ ) : null}+ {state.status === 'ready' && kind === 'html' ? (+ <HtmlFileReader html={state.text} javaScriptEnabled={false} testID="groupChat.server.attachmentHtmlPreview" />+ ) : null}+ {state.status === 'ready' && kind === 'markdown' ? (+ <MarkdownFileReader markdown={state.text} imageSources={NO_EXTERNAL_IMAGES} testID="groupChat.server.attachmentMarkdownPreview" />+ ) : null}+ {state.status === 'ready' && kind === 'json' ? (+ <View style={styles.fill}>+ {jsonPreview?.truncated ? (+ <Text style={[textStyles.footnote, styles.truncated, { color: colors.textSecondary }]}>{t('groupChat.server.attachmentPreviewTruncated')}</Text>+ ) : null}+ <FlatList+ data={jsonPreview?.lines ?? []}+ keyExtractor={(_, index) => String(index)}+ renderItem={({ item, index }) => (+ <View style={styles.codeRow}>+ <Text selectable={false} style={[textStyles.caption, styles.lineNumber, { color: colors.textTertiary }]}>{index + 1}</Text>+ <Text selectable style={[styles.codeText, { color: colors.textPrimary }]}>{item || ' '}</Text>+ </View>+ )}+ style={styles.fill}+ contentContainerStyle={styles.codeList}+ testID="groupChat.server.attachmentJsonPreview"+ />+ </View>+ ) : null}+ </SafeAreaView>+ </Modal>+ );+}++function isCredentialFreeHttpsUrl(value: string): boolean {+ try {+ const url = new URL(value);+ return url.protocol === 'https:' && !url.username && !url.password;+ } catch {+ return false;+ }+}++function isLikelyBinaryText(value: string): boolean {+ return /[\x00-\x08\x0B\x0C\x0E-\x1F]/.test(value);+}++function splitJsonPreviewLines(text: string): { lines: string[]; truncated: boolean } {+ const lines: string[] = [];+ let start = 0;+ while (lines.length < JSON_ATTACHMENT_PREVIEW_MAX_LINES) {+ const end = text.indexOf('\n', start);+ if (end < 0) {+ const lastLine = text.slice(start);+ lines.push(lastLine.endsWith('\r') ? lastLine.slice(0, -1) : lastLine);+ return { lines, truncated: false };+ }+ const lineEnd = end > start && text.charCodeAt(end - 1) === 13 ? end - 1 : end;+ lines.push(text.slice(start, lineEnd));+ start = end + 1;+ }+ return { lines, truncated: start < text.length };+}++const styles = StyleSheet.create({+ fill: { flex: 1 },+ header: { minHeight: 56, flexDirection: 'row', alignItems: 'center', gap: spacing.sm, paddingHorizontal: spacing.md, borderBottomWidth: StyleSheet.hairlineWidth },+ closeButton: { width: 44, height: 44, alignItems: 'center', justifyContent: 'center' },+ title: { flex: 1, minWidth: 0, fontWeight: fontWeight.semibold },+ messageState: { flex: 1, alignItems: 'center', justifyContent: 'center', gap: spacing.md, padding: spacing.xl },+ stateCopy: { textAlign: 'center' },+ truncated: { paddingHorizontal: spacing.md, paddingTop: spacing.sm },+ action: { minHeight: 44, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: spacing.xs, paddingHorizontal: spacing.lg, borderRadius: radius.pill, borderWidth: StyleSheet.hairlineWidth },+ codeList: { paddingHorizontal: spacing.md, paddingVertical: spacing.sm },+ codeRow: { flexDirection: 'row', alignItems: 'flex-start' },+ lineNumber: { width: 40, paddingRight: spacing.sm, textAlign: 'right' },+ codeText: { flex: 1, minWidth: 0, fontFamily: monoFont, fontSize: typeScale.bodySmall, lineHeight: lineHeight.bodySmall },+});diff --git a/apps/mobile/src/session/MarkdownFileReader.tsx b/apps/mobile/src/session/MarkdownFileReader.tsxindex f26c376214..37de28b746 100644--- a/apps/mobile/src/session/MarkdownFileReader.tsx+++ b/apps/mobile/src/session/MarkdownFileReader.tsx@@ -34,6 +34,7 @@ export function MarkdownFileReader({targetLine,testID,viewportInsets,+ imageSources,}: {markdown: string;/** 由文件预览 pager 消费的明确横向翻页;纵向移动会让该手势失败给 WebView。 */@@ -44,6 +45,7 @@ export function MarkdownFileReader({targetLine?: number | null;testID?: string;viewportInsets?: BrowserInsets;+ imageSources?: ReadonlyMap<string, { uri: string }>;}) {const { t } = useTranslation();const { colors } = useTheme();@@ -57,6 +59,7 @@ export function MarkdownFileReader({[t],);const html = useMemo(() => buildSelectableMarkdownHtml(markdown, {+ ...(imageSources ? { imageSources } : {}),borderColor: colors.border,chipColor: colors.surfaceChip,inlineCodeColor: colors.chatInlineCodeText,@@ -79,7 +82,7 @@ export function MarkdownFileReader({},textColor: colors.textPrimary,...(targetLine ? { targetLine } : {}),- }), [colors, markdown, targetLine]);+ }), [colors, imageSources, markdown, targetLine]);// 回调走 ref:onQuoteSelection 引用变化(页面重渲)不应重建 handler,// 更不应让 WebView 重载。diff --git a/apps/mobile/src/session/remoteMediaDiskCacheExpo.ts b/apps/mobile/src/session/remoteMediaDiskCacheExpo.tsindex e987e909c7..f649948848 100644--- a/apps/mobile/src/session/remoteMediaDiskCacheExpo.ts+++ b/apps/mobile/src/session/remoteMediaDiskCacheExpo.ts@@ -181,6 +181,7 @@ export async function withDownloadedRemoteMediaFile<T>(maxBytes: number,read: (file: File) => Promise<T | null>,signal?: AbortSignal,+ onTooLarge?: () => void,): Promise<T | null> {const dir = new Directory(Paths.cache, SHARE_TMP_DIR_NAME);let target: File | null = null;@@ -191,10 +192,15 @@ export async function withDownloadedRemoteMediaFile<T>(target = new File(dir, `res-${unique}.${extOfMime(mimeType)}`);const file = await copyRemoteFile(url, target, signal, signal ? maxBytes : undefined);const size = file.size ?? 0;- if (signal?.aborted || size <= 0 || size > maxBytes) return null;+ if (signal?.aborted || size <= 0) return null;+ if (size > maxBytes) {+ onTooLarge?.();+ return null;+ }const result = await read(file);return signal?.aborted ? null : result;- } catch {+ } catch (error) {+ if (error instanceof Error && error.message === 'PREVIEW_TOO_LARGE') onTooLarge?.();return null;} finally {if (url.startsWith('file://')) releasePeerMedia(url);