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(device-link): 加速跨端文件、附件与远程读取 (#5086)

Dash5ae29365488d
diff --git a/apps/desktop/src/capture-renderer/filePeerHost.ts b/apps/desktop/src/capture-renderer/filePeerHost.ts
index 9255162873..c952e78462 100644
--- a/apps/desktop/src/capture-renderer/filePeerHost.ts
+++ b/apps/desktop/src/capture-renderer/filePeerHost.ts
@@ -9,7 +9,13 @@ export function startFilePeerHost(api: FilePeerHostApi) {
let result: string | undefined;
switch (c.action) {
case 'offer':
- result = await runtime.offer(c.connection, c.servers);
+ result = await runtime.offer(c.connection, c.servers, c.streaming);
+ break;
+ case 'stats':
+ result = await runtime.stats(c.connection);
+ break;
+ case 'invoke':
+ result = await runtime.invoke(c.connection, c.payload);
break;
case 'accept':
result = await runtime.accept(c.connection, c.servers, c.sdp);
diff --git a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts
index ed0d5d3fd7..d92da7d7cd 100644
--- a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts
+++ b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts
@@ -6,6 +6,11 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
const capabilities = vi.hoisted(() => ({ canUseDeviceLink: true }));
+// Transport windows are outside this in-memory IPC handler harness.
+vi.mock('../device-link/filePeer', () => ({
+ tryUploadPeerAttachment: vi.fn(async () => null),
+}));
+
// electron / serverApiClient / device-link host 全部替换为测试替身,
// 只测 handler 纯函数体
vi.mock('electron', () => ({
diff --git a/apps/desktop/src/main/__tests__/normalizeAttachmentsOss.test.ts b/apps/desktop/src/main/__tests__/normalizeAttachmentsOss.test.ts
index 653413bb60..004ef90e0c 100644
--- a/apps/desktop/src/main/__tests__/normalizeAttachmentsOss.test.ts
+++ b/apps/desktop/src/main/__tests__/normalizeAttachmentsOss.test.ts
@@ -68,6 +68,8 @@ vi.mock('../cindy-media/blobStore.js', () => ({
}));
const downloadToFile = vi.hoisted(() => vi.fn(async () => {}));
+const copyPeerAttachment = vi.hoisted(() => vi.fn(async () => {}));
+vi.mock('../device-link/peerAttachmentStore', () => ({ copyPeerAttachment }));
const removeRemote = vi.hoisted(() => vi.fn(async () => {}));
vi.mock('../device-link/mediaTransfer.js', () => ({ downloadToFile, removeRemote }));
@@ -81,9 +83,28 @@ import {
materializeQueuedOssAttachments,
} from '../maker-ipc/normalizeAttachments';
import { buildAttachmentOssRef } from '../../shared/attachmentOssRef';
+import { buildPeerAttachmentRef } from '@cindy/device-link';
const ATTACHMENT_SHA256 = 'a'.repeat(64);
+describe('peer attachment materialization', () => {
+ it('ingests a staged image through existing media ownership without touching OSS', async () => {
+ const metadata = { ticket: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', size: 11, sha256: ATTACHMENT_SHA256, mimeType: 'image/png' };
+ const ref = buildPeerAttachmentRef(metadata);
+ const result = await materializeQueuedOssAttachments('sess-1', {
+ files: [{ path: ref, url: ref, mimeType: 'image/png', category: 'image', ext: '.png' }],
+ persistedContent: JSON.stringify({ images: [{ url: ref }] }),
+ }) as { files: Array<{ url: string }>; persistedContent: string };
+ expect(copyPeerAttachment).toHaveBeenCalledWith(metadata, expect.any(String));
+ expect(copyPeerAttachment).toHaveBeenCalledTimes(1);
+ expect(result.files[0].url).toBe(BLOB_URL);
+ expect(JSON.parse(result.persistedContent).images[0].url).toBe(BLOB_URL);
+ expect(ingestMedia).toHaveBeenCalledOnce();
+ expect(downloadToFile).not.toHaveBeenCalled();
+ expect(removeRemote).not.toHaveBeenCalled();
+ });
+});
+
describe('queued attachment cleanup regression', () => {
it('cleans earlier materialized OSS objects when a later integrity ref rejects the queue', async () => {
const first = buildAttachmentOssRef({ ossKey: 'oss/first.png', mimeType: 'image/png' });
diff --git a/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts b/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts
index e288bd7004..440241e985 100644
--- a/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts
@@ -10,7 +10,18 @@ const mock = vi.hoisted(() => ({
iceConfig: vi.fn(async () => []),
ready: vi.fn(async () => {}),
replyDelay: 0,
+ commandReply: vi.fn((_action: string) => 'v=0'),
+ now: undefined as number | undefined,
+ receiving: undefined as undefined | { sink: string; reply: () => void },
}));
+vi.mock('@cindy/device-link', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@cindy/device-link')>();
+ return {
+ ...actual,
+ createPeerTransferCooldown: () =>
+ actual.createPeerTransferCooldown(() => mock.now ?? Date.now()),
+ };
+});
vi.mock('electron', () => ({
ipcMain: { handle: (key: string, fn: (...args: any[]) => any) => mock.handlers.set(key, fn) },
app: { on: vi.fn(), getPath: () => os.tmpdir() },
@@ -29,9 +40,14 @@ vi.mock('../../remote-desktop/captureWindow', () => ({
await mock.ready();
this.contents = {
isDestroyed: () => false,
- send: (_channel: string, id: string, c: { action: string }) => {
+ send: (_channel: string, id: string, c: { action: string; sink?: string }) => {
if (c.action !== 'close') {
- const reply = () => mock.handlers.get('file-peer:host:reply')!({}, id, true, 'v=0');
+ const reply = () =>
+ mock.handlers.get('file-peer:host:reply')!({}, id, true, mock.commandReply(c.action));
+ if (c.action === 'receive') {
+ mock.receiving = { sink: c.sink!, reply };
+ return;
+ }
if (mock.replyDelay) setTimeout(reply, mock.replyDelay);
else reply();
}
@@ -45,15 +61,151 @@ vi.mock('../../remote-desktop/captureWindow', () => ({
registered() {}
},
}));
-import { registerFilePeerIpc, requestFilePeer, stopFilePeers } from '../filePeer';
+import {
+ registerFilePeerIpc,
+ requestFilePeer,
+ stopFilePeers,
+ tryPeerInvoke,
+ tryPeerFile,
+} from '../filePeer';
describe('authorized file peer source', () => {
+ it.each([0, 15_001])(
+ 'preserves a file receive after concurrent RPC failure (reply delay %i)',
+ async (delay) => {
+ const peer = 'concurrent-read-peer';
+ const invoke = vi.fn(async (_peer: string, _channel: string, args: unknown[]) => {
+ const action = (args[0] as { action: string }).action;
+ return {
+ ok: true,
+ result:
+ action === 'caps'
+ ? { version: 1, streaming: true }
+ : action === 'open'
+ ? {
+ ticket: 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb',
+ size: 5,
+ mimeType: 'text/plain',
+ }
+ : { connection: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', sdp: 'v=0' },
+ };
+ });
+ const transfer = tryPeerFile(peer, 'xdt-file://test', invoke);
+ await vi.waitFor(() => expect(mock.receiving).toBeDefined());
+ mock.replyDelay = delay;
+ expect(
+ await tryPeerInvoke(peer, 'file-browser:remote-op', [{ op: 'readFile' }], invoke),
+ ).toBeNull();
+ await mock.handlers.get('file-peer:host:write')!({}, mock.receiving!.sink, 0, 'aGVsbG8=');
+ mock.receiving!.reply();
+ const result = await transfer;
+ expect(result?.size).toBe(5);
+ await result?.dispose();
+ },
+ 20_000,
+ );
+ it('warms reads, preserves application errors, and retries transport failure only after cooldown', async () => {
+ const peer = 'warm-recovery-peer';
+ const invoke = vi.fn(async (_peer: string, _channel: string, args: unknown[]) => {
+ const action = (args[0] as { action: string }).action;
+ return {
+ ok: true,
+ result:
+ action === 'caps'
+ ? { version: 1, streaming: true }
+ : {
+ connection: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ sdp: 'v=0',
+ },
+ };
+ });
+ const read = () => tryPeerInvoke(peer, 'file-browser:remote-op', [{ op: 'readFile' }], invoke);
+ mock.commandReply.mockImplementation((action) =>
+ action === 'invoke' ? JSON.stringify({ ok: false, error: 'FILE_NOT_FOUND' }) : 'v=0',
+ );
+ expect(await read()).toBeNull();
+ await vi.waitFor(() => expect(mock.commandReply).toHaveBeenCalledWith('stats'));
+ expect(await read()).toEqual({ ok: false, error: 'FILE_NOT_FOUND' });
+ expect(invoke.mock.calls.filter((call) => (call[2][0] as any).action === 'caps')).toHaveLength(
+ 1,
+ );
+ // Broken renderer reply models transport failure, not a remote application error.
+ mock.commandReply.mockReturnValue('broken-json');
+ expect(await read()).toBeNull();
+ for (let i = 0; i < 3; i++) expect(await read()).toBeNull();
+ expect(invoke.mock.calls.filter((call) => (call[2][0] as any).action === 'caps')).toHaveLength(
+ 1,
+ );
+ mock.now = Date.now() + 30_001;
+ try {
+ mock.commandReply
+ .mockClear()
+ .mockImplementation((action) =>
+ action === 'invoke' ? JSON.stringify({ ok: true, result: 'recovered' }) : 'v=0',
+ );
+ expect(await read()).toBeNull();
+ await vi.waitFor(() => expect(mock.commandReply).toHaveBeenCalledWith('stats'));
+ expect(await read()).toEqual({ ok: true, result: 'recovered' });
+ expect(
+ invoke.mock.calls.filter((call) => (call[2][0] as any).action === 'caps'),
+ ).toHaveLength(2);
+ } finally {
+ mock.now = undefined;
+ }
+ });
+ it('returns cold reads immediately while a single capability request remains pending', async () => {
+ let resolve!: (value: { ok: boolean }) => void;
+ const invoke = vi.fn(
+ () =>
+ new Promise<{ ok: boolean }>((done) => {
+ resolve = done;
+ }),
+ );
+ expect(
+ await tryPeerInvoke('cold-peer', 'file-browser:remote-op', [{ op: 'listDir' }], invoke),
+ ).toBeNull();
+ expect(
+ await tryPeerInvoke('cold-peer', 'file-browser:remote-op', [{ op: 'readFile' }], invoke),
+ ).toBeNull();
+ expect(invoke).toHaveBeenCalledTimes(1);
+ resolve({ ok: false });
+ await new Promise((done) => setImmediate(done));
+ expect(
+ await tryPeerInvoke('cold-peer', 'file-browser:remote-op', [{ op: 'listDir' }], invoke),
+ ).toBeNull();
+ expect(invoke).toHaveBeenCalledTimes(1);
+ });
+ it('reuses host dispatch for peer reads and rechecks revocation without closing another peer', async () => {
+ const invoke = vi.fn(async () => ({ ok: true, result: 'preview' }));
+ const { connection } = (await requestFilePeer(
+ 'a',
+ { action: 'offer', sdp: 'v=0' },
+ invoke,
+ )) as { connection: string };
+ const read = (channel: string, args: unknown[]) =>
+ mock.handlers.get('file-peer:host:invoke')!(
+ {},
+ connection,
+ JSON.stringify({ channel, args }),
+ );
+ expect(JSON.parse(await read('file-browser:remote-op', [{ op: 'readFile' }]))).toEqual({
+ ok: true,
+ result: 'preview',
+ });
+ await expect(read('maker:send', [{}])).rejects.toThrow('DENIED');
+ mock.settings.revokedControllers.push('a');
+ await expect(read('file-browser:remote-op', [{ op: 'readFile' }])).rejects.toThrow('REVOKED');
+ expect(invoke).toHaveBeenCalledTimes(1);
+ });
let directory: string, file: string;
beforeEach(async () => {
mock.current = true;
+ mock.receiving = undefined;
+ mock.now = undefined;
mock.iceConfig.mockReset().mockResolvedValue([]);
mock.ready.mockReset().mockResolvedValue();
mock.replyDelay = 0;
+ mock.commandReply.mockReset().mockReturnValue('v=0');
mock.settings = { remoteControlEnabled: true, revokedControllers: [] };
mock.handlers.clear();
registerFilePeerIpc();
@@ -144,6 +296,8 @@ describe('authorized file peer source', () => {
expect(await requestFilePeer('device-a', { action: 'caps' })).toEqual({
version: 1,
maxBytes: limit,
+ streaming: true,
+ attachments: true,
});
const first = await connect();
expect((await open(first.connection)).size).toBe(limit);
diff --git a/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts b/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts
index 0e02ad9260..64ecbc48ed 100644
--- a/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts
@@ -114,7 +114,11 @@ vi.mock('../index', () => ({
}),
}));
vi.mock('../dispatch', () => ({ getActiveControllers: () => [] }));
-vi.mock('../outboundMedia', () => ({ rewriteOutboundMedia: vi.fn(async (_c, a) => a) }));
+vi.mock('../filePeer', () => ({ tryUploadPeerAttachment: vi.fn(async () => null) }));
+vi.mock('../outboundMedia', () => ({
+ rewriteOutboundMedia: vi.fn(async (_c, a) => a),
+ withPeerAttachmentUpload: (_upload: unknown, operation: () => unknown) => operation(),
+}));
vi.mock('../outboundSessionReferences', () => ({
outboundSessionReferencesRequested: () => false,
rewriteOutboundSessionReferences: vi.fn(async (_c, a) => a),
diff --git a/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts b/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts
index cb6ac03f6a..9f88621e16 100644
--- a/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/outboundMedia.test.ts
@@ -7,7 +7,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
const uploadLocalFile = vi.hoisted(() => vi.fn());
const uploadBuffer = vi.hoisted(() => vi.fn());
-vi.mock('../mediaTransfer', () => ({ uploadLocalFile, uploadBuffer }));
+vi.mock('../mediaTransfer', () => ({ uploadLocalFile, uploadBuffer, mimeOf: () => 'text/plain' }));
const resolveSafe = vi.hoisted(() => vi.fn());
vi.mock('../../imageCacheStore', () => ({ resolveSafe }));
@@ -16,7 +16,8 @@ vi.mock('../../logger', () => ({
createLogger: () => ({ info: vi.fn(), debug: vi.fn(), warn: vi.fn(), error: vi.fn() }),
}));
-import { rewriteOutboundMedia, __testing } from '../outboundMedia';
+import { rewriteOutboundMedia, withPeerAttachmentUpload, __testing } from '../outboundMedia';
+import { buildPeerAttachmentRef, parsePeerAttachmentRef } from '@cindy/device-link';
import { buildUserMessageAttachmentPayload } from '../../../renderer/lib/messageAttachmentPayload';
import { withSharedTaskMedia } from '../sharedTaskMediaContext.js';
import { assertSharedTaskReferences } from '../sharedTaskDispatch.js';
@@ -41,6 +42,16 @@ beforeEach(() => {
});
describe('rewriteOutboundMedia — channel gating', () => {
+ it('uses peer staging for exact file bytes, preserves the name and retains OSS fallback', async () => {
+ const direct = vi.fn(async () => buildPeerAttachmentRef({ ticket: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', size: 10, sha256: SHA256, mimeType: 'text/plain' }));
+ const args = ['session', { type: 'user', content: [{ type: 'file', path: '/controller/a.txt', originalName: 'a.txt' }] }];
+ const result = await withPeerAttachmentUpload(direct, () => rewriteOutboundMedia('maker:send', args));
+ const ref = (result[1] as any).content[0].path;
+ expect(parsePeerAttachmentRef(ref)?.originalName).toBe('a.txt');
+ expect(uploadLocalFile).not.toHaveBeenCalled();
+ await withPeerAttachmentUpload(async () => null, () => rewriteOutboundMedia('maker:send', args));
+ expect(uploadLocalFile).toHaveBeenCalledOnce();
+ });
it('uploads a real Desktop composer image even when its payload says desktop-host', async () => {
const attachment = buildUserMessageAttachmentPayload([{ id: 'image', name: 'a.png', path: '/controller/a.png', url: 'xdt-image://task/a.png', size: 10, ext: '.png', category: 'image', mimeType: 'image/png' }]);
expect(attachment.serializedFiles?.[0].pathOrigin).toBe('desktop-host');
diff --git a/apps/desktop/src/main/device-link/__tests__/peerAttachmentStore.test.ts b/apps/desktop/src/main/device-link/__tests__/peerAttachmentStore.test.ts
new file mode 100644
index 0000000000..ab8956456f
--- /dev/null
+++ b/apps/desktop/src/main/device-link/__tests__/peerAttachmentStore.test.ts
@@ -0,0 +1,108 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { mkdtemp, rm, readFile } from 'node:fs/promises';
+import { promises as fs } from 'node:fs';
+import path from 'node:path';
+import os from 'node:os';
+import { createHash } from 'node:crypto';
+const state = vi.hoisted(() => ({ root: '', peer: 'a', current: true }));
+vi.mock('../../appSessionState', () => ({ ownerScopedUserDataPath: () => state.root }));
+vi.mock('../broadcast-tap', () => ({
+ captureDataOwnerBroadcastScope: () => ({}),
+ isDataOwnerBroadcastScopeCurrent: () => state.current,
+}));
+vi.mock('../invoke-context', () => ({
+ getDeviceLinkInvokeContext: () => ({ controllerDeviceId: state.peer }),
+}));
+import { handlePeerAttachment, copyPeerAttachment } from '../peerAttachmentStore';
+beforeEach(async () => {
+ state.root = await mkdtemp(path.join(os.tmpdir(), 'cindy-peer-upload-'));
+ state.current = true;
+ state.peer = 'a';
+});
+afterEach(async () => {
+ vi.restoreAllMocks();
+ await rm(state.root, { recursive: true, force: true });
+});
+const metadata = {
+ size: 5,
+ sha256: createHash('sha256').update('hello').digest('hex'),
+ mimeType: 'text/plain',
+};
+it('expires unfinished tickets after one idle hour even without admission sweeping', async () => {
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(0);
+ const { ticket } = (await handlePeerAttachment('a', { op: 'begin', ...metadata })) as {
+ ticket: string;
+ };
+ clock.mockReturnValue(60 * 60_000 + 1);
+ await expect(
+ handlePeerAttachment('a', { op: 'write', ticket, offset: 0, data: 'aGVsbG8=' }),
+ ).rejects.toThrow('DENIED');
+ await expect(handlePeerAttachment('a', { op: 'finish', ticket })).rejects.toThrow('DENIED');
+ // Expiry must not remove the owner's existing cancellation/cleanup path.
+ await expect(handlePeerAttachment('a', { op: 'cancel', ticket })).resolves.toEqual({ ok: true });
+});
+it('serializes admission sweeping with an in-flight ticket write and rechecks its timestamp', async () => {
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(0);
+ const { ticket } = (await handlePeerAttachment('a', { op: 'begin', ...metadata })) as {
+ ticket: string;
+ };
+ clock.mockReturnValue(60 * 60_000 - 1);
+ const rename = fs.rename.bind(fs);
+ let release!: () => void;
+ const hold = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const spy = vi.spyOn(fs, 'rename').mockImplementationOnce(async (from, to) => {
+ await hold;
+ await rename(from, to);
+ });
+ const write = handlePeerAttachment('a', { op: 'write', ticket, offset: 0, data: 'aGVsbG8=' });
+ await vi.waitFor(() => expect(spy).toHaveBeenCalled());
+ clock.mockReturnValue(60 * 60_000 + 1);
+ const admission = handlePeerAttachment('a', { op: 'begin', ...metadata });
+ release();
+ await Promise.all([write, admission]);
+ expect(await readFile(path.join(state.root, ticket), 'utf8')).toBe('hello');
+ await handlePeerAttachment('a', { op: 'finish', ticket });
+ clock.mockReturnValue(2 * 60 * 60_000);
+ await copyPeerAttachment({ ...metadata, ticket }, path.join(state.root, 'completed'));
+});
+it('verifies complete bytes, retains retryable staging and fences another controller', async () => {
+ const { ticket } = (await handlePeerAttachment('a', { op: 'begin', ...metadata })) as {
+ ticket: string;
+ };
+ await handlePeerAttachment('a', {
+ op: 'write',
+ ticket,
+ offset: 0,
+ data: Buffer.from('hello').toString('base64'),
+ });
+ await expect(
+ copyPeerAttachment({ ...metadata, ticket }, path.join(state.root, 'out')),
+ ).rejects.toThrow();
+ await handlePeerAttachment('a', { op: 'finish', ticket });
+ await copyPeerAttachment({ ...metadata, ticket }, path.join(state.root, 'out'));
+ expect(await readFile(path.join(state.root, 'out'), 'utf8')).toBe('hello');
+ state.peer = 'b';
+ await expect(
+ copyPeerAttachment({ ...metadata, ticket }, path.join(state.root, 'out2')),
+ ).rejects.toThrow('DENIED');
+ await expect(handlePeerAttachment('b', { op: 'cancel', ticket })).rejects.toThrow('DENIED');
+ state.current = false;
+ await expect(handlePeerAttachment('a', { op: 'cancel', ticket })).rejects.toThrow('CANCELLED');
+});
+it('rejects incorrect hashes and out of order writes', async () => {
+ const { ticket } = (await handlePeerAttachment('a', { op: 'begin', ...metadata })) as {
+ ticket: string;
+ };
+ await expect(
+ handlePeerAttachment('a', { op: 'write', ticket, offset: 2, data: 'eA==' }),
+ ).rejects.toThrow('BLOCK');
+ await handlePeerAttachment('a', {
+ op: 'write',
+ ticket,
+ offset: 0,
+ data: Buffer.from('wrong').toString('base64'),
+ });
+ await expect(handlePeerAttachment('a', { op: 'finish', ticket })).rejects.toThrow('INTEGRITY');
+});
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 3d59ff4f55..c49264cfcf 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -3726,7 +3726,7 @@ async function executeRemoteInvoke(src: string, payload: InvokePayload | undefin
}
if (payload.channel === FILE_PEER_CHANNEL) {
- try { return { ok: true, result: await requestFilePeer(src, payload.args?.[0]) }; }
+ try { return { ok: true, result: await requestFilePeer(src, payload.args?.[0], (channel, args) => runInvoke(src, { channel, args })) }; }
catch { return { ok: false, error: { code: 'IPC_ERROR', message: 'FILE_PEER_UNAVAILABLE' } }; }
}
if (payload.channel === PLUGIN_OAUTH_CHANNEL) {
diff --git a/apps/desktop/src/main/device-link/filePeer.ts b/apps/desktop/src/main/device-link/filePeer.ts
index 2923e7473c..3f337aecd0 100644
--- a/apps/desktop/src/main/device-link/filePeer.ts
+++ b/apps/desktop/src/main/device-link/filePeer.ts
@@ -1,10 +1,15 @@
import { app, ipcMain } from 'electron';
-import { randomUUID } from 'node:crypto';
+import { randomUUID, createHash } 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,
+ createPeerTransferCooldown,
+ canUsePeerInvoke,
+ canServePeerInvoke,
+ type InvokeResultPayload,
+ uploadPeerAttachment,
FILE_PEER_CHUNK_BYTES,
FILE_PEER_MAX_BYTES,
FILE_PEER_IDLE_MS,
@@ -21,6 +26,7 @@ import { resolveAuthorizedMedia } from './mediaFetch';
import { readDeviceLinkSettings } from './settings-store';
import { captureDataOwnerBroadcastScope, isDataOwnerBroadcastScopeCurrent } from './broadcast-tap';
import { createLogger } from '../logger.js';
+import { handlePeerAttachment } from './peerAttachmentStore';
// Local-only diagnostics (scope is not upload-allowlisted): stages, sizes and timings, never paths.
const log = createLogger('device-link:filePeer');
@@ -35,6 +41,7 @@ interface Connection {
timer: ReturnType<typeof setTimeout>;
incoming: boolean;
opening?: boolean;
+ invoke?: (channel: string, args: unknown[]) => Promise<unknown>;
}
interface Source {
connection: string;
@@ -57,8 +64,18 @@ interface Outgoing {
remote?: string;
busy: boolean;
invoke: Invoke;
+ rpc?: boolean;
+ attachments?: boolean;
}
const outgoing = new Map<string, Outgoing>();
+const cooldown = createPeerTransferCooldown();
+let cooldownOwner: Owner | undefined;
+function refreshCooldownOwner() {
+ if (!cooldownOwner || !isDataOwnerBroadcastScopeCurrent(cooldownOwner)) {
+ cooldown.clear();
+ cooldownOwner = captureDataOwnerBroadcastScope();
+ }
+}
const connections = new Map<string, Connection>();
const sources = new Map<string, Source>();
const sinks = new Map<string, Sink>();
@@ -165,7 +182,8 @@ async function command(c: FilePeerCommand): Promise<string | undefined> {
() => {
replies.delete(id);
log.warn(`host ${c.action} timed out conn=${short(c.connection)}`);
- stopConnection(c.connection, `${c.action}-timeout`);
+ // An RPC timeout must not cancel a concurrent file transfer on this peer.
+ if (c.action !== 'invoke') stopConnection(c.connection, `${c.action}-timeout`);
reject(new Error('FILE_PEER_TIMEOUT'));
},
c.action === 'receive' ? 60_000 : 15_000,
@@ -176,16 +194,24 @@ async function command(c: FilePeerCommand): Promise<string | undefined> {
});
}
-export async function requestFilePeer(peer: string, value: unknown): Promise<unknown> {
+export async function requestFilePeer(
+ peer: string,
+ value: unknown,
+ invoke?: Connection['invoke'],
+): Promise<unknown> {
const startedAt = Date.now();
let action = 'invalid';
try {
const r = parseFilePeerRequest(value);
action = r.action;
- const result = await handleFilePeerRequest(peer, r);
+ const result = await handleFilePeerRequest(peer, r, invoke);
const opened = r.action === 'open' ? (result as { size?: number; mimeType?: string }) : null;
const connection =
- r.action === 'offer' ? (result as { connection?: string }).connection : 'connection' in r ? r.connection : undefined;
+ r.action === 'offer'
+ ? (result as { connection?: string }).connection
+ : 'connection' in r
+ ? r.connection
+ : undefined;
log.debug(
`request ${action} ok peer=${short(peer)} ms=${Date.now() - startedAt}` +
(connection ? ` conn=${short(connection)}` : '') +
@@ -193,7 +219,9 @@ export async function requestFilePeer(peer: string, value: unknown): Promise<unk
);
return result;
} catch (error) {
- log.warn(`request ${action} failed peer=${short(peer)} ms=${Date.now() - startedAt} error=${errorText(error)}`);
+ log.warn(
+ `request ${action} failed peer=${short(peer)} ms=${Date.now() - startedAt} error=${errorText(error)}`,
+ );
throw error;
}
}
@@ -201,17 +229,22 @@ export async function requestFilePeer(peer: string, value: unknown): Promise<unk
async function handleFilePeerRequest(
peer: string,
r: FilePeerRequest,
+ invoke?: Connection['invoke'],
): Promise<unknown> {
- if (r.action === 'caps') return { version: 1, maxBytes: FILE_PEER_MAX_BYTES };
+ if (r.action === 'caps')
+ return { version: 1, maxBytes: FILE_PEER_MAX_BYTES, streaming: true, attachments: true };
if (r.action === 'offer') {
const id = randomUUID();
track(id, peer, true);
+ connections.get(id)!.invoke = invoke;
try {
// Cold host readiness and TURN configuration share the outer 30s RPC
// budget: max(10s, 8s) + 15s command leaves transport headroom.
const readyStartedAt = Date.now();
const [, servers] = await Promise.all([prepareHost(id), loadDesktopIceServers()]);
- log.debug(`offer host ready conn=${short(id)} ms=${Date.now() - readyStartedAt} iceServers=${servers.length}`);
+ log.debug(
+ `offer host ready conn=${short(id)} ms=${Date.now() - readyStartedAt} iceServers=${servers.length}`,
+ );
const sdp = await command({
action: 'accept',
connection: id,
@@ -226,6 +259,7 @@ async function handleFilePeerRequest(
}
const c = touch(r.connection);
if (!c.incoming || c.peer !== peer) throw new Error('FILE_PEER_DENIED');
+ if (r.action === 'attachment') return handlePeerAttachment(peer, r.request);
if (r.action === 'close') {
stopConnection(r.connection, 'peer-close');
return { ok: true };
@@ -293,13 +327,31 @@ async function handleFilePeerRequest(
}
export function registerFilePeerIpc() {
+ ipcMain.handle(FILE_PEER_LOCAL.INVOKE, async (e, id: unknown, text: unknown) => {
+ host.assertSender(e);
+ if (typeof id !== 'string' || typeof text !== 'string' || text.length > 4 * 1024 * 1024)
+ throw new Error('FILE_PEER_DENIED');
+ const c = touch(id);
+ const payload = JSON.parse(text);
+ if (
+ !c.incoming ||
+ !c.invoke ||
+ typeof payload.channel !== 'string' ||
+ !Array.isArray(payload.args) ||
+ !canServePeerInvoke(payload.channel, payload.args)
+ )
+ throw new Error('FILE_PEER_DENIED');
+ const result = await c.invoke(payload.channel, payload.args);
+ touch(id);
+ return JSON.stringify(result);
+ });
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))
+ (value !== undefined && (typeof value !== 'string' || value.length > 4 * 1024 * 1024))
)
throw new Error('FILE_PEER_REPLY');
const pending = replies.get(id);
@@ -341,11 +393,15 @@ export function registerFilePeerIpc() {
if (!bytes.length) {
sources.delete(ticket);
await s.file.close();
- log.debug(`send done conn=${short(connection)} size=${s.size} ms=${Date.now() - s.openedAt}`);
+ log.debug(
+ `send done conn=${short(connection)} size=${s.size} ms=${Date.now() - s.openedAt}`,
+ );
}
return bytes.toString('base64');
} catch (error) {
- log.warn(`send failed conn=${short(connection)} sent=${s.offset}/${s.size}B error=${errorText(error)}`);
+ log.warn(
+ `send failed conn=${short(connection)} sent=${s.offset}/${s.size}B error=${errorText(error)}`,
+ );
stopConnection(connection, 'read-failed');
throw error;
} finally {
@@ -398,6 +454,10 @@ type Invoke = (
const queuePeerRead = createFileReadQueue();
export function tryPeerFile(peer: string, url: string, invoke: Invoke, signal?: AbortSignal) {
const owner = captureDataOwnerBroadcastScope();
+ if (!cooldownOwner || !isDataOwnerBroadcastScopeCurrent(cooldownOwner)) {
+ cooldown.clear();
+ cooldownOwner = owner;
+ }
return queuePeerRead(
peer,
() => {
@@ -407,8 +467,21 @@ export function tryPeerFile(peer: string, url: string, invoke: Invoke, signal?:
signal,
);
}
-async function receivePeerFile(peer: string, url: string, invoke: Invoke, signal?: AbortSignal) {
+async function receivePeerFile(
+ peer: string,
+ url: string | null,
+ invoke: Invoke,
+ signal?: AbortSignal,
+) {
+ refreshCooldownOwner();
if (signal?.aborted) throw new Error('FILE_PEER_CANCELLED');
+ const remaining = cooldown.remaining(peer);
+ if (remaining) {
+ log.debug(`fallback peer=${short(peer)} reason=cooldown remainingMs=${remaining}`);
+ return null;
+ }
+ const startedAt = Date.now();
+ let step = 'setup';
const owner = captureDataOwnerBroadcastScope();
let out = outgoing.get(peer);
if (out?.busy) return null;
@@ -428,13 +501,20 @@ async function receivePeerFile(peer: string, url: string, invoke: Invoke, signal
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;
+ if (!caps.ok || (caps.result as { version?: unknown })?.version !== 1) {
+ cooldown.fail(peer);
+ log.debug(`fallback peer=${short(peer)} reason=unsupported`);
+ return null;
+ }
+ out.rpc = (caps.result as { streaming?: unknown }).streaming === true;
+ out.attachments = (caps.result as { attachments?: unknown }).attachments === true;
track(id, peer, false);
const [, servers] = await Promise.all([prepareHost(id), loadDesktopIceServers()]);
const offer = await command({
action: 'offer',
connection: id,
servers,
+ streaming: (caps.result as { streaming?: unknown }).streaming === true,
});
const response = await invoke(peer, FILE_PEER_CHANNEL, [{ action: 'offer', sdp: offer }]);
const r = response.result as { connection?: string; sdp?: string };
@@ -450,8 +530,17 @@ async function receivePeerFile(peer: string, url: string, invoke: Invoke, signal
remote = r.connection;
out.remote = remote;
await command({ action: 'answer', connection: id, sdp: r.sdp });
+ log.debug(
+ `connected peer=${short(peer)} setupMs=${Date.now() - startedAt} stats=${await command({ action: 'stats', connection: id })}`,
+ );
}
+ step = 'open';
touch(id);
+ if (url === null) {
+ complete = true;
+ cooldown.success(peer);
+ return null;
+ }
const opened = await invoke(peer, FILE_PEER_CHANNEL, [
{ action: 'open', connection: remote, url },
]);
@@ -465,6 +554,8 @@ async function receivePeerFile(peer: string, url: string, invoke: Invoke, signal
const handle = await fs.open(destination, 'wx', 0o600),
sink = randomUUID();
sinks.set(sink, { connection: id, file: handle, offset: 0, size: file.size, busy: false });
+ step = 'receive';
+ const transferStartedAt = Date.now();
try {
await command({
action: 'receive',
@@ -489,15 +580,24 @@ async function receivePeerFile(peer: string, url: string, invoke: Invoke, signal
const ownedDirectory = directory;
directory = undefined;
complete = true;
+ cooldown.success(peer);
+ const transferMs = Date.now() - transferStartedAt;
+ log.debug(
+ `received peer=${short(peer)} bytes=${file.size} transferMs=${transferMs} totalMs=${Date.now() - startedAt} bytesPerSecond=${Math.round((file.size * 1000) / Math.max(1, transferMs))}`,
+ );
return {
path: destination,
size: file.size,
mimeType: file.mimeType,
dispose: () => fs.rm(ownedDirectory, { recursive: true, force: true }),
};
- } catch {
+ } catch (error) {
if (signal?.aborted || !isDataOwnerBroadcastScopeCurrent(owner))
throw new Error('FILE_PEER_CANCELLED');
+ const delay = step === 'open' ? 0 : cooldown.fail(peer);
+ log.debug(
+ `fallback peer=${short(peer)} stage=${step} cooldownMs=${delay} reason=${errorText(error)}`,
+ );
return null;
} finally {
signal?.removeEventListener('abort', cancel);
@@ -513,3 +613,123 @@ async function receivePeerFile(peer: string, url: string, invoke: Invoke, signal
if (directory) await fs.rm(directory, { recursive: true, force: true });
}
}
+
+const warming = new Set<string>();
+/** Upload only bytes; the eventual message still uses its original WSS acceptance semantics. */
+export async function tryUploadPeerAttachment(
+ peer: string,
+ source: string | Buffer,
+ mimeType: string | undefined,
+ invoke: Invoke,
+): Promise<string | null> {
+ refreshCooldownOwner();
+ const owner = captureDataOwnerBroadcastScope();
+ const check = () => {
+ if (!isDataOwnerBroadcastScopeCurrent(owner)) throw new Error('FILE_PEER_CANCELLED');
+ };
+ return queuePeerRead(peer, async () => {
+ check();
+ if (cooldown.remaining(peer)) return null;
+ let handle: FileHandle | undefined;
+ let active: Outgoing | undefined;
+ try {
+ await receivePeerFile(peer, null, invoke);
+ check();
+ const out = outgoing.get(peer);
+ if (!out?.remote || !out.attachments) return null;
+ active = out;
+ out.busy = true;
+ if (typeof source === 'string')
+ handle = await fs.open(source, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
+ const size = handle ? (await handle.stat()).size : (source as Buffer).length;
+ if (!size || size > FILE_PEER_MAX_BYTES) return null;
+ const read = async (offset: number, length: number) => {
+ check();
+ if (!handle) return (source as Buffer).subarray(offset, offset + length);
+ const bytes = Buffer.alloc(length);
+ if ((await handle.read(bytes, 0, length, offset)).bytesRead !== length)
+ throw new Error('FILE_PEER_CHANGED');
+ return bytes;
+ };
+ const hash = createHash('sha256');
+ for (let offset = 0; offset < size; offset += 1024 * 1024)
+ hash.update(await read(offset, Math.min(1024 * 1024, size - offset)));
+ const transferStartedAt = Date.now();
+ const result = await uploadPeerAttachment(
+ { size, sha256: hash.digest('hex'), mimeType },
+ async (offset, length) => (await read(offset, length)).toString('base64'),
+ async (request) => {
+ check();
+ const response = JSON.parse(
+ (await command({
+ action: 'invoke',
+ connection: out.id,
+ payload: JSON.stringify({
+ channel: FILE_PEER_CHANNEL,
+ args: [{ action: 'attachment', connection: out.remote, request }],
+ }),
+ }))!,
+ );
+ check();
+ if (!response.ok) throw new Error('FILE_PEER_UPLOAD');
+ return response.result;
+ },
+ check,
+ );
+ const ms = Date.now() - transferStartedAt;
+ log.debug(
+ `uploaded peer=${short(peer)} bytes=${size} transferMs=${ms} bytesPerSecond=${Math.round((size * 1000) / Math.max(1, ms))}`,
+ );
+ return result;
+ } catch {
+ check();
+ cooldown.fail(peer);
+ const failed = outgoing.get(peer);
+ if (failed) stopConnection(failed.id, 'upload-failed');
+ return null;
+ } finally {
+ if (active) active.busy = false;
+ await handle?.close();
+ }
+ });
+}
+/** Cold reads use WSS immediately; a single background setup prepares subsequent reads. */
+export async function tryPeerInvoke(
+ peer: string,
+ channel: string,
+ args: unknown[],
+ invoke: Invoke,
+): Promise<InvokeResultPayload | null> {
+ refreshCooldownOwner();
+ if (!canUsePeerInvoke(channel, args)) return null;
+ if (cooldown.remaining(peer)) return null;
+ const owner = captureDataOwnerBroadcastScope();
+ const out = outgoing.get(peer);
+ if (!out?.remote || !out.rpc) {
+ if (!out?.remote && !warming.has(peer)) {
+ warming.add(peer);
+ void queuePeerRead(peer, async () => {
+ if (isDataOwnerBroadcastScopeCurrent(owner)) await receivePeerFile(peer, null, invoke);
+ })
+ .catch(() => {})
+ .finally(() => warming.delete(peer));
+ }
+ return null;
+ }
+ try {
+ const result = await command({
+ action: 'invoke',
+ connection: out.id,
+ payload: JSON.stringify({ channel, args }),
+ });
+ if (!isDataOwnerBroadcastScopeCurrent(owner)) throw new Error('FILE_PEER_CANCELLED');
+ const response = JSON.parse(result!);
+ if (!response || typeof response.ok !== 'boolean') throw new Error('FILE_PEER_REPLY');
+ return response;
+ } catch {
+ if (!isDataOwnerBroadcastScopeCurrent(owner)) throw new Error('FILE_PEER_CANCELLED');
+ cooldown.fail(peer);
+ if (!out.busy) stopConnection(out.id, 'rpc-failed');
+ return null;
+ }
+}
diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.ts
index 0c654e8d57..857254fd8d 100644
--- a/apps/desktop/src/main/device-link/index.ts
+++ b/apps/desktop/src/main/device-link/index.ts
@@ -11,6 +11,7 @@
*/
import os from 'node:os';
+import { tryPeerInvoke } from './filePeer';
import { deviceName, initializeDeviceName } from './deviceName';
import { watchNetworkChanges } from './networkChanges';
import path from 'node:path';
@@ -1761,6 +1762,19 @@ export async function remoteInvoke(
assertLinkNotClosedSinceStart();
options?.preSend?.();
if (!client) throw new Error('[DEVICE_LINK_NOT_CONNECTED] device-link client not initialized');
+ if (!parseSharedTaskPeer(deviceId)) {
+ const accelerated = await tryPeerInvoke(deviceId, channel, args, (peer, nextChannel, nextArgs) => {
+ assertLinkNotClosedSinceStart();
+ return remoteInvoke(peer, nextChannel, nextArgs, { preSend: () => {
+ assertLinkNotClosedSinceStart();
+ options?.preSend?.();
+ } });
+ });
+ assertRemoteControlTargetEnabled(deviceId);
+ assertLinkNotClosedSinceStart();
+ options?.preSend?.();
+ if (accelerated) return accelerated;
+ }
return client.invoke(deviceId, { channel, args }, resolveRemoteInvokeTimeoutMs(channel, args, 'desktop'));
};
const run = (): Promise<InvokeResultPayload> =>
diff --git a/apps/desktop/src/main/device-link/ipc.ts b/apps/desktop/src/main/device-link/ipc.ts
index 44620813c1..b2d3c76336 100644
--- a/apps/desktop/src/main/device-link/ipc.ts
+++ b/apps/desktop/src/main/device-link/ipc.ts
@@ -61,7 +61,8 @@ import {
waitForNewerControllerDisplayNameDirectoryRefresh,
} from './index';
import { getActiveControllers } from './dispatch';
-import { rewriteOutboundMedia } from './outboundMedia';
+import { rewriteOutboundMedia, withPeerAttachmentUpload } from './outboundMedia';
+import { tryUploadPeerAttachment } from './filePeer';
import { parseSharedTaskPeer } from '@cindy/device-link';
import { withSharedTaskMedia } from './sharedTaskMediaContext.js';
import {
@@ -682,8 +683,9 @@ export async function handleInvoke(
if (projectionUnavailable) {
throwIpcError('DEVICE_LINK_CHANNEL_NOT_ALLOWED', 'Queued content editing is not supported by the target device');
}
- callArgs = await withSharedTaskMedia(peer?.role === 'host' ? peer.sharedTaskId : undefined,
- () => existing ? deps.rewriteOutboundMedia!(channel, callArgs, existing) : deps.rewriteOutboundMedia!(channel, callArgs));
+ callArgs = await withPeerAttachmentUpload((source, mime) => peer ? Promise.resolve(null) : tryUploadPeerAttachment(normalizedDeviceId, source, mime, deps.invoke), () =>
+ withSharedTaskMedia(peer?.role === 'host' ? peer.sharedTaskId : undefined,
+ () => existing ? deps.rewriteOutboundMedia!(channel, callArgs, existing) : deps.rewriteOutboundMedia!(channel, callArgs)));
} catch (err) {
if (isIpcError(err) && err.code === 'DEVICE_LINK_CHANNEL_NOT_ALLOWED') {
throw err;
diff --git a/apps/desktop/src/main/device-link/outboundMedia.ts b/apps/desktop/src/main/device-link/outboundMedia.ts
index 9362570d05..fb48be8c0b 100644
--- a/apps/desktop/src/main/device-link/outboundMedia.ts
+++ b/apps/desktop/src/main/device-link/outboundMedia.ts
@@ -11,11 +11,19 @@
* 附件来源(控制端本机):xdt-image:// 缓存 URL / 绝对 fs 路径 / 内存 base64。
*/
import { promises as fsp } from 'node:fs';
+import path from 'node:path';
+import { AsyncLocalStorage } from 'node:async_hooks';
+import { buildPeerAttachmentRef, parsePeerAttachmentRef } from '@cindy/device-link';
+type PeerUpload = (source: string | Buffer, mimeType?: string) => Promise<string | null>;
+const peerUploadContext = new AsyncLocalStorage<PeerUpload>();
+export function withPeerAttachmentUpload<T>(upload: PeerUpload, operation: () => Promise<T>) {
+ return peerUploadContext.run(upload, operation);
+}
import { createLogger } from '../logger';
import * as imageCacheStore from '../imageCacheStore';
import * as cindyMediaBlobStore from '../cindy-media/blobStore';
-import { uploadLocalFile, uploadBuffer, type UploadResult } from './mediaTransfer';
+import { uploadLocalFile, uploadBuffer, mimeOf, type UploadResult } from './mediaTransfer';
import { sharedTaskMediaId } from './sharedTaskMediaContext.js';
import {
OUTBOUND_IMAGE_INPUT_MAX_BYTES,
@@ -72,7 +80,7 @@ function buildUploadedAttachmentRef(
function persistedIntegrityFields(
ref: string,
): { size: number; sha256: string } | Record<string, never> {
- const parsed = parseAttachmentOssRef(ref);
+ const parsed = parseAttachmentOssRef(ref) ?? parsePeerAttachmentRef(ref);
return parsed?.size === undefined ? {} : { size: parsed.size, sha256: parsed.sha256! };
}
@@ -86,6 +94,19 @@ async function uploadAttachment(src: AttachmentSource): Promise<string> {
? src.name
: undefined;
+ const direct = async (source: string | Buffer, contentType?: string) => {
+ const context = peerUploadContext.getStore();
+ if (!context || sharedTaskMediaId()) return null;
+ const effectiveMime = contentType ?? mimeOf(typeof source === 'string' ? path.extname(source).slice(1).toLowerCase() : 'bin');
+ const result = await context(source, effectiveMime);
+ const parsed = result && parsePeerAttachmentRef(result);
+ return parsed ? buildPeerAttachmentRef({ ...parsed, originalName }) : null;
+ };
+ const bufferRef = async (bytes: Buffer, options: Parameters<typeof uploadBuffer>[1]) =>
+ await direct(bytes, options?.contentType) ?? buildUploadedAttachmentRef(await uploadBuffer(bytes, options), originalName);
+ const fileRef = async (file: string, options: Parameters<typeof uploadLocalFile>[1]) =>
+ await direct(file, options?.contentType) ?? buildUploadedAttachmentRef(await uploadLocalFile(file, options), originalName);
+
// 1) 内存 base64(剪贴板/截图,视觉上下文语义)→ 压缩 → uploadBuffer(不把字节内联进 relay)
if (typeof src.base64 === 'string' && src.base64) {
const raw = Buffer.from(src.base64, 'base64');
@@ -96,11 +117,10 @@ async function uploadAttachment(src: AttachmentSource): Promise<string> {
? await compressOutboundImage(raw, mimeType)
: null;
const ext = compressed?.ext ?? (mimeType && EXT_BY_MIME[mimeType]) ?? 'bin';
- const r = await uploadBuffer(compressed?.bytes ?? raw, {
+ return bufferRef(compressed?.bytes ?? raw, {
ext,
contentType: compressed?.contentType ?? mimeType,
});
- return buildUploadedAttachmentRef(r, originalName);
}
// 2) url / path → 解析成本地绝对路径后流式上传
@@ -108,7 +128,7 @@ async function uploadAttachment(src: AttachmentSource): Promise<string> {
const rawPath = typeof src.path === 'string' && src.path ? src.path : '';
const ref = url || rawPath;
if (!ref) throw new Error('附件无可用来源(url/path/base64 皆空)');
- if (parseAttachmentOssRef(ref)) return ref;
+ if (parseAttachmentOssRef(ref) || parsePeerAttachmentRef(ref)) return ref;
if (ref.startsWith('clipboard://')) throw new Error('附件为 clipboard 占位,无字节');
// 2a) xdt-image:// 缓存 → 视觉上下文语义(截图/剪贴板/生成图)压缩后 uploadBuffer;
@@ -148,18 +168,16 @@ async function uploadAttachment(src: AttachmentSource): Promise<string> {
}
}
if (compressed) {
- const r = await uploadBuffer(compressed.bytes, {
+ return bufferRef(compressed.bytes, {
ext: compressed.ext,
contentType: compressed.contentType,
});
- return buildUploadedAttachmentRef(r, originalName);
}
// 显式文件也从缓存副本上传(字节与原文件一致,且不依赖原路径此刻仍存在)。
- const r = await uploadLocalFile(
+ return fileRef(
resolved.absPath,
effectiveMime ? { contentType: effectiveMime } : {},
);
- return buildUploadedAttachmentRef(r, originalName);
}
// 2a') cindy-media:// 媒体总仓 blob(统一地址,规则 25):图片沿用
@@ -183,19 +201,16 @@ async function uploadAttachment(src: AttachmentSource): Promise<string> {
}
}
if (compressed) {
- const r = await uploadBuffer(compressed.bytes, {
+ return bufferRef(compressed.bytes, {
ext: compressed.ext,
contentType: compressed.contentType,
});
- return buildUploadedAttachmentRef(r, originalName);
}
- const r = await uploadLocalFile(resolved.absPath, { contentType: effectiveMime });
- return buildUploadedAttachmentRef(r, originalName);
+ return fileRef(resolved.absPath, { contentType: effectiveMime });
}
// 2b) 用户显式给出的磁盘路径附件是「字节精确」语义(素材/设计稿/文档),不压,原样上传。
- const r = await uploadLocalFile(ref, mimeType ? { contentType: mimeType } : {});
- return buildUploadedAttachmentRef(r, originalName);
+ return fileRef(ref, mimeType ? { contentType: mimeType } : {});
}
function isAttachmentBlock(b: unknown): b is AttachmentSource & { type: string } {
diff --git a/apps/desktop/src/main/device-link/peerAttachmentStore.ts b/apps/desktop/src/main/device-link/peerAttachmentStore.ts
new file mode 100644
index 0000000000..273bc0a693
--- /dev/null
+++ b/apps/desktop/src/main/device-link/peerAttachmentStore.ts
@@ -0,0 +1,188 @@
+import { constants } from 'node:fs';
+import { promises as fs } from 'node:fs';
+import path from 'node:path';
+import { createHash, randomUUID } from 'node:crypto';
+import {
+ createFileReadQueue,
+ buildPeerAttachmentRef,
+ parsePeerAttachmentRef,
+ type PeerAttachment,
+} from '@cindy/device-link';
+import { ownerScopedUserDataPath } from '../appSessionState';
+import { captureDataOwnerBroadcastScope, isDataOwnerBroadcastScopeCurrent } from './broadcast-tap';
+import { getDeviceLinkInvokeContext } from './invoke-context';
+
+// Durable inbox, not media ownership. Normalization ingests into the existing media/file stores.
+// Keep completed uploads retryable across host restarts, like the OSS staging bucket.
+const lifetime = 7 * 24 * 60 * 60_000;
+const queue = createFileReadQueue();
+type Entry = PeerAttachment & { peer: string; createdAt: number; complete: boolean };
+const expired = (entry: Entry, cancelling = false) =>
+ Date.now() - entry.createdAt > (entry.complete || cancelling ? lifetime : 60 * 60_000);
+const validTicket = (value: unknown): value is string =>
+ typeof value === 'string' && /^[a-f0-9-]{36}$/.test(value);
+async function digest(file: string) {
+ const hash = createHash('sha256');
+ const handle = await fs.open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
+ try {
+ for await (const bytes of handle.createReadStream()) hash.update(bytes);
+ } finally {
+ await handle.close().catch(() => {});
+ }
+ return hash.digest('hex');
+}
+export async function handlePeerAttachment(peer: string, r: Record<string, unknown>) {
+ if (r.op !== 'begin' && !validTicket(r.ticket)) throw new Error('INVALID_PEER_ATTACHMENT');
+ const root = ownerScopedUserDataPath('peer-attachment-inbox');
+ const owner = captureDataOwnerBroadcastScope();
+ const check = () => {
+ if (!isDataOwnerBroadcastScopeCurrent(owner)) throw new Error('FILE_PEER_CANCELLED');
+ };
+ // Admission is serialized; ticket operations share only their own ticket's queue.
+ return queue(`${root}:${r.op === 'begin' ? 'admission' : r.ticket}`, async () => {
+ check();
+ await fs.mkdir(root, { recursive: true, mode: 0o700 });
+ if (r.op === 'begin') {
+ const ticket = randomUUID();
+ const parsed = parsePeerAttachmentRef(
+ buildPeerAttachmentRef({ ...r, ticket } as unknown as PeerAttachment),
+ );
+ if (!parsed) throw new Error('INVALID_PEER_ATTACHMENT');
+ let reserved = 0,
+ count = 0;
+ for (const name of await fs.readdir(root)) {
+ if (!name.endsWith('.json') || !validTicket(name.slice(0, -5))) continue;
+ // Reuse the ticket's operation queue; re-read after any in-flight write/finish.
+ await queue(`${root}:${name.slice(0, -5)}`, async () => {
+ check();
+ let entry: Entry;
+ try {
+ entry = JSON.parse(await fs.readFile(path.join(root, name), 'utf8')) as Entry;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;
+ throw error;
+ }
+ if (expired(entry)) {
+ await fs.rm(path.join(root, name.slice(0, -5)), { force: true });
+ await fs.rm(path.join(root, name), { force: true });
+ } else {
+ reserved += entry.size;
+ count++;
+ }
+ });
+ }
+ const space = await fs.statfs(root);
+ if (
+ count >= 128 ||
+ reserved + parsed.size > 4 * 1024 ** 3 ||
+ space.bavail * space.bsize < parsed.size * 2 + 256 * 1024 ** 2
+ )
+ throw new Error('FILE_PEER_STORAGE');
+ check();
+ await fs.writeFile(path.join(root, ticket), '', { flag: 'wx', mode: 0o600 });
+ const entry: Entry = { ...parsed, peer, createdAt: Date.now(), complete: false };
+ await fs.writeFile(path.join(root, `${ticket}.json`), JSON.stringify(entry), {
+ flag: 'wx',
+ mode: 0o600,
+ });
+ check();
+ return { ticket };
+ }
+ if (!validTicket(r.ticket)) throw new Error('INVALID_PEER_ATTACHMENT');
+ const file = path.join(root, r.ticket),
+ manifest = file + '.json';
+ const entry = JSON.parse(await fs.readFile(manifest, 'utf8')) as Entry;
+ if (entry.peer !== peer || expired(entry, r.op === 'cancel'))
+ throw new Error('FILE_PEER_DENIED');
+ check();
+ if (r.op === 'cancel') {
+ await fs.rm(file, { force: true });
+ await fs.rm(manifest, { force: true });
+ return { ok: true };
+ }
+ if (r.op === 'write') {
+ if (
+ entry.complete ||
+ !Number.isSafeInteger(r.offset) ||
+ Number(r.offset) < 0 ||
+ typeof r.data !== 'string' ||
+ r.data.length > 1400000
+ )
+ throw new Error('FILE_PEER_BLOCK');
+ const bytes = Buffer.from(r.data, 'base64');
+ if (
+ !bytes.length ||
+ bytes.length > 1024 * 1024 ||
+ bytes.toString('base64') !== r.data ||
+ Number(r.offset) + bytes.length > entry.size
+ )
+ throw new Error('FILE_PEER_BLOCK');
+ const handle = await fs.open(file, constants.O_RDWR | (constants.O_NOFOLLOW ?? 0));
+ try {
+ if ((await handle.stat()).size !== r.offset) throw new Error('FILE_PEER_BLOCK');
+ check();
+ if (
+ (await handle.write(bytes, 0, bytes.length, Number(r.offset))).bytesWritten !==
+ bytes.length
+ )
+ throw new Error('FILE_PEER_BLOCK');
+ } finally {
+ await handle.close();
+ }
+ entry.createdAt = Date.now();
+ await fs.writeFile(manifest + '.tmp', JSON.stringify(entry), { mode: 0o600 });
+ await fs.rename(manifest + '.tmp', manifest);
+ check();
+ return { ok: true };
+ }
+ if (r.op === 'finish') {
+ if ((await fs.stat(file)).size !== entry.size || (await digest(file)) !== entry.sha256)
+ throw new Error('FILE_PEER_INTEGRITY');
+ check();
+ entry.complete = true;
+ entry.createdAt = Date.now();
+ await fs.writeFile(manifest + '.tmp', JSON.stringify(entry), { mode: 0o600 });
+ await fs.rename(manifest + '.tmp', manifest);
+ check();
+ return { ok: true };
+ }
+ throw new Error('INVALID_PEER_ATTACHMENT');
+ });
+}
+
+async function copyPeerAttachmentBytes(ref: PeerAttachment, destination: string) {
+ const owner = captureDataOwnerBroadcastScope();
+ const root = ownerScopedUserDataPath('peer-attachment-inbox');
+ const file = path.join(root, ref.ticket);
+ const peer = getDeviceLinkInvokeContext()?.controllerDeviceId;
+ if (!peer || !validTicket(ref.ticket)) throw new Error('FILE_PEER_DENIED');
+ const entry = JSON.parse(await fs.readFile(file + '.json', 'utf8')) as Entry;
+ if (
+ !entry.complete ||
+ entry.peer !== peer ||
+ entry.sha256 !== ref.sha256 ||
+ entry.size !== ref.size ||
+ expired(entry)
+ )
+ throw new Error('FILE_PEER_DENIED');
+ if (!isDataOwnerBroadcastScopeCurrent(owner)) throw new Error('FILE_PEER_CANCELLED');
+ await fs.copyFile(file, destination);
+ const valid =
+ (await fs.stat(destination)).size === ref.size && (await digest(destination)) === ref.sha256;
+ if (!isDataOwnerBroadcastScopeCurrent(owner) || !valid) {
+ await fs.rm(destination, { force: true });
+ throw new Error('FILE_PEER_INTEGRITY');
+ }
+}
+
+export async function copyPeerAttachment(ref: PeerAttachment, destination: string) {
+ try {
+ await copyPeerAttachmentBytes(ref, destination);
+ } catch (error) {
+ await fs.rm(destination, { force: true }).catch(() => {});
+ // Filesystem errors include owner-private paths; never propagate them to remote UI.
+ if (error instanceof Error && /^FILE_PEER_(DENIED|INTEGRITY|CANCELLED)$/.test(error.message))
+ throw error;
+ throw new Error('FILE_PEER_ATTACHMENT_UNAVAILABLE');
+ }
+}
diff --git a/apps/desktop/src/main/device-link/remoteAttachment.ts b/apps/desktop/src/main/device-link/remoteAttachment.ts
new file mode 100644
index 0000000000..f68a9a98e8
--- /dev/null
+++ b/apps/desktop/src/main/device-link/remoteAttachment.ts
@@ -0,0 +1,28 @@
+import {
+ isAttachmentOssRef,
+ parseAttachmentOssRef,
+ isPeerAttachmentRef,
+ parsePeerAttachmentRef,
+ type AttachmentIntegrity,
+ type AttachmentOssRef,
+ type PeerAttachment,
+} from '@cindy/device-link';
+import { downloadToFile } from './mediaTransfer';
+import { copyPeerAttachment } from './peerAttachmentStore';
+
+export type RemoteAttachment = AttachmentOssRef & { peer?: PeerAttachment };
+export const isRemoteAttachmentRef = (value: unknown): value is string =>
+ isAttachmentOssRef(value) || isPeerAttachmentRef(value);
+export function parseRemoteAttachmentRef(value: string): RemoteAttachment | null {
+ if (!isPeerAttachmentRef(value)) return parseAttachmentOssRef(value);
+ const peer = parsePeerAttachmentRef(value);
+ return peer ? { ...peer, ossKey: '', peer } : null;
+}
+export async function materializeRemoteAttachment(
+ ref: RemoteAttachment,
+ destination: string,
+ integrity?: AttachmentIntegrity,
+) {
+ if (ref.peer) await copyPeerAttachment(ref.peer, destination);
+ else await downloadToFile(ref.ossKey, destination, integrity);
+}
diff --git a/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts b/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts
index e8e1a82eff..6b6093af8e 100644
--- a/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts
+++ b/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts
@@ -28,9 +28,9 @@ import * as cindyMediaBlobStore from '../cindy-media/blobStore.js';
import * as cindyMediaLedger from '../cindy-media/ledger.js';
import { ingestMedia } from '../cindy-media/ingest.js';
import { createLogger } from '../logger.js';
-import { isAttachmentOssRef, parseAttachmentOssRef } from '../../shared/attachmentOssRef.js';
+import { isRemoteAttachmentRef, parseRemoteAttachmentRef, materializeRemoteAttachment } from '../device-link/remoteAttachment.js';
import type { AttachmentIntegrity, AttachmentOssRef } from '../../shared/attachmentOssRef.js';
-import { downloadToFile, removeRemote } from '../device-link/mediaTransfer.js';
+import { removeRemote } from '../device-link/mediaTransfer.js';
import { throwIpcError } from '../utils/ipcValidate.js';
import { isDangerousAttachmentName } from '../../shared/attachmentSafety.js';
import { readReviewRunOwner, type ReviewRunOwner } from '../../shared/reviewRun.js';
@@ -328,15 +328,15 @@ export async function normalizeUserMessage(
|| (typeof block.path === 'string' && (
block.path.startsWith('xdt-image://')
|| block.path.startsWith('cindy-media://')
- || isAttachmentOssRef(block.path)
+ || isRemoteAttachmentRef(block.path)
))
);
if (isDesktopHostImage) block.pathOrigin = 'desktop-host';
// 0) device-link 出方向 OSS 引用(控制端发来的附件)→ presign-get 下载物化到临时文件,
// 用后删 OSS。新引用下载/校验失败 → 整条不发;旧引用保留历史的单附件降级语义。
- if (typeof block.path === 'string' && isAttachmentOssRef(block.path)) {
- const ref = parseAttachmentOssRef(block.path);
+ if (typeof block.path === 'string' && isRemoteAttachmentRef(block.path)) {
+ const ref = parseRemoteAttachmentRef(block.path);
if (!ref) {
log.warn('malformed oss attach ref, rejecting message');
throwIpcError('DEVICE_LINK_MEDIA_TRANSFER_FAILED', '附件引用无效,请重新上传。');
@@ -345,13 +345,13 @@ export async function normalizeUserMessage(
// 流式下载到临时文件(不整 buffer 进内存,大附件也安全)。
const dest = await ensureTempPath(sessionId, ref.mimeType ?? block.mimeType);
const integrity = integrityForRef(ref);
- await downloadToFile(ref.ossKey, dest, integrity);
+ await materializeRemoteAttachment(ref, dest, integrity);
block.path = dest;
if (!block.mimeType && ref.mimeType) block.mimeType = ref.mimeType;
- void removeRemote(ref.ossKey); // 用后删(best-effort,不阻塞 turn)
+ if (ref.ossKey) void removeRemote(ref.ossKey); // 用后删(best-effort,不阻塞 turn)
} catch (e) {
log.warn('oss attach download failed', { error: String(e) });
- if (isIntegrityMismatch(e)) void removeRemote(ref.ossKey);
+ if (ref.ossKey && isIntegrityMismatch(e)) void removeRemote(ref.ossKey);
// 新客户端声明了完整性时,任何下载/校验失败都必须阻止消息进入 agent;
// 旧引用继续保留历史降级语义,避免升级接收端破坏旧发送端行为。
if (ref.size !== undefined) {
@@ -455,7 +455,7 @@ function isQueuedImageFile(file: SerializedFileLike): boolean {
/** 该字段是 device-link 出方向附件 OSS 引用串。 */
function isOssRefField(v: unknown): v is string {
- return typeof v === 'string' && isAttachmentOssRef(v);
+ return typeof v === 'string' && isRemoteAttachmentRef(v);
}
/** 可物化的本地图片扩展(与 imageCacheStore 的图片 MIME 支持面对齐)。 */
@@ -471,7 +471,7 @@ const LOCAL_IMAGE_EXTS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp']);
function isLocalImagePathField(v: unknown): v is string {
return (
typeof v === 'string' &&
- !isAttachmentOssRef(v) &&
+ !isRemoteAttachmentRef(v) &&
path.isAbsolute(v) &&
LOCAL_IMAGE_EXTS.has(path.extname(v).toLowerCase())
);
@@ -693,14 +693,14 @@ async function materializeQueuedOssAttachmentsInternal(
return null;
}
}
- const ref = parseAttachmentOssRef(refStr);
+ const ref = parseRemoteAttachmentRef(refStr);
if (!ref) {
throwIpcError('DEVICE_LINK_MEDIA_TRANSFER_FAILED', '附件引用无效,请重新上传。');
}
let tmp: string | null = null;
try {
tmp = await ensureTempPath(sessionId, ref.mimeType ?? mimeHint);
- await downloadToFile(ref.ossKey, tmp, integrityForRef(ref));
+ await materializeRemoteAttachment(ref, tmp, integrityForRef(ref));
const mime = ref.mimeType ?? mimeHint;
let entry: MaterializedRef;
// 只收图片进总仓:ingestIntoBlobStore 是整读内存(readFile + sha256),
@@ -727,11 +727,11 @@ async function materializeQueuedOssAttachmentsInternal(
entry = { url, absPath: imageCacheStore.resolveSafe(url).absPath };
}
byRef.set(refStr, entry);
- ossKeys.add(ref.ossKey);
+ if (ref.ossKey) ossKeys.add(ref.ossKey);
return entry;
} catch (e) {
log.warn('materialize queued oss attachment failed, leaving ref', { error: String(e) });
- if (isIntegrityMismatch(e)) void removeRemote(ref.ossKey);
+ if (ref.ossKey && isIntegrityMismatch(e)) void removeRemote(ref.ossKey);
if (ref.size !== undefined) {
throwIpcError(
'DEVICE_LINK_MEDIA_TRANSFER_FAILED',
diff --git a/apps/desktop/src/main/remote-desktop/__tests__/clipboardTransfer.test.ts b/apps/desktop/src/main/remote-desktop/__tests__/clipboardTransfer.test.ts
index c2723489c0..4611b46fe8 100644
--- a/apps/desktop/src/main/remote-desktop/__tests__/clipboardTransfer.test.ts
+++ b/apps/desktop/src/main/remote-desktop/__tests__/clipboardTransfer.test.ts
@@ -6,6 +6,20 @@ beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
describe('clipboard transfer idle expiry', () => {
+ it('replays an acknowledged-lost chunk without duplicating the eventual paste', async () => {
+ const buffer = new ClipboardTransfer();
+ const common = { op: 'clipboardContent' as const, lease: 'lease' };
+ const transfer = vi.fn(async () => undefined);
+ const json = JSON.stringify({ text: 'hello' });
+ const { id } = await buffer.handle({ ...common, action: 'begin', length: json.length }, () => true, transfer) as { id: string };
+ const chunk = { ...common, action: 'write' as const, id, offset: 0, data: json };
+ await buffer.handle(chunk, () => true, transfer);
+ await buffer.handle(chunk, () => true, transfer);
+ await expect(buffer.handle({ ...chunk, data: 'changed' }, () => true, transfer)).rejects.toThrow();
+ await buffer.handle({ ...common, action: 'commit', id }, () => true, transfer);
+ expect(transfer).toHaveBeenCalledTimes(1);
+ await expect(buffer.handle({ ...common, action: 'commit', id }, () => true, transfer)).rejects.toThrow();
+ });
it('returns small copies inline only when requested, and keeps large copies chunked', async () => {
const buffer = new ClipboardTransfer();
const current = () => true;
diff --git a/apps/desktop/src/main/remote-desktop/clipboardTransfer.ts b/apps/desktop/src/main/remote-desktop/clipboardTransfer.ts
index b706043bf7..ad03deb172 100644
--- a/apps/desktop/src/main/remote-desktop/clipboardTransfer.ts
+++ b/apps/desktop/src/main/remote-desktop/clipboardTransfer.ts
@@ -102,6 +102,13 @@ export class ClipboardTransfer {
return { data: value.data.slice(request.offset, request.offset + CLIPBOARD_CHUNK_CHARS) };
}
if (request.action === 'write' && value.direction === 'paste') {
+ // A lost peer acknowledgement may replay this staging chunk over WSS.
+ // Only byte-identical, fully written ranges are idempotent; commit stays single-use.
+ if (request.offset < value.data.length && request.offset + request.data.length <= value.data.length &&
+ value.data.slice(request.offset, request.offset + request.data.length) === request.data) {
+ this.timer?.refresh();
+ return { ok: true };
+ }
if (
request.offset !== value.data.length ||
value.data.length + request.data.length > value.length
diff --git a/apps/desktop/src/preload/desktopCapturePreload.ts b/apps/desktop/src/preload/desktopCapturePreload.ts
index 670d204528..4fa159cf17 100644
--- a/apps/desktop/src/preload/desktopCapturePreload.ts
+++ b/apps/desktop/src/preload/desktopCapturePreload.ts
@@ -41,6 +41,7 @@ if (location.search === '?mode=files') {
ipcRenderer.invoke(FILE_PEER_LOCAL.READ, connection, ticket, offset),
write: (sink, offset, base64) =>
ipcRenderer.invoke(FILE_PEER_LOCAL.WRITE, sink, offset, base64),
+ invoke: (connection, payload) => ipcRenderer.invoke(FILE_PEER_LOCAL.INVOKE, connection, payload),
};
contextBridge.exposeInMainWorld('filePeerHost', files);
} else contextBridge.exposeInMainWorld('desktopCapture', api);
diff --git a/apps/desktop/src/shared/filePeer.ts b/apps/desktop/src/shared/filePeer.ts
index e6feecdb10..92cf5d1fa3 100644
--- a/apps/desktop/src/shared/filePeer.ts
+++ b/apps/desktop/src/shared/filePeer.ts
@@ -5,9 +5,12 @@ export const FILE_PEER_LOCAL = {
REPLY: 'file-peer:host:reply',
READ: 'file-peer:host:read',
WRITE: 'file-peer:host:write',
+ INVOKE: 'file-peer:host:invoke',
} as const;
export type FilePeerCommand =
- | { action: 'offer'; connection: string; servers: DesktopIceServer[] }
+ | { action: 'offer'; connection: string; servers: DesktopIceServer[]; streaming?: boolean }
+ | { action: 'stats'; connection: string }
+ | { action: 'invoke'; connection: string; payload: string }
| { action: 'accept'; connection: string; servers: DesktopIceServer[]; sdp: string }
| { action: 'answer'; connection: string; sdp: string }
| { action: 'receive'; connection: string; ticket: string; size: number; sink: string }
@@ -18,4 +21,5 @@ export interface FilePeerHostApi {
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>;
+ invoke(connection: string, payload: string): Promise<string>;
}
diff --git a/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx b/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx
index cbeacbd37d..6acb8a55cf 100644
--- a/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx
+++ b/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx
@@ -11,6 +11,9 @@ const state = vi.hoisted(() => ({
props: {} as Record<string, (...args: any[]) => void>,
mounts: 0,
unregister: vi.fn(),
+ unregisterInvoke: vi.fn(),
+ unregisterUpload: vi.fn(),
+ unregisterReset: vi.fn(),
install: vi.fn(),
goBack: vi.fn(),
goForward: vi.fn(),
@@ -39,6 +42,9 @@ vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => ({ conn
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; },
+ installPeerInvoke: () => state.unregisterInvoke,
+ installPeerUpload: () => state.unregisterUpload,
+ installPeerReset: () => state.unregisterReset,
clearPeerMedia() {}, recordPeerMedia: vi.fn(),
}));
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
@@ -46,6 +52,7 @@ let root: Root | undefined;
afterEach(() => {
act(() => root?.unmount()); root = undefined;
state.mounts = 0; state.install.mockClear(); state.unregister.mockClear();
+ state.unregisterInvoke.mockClear(); state.unregisterUpload.mockClear(); state.unregisterReset.mockClear();
state.goBack.mockClear(); state.goForward.mockClear();
state.inject.mockClear();
});
@@ -78,6 +85,9 @@ it.each(['onContentProcessDidTerminate', 'onRenderProcessGone'])('recreates peer
const old = state.props;
act(() => old[event]());
expect(state.unregister).toHaveBeenCalledTimes(1);
+ expect(state.unregisterInvoke).toHaveBeenCalledTimes(1);
+ expect(state.unregisterUpload).toHaveBeenCalledTimes(1);
+ expect(state.unregisterReset).toHaveBeenCalledTimes(1);
expect(state.mounts).toBe(2);
act(() => { old[event](); old.onMessage({ nativeEvent: { data: '{"type":"ready"}' } }); });
expect(state.mounts).toBe(2);
diff --git a/apps/mobile/src/__tests__/mobileAttachmentUpload.test.ts b/apps/mobile/src/__tests__/mobileAttachmentUpload.test.ts
index 897b56b6cd..9c590a6c2f 100644
--- a/apps/mobile/src/__tests__/mobileAttachmentUpload.test.ts
+++ b/apps/mobile/src/__tests__/mobileAttachmentUpload.test.ts
@@ -1,5 +1,7 @@
import { beforeAll, describe, expect, it, vi } from 'vitest';
import { apiFetchRaw } from '@/api/client';
+import { installPeerUpload } from '@/device-link/peerFileRegistry';
+import { buildPeerAttachmentRef, parsePeerAttachmentRef } from '@cindy/device-link';
import { DEVICE_LINK_API_BASE_URL } from '@/config/env';
import { i18n } from '@/i18n';
import { buildAttachmentOssRef, parseAttachmentOssRef } from '@/session/attachmentOssRef';
@@ -22,6 +24,41 @@ const readFileChunk = vi.fn(async (_uri: string, _position: number, length: numb
);
describe('mobileAttachmentUpload', () => {
+ it('uploads prepared bytes to the captured peer without presigning OSS', async () => {
+ const apiFetch = vi.fn();
+ const peer = vi.fn(async (_device, _uri, metadata) => buildPeerAttachmentRef({ ...metadata, ticket: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' }));
+ const off = installPeerUpload(peer);
+ try {
+ const attachment = await uploadMobileAttachmentFromFile({ name: 'a.txt', size: 4, mimeType: 'text/plain' }, 'file:///source', {
+ deviceId: 'host-a', token: 'token', deps: { apiFetch, readFileChunk },
+ });
+ expect(peer.mock.calls[0][0]).toBe('host-a');
+ expect(parsePeerAttachmentRef(attachment.path)?.size).toBe(4);
+ expect(apiFetch).not.toHaveBeenCalled();
+ } finally { off(); }
+ });
+ it('never starts OSS after a cancelled peer upload', async () => {
+ const apiFetch = vi.fn();
+ const off = installPeerUpload(async () => { throw new Error('FILE_PEER_CANCELLED'); });
+ try {
+ await expect(uploadMobileAttachmentFromFile({ name: 'a.txt', size: 4 }, 'file:///source', {
+ deviceId: 'host-a', token: 'token', deps: { apiFetch, readFileChunk },
+ })).rejects.toThrow('CANCELLED');
+ expect(apiFetch).not.toHaveBeenCalled();
+ } finally { off(); }
+ });
+ it('falls back to OSS when the peer adapter declines an upload', async () => {
+ const apiFetch = vi.fn(async () => ({ putUrl: 'https://oss.example/upload', key: 'cindy/device-link/u/a.txt' }));
+ const uploadFile = vi.fn(async () => ({ status: 200 }));
+ const off = installPeerUpload(async () => null);
+ try {
+ const attachment = await uploadMobileAttachmentFromFile({ name: 'a.txt', size: 4 }, 'file:///source', {
+ deviceId: 'host-a', token: 'token', deps: { apiFetch: apiFetch as unknown as typeof apiFetchRaw, uploadFile, readFileChunk },
+ });
+ expect(parseAttachmentOssRef(attachment.path)?.ossKey).toBe('cindy/device-link/u/a.txt');
+ expect(uploadFile).toHaveBeenCalledOnce();
+ } finally { off(); }
+ });
it('presigns against the captured shared task rather than the private account namespace', async () => {
const apiFetch = vi.fn(async () => ({ putUrl: 'https://oss.example/upload', key: 'cindy/device-link/shared-task/task/u/file.png', expiresAt: '2026-09-16T12:00:00Z' }));
await presignMobileAttachmentUpload({ name: 'file.png', size: 10, mimeType: 'image/png' }, {
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index 577ca7a978..f756b22554 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -1,4 +1,5 @@
import Constants from 'expo-constants';
+import { tryMobilePeerInvoke, resetMobilePeer } from './peerFileRegistry';
import { isHistoryViewUnavailable } from '@cindy/maker-shared/message-window';
import { findRemoteHistoryView } from '@/session/remoteHistoryView';
import { createBackgroundConnection } from './backgroundConnection';
@@ -1083,6 +1084,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
peerRecoverySchedulerRef.current?.cancel(deviceId);
},
onLinkClosed: (deviceId, reason) => {
+ resetMobilePeer(deviceId);
if (isSharedTaskPeer(deviceId)) setPresenceVersion((version) => version + 1);
catalogRefresh.cancel(deviceId);
resetRemoteProjectOrderPushFence(deviceId);
@@ -1365,6 +1367,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
);
const closeLink = useCallback((deviceId: string) => {
+ resetMobilePeer(deviceId);
registryRef.current.untrackOpenLink(deviceId);
forcedPeerRecoveryIntentRef.current.cancel(deviceId);
openLinkInFlightRef.current.delete(deviceId);
@@ -1399,7 +1402,17 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
preSend();
return accepted;
},
- () => sendInvokeWithAccessHandling<T>(client, deviceId, channel, args, { preSend }),
+ async () => {
+ if (!isSharedTaskPeer(deviceId)) {
+ const result = await tryMobilePeerInvoke(deviceId, channel, args);
+ preSend();
+ if (clientRef.current !== client) throw new DeviceLinkError('NOT_CONNECTED', 'link changed');
+ if (result) {
+ return withAccessRevokedHandling(deviceId, async () => unwrapInvoke<T>(result));
+ }
+ }
+ return sendInvokeWithAccessHandling<T>(client, deviceId, channel, args, { preSend });
+ },
);
}, [sendOpenLinkOnce]);
diff --git a/apps/mobile/src/device-link/peerFileRegistry.ts b/apps/mobile/src/device-link/peerFileRegistry.ts
index f7077f48e6..197c3f25de 100644
--- a/apps/mobile/src/device-link/peerFileRegistry.ts
+++ b/apps/mobile/src/device-link/peerFileRegistry.ts
@@ -1,4 +1,28 @@
import { FILE_PEER_MAX_BYTES } from '@cindy/device-link';
+import type { InvokeResultPayload } from '@cindy/device-link';
+import type { PeerAttachment } from '@cindy/device-link';
+type PeerUpload = (device: string, uri: string, metadata: Omit<PeerAttachment, 'ticket'>, signal?: AbortSignal) => Promise<string | null>;
+let upload: PeerUpload | null = null;
+let reset: ((device: string) => void) | null = null;
+export function installPeerReset(value: (device: string) => void) {
+ reset = value;
+ return () => { if (reset === value) reset = null; };
+}
+export function resetMobilePeer(device: string) { reset?.(device); }
+export function installPeerUpload(value: PeerUpload) {
+ upload = value;
+ return () => { if (upload === value) upload = null; };
+}
+export async function tryMobilePeerUpload(...args: Parameters<PeerUpload>) { return upload?.(...args) ?? null; }
+type PeerInvoke = (device: string, channel: string, args: unknown[]) => Promise<InvokeResultPayload | null>;
+let invoke: PeerInvoke | null = null;
+export function installPeerInvoke(value: PeerInvoke) {
+ invoke = value;
+ return () => { if (invoke === value) invoke = null; };
+}
+export async function tryMobilePeerInvoke(device: string, channel: string, args: unknown[]) {
+ return invoke?.(device, channel, args) ?? null;
+}
export interface LocalPeerMedia {
ossKey: string;
size: number;
diff --git a/apps/mobile/src/device-link/peerFileTransport.tsx b/apps/mobile/src/device-link/peerFileTransport.tsx
index 10b9fd7629..89bd214dd8 100644
--- a/apps/mobile/src/device-link/peerFileTransport.tsx
+++ b/apps/mobile/src/device-link/peerFileTransport.tsx
@@ -1,5 +1,11 @@
-import { canStagePeerMedia } from './peerFileRegistry';
-import { createFileReadQueue } from '@cindy/device-link';
+import { canStagePeerMedia } from "./peerFileRegistry";
+import {
+ createFileReadQueue,
+ createPeerTransferCooldown,
+ canUsePeerInvoke,
+ uploadPeerAttachment,
+ type InvokeResultPayload,
+} from "@cindy/device-link";
import { useEffect, useRef, useState } from "react";
import { AppState, View } from "react-native";
import { WebView } from "react-native-webview";
@@ -24,6 +30,9 @@ import {
import {
installPeerFileDownload,
+ installPeerInvoke,
+ installPeerUpload,
+ installPeerReset,
recordPeerMedia,
clearPeerMedia,
type LocalPeerMedia as LocalMedia,
@@ -72,6 +81,7 @@ export function PeerFileTransport() {
>(),
);
const epoch = useRef(0);
+ const cooldown = useRef(createPeerTransferCooldown());
const account = `${auth.user?.id ?? ""}:${getActiveMobileSessionRealm()}:${auth.isAuthenticated}:${auth.accountGeneration}`;
const owner = `${account}:${link.connectionEpoch}`;
const viewKey = `${owner}:${crashes}`;
@@ -92,11 +102,22 @@ export function PeerFileTransport() {
},
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 };
+ 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 });
});
@@ -109,7 +130,13 @@ export function PeerFileTransport() {
return () => subscription.remove();
}, []);
// Completed files outlive transport reconnects/backgrounding, but never an account switch.
- useEffect(() => () => clearPeerMedia(), [account]);
+ useEffect(
+ () => () => {
+ clearPeerMedia();
+ cooldown.current.clear();
+ },
+ [account],
+ );
useEffect(() => {
if (!foreground || ready !== viewKey || !auth.isAuthenticated) return;
if (!swept) {
@@ -133,32 +160,62 @@ export function PeerFileTransport() {
liveView.current === viewKey &&
AppState.currentState === "active";
let busy = false;
- let connection: { id: string; remote: string; device: string } | null =
- null;
+ const deviceGenerations = new Map<string, object>();
+ const captureDevice = (device: string) => {
+ const generation = deviceGenerations.get(device);
+ return () => current() && deviceGenerations.get(device) === generation;
+ };
+ let connection: {
+ id: string;
+ remote: string;
+ device: string;
+ rpc: boolean;
+ attachments: boolean;
+ } | null = null;
let idle: ReturnType<typeof setTimeout> | undefined;
- const close = () => {
+ const close = (notify = true) => {
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(() => {});
+ if (notify)
+ void link
+ .invoke(old.device, FILE_PEER_CHANNEL, [
+ { action: "close", connection: old.remote },
+ ])
+ .catch(() => {});
}
};
+ const transportCurrent = current;
+ const unregisterReset = installPeerReset((device) => {
+ deviceGenerations.set(device, {});
+ if (connection?.device === device) close(false);
+ });
const transfer = async (
device: string,
- url: string,
+ url: string | null,
signal?: AbortSignal,
readTrace?: number,
): Promise<LocalMedia | null> => {
+ const current = captureDevice(device);
+ // Keep a device close from turning into an upload fallback or reopening its link.
if (!current() || signal?.aborted) throw new Error("FILE_PEER_CANCELLED");
const trace = readTrace || nextFileTrace();
+ const remaining = cooldown.current.remaining(device);
+ if (remaining) {
+ mobileDebugLog("debug", "files", "direct transfer skipped", {
+ trace,
+ reason: "cooldown",
+ remainingMs: remaining,
+ });
+ return null;
+ }
if (busy) {
- mobileDebugLog("debug", "files", "direct transfer skipped", { trace, reason: "busy" });
+ mobileDebugLog("debug", "files", "direct transfer skipped", {
+ trace,
+ reason: "busy",
+ });
return null;
}
busy = true;
@@ -190,18 +247,24 @@ export function PeerFileTransport() {
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]);
+ const invoke = (request: unknown) => {
+ if (!current() || signal?.aborted)
+ throw new Error("FILE_PEER_CANCELLED");
+ return link.invoke<unknown>(device, FILE_PEER_CHANNEL, [request]);
+ };
try {
await link.openLink(device);
if (!remote) {
step = "caps";
const caps = (await invoke({ action: "caps" })) as {
version?: number;
+ streaming?: boolean;
+ attachments?: boolean;
};
if (!current() || signal?.aborted)
throw new Error("FILE_PEER_CANCELLED");
if (caps?.version !== 1) {
+ cooldown.current.fail(device);
mobileDebugLog("debug", "files", "direct transfer skipped", {
trace,
reason: "host-version",
@@ -226,7 +289,11 @@ export function PeerFileTransport() {
if (!current() || signal?.aborted)
throw new Error("FILE_PEER_CANCELLED");
step = "offer";
- const sdp = await command("offer", [id, servers]);
+ const sdp = await command("offer", [
+ id,
+ servers,
+ caps.streaming === true,
+ ]);
step = "host-answer";
const answer = (await invoke({ action: "offer", sdp })) as {
connection?: string;
@@ -245,12 +312,24 @@ export function PeerFileTransport() {
throw new Error("FILE_PEER_CLOSED");
step = "answer";
await command("answer", [id, answer.sdp]);
- connection = { id, remote, device };
+ connection = {
+ id,
+ remote,
+ device,
+ rpc: caps.streaming === true,
+ attachments: caps.attachments === true,
+ };
mobileDebugLog("debug", "files", "direct transfer connected", {
trace,
ms: Date.now() - startedAt,
+ transport: await command("stats", [id]),
});
}
+ if (url === null) {
+ complete = true;
+ cooldown.current.success(device);
+ return null;
+ }
step = "open";
const file = parseFilePeerFile(
await invoke({ action: "open", connection: remote, url }),
@@ -265,6 +344,7 @@ export function PeerFileTransport() {
return null;
}
step = "receive";
+ const transferStartedAt = Date.now();
const directory = new Directory(
Paths.cache,
"remote-media-share",
@@ -306,11 +386,16 @@ export function PeerFileTransport() {
}
target = undefined;
complete = true;
+ cooldown.current.success(device);
mobileDebugLog("debug", "files", "direct transfer done", {
trace,
ms: Date.now() - startedAt,
size: file.size,
mime: file.mimeType,
+ transferMs: Date.now() - transferStartedAt,
+ bytesPerSecond: Math.round(
+ (file.size * 1000) / Math.max(1, Date.now() - transferStartedAt),
+ ),
});
return result;
} catch (error) {
@@ -326,6 +411,7 @@ export function PeerFileTransport() {
});
if (!current() || signal?.aborted)
throw new Error("FILE_PEER_CANCELLED");
+ if (step !== "open") cooldown.current.fail(device);
return null;
} finally {
busy = false;
@@ -338,7 +424,7 @@ export function PeerFileTransport() {
if (complete && current()) idle = setTimeout(close, 30_000);
else {
close();
- if (current()) void command("close", [id]).catch(() => {});
+ if (transportCurrent()) void command("close", [id]).catch(() => {});
if (remote && current())
void invoke({ action: "close", connection: remote }).catch(
() => {},
@@ -347,8 +433,145 @@ export function PeerFileTransport() {
}
};
const queueRead = createFileReadQueue();
- const unregister = installPeerFileDownload((device, url, signal, readTrace) =>
- queueRead('connection', () => transfer(device, url, signal, readTrace), signal));
+ const unregister = installPeerFileDownload(
+ (device, url, signal, readTrace) => {
+ const active = captureDevice(device);
+ return queueRead(
+ "connection",
+ () => {
+ if (!active()) throw new Error("FILE_PEER_CANCELLED");
+ return transfer(device, url, signal, readTrace);
+ },
+ signal,
+ );
+ },
+ );
+ const warming = new Set<string>();
+ const unregisterUpload = installPeerUpload(
+ (device, uri, metadata, signal) => {
+ const current = captureDevice(device);
+ return queueRead(
+ "connection",
+ async () => {
+ const check = () => {
+ if (!current() || signal?.aborted)
+ throw new Error("FILE_PEER_CANCELLED");
+ };
+ check();
+ if (cooldown.current.remaining(device)) return null;
+ let handle: ReturnType<File["open"]> | undefined;
+ try {
+ await transfer(device, null, signal);
+ check();
+ const active = connection;
+ if (!active || active.device !== device || !active.attachments)
+ return null;
+ clearTimeout(idle);
+ busy = true;
+ handle = new File(uri).open();
+ const transferStartedAt = Date.now();
+ const result = await uploadPeerAttachment(
+ metadata,
+ async (offset, length) => {
+ handle!.offset = offset;
+ const bytes = handle!.readBytes(length);
+ if (bytes.length !== length)
+ throw new Error("FILE_PEER_CHANGED");
+ let binary = "";
+ for (const byte of bytes) binary += String.fromCharCode(byte);
+ return btoa(binary);
+ },
+ async (request) => {
+ check();
+ const raw = await command("invoke", [
+ active.id,
+ JSON.stringify({
+ channel: FILE_PEER_CHANNEL,
+ args: [
+ {
+ action: "attachment",
+ connection: active.remote,
+ request,
+ },
+ ],
+ }),
+ ]);
+ check();
+ const response = JSON.parse(String(raw));
+ if (!response.ok) throw new Error("FILE_PEER_UPLOAD");
+ return response.result;
+ },
+ check,
+ );
+ const ms = Date.now() - transferStartedAt;
+ mobileDebugLog("debug", "files", "peer attachment uploaded", {
+ bytes: metadata.size,
+ transferMs: ms,
+ bytesPerSecond: Math.round(
+ (metadata.size * 1000) / Math.max(1, ms),
+ ),
+ });
+ return result;
+ } catch {
+ check();
+ cooldown.current.fail(device);
+ return null;
+ } finally {
+ try {
+ handle?.close();
+ } catch {}
+ busy = false;
+ if (current()) idle = setTimeout(close, 30_000);
+ }
+ },
+ signal,
+ );
+ },
+ );
+ const unregisterInvoke = installPeerInvoke(
+ async (device, channel, args) => {
+ const current = captureDevice(device);
+ if (!canUsePeerInvoke(channel, args)) return null;
+ if (!current()) throw new Error("FILE_PEER_CANCELLED");
+ if (cooldown.current.remaining(device)) return null;
+ if (connection?.device !== device || !connection.rpc) {
+ if (
+ (!connection || connection.device !== device) &&
+ !warming.has(device)
+ ) {
+ warming.add(device);
+ void queueRead("connection", () => {
+ if (!current()) throw new Error("FILE_PEER_CANCELLED");
+ return transfer(device, null);
+ })
+ .catch(() => {})
+ .finally(() => warming.delete(device));
+ }
+ return null;
+ }
+ const id = connection.id;
+ clearTimeout(idle);
+ try {
+ const raw = await command("invoke", [
+ id,
+ JSON.stringify({ channel, args }),
+ ]);
+ if (!current()) throw new Error("FILE_PEER_CANCELLED");
+ const result = JSON.parse(String(raw)) as InvokeResultPayload;
+ if (!result || typeof result.ok !== "boolean")
+ throw new Error("FILE_PEER_REPLY");
+ return result;
+ } catch {
+ if (!current()) throw new Error("FILE_PEER_CANCELLED");
+ cooldown.current.fail(device);
+ // A read can finish after a transfer started, or after another peer replaced it.
+ if (!busy && connection?.id === id) close();
+ return null;
+ } finally {
+ if (current() && !busy) idle = setTimeout(close, 30_000);
+ }
+ },
+ );
mobileDebugLog("debug", "files", "direct transfer ready");
return () => {
mobileDebugLog("debug", "files", "direct transfer reset", {
@@ -358,6 +581,9 @@ export function PeerFileTransport() {
close();
++epoch.current;
unregister();
+ unregisterInvoke();
+ unregisterUpload();
+ unregisterReset();
for (const p of pending.current.values()) {
clearTimeout(p.timer);
p.reject(new Error("FILE_PEER_CLOSED"));
@@ -369,12 +595,16 @@ export function PeerFileTransport() {
} catch {}
}
sinks.current.clear();
- view.current?.injectJavaScript("if (typeof runtime !== 'undefined') runtime.dispose();true;");
+ view.current?.injectJavaScript(
+ "if (typeof runtime !== 'undefined') runtime.dispose();true;",
+ );
};
}, [foreground, ready, auth.isAuthenticated, viewKey]);
const handleProcessTerminated = () => {
if (liveView.current !== viewKey) return;
- mobileDebugLog("warn", "files", "direct transfer runtime terminated", { crashes });
+ mobileDebugLog("warn", "files", "direct transfer runtime terminated", {
+ crashes,
+ });
setReady(null);
setCrashes((n) => Math.min(2, n + 1));
};
@@ -406,7 +636,7 @@ export function PeerFileTransport() {
onMessage={(event) => {
try {
if (liveView.current !== viewKey) return;
- if (event.nativeEvent.data.length > 140000) return;
+ if (event.nativeEvent.data.length > 8 * 1024 * 1024) return;
const m = JSON.parse(event.nativeEvent.data);
if (m.type === "ready") {
setReady(viewKey);
@@ -440,7 +670,8 @@ export function PeerFileTransport() {
throw new Error();
sink.handle.writeBytes(bytes);
sink.offset += bytes.length;
- for (const operation of pending.current.values()) operation.refresh?.();
+ for (const operation of pending.current.values())
+ operation.refresh?.();
ok = true;
} catch {}
send({ type: "writeReply", id: m.id, ok });
diff --git a/apps/mobile/src/session/MobileOutboxBridge.tsx b/apps/mobile/src/session/MobileOutboxBridge.tsx
index 5b123a245a..f9bf9c14ee 100644
--- a/apps/mobile/src/session/MobileOutboxBridge.tsx
+++ b/apps/mobile/src/session/MobileOutboxBridge.tsx
@@ -7,7 +7,7 @@ import {
subscribeMobileAuthOwner,
} from "@/auth/authOwnerGeneration";
import { useDeviceLink } from "@/device-link/DeviceLinkContext";
-import { parseSharedTaskPeer } from '@cindy/device-link';
+import { parseSharedTaskPeer } from "@cindy/device-link";
import {
createMobileMakerTransport,
type RemoteInvoke,
@@ -45,7 +45,10 @@ import {
prepareMobileQueuedSessionReferences,
} from "./sessionReferences";
import { remoteSessionStore } from "./remoteSessionStore";
-import { isDurableOutboxSettled, type DurableOutboxRecord } from "./durableOutbox";
+import {
+ isDurableOutboxSettled,
+ type DurableOutboxRecord,
+} from "./durableOutbox";
import type { InputProjection } from "./types";
/** Runs only while the OS gives the app execution time; foreground/reconnect resume the same ledger. */
@@ -54,8 +57,15 @@ export function MobileOutboxBridge() {
const link = useDeviceLink();
const latest = useRef({ auth, link });
latest.current = { auth, link };
- const owner = useSyncExternalStore(subscribeMobileAuthOwner, getMobileAuthOwner, getMobileAuthOwner);
- const accountId = auth.isAuthenticated && auth.user?.id?.trim() === owner.accountId ? owner.accountKey : "";
+ const owner = useSyncExternalStore(
+ subscribeMobileAuthOwner,
+ getMobileAuthOwner,
+ getMobileAuthOwner,
+ );
+ const accountId =
+ auth.isAuthenticated && auth.user?.id?.trim() === owner.accountId
+ ? owner.accountKey
+ : "";
const runnerRef = useRef<ReturnType<
typeof createDurableOutboxDelivery
> | null>(null);
@@ -244,7 +254,11 @@ export function MobileOutboxBridge() {
const attachment = await uploadMobileAttachmentFromFile(
upload,
durableOutboxUploadUri(r, upload),
- { token, sharedTaskId: parseSharedTaskPeer(r.deviceId)?.sharedTaskId },
+ {
+ token,
+ deviceId: r.deviceId,
+ sharedTaskId: parseSharedTaskPeer(r.deviceId)?.sharedTaskId,
+ },
);
if (!isCurrent() || !mobileDurableOutbox.getSnapshot().includes(r)) {
// Use the captured credential for this old owner's object, never a new account's token.
@@ -297,8 +311,20 @@ export function MobileOutboxBridge() {
});
return found;
},
- cleanup: (record, cancelled) => cleanupOutboxResources(record, owner, () => latest.current.auth.getAccessToken(), cancelled),
- discardUploads: (record, attachments) => discardOutboxUploads(record, owner, () => latest.current.auth.getAccessToken(), attachments),
+ cleanup: (record, cancelled) =>
+ cleanupOutboxResources(
+ record,
+ owner,
+ () => latest.current.auth.getAccessToken(),
+ cancelled,
+ ),
+ discardUploads: (record, attachments) =>
+ discardOutboxUploads(
+ record,
+ owner,
+ () => latest.current.auth.getAccessToken(),
+ attachments,
+ ),
mediaFailed: (error) =>
formatRemoteError(error).includes("DEVICE_LINK_MEDIA_TRANSFER_FAILED"),
retryable: (error) =>
@@ -313,7 +339,10 @@ export function MobileOutboxBridge() {
const run = () => {
refreshLeases();
// Scavenging failure blocks new copies, not already-owned messages' delivery.
- void initializeOutboxFiles().catch(() => undefined).then(() => delivery.run()).catch(() => undefined);
+ void initializeOutboxFiles()
+ .catch(() => undefined)
+ .then(() => delivery.run())
+ .catch(() => undefined);
};
void mobileDurableOutbox
.activate(accountId)
diff --git a/apps/mobile/src/session/attachments.ts b/apps/mobile/src/session/attachments.ts
index f1ee0418fd..10afd0e10a 100644
--- a/apps/mobile/src/session/attachments.ts
+++ b/apps/mobile/src/session/attachments.ts
@@ -2,6 +2,7 @@ import { stripTrailingPathSeparators } from '@cindy/maker-shared/path-text';
import { i18n } from '@/i18n';
import type { RemoteFileRef, RemoteImageRef, RemoteSerializedAttachment } from '@/session/types';
import { buildLegacyAttachmentOssRef } from '@/session/attachmentOssRef';
+import { parsePeerAttachmentRef } from '@cindy/device-link';
export type MobileAttachmentCategory = RemoteSerializedAttachment['category'];
@@ -171,14 +172,15 @@ export function buildMobileRemoteFileAttachment(
}
export function buildMobileUploadedAttachment(input: {
- ossKey: string;
+ ossKey?: string;
+ peerRef?: string;
name: string;
size: number;
sha256: string;
mimeType?: string;
id?: string;
}): RemoteSerializedAttachment | null {
- if (!input.ossKey.trim()) return null;
+ if (input.peerRef ? !parsePeerAttachmentRef(input.peerRef) : !input.ossKey?.trim()) return null;
if (!Number.isFinite(input.size) || input.size <= 0 || input.size > MOBILE_MAX_ATTACHMENT_BYTES) return null;
const name = basenameRemotePath(input.name).trim();
if (!name) return null;
@@ -186,15 +188,15 @@ export function buildMobileUploadedAttachment(input: {
if (!category) return null;
const ext = extractRemoteFileExt(name);
const mimeType = input.mimeType?.trim() || mimeTypeForMobileAttachment(ext, category);
- const ref = buildLegacyAttachmentOssRef({
- ossKey: input.ossKey,
+ const ref = input.peerRef ?? buildLegacyAttachmentOssRef({
+ ossKey: input.ossKey!,
mimeType,
originalName: name,
size: input.size,
sha256: input.sha256,
});
return {
- id: input.id ?? `mobile-upload:${input.ossKey}`,
+ id: input.id ?? `mobile-upload:${input.ossKey ?? parsePeerAttachmentRef(input.peerRef!)!.ticket}`,
name,
path: ref,
ext,
diff --git a/apps/mobile/src/session/durableOutboxFiles.ts b/apps/mobile/src/session/durableOutboxFiles.ts
index 91f510f8a8..86b1c91806 100644
--- a/apps/mobile/src/session/durableOutboxFiles.ts
+++ b/apps/mobile/src/session/durableOutboxFiles.ts
@@ -4,10 +4,11 @@ import AsyncStorage from '@react-native-async-storage/async-storage';
import { DURABLE_OUTBOX_PREFIX, type DurableOutboxRecord, type DurableUpload } from "./durableOutbox";
import type { MobileLocalAttachmentUploadCandidate } from "./mobileLocalAttachmentUpload";
import { isAttachmentOssRef } from './attachmentOssRef';
+import { isPeerAttachmentRef } from '@cindy/device-link';
/** Desktop path references already have their source on the controlled device. */
export function outboxAttachmentNeedsLocalBytes(attachment: { path: string }): boolean {
- return isAttachmentOssRef(attachment.path);
+ return isAttachmentOssRef(attachment.path) || isPeerAttachmentRef(attachment.path);
}
function segment(value: string): string {
diff --git a/apps/mobile/src/session/mobileAttachmentUpload.ts b/apps/mobile/src/session/mobileAttachmentUpload.ts
index 612850f8de..e96e4706d7 100644
--- a/apps/mobile/src/session/mobileAttachmentUpload.ts
+++ b/apps/mobile/src/session/mobileAttachmentUpload.ts
@@ -1,4 +1,5 @@
import { apiFetchRaw } from '@/api/client';
+import { tryMobilePeerUpload } from '@/device-link/peerFileRegistry';
import { DEVICE_LINK_API_BASE_URL } from '@/config/env';
import { i18n } from '@/i18n';
import { withTransientRemoteRetry } from '@/device-link/remoteRetry';
@@ -329,6 +330,7 @@ export async function uploadMobileAttachmentFromFile(
options: {
token: string | null;
sharedTaskId?: string;
+ deviceId?: string;
id?: string;
deps?: UploadDeps;
signal?: AbortSignal;
@@ -352,6 +354,16 @@ export async function uploadMobileAttachmentFromFile(
readChunk: options.deps?.readFileChunk,
signal: options.signal,
});
+ if (options.deviceId && !options.sharedTaskId) {
+ const peerRef = await tryMobilePeerUpload(options.deviceId, snapshot.uri, {
+ size: candidate.size, sha256, mimeType: candidate.mimeType, originalName: candidate.name,
+ }, options.signal);
+ if (peerRef) {
+ const attachment = buildMobileUploadedAttachment({ ...candidate, sha256, peerRef, id: options.id });
+ if (!attachment) throw new Error(i18n.t('composer.upload.fileTypeUnsupported'));
+ return attachment;
+ }
+ }
const presigned = await presignMobileAttachmentUpload(candidate, options);
try {
await putMobileAttachmentUploadFromFile(
diff --git a/apps/mobile/src/session/mobileLocalAttachmentUpload.ts b/apps/mobile/src/session/mobileLocalAttachmentUpload.ts
index 877eb05b0f..c11f46a876 100644
--- a/apps/mobile/src/session/mobileLocalAttachmentUpload.ts
+++ b/apps/mobile/src/session/mobileLocalAttachmentUpload.ts
@@ -33,6 +33,7 @@ export interface MobileLocalAttachmentUploadCandidate {
attachmentScopeKey?: string;
/** Destination captured when enqueued, never read from a later active task. */
sharedTaskId?: string;
+ deviceId?: string;
/** 同一作用域重复进入时也会递增的代际;避免 A → B → A 后接回最早 A 的旧结果。 */
attachmentScopeGeneration?: number;
mimeType?: string;
@@ -103,7 +104,7 @@ export interface MobileLocalAttachmentUploadDeps {
assertSize(size: number, candidate: MobileLocalAttachmentUploadCandidate): void;
/** 真正的 presign + PUT(uploadMobileAttachmentFromFile);signal 中止时应尽快断掉传输。 */
upload(
- candidate: { name: string; size: number; mimeType?: string; sharedTaskId?: string },
+ candidate: { name: string; size: number; mimeType?: string; sharedTaskId?: string; deviceId?: string },
fileUri: string,
opts: { token: string; signal?: AbortSignal },
): Promise<RemoteSerializedAttachment>;
@@ -410,7 +411,7 @@ export function createMobileLocalAttachmentUploadController(
return;
}
const attachment = uploadedAttachment = await step(deps.upload(
- { name: prepared.name, size, mimeType: prepared.mimeType || undefined, ...(source.sharedTaskId ? { sharedTaskId: source.sharedTaskId } : {}) },
+ { name: prepared.name, size, mimeType: prepared.mimeType || undefined, ...(source.sharedTaskId ? { sharedTaskId: source.sharedTaskId } : {}), ...(source.deviceId ? { deviceId: source.deviceId } : {}) },
prepared.uri,
{ token, signal },
), (late) => deps.discard(late, token));
diff --git a/apps/mobile/src/session/useMobileLocalAttachments.ts b/apps/mobile/src/session/useMobileLocalAttachments.ts
index 42164e8f76..08716b8ca7 100644
--- a/apps/mobile/src/session/useMobileLocalAttachments.ts
+++ b/apps/mobile/src/session/useMobileLocalAttachments.ts
@@ -276,7 +276,7 @@ export function useMobileLocalAttachments(
if (candidate.kind === 'image') assertMobileImageSize(size);
else assertMobileDocumentSize(size);
},
- upload: (candidate, fileUri, opts) => uploadMobileAttachmentFromFile(candidate, fileUri, { ...opts, sharedTaskId: candidate.sharedTaskId }),
+ upload: (candidate, fileUri, opts) => uploadMobileAttachmentFromFile(candidate, fileUri, { ...opts, sharedTaskId: candidate.sharedTaskId, deviceId: candidate.deviceId }),
discard: (attachment, token) => discardMobileUploadedAttachment(attachment, {
getToken: () => token === undefined ? optionsRef.current.getAccessToken() : Promise.resolve(token),
}),
@@ -382,13 +382,11 @@ export function useMobileLocalAttachments(
) => {
if (!isAttachmentScopeActive()) return;
controller.enqueue(
- attachmentScopeKey == null
- ? candidates
- : candidates.map((candidate) => ({
+ candidates.map((candidate) => ({
...candidate,
- attachmentScopeGeneration,
- attachmentScopeKey,
+ ...(attachmentScopeKey == null ? {} : { attachmentScopeGeneration, attachmentScopeKey }),
sharedTaskId: parseSharedTaskPeer(optionsRef.current.deviceId ?? '')?.sharedTaskId,
+ deviceId: optionsRef.current.deviceId,
})),
opts,
);
diff --git a/docs/dev-rules/remote-desktop-connectivity.md b/docs/dev-rules/remote-desktop-connectivity.md
index a4ec360ad0..d9389b4138 100644
--- a/docs/dev-rules/remote-desktop-connectivity.md
+++ b/docs/dev-rules/remote-desktop-connectivity.md
@@ -228,6 +228,10 @@ Mobile export/share and requested HTML resources use this policy. Directory list
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.
+The first directory/text request uses the existing WSS path immediately and starts
+one background file-peer setup. Ready peers carry subsequent reads on a separate
+bounded data channel; transport failure falls back to WSS, while a host error remains
+a host error. The same authorized dispatch runs on the host for either transport.
Whole-file reads request `prepareOnly` after host authorization. Up to 64 KiB,
including empty files, returns inline bytes; larger files attempt the reusable
@@ -257,7 +261,7 @@ 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
+with at most 64 outstanding blocks on negotiated `files-v2` (1 MiB), 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.
@@ -308,6 +312,50 @@ 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.
+### Automatic acceleration and fallback
+
+Protocol version 1 remains unchanged. Optional `caps.streaming` selects `files-v2`
+and its separate `reads-v1` request channel; an old host uses `files-v1` with the
+original 16-block batches. V2 replenishes credit after every 32 completed sink
+writes, overlapping network reads and disk writes without unbounded buffering.
+The request channel caps each payload at 4 MiB and outstanding requests at four.
+It accepts directory/text reads, clipboard read/write chunks, and negotiated
+attachment staging only. Clipboard begin/copy/commit and ordinary mutations stay
+on WSS. Identical clipboard staging writes can be replayed after a lost response;
+commit remains single-use, so fallback cannot paste twice.
+
+Failed peer attempts enter per-device cooldown: 30 seconds initially, exponential
+backoff capped at five minutes. Queued transfers provide a single retry after the
+cooldown; success resets the backoff. Cancellation/account changes reject instead
+of starting OSS. Cooldown has no background polling and does not stop another
+device's connection. Local diagnostics record selected direct/relay path, transport
+protocol, RTT, setup time, bytes, transfer time, throughput and fallback stage;
+candidate addresses, paths and payloads are not added to these metrics.
+
+Optional `caps.attachments` enables controller-to-host byte staging for Desktop and
+Mobile, complementing the existing host-to-controller download path. Staging failure
+abandons the upload and falls back to OSS before the message is sent. Shared-task
+guests continue using their existing OSS scope. New peer references are sent only
+to a capable host. The receiving Main process checks size and SHA-256 before returning
+the reference, then normal message acceptance materializes it through the existing
+media/file ownership logic. Message acceptance itself remains on WSS.
+
+The host inbox lives under the current owner's userData namespace. Tickets bind to
+the source controller and are rechecked when materialized. Completed staging survives
+host restarts for seven days; incomplete staging expires after an hour. Admission
+sweeps expired entries and bounds retained reservations to 4 GiB / 128 uploads, with
+space for the consumer copy plus 256 MiB. This inbox is transport staging, not a new
+media store. Mobile retains local source bytes in its durable outbox for retry.
+
+Reproducible local probe: `node scripts/file-peer-smoke.mjs <Chrome> --benchmark`
+adds a 1 ms timer to each simulated source/sink bridge operation. On 2026-09-26,
+the 8 MiB case took 4433 ms with V1 and 2834 ms with V2 (about 36% less elapsed
+time). Local ICE setup was 203 / 124 ms respectively; these figures exclude cloud
+signaling, TURN config fetch and app cold start and are not a WAN speed claim.
+The `--large` probe also passed 101 MiB, exact bytes, EOF, sink failure, fragmented
+Unicode RPC, four concurrent RPCs and RPC during file transfer. Actual Mobile
+WebView/native I/O, deployed TURN and network switching still require device QA.
+
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
@@ -316,3 +364,32 @@ commands use a 60-second deadline renewed by successful disk writes rather than
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.
+
+### Unattended peer-transfer acceptance
+
+Run `pnpm test:peer-transfer` from an installed checkout (Node 22.12+, pnpm).
+No login, second device or manual network toggling is needed. The runner discovers
+Chrome (or installs Playwright Chromium), runs shared/Desktop/Mobile business
+tests and type checks, checks the generated WebView source, then exercises the
+production browser runtime with V1/V2, 101 MiB files, Unicode RPC and a slow bridge.
+It installs pinned `[email protected]` into an isolated temporary directory, starts
+a UDP TURN server bound only to loopback with random in-memory credentials, and
+forces relay-only ICE. Selected-pair stats must report `relay`; direct connectivity
+cannot silently make the relay test pass. This fixture is not a shipping dependency.
+
+The fault probe disconnects a real peer during a random 2 MiB transfer, validates
+the HTTP fallback's SHA-256 through the production file-read policy, confirms
+repeated reads skip peer during cooldown, advances an injected cooldown clock,
+and verifies recovery, slow writes, cancellation, reverse attachment staging and
+connection isolation. HTTP storage and attachment receiver are test adapters;
+real Main attachment persistence/ownership and clipboard replay behavior are
+covered separately by the business tests. These are layered integration tests,
+not a full logged-in app UI test.
+
+Each stage has a deadline; failures exit nonzero. Children and fixture directories
+are cleaned up automatically. A unique OS temporary directory retains stage logs,
+`report.json` (including browser measurements) and `report.md`; its path is printed.
+The report explicitly excludes deployed TURN, TURN TCP/TLS, WAN NAT, physical
+network switching, real OSS and native iOS/Android WebView. A local pass must not
+be presented as passing those environments. No user files or account credentials
+are read by this runner.
diff --git a/package.json b/package.json
index 7dff35ee0e..f63d3e4f8a 100644
--- a/package.json
+++ b/package.json
@@ -139,6 +139,7 @@
"test:db": "pnpm test:runner && node scripts/test-workspaces.mjs --tier db",
"test:guard": "node scripts/test-workspaces.mjs --tier guard",
"test:device-link": "node apps/mobile/scripts/device-link-reconnect-smoke.mjs",
+ "test:peer-transfer": "node scripts/peer-transfer-acceptance.mjs",
"ci:scheduler-guard": "node scripts/scheduler-ci-guard.mjs",
"pctx": "node packages/project-context/dist/cli.js",
"pctx:build": "pnpm --filter project-context build"
diff --git a/packages/device-link/src/__tests__/peerAcceleration.test.ts b/packages/device-link/src/__tests__/peerAcceleration.test.ts
new file mode 100644
index 0000000000..fa050280cb
--- /dev/null
+++ b/packages/device-link/src/__tests__/peerAcceleration.test.ts
@@ -0,0 +1,85 @@
+import { describe, expect, it, vi } from "vitest";
+import { createPeerTransferCooldown } from "../peerTransferCooldown.js";
+import { canUsePeerInvoke } from "../peerInvoke.js";
+import { REMOTE_DESKTOP_CHANNEL } from "../remoteDesktop.js";
+import {
+ uploadPeerAttachment,
+ parsePeerAttachmentRef,
+ buildPeerAttachmentRef,
+} from "../peerAttachment.js";
+
+describe("peer acceleration policy", () => {
+ it("backs off only the failing device, caps delay and recovers after success", () => {
+ let time = 0;
+ const cd = createPeerTransferCooldown(() => time);
+ expect(cd.fail("a")).toBe(30_000);
+ expect(cd.remaining("b")).toBe(0);
+ time = 30_001;
+ expect(cd.remaining("a")).toBe(0);
+ expect(cd.fail("a")).toBe(60_000);
+ for (let i = 0; i < 10; i++) cd.fail("a");
+ expect(cd.remaining("a")).toBe(300_000);
+ cd.success("a");
+ expect(cd.fail("a")).toBe(30_000);
+ cd.clear();
+ expect(cd.remaining("a")).toBe(0);
+ });
+ it("never retries clipboard commits or arbitrary remote commands through peer", () => {
+ expect(
+ canUsePeerInvoke("file-browser:remote-op", [{ op: "readFile" }]),
+ ).toBe(true);
+ expect(canUsePeerInvoke("file-browser:remote-op", [{ op: "delete" }])).toBe(
+ false,
+ );
+ expect(
+ canUsePeerInvoke(REMOTE_DESKTOP_CHANNEL, [
+ { op: "clipboardContent", action: "write" },
+ ]),
+ ).toBe(true);
+ expect(
+ canUsePeerInvoke(REMOTE_DESKTOP_CHANNEL, [
+ { op: "clipboardContent", action: "commit" },
+ ]),
+ ).toBe(false);
+ expect(canUsePeerInvoke("maker:send", [{}])).toBe(false);
+ });
+ it("finishes byte staging before returning a reference; cancellation never finishes", async () => {
+ const ticket = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+ const metadata = { size: 1, sha256: "a".repeat(64), originalName: "a.txt" };
+ const invoke = vi.fn(async (_request: Record<string, unknown>) => ({
+ ticket,
+ }));
+ const ref = await uploadPeerAttachment(
+ metadata,
+ async () => "YQ==",
+ invoke,
+ () => {},
+ );
+ expect(parsePeerAttachmentRef(ref)).toEqual({ ...metadata, ticket });
+ expect(invoke.mock.calls.map(([r]) => (r as any).op)).toEqual([
+ "begin",
+ "write",
+ "finish",
+ ]);
+ expect(parsePeerAttachmentRef("cindy-peer-attach://bad")).toBeNull();
+ expect(() =>
+ buildPeerAttachmentRef({ ...metadata, ticket: "../evil" }),
+ ).toThrow();
+ invoke.mockClear();
+ let checks = 0;
+ await expect(
+ uploadPeerAttachment(
+ metadata,
+ async () => "YQ==",
+ invoke,
+ () => {
+ if (++checks > 1) throw new Error("cancelled");
+ },
+ ),
+ ).rejects.toThrow("cancelled");
+ expect(invoke.mock.calls.map(([r]) => (r as any).op)).toEqual([
+ "begin",
+ "cancel",
+ ]);
+ });
+});
diff --git a/packages/device-link/src/filePeer.ts b/packages/device-link/src/filePeer.ts
index 8ff24ed726..100a5fa3ea 100644
--- a/packages/device-link/src/filePeer.ts
+++ b/packages/device-link/src/filePeer.ts
@@ -10,6 +10,7 @@ export type FilePeerRequest =
| { action: "caps" }
| { action: "offer"; sdp: string }
| { action: "open"; connection: string; url: string }
+ | { action: "attachment"; connection: string; request: Record<string, unknown> }
| { action: "close"; connection: string };
export interface FilePeerFile {
@@ -34,6 +35,8 @@ export function parseFilePeerRequest(value: unknown): FilePeerRequest {
throw new Error("INVALID_FILE_PEER_REQUEST");
if (v.action === "close")
return { action: "close", connection: v.connection };
+ if (v.action === "attachment" && v.request && typeof v.request === "object" && !Array.isArray(v.request))
+ return { action: "attachment", connection: v.connection, request: v.request as Record<string, unknown> };
if (
v.action === "open" &&
typeof v.url === "string" &&
diff --git a/packages/device-link/src/filePeerRuntime.ts b/packages/device-link/src/filePeerRuntime.ts
index 50e215b405..bb0be1de13 100644
--- a/packages/device-link/src/filePeerRuntime.ts
+++ b/packages/device-link/src/filePeerRuntime.ts
@@ -3,12 +3,14 @@
export interface FilePeerRuntimeBridge {
read(connection: string, ticket: string, offset: number): Promise<string>;
write(sink: string, offset: number, base64: string): Promise<void>;
+ invoke?(connection: string, payload: string): Promise<string>;
}
/**
* 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.
+ * V2 keeps a bounded 1 MiB credit window in flight; disk writes replenish credit.
+ * V1 remains available for peers that did not advertise streaming support.
*/
export function createFilePeerRuntime(bridge: FilePeerRuntimeBridge) {
const peers = new Map<
@@ -17,7 +19,129 @@ export function createFilePeerRuntime(bridge: FilePeerRuntimeBridge) {
>();
const chunkBytes = 16384;
const maxBytes = 2147483648;
+ const rpcPeers = new Map<
+ string,
+ {
+ channel: RTCDataChannel;
+ request(payload: string): Promise<string>;
+ close(): void;
+ }
+ >();
+ function attachRpc(id: string, dc: RTCDataChannel) {
+ const pending = new Map<
+ string,
+ {
+ resolve(value: string): void;
+ reject(error: Error): void;
+ timer: ReturnType<typeof setTimeout>;
+ }
+ >();
+ const fragments = new Map<
+ string,
+ { data: string; timer: ReturnType<typeof setTimeout> }
+ >();
+ let sequence = 0;
+ let active = 0;
+ const send = (key: string, response: boolean, value: string) => {
+ if (value.length > 4 * 1024 * 1024 || dc.readyState !== "open")
+ throw new Error("FILE_PEER_RPC_SIZE");
+ for (let offset = 0; offset < Math.max(1, value.length); offset += 16384)
+ dc.send(
+ JSON.stringify({
+ key,
+ response,
+ data: value.slice(offset, offset + 16384),
+ last: offset + 16384 >= value.length,
+ }),
+ );
+ };
+ const shutdown = () => {
+ for (const p of pending.values()) {
+ clearTimeout(p.timer);
+ p.reject(new Error("FILE_PEER_CLOSED"));
+ }
+ for (const f of fragments.values()) clearTimeout(f.timer);
+ pending.clear();
+ fragments.clear();
+ dc.close();
+ };
+ dc.onclose = shutdown;
+ dc.onmessage = ({ data }) => {
+ try {
+ if (typeof data !== "string" || data.length > 100000) throw new Error();
+ const m = JSON.parse(data);
+ if (
+ typeof m.key !== "string" ||
+ !/^\d{1,12}$/.test(m.key) ||
+ typeof m.response !== "boolean" ||
+ typeof m.last !== "boolean" ||
+ typeof m.data !== "string" ||
+ m.data.length > 16384
+ )
+ throw new Error();
+ if (m.response && !pending.has(m.key)) return;
+ const key = `${m.response}:${m.key}`;
+ let f = fragments.get(key);
+ if (!f) {
+ if (fragments.size >= 8) throw new Error();
+ f = { data: "", timer: setTimeout(() => close(id), 15000) };
+ fragments.set(key, f);
+ }
+ f.data += m.data;
+ if (f.data.length > 4 * 1024 * 1024) throw new Error();
+ if (!m.last) return;
+ clearTimeout(f.timer);
+ fragments.delete(key);
+ if (m.response) {
+ const p = pending.get(m.key)!;
+ pending.delete(m.key);
+ clearTimeout(p.timer);
+ p.resolve(f.data);
+ } else {
+ if (!bridge.invoke || active >= 4) throw new Error();
+ active++;
+ void bridge
+ .invoke(id, f.data)
+ .then((value) => {
+ if (peers.has(id)) send(m.key, true, value);
+ })
+ .catch(() => close(id))
+ .finally(() => {
+ active--;
+ });
+ }
+ } catch {
+ close(id);
+ }
+ };
+ rpcPeers.set(id, {
+ channel: dc,
+ close: shutdown,
+ request(payload) {
+ if (pending.size >= 4 || dc.readyState !== "open")
+ return Promise.reject(new Error("FILE_PEER_UNAVAILABLE"));
+ return new Promise((resolve, reject) => {
+ const key = String(++sequence);
+ const timer = setTimeout(() => {
+ pending.delete(key);
+ reject(new Error("FILE_PEER_TIMEOUT"));
+ }, 15000);
+ pending.set(key, { resolve, reject, timer });
+ try {
+ send(key, false, payload);
+ } catch (error) {
+ pending.delete(key);
+ clearTimeout(timer);
+ reject(error);
+ }
+ });
+ },
+ });
+ }
function close(id: string) {
+ const rpc = rpcPeers.get(id);
+ rpcPeers.delete(id);
+ rpc?.close();
const p = peers.get(id);
peers.delete(id);
p?.dc?.close();
@@ -70,10 +194,14 @@ export function createFilePeerRuntime(bridge: FilePeerRuntimeBridge) {
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[]) {
+ async function offer(id: string, servers: RTCIceServer[], streaming = false) {
const p = create(id, servers);
- p.dc = p.pc.createDataChannel("files-v1", { ordered: true });
+ p.dc = p.pc.createDataChannel(streaming ? "files-v2" : "files-v1", {
+ ordered: true,
+ });
p.dc.binaryType = "arraybuffer";
+ if (streaming)
+ attachRpc(id, p.pc.createDataChannel("reads-v1", { ordered: true }));
try {
return await localSdp(p.pc, await p.pc.createOffer());
} catch (error) {
@@ -84,11 +212,67 @@ export function createFilePeerRuntime(bridge: FilePeerRuntimeBridge) {
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) {
+ if (channel.label === "reads-v1" && !rpcPeers.has(id)) {
+ attachRpc(id, channel);
+ return;
+ }
+ if (!["files-v1", "files-v2"].includes(channel.label) || p.dc) {
channel.close();
return;
}
p.dc = channel;
+ channel.binaryType = "arraybuffer";
+ if (channel.label === "files-v2") {
+ let source:
+ { ticket: string; offset: number; credit: number } | undefined;
+ let pumping = false;
+ const pump = async () => {
+ if (pumping) return;
+ pumping = true;
+ try {
+ while (source && source.credit > 0) {
+ const current = source;
+ current.credit--;
+ const bytes = decode(
+ await bridge.read(id, current.ticket, current.offset),
+ );
+ if (peers.get(id) !== p || channel.readyState !== "open") return;
+ channel.send(bytes.buffer);
+ current.offset += bytes.length;
+ if (!bytes.length) source = undefined;
+ }
+ } catch {
+ close(id);
+ } finally {
+ pumping = false;
+ }
+ };
+ channel.onmessage = ({ data }) => {
+ try {
+ if (typeof data !== "string" || data.length > 256)
+ throw new Error();
+ const r = JSON.parse(data);
+ if (
+ !Number.isSafeInteger(r.credit) ||
+ r.credit < 1 ||
+ r.credit > 64
+ )
+ throw new Error();
+ if (r.ticket !== undefined) {
+ if (source || !/^[a-f0-9-]{36}$/.test(r.ticket) || r.offset !== 0)
+ throw new Error();
+ source = { ticket: r.ticket, offset: 0, credit: r.credit };
+ } else {
+ if (!source || source.credit + r.credit > 64) throw new Error();
+ source.credit += r.credit;
+ }
+ void pump();
+ } catch {
+ close(id);
+ }
+ };
+ return;
+ }
channel.onmessage = async ({ data }) => {
try {
if (
@@ -135,30 +319,36 @@ export function createFilePeerRuntime(bridge: FilePeerRuntimeBridge) {
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();
- });
+ await Promise.all(
+ [p.dc, rpcPeers.get(id)?.channel]
+ .filter((dc): dc is RTCDataChannel => !!dc)
+ .map(
+ (dc) =>
+ new Promise<void>((resolve, reject) => {
+ 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,
@@ -180,6 +370,87 @@ export function createFilePeerRuntime(bridge: FilePeerRuntimeBridge) {
throw new Error("FILE_PEER_UNAVAILABLE");
p.busy = true;
try {
+ if (dc.label === "files-v2") {
+ await new Promise<void>((resolve, reject) => {
+ let received = 0,
+ written = 0,
+ queued = 0,
+ replenished = 0;
+ const blocks = Math.ceil(size / chunkBytes) + 1;
+ let granted = Math.min(64, blocks);
+ let ended = false,
+ settled = false;
+ let writes = Promise.resolve();
+ let timer = setTimeout(
+ () => done(new Error("FILE_PEER_TIMEOUT")),
+ 60000,
+ );
+ function done(error?: Error) {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ dc!.removeEventListener("message", message);
+ dc!.removeEventListener("close", closed);
+ error ? reject(error) : resolve();
+ }
+ function closed() {
+ done(new Error("FILE_PEER_CLOSED"));
+ }
+ function message(event: MessageEvent) {
+ if (
+ ended ||
+ !(event.data instanceof ArrayBuffer) ||
+ ++queued > 64
+ ) {
+ done(new Error("FILE_PEER_BLOCK"));
+ return;
+ }
+ const bytes = new Uint8Array(event.data);
+ if (bytes.length !== Math.min(chunkBytes, size - received)) {
+ done(new Error("FILE_PEER_SIZE"));
+ return;
+ }
+ received += bytes.length;
+ ended = bytes.length === 0;
+ writes = writes
+ .then(async () => {
+ if (settled) return;
+ if (!bytes.length) {
+ done();
+ return;
+ }
+ let binary = "";
+ for (const byte of bytes) binary += String.fromCharCode(byte);
+ await bridge.write(sink, written, btoa(binary));
+ if (settled) return;
+ if (peers.get(id) !== p) throw new Error("FILE_PEER_CLOSED");
+ written += bytes.length;
+ queued--;
+ clearTimeout(timer);
+ timer = setTimeout(
+ () => done(new Error("FILE_PEER_TIMEOUT")),
+ 60000,
+ );
+ // Count EOF in the window; never send late credit after it was sent.
+ if (++replenished === 32 && granted < blocks) {
+ const credit = Math.min(32, blocks - granted);
+ dc!.send(JSON.stringify({ credit }));
+ granted += credit;
+ replenished = 0;
+ }
+ })
+ .catch((error) => done(error));
+ }
+ dc.addEventListener("message", message);
+ dc.addEventListener("close", closed);
+ try {
+ dc.send(JSON.stringify({ ticket, offset: 0, credit: granted }));
+ } catch {
+ closed();
+ }
+ });
+ return;
+ }
let offset = 0;
// Also request a zero-byte EOF block: the source rechecks size/mtime before completion.
while (offset <= size) {
@@ -239,6 +510,50 @@ export function createFilePeerRuntime(bridge: FilePeerRuntimeBridge) {
}
}
return {
+ async invoke(id: string, payload: string) {
+ const rpc = rpcPeers.get(id);
+ if (!rpc) throw new Error("FILE_PEER_UNAVAILABLE");
+ return rpc.request(payload);
+ },
+ async stats(id: string) {
+ const p = peers.get(id);
+ if (!p) throw new Error("FILE_PEER_CLOSED");
+ const report = await p.pc.getStats();
+ const entries = new Map<string, RTCStats & Record<string, any>>();
+ report.forEach((entry) => entries.set(entry.id, entry));
+ let pair: RTCStats | undefined;
+ report.forEach((entry) => {
+ if (entry.type === "transport" && entry.selectedCandidatePairId)
+ pair = entries.get(entry.selectedCandidatePairId);
+ });
+ const selected = pair as
+ | (RTCStats & {
+ localCandidateId?: string;
+ remoteCandidateId?: string;
+ currentRoundTripTime?: number;
+ })
+ | undefined;
+ const local = selected?.localCandidateId
+ ? entries.get(selected.localCandidateId)
+ : undefined;
+ const remote = selected?.remoteCandidateId
+ ? entries.get(selected.remoteCandidateId)
+ : undefined;
+ return JSON.stringify({
+ path: !selected
+ ? "unknown"
+ : local?.candidateType === "relay" ||
+ remote?.candidateType === "relay"
+ ? "relay"
+ : "direct",
+ protocol: local?.protocol ?? "unknown",
+ rttMs:
+ typeof selected?.currentRoundTripTime === "number"
+ ? Math.round(selected.currentRoundTripTime * 1000)
+ : null,
+ streaming: p.dc?.label === "files-v2",
+ });
+ },
offer,
accept,
answer,
diff --git a/packages/device-link/src/filePeerRuntimeSource.ts b/packages/device-link/src/filePeerRuntimeSource.ts
index 3ac0ec7cc9..b6cedf6336 100644
--- a/packages/device-link/src/filePeerRuntimeSource.ts
+++ b/packages/device-link/src/filePeerRuntimeSource.ts
@@ -1,2 +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";
+export const FILE_PEER_RUNTIME_SOURCE = "\"use strict\";var CindyFilePeerRuntime=(()=>{var O=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var $=Object.prototype.hasOwnProperty;var V=(u,f)=>{for(var p in f)O(u,p,{get:f[p],enumerable:!0})},x=(u,f,p,v)=>{if(f&&typeof f==\"object\"||typeof f==\"function\")for(let g of Z(f))!$.call(u,g)&&g!==p&&O(u,g,{get:()=>f[g],enumerable:!(v=K(f,g))||v.enumerable});return u};var G=u=>x(O({},\"__esModule\",{value:!0}),u);var Y={};V(Y,{createFilePeerRuntime:()=>j});function j(u){let f=new Map,p=16384,v=2147483648,g=new Map;function k(e,a){let o=new Map,r=new Map,i=0,n=0,c=(s,t,E)=>{if(E.length>4*1024*1024||a.readyState!==\"open\")throw new Error(\"FILE_PEER_RPC_SIZE\");for(let l=0;l<Math.max(1,E.length);l+=16384)a.send(JSON.stringify({key:s,response:t,data:E.slice(l,l+16384),last:l+16384>=E.length}))},d=()=>{for(let s of o.values())clearTimeout(s.timer),s.reject(new Error(\"FILE_PEER_CLOSED\"));for(let s of r.values())clearTimeout(s.timer);o.clear(),r.clear(),a.close()};a.onclose=d,a.onmessage=({data:s})=>{try{if(typeof s!=\"string\"||s.length>1e5)throw new Error;let t=JSON.parse(s);if(typeof t.key!=\"string\"||!/^\\d{1,12}$/.test(t.key)||typeof t.response!=\"boolean\"||typeof t.last!=\"boolean\"||typeof t.data!=\"string\"||t.data.length>16384)throw new Error;if(t.response&&!o.has(t.key))return;let E=`${t.response}:${t.key}`,l=r.get(E);if(!l){if(r.size>=8)throw new Error;l={data:\"\",timer:setTimeout(()=>w(e),15e3)},r.set(E,l)}if(l.data+=t.data,l.data.length>4*1024*1024)throw new Error;if(!t.last)return;if(clearTimeout(l.timer),r.delete(E),t.response){let m=o.get(t.key);o.delete(t.key),clearTimeout(m.timer),m.resolve(l.data)}else{if(!u.invoke||n>=4)throw new Error;n++,u.invoke(e,l.data).then(m=>{f.has(e)&&c(t.key,!0,m)}).catch(()=>w(e)).finally(()=>{n--})}}catch{w(e)}},g.set(e,{channel:a,close:d,request(s){return o.size>=4||a.readyState!==\"open\"?Promise.reject(new Error(\"FILE_PEER_UNAVAILABLE\")):new Promise((t,E)=>{let l=String(++i),m=setTimeout(()=>{o.delete(l),E(new Error(\"FILE_PEER_TIMEOUT\"))},15e3);o.set(l,{resolve:t,reject:E,timer:m});try{c(l,!1,s)}catch(y){o.delete(l),clearTimeout(m),E(y)}})}})}function w(e){let a=g.get(e);g.delete(e),a?.close();let o=f.get(e);f.delete(e),o?.dc?.close(),o?.pc.close()}function D(e,a){if(f.has(e)||f.size>=4)throw new Error(\"FILE_PEER_BUSY\");let o=new RTCPeerConnection({iceServers:a}),r={pc:o,dc:null,busy:!1};return f.set(e,r),o.onconnectionstatechange=()=>{[\"failed\",\"closed\",\"disconnected\"].includes(o.connectionState)&&w(e)},r}async function A(e,a){if(await e.setLocalDescription(a),e.iceGatheringState!==\"complete\"&&await new Promise(o=>{let r=setTimeout(i,4e3);function i(){clearTimeout(r),e.removeEventListener(\"icegatheringstatechange\",n),o()}function n(){e.iceGatheringState===\"complete\"&&i()}e.addEventListener(\"icegatheringstatechange\",n),n()}),!e.localDescription?.sdp||e.signalingState===\"closed\")throw new Error(\"FILE_PEER_CLOSED\");return e.localDescription.sdp}function M(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 a=atob(e);if(a.length>p)throw new Error(\"FILE_PEER_BLOCK\");return Uint8Array.from(a,o=>o.charCodeAt(0))}async function N(e,a,o=!1){let r=D(e,a);r.dc=r.pc.createDataChannel(o?\"files-v2\":\"files-v1\",{ordered:!0}),r.dc.binaryType=\"arraybuffer\",o&&k(e,r.pc.createDataChannel(\"reads-v1\",{ordered:!0}));try{return await A(r.pc,await r.pc.createOffer())}catch(i){throw w(e),i}}async function U(e,a,o){let r=D(e,a);r.pc.ondatachannel=({channel:i})=>{if(i.label===\"reads-v1\"&&!g.has(e)){k(e,i);return}if(![\"files-v1\",\"files-v2\"].includes(i.label)||r.dc){i.close();return}if(r.dc=i,i.binaryType=\"arraybuffer\",i.label===\"files-v2\"){let n,c=!1,d=async()=>{if(!c){c=!0;try{for(;n&&n.credit>0;){let s=n;s.credit--;let t=M(await u.read(e,s.ticket,s.offset));if(f.get(e)!==r||i.readyState!==\"open\")return;i.send(t.buffer),s.offset+=t.length,t.length||(n=void 0)}}catch{w(e)}finally{c=!1}}};i.onmessage=({data:s})=>{try{if(typeof s!=\"string\"||s.length>256)throw new Error;let t=JSON.parse(s);if(!Number.isSafeInteger(t.credit)||t.credit<1||t.credit>64)throw new Error;if(t.ticket!==void 0){if(n||!/^[a-f0-9-]{36}$/.test(t.ticket)||t.offset!==0)throw new Error;n={ticket:t.ticket,offset:0,credit:t.credit}}else{if(!n||n.credit+t.credit>64)throw new Error;n.credit+=t.credit}d()}catch{w(e)}};return}i.onmessage=async({data:n})=>{try{if(f.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>v||c.credit!==16)throw new Error(\"FILE_PEER_BLOCK\");r.busy=!0;let d=c.offset;for(let s=0;s<16;s++){let t=M(await u.read(e,c.ticket,d));if(f.get(e)!==r||i.readyState!==\"open\")return;if(i.send(t.buffer),d+=t.length,!t.length)break}}catch{w(e)}finally{r.busy=!1}}};try{return await r.pc.setRemoteDescription({type:\"offer\",sdp:o}),await A(r.pc,await r.pc.createAnswer())}catch(i){throw w(e),i}}async function J(e,a){let o=f.get(e);if(!o)throw new Error(\"FILE_PEER_CLOSED\");await o.pc.setRemoteDescription({type:\"answer\",sdp:a}),await Promise.all([o.dc,g.get(e)?.channel].filter(r=>!!r).map(r=>new Promise((i,n)=>{let c=setTimeout(()=>d(new Error(\"FILE_PEER_TIMEOUT\")),8e3);function d(E){clearTimeout(c),r.removeEventListener(\"open\",s),r.removeEventListener(\"close\",t),E?n(E):i()}function s(){d()}function t(){d(new Error(\"FILE_PEER_CLOSED\"))}r.addEventListener(\"open\",s),r.addEventListener(\"close\",t),r.readyState===\"open\"?d():r.readyState===\"closed\"&&t()})))}async function q(e,a,o,r){let i=f.get(e),n=i?.dc;if(!i||!n||n.readyState!==\"open\"||i.busy||!Number.isSafeInteger(o)||o<0||o>v)throw new Error(\"FILE_PEER_UNAVAILABLE\");i.busy=!0;try{if(n.label===\"files-v2\"){await new Promise((d,s)=>{let t=0,E=0,l=0,m=0,y=Math.ceil(o/p)+1,L=Math.min(64,y),C=!1,h=!1,T=Promise.resolve(),b=setTimeout(()=>R(new Error(\"FILE_PEER_TIMEOUT\")),6e4);function R(I){h||(h=!0,clearTimeout(b),n.removeEventListener(\"message\",B),n.removeEventListener(\"close\",F),I?s(I):d())}function F(){R(new Error(\"FILE_PEER_CLOSED\"))}function B(I){if(C||!(I.data instanceof ArrayBuffer)||++l>64){R(new Error(\"FILE_PEER_BLOCK\"));return}let _=new Uint8Array(I.data);if(_.length!==Math.min(p,o-t)){R(new Error(\"FILE_PEER_SIZE\"));return}t+=_.length,C=_.length===0,T=T.then(async()=>{if(h)return;if(!_.length){R();return}let P=\"\";for(let S of _)P+=String.fromCharCode(S);if(await u.write(r,E,btoa(P)),!h){if(f.get(e)!==i)throw new Error(\"FILE_PEER_CLOSED\");if(E+=_.length,l--,clearTimeout(b),b=setTimeout(()=>R(new Error(\"FILE_PEER_TIMEOUT\")),6e4),++m===32&&L<y){let S=Math.min(32,y-L);n.send(JSON.stringify({credit:S})),L+=S,m=0}}}).catch(P=>R(P))}n.addEventListener(\"message\",B),n.addEventListener(\"close\",F);try{n.send(JSON.stringify({ticket:a,offset:0,credit:L}))}catch{F()}});return}let c=0;for(;c<=o;){let d=await new Promise((s,t)=>{let E=[],l=c,m=setTimeout(()=>y(new Error(\"FILE_PEER_TIMEOUT\")),6e4);function y(h){clearTimeout(m),n.removeEventListener(\"message\",C),n.removeEventListener(\"close\",L),h?t(h):s(E)}function L(){y(new Error(\"FILE_PEER_CLOSED\"))}function C(h){if(!(h.data instanceof ArrayBuffer)){y(new Error(\"FILE_PEER_BLOCK\"));return}let T=new Uint8Array(h.data);if(T.length!==Math.min(p,o-l)){y(new Error(\"FILE_PEER_SIZE\"));return}E.push(T),l+=T.length,(!T.length||E.length===16)&&y()}n.addEventListener(\"message\",C),n.addEventListener(\"close\",L);try{n.send(JSON.stringify({ticket:a,offset:c,credit:16}))}catch{L()}});for(let s of d){if(!s.length)return;let t=\"\";for(let E of s)t+=String.fromCharCode(E);if(await u.write(r,c,btoa(t)),f.get(e)!==i)throw new Error(\"FILE_PEER_CLOSED\");c+=s.length}}}catch(c){throw w(e),c}finally{i.busy=!1}}return{async invoke(e,a){let o=g.get(e);if(!o)throw new Error(\"FILE_PEER_UNAVAILABLE\");return o.request(a)},async stats(e){let a=f.get(e);if(!a)throw new Error(\"FILE_PEER_CLOSED\");let o=await a.pc.getStats(),r=new Map;o.forEach(s=>r.set(s.id,s));let i;o.forEach(s=>{s.type===\"transport\"&&s.selectedCandidatePairId&&(i=r.get(s.selectedCandidatePairId))});let n=i,c=n?.localCandidateId?r.get(n.localCandidateId):void 0,d=n?.remoteCandidateId?r.get(n.remoteCandidateId):void 0;return JSON.stringify({path:n?c?.candidateType===\"relay\"||d?.candidateType===\"relay\"?\"relay\":\"direct\":\"unknown\",protocol:c?.protocol??\"unknown\",rttMs:typeof n?.currentRoundTripTime==\"number\"?Math.round(n.currentRoundTripTime*1e3):null,streaming:a.dc?.label===\"files-v2\"})},offer:N,accept:U,answer:J,receive:q,close:w,dispose:()=>{for(let e of f.keys())w(e)}}}return G(Y);})();\n";
diff --git a/packages/device-link/src/index.ts b/packages/device-link/src/index.ts
index 395ba5f5a6..1c41e3cca8 100644
--- a/packages/device-link/src/index.ts
+++ b/packages/device-link/src/index.ts
@@ -28,6 +28,9 @@ export * from "./remoteCursor.js";
export * from "./peerRecoveryScheduler.js";
export * from "./invokePolicy.js";
export * from "./filePeer.js";
+export * from "./peerTransferCooldown.js";
+export * from "./peerInvoke.js";
+export * from "./peerAttachment.js";
export * from "./fileAccess.js";
export * from "./filePeerRuntime.js";
diff --git a/packages/device-link/src/peerAttachment.ts b/packages/device-link/src/peerAttachment.ts
new file mode 100644
index 0000000000..20cdacd616
--- /dev/null
+++ b/packages/device-link/src/peerAttachment.ts
@@ -0,0 +1,80 @@
+import { isValidAttachmentIntegrity } from "./attachmentOssRef.js";
+
+export interface PeerAttachment {
+ ticket: string;
+ size: number;
+ sha256: string;
+ mimeType?: string;
+ originalName?: string;
+}
+const prefix = "cindy-peer-attach://";
+export const isPeerAttachmentRef = (value: unknown): value is string =>
+ typeof value === "string" && value.startsWith(prefix);
+export function parsePeerAttachmentRef(value: string): PeerAttachment | null {
+ if (!isPeerAttachmentRef(value) || value.length > 16384) return null;
+ try {
+ const r = JSON.parse(
+ decodeURIComponent(value.slice(prefix.length)),
+ ) as PeerAttachment;
+ if (
+ !r ||
+ !/^[a-f0-9-]{36}$/.test(r.ticket) ||
+ !isValidAttachmentIntegrity(r) ||
+ r.size > 2 * 1024 ** 3 ||
+ (r.mimeType !== undefined &&
+ (typeof r.mimeType !== "string" ||
+ !/^[\w.+-]+\/[\w.+-]+$/.test(r.mimeType))) ||
+ (r.originalName !== undefined &&
+ (typeof r.originalName !== "string" || r.originalName.length > 1024))
+ )
+ return null;
+ return {
+ ticket: r.ticket,
+ size: r.size,
+ sha256: r.sha256,
+ mimeType: r.mimeType,
+ originalName: r.originalName,
+ };
+ } catch {
+ return null;
+ }
+}
+export function buildPeerAttachmentRef(value: PeerAttachment): string {
+ const result = prefix + encodeURIComponent(JSON.stringify(value));
+ if (!parsePeerAttachmentRef(result))
+ throw new Error("INVALID_PEER_ATTACHMENT");
+ return result;
+}
+
+/** A failed upload is abandoned before sending the message; callers then upload through OSS. */
+export async function uploadPeerAttachment(
+ metadata: Omit<PeerAttachment, "ticket">,
+ read: (offset: number, length: number) => Promise<string>,
+ invoke: (request: Record<string, unknown>) => Promise<unknown>,
+ check: () => void,
+): Promise<string> {
+ check();
+ const { ticket } = (await invoke({ op: "begin", ...metadata })) as {
+ ticket: string;
+ };
+ if (typeof ticket !== "string" || !/^[a-f0-9-]{36}$/.test(ticket))
+ throw new Error("INVALID_PEER_ATTACHMENT");
+ try {
+ for (let offset = 0; offset < metadata.size; offset += 1024 * 1024) {
+ check();
+ const data = await read(
+ offset,
+ Math.min(1024 * 1024, metadata.size - offset),
+ );
+ check();
+ await invoke({ op: "write", ticket, offset, data });
+ }
+ check();
+ await invoke({ op: "finish", ticket });
+ check();
+ return buildPeerAttachmentRef({ ...metadata, ticket });
+ } catch (error) {
+ void invoke({ op: "cancel", ticket }).catch(() => {});
+ throw error;
+ }
+}
diff --git a/packages/device-link/src/peerInvoke.ts b/packages/device-link/src/peerInvoke.ts
new file mode 100644
index 0000000000..f5a1432e28
--- /dev/null
+++ b/packages/device-link/src/peerInvoke.ts
@@ -0,0 +1,22 @@
+import { REMOTE_DESKTOP_CHANNEL } from "./remoteDesktop.js";
+import { FILE_PEER_CHANNEL } from "./filePeer.js";
+
+/** Only replayable reads and idempotent staging writes may fall back after transport loss. */
+export function canUsePeerInvoke(channel: string, args: unknown[]): boolean {
+ if (args.length !== 1 || !args[0] || typeof args[0] !== "object")
+ return false;
+ const r = args[0] as Record<string, unknown>;
+ if (channel === "file-browser:remote-op")
+ return r.op === "listDir" || r.op === "readFile";
+ return (
+ channel === REMOTE_DESKTOP_CHANNEL &&
+ r.op === "clipboardContent" &&
+ (r.action === "read" || r.action === "write")
+ );
+}
+
+/** Attachment failures restart through OSS, never replay uncertain staging operations over WSS. */
+export function canServePeerInvoke(channel: string, args: unknown[]): boolean {
+ return canUsePeerInvoke(channel, args) || (channel === FILE_PEER_CHANNEL && args.length === 1 &&
+ !!args[0] && typeof args[0] === 'object' && (args[0] as { action?: unknown }).action === 'attachment');
+}
diff --git a/packages/device-link/src/peerTransferCooldown.ts b/packages/device-link/src/peerTransferCooldown.ts
new file mode 100644
index 0000000000..9c4e637373
--- /dev/null
+++ b/packages/device-link/src/peerTransferCooldown.ts
@@ -0,0 +1,23 @@
+/** Per owner/device circuit breaker. No timers, polling or cross-device failures. */
+export function createPeerTransferCooldown(now = Date.now) {
+ const states = new Map<string, { failures: number; until: number }>();
+ return {
+ remaining(key: string) {
+ return Math.max(0, (states.get(key)?.until ?? 0) - now());
+ },
+ fail(key: string) {
+ const failures = Math.min(5, (states.get(key)?.failures ?? 0) + 1);
+ const delay = Math.min(300_000, 30_000 * 2 ** (failures - 1));
+ states.delete(key);
+ if (states.size >= 128) states.delete(states.keys().next().value!);
+ states.set(key, { failures, until: now() + delay });
+ return delay;
+ },
+ success(key: string) {
+ states.delete(key);
+ },
+ clear() {
+ states.clear();
+ },
+ };
+}
diff --git a/scripts/__tests__/terminate-test-process.test.mjs b/scripts/__tests__/terminate-test-process.test.mjs
new file mode 100644
index 0000000000..492b4eebcd
--- /dev/null
+++ b/scripts/__tests__/terminate-test-process.test.mjs
@@ -0,0 +1,30 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { spawn } from 'node:child_process';
+import { once } from 'node:events';
+import { terminateTestProcess } from '../shared/terminate-test-process.mjs';
+
+test('kills a test probe and its detached browser-like descendant', { timeout: 10_000 }, async () => {
+ const probe = spawn(process.execPath, ['-e', `
+ const { spawn } = require('node:child_process');
+ const descendant = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { detached: true, stdio: 'ignore' });
+ console.log(descendant.pid);
+ setInterval(() => {}, 1000);
+ `], { stdio: ['ignore', 'pipe', 'ignore'] });
+ let descendant;
+ try {
+ const [data] = await once(probe.stdout, 'data');
+ descendant = Number(String(data).trim());
+ assert.ok(Number.isSafeInteger(descendant) && descendant > 0);
+ const closed = once(probe, 'close');
+ terminateTestProcess(probe);
+ await closed;
+ const running = () => { try { process.kill(descendant, 0); return true; } catch { return false; } };
+ for (let i = 0; i < 100 && running(); i++) await new Promise(resolve => setTimeout(resolve, 20));
+ assert.equal(running(), false);
+ terminateTestProcess(probe); // Settled children cannot target a reused PID.
+ } finally {
+ if (descendant) { try { process.kill(descendant, 'SIGKILL'); } catch {} }
+ if (probe.exitCode === null && probe.signalCode === null) probe.kill('SIGKILL');
+ }
+});
diff --git a/scripts/file-peer-smoke.mjs b/scripts/file-peer-smoke.mjs
index ba5732f487..67f4f41724 100644
--- a/scripts/file-peer-smoke.mjs
+++ b/scripts/file-peer-smoke.mjs
@@ -1,52 +1,173 @@
// 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');
+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 });
+if (!executablePath) throw new Error("Pass a Chrome executable");
+// Acceptance runner supplies temporary loopback TURN credentials, never production secrets.
+const iceServers = JSON.parse(process.env.CINDY_PEER_TEST_ICE ?? "[]");
+const expectedPath = iceServers.length ? "relay" : "direct";
+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();
+ if (iceServers.length) await page.evaluate(() => {
+ const Native = window.RTCPeerConnection;
+ window.RTCPeerConnection = class extends Native {
+ constructor(config) { super({ ...config, iceTransportPolicy: "relay" }); }
+ };
+ });
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++; }
+ await page.addScriptTag({
+ content: await page.evaluate(
+ () => PeerRuntimeSource.FILE_PEER_RUNTIME_SOURCE,
+ ),
+ });
+ for (const streaming of [false, true]) {
+ const result = await page.evaluate(
+ async ({ large, streaming, benchmark, iceServers, expectedPath }) => {
+ const { createFilePeerRuntime } = CindyFilePeerRuntime;
+ let sourceSize = 0,
+ outputSize = 0,
+ sourceOffset = 0,
+ failWrite = false;
+ const ticket = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+ const host = createFilePeerRuntime({
+ invoke: async (_id, value) => value,
+ read: async (_id, t, offset) => {
+ if (benchmark) await new Promise(resolve => setTimeout(resolve, 1));
+ 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 (benchmark) await new Promise(resolve => setTimeout(resolve, 1));
+ 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 setupStart = performance.now();
+ const offer = await client.offer("client", iceServers, streaming);
+ await client.answer("client", await host.accept("host", iceServers, offer));
+ const setupMs = Math.round(performance.now() - setupStart);
+ const stats = JSON.parse(await client.stats("client"));
+ if (stats.path !== expectedPath) throw new Error("unexpected selected ICE path");
+ if (streaming) {
+ const value = JSON.stringify({ text: "中文🙂".repeat(128 * 1024) });
+ if ((await client.invoke("client", value)) !== value)
+ throw new Error("fragmented RPC differs");
+ const replies = await Promise.all(
+ ["a", "b", "c", "d"].map((value) => client.invoke("client", value)),
+ );
+ if (replies.join("") !== "abcd")
+ throw new Error("RPC correlation failed");
+ const stats = JSON.parse(await client.stats("client"));
+ if (stats.path !== expectedPath || !stats.streaming)
+ throw new Error("selected path missing");
+ }
+ const sizes = [
+ 0,
+ 1,
+ 16384,
+ 16385,
+ 262144,
+ 262145,
+ 1048576,
+ ...(benchmark ? [8 * 1024 * 1024] : []),
+ ...(large
+ ? [large === "2g" ? 2 * 1024 * 1024 * 1024 : 101 * 1024 * 1024]
+ : []),
+ ];
+ try {
+ const transfers = [];
+ for (const size of sizes) {
+ sourceSize = size;
+ sourceOffset = 0;
+ outputSize = 0;
+ const start = performance.now();
+ await Promise.all([
+ client.receive("client", ticket, size, "sink"),
+ ...(streaming
+ ? [client.invoke("client", "concurrent-read")]
+ : []),
+ ]);
+ if (outputSize !== size) throw new Error("bytes differ");
+ const ms = Math.max(1, Math.round(performance.now() - start));
+ transfers.push({ size, ms, bytesPerSecond: Math.round(size * 1000 / ms) });
+ }
+ 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 {
+ streaming,
+ passedSizes: sizes,
+ diskFailureRejected: rejected,
+ rpc: streaming,
+ setupMs,
+ stats,
+ transfers,
+ };
+ } finally {
+ host.dispose();
+ client.dispose();
+ }
},
- });
- 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(); }
+ {
+ large: process.argv.includes("--2g")
+ ? "2g"
+ : process.argv.includes("--large"),
+ streaming,
+ benchmark: process.argv.includes('--benchmark'),
+ iceServers,
+ expectedPath,
+ },
+ );
+ console.log(JSON.stringify(result));
+ }
+} finally {
+ await browser.close();
+}
diff --git a/scripts/peer-transfer-acceptance.mjs b/scripts/peer-transfer-acceptance.mjs
new file mode 100644
index 0000000000..0efaa4c372
--- /dev/null
+++ b/scripts/peer-transfer-acceptance.mjs
@@ -0,0 +1,128 @@
+// One command, no accounts/devices or manual fault injection. Run with Node >=22.12.
+import { spawn, fork } from 'node:child_process';
+import { access, mkdtemp, readFile, writeFile, rm } from 'node:fs/promises';
+import { createWriteStream } from 'node:fs';
+import { createRequire } from 'node:module';
+import os from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { terminateTestProcess } from './shared/terminate-test-process.mjs';
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const require = createRequire(new URL('../apps/desktop/package.json', import.meta.url));
+const reportDir = await mkdtemp(path.join(os.tmpdir(), 'cindy-peer-acceptance-'));
+const scratch = await mkdtemp(path.join(os.tmpdir(), 'cindy-peer-fixtures-'));
+console.log(`Artifacts: ${reportDir}`);
+const report = {
+ startedAt: new Date().toISOString(), stages: [],
+ limitations: ['Local TURN/loopback only; deployed TURN, WAN NAT and network switching are not exercised.',
+ 'Mobile business logic and shared WebRTC runtime are tested; native iOS/Android WebView and physical devices are not exercised.',
+ 'OSS fallback is verified with test adapters, not a production OSS account.'],
+};
+let turn;
+let interrupted = false;
+const children = new Set();
+const abort = () => { for (const child of children) terminateTestProcess(child); };
+process.once('SIGINT', () => { interrupted = true; abort(); process.exitCode = 130; });
+process.once('SIGTERM', () => { interrupted = true; abort(); process.exitCode = 143; });
+async function run(name, command, args, { cwd = root, env = {}, timeout = 300_000 } = {}) {
+ if (interrupted) throw new Error('Acceptance run interrupted');
+ const start = Date.now();
+ console.log(`[peer acceptance] ${name}`);
+ const logfile = path.join(reportDir, `${name}.log`);
+ const stream = createWriteStream(logfile, { mode: 0o600 });
+ const child = spawn(command, args, { cwd, env: { ...process.env, ...env }, stdio: ['ignore', 'pipe', 'pipe'] });
+ children.add(child);
+ child.stdout.pipe(stream, { end: false });
+ child.stderr.pipe(stream, { end: false });
+ let timedOut = false;
+ const timer = setTimeout(() => { timedOut = true; terminateTestProcess(child); }, timeout);
+ const result = await new Promise(resolve => {
+ child.once('error', error => resolve({ error: error.message }));
+ child.once('close', (code, signal) => resolve({ code, signal }));
+ });
+ clearTimeout(timer);
+ children.delete(child);
+ await new Promise(resolve => stream.end(resolve));
+ const stage = { name, ...result, timedOut, ms: Date.now() - start, log: logfile,
+ status: result.code === 0 && !timedOut ? 'passed' : 'failed' };
+ if (name.startsWith('browser-')) {
+ stage.results = (await readFile(logfile, 'utf8')).split('\n').flatMap(line => {
+ try { return [JSON.parse(line)]; } catch { return []; }
+ });
+ }
+ report.stages.push(stage);
+ if (stage.status === 'failed') throw new Error(`${name} failed; see ${logfile}`);
+ return logfile;
+}
+try {
+ const candidates = [process.env.CHROME_PATH,
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
+ '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser',
+ require('playwright-core').chromium.executablePath()].filter(Boolean);
+ let chrome;
+ for (const candidate of candidates) { try { await access(candidate); chrome = candidate; break; } catch {} }
+ if (!chrome) {
+ const cli = path.join(path.dirname(require.resolve('playwright-core/package.json')), 'cli.js');
+ await run('install-chromium', process.execPath, [cli, 'install', 'chromium']);
+ chrome = require('playwright-core').chromium.executablePath();
+ }
+ const pnpm = process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm';
+ await run('process-cleanup', process.execPath, ['--test', 'scripts/__tests__/terminate-test-process.test.mjs']);
+ await run('webview-source', process.execPath, ['scripts/file-peer-runtime.mjs', '--check']);
+ await run('shared-policy', pnpm, ['--filter', '@cindy/device-link', 'test']);
+ await run('desktop-business', pnpm, ['--filter', 'desktop', 'test',
+ 'src/main/__tests__/deviceLinkIpc.test.ts',
+ 'src/main/device-link/__tests__/mirrorCacheIpcBoundary.test.ts',
+ 'src/main/device-link/__tests__/filePeer.test.ts',
+ 'src/main/device-link/__tests__/peerAttachmentStore.test.ts',
+ 'src/main/device-link/__tests__/outboundMedia.test.ts',
+ 'src/main/device-link/__tests__/outboundMediaCompress.test.ts',
+ 'src/main/device-link/__tests__/fileAccess.test.ts',
+ 'src/main/__tests__/normalizeAttachmentsOss.test.ts',
+ 'src/main/remote-desktop/__tests__/clipboardTransfer.test.ts',
+ 'src/main/device-link/__tests__/dispatchSendSafety.test.ts',
+ 'src/main/device-link/__tests__/dispatchWeakNetwork.test.ts']);
+ await run('mobile-business', pnpm, ['--filter', 'mobile', 'exec', 'vitest', 'run',
+ 'src/__tests__/fileWebViewTermination.test.tsx',
+ 'src/__tests__/mobileAttachmentUpload.test.ts', 'src/__tests__/mobileLocalAttachmentUpload.test.ts',
+ 'src/__tests__/attachments.test.ts', 'src/__tests__/durableOutboxFiles.test.ts',
+ 'src/__tests__/peerFileRegistry.test.ts']);
+ for (const [name, args] of [
+ ['shared-types', ['--filter', '@cindy/device-link', 'build']],
+ ['desktop-types', ['--filter', 'desktop', 'typecheck']],
+ ['mobile-types', ['--filter', 'mobile', 'exec', 'tsc', '--noEmit']],
+ ]) await run(name, pnpm, args);
+ await run('browser-direct', process.execPath, ['scripts/file-peer-smoke.mjs', chrome, '--large']);
+ await run('browser-benchmark', process.execPath, ['scripts/file-peer-smoke.mjs', chrome, '--benchmark']);
+ await run('browser-faults', process.execPath, ['scripts/peer-transfer-fault-smoke.mjs', chrome]);
+ // Isolated, pinned development fixture; never added to shipping dependencies.
+ await run('install-turn-fixture', process.platform === 'win32' ? 'npm.cmd' : 'npm',
+ ['install', '--prefix', scratch, '--ignore-scripts', '--no-audit', '--no-fund', '[email protected]']);
+ turn = fork(path.join(root, 'scripts/peer-transfer-turn-fixture.cjs'),
+ [path.join(scratch, 'node_modules/node-turn')], { stdio: ['ignore', 'ignore', 'ignore', 'ipc'] });
+ children.add(turn);
+ const ice = await new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('TURN startup timed out')), 10_000);
+ turn.once('message', value => { clearTimeout(timer); resolve(value); });
+ turn.once('exit', () => { clearTimeout(timer); reject(new Error('TURN exited')); });
+ turn.once('error', error => { clearTimeout(timer); reject(error); });
+ });
+ await run('browser-relay', process.execPath, ['scripts/file-peer-smoke.mjs', chrome, '--large'],
+ { env: { CINDY_PEER_TEST_ICE: JSON.stringify([ice]) } });
+ report.status = 'passed';
+} catch (error) {
+ report.status = 'failed';
+ report.error = error.message;
+ process.exitCode ||= 1;
+} finally {
+ abort();
+ await rm(scratch, { recursive: true, force: true });
+ report.finishedAt = new Date().toISOString();
+ await writeFile(path.join(reportDir, 'report.json'), JSON.stringify(report, null, 2));
+ await writeFile(path.join(reportDir, 'report.md'), [
+ `Peer transfer acceptance: ${report.status}`, '',
+ ...report.stages.map(stage => `- ${stage.name}: ${stage.status} (${stage.ms} ms), ${stage.log}`),
+ '', ...(report.error ? [report.error, ''] : []), 'Coverage limits:', ...report.limitations.map(s => `- ${s}`), '',
+ ].join('\n'));
+ console.log(`Report: ${path.join(reportDir, 'report.md')}`);
+}
diff --git a/scripts/peer-transfer-fault-smoke.mjs b/scripts/peer-transfer-fault-smoke.mjs
new file mode 100644
index 0000000000..a834d7eb49
--- /dev/null
+++ b/scripts/peer-transfer-fault-smoke.mjs
@@ -0,0 +1,145 @@
+// Real WebRTC + production read policy/cooldown/upload helper. HTTP is an OSS test adapter.
+import { createRequire } from 'node:module';
+import { createServer } from 'node:http';
+import { randomBytes, createHash } from 'node:crypto';
+import { fileURLToPath } from 'node:url';
+import path from 'node:path';
+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 bytes = randomBytes(2 * 1024 * 1024 + 7);
+const sha256 = createHash('sha256').update(bytes).digest('hex');
+let httpReads = 0;
+const server = createServer((req, res) => {
+ res.setHeader('Access-Control-Allow-Origin', '*');
+ if (req.url !== '/object') { res.end('peer acceptance'); return; }
+ httpReads++;
+ res.end(bytes);
+});
+await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
+let browser;
+try {
+ const bundle = await build({ stdin: {
+ contents: `export { createFilePeerRuntime } from './packages/device-link/src/filePeerRuntime.ts';
+ export { readDeviceFile } from './packages/device-link/src/fileAccess.ts';
+ export { createPeerTransferCooldown } from './packages/device-link/src/peerTransferCooldown.ts';
+ export { uploadPeerAttachment, parsePeerAttachmentRef } from './packages/device-link/src/peerAttachment.ts';`,
+ resolveDir: root, loader: 'ts',
+ }, bundle: true, write: false, format: 'iife', globalName: 'Production' });
+ browser = await chromium.launch({ executablePath: process.argv[2], headless: true });
+ const page = await browser.newPage();
+ await page.goto(`http://127.0.0.1:${server.address().port}`);
+ await page.exposeFunction('source', offset => bytes.subarray(offset, offset + 16384).toString('base64'));
+ await page.addScriptTag({ content: bundle.outputFiles[0].text });
+ const result = await page.evaluate(async ({ size, sha256 }) => {
+ const { createFilePeerRuntime, readDeviceFile, createPeerTransferCooldown,
+ uploadPeerAttachment, parsePeerAttachmentRef } = Production;
+ const assert = (ok, message) => { if (!ok) throw new Error(message); };
+ const decode = text => Uint8Array.from(atob(text), c => c.charCodeAt(0));
+ const hash = async value => Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', value)))
+ .map(n => n.toString(16).padStart(2, '0')).join('');
+ let clock = 0, attempts = 0, fallbacks = 0;
+ const cd = createPeerTransferCooldown(() => clock);
+ const ticket = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
+ const pairs = [];
+ async function connect({ breakAt = Infinity, slow = false } = {}) {
+ const output = new Uint8Array(size);
+ let written = 0;
+ const host = createFilePeerRuntime({
+ read: async (_id, _ticket, offset) => {
+ if (offset >= breakAt) { host.close('host'); throw new Error('injected disconnect'); }
+ return source(offset);
+ }, write: async () => { throw new Error('unexpected write'); },
+ invoke: async (_id, payload) => payload,
+ });
+ const client = createFilePeerRuntime({ read: async () => '',
+ write: async (_sink, offset, data) => {
+ if (slow) await new Promise(resolve => setTimeout(resolve, 2));
+ assert(offset === written, 'out-of-order disk writes');
+ const chunk = decode(data); output.set(chunk, offset); written += chunk.length;
+ },
+ });
+ pairs.push({ host, client });
+ const offer = await client.offer('client', [], true);
+ await client.answer('client', await host.accept('host', [], offer));
+ return { host, client, output, written: () => written };
+ }
+ const prepared = { ossKey: '', size, mimeType: 'application/octet-stream', transferRequired: true };
+ async function read(pair, signal) {
+ return readDeviceFile({ prepare: async () => prepared, signal,
+ peer: async () => {
+ if (cd.remaining('device-a')) return null;
+ attempts++;
+ try {
+ await pair.client.receive('client', ticket, size, 'sink');
+ cd.success('device-a');
+ return { ...prepared, ossKey: 'peer', data: pair.output };
+ } catch { cd.fail('device-a'); return null; }
+ },
+ fallback: async () => {
+ fallbacks++;
+ return { ...prepared, ossKey: 'oss-test-adapter', data: new Uint8Array(await (await fetch('/object')).arrayBuffer()) };
+ },
+ });
+ }
+ try {
+ const broken = await connect({ breakAt: 512 * 1024 });
+ const fallback = await read(broken);
+ assert(broken.written() > 0 && broken.written() < size, 'fault must occur mid-file');
+ assert(fallback.ossKey === 'oss-test-adapter' && await hash(fallback.data) === sha256, 'fallback integrity');
+ await read(broken); await read(broken);
+ assert(attempts === 1 && fallbacks === 3, 'cooldown must prevent reconnect attempts');
+ assert(cd.remaining('device-b') === 0, 'cooldown leaked across devices');
+ clock = 30_001; // Advance the production cooldown clock, not the network clock.
+ const recovered = await connect({ slow: true });
+ const complete = await read(recovered);
+ assert(complete.ossKey === 'peer' && await hash(complete.data) === sha256, 'recovery integrity');
+ assert(attempts === 2 && fallbacks === 3 && cd.remaining('device-a') === 0, 'recovery failed');
+ const abort = new AbortController(); abort.abort();
+ let cancelled = false;
+ try { await read(recovered, abort.signal); } catch (e) { cancelled = /CANCELLED/.test(e.message); }
+ assert(cancelled && fallbacks === 3, 'cancel triggered fallback');
+
+ // Actual reverse-direction attachment staging over reads-v1, using the shared uploader.
+ let staged = new Uint8Array(size), offset = 0, finished = false;
+ const receiver = createFilePeerRuntime({ read: async () => '', write: async () => {},
+ invoke: async (_id, payload) => {
+ const request = JSON.parse(payload);
+ if (request.op === 'begin') return JSON.stringify({ ticket });
+ if (request.op === 'write') {
+ assert(request.offset === offset, 'attachment offset');
+ const chunk = decode(request.data); staged.set(chunk, offset); offset += chunk.length;
+ }
+ if (request.op === 'finish') {
+ assert(offset === size && await hash(staged) === sha256, 'attachment integrity'); finished = true;
+ }
+ return '{}';
+ },
+ });
+ const sender = createFilePeerRuntime({ read: async () => '', write: async () => {} });
+ pairs.push({ host: receiver, client: sender });
+ await sender.answer('up', await receiver.accept('down', [], await sender.offer('up', [], true)));
+ const ref = await uploadPeerAttachment({ size, sha256, originalName: '测试.bin' },
+ async (start, length) => {
+ // The upload helper asks for 1 MiB; the source bridge exposes 16 KiB blocks.
+ let text = '';
+ for (let pos = start; pos < Math.min(size, start + length); pos += 16384) text += atob(await source(pos));
+ return btoa(text);
+ }, async request => JSON.parse(await sender.invoke('up', JSON.stringify(request))), () => {});
+ assert(finished && parsePeerAttachmentRef(ref)?.sha256 === sha256, 'attachment finished too soon');
+ recovered.host.dispose();
+ // Closing this pair must not break a second, already connected pair.
+ assert(await sender.invoke('up', JSON.stringify({ op: 'probe' })) === '{}', 'peer isolation');
+ return { midTransferFallback: true, sha256Verified: true, cooldownAttempts: attempts,
+ fallbackCount: fallbacks, recovery: true, slowSink: true, cancellation: true,
+ reverseAttachment: true, peerIsolation: true, cooldownClock: 'virtual' };
+ } finally { for (const { host, client } of pairs) { host.dispose(); client.dispose(); } }
+ }, { size: bytes.length, sha256 });
+ if (httpReads !== 3) throw new Error(`Unexpected fallback HTTP reads: ${httpReads}`);
+ console.log(JSON.stringify({ ...result, httpReads }));
+} finally {
+ await browser?.close();
+ server.closeAllConnections();
+ await new Promise(resolve => server.close(resolve));
+}
diff --git a/scripts/peer-transfer-turn-fixture.cjs b/scripts/peer-transfer-turn-fixture.cjs
new file mode 100644
index 0000000000..22fa809709
--- /dev/null
+++ b/scripts/peer-transfer-turn-fixture.cjs
@@ -0,0 +1,27 @@
+// Test-only subprocess: loopback listeners, random credentials, no user data.
+const { randomBytes } = require('node:crypto');
+const dgram = require('node:dgram');
+const Turn = require(process.argv[2]);
+const probe = dgram.createSocket('udp4');
+probe.bind(0, '127.0.0.1', () => {
+ const port = probe.address().port;
+ probe.close(() => {
+ const username = randomBytes(12).toString('hex');
+ const credential = randomBytes(24).toString('hex');
+ const server = new Turn({
+ listeningIps: ['127.0.0.1'], relayIps: ['127.0.0.1'], listeningPort: port,
+ authMech: 'long-term', credentials: { [username]: credential },
+ realm: 'cindy-acceptance.invalid', debugLevel: 'OFF',
+ });
+ server.start();
+ // This pinned test dependency has no public ready event.
+ for (const socket of server.network.sockets) {
+ socket.once('error', () => process.exit(1));
+ socket.once('listening', () => process.send({
+ urls: `turn:127.0.0.1:${port}?transport=udp`, username, credential,
+ }));
+ }
+ process.on('disconnect', () => process.exit(0));
+ process.on('SIGTERM', () => process.exit(0));
+ });
+});
diff --git a/scripts/shared/terminate-test-process.mjs b/scripts/shared/terminate-test-process.mjs
new file mode 100644
index 0000000000..11dad85fce
--- /dev/null
+++ b/scripts/shared/terminate-test-process.mjs
@@ -0,0 +1,30 @@
+import { execFileSync } from 'node:child_process';
+
+// Test-owned subprocesses only. Chrome starts a separate process group, so killing
+// just the probe's group is insufficient: discover descendants before orphaning them.
+export function terminateTestProcess(child) {
+ if (!child.pid || child.exitCode !== null || child.signalCode !== null) return;
+ if (process.platform === 'win32') {
+ execFileSync('taskkill.exe', ['/PID', String(child.pid), '/T', '/F'], { stdio: 'ignore' });
+ return;
+ }
+ const kill = (pid, signal) => {
+ try { process.kill(pid, signal); } catch (error) { if (error.code !== 'ESRCH') throw error; }
+ };
+ kill(child.pid, 'SIGSTOP');
+ try {
+ const rows = execFileSync('ps', ['-A', '-o', 'pid=,ppid='], { encoding: 'utf8' })
+ .trim().split('\n').map(row => row.trim().split(/\s+/).map(Number));
+ const owned = [child.pid];
+ for (let index = 0; index < owned.length; index++) {
+ for (const [pid, parent] of rows) if (parent === owned[index] && !owned.includes(pid)) owned.push(pid);
+ }
+ for (const pid of owned.reverse()) {
+ // Also includes children spawned into an owned group after the snapshot.
+ kill(-pid, 'SIGKILL');
+ kill(pid, 'SIGKILL');
+ }
+ } finally {
+ kill(child.pid, 'SIGKILL');
+ }
+}