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: 修复大文本预览并减少弱网后台争用和诊断噪声

Dashbb68157ddcac
diff --git a/apps/desktop/src/main/__tests__/text-file-preview.test.ts b/apps/desktop/src/main/__tests__/text-file-preview.test.ts
new file mode 100644
index 0000000000..584d5c86bc
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/text-file-preview.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from 'vitest';
+import { textFilePreviewResult, TEXT_PREVIEW_MAX_BYTES } from '../text-file-preview';
+
+// Unit: the IPC response builder must not put a legal 4–10 MiB preview into a
+// 4 MiB device message. No earlier test covered UTF-8/JSON expansion or opt-in.
+describe('text preview response', () => {
+ it.each([
+ Buffer.alloc(4 * 1024 * 1024, 97),
+ Buffer.alloc(TEXT_PREVIEW_MAX_BYTES, 97),
+ Buffer.from('中'.repeat(1_400_000)),
+ Buffer.from('"\\'.repeat(1_050_000)),
+ ])('offers file transfer for oversized encoded responses', (bytes) => {
+ const result = textFilePreviewResult(bytes, true);
+ expect('transferRequired' in result).toBe(true);
+ expect(result).toEqual({
+ success: true,
+ transferRequired: true,
+ size: bytes.length,
+ limitMb: 10,
+ });
+ });
+ it('keeps small and empty texts inline', () => {
+ for (const text of ['', '中文 " \\ hello', 'a'.repeat(4 * 1024 * 1024 - 128 * 1024)]) {
+ const bytes = Buffer.from(text);
+ expect(textFilePreviewResult(bytes, true)).toEqual({
+ success: true,
+ data: text,
+ size: bytes.length,
+ limitMb: 10,
+ });
+ }
+ });
+ it('preserves local and older callers that did not opt into file transfer', () => {
+ const bytes = Buffer.alloc(4 * 1024 * 1024, 97);
+ expect(textFilePreviewResult(bytes, false)).toEqual({
+ success: true,
+ data: bytes.toString(),
+ size: bytes.length,
+ limitMb: 10,
+ });
+ });
+ it('rejects files that grew past the preview limit after stat', () => {
+ expect(textFilePreviewResult(Buffer.alloc(TEXT_PREVIEW_MAX_BYTES + 1), true)).toEqual({
+ success: false,
+ reason: 'oversize',
+ size: TEXT_PREVIEW_MAX_BYTES + 1,
+ limitMb: 10,
+ });
+ });
+});
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 9b01c2874c..22d3eb36f9 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -90,6 +90,7 @@ import {
import { isAllowedBillingMailtoRequest } from '../shared/billing.js';
import path from 'node:path';
import fs from 'node:fs';
+import { textFilePreviewResult, TEXT_PREVIEW_LIMIT_MB } from './text-file-preview';
import os from 'node:os';
import { pipeline } from 'node:stream/promises';
import { execFile, execFileSync, spawn } from 'node:child_process';
@@ -7222,7 +7223,7 @@ const registerIpcHandlers = () => {
// ── TextLightbox IPC (text-lightbox F4/F5) ──
//
- // Reads a text file for the TextLightbox preview. Hard cap is 20 MB per
+ // Reads a text file for the TextLightbox preview. Hard cap is 10 MiB per
// text-lightbox spec; over-cap files are rejected with `oversize` so the
// renderer can render the Oversize body without re-statting the file.
// Reuses the same `isPathAllowed` blocklist as file-attachment IPCs.
@@ -7230,13 +7231,14 @@ const registerIpcHandlers = () => {
'text-file:read-preview',
async (
_event: Electron.IpcMainInvokeEvent,
- params: { filePath: string },
+ params: { filePath: string; allowFileTransfer?: boolean },
): Promise<{
success: boolean;
error?: string;
/** 'oversize' = file > MAX_PREVIEW_MB; renderer should switch to Oversize body. */
reason?: 'oversize' | 'not_found' | 'forbidden' | 'read_failed';
data?: string;
+ transferRequired?: boolean;
size: number;
/** Preview cap in MB — surfaced so renderer can render dynamic copy
* ("exceeding the {limitMb} MB preview limit") without hard-coding. */
@@ -7252,7 +7254,7 @@ const registerIpcHandlers = () => {
// (renderer reads `limitMb` to render dynamic copy).
// 10MB:预览走同步全文读 + 主线程高亮渲染,再大会明显卡;附件走路径透传
// 不占这条预览成本(附件层已不在 renderer 做大小限制),两者解耦。
- const MAX_PREVIEW_MB = 10;
+ const MAX_PREVIEW_MB = TEXT_PREVIEW_LIMIT_MB;
const MAX_PREVIEW = MAX_PREVIEW_MB * 1024 * 1024;
if (!filePath || !path.isAbsolute(filePath)) {
@@ -7294,8 +7296,8 @@ const registerIpcHandlers = () => {
return { success: false, reason: 'oversize', size, limitMb: MAX_PREVIEW_MB };
}
- const data = await fs.promises.readFile(filePath, 'utf8');
- return { success: true, data, size, limitMb: MAX_PREVIEW_MB };
+ const data = await fs.promises.readFile(filePath);
+ return textFilePreviewResult(data, params.allowFileTransfer === true);
} catch (err) {
return {
success: false,
diff --git a/apps/desktop/src/main/text-file-preview.ts b/apps/desktop/src/main/text-file-preview.ts
new file mode 100644
index 0000000000..aead806c99
--- /dev/null
+++ b/apps/desktop/src/main/text-file-preview.ts
@@ -0,0 +1,18 @@
+import { MAX_TRANSPORT_MESSAGE_BYTES } from '@cindy/device-link';
+
+export const TEXT_PREVIEW_LIMIT_MB = 10;
+export const TEXT_PREVIEW_MAX_BYTES = TEXT_PREVIEW_LIMIT_MB * 1024 * 1024;
+
+/** Keep envelope/codec metadata outside the body budget; count UTF-8 JSON, not characters. */
+export function textFilePreviewResult(bytes: Buffer, allowFileTransfer: boolean) {
+ const metadata = { size: bytes.byteLength, limitMb: TEXT_PREVIEW_LIMIT_MB };
+ if (bytes.byteLength > TEXT_PREVIEW_MAX_BYTES)
+ return { success: false, reason: 'oversize' as const, ...metadata };
+ const result = { success: true, data: bytes.toString('utf8'), ...metadata };
+ if (
+ allowFileTransfer &&
+ Buffer.byteLength(JSON.stringify(result), 'utf8') > MAX_TRANSPORT_MESSAGE_BYTES - 64 * 1024
+ )
+ return { success: true, transferRequired: true, ...metadata };
+ return result;
+}
diff --git a/apps/mobile/app/files/preview/[sessionId].tsx b/apps/mobile/app/files/preview/[sessionId].tsx
index 537d655a33..d01f62d867 100644
--- a/apps/mobile/app/files/preview/[sessionId].tsx
+++ b/apps/mobile/app/files/preview/[sessionId].tsx
@@ -502,14 +502,16 @@ function RemoteFilePreviewContent() {
// absPath 单文件模式走 text-file:read-preview(被控端绝对路径文本通道),
// 回包适配成 readFile 同构结果,文本页零分支。
const readTextFile = useCallback(
- (relPath: string): Promise<FileBrowserReadFileResult> =>
+ (relPath: string, signal?: AbortSignal): Promise<FileBrowserReadFileResult> =>
withTransientRemoteRetry(async () => {
+ if (signal?.aborted) throw new Error('PREVIEW_CANCELLED');
await openLink(deviceId);
+ if (signal?.aborted) throw new Error('PREVIEW_CANCELLED');
const startedAt = Date.now();
const channel = singleAbsPath ? 'text-preview' : 'read-file';
try {
const res = singleAbsPath
- ? adaptTextFilePreviewResult(singleAbsPath, await maker.fs.readTextFilePreview(singleAbsPath))
+ ? adaptTextFilePreviewResult(singleAbsPath, await maker.fs.readTextFilePreview(singleAbsPath, { signal }))
: await maker.fileBrowser.readFile(workdir, relPath, { acceptGzip: true });
// Whole-text reads share the relay with rendered-HTML resource requests; size only.
// gzip 回包是压缩数据的 base64,与纯文本字符数分字段记录,避免两种口径混用。
@@ -823,7 +825,7 @@ function FilePreviewPage({
onOpenLightbox(url: string): void;
/** chat-text-quote:markdown 渲染态的选中引用回调(仅文本页消费)。 */
onQuoteSelection?: (text: string) => void;
- readTextFile(relPath: string): Promise<FileBrowserReadFileResult>;
+ readTextFile(relPath: string, signal?: AbortSignal): Promise<FileBrowserReadFileResult>;
recoveryEpoch: number;
targetLine: number | null;
/** 是否真正可见的当前页(可执行渲染态的挂载门,见调用处说明)。 */
@@ -1158,7 +1160,7 @@ function TextPreviewPage({
/** chat-text-quote:markdown 渲染态的选中引用回调(源码态暂不支持,见 PR 说明)。 */
onQuoteSelection?: (text: string) => void;
/** 屏级注入:readFile 带瞬断重试 + openLink(与列表/搜索/导出同路径)。 */
- readTextFile(relPath: string): Promise<FileBrowserReadFileResult>;
+ readTextFile(relPath: string, signal?: AbortSignal): Promise<FileBrowserReadFileResult>;
targetLine: number | null;
/** 是否真正可见的当前页:HTML 渲染态只在可见时挂 WebView(文本预取不受限)。 */
visible: boolean;
@@ -1208,9 +1210,10 @@ function TextPreviewPage({
if (!active || !wantsText || loadedRef.current || !workdir) return;
loadedRef.current = true;
let cancelled = false;
+ const abort = new AbortController();
const unavailable = (value: TextPreviewState) => setState((previous) =>
previous.status === 'ready' ? previous : value);
- void readTextFile(item.relPath)
+ void readTextFile(item.relPath, abort.signal)
.then((res: FileBrowserReadFileResult) => {
if (cancelled) return;
if (!res.ok) {
@@ -1257,6 +1260,7 @@ function TextPreviewPage({
});
return () => {
cancelled = true;
+ abort.abort();
loadedRef.current = false;
};
}, [active, wantsText, cacheable, cacheScope, deviceId, item.relPath, richKind, readTextFile, t, workdir, textReloadEpoch]);
diff --git a/apps/mobile/src/__tests__/historyViewProvider.test.tsx b/apps/mobile/src/__tests__/historyViewProvider.test.tsx
index 0c42fe0501..9ef176ad95 100644
--- a/apps/mobile/src/__tests__/historyViewProvider.test.tsx
+++ b/apps/mobile/src/__tests__/historyViewProvider.test.tsx
@@ -14,6 +14,8 @@ import {
} from '@cindy/device-link';
import { isHistoryViewUnavailable } from '@cindy/maker-shared/message-window';
import { DeviceLinkProvider, useDeviceLink, type DeviceLinkContextValue } from '../device-link/DeviceLinkContext';
+import { useMobileMakerTransport } from '../device-link/useMobileMakerTransport';
+import type { MobileMakerTransport } from '../device-link/mobileMakerTransport';
import { acquireDeviceSendSlot, resetDeviceResponsivenessTracking, settleDeviceSend, unresponsiveDevicesStore } from '../device-link/unresponsiveDevicesStore';
import { revokedDevicesStore } from '../device-link/revokedDevicesStore';
import { localNetworkStore, type NetworkState } from '../device-link/localNetworkStatus';
@@ -108,7 +110,8 @@ const accepted = (capabilities?: string[]): LinkAcceptPayload => ({ appVersion:
const historyChannel = 'local-db:messages:view';
let root: Root;
let context: DeviceLinkContextValue;
-function Probe() { context = useDeviceLink(); return null; }
+let maker: MobileMakerTransport;
+function Probe() { context = useDeviceLink(); maker = useMobileMakerTransport('host'); return null; }
function render() { root.render(createElement(DeviceLinkProvider, null, createElement(Probe))); }
function deferredAccept() {
let resolve!: (value: LinkAcceptPayload) => void;
@@ -284,6 +287,35 @@ describe('Provider device roster reads', () => {
});
describe('Provider queued send guards', () => {
+ it('opts the production text reader into file transfer and honors pre-cancelled reads', async () => {
+ const client = transport.clients[0];
+ client.invoke.mockResolvedValue({ ok: true, result: { success: true, data: 'text', size: 4 } });
+ await act(async () => {
+ expect(await maker.fs.readTextFilePreview('/text.txt')).toMatchObject({ data: 'text' });
+ });
+ expect(client.invoke).toHaveBeenCalledWith('host', {
+ channel: 'text-file:read-preview', args: [{ filePath: '/text.txt', allowFileTransfer: true }],
+ }, undefined, expect.any(Object));
+ client.invoke.mockClear();
+ const abort = new AbortController(); abort.abort();
+ await expect(maker.fs.readTextFilePreview('/text.txt', { signal: abort.signal })).rejects.toThrow('PREVIEW_CANCELLED');
+ expect(client.invoke).not.toHaveBeenCalled();
+ });
+ // Unit: resource auto-refresh must reach the shared scheduler as background;
+ // the previous adapter dropped that local hint and consumed foreground slots.
+ it('preserves background intent without changing ordinary resource reads', async () => {
+ const client = transport.clients[0];
+ await act(async () => {
+ await context.invoke('host', 'maker:remote-resources:manifest', [], { background: true });
+ await context.invoke('host', 'maker:remote-resources:manifest', []);
+ });
+ const calls = client.invoke.mock.calls.filter(([, payload]) => payload.channel === 'maker:remote-resources:manifest');
+ expect(calls.map(call => call[3]?.background)).toEqual([true, undefined]);
+ expect(calls.map(call => call[1])).toEqual([
+ { channel: 'maker:remote-resources:manifest', args: [] },
+ { channel: 'maker:remote-resources:manifest', args: [] },
+ ]);
+ });
it('rejects a write cancelled after admission without sending or counting a remote timeout', async () => {
resetDeviceResponsivenessTracking();
const client = transport.clients[0];
diff --git a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
index cf55e8eca9..71b9035f31 100644
--- a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
+++ b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
@@ -39,6 +39,26 @@ function harness() {
}
describe("mobile maker transport", () => {
+ // Unit: a visible text snapshot is already cached by the reader. Its refresh
+ // must await the Host, while retaining the existing confirmed-version cache.
+ it('revalidates text without returning stale bytes or invalidating a confirmed version', async () => {
+ setMobileAuthOwner('text-revalidation');
+ const stale = { ossKey: '', size: 3, mimeType: 'text/plain', version: 'a'.repeat(64), inlineBase64: 'b2xk' };
+ const current = { ...stale, version: 'b'.repeat(64), inlineBase64: 'bmV3' };
+ fileCache.readLatest.mockResolvedValue(stale);
+ fileCache.readInline.mockResolvedValue(current);
+ const invoke = vi.fn(async () => ({ ...current, inlineBase64: undefined, transferRequired: true }));
+ const maker = createMobileMakerTransport({ deviceId: 'text-host', invoke: invoke as RemoteInvoke });
+ try {
+ expect(await maker.fetchRemoteMedia('xdt-file://open?path=/text.txt', { stream: false, revalidate: true })).toEqual(current);
+ expect(fileCache.readLatest).not.toHaveBeenCalled();
+ expect(fileCache.invalidate).not.toHaveBeenCalled();
+ expect(invoke).toHaveBeenCalledOnce();
+ } finally {
+ fileCache.readLatest.mockReset(); fileCache.readInline.mockReset();
+ authOwnerTesting.reset(); vi.clearAllMocks();
+ }
+ });
it('reads through an older shared host without sending unknown metadata-only fields', async () => {
const result = { ossKey: '', size: 3, mimeType: 'text/plain', inlineBase64: 'YWJj' };
const invoke = vi.fn(async (_device, _channel, [request]) => {
diff --git a/apps/mobile/src/__tests__/remoteAbsFileFetch.test.ts b/apps/mobile/src/__tests__/remoteAbsFileFetch.test.ts
index 4e5ced4816..ef6e309717 100644
--- a/apps/mobile/src/__tests__/remoteAbsFileFetch.test.ts
+++ b/apps/mobile/src/__tests__/remoteAbsFileFetch.test.ts
@@ -5,10 +5,75 @@ import {
adaptTextFilePreviewResult,
fetchRemoteAbsFileToUrl,
fetchRemoteAbsFileOnce,
+ readRemoteTextFilePreview,
type RemoteAbsFileFetchDeps,
} from '@/session/remoteAbsFileFetch';
import type { RemoteTextFilePreviewResult } from '@/device-link/mobileMakerTransport';
import { clearPeerMedia, recordPeerMedia } from '@/device-link/peerFileRegistry';
+const textIO = vi.hoisted(() => ({ size: 5, text: 'hello', read: vi.fn() }));
+vi.mock('@/session/remoteMediaDiskCacheExpo', () => ({
+ withDownloadedRemoteMediaFile: async (_url: string, _mime: string, _max: number, read: (file: unknown) => unknown) => {
+ textIO.read();
+ return read({ size: textIO.size, text: async () => textIO.text });
+ },
+}));
+
+// Unit: exercise the actual RPC → file fallback, rather than only adapting the
+// RPC shape. A legal large reply used to fail before reaching the text reader.
+describe('large text preview', () => {
+ const setup = () => {
+ const { deps, fetchRemoteMedia, presignGet } = makeDeps();
+ const readPreview = vi.fn<() => Promise<RemoteTextFilePreviewResult>>(async () => ({ success: true, transferRequired: true, size: 5 }));
+ const deleteOssObject = vi.fn();
+ textIO.size = 5; textIO.text = 'hello'; textIO.read.mockClear();
+ fetchRemoteMedia.mockResolvedValue({ ossKey: 'oss/text', size: 5, mimeType: 'text/plain' });
+ return { deps: { ...deps, readPreview, deleteOssObject, isCurrent: () => true }, fetchRemoteMedia, presignGet, readPreview, deleteOssObject };
+ };
+ it.each([false, true])('reads and cleans transferred text, legacy error=%s', async legacy => {
+ const h = setup();
+ if (legacy) h.readPreview.mockRejectedValue(Object.assign(new Error('too large'), { code: 'PAYLOAD_TOO_LARGE' }));
+ expect(await readRemoteTextFilePreview(h.deps, '/tmp/text.txt')).toEqual({ success: true, data: 'hello', size: 5, limitMb: 10 });
+ expect(h.fetchRemoteMedia.mock.calls[0][0]).toContain('maxBytes=10485760');
+ expect(h.deleteOssObject).toHaveBeenCalledExactlyOnceWith('oss/text');
+ });
+ it.each(['forbidden', 'not_found', 'oversize'] as const)('does not transfer after host returns %s', async reason => {
+ const h = setup();
+ const result = { success: false, reason, size: 12 };
+ h.readPreview.mockResolvedValue(result);
+ expect(await readRemoteTextFilePreview(h.deps, '/tmp/text.txt')).toBe(result);
+ expect(h.fetchRemoteMedia).not.toHaveBeenCalled();
+ });
+ it('keeps small text inline and does not retry connection failures as file reads', async () => {
+ const h = setup();
+ h.readPreview.mockResolvedValue({ success: true, data: '', size: 0 });
+ expect(await readRemoteTextFilePreview(h.deps, '/tmp/text.txt')).toMatchObject({ data: '' });
+ h.readPreview.mockRejectedValue(new Error('offline'));
+ await expect(readRemoteTextFilePreview(h.deps, '/tmp/text.txt')).rejects.toThrow('offline');
+ expect(h.fetchRemoteMedia).not.toHaveBeenCalled();
+ });
+ it('stops before transferring when cancelled during the RPC', async () => {
+ const h = setup();
+ const abort = new AbortController();
+ h.readPreview.mockImplementation(async () => { abort.abort(); return { success: true, transferRequired: true, size: 5 }; });
+ await expect(readRemoteTextFilePreview(h.deps, '/tmp/text.txt', abort.signal)).rejects.toThrow('PREVIEW_CANCELLED');
+ expect(h.fetchRemoteMedia).not.toHaveBeenCalled();
+ });
+ it('cleans an uploaded object even when presigning fails', async () => {
+ const h = setup();
+ h.presignGet.mockRejectedValue(new Error('offline'));
+ await expect(readRemoteTextFilePreview(h.deps, '/tmp/text.txt')).rejects.toThrow('offline');
+ expect(h.deleteOssObject).toHaveBeenCalledExactlyOnceWith('oss/text');
+ });
+ it('rejects truncated data and releases the direct transfer staging file', async () => {
+ const h = setup();
+ const media = { ossKey: '', size: 6, mimeType: 'text/plain' };
+ const dispose = vi.fn();
+ recordPeerMedia(media, 'file:///text-staged', dispose);
+ h.fetchRemoteMedia.mockResolvedValue(media);
+ await expect(readRemoteTextFilePreview(h.deps, '/tmp/text.txt')).rejects.toThrow('PREVIEW_CHANGED');
+ expect(dispose).toHaveBeenCalledOnce();
+ });
+});
// 文案已 i18n 化;固定 zh-CN 让字面量断言与语言环境解耦(全局 mock 默认 en-US)。
beforeAll(async () => {
@@ -20,7 +85,7 @@ function makeDeps(overrides: Partial<{
getUrl: string;
expiresAt: string;
}> = {}) {
- const fetchRemoteMedia = vi.fn(async () => ({
+ const fetchRemoteMedia = vi.fn<RemoteAbsFileFetchDeps['maker']['fetchRemoteMedia']>(async () => ({
ossKey: overrides.ossKey ?? 'oss/abc',
mimeType: 'image/png',
size: 1234,
diff --git a/apps/mobile/src/__tests__/remoteMediaDiskCacheExpo.test.ts b/apps/mobile/src/__tests__/remoteMediaDiskCacheExpo.test.ts
index 6b7213c2a7..bff9d3f002 100644
--- a/apps/mobile/src/__tests__/remoteMediaDiskCacheExpo.test.ts
+++ b/apps/mobile/src/__tests__/remoteMediaDiskCacheExpo.test.ts
@@ -20,13 +20,14 @@ const io = vi.hoisted(() => ({
resumable: vi.fn(),
cancel: vi.fn(async () => undefined),
deleteAsync: vi.fn(async () => undefined),
+ progress: (_value: { totalBytesWritten: number }) => {},
}));
vi.mock('expo-file-system/legacy', () => ({
- createDownloadResumable: (url: string, uri: string) => ({
- downloadAsync: () => io.resumable(url, uri),
- cancelAsync: io.cancel,
- }),
+ createDownloadResumable: (url: string, uri: string, _options?: unknown, progress?: typeof io.progress) => {
+ io.progress = progress ?? (() => {});
+ return { downloadAsync: () => io.resumable(url, uri), cancelAsync: io.cancel };
+ },
deleteAsync: io.deleteAsync,
}));
@@ -142,6 +143,30 @@ describe('bounded temporary media downloads', () => {
expect(io.remove).toHaveBeenCalledExactlyOnceWith(io.download.mock.calls[0]![1].uri);
});
+ // Unit: large text fallback must stop a slow/oversized OSS download and clean
+ // its partial file. Existing cases covered cancellation only for sharing.
+ it.each(['cancel', 'oversize'] as const)('does not deliver preview bytes after %s', async reason => {
+ const abort = new AbortController();
+ io.resumable.mockReturnValue(new Promise(() => {}));
+ const read = vi.fn();
+ const result = withDownloadedRemoteMediaFile('https://example.com/text', 'text/plain', 8, read, abort.signal);
+ await vi.waitFor(() => expect(io.resumable).toHaveBeenCalledOnce());
+ if (reason === 'cancel') abort.abort();
+ else io.progress({ totalBytesWritten: 9 });
+ expect(await result).toBeNull();
+ expect(read).not.toHaveBeenCalled();
+ expect(io.cancel).toHaveBeenCalled();
+ expect(io.deleteAsync).toHaveBeenCalledOnce();
+ });
+
+ it('discards a text result cancelled while the file was being read', async () => {
+ const abort = new AbortController();
+ const result = await withDownloadedRemoteMediaFile('file:///peer/staged', 'text/plain', 8,
+ async () => { abort.abort(); return 'late text'; }, abort.signal);
+ expect(result).toBeNull();
+ expect(io.remove).toHaveBeenCalledOnce();
+ });
+
it.each([0, 9])('removes a %s-byte download without exposing it to the consumer', async (size) => {
io.size = size;
const read = vi.fn();
diff --git a/apps/mobile/src/debug/localDiagnostics.test.ts b/apps/mobile/src/debug/localDiagnostics.test.ts
index 8a29ddb130..a8d5eaf45e 100644
--- a/apps/mobile/src/debug/localDiagnostics.test.ts
+++ b/apps/mobile/src/debug/localDiagnostics.test.ts
@@ -56,6 +56,35 @@ beforeEach(() => {
files.available.mockReset().mockResolvedValue(true);
});
describe("local journal persistence", () => {
+ // Unit: unchanged 2-second render snapshots dominated the field log. Keep
+ // heartbeat, changed counters and stall/lifecycle evidence through the sink.
+ it('deduplicates render snapshots while retaining changes, periodic samples and stalls', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'Date', 'performance'] });
+ const log = await import('./localDiagnostics');
+ const metrics = await import('../session/mobileMarkdownRenderMetrics');
+ const stop = log.startLocalDiagnostics();
+ const snapshots = () => files.append.mock.calls.flatMap(([batch]) => batch.trim().split('\n'))
+ .filter(line => line).map(line => JSON.parse(line)).filter(row => row.args?.[0] === 'render metrics');
+ try {
+ await log.hydrateDiagnostics();
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(snapshots()).toHaveLength(1);
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(snapshots()).toHaveLength(2);
+ metrics.recordMobileMessageRenderItem();
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(snapshots()).toHaveLength(3);
+ lifecycle.listen.mock.calls[0][1]('active');
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(snapshots()).toHaveLength(4);
+ const now = performance.now();
+ const clock = vi.spyOn(performance, 'now').mockReturnValue(now + 10_000);
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(snapshots()).toHaveLength(5);
+ expect((await log.diagnosticSnapshot()).some(event => event.event === 'js stall')).toBe(true);
+ clock.mockRestore();
+ } finally { stop(); }
+ });
it("records both clocks and lifecycle distance for a foreground timer gap", async () => {
vi.useFakeTimers();
let now = 100;
diff --git a/apps/mobile/src/debug/localDiagnostics.ts b/apps/mobile/src/debug/localDiagnostics.ts
index 4d1024c492..52d3d12614 100644
--- a/apps/mobile/src/debug/localDiagnostics.ts
+++ b/apps/mobile/src/debug/localDiagnostics.ts
@@ -242,6 +242,8 @@ export function startLocalDiagnostics(): () => void {
let lastTick = performance.now();
let lastWallTick = Date.now();
let lifecycleAt = lastTick;
+ let lastRenderSnapshot: string | undefined;
+ let lastRenderAt = -Infinity;
void hydrateDiagnostics().then(() => {
if (!stopped)
mobileDebugLog("info", "lifecycle", "app started", { appState: state });
@@ -252,6 +254,7 @@ export function startLocalDiagnostics(): () => void {
lastTick = performance.now();
lastWallTick = Date.now();
lifecycleAt = lastTick;
+ lastRenderSnapshot = undefined;
mobileDebugLog("info", "lifecycle", `app ${next}`);
void flushDiagnostics().catch(() => {});
});
@@ -269,11 +272,18 @@ export function startLocalDiagnostics(): () => void {
});
lastTick = now;
lastWallTick = Date.now();
- if (enabled)
- mobileDebugLog("debug", "performance", "render metrics", {
+ if (enabled) {
+ const metrics = {
markdown: getMobileMarkdownRenderMetrics(),
webViews: getMobileMessageWebViewMetrics(),
- });
+ };
+ const snapshot = JSON.stringify(metrics);
+ if (stalled || snapshot !== lastRenderSnapshot || now - lastRenderAt >= 30_000) {
+ mobileDebugLog("debug", "performance", "render metrics", metrics);
+ lastRenderSnapshot = snapshot;
+ lastRenderAt = now;
+ }
+ }
// Counters cover the interval since the previous line, so a line written
// right after a stall attributes the work that ran during it.
ticksSinceJankMetrics += 1;
@@ -294,6 +304,7 @@ export function startLocalDiagnostics(): () => void {
} else if (timer === undefined) {
lastTick = performance.now();
lastWallTick = Date.now();
+ lastRenderSnapshot = undefined;
timer = setInterval(tick, 2000);
}
};
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index 90daea796f..6d439c4249 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -210,7 +210,7 @@ export interface DeviceLinkContextValue {
deviceId: string,
channel: string,
args?: unknown[],
- opts?: { preSend?: () => void },
+ opts?: { preSend?: () => void; background?: boolean },
): Promise<T>;
// `owner` is a stable id for the mounted consumer (e.g. `session:<id>`, `device:<id>`),
// so repeated subscribes from resync/retry are idempotent and a topic is only released
@@ -1534,7 +1534,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
deviceId: string,
channel: string,
args: unknown[] = [],
- opts?: { preSend?: () => void },
+ opts?: { preSend?: () => void; background?: boolean },
) => {
const preSend = () => {
if (presenceAvailableByDeviceRef.current.get(deviceId) === false) {
@@ -1567,7 +1567,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
return withAccessRevokedHandling(deviceId, async () => unwrapInvoke<T>(result));
}
}
- return sendInvokeWithAccessHandling<T>(client, deviceId, channel, args, { preSend });
+ return sendInvokeWithAccessHandling<T>(client, deviceId, channel, args, { preSend, background: opts?.background });
},
);
}, [sendOpenLinkOnce]);
@@ -2054,6 +2054,7 @@ async function sendOpenLink(
interface SendInvokeOptions {
preSend?: () => void;
+ background?: boolean;
/** 同一轮明确 fan-out 共享;普通独立请求省略。 */
responsivenessCohort?: number;
/** 仅主动的代表性 half-open 探测允许领取 probe 席位。 */
@@ -2104,7 +2105,7 @@ async function sendInvoke<T>(
// 长通道(media / 文件搜索 / schedule 就绪窗口等)按 invokeTimeouts 解析
// 规则保留更长窗口,避免 mobile 收紧的默认 15s 误伤合法慢操作。
resolveMobileInvokeTimeoutMs(channel, args),
- { preSend: () => {
+ { background: opts?.background, preSend: () => {
try {
opts?.preSend?.();
} catch (err) {
diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.ts
index cf3a64d55f..640bc8ef76 100644
--- a/apps/mobile/src/device-link/mobileMakerTransport.ts
+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts
@@ -249,6 +249,8 @@ export interface RemoteTextFilePreviewResult {
error?: string;
reason?: "oversize" | "not_found" | "forbidden" | "read_failed";
data?: string;
+ /** Only returned when the caller opts into the existing file transfer path. */
+ transferRequired?: boolean;
size: number;
limitMb?: number;
}
@@ -901,7 +903,7 @@ export interface MobileMakerTransport {
listDir(path: string): Promise<RemoteDirectoryListResult>;
statPath(path: string): Promise<RemotePathStatResult>;
mkdirP(path: string): Promise<{ resolvedPath: string }>;
- readTextFilePreview(path: string): Promise<RemoteTextFilePreviewResult>;
+ readTextFilePreview(path: string, options?: { allowFileTransfer?: boolean; signal?: AbortSignal }): Promise<RemoteTextFilePreviewResult>;
};
/** 完整文件浏览(workdir 相对路径语义,被控端 file-browser:remote-op 聚合通道)。 */
fileBrowser: {
@@ -1142,7 +1144,7 @@ export function createMobileMakerTransport({
"result",
() =>
readDeviceFile({
- cacheFirst: stream || opts?.skipCache || opts?.thumbnail || isSharedTaskPeer(deviceId) ? undefined : {
+ cacheFirst: stream || opts?.revalidate || opts?.skipCache || opts?.thumbnail || isSharedTaskPeer(deviceId) ? undefined : {
read: async () => (await getFileCache())?.readLatest(deviceId, url, () => fileIsCurrent() && !opts?.signal?.aborted) ?? null,
retain: async (result) => { await opts?.retainBackground?.(withDownload(result), fileIsCurrent); },
},
@@ -1572,8 +1574,8 @@ export function createMobileMakerTransport({
listDir: (path) => call("fs:list-dir", [{ path }]),
statPath: (path) => call("fs:stat-path", [{ path }]),
mkdirP: (path) => call("fs:mkdir-p", [{ path }]),
- readTextFilePreview: (filePath) =>
- call("text-file:read-preview", [{ filePath }]),
+ readTextFilePreview: (filePath, options) =>
+ call("text-file:read-preview", [{ filePath, ...(options?.allowFileTransfer ? { allowFileTransfer: true } : {}) }]),
},
fileBrowser: {
cacheScope: JSON.stringify([fileOwner.accountKey, deviceId]),
diff --git a/apps/mobile/src/device-link/useMobileMakerTransport.ts b/apps/mobile/src/device-link/useMobileMakerTransport.ts
index 90c96ffa6e..118b12de70 100644
--- a/apps/mobile/src/device-link/useMobileMakerTransport.ts
+++ b/apps/mobile/src/device-link/useMobileMakerTransport.ts
@@ -1,6 +1,9 @@
import { useMemo, useRef } from "react";
import { useAuth } from "@/auth/AuthContext";
import { useDeviceLink } from "./DeviceLinkContext";
+import { DEVICE_LINK_API_BASE_URL } from '@/config/env';
+import { readRemoteTextFilePreview } from '@/session/remoteAbsFileFetch';
+import type { MobileRemoteMediaPresignResult } from '@/session/remoteMedia';
import {
createMobileMakerTransport,
type MobileMakerTransport,
@@ -9,17 +12,36 @@ import {
export function useMobileMakerTransport(
deviceId: string,
): MobileMakerTransport {
- const { invoke } = useDeviceLink();
- const { accountGeneration } = useAuth();
+ const { invoke, openLink } = useDeviceLink();
+ const { accountGeneration, apiFetch } = useAuth();
const generation = useRef(accountGeneration);
generation.current = accountGeneration;
return useMemo(
- () =>
- createMobileMakerTransport({
+ () => {
+ const isCurrent = () => generation.current === accountGeneration;
+ const assertCurrent = () => {
+ if (!isCurrent()) throw new Error('PREVIEW_CANCELLED');
+ };
+ const maker = createMobileMakerTransport({
deviceId,
invoke,
- isCurrent: () => generation.current === accountGeneration,
- }),
- [deviceId, invoke, accountGeneration],
+ isCurrent,
+ });
+ const readPreview = maker.fs.readTextFilePreview;
+ maker.fs.readTextFilePreview = (path, options) => readRemoteTextFilePreview({
+ maker, deviceId, openLink, isCurrent,
+ readPreview: (path) => readPreview(path, { allowFileTransfer: true }),
+ presignGet: (key) => apiFetch<MobileRemoteMediaPresignResult>('/api/device-link/media/presign-get', {
+ baseUrl: DEVICE_LINK_API_BASE_URL, method: 'POST', body: { key }, assertCurrent,
+ }),
+ deleteOssObject: (key) => {
+ if (isCurrent()) void apiFetch('/api/device-link/media', {
+ baseUrl: DEVICE_LINK_API_BASE_URL, method: 'DELETE', body: { key }, assertCurrent,
+ }).catch(() => undefined);
+ },
+ }, path, options?.signal);
+ return maker;
+ },
+ [deviceId, invoke, openLink, accountGeneration, apiFetch],
);
}
diff --git a/apps/mobile/src/session/HomeSurface.tsx b/apps/mobile/src/session/HomeSurface.tsx
index 8ff67a03fd..e6f7a62f8e 100644
--- a/apps/mobile/src/session/HomeSurface.tsx
+++ b/apps/mobile/src/session/HomeSurface.tsx
@@ -1778,7 +1778,13 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
return () => { cancelled = true; };
}
void discoverRemoteHomeCollections(
- invoke,
+ (deviceId, channel, args) => invoke(deviceId, channel, args, {
+ background: true,
+ preSend: () => {
+ if (cancelled || homeAccountGenerationRef.current !== accountGeneration)
+ throw new Error('Remote discovery superseded');
+ },
+ }),
targets,
i18nInstance.language,
remoteHomeCollectionsRef.current,
diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsx
index b2ae344e90..d2eb1b7d86 100644
--- a/apps/mobile/src/session/MessageRenderer.tsx
+++ b/apps/mobile/src/session/MessageRenderer.tsx
@@ -702,7 +702,7 @@ interface MessageActions {
/** 待发送气泡(pending_send 项)的展开态与队列操作回调。 */
pendingSend?: PendingSendBubbleActions;
getSentImagePreview?: GetSentMessageImagePreview;
- onReadTextFilePreview?: (filePath: string) => Promise<RemoteTextFilePreviewResult>;
+ onReadTextFilePreview?: (filePath: string, options?: { signal?: AbortSignal }) => Promise<RemoteTextFilePreviewResult>;
onReleaseRemoteMedia?: (sourceUrl: string, media: MobileResolvedRemoteMedia) => void;
onResolveRemoteMedia?: ResolveRemoteMediaFn;
busyClientId?: string | null;
@@ -7189,7 +7189,7 @@ function MessagePayloadModal({
/** 图表导出图的标注配置(来自聊天 lightbox 的同一份 chatAnnotation)。 */
imageAnnotation?: ImageLightboxAnnotationConfig;
onClose(): void;
- onReadTextFilePreview?: (filePath: string) => Promise<RemoteTextFilePreviewResult>;
+ onReadTextFilePreview?: (filePath: string, options?: { signal?: AbortSignal }) => Promise<RemoteTextFilePreviewResult>;
onReleaseRemoteMedia?: (sourceUrl: string, media: MobileResolvedRemoteMedia) => void;
onResolveRemoteMedia?: ResolveRemoteMediaFn;
onShareImage?: ComponentProps<typeof ImageLightbox>['onShareImage'];
@@ -7574,7 +7574,7 @@ function MessagePayloadBody({
onResolveRemoteMedia,
}: {
payload: MessagePayload;
- onReadTextFilePreview?: (filePath: string) => Promise<RemoteTextFilePreviewResult>;
+ onReadTextFilePreview?: (filePath: string, options?: { signal?: AbortSignal }) => Promise<RemoteTextFilePreviewResult>;
onReleaseRemoteMedia?: (sourceUrl: string, media: MobileResolvedRemoteMedia) => void;
onResolveRemoteMedia?: ResolveRemoteMediaFn;
}) {
@@ -7768,7 +7768,7 @@ function DiffPayloadBody({
}: {
diff: NormalizedToolDiff;
layout: PayloadBodyLayout;
- onReadTextFilePreview?: (filePath: string) => Promise<RemoteTextFilePreviewResult>;
+ onReadTextFilePreview?: (filePath: string, options?: { signal?: AbortSignal }) => Promise<RemoteTextFilePreviewResult>;
}) {
const { colors } = useTheme();
const { t, i18n: i18nInstance } = useTranslation();
@@ -7956,7 +7956,7 @@ function FilePayloadBody({
onResolveRemoteMedia?: ResolveRemoteMediaFn;
layout: PayloadBodyLayout;
payload: Extract<MessagePayload, { kind: 'file' }>;
- onReadTextFilePreview?: (filePath: string) => Promise<RemoteTextFilePreviewResult>;
+ onReadTextFilePreview?: (filePath: string, options?: { signal?: AbortSignal }) => Promise<RemoteTextFilePreviewResult>;
}) {
const { colors } = useTheme();
const { t, i18n: i18nInstance } = useTranslation();
@@ -8055,26 +8055,34 @@ type RemoteTextFilePreviewLoadState =
function useRemoteTextFilePreview(
sourcePath: string,
- onReadTextFilePreview?: (filePath: string) => Promise<RemoteTextFilePreviewResult>,
+ onReadTextFilePreview?: (filePath: string, options?: { signal?: AbortSignal }) => Promise<RemoteTextFilePreviewResult>,
) {
const { i18n: i18nInstance } = useTranslation();
const [previewLoadState, setPreviewLoadState] = useState<RemoteTextFilePreviewLoadState>(
{ status: 'idle' },
);
const previewSeqRef = useRef(0);
+ const previewAbortRef = useRef<AbortController | null>(null);
const previewKind = useMemo(() => remoteFilePreviewKind(sourcePath), [sourcePath]);
const canPreview = previewKind === 'text' && !!sourcePath && !!onReadTextFilePreview;
useEffect(() => {
previewSeqRef.current += 1;
setPreviewLoadState({ status: 'idle' });
- }, [sourcePath]);
+ return () => {
+ previewSeqRef.current += 1;
+ previewAbortRef.current?.abort();
+ };
+ }, [sourcePath, onReadTextFilePreview]);
const loadPreview = useCallback(() => {
if (!canPreview || previewLoadState.status === 'loading') return;
const seq = ++previewSeqRef.current;
+ previewAbortRef.current?.abort();
+ const abort = new AbortController();
+ previewAbortRef.current = abort;
setPreviewLoadState({ status: 'loading' });
- void onReadTextFilePreview(sourcePath)
+ void onReadTextFilePreview(sourcePath, { signal: abort.signal })
.then((result) => {
if (previewSeqRef.current !== seq) return;
if (result.success && typeof result.data === 'string') {
diff --git a/apps/mobile/src/session/remoteAbsFileFetch.ts b/apps/mobile/src/session/remoteAbsFileFetch.ts
index 3bb0f239c3..ef9c9082be 100644
--- a/apps/mobile/src/session/remoteAbsFileFetch.ts
+++ b/apps/mobile/src/session/remoteAbsFileFetch.ts
@@ -25,6 +25,7 @@ import type {
MobileMakerTransport,
RemoteTextFilePreviewResult,
} from '@/device-link/mobileMakerTransport';
+import { releasePeerMedia } from '@/device-link/peerFileRegistry';
import {
effectiveRemoteMediaSshContext,
remoteFileMediaUrl,
@@ -221,3 +222,62 @@ export function adaptTextFilePreviewResult(
: res.error ?? i18n.t('composer.attachments.readFailed');
return { ok: false, code: 'READ_FAILED', message };
}
+
+/** Size-limited text fallback; uses existing transfer/cache and temporary-file cleanup. */
+export async function readRemoteTextFilePreview(
+ deps: RemoteAbsFileFetchDeps & {
+ readPreview: (path: string) => Promise<RemoteTextFilePreviewResult>;
+ isCurrent: () => boolean;
+ },
+ path: string,
+ signal: AbortSignal = new AbortController().signal,
+): Promise<RemoteTextFilePreviewResult> {
+ const assertActive = () => {
+ if (signal?.aborted || !deps.isCurrent()) throw new Error('PREVIEW_CANCELLED');
+ };
+ assertActive();
+ let preview: RemoteTextFilePreviewResult | undefined;
+ try {
+ preview = await deps.readPreview(path);
+ } catch (error) {
+ // Older Hosts ignore the opt-in and return their existing compact error.
+ // Permission, missing-file and connection failures must never bypass the text reader.
+ if (!error || typeof error !== 'object' || !('code' in error) || error.code !== 'PAYLOAD_TOO_LARGE') throw error;
+ }
+ assertActive();
+ if (preview && (!preview.success || !preview.transferRequired)) return preview;
+ const maxBytes = 10 * 1024 * 1024;
+ const uploaded = new Set<string>();
+ let localUri: string | undefined;
+ try {
+ const media = await resolveMobileRemoteMedia(
+ { kind: 'image', url: remoteFileMediaUrl(path, undefined, undefined, { maxBytes }) },
+ { fetchRemoteMedia: deps.maker.fetchRemoteMedia, presignGet: deps.presignGet },
+ // The visible text cache already provides the stale snapshot. This read
+ // must validate the Host version before updating that snapshot again.
+ { signal, stream: false, revalidate: true, beforeFetch: async () => {
+ assertActive();
+ await deps.openLink(deps.deviceId);
+ assertActive();
+ }, onOssKey: (key) => uploaded.add(key) },
+ );
+ if (media.url.startsWith('file://')) localUri = media.url;
+ assertActive();
+ if (!Number.isSafeInteger(media.size) || media.size < 0) throw new Error('PREVIEW_CHANGED');
+ if (media.size > maxBytes) return { success: false, reason: 'oversize', size: media.size, limitMb: 10 };
+ const { withDownloadedRemoteMediaFile } = await import('./remoteMediaDiskCacheExpo');
+ const result = await withDownloadedRemoteMediaFile(media.url, media.mimeType, maxBytes, async (file) => {
+ assertActive();
+ if (file.size !== media.size) throw new Error('PREVIEW_CHANGED');
+ const data = await file.text();
+ assertActive();
+ return { success: true, data, size: media.size, limitMb: 10 };
+ }, signal);
+ assertActive();
+ if (!result) throw new Error('PREVIEW_READ_FAILED');
+ return result;
+ } finally {
+ if (localUri) releasePeerMedia(localUri);
+ for (const key of uploaded) deps.deleteOssObject?.(key);
+ }
+}
diff --git a/apps/mobile/src/session/remoteMedia.ts b/apps/mobile/src/session/remoteMedia.ts
index b5cdd2ebf6..a8b777f5d9 100644
--- a/apps/mobile/src/session/remoteMedia.ts
+++ b/apps/mobile/src/session/remoteMedia.ts
@@ -51,6 +51,8 @@ export interface MobileResolvedRemoteMedia {
}
export interface MobileRemoteMediaFetchOptions {
+ /** Await Host version validation; still reuse bytes for that confirmed version. */
+ revalidate?: boolean;
/** Local callbacks: only connect on a cache miss or during background revalidation. */
beforeFetch?: () => Promise<unknown>;
retainBackground?: (result: MobileRemoteMediaFetchResult, isCurrent?: () => boolean) => Promise<void>;
@@ -75,6 +77,7 @@ export interface MobileRemoteMediaResolverDeps {
}
export interface MobileRemoteMediaResolveOptions {
+ revalidate?: boolean;
beforeFetch?: () => Promise<unknown>;
discardBackgroundOssKey?: (key: string) => void;
onProgress?: (loaded: number, total: number) => void;
@@ -204,6 +207,7 @@ export async function resolveMobileRemoteMedia(
throw new Error(i18n.t("composer.attachments.notFetchableMedia"));
}
const fetchOpts = {
+ ...(opts?.revalidate ? { revalidate: true } : {}),
...(opts?.beforeFetch ? { beforeFetch: opts.beforeFetch } : {}),
...(opts?.stream === false ? { retainBackground: async (result: MobileRemoteMediaFetchResult, isCurrent?: () => boolean) => {
if (!result.ossKey || isCurrent?.() === false) return;
diff --git a/apps/mobile/src/session/remoteMediaDiskCacheExpo.ts b/apps/mobile/src/session/remoteMediaDiskCacheExpo.ts
index a18a9ef7cb..e987e909c7 100644
--- a/apps/mobile/src/session/remoteMediaDiskCacheExpo.ts
+++ b/apps/mobile/src/session/remoteMediaDiskCacheExpo.ts
@@ -28,13 +28,19 @@ async function downloadCancellable(
url: string,
target: File,
signal: AbortSignal,
+ maxBytes?: number,
): Promise<File> {
const FileSystem = await import("expo-file-system/legacy");
- const task = FileSystem.createDownloadResumable(url, target.uri);
let rejectStopped: (reason: Error) => void = () => undefined;
const stopped = new Promise<never>((_, reject) => {
rejectStopped = reject;
});
+ const task = FileSystem.createDownloadResumable(url, target.uri, {}, (progress) => {
+ if (maxBytes !== undefined && progress.totalBytesWritten > maxBytes) {
+ rejectStopped(new Error('PREVIEW_TOO_LARGE'));
+ void task.cancelAsync().catch(() => undefined);
+ }
+ });
const stop = () => {
rejectStopped(new Error("DOWNLOAD_CANCELLED"));
void task.cancelAsync().catch(() => undefined);
@@ -62,9 +68,12 @@ async function copyRemoteFile(
url: string,
target: File,
signal?: AbortSignal,
+ maxBytes?: number,
): Promise<File> {
if (url.startsWith("file://")) {
- await new File(url).copy(target);
+ const source = new File(url);
+ if (maxBytes !== undefined && source.size > maxBytes) throw new Error('PREVIEW_TOO_LARGE');
+ await source.copy(target);
return target;
}
if (url.startsWith("data:")) {
@@ -76,7 +85,7 @@ async function copyRemoteFile(
target.write(Uint8Array.from(atob(match[1]), (char) => char.charCodeAt(0)));
return target;
}
- if (signal) return downloadCancellable(url, target, signal);
+ if (signal || maxBytes !== undefined) return downloadCancellable(url, target, signal ?? new AbortController().signal, maxBytes);
return File.downloadFileAsync(url, target, { idempotent: true });
}
@@ -171,17 +180,20 @@ export async function withDownloadedRemoteMediaFile<T>(
mimeType: string,
maxBytes: number,
read: (file: File) => Promise<T | null>,
+ signal?: AbortSignal,
): Promise<T | null> {
const dir = new Directory(Paths.cache, SHARE_TMP_DIR_NAME);
let target: File | null = null;
try {
+ if (signal?.aborted) return null;
dir.create({ intermediates: true, idempotent: true });
const unique = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
target = new File(dir, `res-${unique}.${extOfMime(mimeType)}`);
- const file = await copyRemoteFile(url, target);
+ const file = await copyRemoteFile(url, target, signal, signal ? maxBytes : undefined);
const size = file.size ?? 0;
- if (size <= 0 || size > maxBytes) return null;
- return await read(file);
+ if (signal?.aborted || size <= 0 || size > maxBytes) return null;
+ const result = await read(file);
+ return signal?.aborted ? null : result;
} catch {
return null;
} finally {
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 14627f6620..f1846ee1e8 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -188,6 +188,21 @@ known 是消息 ID 与主机提供的 SHA-256 正文指纹对。支持的主机
传输去重仅保留有界内存,两端持久展示缓存继续使用原有账号隔离与删除屏障。
不修改 relay、不新增权限、数据库 migration 或 Mobile 原生指纹。
+## 大文本预览的文件传输回退
+
+`text-file:read-preview` 接受可选 `allowFileTransfer: true`。仍先执行原绝对路径、
+访问策略和 10 MiB 大小校验;成功结果的 UTF-8 JSON 大于设备消息预算(4 MiB 留出
+64 KiB 封装余量)时,仅向显式支持的调用方返回 `{ success: true, transferRequired: true,
+size, limitMb }`,不把正文塞入消息。未声明支持的本地/旧控制端仍收到原有结果。
+新手机收到标记后,使用既有 `xdt-file` 文件通道及版本缓存取件,并携带 `maxBytes=10485760`;
+读取前后校验取消、账号和实际大小,结束时释放取件暂存及 OSS 对象。文本已有独立展示缓存,
+其更新等待主机版本复验后再复用对应字节,避免把旧快照反复写回。无新增存储目录或通道。
+
+旧 Host 忽略新增请求字段,新手机继续接收原正文/错误;收到明确的 `PAYLOAD_TOO_LARGE`
+时可走同一文件回退,权限、缺失和连接错误不触发回退。旧 Host 若不能返回明确超限错误,
+仍需更新 Host 才能消除此失败;不以超时为由重发或绕过文本授权。完整修复需要两端更新,
+不需要服务端或 Mobile 原生构建变化。
+
## invoke 结果传输编码(弱网减流量)
控制端 `invoke` payload 可选携带 `transfer: { gzip?: 1, ifNoneMatch?: string }`:注入了解压
diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.md
index 6ea0ddb02e..7fd95c93ad 100644
--- a/docs/dev-rules/remote-and-mobile-adaptation.md
+++ b/docs/dev-rules/remote-and-mobile-adaptation.md
@@ -196,6 +196,9 @@ Desktop 向曾协商可靠传输、当前发送链路未就绪的设备发起新
隔离,关闭一个任务不会取消其他任务或普通远控请求,transport 的任务范围保持不变。
任务列表首拉与恢复探测走前台配额(仍受总并发 12 限制);Desktop 的周期弱刷新与归档
列表通过本地 scheduling 提示走后台配额,提示不进入 wire,也不改变授权。
+Mobile 首页自动资源发现同样通过本地 `background` 提示进入既有后台配额,
+排队后再次核验本轮发现及账号是否仍有效;失效调用不发送。用户主动打开资源保留原优先级,
+不按资源通道统一降级,不改变心跳、订阅、其它设备或共享 relay 的恢复行为。
socket 缓冲或目标 peer 可靠队列超过 128 KiB、或该 peer 积压至少半个接收窗口时,
后台准入收敛到一路;已发送请求正常结算,压力消退后按原上限推进。
前台请求优先于尚未发送的后台请求;不同设备独立推进。PR 的重复聚焦/注册沿用