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): harden group text attachment previews

ylliuuu66a4875a7598ac
diff --git a/apps/mobile/src/__tests__/BotGroupTextAttachmentPreview.test.tsx b/apps/mobile/src/__tests__/BotGroupTextAttachmentPreview.test.tsx
index d2e931d38e..92738df6d1 100644
--- a/apps/mobile/src/__tests__/BotGroupTextAttachmentPreview.test.tsx
+++ b/apps/mobile/src/__tests__/BotGroupTextAttachmentPreview.test.tsx
@@ -124,12 +124,18 @@ function makeAttachment(id: string, name: string, url: string): BotGroupAttachme
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) {
+async function renderPreview(kind: 'html' | 'markdown' | 'json', fileName: string, text: string, urls: string | readonly string[] = 'https://files.example.test/' + fileName) {
downloadState.text = text;
+ const resolvedUrls = typeof urls === 'string' ? [urls] : [...urls];
+ let resolveIndex = 0;
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 resolve = vi.fn(async (id: string, _signal?: AbortSignal) => {
+ const url = resolvedUrls[Math.min(resolveIndex, resolvedUrls.length - 1)]!;
+ resolveIndex += 1;
+ return makeAttachment(id, fileName, url);
+ });
const onClose = vi.fn();
await act(async () => {
root!.render(createElement(BotGroupTextAttachmentPreview, {
@@ -137,7 +143,7 @@ async function renderPreview(kind: 'html' | 'markdown' | 'json', fileName: strin
}));
await new Promise(done => setTimeout(done, 0));
});
- return { container: host, resolve, onClose, url };
+ return { container: host, resolve, onClose, url: resolvedUrls[0]! };
}
describe('bot-group text attachment preview kinds', () => {
@@ -165,6 +171,13 @@ describe('BotGroupTextAttachmentPreview', () => {
expect(openBrowserAsync).not.toHaveBeenCalled();
});
+ it('keeps valid HTML form-feed whitespace readable', async () => {
+ const { container } = await renderPreview('html', 'report.html', '<div\fclass="report">Form feed</div>');
+ const reader = container.querySelector('[data-testid="groupChat.server.attachmentHtmlPreview"]');
+ expect(reader).not.toBeNull();
+ expect(reader?.textContent).toContain('Form feed');
+ });
+
it('sends Markdown through the existing reader without allowing remote image sources', async () => {
const body = '![tracking pixel](https://tracker.example.test/pixel.png)';
const { container } = await renderPreview('markdown', 'notes.md', body);
@@ -194,6 +207,42 @@ describe('BotGroupTextAttachmentPreview', () => {
expect(container.textContent).toContain('groupChat.server.attachmentPreviewTruncated');
});
+ it('caps the rendered length of a single-line JSON file', async () => {
+ const { container } = await renderPreview('json', 'compact.json', '{"value":"' + 'x'.repeat(256_000) + '"}');
+ const list = container.querySelector('[data-testid="groupChat.server.attachmentJsonPreview"]');
+ expect(list?.textContent?.length).toBeLessThanOrEqual(4_097);
+ expect(container.textContent).toContain('groupChat.server.attachmentPreviewTruncated');
+ });
+
+ it('caps the total character budget across JSON lines', async () => {
+ const body = Array.from({ length: 32 }, () => 'x'.repeat(4_096)).join('\n');
+ const { container } = await renderPreview('json', 'many-lines.json', body);
+ const list = container.querySelector('[data-testid="groupChat.server.attachmentJsonPreview"]');
+ expect(list?.getAttribute('data-row-count')).toBe('25');
+ expect(container.textContent).toContain('groupChat.server.attachmentPreviewTruncated');
+ });
+
+ it('shows an explicit empty state for an empty text attachment', async () => {
+ const { container } = await renderPreview('json', 'empty.json', '');
+ expect(container.querySelector('[data-testid="groupChat.server.attachmentPreview.empty"]')).not.toBeNull();
+ expect(container.querySelector('[data-testid="groupChat.server.attachmentPreview.failed"]')).toBeNull();
+ });
+
+ it('renews the attachment URL before opening the browser fallback', async () => {
+ downloadState.tooLargeCount = 1;
+ const expiredUrl = 'https://files.example.test/expired.md';
+ const renewedUrl = 'https://files.example.test/renewed.md';
+ const { container, resolve, onClose } = await renderPreview('markdown', 'notes.md', 'body', [expiredUrl, renewedUrl]);
+ const openOutside = container.querySelector('[data-testid="groupChat.server.attachmentPreviewOpenOutside"]') as HTMLButtonElement;
+ await act(async () => {
+ openOutside.click();
+ await new Promise(done => setTimeout(done, 0));
+ });
+ expect(resolve).toHaveBeenCalledTimes(2);
+ expect(openBrowserAsync).toHaveBeenCalledWith(renewedUrl);
+ expect(onClose).toHaveBeenCalledOnce();
+ });
+
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();
diff --git a/apps/mobile/src/__tests__/remoteMediaDiskCacheExpo.test.ts b/apps/mobile/src/__tests__/remoteMediaDiskCacheExpo.test.ts
index 8f53003e7f..8b0d104646 100644
--- a/apps/mobile/src/__tests__/remoteMediaDiskCacheExpo.test.ts
+++ b/apps/mobile/src/__tests__/remoteMediaDiskCacheExpo.test.ts
@@ -197,6 +197,23 @@ describe('bounded temporary media downloads', () => {
expect(io.remove).toHaveBeenCalledOnce();
});
+ it('reads an empty text file when the caller explicitly allows it', async () => {
+ io.size = 0;
+ const read = vi.fn(async file => 'read-' + file.size);
+ const result = await withDownloadedRemoteMediaFile(
+ 'https://example.com/empty.json',
+ 'application/json',
+ 8,
+ read,
+ undefined,
+ undefined,
+ { allowEmpty: true },
+ );
+ expect(result).toBe('read-0');
+ expect(read).toHaveBeenCalledOnce();
+ expect(io.remove).toHaveBeenCalledOnce();
+ });
+
it.each(['download', 'read'])('removes partial files after a %s failure', async (failure) => {
const read = vi.fn(async () => { throw new Error('read failed'); });
if (failure === 'download') io.download.mockRejectedValueOnce(new Error('interrupted'));
diff --git a/apps/mobile/src/i18n/locales/en/groupChat.json b/apps/mobile/src/i18n/locales/en/groupChat.json
index dfc79e4056..94c9e3912a 100644
--- a/apps/mobile/src/i18n/locales/en/groupChat.json
+++ b/apps/mobile/src/i18n/locales/en/groupChat.json
@@ -255,7 +255,8 @@
"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.",
+ "attachmentPreviewTruncated": "Preview limited to 10,000 lines and 100,000 characters.",
+ "attachmentPreviewEmpty": "This file is empty.",
"attachmentPreviewRetry": "Try again",
"attachmentPreviewOpenOutside": "Open in browser",
"attachmentPreviewClose": "Close attachment preview",
diff --git a/apps/mobile/src/i18n/locales/ja/groupChat.json b/apps/mobile/src/i18n/locales/ja/groupChat.json
index 0881c96ec2..ec8e275932 100644
--- a/apps/mobile/src/i18n/locales/ja/groupChat.json
+++ b/apps/mobile/src/i18n/locales/ja/groupChat.json
@@ -255,7 +255,8 @@
"attachmentPreviewFailed": "この添付ファイルをプレビューできません。もう一度お試しください。",
"attachmentPreviewTooLarge": "ファイルが10 MBを超えているため、スマートフォンではプレビューできません。",
"attachmentPreviewBinary": "この添付ファイルは読み取り可能なテキストではないため、プレビューできません。",
- "attachmentPreviewTruncated": "最初の10,000行のみ表示しています。",
+ "attachmentPreviewTruncated": "プレビューは最大10,000行、100,000文字まで表示します。",
+ "attachmentPreviewEmpty": "このファイルは空です。",
"attachmentPreviewRetry": "再試行",
"attachmentPreviewOpenOutside": "ブラウザーで開く",
"attachmentPreviewClose": "添付ファイルのプレビューを閉じる",
diff --git a/apps/mobile/src/i18n/locales/ko/groupChat.json b/apps/mobile/src/i18n/locales/ko/groupChat.json
index eebb47868a..438517c7f8 100644
--- a/apps/mobile/src/i18n/locales/ko/groupChat.json
+++ b/apps/mobile/src/i18n/locales/ko/groupChat.json
@@ -255,7 +255,8 @@
"attachmentPreviewFailed": "이 첨부 파일을 미리 볼 수 없습니다. 다시 시도하세요.",
"attachmentPreviewTooLarge": "파일이 10MB를 초과해 모바일에서 미리 볼 수 없습니다.",
"attachmentPreviewBinary": "이 첨부 파일은 읽을 수 있는 텍스트가 아니어서 미리 볼 수 없습니다.",
- "attachmentPreviewTruncated": "처음 10,000줄만 표시합니다.",
+ "attachmentPreviewTruncated": "미리보기는 최대 10,000줄, 100,000자까지 표시합니다.",
+ "attachmentPreviewEmpty": "이 파일은 비어 있습니다.",
"attachmentPreviewRetry": "다시 시도",
"attachmentPreviewOpenOutside": "브라우저에서 열기",
"attachmentPreviewClose": "첨부 파일 미리보기 닫기",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/groupChat.json b/apps/mobile/src/i18n/locales/zh-CN/groupChat.json
index faa018a16b..516682b040 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/groupChat.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/groupChat.json
@@ -255,7 +255,8 @@
"attachmentPreviewFailed": "无法预览此附件,请重试。",
"attachmentPreviewTooLarge": "附件超过 10 MB,手机上无法预览。",
"attachmentPreviewBinary": "此附件不是可阅读的文本,无法预览。",
- "attachmentPreviewTruncated": "仅显示前 10,000 行。",
+ "attachmentPreviewTruncated": "预览最多显示 10,000 行、100,000 个字符。",
+ "attachmentPreviewEmpty": "此文件为空。",
"attachmentPreviewRetry": "重试",
"attachmentPreviewOpenOutside": "在浏览器中打开",
"attachmentPreviewClose": "关闭附件预览",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/groupChat.json b/apps/mobile/src/i18n/locales/zh-TW/groupChat.json
index 3f307d4559..bab3561d16 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/groupChat.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/groupChat.json
@@ -255,7 +255,8 @@
"attachmentPreviewFailed": "無法預覽此附件,請重試。",
"attachmentPreviewTooLarge": "附件超過 10 MB,手機上無法預覽。",
"attachmentPreviewBinary": "此附件不是可閱讀的文字,無法預覽。",
- "attachmentPreviewTruncated": "僅顯示前 10,000 行。",
+ "attachmentPreviewTruncated": "預覽最多顯示 10,000 行、100,000 個字元。",
+ "attachmentPreviewEmpty": "此檔案為空。",
"attachmentPreviewRetry": "重試",
"attachmentPreviewOpenOutside": "在瀏覽器中開啟",
"attachmentPreviewClose": "關閉附件預覽",
diff --git a/apps/mobile/src/session/BotGroupTextAttachmentPreview.tsx b/apps/mobile/src/session/BotGroupTextAttachmentPreview.tsx
index e72601d93e..808b3cf72b 100644
--- a/apps/mobile/src/session/BotGroupTextAttachmentPreview.tsx
+++ b/apps/mobile/src/session/BotGroupTextAttachmentPreview.tsx
@@ -14,6 +14,8 @@ import { fontWeight, lineHeight, monoFont, radius, spacing, textStyles, typeScal
const TEXT_ATTACHMENT_PREVIEW_MAX_BYTES = 10 * 1024 * 1024;
const JSON_ATTACHMENT_PREVIEW_MAX_LINES = 10_000;
+const JSON_ATTACHMENT_PREVIEW_MAX_CHARACTERS = 100_000;
+const JSON_ATTACHMENT_PREVIEW_MAX_LINE_CHARACTERS = 4_096;
const NO_EXTERNAL_IMAGES: ReadonlyMap<string, { uri: string }> = new Map();
export type BotGroupTextAttachmentPreviewKind = 'html' | 'markdown' | 'json';
@@ -21,9 +23,10 @@ export type BotGroupTextAttachmentPreviewKind = 'html' | 'markdown' | 'json';
type PreviewState =
| { status: 'loading' }
| { status: 'ready'; text: string }
+ | { status: 'empty' }
| { status: 'failed' }
- | { status: 'too-large'; url: string }
- | { status: 'binary'; url: string };
+ | { status: 'too-large' }
+ | { status: 'binary' };
type ResolveServerMedia = (id: string, signal?: AbortSignal) => Promise<BotGroupAttachment>;
@@ -74,13 +77,16 @@ export function BotGroupTextAttachmentPreview({ attachmentId, fileName, kind, re
},
request.signal,
() => { tooLarge = true; },
+ { allowEmpty: true },
);
if (request.signal.aborted) return;
if (!result) {
- setState(tooLarge ? { status: 'too-large', url: attachment.url } : { status: 'failed' });
+ setState(tooLarge ? { status: 'too-large' } : { status: 'failed' });
return;
}
- setState(result.kind === 'binary' ? { status: 'binary', url: attachment.url } : { status: 'ready', text: result.text });
+ setState(result.kind === 'binary'
+ ? { status: 'binary' }
+ : result.text.length === 0 ? { status: 'empty' } : { status: 'ready', text: result.text });
} catch {
if (!request.signal.aborted) setState({ status: 'failed' });
}
@@ -99,13 +105,24 @@ export function BotGroupTextAttachmentPreview({ attachmentId, fileName, kind, re
? t('groupChat.server.attachmentPreviewTooLarge')
: state.status === 'binary'
? t('groupChat.server.attachmentPreviewBinary')
- : t('groupChat.server.attachmentPreviewFailed');
- const openOutside = async (url: string) => {
+ : state.status === 'empty'
+ ? t('groupChat.server.attachmentPreviewEmpty')
+ : t('groupChat.server.attachmentPreviewFailed');
+ const openOutside = async () => {
+ controller.current?.abort();
+ const request = new AbortController();
+ controller.current = request;
+ setState({ status: 'loading' });
try {
- await openBrowserAsync(url);
- onClose();
+ 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');
+ }
+ await openBrowserAsync(attachment.url);
+ if (!request.signal.aborted) onClose();
} catch {
- setState({ status: 'failed' });
+ if (!request.signal.aborted) setState({ status: 'failed' });
}
};
@@ -130,7 +147,7 @@ export function BotGroupTextAttachmentPreview({ attachmentId, fileName, kind, re
<Text style={[textStyles.footnote, { color: colors.textSecondary }]}>{t('groupChat.server.attachmentPreviewLoading')}</Text>
</View>
) : null}
- {state.status === 'failed' || state.status === 'too-large' || state.status === 'binary' ? (
+ {state.status === 'failed' || state.status === 'too-large' || state.status === 'binary' || state.status === 'empty' ? (
<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' ? (
@@ -139,7 +156,7 @@ export function BotGroupTextAttachmentPreview({ attachmentId, fileName, kind, re
</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">
+ <Pressable accessibilityRole="button" onPress={() => { void openOutside(); }} 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>
@@ -187,22 +204,23 @@ function isCredentialFreeHttpsUrl(value: string): boolean {
}
function isLikelyBinaryText(value: string): boolean {
- return /[\x00-\x08\x0B\x0C\x0E-\x1F]/.test(value);
+ return /[\x00-\x08\x0B\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) {
+ let characters = 0;
+ while (lines.length < JSON_ATTACHMENT_PREVIEW_MAX_LINES && characters < JSON_ATTACHMENT_PREVIEW_MAX_CHARACTERS) {
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;
+ const lineEnd = end < 0 ? text.length : end > start && text.charCodeAt(end - 1) === 13 ? end - 1 : end;
+ const line = text.slice(start, lineEnd);
+ const visible = line.slice(0, Math.min(JSON_ATTACHMENT_PREVIEW_MAX_LINE_CHARACTERS, JSON_ATTACHMENT_PREVIEW_MAX_CHARACTERS - characters));
+ lines.push(visible);
+ characters += visible.length;
+ start = end < 0 ? text.length : end + 1;
+ if (visible.length < line.length) return { lines, truncated: true };
+ if (end < 0) return { lines, truncated: false };
}
return { lines, truncated: start < text.length };
}
diff --git a/apps/mobile/src/session/remoteMediaDiskCacheExpo.ts b/apps/mobile/src/session/remoteMediaDiskCacheExpo.ts
index f649948848..24dd0fbd61 100644
--- a/apps/mobile/src/session/remoteMediaDiskCacheExpo.ts
+++ b/apps/mobile/src/session/remoteMediaDiskCacheExpo.ts
@@ -182,6 +182,7 @@ export async function withDownloadedRemoteMediaFile<T>(
read: (file: File) => Promise<T | null>,
signal?: AbortSignal,
onTooLarge?: () => void,
+ options?: { allowEmpty?: boolean },
): Promise<T | null> {
const dir = new Directory(Paths.cache, SHARE_TMP_DIR_NAME);
let target: File | null = null;
@@ -192,7 +193,7 @@ 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) return null;
+ if (signal?.aborted || size < 0 || (size === 0 && !options?.allowEmpty)) return null;
if (size > maxBytes) {
onTooLarge?.();
return null;