Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(task-copy): 复制传输提速、取消立即生效、恢复进度不闪表单,进度改为“已传输” (#5381)
Dashda76c808aaec
diff --git a/apps/desktop/src/capture-renderer/filePeerHost.ts b/apps/desktop/src/capture-renderer/filePeerHost.tsindex e7828ea8c7..759b03bd1d 100644--- a/apps/desktop/src/capture-renderer/filePeerHost.ts+++ b/apps/desktop/src/capture-renderer/filePeerHost.ts@@ -15,7 +15,7 @@ export function startFilePeerHost(api: FilePeerHostApi) {result = await runtime.stats(c.connection);break;case 'invoke':- result = await runtime.invoke(c.connection, c.payload, c.timeoutMs);+ result = await runtime.invoke(c.connection, c.payload, c.timeoutMs, c.body);break;case 'accept':result = await runtime.accept(c.connection, c.servers, c.sdp);diff --git a/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts b/apps/desktop/src/main/device-link/__tests__/filePeer.test.tsindex 2c47b6f18d..cfc6582cd2 100644--- a/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts@@ -1,5 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { mkdtemp, rm, writeFile, truncate } from 'node:fs/promises';+import { promises as fsPromises } from 'node:fs';import os from 'node:os';import path from 'node:path';const mock = vi.hoisted(() => ({@@ -11,7 +12,8 @@ const mock = vi.hoisted(() => ({ready: vi.fn(async () => {}),replyDelay: 0,sent: [] as string[],- commandReply: vi.fn((_action: string) => 'v=0'),+ commands: [] as Record<string, any>[],+ commandReply: vi.fn((_action: string): string | undefined => 'v=0'),now: undefined as number | undefined,receiving: undefined as undefined | { sink: string; reply: () => void },}));@@ -48,6 +50,7 @@ vi.mock('../../remote-desktop/captureWindow', () => ({send: (_channel: string, id: string, c: { action: string; sink?: string }) => {if (c.action !== 'close') {mock.sent.push(c.action);+ mock.commands.push(c);const reply = () =>mock.handlers.get('file-peer:host:reply')!({}, id, true, mock.commandReply(c.action));if (c.action === 'receive') {@@ -232,6 +235,7 @@ describe('authorized file peer source', () => {mock.receiving = undefined;mock.now = undefined;mock.sent.length = 0;+ mock.commands.length = 0;mock.iceConfig.mockReset().mockResolvedValue([]);mock.ready.mockReset().mockResolvedValue();mock.replyDelay = 0;@@ -329,6 +333,7 @@ describe('authorized file peer source', () => {streaming: true,attachments: true,largeAttachments: true,+ streamAttachments: true,});const first = await connect();expect((await open(first.connection)).size).toBe(limit);@@ -337,6 +342,319 @@ describe('authorized file peer source', () => {const second = await connect();await expect(open(second.connection)).rejects.toThrow('SIZE');});+ it('hands a streamed block body to the attachment write as raw bytes, never to other requests', async () => {+ const invoke = vi.fn(async (_channel: string, args: unknown[]) => ({ ok: true, args }));+ const { connection } = (await requestFilePeer(+ 'device-a',+ { action: 'offer', sdp: 'v=0' },+ invoke as never,+ )) as { connection: string };+ const handle = mock.handlers.get('file-peer:host:invoke')!;+ const payload = (request: Record<string, unknown>) =>+ JSON.stringify({+ channel: 'device-link:file-peer',+ args: [{ action: 'attachment', connection, request }],+ });+ const body = new Uint8Array(Buffer.from('hi'));+ await handle({}, connection, payload({ op: 'write', ticket: 't', offset: 0 }), body);+ const data = (invoke.mock.calls[0][1][0] as { request: { data: unknown } }).request.data;+ expect(Buffer.isBuffer(data) && data.toString()).toBe('hi');+ for (const [text, bytes] of [+ [payload({ op: 'finish', ticket: 't' }), body],+ [payload({ op: 'write', ticket: 't', offset: 0, data: 'aGk=' }), body],+ [payload({ op: 'write', ticket: 't', offset: 0 }), new Uint8Array(1024 * 1024 + 1)],+ [payload({ op: 'write', ticket: 't', offset: 0 }), 'aGk='],+ [JSON.stringify({ channel: 'file-browser:remote-op', args: [{ op: 'readFile' }] }), body],+ ] as const)+ await expect(handle({}, connection, text, bytes)).rejects.toThrow('DENIED');+ expect(invoke).toHaveBeenCalledTimes(1);+ });+ it.each([+ ['stream-peer', true],+ ['old-attachment-peer', false],+ ])('uploads blocks to %s with the advertised write format', async (peer, stream) => {+ const source = path.join(directory, 'upload');+ await writeFile(source, Buffer.alloc(2.5 * 1024 * 1024, 7));+ const ticket = 'cccccccc-cccc-cccc-cccc-cccccccccccc';+ const invoke = vi.fn(async (_peer: string, _channel: string, args: unknown[]) => ({+ ok: true,+ result:+ (args[0] as { action: string }).action === 'caps'+ ? { version: 1, streaming: true, attachments: true, streamAttachments: stream }+ : { connection: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', sdp: 'v=0' },+ }));+ // Replies are synchronous, so the command being answered is the last one recorded.+ mock.commandReply.mockImplementation((action) =>+ action === 'invoke'+ ? JSON.stringify({+ ok: true,+ result:+ JSON.parse(mock.commands.at(-1)!.payload).args[0].request.op === 'begin'+ ? { ticket }+ : {},+ })+ : 'v=0',+ );+ const ref = await tryUploadPeerAttachment(peer, source, 'application/octet-stream', invoke);+ expect(ref).toContain(ticket);+ const writes = mock.commands+ .filter((c) => c.action === 'invoke')+ .map((c) => ({+ body: c.body as string | undefined,+ timeoutMs: c.timeoutMs as number | undefined,+ request: JSON.parse(c.payload).args[0].request,+ }))+ .filter((c) => c.request.op === 'write');+ expect(writes.map((c) => c.request.offset)).toEqual([0, 1024 * 1024, 2 * 1024 * 1024]);+ for (const c of writes) {+ // Old receivers only understand the base64 field; streaming ones get the raw-byte body.+ expect(c.body !== undefined).toBe(stream);+ expect(c.request.data !== undefined).toBe(!stream);+ expect(c.timeoutMs).toBe(stream ? 45_000 : undefined);+ }+ expect(Buffer.from(writes[2].body ?? writes[2].request.data, 'base64')).toEqual(+ Buffer.alloc(0.5 * 1024 * 1024, 7),+ );+ });+ it('stops a cancelled upload mid-file, discards the staging and keeps the peer usable', async () => {+ const peer = 'cancel-upload-peer';+ const source = path.join(directory, 'upload');+ await writeFile(source, Buffer.alloc(5 * 1024 * 1024, 3));+ const ticket = 'dddddddd-dddd-dddd-dddd-dddddddddddd';+ const invoke = vi.fn(async (_peer: string, _channel: string, args: unknown[]) => ({+ ok: true,+ result:+ (args[0] as { action: string }).action === 'caps'+ ? { version: 1, streaming: true, attachments: true, streamAttachments: true }+ : { connection: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', sdp: 'v=0' },+ }));+ const abort = new AbortController();+ const ops = () =>+ mock.commands+ .filter((c) => c.action === 'invoke')+ .map((c) => JSON.parse(c.payload).args[0].request.op as string);+ mock.commandReply.mockImplementation((action) => {+ if (action !== 'invoke') return 'v=0';+ const op = JSON.parse(mock.commands.at(-1)!.payload).args[0].request.op;+ // The user cancels while the second block is on the wire.+ if (op === 'write' && ops().filter((o) => o === 'write').length === 2) abort.abort();+ return JSON.stringify({ ok: true, result: op === 'begin' ? { ticket } : {} });+ });+ await expect(+ tryUploadPeerAttachment(peer, source, undefined, invoke, undefined, abort.signal),+ ).rejects.toThrow('FILE_PEER_CANCELLED');+ // No further blocks after the cancel; the receiver is then told to drop what it staged+ // (the abandoned upload sends that after the caller has already returned).+ await vi.waitFor(() => expect(ops().at(-1)).toBe('cancel'));+ expect(ops().filter((o) => o === 'write').length).toBeLessThanOrEqual(4);+ // A cancel is not a transport failure: the next upload still goes direct.+ mock.commands.length = 0;+ expect(await tryUploadPeerAttachment(peer, source, undefined, invoke)).toContain(ticket);+ expect(ops().at(-1)).toBe('finish');+ });+ it('returns at once when cancelled while a block reply is still pending', async () => {+ const peer = 'pending-reply-cancel-peer';+ const source = path.join(directory, 'upload');+ await writeFile(source, Buffer.alloc(3 * 1024 * 1024, 5));+ const ticket = 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee';+ const invoke = vi.fn(async (_peer: string, _channel: string, args: unknown[]) => ({+ ok: true,+ result:+ (args[0] as { action: string }).action === 'caps'+ ? { version: 1, streaming: true, attachments: true, streamAttachments: true }+ : { connection: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', sdp: 'v=0' },+ }));+ const abort = new AbortController();+ const ops = () =>+ mock.commands+ .filter((c) => c.action === 'invoke')+ .map((c) => JSON.parse(c.payload).args[0].request.op as string);+ mock.commandReply.mockImplementation((action) => {+ if (action !== 'invoke') return 'v=0';+ const op = JSON.parse(mock.commands.at(-1)!.payload).args[0].request.op;+ // From the first block on, replies stall like a slow link; then the user cancels.+ if (op === 'write' && !mock.replyDelay) {+ mock.replyDelay = 4_000;+ setTimeout(() => abort.abort(), 10);+ }+ return JSON.stringify({ ok: true, result: op === 'begin' ? { ticket } : {} });+ });+ const startedAt = Date.now();+ await expect(+ tryUploadPeerAttachment(peer, source, undefined, invoke, undefined, abort.signal),+ ).rejects.toThrow('FILE_PEER_CANCELLED');+ expect(Date.now() - startedAt).toBeLessThan(2_000);+ // The connection stays up, so the target is still told to drop the partial staging.+ await vi.waitFor(() => expect(ops().at(-1)).toBe('cancel'));+ });+ it('returns at once when cancelled during the capability probe, with the source already closed', async () => {+ const source = path.join(directory, 'upload');+ await writeFile(source, 'hello');+ const opened = vi.spyOn(fsPromises, 'open');+ let answer!: (value: unknown) => void;+ const invoke = vi.fn(+ () =>+ new Promise((resolve) => {+ answer = resolve;+ }),+ );+ const abort = new AbortController();+ const upload = tryUploadPeerAttachment(+ 'silent-peer',+ source,+ undefined,+ invoke as never,+ undefined,+ abort.signal,+ );+ await vi.waitFor(() => expect(invoke).toHaveBeenCalled());+ const handle = await (opened.mock.results[0].value as ReturnType<typeof fsPromises.open>);+ // A slow close (like a busy disk) makes a caller that settles early observable.+ const close = handle.close.bind(handle);+ let closed = false;+ handle.close = async () => {+ await new Promise((resolve) => setTimeout(resolve, 30));+ await close();+ closed = true;+ };+ abort.abort();+ // The caller may delete the file straight away (Windows), so the close must have finished+ // when the call settles — not still be running in the background.+ const settled = await upload.then(+ () => ({ error: '', closed }),+ (error: Error) => ({ error: error.message, closed }),+ );+ opened.mockRestore();+ expect(settled).toEqual({ error: 'FILE_PEER_CANCELLED', closed: true });+ // The late probe result is ignored: nothing is hashed or sent afterwards.+ answer({ ok: true, result: { version: 1, streaming: true, attachments: true } });+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(invoke).toHaveBeenCalledTimes(1);+ expect(mock.commands.filter((c) => c.action === 'invoke')).toEqual([]);+ });+ it('drops the ticket of a begin answered only after the upload was cancelled', async () => {+ const peer = 'late-begin-peer';+ const source = path.join(directory, 'upload');+ await writeFile(source, 'hello');+ const ticket = 'ffffffff-ffff-ffff-ffff-ffffffffffff';+ const invoke = vi.fn(async (_peer: string, _channel: string, args: unknown[]) => ({+ ok: true,+ result:+ (args[0] as { action: string }).action === 'caps'+ ? { version: 1, streaming: true, attachments: true, streamAttachments: true }+ : { connection: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', sdp: 'v=0' },+ }));+ const abort = new AbortController();+ const requests = () =>+ mock.commands+ .filter((c) => c.action === 'invoke')+ .map((c) => JSON.parse(c.payload).args[0].request as { op: string; ticket?: string });+ mock.commandReply.mockImplementation((action) => {+ // Once connected, the target answers slowly.+ if (action === 'answer') mock.replyDelay = 50;+ if (action !== 'invoke') return 'v=0';+ const op = JSON.parse(mock.commands.at(-1)!.payload).args[0].request.op;+ return JSON.stringify({ ok: true, result: op === 'begin' ? { ticket } : {} });+ });+ const upload = tryUploadPeerAttachment(peer, source, undefined, invoke, undefined, abort.signal);+ // The target has created the ticket, but before its answer arrives the user cancels.+ await vi.waitFor(() => expect(requests().map((r) => r.op)).toContain('begin'));+ abort.abort();+ await expect(upload).rejects.toThrow('FILE_PEER_CANCELLED');+ // The cancel returned at once; the late ticket is still released on the target.+ await vi.waitFor(() => expect(requests().at(-1)).toEqual({ op: 'cancel', ticket }));+ expect(requests().filter((r) => r.op === 'write')).toEqual([]);+ });+ it('cancelling an upload during connection setup leaves another peer and its transfer untouched', async () => {+ const source = path.join(directory, 'upload');+ await writeFile(source, 'hello');+ // Peer B: an established connection with a download in flight.+ const invokeB = 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 download = tryPeerFile('fault-radius-peer-b', 'xdt-file://test', invokeB);+ await vi.waitFor(() => expect(mock.receiving).toBeDefined());+ const inFlightB = mock.receiving!;+ // Peer A: the upload is cancelled while its connection is still being set up (no answer).+ const invokeA = vi.fn(async (_peer: string, _channel: string, args: unknown[]) =>+ (args[0] as { action: string }).action === 'caps'+ ? {+ ok: true,+ result: { version: 1, streaming: true, attachments: true, streamAttachments: true },+ }+ : new Promise<never>(() => {}),+ );+ const abort = new AbortController();+ const upload = tryUploadPeerAttachment(+ 'fault-radius-peer-a',+ source,+ undefined,+ invokeA as never,+ undefined,+ abort.signal,+ );+ await vi.waitFor(() =>+ expect(invokeA.mock.calls.map((call) => (call[2][0] as { action: string }).action)).toContain(+ 'offer',+ ),+ );+ abort.abort();+ await expect(upload).rejects.toThrow('FILE_PEER_CANCELLED');+ // B never notices: its in-flight transfer completes on the same connection.+ await mock.handlers.get('file-peer:host:write')!({}, inFlightB.sink, 0, 'aGVsbG8=');+ inFlightB.reply();+ const result = await download;+ expect(result?.size).toBe(5);+ await result?.dispose();+ expect(invokeB.mock.calls.map((call) => (call[2][0] as { action: string }).action)).not.toContain(+ 'close',+ );+ });+ it('drops a cancelled upload still queued behind another transfer on the same peer', async () => {+ const peer = 'queued-cancel-peer';+ const source = path.join(directory, 'upload');+ await writeFile(source, 'hello');+ 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, attachments: true, streamAttachments: true }+ : action === 'open'+ ? { ticket: 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', size: 5, mimeType: 'text/plain' }+ : { connection: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', sdp: 'v=0' },+ };+ });+ // A preview download holds the peer's transfer queue until its bytes arrive.+ const download = tryPeerFile(peer, 'xdt-file://test', invoke);+ await vi.waitFor(() => expect(mock.receiving).toBeDefined());+ const abort = new AbortController();+ const upload = tryUploadPeerAttachment(+ peer,+ source,+ undefined,+ invoke,+ undefined,+ abort.signal,+ );+ abort.abort();+ await expect(upload).rejects.toThrow('FILE_PEER_CANCELLED');+ await mock.handlers.get('file-peer:host:write')!({}, mock.receiving!.sink, 0, 'aGVsbG8=');+ mock.receiving!.reply();+ const result = await download;+ expect(result?.size).toBe(5);+ await result?.dispose();+ });it('rejects another peer using a connection handle', async () => {const { connection } = await connect();await expect(open(connection, 'device-b')).rejects.toThrow('DENIED');diff --git a/apps/desktop/src/main/device-link/__tests__/mediaTransfer.test.ts b/apps/desktop/src/main/device-link/__tests__/mediaTransfer.test.tsindex 1792dba854..e5ee08c292 100644--- a/apps/desktop/src/main/device-link/__tests__/mediaTransfer.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/mediaTransfer.test.ts@@ -14,7 +14,7 @@*/import { describe, it, expect, vi, beforeEach } from 'vitest';import { createHash } from 'node:crypto';-import { PassThrough, Readable } from 'node:stream';+import { PassThrough, Readable, addAbortSignal } from 'node:stream';/** Electron net.fetch(Chromium 网络栈):OSS GET / range,以及 PUT 的回退跳。 */const netFetchMock = vi.hoisted(() => vi.fn());@@ -167,6 +167,65 @@ describe('uploadLocalFile — 小文件整体 PUT', () => {expect(netFetchMock).not.toHaveBeenCalled();});+ it('取消上传 → 立刻中止 PUT,不换传输栈重试,并删除已签发的对象', async () => {+ const abort = new AbortController();+ undiciFetchMock.mockImplementation(+ (_url: string, init: RequestInit) =>+ new Promise((_, reject) => {+ init.signal?.addEventListener('abort', () =>+ reject(new DOMException('aborted', 'AbortError')),+ );+ abort.abort();+ }),+ );+ await expect(uploadLocalFile('/tmp/a.png', { signal: abort.signal })).rejects.toThrow(+ 'UPLOAD_CANCELLED',+ );+ expect(undiciFetchMock).toHaveBeenCalledTimes(1);+ expect(netFetchMock).not.toHaveBeenCalled();+ expect(apiFetch.mock.calls.map(([path]) => path)).toEqual([PUT_PATH, DEL_PATH]);+ // Already cancelled: nothing is presigned or sent.+ apiFetch.mockClear();+ undiciFetchMock.mockClear();+ await expect(uploadLocalFile('/tmp/a.png', { signal: abort.signal })).rejects.toThrow();+ expect(apiFetch).not.toHaveBeenCalled();+ expect(undiciFetchMock).not.toHaveBeenCalled();+ });++ it('预签名无响应时取消 → 立即中止,不发 PUT;清理删除有期限且取消不等它', async () => {+ const abort = new AbortController();+ apiFetch.mockImplementation((path: string) =>+ path === PUT_PATH ? new Promise(() => {}) : Promise.resolve({ deleted: true }),+ );+ const upload = uploadLocalFile('/tmp/a.png', { signal: abort.signal });+ await vi.waitFor(() => expect(apiFetch).toHaveBeenCalled());+ abort.abort();+ await expect(upload).rejects.toThrow('UPLOAD_CANCELLED');+ expect(undiciFetchMock).not.toHaveBeenCalled();+ // A cancelled PUT does not wait for the (possibly hanging) delete; the delete itself is bounded.+ apiFetch.mockClear();+ apiFetch.mockImplementation((path: string) =>+ path === PUT_PATH+ ? Promise.resolve({ putUrl: 'https://oss.example/put', key: KEY, expiresAt: 'x' })+ : new Promise(() => {}),+ );+ const second = new AbortController();+ undiciFetchMock.mockImplementation(+ (_url: string, init: RequestInit) =>+ new Promise((_, reject) => {+ init.signal?.addEventListener('abort', () =>+ reject(new DOMException('aborted', 'AbortError')),+ );+ second.abort();+ }),+ );+ await expect(uploadLocalFile('/tmp/a.png', { signal: second.signal })).rejects.toThrow(+ 'UPLOAD_CANCELLED',+ );+ const deleteCall = apiFetch.mock.calls.find(([path]) => path === DEL_PATH);+ expect(deleteCall?.[1]).toMatchObject({ method: 'DELETE', timeoutMs: 15_000 });+ });+it('路径不是文件 → 抛错', async () => {statMock.mockResolvedValue({ isFile: () => false, size: 0 });await expect(uploadLocalFile('/tmp/dir')).rejects.toThrow();@@ -237,6 +296,106 @@ describe('uploadLocalFile — bounded snapshots', () => {});});+describe('uploadLocalFile — 流式上传取消', () => {+ it('取消时等源文件流真正关闭后才返回(Windows 删除暂存目录前文件必须已关闭)', async () => {+ const size = __testing.STREAM_THRESHOLD + 1;+ statMock.mockResolvedValue({ isFile: () => true, size });+ // Slow close, like a busy disk: a caller that settles early would observe `closed === false`.+ const source = new Readable({+ read() {+ this.push(Buffer.alloc(1024, 1));+ },+ destroy(error, callback) {+ setTimeout(() => callback(error), 30);+ },+ });+ createReadStreamMock.mockImplementation(() => source);+ const abort = new AbortController();+ undiciFetchMock.mockImplementation(+ (_url: string, init: RequestInit) =>+ new Promise((_, reject) => {+ init.signal?.addEventListener('abort', () =>+ reject(new DOMException('aborted', 'AbortError')),+ );+ abort.abort();+ }),+ );+ const settled = await uploadLocalFile('/tmp/big.mp4', { signal: abort.signal }).then(+ () => ({ error: '', closed: source.closed }),+ (error: Error) => ({ error: error.message, closed: source.closed }),+ );+ expect(settled).toEqual({ error: 'UPLOAD_CANCELLED', closed: true });+ });+});++describe('uploadLocalFile — 小文件预读取消', () => {+ it('预读卡在慢盘时取消 → 立即停止读取,等读流关闭后返回,不发 PUT', async () => {+ statMock.mockResolvedValue({ isFile: () => true, size: 100 });+ let source!: Readable;+ // A read that never completes, honouring the signal the way fs streams do.+ createReadStreamMock.mockImplementation((_path: string, options: { signal?: AbortSignal }) => {+ source = new Readable({+ read() {},+ destroy(error, callback) {+ setTimeout(() => callback(error), 30);+ },+ });+ return options.signal ? addAbortSignal(options.signal, source) : source;+ });+ const abort = new AbortController();+ const upload = uploadLocalFile('/tmp/a.png', { maxBytes: 100, signal: abort.signal });+ await vi.waitFor(() => expect(createReadStreamMock).toHaveBeenCalled());+ abort.abort();+ const settled = await upload.then(+ () => ({ failed: false, closed: source.closed }),+ () => ({ failed: true, closed: source.closed }),+ );+ expect(settled).toEqual({ failed: true, closed: true });+ expect(undiciFetchMock).not.toHaveBeenCalled();+ });+});++describe('uploadLocalFile — 换栈重试后取消', () => {+ it('等所有尝试打开过的源文件流都关闭后才返回', async () => {+ const size = __testing.STREAM_THRESHOLD + 1;+ statMock.mockResolvedValue({ isFile: () => true, size });+ // The first attempt's stream closes more slowly than the retry's.+ const slowSource = (closeMs: number) =>+ new Readable({+ read() {+ this.push(Buffer.alloc(1024, 1));+ },+ destroy(error, callback) {+ setTimeout(() => callback(error), closeMs);+ },+ });+ const sources = [slowSource(60), slowSource(10)];+ const opened: Readable[] = [];+ createReadStreamMock.mockImplementation(() => {+ const source = sources.shift()!;+ opened.push(source);+ return source;+ });+ // undici fails at the network layer → retry via Electron net, which the user cancels.+ undiciFetchMock.mockRejectedValue(new TypeError('fetch failed'));+ const abort = new AbortController();+ netFetchMock.mockImplementation(+ (_url: string, init: RequestInit) =>+ new Promise((_, reject) => {+ init.signal?.addEventListener('abort', () =>+ reject(new DOMException('aborted', 'AbortError')),+ );+ abort.abort();+ }),+ );+ const settled = await uploadLocalFile('/tmp/big.mp4', { signal: abort.signal }).then(+ () => ({ error: '', closed: opened.map((source) => source.closed) }),+ (error: Error) => ({ error: error.message, closed: opened.map((source) => source.closed) }),+ );+ expect(settled).toEqual({ error: 'UPLOAD_CANCELLED', closed: [true, true] });+ });+});+describe('uploadLocalFile — 大文件流式 PUT', () => {it('超阈值 → body 为 ReadableStream + duplex half,不读进内存', async () => {const size = __testing.STREAM_THRESHOLD + 1;diff --git a/apps/desktop/src/main/device-link/__tests__/peerAttachmentStore.test.ts b/apps/desktop/src/main/device-link/__tests__/peerAttachmentStore.test.tsindex edb84d6bc7..6731dce3fb 100644--- a/apps/desktop/src/main/device-link/__tests__/peerAttachmentStore.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/peerAttachmentStore.test.ts@@ -126,3 +126,40 @@ it('admits attachments of any size when the disk has room, reserving unwritten i'FILE_PEER_STORAGE',);});+it('accepts raw-byte blocks and lands writes dispatched back to back in order', async () => {+ const content = Buffer.from('hello world');+ const meta = { size: content.length, sha256: createHash('sha256').update(content).digest('hex') };+ const { ticket } = (await handlePeerAttachment('a', { op: 'begin', ...meta })) as {+ ticket: string;+ };+ // Streaming senders keep several writes in flight; the per-ticket queue applies them in order.+ await Promise.all([+ handlePeerAttachment('a', { op: 'write', ticket, offset: 0, data: content.subarray(0, 4) }),+ handlePeerAttachment('a', { op: 'write', ticket, offset: 4, data: content.subarray(4, 8) }),+ handlePeerAttachment('a', {+ op: 'write',+ ticket,+ offset: 8,+ data: content.subarray(8).toString('base64'),+ }),+ ]);+ await handlePeerAttachment('a', { op: 'finish', ticket });+ expect(await readFile(path.join(state.root, ticket))).toEqual(content);+ const empty = (await handlePeerAttachment('a', { op: 'begin', ...meta })) as { ticket: string };+ await expect(+ handlePeerAttachment('a', {+ op: 'write',+ ticket: empty.ticket,+ offset: 0,+ data: Buffer.alloc(0),+ }),+ ).rejects.toThrow('BLOCK');+ await expect(+ handlePeerAttachment('a', {+ op: 'write',+ ticket: empty.ticket,+ offset: 0,+ data: Buffer.alloc(1024 * 1024 + 1),+ }),+ ).rejects.toThrow('BLOCK');+});diff --git a/apps/desktop/src/main/device-link/filePeer.ts b/apps/desktop/src/main/device-link/filePeer.tsindex 6075a1b092..8522c6971d 100644--- a/apps/desktop/src/main/device-link/filePeer.ts+++ b/apps/desktop/src/main/device-link/filePeer.ts@@ -12,6 +12,7 @@ import {uploadPeerAttachment,FILE_PEER_CHUNK_BYTES,FILE_PEER_MAX_BYTES,+ RPC_BODY_MAX_BYTES,canSendPeerAttachment,FILE_PEER_IDLE_MS,FILE_PEER_CHANNEL,@@ -69,6 +70,8 @@ interface Outgoing {attachments?: boolean;/** 对端接收直连附件不设固定上限(只看磁盘空间);旧端仍按 OSS 上限拒收更大的附件。 */largeAttachments?: boolean;+ /** 对端接受多块在途与二进制写入;旧端仍逐块等确认、按 base64 发送。 */+ streamAttachments?: boolean;}const outgoing = new Map<string, Outgoing>();const cooldown = createPeerTransferCooldown();@@ -391,6 +394,7 @@ async function handleFilePeerRequest(streaming: true,attachments: true,largeAttachments: true,+ streamAttachments: true,};if (r.action === 'offer') {const id = randomUUID();@@ -488,9 +492,15 @@ async function handleFilePeerRequest(}export function registerFilePeerIpc() {- ipcMain.handle(FILE_PEER_LOCAL.INVOKE, async (e, id: unknown, text: unknown) => {+ ipcMain.handle(FILE_PEER_LOCAL.INVOKE, async (e, id: unknown, text: unknown, body: unknown) => {host.assertSender(e);- if (typeof id !== 'string' || typeof text !== 'string' || text.length > 4 * 1024 * 1024)+ if (+ typeof id !== 'string' ||+ typeof text !== 'string' ||+ text.length > 4 * 1024 * 1024 ||+ (body !== undefined &&+ (!(body instanceof Uint8Array) || !body.length || body.length > RPC_BODY_MAX_BYTES))+ )throw new Error('FILE_PEER_DENIED');const c = touch(id);const payload = JSON.parse(text);@@ -502,6 +512,20 @@ export function registerFilePeerIpc() {!canServePeerInvoke(payload.channel, payload.args))throw new Error('FILE_PEER_DENIED');+ if (body !== undefined) {+ // Only an attachment block write carries a body; it replaces the base64 `data` field.+ const request = (payload.args[0] as { action?: unknown; request?: unknown }).request as+ Record<string, unknown> | undefined;+ if (+ payload.channel !== FILE_PEER_CHANNEL ||+ !request ||+ typeof request !== 'object' ||+ request.op !== 'write' ||+ request.data !== undefined+ )+ throw new Error('FILE_PEER_DENIED');+ request.data = Buffer.from(body.buffer, body.byteOffset, body.byteLength);+ }const stopKeepAlive = keepAlive(id);let result: unknown;try {@@ -679,6 +703,8 @@ async function receivePeerFile(out.attachments = (caps.result as { attachments?: unknown }).attachments === true;out.largeAttachments =(caps.result as { largeAttachments?: unknown }).largeAttachments === true;+ out.streamAttachments =+ (caps.result as { streamAttachments?: unknown }).streamAttachments === true;track(id, peer, false);const [, servers] = await Promise.all([prepareHost(id), loadDesktopIceServers()]);const offer = await command({@@ -818,22 +844,45 @@ async function peerAttachmentCaps(};}+/** Settles with `promise`, or rejects FILE_PEER_CANCELLED as soon as `signal` aborts. */+function untilAborted<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {+ if (!signal) return promise;+ return new Promise<T>((resolve, reject) => {+ const abort = () => reject(new Error('FILE_PEER_CANCELLED'));+ if (signal.aborted) abort();+ else signal.addEventListener('abort', abort, { once: true });+ promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', abort));+ });+}+const warming = new Set<string>();-/** Upload only bytes; the eventual message still uses its original WSS acceptance semantics. */+/**+ * Upload only bytes; the eventual message still uses its original WSS acceptance semantics.+ * Aborting `signal` stops hashing or sending within one block, discards the receiver's partial+ * staging and rejects with FILE_PEER_CANCELLED instead of returning null (no OSS fallback, no+ * failure cooldown).+ */export async function tryUploadPeerAttachment(peer: string,source: string | Buffer,mimeType: string | undefined,invoke: Invoke,onProgress?: (bytes: number) => void,+ signal?: AbortSignal,): Promise<string | null> {refreshCooldownOwner();const owner = captureDataOwnerBroadcastScope();const check = () => {if (!isDataOwnerBroadcastScopeCurrent(owner)) throw new Error('FILE_PEER_CANCELLED');};- return queuePeerRead(peer, async () => {+ // Block-level checkpoints also honour the caller's cancellation; the cleanup RPC below+ // (uploadPeerAttachment's `cancel`) only needs the owner check.+ const checkActive = () => {check();+ if (signal?.aborted) throw new Error('FILE_PEER_CANCELLED');+ };+ const upload = async () => {+ checkActive();if (cooldown.remaining(peer)) return null;let handle: FileHandle | undefined;let active: Outgoing | undefined;@@ -843,10 +892,12 @@ export async function tryUploadPeerAttachment(const size = handle ? (await handle.stat()).size : (source as Buffer).length;if (!size) return null;// 读整份文件算摘要之前先确认对端能收:对端离线、旧版或不支持时不白读一遍(随后还要走 OSS)。- if (!canSendPeerAttachment(await peerAttachmentCaps(peer, invoke), size)) return null;- check();+ // The probe is the one wait with no checkpoint of its own; a late answer is ignored.+ const caps = await untilAborted(peerAttachmentCaps(peer, invoke), signal);+ if (!canSendPeerAttachment(caps, size)) return null;+ checkActive();const read = async (offset: number, length: number) => {- check();+ checkActive();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)@@ -858,8 +909,11 @@ export async function tryUploadPeerAttachment(for (let offset = 0; offset < size; offset += 1024 * 1024)hash.update(await read(offset, Math.min(1024 * 1024, size - offset)));const sha256 = hash.digest('hex');- await receivePeerFile(peer, null, invoke);- check();+ // Cancelling during connection setup stops that setup (without a failure cooldown) and does+ // not wait for its signalling RPC; that late answer is ignored. Only this peer's connection+ // being set up is torn down — other peers and their transfers are untouched.+ await untilAborted(receivePeerFile(peer, null, invoke, signal), signal);+ checkActive();const out = outgoing.get(peer);if (!out?.remote || !canSendPeerAttachment(out, size)) return null;active = out;@@ -868,25 +922,39 @@ export async function tryUploadPeerAttachment(const result = await uploadPeerAttachment({ size, sha256, mimeType },async (offset, length) => (await read(offset, length)).toString('base64'),- async (request, timeoutMs) => {+ async (request, timeoutMs, body) => {check();- const response = JSON.parse(- (await command({+ const send = (r: Record<string, unknown>) =>+ command({action: 'invoke',connection: out.id,...(timeoutMs ? { timeoutMs } : {}),+ ...(body === undefined ? {} : { body }),payload: JSON.stringify({channel: FILE_PEER_CHANNEL,- args: [{ action: 'attachment', connection: out.remote, request }],+ args: [{ action: 'attachment', connection: out.remote, request: r }],}),- }))!,- );+ });+ const sent = send(request);+ // A begin answered only after cancellation: the target created a ticket nobody will+ // cancel, so drop it here (cleanup otherwise starts once the ticket is known).+ if (request.op === 'begin')+ void sent+ .then((raw) => {+ const ticket = signal?.aborted ? JSON.parse(raw!)?.result?.ticket : undefined;+ if (typeof ticket === 'string') return send({ op: 'cancel', ticket });+ })+ .catch(() => {});+ // A cancelled upload stops waiting for in-flight blocks at once; their late replies are+ // ignored and the connection stays up, so the `cancel` request still reaches the target.+ const response = JSON.parse((await untilAborted(sent, signal))!);check();if (!response.ok) throw new Error('FILE_PEER_UPLOAD');return response.result;},- check,+ checkActive,onProgress,+ out.streamAttachments === true,);const ms = Date.now() - transferStartedAt;log.debug(@@ -895,6 +963,7 @@ export async function tryUploadPeerAttachment(return result;} catch {check();+ if (signal?.aborted) throw new Error('FILE_PEER_CANCELLED');cooldown.fail(peer);const failed = outgoing.get(peer);if (failed) stopConnection(failed.id, 'upload-failed');@@ -903,7 +972,11 @@ export async function tryUploadPeerAttachment(if (active) active.busy = false;await handle?.close();}- });+ };+ // Cancellation is prompt because every wait inside `upload` honours the signal (queue, probe,+ // hashing, setup, blocks) — never by racing the caller ahead: the call settles only after its+ // `finally` has closed the source file, so the caller may delete it straight away (Windows).+ return queuePeerRead(peer, upload, signal);}/** Cold reads use WSS immediately; a single background setup prepares subsequent reads. */export async function tryPeerInvoke(diff --git a/apps/desktop/src/main/device-link/mediaTransfer.ts b/apps/desktop/src/main/device-link/mediaTransfer.tsindex 5feea39b37..41b724a60d 100644--- a/apps/desktop/src/main/device-link/mediaTransfer.ts+++ b/apps/desktop/src/main/device-link/mediaTransfer.ts@@ -125,6 +125,18 @@ async function presignPut(});}+/** Rejects as soon as `signal` aborts; the abandoned promise's result is ignored. */+function abortable<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {+ if (!signal) return promise;+ return new Promise<T>((resolve, reject) => {+ const abort = () => reject(new Error('UPLOAD_CANCELLED'));+ if (signal.aborted) abort();+ else signal.addEventListener('abort', abort, { once: true });+ promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', abort));+ });+}+const REMOVE_REMOTE_TIMEOUT_MS = 15_000;+/** 向 relay server 申请下载预签名(server 校验请求方 == key 内嵌 userId)。 */async function presignGet(key: string): Promise<PresignGetResponse> {requireAppCapability('canUseDeviceLink', 'Device Link requires a Cindy account.');@@ -277,6 +289,7 @@ async function putBytesToOss(putUrl: string,bodySource: OssPutBodySource,contentType: string,+ signal?: AbortSignal,): Promise<void> {const host = hostOf(putUrl);const headers: Record<string, string> = {@@ -293,7 +306,12 @@ async function putBytesToOss(} catch (err) {throw new NonRetriableOssPutError(err);}- const init: RequestInit & { duplex?: 'half' } = { method: 'PUT', headers, body };+ const init: RequestInit & { duplex?: 'half' } = {+ method: 'PUT',+ headers,+ body,+ ...(signal ? { signal } : {}),+ };// 流式 body 必须带 duplex:'half'(标准 fetch 要求),Buffer body 无需。if (body instanceof ReadableStream) init.duplex = 'half';const resp = await impl(putUrl, init as RequestInit);@@ -320,8 +338,14 @@ async function putBytesToOss(const hints: string[] = [];for (const transport of order) {try {+ signal?.throwIfAborted();await attempt(transport.impl);} catch (err) {+ // A cancelled upload is final: never retry it through the other transport.+ if (signal?.aborted) {+ bodySource.dispose?.();+ throw new Error('UPLOAD_CANCELLED');+ }if (err instanceof NonRetriableOssPutError) {const retriableCacheArtifact =cachedFallbackFirst && transport.name === 'electron-net' && err.httpStatus !== undefined;@@ -391,6 +415,8 @@ export async function uploadLocalFile(maxBytes?: number;/** 可选上传进度(已送入 HTTP 栈的字节数,略超前于真实网络进度)。 */onProgress?: (uploadedBytes: number) => void;+ /** Aborting stops the PUT at once (no transport retry) and deletes the staged object. */+ signal?: AbortSignal;} = {},): Promise<UploadResult> {const st = await stat(localPath);@@ -408,8 +434,12 @@ export async function uploadLocalFile(const ext =opts.extHint !== undefined ? opts.extHint.replace(/^\.+/, '').toLowerCase() : extOf(localPath);const contentType = opts.contentType ?? mimeOf(ext);- const { putUrl, key } = await presignPut(size, ext, contentType);+ opts.signal?.throwIfAborted();+ // A presign creates no object, so a result that arrives after cancellation needs no cleanup.+ const { putUrl, key } = await abortable(presignPut(size, ext, contentType), opts.signal);let sha256: string;+ // One per streaming attempt (a transport retry opens the file again): all must release it.+ const sourcesClosed: Promise<void>[] = [];try {if (size <= STREAM_THRESHOLD) {@@ -420,14 +450,20 @@ export async function uploadLocalFile(// One extra byte detects growth without reading an arbitrarily enlarged file.const chunks: Buffer[] = [];let received = 0;- for await (const chunk of createReadStream(localPath, { end: size })) {+ // Cancellation stops the pre-read too; the catch below waits for this stream to close.+ const source = createReadStream(localPath, {+ end: size,+ ...(opts.signal ? { signal: opts.signal } : {}),+ });+ sourcesClosed.push(new Promise((resolve) => source.once('close', () => resolve())));+ for await (const chunk of source) {received += chunk.length;if (received > size) throw new Error('REMOTE_FILE_TOO_LARGE');chunks.push(chunk);}buf = Buffer.concat(chunks);} else {- buf = await readFile(localPath);+ buf = await readFile(localPath, opts.signal ? { signal: opts.signal } : undefined);}if (buf.byteLength !== size) {throw new Error(`文件在上传前发生变化:预期 ${size} 字节,实际 ${buf.byteLength} 字节`);@@ -435,7 +471,12 @@ export async function uploadLocalFile(sha256 = createHash('sha256').update(buf).digest('hex');// Buffer body 可重放:换栈重试直接复用同一份字节(fetch 不 transfer ArrayBuffer),// 也没有需要释放的底层资源。- await putBytesToOss(putUrl, { create: () => exactArrayBuffer(buf) }, contentType);+ await putBytesToOss(+ putUrl,+ { create: () => exactArrayBuffer(buf) },+ contentType,+ opts.signal,+ );opts.onProgress?.(size);} else {// 大媒体:磁盘流式 PUT,避免整文件进内存;经计数 Transform 上报进度。@@ -455,6 +496,7 @@ export async function uploadLocalFile(localPath,opts.maxBytes !== undefined ? { end: size } : undefined,);+ sourcesClosed.push(new Promise((resolve) => source.once('close', () => resolve())));const hasher = createHash('sha256');const current: StreamAttempt = {sent: 0,@@ -500,7 +542,7 @@ export async function uploadLocalFile(// 已缓冲的数据,每次换栈上传都漏一个。dispose: () => attempts.at(-1)?.dispose(),};- await putBytesToOss(putUrl, bodySource, contentType);+ await putBytesToOss(putUrl, bodySource, contentType, opts.signal);const uploadedAttempt = attempts.at(-1);if (!uploadedAttempt || uploadedAttempt.sent !== size) {// Cleanup is centralized below so transport and source-stream errors use the same path.@@ -512,8 +554,12 @@ export async function uploadLocalFile(sha256 = uploadedAttempt.sha256;}} catch (error) {- // Cleanup is best-effort after every post-presign transfer failure.- await removeRemote(key);+ // Cleanup is best-effort after every post-presign transfer failure; a cancelled upload+ // does not wait for it.+ const removing = removeRemote(key);+ // A cancelled upload skips the network wait but still returns only after the file is closed,+ // so the caller can delete it at once (Windows cannot remove an open file).+ await (opts.signal?.aborted ? Promise.all(sourcesClosed) : removing);throw error;}log.debug(`uploaded key=${key} size=${size} ct=${contentType} integrity=sha256`);@@ -667,6 +713,9 @@ export async function removeRemote(key: string): Promise<void> {method: 'DELETE',body: { key },baseUrl: deviceLinkApiBase,+ // Best-effort (the OSS lifecycle rule is the backstop): never let an unresponsive relay+ // hold up the upload failure or copy cancellation waiting on it.+ timeoutMs: REMOVE_REMOTE_TIMEOUT_MS,});log.debug(`removed key=${key}`);} catch (err) {diff --git a/apps/desktop/src/main/device-link/peerAttachmentStore.ts b/apps/desktop/src/main/device-link/peerAttachmentStore.tsindex c83dee33c2..00d0d41505 100644--- a/apps/desktop/src/main/device-link/peerAttachmentStore.ts+++ b/apps/desktop/src/main/device-link/peerAttachmentStore.ts@@ -109,19 +109,23 @@ export async function handlePeerAttachment(peer: string, r: Record<string, unknoreturn { ok: true };}if (r.op === 'write') {+ // Streaming senders deliver raw bytes (attached by the file-peer IPC); older senders base64.+ const binary = r.data instanceof Uint8Array;if (entry.complete ||!Number.isSafeInteger(r.offset) ||Number(r.offset) < 0 ||- typeof r.data !== 'string' ||- r.data.length > 1400000+ (!binary && (typeof r.data !== 'string' || r.data.length > 1400000)))throw new Error('FILE_PEER_BLOCK');- const bytes = Buffer.from(r.data, 'base64');+ const view = r.data as Uint8Array;+ const bytes = binary+ ? Buffer.from(view.buffer, view.byteOffset, view.byteLength)+ : Buffer.from(r.data as string, 'base64');if (!bytes.length ||bytes.length > 1024 * 1024 ||- bytes.toString('base64') !== r.data ||+ (!binary && bytes.toString('base64') !== r.data) ||Number(r.offset) + bytes.length > entry.size)throw new Error('FILE_PEER_BLOCK');diff --git a/apps/desktop/src/main/task-migration/__tests__/service.test.ts b/apps/desktop/src/main/task-migration/__tests__/service.test.tsindex aeeb5589ee..826f0e4832 100644--- a/apps/desktop/src/main/task-migration/__tests__/service.test.ts+++ b/apps/desktop/src/main/task-migration/__tests__/service.test.ts@@ -29,6 +29,8 @@ const state = vi.hoisted(() => ({drain: vi.fn(),exported: vi.fn(),uploadedProgress: vi.fn(),+ /** Models a long in-flight upload: it only ends when its signal aborts. */+ stallUpload: undefined as undefined | (() => void),loseReply: '' as string,importsFail: false,siblingRunning: false,@@ -142,7 +144,16 @@ vi.mock('../../device-link/filePeer', () => ({ tryUploadPeerAttachment: async ()vi.mock('../../device-link/mediaTransfer', () => ({MAX_MEDIA_BYTES: 2 * 1024 ** 3,removeRemote: (key: string) => state.remove(key),- uploadLocalFile: async (file: string, opts: { onProgress?: (bytes: number) => void }) => {+ uploadLocalFile: async (+ file: string,+ opts: { onProgress?: (bytes: number) => void; signal?: AbortSignal },+ ) => {+ if (state.stallUpload) {+ state.stallUpload();+ await new Promise((_, reject) =>+ opts.signal?.addEventListener('abort', () => reject(new Error('UPLOAD_CANCELLED'))),+ );+ }const bytes = await fs.readFile(file),key = `migration/${state.files.size}`;opts.onProgress?.(bytes.length);@@ -313,6 +324,7 @@ describe('resumable cross-computer copy', () => {state.drain.mockReset();state.exported.mockClear();state.uploadedProgress.mockReset();+ state.stallUpload = undefined;state.root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-migration-service-')),);@@ -664,6 +676,29 @@ describe('resumable cross-computer copy', () => {await start();expect((await settled()).stage).toBe('complete');});+ it('cancelling stops the file in flight instead of waiting for it to finish', async () => {+ let started!: () => void;+ const uploading = new Promise<void>((resolve) => (started = resolve));+ state.stallUpload = () => started();+ expect((await start()).cancellable).toBe(true);+ await uploading;+ expect(await requestTaskMigration({ action: 'cancel', sessionId: 'fork' })).toMatchObject({+ running: true,+ cancelling: true,+ });+ // Without aborting the stalled upload this never settles.+ const status = await settled();+ expect(status.stage).toBe('cancelled');+ expect(status.error).toBeUndefined();+ expect(state.files.size).toBe(0);+ expect(state.imports).not.toHaveBeenCalled();+ await expect(+ fs.stat(path.join(state.root, 'A', 'task-copies', 'outgoing', status.targetSessionId!)),+ ).rejects.toMatchObject({ code: 'ENOENT' });+ state.stallUpload = undefined;+ await start();+ expect((await settled()).stage).toBe('complete');+ });it('closing a failed transfer removes source staging without deleting an already committed target', async () => {state.loseReply = 'receive';await start();diff --git a/apps/desktop/src/main/task-migration/service.ts b/apps/desktop/src/main/task-migration/service.tsindex 1e17138c0a..a612620680 100644--- a/apps/desktop/src/main/task-migration/service.ts+++ b/apps/desktop/src/main/task-migration/service.ts@@ -94,6 +94,8 @@ interface RunningCopy {/** The target may commit from here on; cancelling would orphan its copy. */committing?: boolean;cancelRequested?: boolean;+ /** Aborted together with cancelRequested so the file in flight stops, not just the next checkpoint. */+ abort: AbortController;}const running = new Map<string, RunningCopy>();/** The target's cause never crosses the wire (only its code does), so keep it in this log. */@@ -486,20 +488,31 @@ async function sendFile(file: string,artifacts = path.dirname(file),onProgress?: (bytes: number) => void,+ signal?: AbortSignal,): Promise<MigrationFile> {const space = await fs.statfs(path.dirname(file));const partBytes = Math.floor(Math.min(FILE_PEER_MAX_BYTES, MAX_MEDIA_BYTES, (space.bavail * space.bsize) / 4),);let completed = 0;- return sendParts(file, partBytes, async (part) => {- const result = await sendPart(scope, device, part, artifacts, (bytes) =>- onProgress?.(completed + bytes),- );- completed += result.size;- onProgress?.(completed);- return result;- });+ return sendParts(+ file,+ partBytes,+ async (part) => {+ const result = await sendPart(+ scope,+ device,+ part,+ artifacts,+ (bytes) => onProgress?.(completed + bytes),+ signal,+ );+ completed += result.size;+ onProgress?.(completed);+ return result;+ },+ signal,+ );}async function sendPart(scope: Scope,@@ -507,6 +520,7 @@ async function sendPart(file: string,artifacts: string,onProgress?: (bytes: number) => void,+ signal?: AbortSignal,): Promise<MigrationFileRef> {scope.assertCurrent();const peer = await tryUploadPeerAttachment(@@ -516,6 +530,7 @@ async function sendPart((deviceId, channel, args) =>remoteInvoke(deviceId, channel, args, { preSend: scope.assertCurrent }),onProgress,+ signal,);scope.assertCurrent();if (peer) {@@ -524,7 +539,11 @@ async function sendPart(return { ref: peer, size: result.size, sha256: result.sha256 };}onProgress?.(0); // OSS fallback starts this part again, not a second completed part.- const result = await uploadLocalFile(file, { maxBytes: (await fs.stat(file)).size, onProgress });+ const result = await uploadLocalFile(file, {+ maxBytes: (await fs.stat(file)).size,+ onProgress,+ signal,+ });// Record the upload before the checkpoint so a cancelled copy still deletes it.const keysFile = path.join(artifacts, 'transfer-keys.json');const keys = JSON.parse(readAtomicFileSync(keysFile) ?? '[]') as string[];@@ -650,15 +669,22 @@ async function transfer(scope: Scope, record: MigrationHandoff) {bytesPerSecond: 0,};const send = async (file: string, artifacts = path.dirname(file)) => {- const result = await sendFile(scope, record.targetDeviceId, file, artifacts, (bytes) => {- const sentBytes = Math.min(resources.transferBytes, completed + bytes);- live.progress = {- phase: 'sending',- sentBytes,- totalBytes: resources.transferBytes,- bytesPerSecond: (sentBytes * 1000) / Math.max(1, Date.now() - startedAt),- };- });+ const result = await sendFile(+ scope,+ record.targetDeviceId,+ file,+ artifacts,+ (bytes) => {+ const sentBytes = Math.min(resources.transferBytes, completed + bytes);+ live.progress = {+ phase: 'sending',+ sentBytes,+ totalBytes: resources.transferBytes,+ bytesPerSecond: (sentBytes * 1000) / Math.max(1, Date.now() - startedAt),+ };+ },+ live.abort.signal,+ );completed += result.size;return result;};@@ -726,7 +752,10 @@ function launch(scope: Scope, record: MigrationHandoff & { kind: 'outgoing' }) {const key = `${scope.root}:${record.sessionId}`;if (running.has(key)) return;// See transfer(): a resumed transfer stays non-cancellable until its receipt is checked.- const live: RunningCopy = { committing: record.stage !== 'preparing' };+ const live: RunningCopy = {+ committing: record.stage !== 'preparing',+ abort: new AbortController(),+ };running.set(key, live);// Every existing checkpoint doubles as a cancellation point for this copy.const copyScope: Scope = {@@ -1195,6 +1224,7 @@ export async function requestTaskMigration(raw: unknown): Promise<TaskMigrationVif (live) {if (live.committing) throw new Error('MIGRATION_CANNOT_CANCEL');live.cancelRequested = true;+ live.abort.abort();return view(scope, scope.read(request.sessionId));}}diff --git a/apps/desktop/src/main/task-migration/transferParts.ts b/apps/desktop/src/main/task-migration/transferParts.tsindex 7b7afb9209..211d1bdb21 100644--- a/apps/desktop/src/main/task-migration/transferParts.ts+++ b/apps/desktop/src/main/task-migration/transferParts.ts@@ -10,6 +10,7 @@ export async function sendParts(file: string,maxPartBytes: number,send: (file: string) => Promise<MigrationFileRef>,+ signal?: AbortSignal,): Promise<MigrationFile> {const size = (await fs.stat(file)).size;if (!Number.isSafeInteger(maxPartBytes) || maxPartBytes < 1)@@ -22,9 +23,11 @@ export async function sendParts(const length = Math.min(maxPartBytes, size - offset);await assertDiskCapacity([{ path: directory, bytes: length }]);const part = path.join(directory, 'part');+ // Copying a part can take a while for multi-GB files; cancellation stops it too.await pipeline(createReadStream(file, { start: offset, end: offset + length - 1 }),createWriteStream(part, { flags: 'wx', mode: 0o600 }),+ { signal },);const sent = await send(part);if (sent.size !== length) throw new Error('MIGRATION_WORKSPACE_CHANGED');diff --git a/apps/desktop/src/preload/desktopCapturePreload.ts b/apps/desktop/src/preload/desktopCapturePreload.tsindex 4fa159cf17..6f3f7c1a44 100644--- a/apps/desktop/src/preload/desktopCapturePreload.ts+++ b/apps/desktop/src/preload/desktopCapturePreload.ts@@ -41,7 +41,8 @@ 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),+ invoke: (connection, payload, body) =>+ ipcRenderer.invoke(FILE_PEER_LOCAL.INVOKE, connection, payload, body),};contextBridge.exposeInMainWorld('filePeerHost', files);} else contextBridge.exposeInMainWorld('desktopCapture', api);diff --git a/apps/desktop/src/renderer/features/cc-agent/TaskMigrationStatus.tsx b/apps/desktop/src/renderer/features/cc-agent/TaskMigrationStatus.tsxindex e54dfb8dfa..13ba570af2 100644--- a/apps/desktop/src/renderer/features/cc-agent/TaskMigrationStatus.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/TaskMigrationStatus.tsx@@ -58,7 +58,13 @@ export function TaskMigrationStatus({ session }: { session: Session }) {? t('taskMigration.completeWithSkipped', { count: status.skipped.total }): t(`taskMigration.stages.${status.stage}`)}</Button>- {open && <TaskMigrationDialog session={session} onDismiss={() => setOpen(false)} />}+ {open && (+ <TaskMigrationDialog+ session={session}+ initialStatus={status}+ onDismiss={() => setOpen(false)}+ />+ )}</>);}diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsxindex d480eb9e42..f304c05a58 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/TaskMigrationDialog.tsx@@ -23,10 +23,16 @@ export function TaskMigrationDialog({session,onDismiss,destination,+ initialStatus,}: {session: Session;onDismiss(): void;destination?: TaskMoveDestination;+ /**+ * The caller's latest status when reopening an existing copy (no `destination`). Without it the+ * dialog would show the start form until its first poll returns.+ */+ initialStatus?: TaskMigrationView | null;}) {const { t } = useTranslation();const navigate = useNavigate();@@ -34,7 +40,9 @@ export function TaskMigrationDialog({const [target, setTarget] = useState(destination?.deviceId ?? '');const [projects, setProjects] = useState<string[]>([]);const [project, setProject] = useState(destination?.project ?? '');- const [status, setStatus] = useState<TaskMigrationView | null>(null);+ const [status, setStatus] = useState<TaskMigrationView | null>(+ destination ? null : (initialStatus ?? null),+ );const [busy, setBusy] = useState(false);const [starting, setStarting] = useState(false);const [readyTarget, setReadyTarget] = useState('');diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/TaskMigrationDialog.test.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/TaskMigrationDialog.test.tsxindex 1470d31995..0cf2e60ac9 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/TaskMigrationDialog.test.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/TaskMigrationDialog.test.tsx@@ -322,6 +322,33 @@ it('keeps transfer progress in the dialog until the target completes, includingexpect(screen.getAllByRole('button')).toHaveLength(2);});+it('reopening a running copy shows its progress at once, never the start form', async () => {+ const running = {+ supported: true,+ deviceId: 'A',+ stage: 'transferring',+ running: true,+ targetDeviceId: 'B',+ progress: { phase: 'sending', sentBytes: 1, totalBytes: 2, bytesPerSecond: 1 },+ } as const;+ // The first poll is still in flight when the dialog opens.+ state.request.mockImplementation(() => new Promise(() => {}));+ render(+ <MemoryRouter>+ <TaskMigrationDialog session={source} initialStatus={running} onDismiss={state.dismiss} />+ </MemoryRouter>,+ );+ expect(screen.getByText('taskMigration.copyingTitle')).toBeTruthy();+ expect(screen.getByText('taskMigration.transferProgress')).toBeTruthy();+ expect(screen.queryByText('taskMigration.title')).toBeNull();+ expect(screen.queryByText('taskMigration.start')).toBeNull();+ expect(screen.queryByText('taskMigration.bindingsNotice')).toBeNull();+ expect(+ state.request.mock.calls.some(+ ([, command]) => (command as { action: string }).action === 'estimate',+ ),+ ).toBe(false);+});it('cancels a running copy and closes once the source has stopped it', async () => {let snapshot: Record<string, unknown> = {stage: 'transferring',diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 4eb8fceeb2..9ad84cb9e2 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -75,11 +75,11 @@"keepOpen": "Copying to {{name}}. Closing this window won't stop the copy; check progress at the top of the original task.","runInBackground": "Continue in background","cancelCopy": "Cancel copy",- "cancelling": "Cancelling. Stops after the current file finishes sending…",+ "cancelling": "Cancelling…","failureTitle": "Copy failed","failureDescription": "Close this window and start a new copy from the task menu.","finishing": "{{name}} is receiving, checking and creating the task…",- "transferProgress": "Upload progress {{sent}} / {{total}} · Average {{speed}}/s (reception not yet complete)",+ "transferProgress": "Transferred {{sent}} / {{total}} · Average {{speed}}/s","thisComputer": "this computer","selectedComputer": "selected computer","estimating": "Counting files and calculating size…",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 17615e6fd9..8342b553da 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -75,11 +75,11 @@"keepOpen": "{{name}}にコピーしています。このウィンドウを閉じてもコピーは続行され、元のタスク上部で進捗を確認できます。","runInBackground": "バックグラウンドで続行","cancelCopy": "コピーをキャンセル",- "cancelling": "キャンセルしています。現在のファイルの送信が終わると停止します…",+ "cancelling": "キャンセルしています…","failureTitle": "コピー失敗","failureDescription": "閉じた後、タスクメニューから新しくコピーできます。","finishing": "{{name}}で受信・検証し、タスクを作成中…",- "transferProgress": "アップロード {{sent}} / {{total}} · 平均 {{speed}}/s(受信は未完了)",+ "transferProgress": "転送済み {{sent}} / {{total}} · 平均 {{speed}}/s","thisComputer": "このコンピューター","selectedComputer": "選択したコンピューター","estimating": "ファイル数とサイズを計算中…",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex e475e71bbb..cbbbb29517 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -75,11 +75,11 @@"keepOpen": "{{name}}로 복사 중입니다. 창을 닫아도 복사는 계속되며, 원본 작업 상단에서 진행 상황을 확인할 수 있습니다.","runInBackground": "백그라운드에서 계속","cancelCopy": "복사 취소",- "cancelling": "취소하는 중입니다. 현재 파일 전송이 끝나면 중지됩니다…",+ "cancelling": "취소하는 중…","failureTitle": "복사 실패","failureDescription": "창을 닫은 후 작업 메뉴에서 새로 복사할 수 있습니다.","finishing": "{{name}}에서 수신, 검증 및 작업 생성 중…",- "transferProgress": "업로드 {{sent}} / {{total}} · 평균 {{speed}}/s (수신 미완료)",+ "transferProgress": "전송됨 {{sent}} / {{total}} · 평균 {{speed}}/s","thisComputer": "이 컴퓨터","selectedComputer": "선택한 컴퓨터","estimating": "파일 수와 크기 계산 중…",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex a68570ce9d..05b517c498 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -75,11 +75,11 @@"keepOpen": "正在复制到{{name}}。关闭窗口不会中断复制,可在原任务顶部查看进度。","runInBackground": "后台继续","cancelCopy": "取消复制",- "cancelling": "正在取消,当前文件发送完后停止…",+ "cancelling": "正在取消…","failureTitle": "复制失败","failureDescription": "关闭后可从任务菜单重新发起复制。","finishing": "{{name}}正在接收、校验并创建任务…",- "transferProgress": "上传进度 {{sent}} / {{total}} · 平均 {{speed}}/s(尚未完成接收)",+ "transferProgress": "已传输 {{sent}} / {{total}} · 平均 {{speed}}/s","thisComputer": "本机","selectedComputer": "所选电脑","estimating": "正在统计文件数量和大小…",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex a7a2d76946..b93b3f20ff 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -75,11 +75,11 @@"keepOpen": "正在複製到{{name}}。關閉視窗不會中斷複製,可在原任務頂部查看進度。","runInBackground": "背景繼續","cancelCopy": "取消複製",- "cancelling": "正在取消,目前檔案傳送完後停止…",+ "cancelling": "正在取消…","failureTitle": "複製失敗","failureDescription": "關閉後可從任務選單重新發起複製。","finishing": "{{name}}正在接收、驗證並建立任務…",- "transferProgress": "上傳進度 {{sent}} / {{total}} · 平均 {{speed}}/s(尚未完成接收)",+ "transferProgress": "已傳輸 {{sent}} / {{total}} · 平均 {{speed}}/s","thisComputer": "本機","selectedComputer": "所選電腦","estimating": "正在統計檔案數量和大小…",diff --git a/apps/desktop/src/shared/filePeer.ts b/apps/desktop/src/shared/filePeer.tsindex 6dd3eaeb47..5200cf4aab 100644--- a/apps/desktop/src/shared/filePeer.ts+++ b/apps/desktop/src/shared/filePeer.ts@@ -10,7 +10,8 @@ export const FILE_PEER_LOCAL = {export type FilePeerCommand =| { action: 'offer'; connection: string; servers: DesktopIceServer[]; streaming?: boolean }| { action: 'stats'; connection: string }- | { action: 'invoke'; connection: string; payload: string; timeoutMs?: number }+ /** `body`: base64 block sent as the RPC binary body (peer advertised streamAttachments). */+ | { action: 'invoke'; connection: string; payload: string; timeoutMs?: number; body?: 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 }@@ -21,5 +22,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>;+ invoke(connection: string, payload: string, body?: Uint8Array): Promise<string>;}diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 97ce77589f..8d9f667e80 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -266,6 +266,15 @@ OSS 保底仍受服务端 presign 单对象上限(`OSS_ATTACHMENT_MAX_BYTES`文件读取(`open`)仍沿用 `FILE_PEER_MAX_BYTES`。不新增 channel、relay 类型或持久化 schema,服务端无需改动。+直连附件上传的提速同样按能力协商:Desktop 主机的 `caps` 追加可选 `streamAttachments: true`,+表示它接受同一附件最多 `PEER_ATTACHMENT_STREAM_WINDOW`(3)个写入块同时在途,并接受以+RPC 二进制正文传来的块(`write` 不带 `data`,原始字节紧跟该请求的最后一个 JSON 分片发送,+单块不超过 1 MiB;在途写入的等待按窗口放宽为 45 秒)。接收端仍按发送顺序逐块落盘、要求+偏移连续,`finish` 照旧校验大小与 SHA-256。旧主机不声明该能力:发送端继续逐块等确认并用+base64 `data` 字段,不向旧主机发送二进制帧(旧运行时收到会关闭连接)。旧发送端不读新字段,+新主机继续接受 base64 块。Mobile 发送端暂沿用逐块方式。不新增 channel、relay 类型或持久化+schema,服务端无需改动。+## 任务复制的外置会话记录与超限大小`maker:task-copy` 的 `caps` 追加 `externalTranscripts: true`。源端在每次准备时询问;目标声明后,diff --git a/docs/dev-rules/remote-desktop-connectivity.md b/docs/dev-rules/remote-desktop-connectivity.mdindex 2304cd2080..4269dc8cc2 100644--- a/docs/dev-rules/remote-desktop-connectivity.md+++ b/docs/dev-rules/remote-desktop-connectivity.md@@ -367,6 +367,9 @@ guests continue using their existing OSS scope. New peer references are sent onlto a capable host. The receiving Main process checks size and SHA-256 before returningthe reference, then normal message acceptance materializes it through the existingmedia/file ownership logic. Message acceptance itself remains on WSS.+Hosts that also advertise `caps.streamAttachments` accept up to three 1 MiB blocks in+flight, sent as raw RPC bodies instead of base64 fields; other hosts keep the+one-block-at-a-time base64 upload ([protocol-compatibility.md](protocol-compatibility.md)).The host inbox lives under the current owner's userData namespace. Tickets bind tothe source controller and are rechecked when materialized. Completed staging survivesdiff --git a/docs/product-rules/task-device-migration.md b/docs/product-rules/task-device-migration.mdindex 1268185f6b..faaf101880 100644--- a/docs/product-rules/task-device-migration.md+++ b/docs/product-rules/task-device-migration.md@@ -38,8 +38,11 @@提示改为复制文件更少的项目,不开始复制。该上限只是确认页的准入检查,复制本身仍不设总量上限。6. 复制进行中的弹窗可通过「后台继续」或 Esc 关闭,关闭不中断复制,之后从原任务顶部的复制状态重新查看进度(2026-10-01 用户要求,替代此前“全程保留弹窗、不提供隐藏到后台入口”的口径)。准备阶段显示 Spinner 与空进度条,- 发送阶段显示本机上传字节进度及平均速度,明确接收尚未完成。- 源端声明 `cancellable` 时提供「取消复制」:在目标开始接收前,于既有检查点中止(正在发送的文件发完后生效),+ 发送阶段显示“已传输 X / Y · 平均 Z/s”(2026-10-02 用户确认:不写“上传”、去掉“尚未完成接收”的括注;+ 状态行已写明正在传输并校验文件,接收、校验与创建任务另有阶段显示,见下文)。+ 源端声明 `cancellable` 时提供「取消复制」:在目标开始接收前立即中止,正在发送的文件(直连或 OSS 中转)+ 与大文件分段复制都当场停止、不等发完(含仍在建立的直连与等待中的块确认);直连已送达的部分通知目标丢弃,+ 取消不计入直连失败冷却。随后清理已上传的 OSS 对象及本地暂存并记为已取消,弹窗显示 `cancelling` 直到停稳后关闭;目标开始接收后拒绝取消(`MIGRATION_CANNOT_CANCEL`),不回滚目标;重试中的复制在回执确认目标没有这次复制的接收记录前同样不可取消。旧源端不声明 `cancellable`,只提供后台继续。OSS 进度计 HTTP 请求体已提交字节(可能仍在缓冲),peer 计分段确认字节,不作为接收完成凭据。diff --git a/packages/device-link/src/__tests__/filePeerRuntime.test.ts b/packages/device-link/src/__tests__/filePeerRuntime.test.tsnew file mode 100644index 0000000000..df4e5bc7f9--- /dev/null+++ b/packages/device-link/src/__tests__/filePeerRuntime.test.ts@@ -0,0 +1,73 @@+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { createFilePeerRuntime } from "../filePeerRuntime.js";++/** Just enough of RTCPeerConnection for `offer()` to open the RPC channel. */+interface FakeChannel {+ label: string;+ readyState: string;+ closed: boolean;+ onmessage?: (event: { data: unknown }) => void;+ send(data: unknown): void;+ close(): void;+}+const channels: FakeChannel[] = [];+class FakePeerConnection {+ localDescription = { sdp: "v=0" };+ iceGatheringState = "complete";+ signalingState = "stable";+ createDataChannel(label: string) {+ const channel: FakeChannel = {+ label,+ readyState: "open",+ closed: false,+ send() {},+ close() {+ this.closed = true;+ },+ };+ channels.push(channel);+ return channel;+ }+ async createOffer() {+ return { type: "offer", sdp: "v=0" };+ }+ async setLocalDescription() {}+ addEventListener() {}+ removeEventListener() {}+ close() {}+}++beforeEach(() => {+ channels.length = 0;+ vi.stubGlobal("RTCPeerConnection", FakePeerConnection);+});+afterEach(() => vi.unstubAllGlobals());++async function rpcChannel(invoke: (id: string, payload: string, body?: Uint8Array) => Promise<string>) {+ const runtime = createFilePeerRuntime({ read: async () => "", write: async () => {}, invoke });+ await runtime.offer("peer", [], true);+ return channels.find((channel) => channel.label === "reads-v1")!;+}+const header = (body: number) =>+ JSON.stringify({ key: "1", response: false, data: "{}", last: true, body });++it("accepts a body in the sender's framing: full 16 KiB frames, shorter only at the end", async () => {+ const invoke = vi.fn(async () => "ok");+ const rpc = await rpcChannel(invoke);+ rpc.onmessage!({ data: header(16384 + 3) });+ rpc.onmessage!({ data: new Uint8Array(16384).buffer });+ rpc.onmessage!({ data: new Uint8Array([1, 2, 3]).buffer });+ expect(rpc.closed).toBe(false);+ expect(invoke).toHaveBeenCalledTimes(1);+ expect((invoke.mock.calls[0] as unknown[])[2]).toHaveLength(16384 + 3);+});++it("closes the channel when a peer splits a body into smaller frames", async () => {+ const invoke = vi.fn(async () => "ok");+ const rpc = await rpcChannel(invoke);+ rpc.onmessage!({ data: header(1024 * 1024) });+ // A tiny frame where a full 16 KiB one belongs would let a peer pile up a million parts.+ rpc.onmessage!({ data: new Uint8Array(1).buffer });+ expect(rpc.closed).toBe(true);+ expect(invoke).not.toHaveBeenCalled();+});diff --git a/packages/device-link/src/__tests__/peerAcceleration.test.ts b/packages/device-link/src/__tests__/peerAcceleration.test.tsindex 675c65866b..a1a63afb1f 100644--- a/packages/device-link/src/__tests__/peerAcceleration.test.ts+++ b/packages/device-link/src/__tests__/peerAcceleration.test.ts@@ -7,6 +7,7 @@ import {parsePeerAttachmentRef,peerAttachmentFinishTimeoutMs,buildPeerAttachmentRef,+ PEER_ATTACHMENT_STREAM_WINDOW,} from "../peerAttachment.js";describe("peer acceleration policy", () => {@@ -119,4 +120,95 @@ describe("peer acceleration policy", () => {"cancel",]);});+ it("streams blocks with a bounded in-flight window and raw bodies; legacy peers stay stop-and-wait", async () => {+ const ticket = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";+ const size = 5 * 1024 * 1024 + 7;+ for (const stream of [true, false]) {+ let inFlight = 0;+ let maxInFlight = 0;+ const releases: Array<() => void> = [];+ const writes: Array<{ request: Record<string, unknown>; timeoutMs?: number; body?: string }> = [];+ const progress = vi.fn();+ const upload = uploadPeerAttachment(+ { size, sha256: "a".repeat(64) },+ async (offset, length) => `${offset}:${length}`,+ async (request, timeoutMs, body) => {+ if (request.op === "begin") return { ticket };+ if (request.op !== "write") return {};+ writes.push({ request, timeoutMs, body });+ maxInFlight = Math.max(maxInFlight, ++inFlight);+ await new Promise<void>((resolve) => releases.push(resolve));+ inFlight--;+ return {};+ },+ () => {},+ progress,+ stream,+ );+ while (writes.length < 6 || releases.length) {+ await vi.waitFor(() => expect(releases.length).toBeGreaterThan(0));+ releases.shift()!();+ await Promise.resolve();+ }+ await upload;+ expect(maxInFlight).toBe(stream ? PEER_ATTACHMENT_STREAM_WINDOW : 1);+ expect(writes.map((w) => w.request.offset)).toEqual(+ [0, 1, 2, 3, 4, 5].map((i) => i * 1024 * 1024),+ );+ const last = writes[5];+ if (stream) {+ expect(last.request.data).toBeUndefined();+ expect(last.body).toBe(`${5 * 1024 * 1024}:7`);+ expect(last.timeoutMs).toBe(15_000 * PEER_ATTACHMENT_STREAM_WINDOW);+ } else {+ expect(last.request.data).toBe(`${5 * 1024 * 1024}:7`);+ expect(last.body).toBeUndefined();+ expect(last.timeoutMs).toBeUndefined();+ }+ // Progress only advances over acknowledged blocks, in order.+ expect(progress.mock.calls.map(([bytes]) => bytes)).toEqual([+ ...[1, 2, 3, 4, 5].map((i) => i * 1024 * 1024),+ size,+ ]);+ }+ });+ it("stops streaming on the first failed block, cancels once and leaves no unhandled rejection", async () => {+ const unhandled = vi.fn();+ process.on("unhandledRejection", unhandled);+ try {+ const ops: string[] = [];+ const progress = vi.fn();+ await expect(+ uploadPeerAttachment(+ { size: 4 * 1024 * 1024, sha256: "a".repeat(64) },+ // A macrotask per read lets the failed block settle before the next one is sent.+ async () => {+ await new Promise((resolve) => setTimeout(resolve, 0));+ return "YQ==";+ },+ async (request) => {+ ops.push(String(request.op));+ if (request.op === "begin")+ return { ticket: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa" };+ // A later block fails before the first is acknowledged.+ if (request.op === "write" && request.offset !== 0)+ throw new Error(`lost ${request.offset}`);+ if (request.op === "write")+ await new Promise((resolve) => setTimeout(resolve, 10));+ return {};+ },+ () => {},+ progress,+ true,+ ),+ ).rejects.toThrow(`lost ${1024 * 1024}`);+ await new Promise((resolve) => setTimeout(resolve, 20));+ // Nothing more is sent once a block is known to have failed.+ expect(ops).toEqual(["begin", "write", "write", "cancel"]);+ expect(progress.mock.calls).toEqual([[1024 * 1024]]);+ expect(unhandled).not.toHaveBeenCalled();+ } finally {+ process.off("unhandledRejection", unhandled);+ }+ });});diff --git a/packages/device-link/src/filePeerRuntime.ts b/packages/device-link/src/filePeerRuntime.tsindex a43ea4127e..b032d1a019 100644--- a/packages/device-link/src/filePeerRuntime.ts+++ b/packages/device-link/src/filePeerRuntime.ts@@ -3,9 +3,21 @@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>;+ /** `body` carries a request's binary payload (see RPC_BODY_MAX_BYTES). */+ invoke?(+ connection: string,+ payload: string,+ body?: Uint8Array,+ ): Promise<string>;}+/**+ * A request may append up to 1 MiB of raw bytes after its JSON fragments. Peers that do+ * not advertise `caps.streamAttachments` close the channel on binary frames, so callers+ * send a body only to capable peers.+ */+export const RPC_BODY_MAX_BYTES = 1024 * 1024;+/** Diagnostics only: application-level progress of the latest receive on a peer. */interface ReceiveProgress {size: number;@@ -60,11 +72,16 @@ export function createFilePeerRuntime(bridge: FilePeerRuntimeBridge) {string,{channel: RTCDataChannel;- request(payload: string, timeoutMs?: number): Promise<string>;+ request(+ payload: string,+ timeoutMs?: number,+ body?: Uint8Array,+ ): Promise<string>;close(): void;}>();function attachRpc(id: string, dc: RTCDataChannel) {+ dc.binaryType = "arraybuffer";const pending = new Map<string,{@@ -75,22 +92,91 @@ export function createFilePeerRuntime(bridge: FilePeerRuntimeBridge) {>();const fragments = new Map<string,- { data: string; timer: ReturnType<typeof setTimeout> }+ {+ data: string;+ timer: ReturnType<typeof setTimeout>;+ body?: { remaining: number; parts: Uint8Array[] };+ }>();+ // A body's binary frames directly follow its last JSON fragment: send() emits a whole+ // message synchronously on an ordered channel, so nothing can interleave.+ let receivingBody: string | undefined;+ // An incomplete message closes the connection only after this long without any new frame:+ // a slow but live link keeps a body alive however long it takes.+ const stallMs = 15000;let sequence = 0;let active = 0;- const send = (key: string, response: boolean, value: string) => {- if (value.length > 4 * 1024 * 1024 || dc.readyState !== "open")+ const send = (+ key: string,+ response: boolean,+ value: string,+ body?: Uint8Array,+ ) => {+ if (+ value.length > 4 * 1024 * 1024 ||+ (body && (!body.length || body.length > RPC_BODY_MAX_BYTES)) ||+ dc.readyState !== "open"+ )throw new Error("FILE_PEER_RPC_SIZE");- for (let offset = 0; offset < Math.max(1, value.length); offset += 16384)+ for (+ let offset = 0;+ offset < Math.max(1, value.length);+ offset += 16384+ ) {+ const last = offset + 16384 >= value.length;dc.send(JSON.stringify({key,response,data: value.slice(offset, offset + 16384),- last: offset + 16384 >= value.length,+ last,+ ...(last && body ? { body: body.length } : {}),}),);+ }+ if (body)+ for (let offset = 0; offset < body.length; offset += 16384)+ dc.send(body.slice(offset, offset + 16384));+ };+ const dispatch = (key: string, payload: string, body?: Uint8Array) => {+ if (!bridge.invoke || active >= 4) throw new Error();+ active++;+ void bridge+ .invoke(id, payload, body)+ .then((value) => {+ if (peers.has(id)) send(key, true, value);+ })+ .catch(() => close(id))+ .finally(() => {+ active--;+ });+ };+ const receiveBody = (data: unknown) => {+ const f = receivingBody ? fragments.get(receivingBody) : undefined;+ if (!f?.body || !(data instanceof ArrayBuffer)) throw new Error();+ const bytes = new Uint8Array(data);+ // Exactly the sender's framing (16 KiB, shorter only at the end), like the files-v2 receive+ // path: a peer cannot make the body arrive as millions of tiny frames.+ if (bytes.length !== Math.min(16384, f.body.remaining)) throw new Error();+ f.body.parts.push(bytes);+ f.body.remaining -= bytes.length;+ clearTimeout(f.timer);+ if (f.body.remaining) {+ f.timer = setTimeout(() => close(id), stallMs);+ return;+ }+ const key = receivingBody!;+ receivingBody = undefined;+ fragments.delete(key);+ const body = new Uint8Array(+ f.body.parts.reduce((sum, part) => sum + part.length, 0),+ );+ let offset = 0;+ for (const part of f.body.parts) {+ body.set(part, offset);+ offset += part.length;+ }+ dispatch(key.slice("false:".length), f.data, body);};const shutdown = () => {for (const p of pending.values()) {@@ -105,6 +191,7 @@ export function createFilePeerRuntime(bridge: FilePeerRuntimeBridge) {dc.onclose = shutdown;dc.onmessage = ({ data }) => {try {+ if (receivingBody !== undefined) return receiveBody(data);if (typeof data !== "string" || data.length > 100000) throw new Error();const m = JSON.parse(data);if (@@ -113,7 +200,13 @@ export function createFilePeerRuntime(bridge: FilePeerRuntimeBridge) {typeof m.response !== "boolean" ||typeof m.last !== "boolean" ||typeof m.data !== "string" ||- m.data.length > 16384+ m.data.length > 16384 ||+ (m.body !== undefined &&+ (m.response ||+ !m.last ||+ !Number.isSafeInteger(m.body) ||+ m.body < 1 ||+ m.body > RPC_BODY_MAX_BYTES)))throw new Error();if (m.response && !pending.has(m.key)) return;@@ -121,12 +214,19 @@ export function createFilePeerRuntime(bridge: FilePeerRuntimeBridge) {let f = fragments.get(key);if (!f) {if (fragments.size >= 8) throw new Error();- f = { data: "", timer: setTimeout(() => close(id), 15000) };+ f = { data: "", timer: setTimeout(() => close(id), stallMs) };fragments.set(key, f);}f.data += m.data;if (f.data.length > 4 * 1024 * 1024) throw new Error();if (!m.last) return;+ if (m.body !== undefined) {+ clearTimeout(f.timer);+ f.timer = setTimeout(() => close(id), stallMs);+ f.body = { remaining: m.body, parts: [] };+ receivingBody = key;+ return;+ }clearTimeout(f.timer);fragments.delete(key);if (m.response) {@@ -134,19 +234,7 @@ export function createFilePeerRuntime(bridge: FilePeerRuntimeBridge) {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--;- });- }+ } else dispatch(m.key, f.data);} catch {close(id);}@@ -154,21 +242,18 @@ export function createFilePeerRuntime(bridge: FilePeerRuntimeBridge) {rpcPeers.set(id, {channel: dc,close: shutdown,- request(payload, timeoutMs) {+ request(payload, timeoutMs, body) {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"));- },- rpcTimeoutMs(timeoutMs),- );+ const timer = setTimeout(() => {+ pending.delete(key);+ reject(new Error("FILE_PEER_TIMEOUT"));+ }, rpcTimeoutMs(timeoutMs));pending.set(key, { resolve, reject, timer });try {- send(key, false, payload);+ send(key, false, payload, body);} catch (error) {pending.delete(key);clearTimeout(timer);@@ -609,10 +694,29 @@ export function createFilePeerRuntime(bridge: FilePeerRuntimeBridge) {}}return {- async invoke(id: string, payload: string, timeoutMs?: number) {+ /** `body` is base64 so string-only bridges (Mobile WebView) can pass it; it travels as raw bytes. */+ async invoke(+ id: string,+ payload: string,+ timeoutMs?: number,+ body?: string,+ ) {const rpc = rpcPeers.get(id);if (!rpc) throw new Error("FILE_PEER_UNAVAILABLE");- return rpc.request(payload, timeoutMs);+ if (body === undefined) return rpc.request(payload, timeoutMs);+ if (+ typeof body !== "string" ||+ body.length > Math.ceil(RPC_BODY_MAX_BYTES / 3) * 4 ||+ !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(+ body,+ )+ )+ throw new Error("FILE_PEER_RPC_SIZE");+ return rpc.request(+ payload,+ timeoutMs,+ Uint8Array.from(atob(body), (c) => c.charCodeAt(0)),+ );},async stats(id: string) {const p = peers.get(id);diff --git a/packages/device-link/src/filePeerRuntimeSource.ts b/packages/device-link/src/filePeerRuntimeSource.tsindex d8f514636f..a710d11742 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 A=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var W=Object.getOwnPropertyNames;var V=Object.prototype.hasOwnProperty;var j=(p,g)=>{for(var S in g)A(p,S,{get:g[S],enumerable:!0})},z=(p,g,S,P)=>{if(g&&typeof g==\"object\"||typeof g==\"function\")for(let v of W(g))!V.call(p,v)&&v!==S&&A(p,v,{get:()=>g[v],enumerable:!(P=$(g,v))||P.enumerable});return p};var G=p=>z(A({},\"__esModule\",{value:!0}),p);var Q={};j(Q,{createFilePeerRuntime:()=>H});function Y(p){return Number.isSafeInteger(p)&&p>15e3?Math.min(p,60*6e4):15e3}function H(p){let g=new Map,S=16384,P=2147483648,v=new Map;function D(t,d){let s=new Map,e=new Map,c=0,n=0,f=(i,r,l)=>{if(l.length>4*1024*1024||d.readyState!==\"open\")throw new Error(\"FILE_PEER_RPC_SIZE\");for(let o=0;o<Math.max(1,l.length);o+=16384)d.send(JSON.stringify({key:i,response:r,data:l.slice(o,o+16384),last:o+16384>=l.length}))},m=()=>{for(let i of s.values())clearTimeout(i.timer),i.reject(new Error(\"FILE_PEER_CLOSED\"));for(let i of e.values())clearTimeout(i.timer);s.clear(),e.clear(),d.close()};d.onclose=m,d.onmessage=({data:i})=>{try{if(typeof i!=\"string\"||i.length>1e5)throw new Error;let r=JSON.parse(i);if(typeof r.key!=\"string\"||!/^\\d{1,12}$/.test(r.key)||typeof r.response!=\"boolean\"||typeof r.last!=\"boolean\"||typeof r.data!=\"string\"||r.data.length>16384)throw new Error;if(r.response&&!s.has(r.key))return;let l=`${r.response}:${r.key}`,o=e.get(l);if(!o){if(e.size>=8)throw new Error;o={data:\"\",timer:setTimeout(()=>R(t),15e3)},e.set(l,o)}if(o.data+=r.data,o.data.length>4*1024*1024)throw new Error;if(!r.last)return;if(clearTimeout(o.timer),e.delete(l),r.response){let w=s.get(r.key);s.delete(r.key),clearTimeout(w.timer),w.resolve(o.data)}else{if(!p.invoke||n>=4)throw new Error;n++,p.invoke(t,o.data).then(w=>{g.has(t)&&f(r.key,!0,w)}).catch(()=>R(t)).finally(()=>{n--})}}catch{R(t)}},v.set(t,{channel:d,close:m,request(i,r){return s.size>=4||d.readyState!==\"open\"?Promise.reject(new Error(\"FILE_PEER_UNAVAILABLE\")):new Promise((l,o)=>{let w=String(++c),y=setTimeout(()=>{s.delete(w),o(new Error(\"FILE_PEER_TIMEOUT\"))},Y(r));s.set(w,{resolve:l,reject:o,timer:y});try{f(w,!1,i)}catch(u){s.delete(w),clearTimeout(y),o(u)}})}})}function R(t){let d=v.get(t);v.delete(t),d?.close();let s=g.get(t);g.delete(t),s?.dc?.close(),s?.pc.close()}function O(t,d){if(g.has(t)||g.size>=4)throw new Error(\"FILE_PEER_BUSY\");let s=new RTCPeerConnection({iceServers:d}),e={pc:s,dc:null,busy:!1};return g.set(t,e),s.onconnectionstatechange=()=>{[\"failed\",\"closed\",\"disconnected\"].includes(s.connectionState)&&R(t)},e}async function F(t,d){if(await t.setLocalDescription(d),t.iceGatheringState!==\"complete\"&&await new Promise(s=>{let e=setTimeout(c,4e3);function c(){clearTimeout(e),t.removeEventListener(\"icegatheringstatechange\",n),s()}function n(){t.iceGatheringState===\"complete\"&&c()}t.addEventListener(\"icegatheringstatechange\",n),n()}),!t.localDescription?.sdp||t.signalingState===\"closed\")throw new Error(\"FILE_PEER_CLOSED\");return t.localDescription.sdp}function x(t){if(t.length>22e3||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t))throw new Error(\"FILE_PEER_BLOCK\");let d=atob(t);if(d.length>S)throw new Error(\"FILE_PEER_BLOCK\");return Uint8Array.from(d,s=>s.charCodeAt(0))}async function U(t,d,s=!1){let e=O(t,d);e.dc=e.pc.createDataChannel(s?\"files-v2\":\"files-v1\",{ordered:!0}),e.dc.binaryType=\"arraybuffer\",s&&D(t,e.pc.createDataChannel(\"reads-v1\",{ordered:!0}));try{return await F(e.pc,await e.pc.createOffer())}catch(c){throw R(t),c}}async function J(t,d,s){let e=O(t,d);e.pc.ondatachannel=({channel:c})=>{if(c.label===\"reads-v1\"&&!v.has(t)){D(t,c);return}if(![\"files-v1\",\"files-v2\"].includes(c.label)||e.dc){c.close();return}if(e.dc=c,c.binaryType=\"arraybuffer\",c.label===\"files-v2\"){let n,f=!1,m=async()=>{if(!f){f=!0;try{for(;n&&n.credit>0;){let i=n;i.credit--;let r=Date.now(),l=x(await p.read(t,i.ticket,i.offset));if(g.get(t)!==e||c.readyState!==\"open\")return;if(c.send(l.buffer),i.offset+=l.length,e.send){let o=Date.now()-r;e.send.reads++,e.send.readMs+=o,e.send.readMaxMs=Math.max(e.send.readMaxMs,o),e.send.sent=i.offset,e.send.credit=i.credit}l.length||(n=void 0)}n&&e.send&&e.send.waitingSince===null&&(e.send.waitingSince=Date.now())}catch{R(t)}finally{f=!1}}};c.onmessage=({data:i})=>{try{if(typeof i!=\"string\"||i.length>256)throw new Error;let r=JSON.parse(i);if(!Number.isSafeInteger(r.credit)||r.credit<1||r.credit>64)throw new Error;if(r.ticket!==void 0){if(n||!/^[a-f0-9-]{36}$/.test(r.ticket)||r.offset!==0)throw new Error;n={ticket:r.ticket,offset:0,credit:r.credit},e.send={startedAt:Date.now(),sent:0,credit:r.credit,reads:0,readMs:0,readMaxMs:0,creditWaitMs:0,waitingSince:null}}else{if(!n||n.credit+r.credit>64)throw new Error;n.credit+=r.credit,e.send&&(e.send.credit=n.credit,e.send.waitingSince!==null&&(e.send.creditWaitMs+=Date.now()-e.send.waitingSince,e.send.waitingSince=null))}m()}catch{R(t)}};return}c.onmessage=async({data:n})=>{try{if(g.get(t)!==e||e.busy||typeof n!=\"string\"||n.length>256)throw new Error(\"FILE_PEER_BLOCK\");let f=JSON.parse(n);if(!/^[a-f0-9-]{36}$/.test(f.ticket)||!Number.isSafeInteger(f.offset)||f.offset<0||f.offset>P||f.credit!==16)throw new Error(\"FILE_PEER_BLOCK\");e.busy=!0;let m=f.offset;for(let i=0;i<16;i++){let r=x(await p.read(t,f.ticket,m));if(g.get(t)!==e||c.readyState!==\"open\")return;if(c.send(r.buffer),m+=r.length,!r.length)break}}catch{R(t)}finally{e.busy=!1}}};try{return await e.pc.setRemoteDescription({type:\"offer\",sdp:s}),await F(e.pc,await e.pc.createAnswer())}catch(c){throw R(t),c}}async function K(t,d){let s=g.get(t);if(!s)throw new Error(\"FILE_PEER_CLOSED\");await s.pc.setRemoteDescription({type:\"answer\",sdp:d}),await Promise.all([s.dc,v.get(t)?.channel].filter(e=>!!e).map(e=>new Promise((c,n)=>{let f=setTimeout(()=>m(new Error(\"FILE_PEER_TIMEOUT\")),8e3);function m(l){clearTimeout(f),e.removeEventListener(\"open\",i),e.removeEventListener(\"close\",r),l?n(l):c()}function i(){m()}function r(){m(new Error(\"FILE_PEER_CLOSED\"))}e.addEventListener(\"open\",i),e.addEventListener(\"close\",r),e.readyState===\"open\"?m():e.readyState===\"closed\"&&r()})))}async function Z(t,d,s,e){let c=g.get(t),n=c?.dc;if(!c||!n||n.readyState!==\"open\"||c.busy||!Number.isSafeInteger(s)||s<0||s>P)throw new Error(\"FILE_PEER_UNAVAILABLE\");c.busy=!0;try{if(n.label===\"files-v2\"){await new Promise((m,i)=>{let r=0,l=0,o=0,w=0,y=Math.ceil(s/S)+1,u=Math.min(64,y),h=!1,a=!1,M=Promise.resolve(),E={size:s,startedAt:Date.now(),received:0,written:0,queued:0,queuedMax:0,granted:u,writes:0,writeMs:0,writeMaxMs:0,lastDataAt:0};c.recv=E;let L=setTimeout(()=>b(new Error(\"FILE_PEER_TIMEOUT\")),6e4);function b(I){a||(a=!0,clearTimeout(L),n.removeEventListener(\"message\",q),n.removeEventListener(\"close\",C),I?i(I):m())}function C(){b(new Error(\"FILE_PEER_CLOSED\"))}function q(I){if(h||!(I.data instanceof ArrayBuffer)||++o>64){b(new Error(\"FILE_PEER_BLOCK\"));return}let T=new Uint8Array(I.data);if(T.length!==Math.min(S,s-r)){b(new Error(\"FILE_PEER_SIZE\"));return}r+=T.length,h=T.length===0,E.received=r,E.queued=o,E.queuedMax=Math.max(E.queuedMax,o),E.lastDataAt=Date.now(),M=M.then(async()=>{if(a)return;if(!T.length){o--,E.queued=o,b();return}let k=Date.now(),B=\"\";for(let _ of T)B+=String.fromCharCode(_);if(await p.write(e,l,btoa(B)),a)return;if(g.get(t)!==c)throw new Error(\"FILE_PEER_CLOSED\");l+=T.length,o--;let N=Date.now()-k;if(E.writes++,E.writeMs+=N,E.writeMaxMs=Math.max(E.writeMaxMs,N),E.written=l,E.queued=o,clearTimeout(L),L=setTimeout(()=>b(new Error(\"FILE_PEER_TIMEOUT\")),6e4),++w===32&&u<y){let _=Math.min(32,y-u);n.send(JSON.stringify({credit:_})),u+=_,E.granted=u,w=0}}).catch(k=>b(k))}n.addEventListener(\"message\",q),n.addEventListener(\"close\",C);try{n.send(JSON.stringify({ticket:d,offset:0,credit:u}))}catch{C()}});return}let f=0;for(;f<=s;){let m=await new Promise((i,r)=>{let l=[],o=f,w=setTimeout(()=>y(new Error(\"FILE_PEER_TIMEOUT\")),6e4);function y(a){clearTimeout(w),n.removeEventListener(\"message\",h),n.removeEventListener(\"close\",u),a?r(a):i(l)}function u(){y(new Error(\"FILE_PEER_CLOSED\"))}function h(a){if(!(a.data instanceof ArrayBuffer)){y(new Error(\"FILE_PEER_BLOCK\"));return}let M=new Uint8Array(a.data);if(M.length!==Math.min(S,s-o)){y(new Error(\"FILE_PEER_SIZE\"));return}l.push(M),o+=M.length,(!M.length||l.length===16)&&y()}n.addEventListener(\"message\",h),n.addEventListener(\"close\",u);try{n.send(JSON.stringify({ticket:d,offset:f,credit:16}))}catch{u()}});for(let i of m){if(!i.length)return;let r=\"\";for(let l of i)r+=String.fromCharCode(l);if(await p.write(e,f,btoa(r)),g.get(t)!==c)throw new Error(\"FILE_PEER_CLOSED\");f+=i.length}}}catch(f){throw R(t),f}finally{c.busy=!1}}return{async invoke(t,d,s){let e=v.get(t);if(!e)throw new Error(\"FILE_PEER_UNAVAILABLE\");return e.request(d,s)},async stats(t){let d=g.get(t);if(!d)throw new Error(\"FILE_PEER_CLOSED\");let s=await d.pc.getStats(),e=new Map;s.forEach(a=>e.set(a.id,a));let c;s.forEach(a=>{a.type===\"transport\"&&a.selectedCandidatePairId&&(c=e.get(a.selectedCandidatePairId))});let n=c,f=n?.localCandidateId?e.get(n.localCandidateId):void 0,m=n?.remoteCandidateId?e.get(n.remoteCandidateId):void 0,i=(a,M)=>{if(!a)return;let E={};for(let L of M){let b=a[L];typeof b==\"number\"&&Number.isFinite(b)?E[L]=Math.round(b):typeof b==\"string\"&&b.length<=32&&(E[L]=b)}return Object.keys(E).length?E:void 0},r,l,o=(a,M)=>{let E=typeof M==\"string\"&&M.length<=16?M:\"other\";a[E]=(a[E]??0)+1},w={local:{},remote:{},pairs:{},localRelay:{}};s.forEach(a=>{a.type===\"transport\"&&a.selectedCandidatePairId&&(r=a),a.type===\"data-channel\"&&a.label===d.dc?.label&&(l=a),a.type===\"local-candidate\"&&(o(w.local,a.candidateType),a.candidateType===\"relay\"&&o(w.localRelay,a.relayProtocol)),a.type===\"remote-candidate\"&&o(w.remote,a.candidateType),a.type===\"candidate-pair\"&&o(w.pairs,a.state)});let y=Date.now(),u=d.recv,h=d.send;return JSON.stringify({path:n?f?.candidateType===\"relay\"||m?.candidateType===\"relay\"?\"relay\":\"direct\":\"unknown\",protocol:f?.protocol??\"unknown\",rttMs:typeof n?.currentRoundTripTime==\"number\"?Math.round(n.currentRoundTripTime*1e3):null,streaming:d.dc?.label===\"files-v2\",local:i(f,[\"candidateType\",\"protocol\",\"relayProtocol\",\"networkType\"]),remote:i(m,[\"candidateType\",\"protocol\"]),candidates:w,pair:i(n,[\"state\",\"bytesSent\",\"bytesReceived\",\"packetsSent\",\"packetsReceived\",\"packetsDiscardedOnSend\",\"availableOutgoingBitrate\",\"availableIncomingBitrate\",\"requestsSent\",\"responsesReceived\",\"consentRequestsSent\"]),transport:i(r,[\"dtlsState\",\"bytesSent\",\"bytesReceived\",\"packetsSent\",\"packetsReceived\",\"selectedCandidatePairChanges\"]),channel:{...i(l,[\"messagesSent\",\"bytesSent\",\"messagesReceived\",\"bytesReceived\"]),bufferedAmount:d.dc?.bufferedAmount},receive:u&&{size:u.size,elapsedMs:y-u.startedAt,received:u.received,written:u.written,queued:u.queued,queuedMax:u.queuedMax,granted:u.granted,writes:u.writes,writeAvgMs:u.writes?Math.round(u.writeMs/u.writes):null,writeMaxMs:u.writeMaxMs,idleMs:u.lastDataAt?y-u.lastDataAt:null},send:h&&{elapsedMs:y-h.startedAt,sent:h.sent,credit:h.credit,reads:h.reads,readAvgMs:h.reads?Math.round(h.readMs/h.reads):null,readMaxMs:h.readMaxMs,creditWaitMs:h.creditWaitMs+(h.waitingSince===null?0:y-h.waitingSince)}})},offer:U,accept:J,answer:K,receive:Z,close:R,dispose:()=>{for(let t of g.keys())R(t)}}}return G(Q);})();\n";+export const FILE_PEER_RUNTIME_SOURCE = "\"use strict\";var CindyFilePeerRuntime=(()=>{var k=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var K=Object.getOwnPropertyNames;var z=Object.prototype.hasOwnProperty;var W=(b,w)=>{for(var T in w)k(b,T,{get:w[T],enumerable:!0})},X=(b,w,T,P)=>{if(w&&typeof w==\"object\"||typeof w==\"function\")for(let S of K(w))!z.call(b,S)&&S!==T&&k(b,S,{get:()=>w[S],enumerable:!(P=$(w,S))||P.enumerable});return b};var V=b=>X(k({},\"__esModule\",{value:!0}),b);var Q={};W(Q,{RPC_BODY_MAX_BYTES:()=>j,createFilePeerRuntime:()=>H});var j=1048576;function G(b){return Number.isSafeInteger(b)&&b>15e3?Math.min(b,60*6e4):15e3}function H(b){let w=new Map,T=16384,P=2147483648,S=new Map;function D(t,d){d.binaryType=\"arraybuffer\";let a=new Map,e=new Map,o,s=15e3,E=0,h=0,l=(g,n,c,i)=>{if(c.length>4*1024*1024||i&&(!i.length||i.length>1048576)||d.readyState!==\"open\")throw new Error(\"FILE_PEER_RPC_SIZE\");for(let r=0;r<Math.max(1,c.length);r+=16384){let m=r+16384>=c.length;d.send(JSON.stringify({key:g,response:n,data:c.slice(r,r+16384),last:m,...m&&i?{body:i.length}:{}}))}if(i)for(let r=0;r<i.length;r+=16384)d.send(i.slice(r,r+16384))},f=(g,n,c)=>{if(!b.invoke||h>=4)throw new Error;h++,b.invoke(t,n,c).then(i=>{w.has(t)&&l(g,!0,i)}).catch(()=>M(t)).finally(()=>{h--})},p=g=>{let n=o?e.get(o):void 0;if(!n?.body||!(g instanceof ArrayBuffer))throw new Error;let c=new Uint8Array(g);if(c.length!==Math.min(16384,n.body.remaining))throw new Error;if(n.body.parts.push(c),n.body.remaining-=c.length,clearTimeout(n.timer),n.body.remaining){n.timer=setTimeout(()=>M(t),s);return}let i=o;o=void 0,e.delete(i);let r=new Uint8Array(n.body.parts.reduce((u,v)=>u+v.length,0)),m=0;for(let u of n.body.parts)r.set(u,m),m+=u.length;f(i.slice(6),n.data,r)},y=()=>{for(let g of a.values())clearTimeout(g.timer),g.reject(new Error(\"FILE_PEER_CLOSED\"));for(let g of e.values())clearTimeout(g.timer);a.clear(),e.clear(),d.close()};d.onclose=y,d.onmessage=({data:g})=>{try{if(o!==void 0)return p(g);if(typeof g!=\"string\"||g.length>1e5)throw new Error;let n=JSON.parse(g);if(typeof n.key!=\"string\"||!/^\\d{1,12}$/.test(n.key)||typeof n.response!=\"boolean\"||typeof n.last!=\"boolean\"||typeof n.data!=\"string\"||n.data.length>16384||n.body!==void 0&&(n.response||!n.last||!Number.isSafeInteger(n.body)||n.body<1||n.body>1048576))throw new Error;if(n.response&&!a.has(n.key))return;let c=`${n.response}:${n.key}`,i=e.get(c);if(!i){if(e.size>=8)throw new Error;i={data:\"\",timer:setTimeout(()=>M(t),s)},e.set(c,i)}if(i.data+=n.data,i.data.length>4*1024*1024)throw new Error;if(!n.last)return;if(n.body!==void 0){clearTimeout(i.timer),i.timer=setTimeout(()=>M(t),s),i.body={remaining:n.body,parts:[]},o=c;return}if(clearTimeout(i.timer),e.delete(c),n.response){let r=a.get(n.key);a.delete(n.key),clearTimeout(r.timer),r.resolve(i.data)}else f(n.key,i.data)}catch{M(t)}},S.set(t,{channel:d,close:y,request(g,n,c){return a.size>=4||d.readyState!==\"open\"?Promise.reject(new Error(\"FILE_PEER_UNAVAILABLE\")):new Promise((i,r)=>{let m=String(++E),u=setTimeout(()=>{a.delete(m),r(new Error(\"FILE_PEER_TIMEOUT\"))},G(n));a.set(m,{resolve:i,reject:r,timer:u});try{l(m,!1,g,c)}catch(v){a.delete(m),clearTimeout(u),r(v)}})}})}function M(t){let d=S.get(t);S.delete(t),d?.close();let a=w.get(t);w.delete(t),a?.dc?.close(),a?.pc.close()}function O(t,d){if(w.has(t)||w.size>=4)throw new Error(\"FILE_PEER_BUSY\");let a=new RTCPeerConnection({iceServers:d}),e={pc:a,dc:null,busy:!1};return w.set(t,e),a.onconnectionstatechange=()=>{[\"failed\",\"closed\",\"disconnected\"].includes(a.connectionState)&&M(t)},e}async function F(t,d){if(await t.setLocalDescription(d),t.iceGatheringState!==\"complete\"&&await new Promise(a=>{let e=setTimeout(o,4e3);function o(){clearTimeout(e),t.removeEventListener(\"icegatheringstatechange\",s),a()}function s(){t.iceGatheringState===\"complete\"&&o()}t.addEventListener(\"icegatheringstatechange\",s),s()}),!t.localDescription?.sdp||t.signalingState===\"closed\")throw new Error(\"FILE_PEER_CLOSED\");return t.localDescription.sdp}function B(t){if(t.length>22e3||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t))throw new Error(\"FILE_PEER_BLOCK\");let d=atob(t);if(d.length>T)throw new Error(\"FILE_PEER_BLOCK\");return Uint8Array.from(d,a=>a.charCodeAt(0))}async function N(t,d,a=!1){let e=O(t,d);e.dc=e.pc.createDataChannel(a?\"files-v2\":\"files-v1\",{ordered:!0}),e.dc.binaryType=\"arraybuffer\",a&&D(t,e.pc.createDataChannel(\"reads-v1\",{ordered:!0}));try{return await F(e.pc,await e.pc.createOffer())}catch(o){throw M(t),o}}async function Z(t,d,a){let e=O(t,d);e.pc.ondatachannel=({channel:o})=>{if(o.label===\"reads-v1\"&&!S.has(t)){D(t,o);return}if(![\"files-v1\",\"files-v2\"].includes(o.label)||e.dc){o.close();return}if(e.dc=o,o.binaryType=\"arraybuffer\",o.label===\"files-v2\"){let s,E=!1,h=async()=>{if(!E){E=!0;try{for(;s&&s.credit>0;){let l=s;l.credit--;let f=Date.now(),p=B(await b.read(t,l.ticket,l.offset));if(w.get(t)!==e||o.readyState!==\"open\")return;if(o.send(p.buffer),l.offset+=p.length,e.send){let y=Date.now()-f;e.send.reads++,e.send.readMs+=y,e.send.readMaxMs=Math.max(e.send.readMaxMs,y),e.send.sent=l.offset,e.send.credit=l.credit}p.length||(s=void 0)}s&&e.send&&e.send.waitingSince===null&&(e.send.waitingSince=Date.now())}catch{M(t)}finally{E=!1}}};o.onmessage=({data:l})=>{try{if(typeof l!=\"string\"||l.length>256)throw new Error;let f=JSON.parse(l);if(!Number.isSafeInteger(f.credit)||f.credit<1||f.credit>64)throw new Error;if(f.ticket!==void 0){if(s||!/^[a-f0-9-]{36}$/.test(f.ticket)||f.offset!==0)throw new Error;s={ticket:f.ticket,offset:0,credit:f.credit},e.send={startedAt:Date.now(),sent:0,credit:f.credit,reads:0,readMs:0,readMaxMs:0,creditWaitMs:0,waitingSince:null}}else{if(!s||s.credit+f.credit>64)throw new Error;s.credit+=f.credit,e.send&&(e.send.credit=s.credit,e.send.waitingSince!==null&&(e.send.creditWaitMs+=Date.now()-e.send.waitingSince,e.send.waitingSince=null))}h()}catch{M(t)}};return}o.onmessage=async({data:s})=>{try{if(w.get(t)!==e||e.busy||typeof s!=\"string\"||s.length>256)throw new Error(\"FILE_PEER_BLOCK\");let E=JSON.parse(s);if(!/^[a-f0-9-]{36}$/.test(E.ticket)||!Number.isSafeInteger(E.offset)||E.offset<0||E.offset>P||E.credit!==16)throw new Error(\"FILE_PEER_BLOCK\");e.busy=!0;let h=E.offset;for(let l=0;l<16;l++){let f=B(await b.read(t,E.ticket,h));if(w.get(t)!==e||o.readyState!==\"open\")return;if(o.send(f.buffer),h+=f.length,!f.length)break}}catch{M(t)}finally{e.busy=!1}}};try{return await e.pc.setRemoteDescription({type:\"offer\",sdp:a}),await F(e.pc,await e.pc.createAnswer())}catch(o){throw M(t),o}}async function Y(t,d){let a=w.get(t);if(!a)throw new Error(\"FILE_PEER_CLOSED\");await a.pc.setRemoteDescription({type:\"answer\",sdp:d}),await Promise.all([a.dc,S.get(t)?.channel].filter(e=>!!e).map(e=>new Promise((o,s)=>{let E=setTimeout(()=>h(new Error(\"FILE_PEER_TIMEOUT\")),8e3);function h(p){clearTimeout(E),e.removeEventListener(\"open\",l),e.removeEventListener(\"close\",f),p?s(p):o()}function l(){h()}function f(){h(new Error(\"FILE_PEER_CLOSED\"))}e.addEventListener(\"open\",l),e.addEventListener(\"close\",f),e.readyState===\"open\"?h():e.readyState===\"closed\"&&f()})))}async function J(t,d,a,e){let o=w.get(t),s=o?.dc;if(!o||!s||s.readyState!==\"open\"||o.busy||!Number.isSafeInteger(a)||a<0||a>P)throw new Error(\"FILE_PEER_UNAVAILABLE\");o.busy=!0;try{if(s.label===\"files-v2\"){await new Promise((h,l)=>{let f=0,p=0,y=0,g=0,n=Math.ceil(a/T)+1,c=Math.min(64,n),i=!1,r=!1,m=Promise.resolve(),u={size:a,startedAt:Date.now(),received:0,written:0,queued:0,queuedMax:0,granted:c,writes:0,writeMs:0,writeMaxMs:0,lastDataAt:0};o.recv=u;let v=setTimeout(()=>R(new Error(\"FILE_PEER_TIMEOUT\")),6e4);function R(L){r||(r=!0,clearTimeout(v),s.removeEventListener(\"message\",x),s.removeEventListener(\"close\",I),L?l(L):h())}function I(){R(new Error(\"FILE_PEER_CLOSED\"))}function x(L){if(i||!(L.data instanceof ArrayBuffer)||++y>64){R(new Error(\"FILE_PEER_BLOCK\"));return}let _=new Uint8Array(L.data);if(_.length!==Math.min(T,a-f)){R(new Error(\"FILE_PEER_SIZE\"));return}f+=_.length,i=_.length===0,u.received=f,u.queued=y,u.queuedMax=Math.max(u.queuedMax,y),u.lastDataAt=Date.now(),m=m.then(async()=>{if(r)return;if(!_.length){y--,u.queued=y,R();return}let A=Date.now(),q=\"\";for(let C of _)q+=String.fromCharCode(C);if(await b.write(e,p,btoa(q)),r)return;if(w.get(t)!==o)throw new Error(\"FILE_PEER_CLOSED\");p+=_.length,y--;let U=Date.now()-A;if(u.writes++,u.writeMs+=U,u.writeMaxMs=Math.max(u.writeMaxMs,U),u.written=p,u.queued=y,clearTimeout(v),v=setTimeout(()=>R(new Error(\"FILE_PEER_TIMEOUT\")),6e4),++g===32&&c<n){let C=Math.min(32,n-c);s.send(JSON.stringify({credit:C})),c+=C,u.granted=c,g=0}}).catch(A=>R(A))}s.addEventListener(\"message\",x),s.addEventListener(\"close\",I);try{s.send(JSON.stringify({ticket:d,offset:0,credit:c}))}catch{I()}});return}let E=0;for(;E<=a;){let h=await new Promise((l,f)=>{let p=[],y=E,g=setTimeout(()=>n(new Error(\"FILE_PEER_TIMEOUT\")),6e4);function n(r){clearTimeout(g),s.removeEventListener(\"message\",i),s.removeEventListener(\"close\",c),r?f(r):l(p)}function c(){n(new Error(\"FILE_PEER_CLOSED\"))}function i(r){if(!(r.data instanceof ArrayBuffer)){n(new Error(\"FILE_PEER_BLOCK\"));return}let m=new Uint8Array(r.data);if(m.length!==Math.min(T,a-y)){n(new Error(\"FILE_PEER_SIZE\"));return}p.push(m),y+=m.length,(!m.length||p.length===16)&&n()}s.addEventListener(\"message\",i),s.addEventListener(\"close\",c);try{s.send(JSON.stringify({ticket:d,offset:E,credit:16}))}catch{c()}});for(let l of h){if(!l.length)return;let f=\"\";for(let p of l)f+=String.fromCharCode(p);if(await b.write(e,E,btoa(f)),w.get(t)!==o)throw new Error(\"FILE_PEER_CLOSED\");E+=l.length}}}catch(E){throw M(t),E}finally{o.busy=!1}}return{async invoke(t,d,a,e){let o=S.get(t);if(!o)throw new Error(\"FILE_PEER_UNAVAILABLE\");if(e===void 0)return o.request(d,a);if(typeof e!=\"string\"||e.length>Math.ceil(1048576/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw new Error(\"FILE_PEER_RPC_SIZE\");return o.request(d,a,Uint8Array.from(atob(e),s=>s.charCodeAt(0)))},async stats(t){let d=w.get(t);if(!d)throw new Error(\"FILE_PEER_CLOSED\");let a=await d.pc.getStats(),e=new Map;a.forEach(r=>e.set(r.id,r));let o;a.forEach(r=>{r.type===\"transport\"&&r.selectedCandidatePairId&&(o=e.get(r.selectedCandidatePairId))});let s=o,E=s?.localCandidateId?e.get(s.localCandidateId):void 0,h=s?.remoteCandidateId?e.get(s.remoteCandidateId):void 0,l=(r,m)=>{if(!r)return;let u={};for(let v of m){let R=r[v];typeof R==\"number\"&&Number.isFinite(R)?u[v]=Math.round(R):typeof R==\"string\"&&R.length<=32&&(u[v]=R)}return Object.keys(u).length?u:void 0},f,p,y=(r,m)=>{let u=typeof m==\"string\"&&m.length<=16?m:\"other\";r[u]=(r[u]??0)+1},g={local:{},remote:{},pairs:{},localRelay:{}};a.forEach(r=>{r.type===\"transport\"&&r.selectedCandidatePairId&&(f=r),r.type===\"data-channel\"&&r.label===d.dc?.label&&(p=r),r.type===\"local-candidate\"&&(y(g.local,r.candidateType),r.candidateType===\"relay\"&&y(g.localRelay,r.relayProtocol)),r.type===\"remote-candidate\"&&y(g.remote,r.candidateType),r.type===\"candidate-pair\"&&y(g.pairs,r.state)});let n=Date.now(),c=d.recv,i=d.send;return JSON.stringify({path:s?E?.candidateType===\"relay\"||h?.candidateType===\"relay\"?\"relay\":\"direct\":\"unknown\",protocol:E?.protocol??\"unknown\",rttMs:typeof s?.currentRoundTripTime==\"number\"?Math.round(s.currentRoundTripTime*1e3):null,streaming:d.dc?.label===\"files-v2\",local:l(E,[\"candidateType\",\"protocol\",\"relayProtocol\",\"networkType\"]),remote:l(h,[\"candidateType\",\"protocol\"]),candidates:g,pair:l(s,[\"state\",\"bytesSent\",\"bytesReceived\",\"packetsSent\",\"packetsReceived\",\"packetsDiscardedOnSend\",\"availableOutgoingBitrate\",\"availableIncomingBitrate\",\"requestsSent\",\"responsesReceived\",\"consentRequestsSent\"]),transport:l(f,[\"dtlsState\",\"bytesSent\",\"bytesReceived\",\"packetsSent\",\"packetsReceived\",\"selectedCandidatePairChanges\"]),channel:{...l(p,[\"messagesSent\",\"bytesSent\",\"messagesReceived\",\"bytesReceived\"]),bufferedAmount:d.dc?.bufferedAmount},receive:c&&{size:c.size,elapsedMs:n-c.startedAt,received:c.received,written:c.written,queued:c.queued,queuedMax:c.queuedMax,granted:c.granted,writes:c.writes,writeAvgMs:c.writes?Math.round(c.writeMs/c.writes):null,writeMaxMs:c.writeMaxMs,idleMs:c.lastDataAt?n-c.lastDataAt:null},send:i&&{elapsedMs:n-i.startedAt,sent:i.sent,credit:i.credit,reads:i.reads,readAvgMs:i.reads?Math.round(i.readMs/i.reads):null,readMaxMs:i.readMaxMs,creditWaitMs:i.creditWaitMs+(i.waitingSince===null?0:n-i.waitingSince)}})},offer:N,accept:Z,answer:Y,receive:J,close:M,dispose:()=>{for(let t of w.keys())M(t)}}}return V(Q);})();\n";diff --git a/packages/device-link/src/peerAttachment.ts b/packages/device-link/src/peerAttachment.tsindex 03041320b1..1901a22514 100644--- a/packages/device-link/src/peerAttachment.ts+++ b/packages/device-link/src/peerAttachment.ts@@ -71,16 +71,28 @@ export function peerAttachmentFinishTimeoutMs(size: number): number {return 15_000 + Math.ceil(Math.max(0, size) / (20 * 1024 ** 2)) * 1000;}-/** A failed upload is abandoned before sending the message; callers then upload through OSS. */+/**+ * 对端声明 `caps.streamAttachments` 时,同时在途的写入块数。块按发送顺序在接收端逐个落盘;+ * 文件通道每端最多 4 个在途请求,留 1 个给同一连接上的远程读取。+ */+export const PEER_ATTACHMENT_STREAM_WINDOW = 3;++/**+ * A failed upload is abandoned before sending the message; callers then upload through OSS.+ * `stream` (peer advertised `caps.streamAttachments`) keeps several writes in flight and passes+ * each block as the RPC binary body instead of a base64 field.+ */export async function uploadPeerAttachment(metadata: Omit<PeerAttachment, "ticket">,read: (offset: number, length: number) => Promise<string>,invoke: (request: Record<string, unknown>,timeoutMs?: number,+ body?: string,) => Promise<unknown>,check: () => void,onProgress?: (bytes: number) => void,+ stream = false,): Promise<string> {check();const { ticket } = (await invoke({ op: "begin", ...metadata })) as {@@ -88,17 +100,39 @@ export async function uploadPeerAttachment(};if (typeof ticket !== "string" || !/^[a-f0-9-]{36}$/.test(ticket))throw new Error("INVALID_PEER_ATTACHMENT");+ const window = stream ? PEER_ATTACHMENT_STREAM_WINDOW : 1;+ // A queued block waits behind the others on the wire, so its deadline covers the whole window.+ // The receiver only drops a body that stalls, so it never cuts a block off before this deadline.+ const writeTimeoutMs = stream ? 15_000 * window : undefined;+ const inFlight: Promise<number>[] = [];+ let failed = false;+ // Not `onProgress?.(await …)`: optional call skips its argument, which would never dequeue.+ const settleOldest = async () => {+ const end = await inFlight.shift()!;+ onProgress?.(end);+ };try {for (let offset = 0; offset < metadata.size; offset += 1024 * 1024) {check();- const data = await read(- offset,- Math.min(1024 * 1024, metadata.size - offset),- );+ const end = Math.min(offset + 1024 * 1024, metadata.size);+ const data = await read(offset, end - offset);check();- await invoke({ op: "write", ticket, offset, data });- onProgress?.(Math.min(offset + 1024 * 1024, metadata.size));+ // Awaiting in send order reports progress monotonically; once any block failed, stop+ // sending and drain until that failure surfaces.+ while (inFlight.length >= window || (failed && inFlight.length))+ await settleOldest();+ const write = (+ stream+ ? invoke({ op: "write", ticket, offset }, writeTimeoutMs, data)+ : invoke({ op: "write", ticket, offset, data })+ ).then(() => end);+ // A later block may fail before earlier ones settle; record it instead of leaving it unhandled.+ write.catch(() => {+ failed = true;+ });+ inFlight.push(write);}+ while (inFlight.length) await settleOldest();check();await invoke({ op: "finish", ticket },diff --git a/scripts/file-peer-smoke.mjs b/scripts/file-peer-smoke.mjsindex 6413fcd63f..88f78dfcca 100644--- a/scripts/file-peer-smoke.mjs+++ b/scripts/file-peer-smoke.mjs@@ -51,7 +51,15 @@ try {failWrite = false;const ticket = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";const host = createFilePeerRuntime({- invoke: async (_id, value) => value,+ // Body requests echo a digest of the raw bytes so the client can verify them.+ invoke: async (_id, value, body) =>+ body+ ? JSON.stringify({+ value,+ length: body.length,+ digest: body.reduce((sum, byte) => (sum * 31 + byte) >>> 0, 0),+ })+ : value,read: async (_id, t, offset) => {if (benchmark) await new Promise(resolve => setTimeout(resolve, 1));if (t !== ticket || offset !== sourceOffset)@@ -97,6 +105,29 @@ try {);if (replies.join("") !== "abcd")throw new Error("RPC correlation failed");+ // Binary request bodies around the 16 KiB frame boundary, up to the 1 MiB block.+ const withBody = (value, length) => {+ const bytes = Uint8Array.from({ length }, (_, i) => (i * 7 + length) % 256);+ let binary = "";+ for (const byte of bytes) binary += String.fromCharCode(byte);+ const digest = bytes.reduce((sum, byte) => (sum * 31 + byte) >>> 0, 0);+ return client+ .invoke("client", value, undefined, btoa(binary))+ .then((reply) => {+ const r = JSON.parse(reply);+ if (r.value !== value || r.length !== length || r.digest !== digest)+ throw new Error("RPC body differs");+ });+ };+ for (const length of [1, 16384, 16385, 1048576]) await withBody("body", length);+ // Three bodies in flight beside a plain request stay correlated.+ const [, plain] = await Promise.all([+ withBody("first", 1048576),+ client.invoke("client", "plain"),+ withBody("second", 300000),+ withBody("third", 1048576),+ ]);+ if (plain !== "plain") throw new Error("RPC correlation with bodies failed");const stats = JSON.parse(await client.stats("client"));if (stats.path !== expectedPath || !stats.streaming)throw new Error("selected path missing");