Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(mobile): 聊天附件不限类型与大小,直连附件去掉固定上限 (#5281)

Dash04e22d1ed86d
diff --git a/apps/desktop/src/capture-renderer/filePeerHost.ts b/apps/desktop/src/capture-renderer/filePeerHost.ts
index c952e78462..e7828ea8c7 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);
+ result = await runtime.invoke(c.connection, c.payload, c.timeoutMs);
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.ts
index 440241e985..08939177d1 100644
--- a/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts
@@ -22,6 +22,10 @@ vi.mock('@cindy/device-link', async (importOriginal) => {
actual.createPeerTransferCooldown(() => mock.now ?? Date.now()),
};
});
+vi.mock('node:crypto', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('node:crypto')>();
+ return { ...actual, createHash: vi.fn(actual.createHash) };
+});
vi.mock('electron', () => ({
ipcMain: { handle: (key: string, fn: (...args: any[]) => any) => mock.handlers.set(key, fn) },
app: { on: vi.fn(), getPath: () => os.tmpdir() },
@@ -67,7 +71,30 @@ import {
stopFilePeers,
tryPeerInvoke,
tryPeerFile,
+ tryUploadPeerAttachment,
} from '../filePeer';
+import { createHash } from 'node:crypto';
+
+describe('peer attachment upload preflight', () => {
+ it('checks the peer before reading a large file and never connects to an old peer', async () => {
+ const dir = await mkdtemp(path.join(os.tmpdir(), 'cindy-peer-upload-'));
+ try {
+ const file = path.join(dir, 'movie.mov');
+ await writeFile(file, '');
+ await truncate(file, 3 * 1024 ** 3);
+ const invoke = vi.fn(async () => ({
+ ok: true,
+ result: { version: 1, streaming: true, attachments: true },
+ }));
+ vi.mocked(createHash).mockClear();
+ expect(await tryUploadPeerAttachment('old-large-peer', file, 'video/quicktime', invoke)).toBeNull();
+ expect(invoke.mock.calls.map((call) => (call as unknown[])[2])).toEqual([[{ action: 'caps' }]]);
+ expect(createHash).not.toHaveBeenCalled();
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+ });
+});
describe('authorized file peer source', () => {
it.each([0, 15_001])(
@@ -298,6 +325,7 @@ describe('authorized file peer source', () => {
maxBytes: limit,
streaming: true,
attachments: true,
+ largeAttachments: true,
});
const first = await connect();
expect((await open(first.connection)).size).toBe(limit);
@@ -347,6 +375,70 @@ describe('authorized file peer source', () => {
mock.current = false;
await expect(read(b.connection, fb.ticket, 5)).rejects.toThrow('CLOSED');
});
+ it('keeps a connection alive while a long attachment request is handled, then idles out', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] });
+ try {
+ let finish!: (value: unknown) => void;
+ const invoke = vi.fn(() => new Promise((resolve) => { finish = resolve; }));
+ const { connection } = (await requestFilePeer(
+ 'device-a',
+ { action: 'offer', sdp: 'v=0' },
+ invoke as never,
+ )) as { connection: string };
+ const payload = JSON.stringify({
+ channel: 'device-link:file-peer',
+ args: [{ action: 'attachment', connection, request: { op: 'finish' } }],
+ });
+ // 接收端整读重算大附件摘要可能远超 60 秒空闲时限。
+ const handled = mock.handlers.get('file-peer:host:invoke')!({}, connection, payload);
+ await vi.advanceTimersByTimeAsync(150_000);
+ finish({ ok: true });
+ await expect(handled).resolves.toBe(JSON.stringify({ ok: true }));
+ await vi.advanceTimersByTimeAsync(61_000);
+ await expect(
+ mock.handlers.get('file-peer:host:invoke')!({}, connection, payload),
+ ).rejects.toThrow('FILE_PEER_CLOSED');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+ it('keeps only the stalled peer alive; another controller link and in-flight request are unaffected', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] });
+ try {
+ let finishA!: (value: unknown) => void;
+ let finishB!: (value: unknown) => void;
+ const invokeA = vi.fn(() => new Promise((resolve) => { finishA = resolve; }));
+ const invokeB = vi.fn(() => new Promise((resolve) => { finishB = resolve; }));
+ const offer = async (peer: string, invoke: unknown) =>
+ ((await requestFilePeer(peer, { action: 'offer', sdp: 'v=0' }, invoke as never)) as {
+ connection: string;
+ }).connection;
+ const a = await offer('device-a', invokeA);
+ const b = await offer('device-b', invokeB);
+ const handle = (connection: string) =>
+ mock.handlers.get('file-peer:host:invoke')!(
+ {},
+ connection,
+ JSON.stringify({
+ channel: 'device-link:file-peer',
+ args: [{ action: 'attachment', connection, request: { op: 'finish' } }],
+ }),
+ );
+ // device-a 停在一次很长的请求上(不回包);device-b 同时有自己的在途请求。
+ const stalledA = handle(a);
+ const inflightB = handle(b);
+ await vi.advanceTimersByTimeAsync(20_000);
+ finishB({ ok: 'b' });
+ await expect(inflightB).resolves.toBe(JSON.stringify({ ok: 'b' }));
+ // A 的保活只刷新 A 自己的连接:B 按自身空闲时限关闭,不被 A 延长。
+ await vi.advanceTimersByTimeAsync(61_000);
+ await expect(handle(b)).rejects.toThrow('FILE_PEER_CLOSED');
+ finishA({ ok: 'a' });
+ await expect(stalledA).resolves.toBe(JSON.stringify({ ok: 'a' }));
+ } finally {
+ vi.useRealTimers();
+ }
+ });
it('keeps a stalled transfer alive past 30 seconds, renews on progress and closes after 60 idle seconds', async () => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
try {
diff --git a/apps/desktop/src/main/device-link/__tests__/peerAttachmentStore.test.ts b/apps/desktop/src/main/device-link/__tests__/peerAttachmentStore.test.ts
index ab8956456f..edb84d6bc7 100644
--- a/apps/desktop/src/main/device-link/__tests__/peerAttachmentStore.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/peerAttachmentStore.test.ts
@@ -106,3 +106,23 @@ it('rejects incorrect hashes and out of order writes', async () => {
});
await expect(handlePeerAttachment('a', { op: 'finish', ticket })).rejects.toThrow('INTEGRITY');
});
+it('admits attachments of any size when the disk has room, reserving unwritten in-flight bytes', async () => {
+ const gib = 1024 ** 3;
+ const statfs = vi.spyOn(fs, 'statfs');
+ // 16 GiB free: a 5 GiB upload peaks at three copies (inbox, temp, durable) + 256 MiB headroom,
+ // with no fixed total cap.
+ statfs.mockResolvedValue({ bavail: 16, bsize: gib } as Awaited<ReturnType<typeof fs.statfs>>);
+ const large = { size: 5 * gib, sha256: 'a'.repeat(64) };
+ const first = (await handlePeerAttachment('a', { op: 'begin', ...large })) as { ticket: string };
+ expect(first.ticket).toMatch(/^[a-f0-9-]{36}$/);
+ // The unfinished 5 GiB upload still has to land on disk: 5 + 3*5 + 0.25 > 16.
+ await expect(handlePeerAttachment('a', { op: 'begin', ...large })).rejects.toThrow(
+ 'FILE_PEER_STORAGE',
+ );
+ await handlePeerAttachment('a', { op: 'cancel', ticket: first.ticket });
+ // 15 GiB would fit two copies but not the three-copy materialization peak.
+ statfs.mockResolvedValue({ bavail: 15, bsize: gib } as Awaited<ReturnType<typeof fs.statfs>>);
+ await expect(handlePeerAttachment('a', { op: 'begin', ...large })).rejects.toThrow(
+ 'FILE_PEER_STORAGE',
+ );
+});
diff --git a/apps/desktop/src/main/device-link/filePeer.ts b/apps/desktop/src/main/device-link/filePeer.ts
index 423490ee78..ef885b2e28 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,
+ canSendPeerAttachment,
FILE_PEER_IDLE_MS,
FILE_PEER_CHANNEL,
parseFilePeerRequest,
@@ -66,6 +67,8 @@ interface Outgoing {
invoke: Invoke;
rpc?: boolean;
attachments?: boolean;
+ /** 对端接收直连附件不设固定上限(只看磁盘空间);旧端仍按 OSS 上限拒收更大的附件。 */
+ largeAttachments?: boolean;
}
const outgoing = new Map<string, Outgoing>();
const cooldown = createPeerTransferCooldown();
@@ -107,6 +110,21 @@ function touch(id: string) {
c.timer.unref();
return c;
}
+/**
+ * 等待单次请求期间按空闲时限的一半刷新连接:大附件的摘要校验可能超过空闲时限,
+ * 进行中的请求不能被当成空闲关掉。连接已关闭或被撤权时停止刷新。
+ */
+function keepAlive(id: string): () => void {
+ const timer = setInterval(() => {
+ try {
+ touch(id);
+ } catch {
+ clearInterval(timer);
+ }
+ }, FILE_PEER_IDLE_MS / 2);
+ timer.unref();
+ return () => clearInterval(timer);
+}
function track(id: string, peer: string, incoming: boolean) {
if (connections.size >= 4) throw new Error('FILE_PEER_BUSY');
const timer = setTimeout(() => stopConnection(id, 'idle'), FILE_PEER_IDLE_MS);
@@ -176,6 +194,14 @@ async function prepareHost(connection: string): Promise<void> {
}
async function command(c: FilePeerCommand): Promise<string | undefined> {
await prepareHost(c.connection);
+ const stopKeepAlive = c.action === 'invoke' ? keepAlive(c.connection) : undefined;
+ try {
+ return await sendCommand(c);
+ } finally {
+ stopKeepAlive?.();
+ }
+}
+function sendCommand(c: FilePeerCommand): Promise<string | undefined> {
return new Promise((resolve, reject) => {
const id = randomUUID();
const timer = setTimeout(
@@ -186,7 +212,11 @@ async function command(c: FilePeerCommand): Promise<string | undefined> {
if (c.action !== 'invoke') stopConnection(c.connection, `${c.action}-timeout`);
reject(new Error('FILE_PEER_TIMEOUT'));
},
- c.action === 'receive' ? 60_000 : 15_000,
+ c.action === 'receive'
+ ? 60_000
+ : c.action === 'invoke' && c.timeoutMs && c.timeoutMs > 15_000
+ ? c.timeoutMs
+ : 15_000,
);
timer.unref();
replies.set(id, { connection: c.connection, resolve, reject, timer });
@@ -232,7 +262,13 @@ async function handleFilePeerRequest(
invoke?: Connection['invoke'],
): Promise<unknown> {
if (r.action === 'caps')
- return { version: 1, maxBytes: FILE_PEER_MAX_BYTES, streaming: true, attachments: true };
+ return {
+ version: 1,
+ maxBytes: FILE_PEER_MAX_BYTES,
+ streaming: true,
+ attachments: true,
+ largeAttachments: true,
+ };
if (r.action === 'offer') {
const id = randomUUID();
track(id, peer, true);
@@ -341,7 +377,13 @@ export function registerFilePeerIpc() {
!canServePeerInvoke(payload.channel, payload.args)
)
throw new Error('FILE_PEER_DENIED');
- const result = await c.invoke(payload.channel, payload.args);
+ const stopKeepAlive = keepAlive(id);
+ let result: unknown;
+ try {
+ result = await c.invoke(payload.channel, payload.args);
+ } finally {
+ stopKeepAlive();
+ }
touch(id);
return JSON.stringify(result);
});
@@ -508,6 +550,8 @@ async function receivePeerFile(
}
out.rpc = (caps.result as { streaming?: unknown }).streaming === true;
out.attachments = (caps.result as { attachments?: unknown }).attachments === true;
+ out.largeAttachments =
+ (caps.result as { largeAttachments?: unknown }).largeAttachments === true;
track(id, peer, false);
const [, servers] = await Promise.all([prepareHost(id), loadDesktopIceServers()]);
const offer = await command({
@@ -614,6 +658,28 @@ async function receivePeerFile(
}
}
+interface PeerAttachmentCaps {
+ attachments?: boolean;
+ largeAttachments?: boolean;
+}
+/** 已有连接直接复用其能力;否则只发一次 caps 查询(走既有通道,不建 WebRTC 连接)。 */
+async function peerAttachmentCaps(
+ peer: string,
+ invoke: Invoke,
+): Promise<PeerAttachmentCaps | undefined> {
+ const existing = outgoing.get(peer);
+ if (existing?.remote) return existing;
+ const caps = await invoke(peer, FILE_PEER_CHANNEL, [{ action: 'caps' }]);
+ const result = caps.ok
+ ? (caps.result as { version?: unknown; attachments?: unknown; largeAttachments?: unknown })
+ : undefined;
+ if (result?.version !== 1) return undefined;
+ return {
+ attachments: result.attachments === true,
+ largeAttachments: result.largeAttachments === true,
+ };
+}
+
const warming = new Set<string>();
/** Upload only bytes; the eventual message still uses its original WSS acceptance semantics. */
export async function tryUploadPeerAttachment(
@@ -634,16 +700,13 @@ export async function tryUploadPeerAttachment(
let handle: FileHandle | undefined;
let active: Outgoing | undefined;
try {
- await receivePeerFile(peer, null, invoke);
- check();
- const out = outgoing.get(peer);
- if (!out?.remote || !out.attachments) return null;
- active = out;
- out.busy = true;
if (typeof source === 'string')
handle = await fs.open(source, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
const size = handle ? (await handle.stat()).size : (source as Buffer).length;
- if (!size || size > FILE_PEER_MAX_BYTES) return null;
+ if (!size) return null;
+ // 读整份文件算摘要之前先确认对端能收:对端离线、旧版或不支持时不白读一遍(随后还要走 OSS)。
+ if (!canSendPeerAttachment(await peerAttachmentCaps(peer, invoke), size)) return null;
+ check();
const read = async (offset: number, length: number) => {
check();
if (!handle) return (source as Buffer).subarray(offset, offset + length);
@@ -652,19 +715,28 @@ export async function tryUploadPeerAttachment(
throw new Error('FILE_PEER_CHANGED');
return bytes;
};
+ // 能力确认后先算摘要再建链:大文件摘要可能超过连接空闲时限,建好的连接不能在 begin 前被闲置关掉。
const hash = createHash('sha256');
for (let offset = 0; offset < size; offset += 1024 * 1024)
hash.update(await read(offset, Math.min(1024 * 1024, size - offset)));
+ const sha256 = hash.digest('hex');
+ await receivePeerFile(peer, null, invoke);
+ check();
+ const out = outgoing.get(peer);
+ if (!out?.remote || !canSendPeerAttachment(out, size)) return null;
+ active = out;
+ out.busy = true;
const transferStartedAt = Date.now();
const result = await uploadPeerAttachment(
- { size, sha256: hash.digest('hex'), mimeType },
+ { size, sha256, mimeType },
async (offset, length) => (await read(offset, length)).toString('base64'),
- async (request) => {
+ async (request, timeoutMs) => {
check();
const response = JSON.parse(
(await command({
action: 'invoke',
connection: out.id,
+ ...(timeoutMs ? { timeoutMs } : {}),
payload: JSON.stringify({
channel: FILE_PEER_CHANNEL,
args: [{ action: 'attachment', connection: out.remote, request }],
diff --git a/apps/desktop/src/main/device-link/peerAttachmentStore.ts b/apps/desktop/src/main/device-link/peerAttachmentStore.ts
index 273bc0a693..c83dee33c2 100644
--- a/apps/desktop/src/main/device-link/peerAttachmentStore.ts
+++ b/apps/desktop/src/main/device-link/peerAttachmentStore.ts
@@ -48,7 +48,9 @@ export async function handlePeerAttachment(peer: string, r: Record<string, unkno
buildPeerAttachmentRef({ ...r, ticket } as unknown as PeerAttachment),
);
if (!parsed) throw new Error('INVALID_PEER_ATTACHMENT');
- let reserved = 0,
+ // 不设总量上限,只看磁盘:未完成的上传还会继续写入,已写部分已计入可用空间,
+ // 这里按剩余待写字节预留。
+ let pending = 0,
count = 0;
for (const name of await fs.readdir(root)) {
if (!name.endsWith('.json') || !validTicket(name.slice(0, -5))) continue;
@@ -66,16 +68,22 @@ export async function handlePeerAttachment(peer: string, r: Record<string, unkno
await fs.rm(path.join(root, name.slice(0, -5)), { force: true });
await fs.rm(path.join(root, name), { force: true });
} else {
- reserved += entry.size;
+ if (!entry.complete) {
+ const written = await fs
+ .stat(path.join(root, name.slice(0, -5)))
+ .then((stat) => stat.size)
+ .catch(() => 0);
+ pending += Math.max(0, entry.size - written);
+ }
count++;
}
});
}
const space = await fs.statfs(root);
+ // 物化峰值同时存在三份:收件箱保留件、会话临时件、媒体仓/附件缓存的持久副本。
if (
count >= 128 ||
- reserved + parsed.size > 4 * 1024 ** 3 ||
- space.bavail * space.bsize < parsed.size * 2 + 256 * 1024 ** 2
+ space.bavail * space.bsize < pending + parsed.size * 3 + 256 * 1024 ** 2
)
throw new Error('FILE_PEER_STORAGE');
check();
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/normalizeAttachmentsTemp.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/normalizeAttachmentsTemp.test.ts
index 3460b53ecb..f8d6694774 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/normalizeAttachmentsTemp.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/normalizeAttachmentsTemp.test.ts
@@ -182,6 +182,10 @@ describe('inline attachment temporary files', () => {
base64: undefined,
}],
});
+ // 下载的临时件按文件流式入仓,不整读进 main 内存(附件不限大小)。
+ const ingestParams = vi.mocked(ingestMedia).mock.calls[0][0] as { filePath?: string; buffer?: unknown };
+ expect(ingestParams.filePath).toEqual(expect.any(String));
+ expect(ingestParams.buffer).toBeUndefined();
materialized.cleanupAfterAcceptance?.();
expect(removeRemote).toHaveBeenCalledWith('cindy/device-link/user/image.png');
});
@@ -293,6 +297,10 @@ describe('inline attachment temporary files', () => {
persistedContent: undefined,
});
expect(downloadToFile).not.toHaveBeenCalled();
+ // 控制端指定的本机图片路径保持原读取方式(整读),不改变其读取语义。
+ const ingestParams = vi.mocked(ingestMedia).mock.calls[0][0] as { filePath?: string; buffer?: unknown };
+ expect(ingestParams.filePath).toBeUndefined();
+ expect(Buffer.isBuffer(ingestParams.buffer)).toBe(true);
});
it('keeps queued images on managed URLs instead of rematerializing their source paths', async () => {
diff --git a/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts b/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts
index 6b6093af8e..ae81923394 100644
--- a/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts
+++ b/apps/desktop/src/main/maker-ipc/normalizeAttachments.ts
@@ -640,13 +640,14 @@ async function materializeQueuedOssAttachmentsInternal(
// 可入总仓的媒体(图片等白名单 mime)→ ingest 进 cindy-media 并直接挂
// session-attachment 引用(入队消息没有草稿期,等价老 lifecycle committed);
// 媒体附件统一走总仓 ingest(规则 25)。
+ // source 为 Host 自己下载落盘的临时件时按文件流式入仓:附件不限大小,整读进主进程内存
+ // 会让数 GB 的图片压垮 main;控制端指定的本机图片路径仍按原方式整读,不改变其读取语义。
const ingestIntoBlobStore = async (
- sourcePath: string,
+ source: { buffer: Buffer } | { filePath: string },
mimeType: string,
): Promise<MaterializedRef> => {
- const buffer = await fs.readFile(sourcePath);
const written = await ingestMedia({
- buffer,
+ ...source,
mimeType,
refs: [
{
@@ -685,7 +686,7 @@ async function materializeQueuedOssAttachmentsInternal(
const ext = path.extname(refStr).toLowerCase();
const mimeType = cindyMediaBlobStore.mimeForExt(ext);
if (!mimeType) throw new Error(`unsupported image ext: ${ext}`);
- const entry = await ingestIntoBlobStore(refStr, mimeType);
+ const entry = await ingestIntoBlobStore({ buffer: await fs.readFile(refStr) }, mimeType);
byRef.set(refStr, entry);
return entry;
} catch (e) {
@@ -703,16 +704,15 @@ async function materializeQueuedOssAttachmentsInternal(
await materializeRemoteAttachment(ref, tmp, integrityForRef(ref));
const mime = ref.mimeType ?? mimeHint;
let entry: MaterializedRef;
- // 只收图片进总仓:ingestIntoBlobStore 是整读内存(readFile + sha256),
- // 手机传的大视频/音频若走这条会让 main 进程内存翻倍(review P1);
- // 等 blobStore 流式入口落地再放开非图片媒体,现阶段维持老文件级拷贝。
+ // 只收图片进总仓(下载的临时件按文件流式入仓,不整读进 main 内存);
+ // 视频/音频等非图片媒体是否进字节仓另议,现阶段维持老文件级拷贝。
if (
mime &&
mime.startsWith('image/') &&
cindyMediaBlobStore.supportedMime(mime) &&
!isDangerousAttachmentName(ref.originalName ?? '')
) {
- entry = await ingestIntoBlobStore(tmp, mime);
+ entry = await ingestIntoBlobStore({ filePath: tmp }, mime);
} else {
// 非媒体附件维持历史兼容路径落地;规则 25 明确非媒体不进字节仓。
const originalName =
diff --git a/apps/desktop/src/shared/filePeer.ts b/apps/desktop/src/shared/filePeer.ts
index 92cf5d1fa3..6dd3eaeb47 100644
--- a/apps/desktop/src/shared/filePeer.ts
+++ b/apps/desktop/src/shared/filePeer.ts
@@ -10,7 +10,7 @@ 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 }
+ | { action: 'invoke'; connection: string; payload: string; timeoutMs?: number }
| { action: 'accept'; connection: string; servers: DesktopIceServer[]; sdp: string }
| { action: 'answer'; connection: string; sdp: string }
| { action: 'receive'; connection: string; ticket: string; size: number; sink: string }
diff --git a/apps/mobile/app/sessions/new.tsx b/apps/mobile/app/sessions/new.tsx
index 5fdb4d2db5..821a9d94b2 100644
--- a/apps/mobile/app/sessions/new.tsx
+++ b/apps/mobile/app/sessions/new.tsx
@@ -901,7 +901,7 @@ export default function NewRemoteSessionScreen() {
count: MOBILE_MAX_ATTACHMENTS,
}));
} else if (selection.rejectedUris.length > 0) {
- setAttachmentError(i18n.t('composer.upload.fileTypeUnsupported'));
+ setAttachmentError(i18n.t('composer.upload.noFileRead'));
} else {
setAttachmentError(null);
}
diff --git a/apps/mobile/src/__tests__/attachments.test.ts b/apps/mobile/src/__tests__/attachments.test.ts
index a80cdce313..01564bd873 100644
--- a/apps/mobile/src/__tests__/attachments.test.ts
+++ b/apps/mobile/src/__tests__/attachments.test.ts
@@ -7,12 +7,12 @@ import {
buildMobileRemoteFileAttachment,
buildMobileUploadedAttachment,
MOBILE_MAX_ATTACHMENTS,
- MOBILE_MAX_ATTACHMENT_BYTES,
categorizeMobileAttachment,
mergeAttachmentsWithinLimit,
extractRemoteFileExt,
} from '@/session/attachments';
import { isAttachmentOssRef, parseAttachmentOssRef } from '@/session/attachmentOssRef';
+import { OSS_ATTACHMENT_MAX_BYTES, buildPeerAttachmentRef } from '@cindy/device-link';
import type { RemoteSerializedAttachment } from '@/session/types';
const SHA256 = 'a'.repeat(64);
@@ -31,7 +31,9 @@ describe('mobile remote file attachments', () => {
expect(categorizeMobileAttachment('report.docx')).toBe('office');
expect(categorizeMobileAttachment('SessionScreen.tsx')).toBe('text');
expect(categorizeMobileAttachment('Dockerfile')).toBe('text');
- expect(categorizeMobileAttachment('archive.zip')).toBeNull();
+ expect(categorizeMobileAttachment('archive.zip')).toBe('file');
+ expect(categorizeMobileAttachment('clip.mp4')).toBe('file');
+ expect(categorizeMobileAttachment('LICENSE')).toBe('file');
});
it('builds desktop-compatible serialized attachment and persisted file refs', () => {
@@ -159,23 +161,48 @@ describe('mobile remote file attachments', () => {
});
});
- it('rejects uploaded mobile files outside desktop attachment limits', () => {
+ it('accepts any file type like desktop', () => {
+ const archive = buildMobileUploadedAttachment({
+ ossKey: 'cindy/device-link/user-1/archive.zip',
+ name: 'archive.zip',
+ size: 1024,
+ sha256: SHA256,
+ });
+ expect(archive).toMatchObject({
+ name: 'archive.zip',
+ ext: '.zip',
+ category: 'file',
+ mimeType: 'application/octet-stream',
+ });
+ expect(archive).not.toHaveProperty('url');
+ });
+
+ it('limits only OSS-relayed attachments; direct attachments have no fixed size cap', () => {
expect(
buildMobileUploadedAttachment({
- ossKey: 'cindy/device-link/user-1/archive.zip',
- name: 'archive.zip',
- size: 1024,
+ ossKey: 'cindy/device-link/user-1/big.pdf',
+ name: 'big.pdf',
+ size: OSS_ATTACHMENT_MAX_BYTES,
sha256: SHA256,
}),
- ).toBeNull();
+ ).toMatchObject({ category: 'pdf', size: OSS_ATTACHMENT_MAX_BYTES });
expect(
buildMobileUploadedAttachment({
ossKey: 'cindy/device-link/user-1/spec.pdf',
name: 'spec.pdf',
- size: MOBILE_MAX_ATTACHMENT_BYTES + 1,
+ size: OSS_ATTACHMENT_MAX_BYTES + 1,
sha256: SHA256,
}),
).toBeNull();
+ const size = 10 * 1024 ** 3;
+ const peerRef = buildPeerAttachmentRef({
+ ticket: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
+ size,
+ sha256: SHA256,
+ });
+ expect(
+ buildMobileUploadedAttachment({ peerRef, name: 'movie.mov', size, sha256: SHA256 }),
+ ).toMatchObject({ category: 'file', size, path: peerRef });
});
});
diff --git a/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx b/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx
index 6acb8a55cf..c1c5e945b9 100644
--- a/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx
+++ b/apps/mobile/src/__tests__/fileWebViewTermination.test.tsx
@@ -44,6 +44,7 @@ vi.mock('@/device-link/peerFileRegistry', () => ({
installPeerFileDownload: (...args: unknown[]) => { state.install(...args); return state.unregister; },
installPeerInvoke: () => state.unregisterInvoke,
installPeerUpload: () => state.unregisterUpload,
+ installPeerUploadProbe: () => () => {},
installPeerReset: () => state.unregisterReset,
clearPeerMedia() {}, recordPeerMedia: vi.fn(),
}));
diff --git a/apps/mobile/src/__tests__/incomingShare.test.ts b/apps/mobile/src/__tests__/incomingShare.test.ts
index 28bc7f494d..078a5a47b8 100644
--- a/apps/mobile/src/__tests__/incomingShare.test.ts
+++ b/apps/mobile/src/__tests__/incomingShare.test.ts
@@ -124,7 +124,7 @@ describe('incoming Share Extension payloads', () => {
});
});
- it('falls back to a decoded URI basename and rejects unsupported attachment types', () => {
+ it('falls back to a decoded URI basename and accepts any attachment type', () => {
const result = selectIncomingShareUploadCandidates([
payload({
contentUri: 'file:///shared/My%20Notes.md',
@@ -146,8 +146,12 @@ describe('incoming Share Extension payloads', () => {
name: 'My Notes.md',
size: 0,
mimeType: 'text/markdown',
- }]);
- expect(result.rejectedUris).toEqual(['file:///shared/archive.zip']);
+ }, expect.objectContaining({
+ kind: 'file',
+ uri: 'file:///shared/archive.zip',
+ name: 'archive.zip',
+ })]);
+ expect(result.rejectedUris).toEqual([]);
});
it('keeps a batch until the matching consumer acknowledges it exactly once', () => {
diff --git a/apps/mobile/src/__tests__/mobileAttachmentUpload.test.ts b/apps/mobile/src/__tests__/mobileAttachmentUpload.test.ts
index 9c590a6c2f..7e8631d345 100644
--- a/apps/mobile/src/__tests__/mobileAttachmentUpload.test.ts
+++ b/apps/mobile/src/__tests__/mobileAttachmentUpload.test.ts
@@ -172,7 +172,7 @@ describe('mobileAttachmentUpload', () => {
});
});
- it('rejects an unsupported local file type before any presign or PUT (no orphaned OSS object)', async () => {
+ it('rejects a file beyond the OSS limit before any presign or PUT (no orphaned OSS object)', async () => {
const apiFetch = vi.fn();
const fetchPut = vi.fn();
@@ -180,7 +180,7 @@ describe('mobileAttachmentUpload', () => {
uploadMobileAttachment(
{
name: 'archive.zip',
- size: 4096,
+ size: 2 * 1024 * 1024 * 1024 + 1,
mimeType: 'application/zip',
},
new Blob(['zip'], { type: 'application/zip' }),
@@ -192,7 +192,7 @@ describe('mobileAttachmentUpload', () => {
},
},
),
- ).rejects.toThrow('这个本机文件类型暂不支持作为附件发送。');
+ ).rejects.toThrow('文件超过 2 GB,只能在与电脑直连时发送');
// 关键:校验发生在网络调用之前,绝不能 presign / PUT,否则会留下孤儿对象。
expect(apiFetch).not.toHaveBeenCalled();
@@ -385,7 +385,7 @@ describe('mobileAttachmentUpload', () => {
})).rejects.toThrow('附件上传失败:HTTP 403 (SignatureDoesNotMatch)');
});
- it('rejects an unsupported file type before presign in the native file path (no orphaned OSS object)', async () => {
+ it('rejects a file beyond the OSS limit before hashing or presign when no direct connection is possible', async () => {
const apiFetch = vi.fn();
const uploadFile = vi.fn();
@@ -393,7 +393,7 @@ describe('mobileAttachmentUpload', () => {
uploadMobileAttachmentFromFile(
{
name: 'archive.zip',
- size: 4096,
+ size: 2 * 1024 * 1024 * 1024 + 1,
mimeType: 'application/zip',
},
'file:///tmp/archive.zip',
@@ -405,7 +405,7 @@ describe('mobileAttachmentUpload', () => {
},
},
),
- ).rejects.toThrow('这个本机文件类型暂不支持作为附件发送。');
+ ).rejects.toThrow('文件超过 2 GB,只能在与电脑直连时发送');
expect(apiFetch).not.toHaveBeenCalled();
expect(uploadFile).not.toHaveBeenCalled();
@@ -542,6 +542,29 @@ describe('mobileAttachmentUpload', () => {
} finally { vi.useRealTimers(); }
});
+ it('has no fixed total deadline for a large native upload that keeps progressing', async () => {
+ vi.useFakeTimers();
+ try {
+ let finish!: (value: { status: number }) => void;
+ let progress!: (bytes: number) => void;
+ let signal!: AbortSignal;
+ const uploadFile = vi.fn((_url, _uri, _headers, opts) => {
+ progress = opts.onProgress;
+ signal = opts.signal;
+ return new Promise<{ status: number }>((resolve) => { finish = resolve; });
+ });
+ const pending = putMobileAttachmentUploadFromFile('https://oss.example/upload', 'file:///tmp/big.mov', 'video/quicktime', { uploadFile });
+ for (let minute = 1; minute <= 10; minute += 1) {
+ await vi.advanceTimersByTimeAsync(50_000);
+ progress(minute * 100 * 1024 * 1024);
+ }
+ expect(signal.aborted).toBe(false);
+ expect(uploadFile).toHaveBeenCalledTimes(1);
+ finish({ status: 200 });
+ await pending;
+ } finally { vi.useRealTimers(); }
+ });
+
it('duplicate progress events cannot keep a stalled native upload alive', async () => {
vi.useFakeTimers();
try {
diff --git a/apps/mobile/src/__tests__/mobileAttachmentUploadLarge.test.ts b/apps/mobile/src/__tests__/mobileAttachmentUploadLarge.test.ts
new file mode 100644
index 0000000000..cde922b6e6
--- /dev/null
+++ b/apps/mobile/src/__tests__/mobileAttachmentUploadLarge.test.ts
@@ -0,0 +1,70 @@
+import { beforeAll, describe, expect, it, vi } from 'vitest';
+import { apiFetchRaw } from '@/api/client';
+import { installPeerUpload, installPeerUploadProbe } from '@/device-link/peerFileRegistry';
+import { OSS_ATTACHMENT_MAX_BYTES, buildPeerAttachmentRef, parsePeerAttachmentRef } from '@cindy/device-link';
+import { i18n } from '@/i18n';
+import { sha256MobileAttachmentFile } from '@/session/mobileAttachmentSha256';
+import { uploadMobileAttachmentFromFile } from '@/session/mobileAttachmentUpload';
+
+// 真实摘要要逐块读完数 GB,这里只验证路由:摘要换成定值。
+vi.mock('@/session/mobileAttachmentSha256', () => ({
+ sha256MobileAttachmentFile: vi.fn(async () => 'a'.repeat(64)),
+ sha256MobileAttachmentBody: vi.fn(async () => 'a'.repeat(64)),
+}));
+
+beforeAll(async () => {
+ await i18n.changeLanguage('zh-CN');
+});
+
+const size = OSS_ATTACHMENT_MAX_BYTES + 1;
+const readFileChunk = vi.fn();
+
+describe('mobileAttachmentUpload beyond the OSS limit', () => {
+ it('sends over the direct connection without any size cap', async () => {
+ const apiFetch = vi.fn();
+ const peer = vi.fn(async (_device, _uri, metadata) =>
+ buildPeerAttachmentRef({ ...metadata, ticket: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa' }));
+ const off = installPeerUpload(peer);
+ const offProbe = installPeerUploadProbe(async () => true);
+ try {
+ const attachment = await uploadMobileAttachmentFromFile({ name: 'movie.mov', size }, 'file:///source', {
+ deviceId: 'host-a', token: 'token', deps: { apiFetch: apiFetch as unknown as typeof apiFetchRaw, readFileChunk },
+ });
+ expect(parsePeerAttachmentRef(attachment.path)?.size).toBe(size);
+ expect(attachment.category).toBe('file');
+ expect(apiFetch).not.toHaveBeenCalled();
+ } finally { off(); offProbe(); }
+ });
+
+ it('fails before snapshotting or hashing when the peer cannot take a direct attachment', async () => {
+ const apiFetch = vi.fn();
+ const snapshotFile = vi.fn();
+ const peer = vi.fn();
+ const probe = vi.fn(async () => false);
+ vi.mocked(sha256MobileAttachmentFile).mockClear();
+ const off = installPeerUpload(peer);
+ const offProbe = installPeerUploadProbe(probe);
+ try {
+ await expect(uploadMobileAttachmentFromFile({ name: 'movie.mov', size }, 'file:///source', {
+ deviceId: 'host-a', token: 'token', deps: { apiFetch: apiFetch as unknown as typeof apiFetchRaw, snapshotFile },
+ })).rejects.toThrow('文件超过 2 GB,只能在与电脑直连时发送');
+ expect(probe).toHaveBeenCalledWith('host-a', size);
+ expect(snapshotFile).not.toHaveBeenCalled();
+ expect(sha256MobileAttachmentFile).not.toHaveBeenCalled();
+ expect(peer).not.toHaveBeenCalled();
+ expect(apiFetch).not.toHaveBeenCalled();
+ } finally { off(); offProbe(); }
+ });
+
+ it('fails without falling back to OSS when the direct connection is unavailable', async () => {
+ const apiFetch = vi.fn();
+ const off = installPeerUpload(async () => null);
+ const offProbe = installPeerUploadProbe(async () => true);
+ try {
+ await expect(uploadMobileAttachmentFromFile({ name: 'movie.mov', size }, 'file:///source', {
+ deviceId: 'host-a', token: 'token', deps: { apiFetch: apiFetch as unknown as typeof apiFetchRaw, readFileChunk },
+ })).rejects.toThrow('文件超过 2 GB,只能在与电脑直连时发送');
+ expect(apiFetch).not.toHaveBeenCalled();
+ } finally { off(); offProbe(); }
+ });
+});
diff --git a/apps/mobile/src/__tests__/mobileImageAttachment.test.ts b/apps/mobile/src/__tests__/mobileImageAttachment.test.ts
index 8cee4b6da6..f182068673 100644
--- a/apps/mobile/src/__tests__/mobileImageAttachment.test.ts
+++ b/apps/mobile/src/__tests__/mobileImageAttachment.test.ts
@@ -1,6 +1,5 @@
import { beforeAll, describe, expect, it, vi } from 'vitest';
import { i18n } from '@/i18n';
-import { MOBILE_MAX_ATTACHMENT_BYTES } from '@/session/attachments';
import {
assertMobileImageSize,
buildMobileImageAttachmentCandidate,
@@ -54,7 +53,8 @@ describe('mobileImageAttachment', () => {
it('rejects missing uri and invalid sizes with user-facing errors', () => {
expect(() => buildMobileImageAttachmentCandidate({ uri: '' }, 0)).toThrow('没有读取到可上传的图片');
expect(() => assertMobileImageSize(0)).toThrow('图片为空');
- expect(() => assertMobileImageSize(MOBILE_MAX_ATTACHMENT_BYTES + 1)).toThrow('图片超过');
+ // 与桌面一致不设图片体积上限;OSS 保底上限由上传层按是否能直连判断。
+ expect(() => assertMobileImageSize(3 * 1024 ** 3)).not.toThrow();
});
});
diff --git a/apps/mobile/src/__tests__/mobileImagePreprocess.test.ts b/apps/mobile/src/__tests__/mobileImagePreprocess.test.ts
index 7b7b1b5008..33d88d9f45 100644
--- a/apps/mobile/src/__tests__/mobileImagePreprocess.test.ts
+++ b/apps/mobile/src/__tests__/mobileImagePreprocess.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from 'vitest';
import {
+ MOBILE_IMAGE_PREPROCESS_MAX_BYTES,
MOBILE_IMAGE_UPLOAD_JPEG_QUALITY,
MOBILE_IMAGE_UPLOAD_MAX_LONG_EDGE,
MOBILE_IMAGE_UPLOAD_SKIP_BYTES,
@@ -19,6 +20,17 @@ describe('planMobileImageUploadPreprocess', () => {
})).toBeNull();
});
+ it('超大文件不在手机上解码,原样上传(避免整图解码占满内存)', () => {
+ for (const mimeType of ['image/jpeg', 'image/png']) {
+ expect(planMobileImageUploadPreprocess({
+ mimeType, size: MOBILE_IMAGE_PREPROCESS_MAX_BYTES + 1, width: 12000, height: 9000,
+ })).toBeNull();
+ }
+ expect(planMobileImageUploadPreprocess({
+ mimeType: 'image/jpeg', size: MOBILE_IMAGE_PREPROCESS_MAX_BYTES, width: 12000, height: 9000,
+ })).not.toBeNull();
+ });
+
it('小尺寸小体积 jpeg 原样上传', () => {
expect(planMobileImageUploadPreprocess({
mimeType: 'image/jpeg', size: SMALL, width: 1200, height: 900,
diff --git a/apps/mobile/src/__tests__/mobileLocalAttachmentUpload.test.ts b/apps/mobile/src/__tests__/mobileLocalAttachmentUpload.test.ts
index c82984a321..42cc053890 100644
--- a/apps/mobile/src/__tests__/mobileLocalAttachmentUpload.test.ts
+++ b/apps/mobile/src/__tests__/mobileLocalAttachmentUpload.test.ts
@@ -195,18 +195,39 @@ describe('createMobileLocalAttachmentUploadController', () => {
} finally { vi.useRealTimers(); }
});
- it('reclaims an upload arriving after the total deadline without publishing it', async () => {
+ it('does not apply the total deadline while a large upload is transferring', async () => {
vi.useFakeTimers();
try {
const gate = gatedUpload();
- const { deps, uploaded, discarded } = makeDeps({ upload: gate.upload });
+ const { deps, uploaded, failed } = makeDeps({ upload: gate.upload });
const controller = createMobileLocalAttachmentUploadController(deps);
controller.enqueue([candidate('a.jpg')], { token: 't' });
+ // 传输层自己按无进度判超时;这里跨过多个 180 秒窗口仍在上传。
+ await vi.advanceTimersByTimeAsync(600_000);
+ expect(gate.inFlight()).toEqual(['a.jpg']);
+ expect(failed).toEqual([]);
+ gate.release('a.jpg');
+ expect(await controller.waitForIdle()).toEqual({ failedCount: 0 });
+ expect(uploaded).toHaveLength(1);
+ controller.dispose();
+ } finally { vi.useRealTimers(); }
+ });
+
+ it('re-arms the deadline after upload and reclaims the attachment when delivery never settles', async () => {
+ vi.useFakeTimers();
+ try {
+ const gate = gatedUpload();
+ const { deps, discarded, failed } = makeDeps({
+ upload: gate.upload,
+ onUploaded: () => new Promise<void>(() => {}),
+ });
+ const controller = createMobileLocalAttachmentUploadController(deps);
+ controller.enqueue([candidate('a.jpg')], { token: 't' });
+ await vi.advanceTimersByTimeAsync(600_000);
+ gate.release('a.jpg');
await vi.advanceTimersByTimeAsync(180_000);
expect(await controller.waitForIdle()).toEqual({ failedCount: 1 });
- gate.release('a.jpg');
- await vi.advanceTimersByTimeAsync(0);
- expect(uploaded).toEqual([]);
+ expect(failed).toHaveLength(1);
expect(discarded).toEqual([attachmentFor('a.jpg')]);
controller.dispose();
} finally { vi.useRealTimers(); }
diff --git a/apps/mobile/src/device-link/peerFileRegistry.ts b/apps/mobile/src/device-link/peerFileRegistry.ts
index 197c3f25de..32cbd3b78e 100644
--- a/apps/mobile/src/device-link/peerFileRegistry.ts
+++ b/apps/mobile/src/device-link/peerFileRegistry.ts
@@ -14,6 +14,16 @@ export function installPeerUpload(value: PeerUpload) {
return () => { if (upload === value) upload = null; };
}
export async function tryMobilePeerUpload(...args: Parameters<PeerUpload>) { return upload?.(...args) ?? null; }
+/** 读整份文件之前确认直连可用(只查对端能力,不传字节);没有可用传输时视为不可直连。 */
+type PeerUploadProbe = (device: string, size: number) => Promise<boolean>;
+let uploadProbe: PeerUploadProbe | null = null;
+export function installPeerUploadProbe(value: PeerUploadProbe) {
+ uploadProbe = value;
+ return () => { if (uploadProbe === value) uploadProbe = null; };
+}
+export async function canMobilePeerUpload(device: string, size: number) {
+ return uploadProbe ? uploadProbe(device, size).catch(() => false) : false;
+}
type PeerInvoke = (device: string, channel: string, args: unknown[]) => Promise<InvokeResultPayload | null>;
let invoke: PeerInvoke | null = null;
export function installPeerInvoke(value: PeerInvoke) {
diff --git a/apps/mobile/src/device-link/peerFileTransport.tsx b/apps/mobile/src/device-link/peerFileTransport.tsx
index 89bd214dd8..616f73be53 100644
--- a/apps/mobile/src/device-link/peerFileTransport.tsx
+++ b/apps/mobile/src/device-link/peerFileTransport.tsx
@@ -4,6 +4,7 @@ import {
createPeerTransferCooldown,
canUsePeerInvoke,
uploadPeerAttachment,
+ canSendPeerAttachment,
type InvokeResultPayload,
} from "@cindy/device-link";
import { useEffect, useRef, useState } from "react";
@@ -32,6 +33,7 @@ import {
installPeerFileDownload,
installPeerInvoke,
installPeerUpload,
+ installPeerUploadProbe,
installPeerReset,
recordPeerMedia,
clearPeerMedia,
@@ -92,7 +94,7 @@ export function PeerFileTransport() {
`window.filePeerMessage(${JSON.stringify(message)});true;`,
);
}
- async function command(action: string, args: unknown[]) {
+ async function command(action: string, args: unknown[], timeoutMs?: number) {
return new Promise<unknown>((resolve, reject) => {
const id = randomUUID();
let timer = setTimeout(
@@ -100,7 +102,11 @@ export function PeerFileTransport() {
pending.current.delete(id);
reject(new Error("FILE_PEER_TIMEOUT"));
},
- action === "receive" ? 60_000 : 15000,
+ action === "receive"
+ ? 60_000
+ : timeoutMs && timeoutMs > 15000
+ ? timeoutMs
+ : 15000,
);
const entry = {
resolve,
@@ -171,6 +177,8 @@ export function PeerFileTransport() {
device: string;
rpc: boolean;
attachments: boolean;
+ /** 电脑端直连附件不设固定上限;旧版电脑会拒收超过 OSS 上限的附件。 */
+ largeAttachments: boolean;
} | null = null;
let idle: ReturnType<typeof setTimeout> | undefined;
const close = (notify = true) => {
@@ -260,6 +268,7 @@ export function PeerFileTransport() {
version?: number;
streaming?: boolean;
attachments?: boolean;
+ largeAttachments?: boolean;
};
if (!current() || signal?.aborted)
throw new Error("FILE_PEER_CANCELLED");
@@ -318,6 +327,7 @@ export function PeerFileTransport() {
device,
rpc: caps.streaming === true,
attachments: caps.attachments === true,
+ largeAttachments: caps.largeAttachments === true,
};
mobileDebugLog("debug", "files", "direct transfer connected", {
trace,
@@ -447,6 +457,33 @@ export function PeerFileTransport() {
},
);
const warming = new Set<string>();
+ // 读整份大文件之前的能力确认:复用已建连接的能力,否则只发一次 caps 查询,不建 WebRTC 连接。
+ const unregisterUploadProbe = installPeerUploadProbe(async (device, size) => {
+ const current = captureDevice(device);
+ if (!current() || cooldown.current.remaining(device)) return false;
+ if (connection?.device === device)
+ return canSendPeerAttachment(connection, size);
+ await link.openLink(device);
+ if (!current()) return false;
+ const caps = (await link.invoke<unknown>(device, FILE_PEER_CHANNEL, [
+ { action: "caps" },
+ ])) as {
+ version?: number;
+ attachments?: boolean;
+ largeAttachments?: boolean;
+ } | null;
+ return (
+ current() &&
+ caps?.version === 1 &&
+ canSendPeerAttachment(
+ {
+ attachments: caps.attachments === true,
+ largeAttachments: caps.largeAttachments === true,
+ },
+ size,
+ )
+ );
+ });
const unregisterUpload = installPeerUpload(
(device, uri, metadata, signal) => {
const current = captureDevice(device);
@@ -464,7 +501,12 @@ export function PeerFileTransport() {
await transfer(device, null, signal);
check();
const active = connection;
- if (!active || active.device !== device || !active.attachments)
+ // 对端不支持(含旧版电脑按 OSS 上限拒收大附件):直接放弃直连,不计入失败冷却。
+ if (
+ !active ||
+ active.device !== device ||
+ !canSendPeerAttachment(active, metadata.size)
+ )
return null;
clearTimeout(idle);
busy = true;
@@ -481,21 +523,26 @@ export function PeerFileTransport() {
for (const byte of bytes) binary += String.fromCharCode(byte);
return btoa(binary);
},
- async (request) => {
+ async (request, timeoutMs) => {
check();
- const raw = await command("invoke", [
- active.id,
- JSON.stringify({
- channel: FILE_PEER_CHANNEL,
- args: [
- {
- action: "attachment",
- connection: active.remote,
- request,
- },
- ],
- }),
- ]);
+ const raw = await command(
+ "invoke",
+ [
+ active.id,
+ JSON.stringify({
+ channel: FILE_PEER_CHANNEL,
+ args: [
+ {
+ action: "attachment",
+ connection: active.remote,
+ request,
+ },
+ ],
+ }),
+ timeoutMs,
+ ],
+ timeoutMs,
+ );
check();
const response = JSON.parse(String(raw));
if (!response.ok) throw new Error("FILE_PEER_UPLOAD");
@@ -583,6 +630,7 @@ export function PeerFileTransport() {
unregister();
unregisterInvoke();
unregisterUpload();
+ unregisterUploadProbe();
unregisterReset();
for (const p of pending.current.values()) {
clearTimeout(p.timer);
diff --git a/apps/mobile/src/i18n/locales/en/composer.json b/apps/mobile/src/i18n/locales/en/composer.json
index bb225fecad..691acabf3d 100644
--- a/apps/mobile/src/i18n/locales/en/composer.json
+++ b/apps/mobile/src/i18n/locales/en/composer.json
@@ -45,7 +45,7 @@
"upload": {
"shareReceiveFailed": "Couldn't finish receiving the shared files. Free up storage, then reopen this screen to retry.",
"emptyFile": "This file is empty and can't be sent as an attachment.",
- "fileTooLarge": "The file exceeds {{size}} MB and can't be sent as an attachment for now.",
+ "fileTooLarge": "The file exceeds {{limit}}, so it can only be sent over a direct connection to the computer, which isn't available right now. Make sure the computer's Cindy is up to date, keep this app open, and try again.",
"cancelled": "Attachment upload cancelled.",
"incompleteRead": "Incomplete file read: expected {{expected}} bytes, got {{actual}} bytes.",
"integrityUnavailable": "This attachment upload body can't be integrity-checked.",
@@ -55,13 +55,11 @@
"failedHttp": "Attachment upload failed: HTTP {{status}}{{code}}",
"failedNetwork": "Attachment upload failed: network transfer error, check your connection and try again. ({{detail}})",
"timeout": "Attachment upload timed out; check your connection and try again.",
- "fileTypeUnsupported": "This local file type can't be sent as an attachment yet.",
"snapshotFailedNoCacheDir": "Could not create attachment snapshot: cache directory unavailable",
"snapshotFailed": "Could not create attachment snapshot",
"invalidUploadUrl": "The server did not return a valid attachment upload URL.",
"noImageRead": "No uploadable image was read.",
"emptyImage": "This image is empty and can't be sent as an attachment.",
- "imageTooLarge": "The image exceeds {{size}} MB and can't be sent as an attachment for now.",
"imageTooLargeSend": "The image exceeds {{size}} MB and can't be sent for now.",
"sessionExpiredImage": "Your session has expired. Sign in again to upload the image.",
"sessionExpiredFile": "Your session has expired. Sign in again to upload the attachment.",
diff --git a/apps/mobile/src/i18n/locales/ja/composer.json b/apps/mobile/src/i18n/locales/ja/composer.json
index 20631f7265..509206b457 100644
--- a/apps/mobile/src/i18n/locales/ja/composer.json
+++ b/apps/mobile/src/i18n/locales/ja/composer.json
@@ -45,7 +45,7 @@
"upload": {
"shareReceiveFailed": "共有ファイルの受信を完了できませんでした。ストレージの空き容量を確認し、この画面を開き直して再試行してください。",
"emptyFile": "このファイルは空のため、添付ファイルとして送信できません。",
- "fileTooLarge": "ファイルが {{size}} MB を超えているため、現在は添付ファイルとして送信できません。",
+ "fileTooLarge": "ファイルが {{limit}} を超えているため、コンピューターと直接接続しているときのみ送信できますが、現在は直接接続できません。コンピューターの Cindy を最新版に更新し、このアプリを前面に表示したまま再試行してください。",
"cancelled": "添付ファイルのアップロードをキャンセルしました。",
"incompleteRead": "ファイルの読み取りが不完全です。予期: {{expected}} バイト、実際: {{actual}} バイト。",
"integrityUnavailable": "この添付ファイルのアップロード本文は整合性チェックができません。",
@@ -55,13 +55,11 @@
"failedHttp": "添付ファイルのアップロードに失敗しました: HTTP {{status}}{{code}}",
"failedNetwork": "添付ファイルのアップロードに失敗しました。ネットワーク転送エラーです。接続を確認してからやり直してください。({{detail}})",
"timeout": "添付ファイルのアップロードがタイムアウトしました。接続を確認してからやり直してください。",
- "fileTypeUnsupported": "このローカルファイルの種類はまだ添付ファイルとして送信できません。",
"snapshotFailedNoCacheDir": "添付ファイルのスナップショットを作成できません: キャッシュディレクトリが利用できません",
"snapshotFailed": "添付ファイルのスナップショットを作成できません",
"invalidUploadUrl": "サーバーから有効な添付ファイルのアップロードURLが返されませんでした。",
"noImageRead": "アップロードできる画像を読み取れませんでした。",
"emptyImage": "この画像は空のため、添付ファイルとして送信できません。",
- "imageTooLarge": "画像が {{size}} MB を超えているため、現在は添付ファイルとして送信できません。",
"imageTooLargeSend": "画像が {{size}} MB を超えているため、現在は送信できません。",
"sessionExpiredImage": "ログインの有効期限が切れました。再度ログインしてから画像をアップロードしてください。",
"sessionExpiredFile": "ログインの有効期限が切れました。再度ログインしてから添付ファイルをアップロードしてください。",
diff --git a/apps/mobile/src/i18n/locales/ko/composer.json b/apps/mobile/src/i18n/locales/ko/composer.json
index dd4e5228c8..9e157a74b1 100644
--- a/apps/mobile/src/i18n/locales/ko/composer.json
+++ b/apps/mobile/src/i18n/locales/ko/composer.json
@@ -45,7 +45,7 @@
"upload": {
"shareReceiveFailed": "공유 파일 수신을 완료하지 못했습니다. 저장 공간을 확인한 후 이 화면을 다시 열어 재시도해 주세요.",
"emptyFile": "이 파일은 비어 있어 첨부 파일로 보낼 수 없습니다.",
- "fileTooLarge": "파일이 {{size}} MB를 초과하여 지금은 첨부 파일로 보낼 수 없습니다.",
+ "fileTooLarge": "파일이 {{limit}}를 초과하여 컴퓨터와 직접 연결된 경우에만 보낼 수 있는데, 현재 직접 연결할 수 없습니다. 컴퓨터의 Cindy를 최신 버전으로 업데이트하고 앱을 화면에 켜 둔 채 다시 시도해 주세요.",
"cancelled": "첨부 파일 업로드를 취소했습니다.",
"incompleteRead": "파일 읽기가 완료되지 않았습니다. 예상: {{expected}}바이트, 실제: {{actual}}바이트.",
"integrityUnavailable": "이 첨부 파일 업로드 본문은 무결성 검사를 할 수 없습니다.",
@@ -55,13 +55,11 @@
"failedHttp": "첨부 파일 업로드에 실패했습니다: HTTP {{status}}{{code}}",
"failedNetwork": "첨부 파일 업로드에 실패했습니다. 네트워크 전송 오류입니다. 연결을 확인한 후 다시 시도하세요. ({{detail}})",
"timeout": "첨부 파일 업로드 시간이 초과되었습니다. 연결을 확인한 후 다시 시도하세요.",
- "fileTypeUnsupported": "이 로컬 파일 형식은 아직 첨부 파일로 보낼 수 없습니다.",
"snapshotFailedNoCacheDir": "첨부 파일 스냅샷을 만들 수 없습니다: 캐시 디렉터리를 사용할 수 없습니다",
"snapshotFailed": "첨부 파일 스냅샷을 만들 수 없습니다",
"invalidUploadUrl": "서버가 유효한 첨부 파일 업로드 URL을 반환하지 않았습니다.",
"noImageRead": "업로드할 이미지를 읽지 못했습니다.",
"emptyImage": "이 이미지는 비어 있어 첨부 파일로 보낼 수 없습니다.",
- "imageTooLarge": "이미지가 {{size}} MB를 초과하여 지금은 첨부 파일로 보낼 수 없습니다.",
"imageTooLargeSend": "이미지가 {{size}} MB를 초과하여 지금은 보낼 수 없습니다.",
"sessionExpiredImage": "로그인이 만료되었습니다. 다시 로그인한 후 이미지를 업로드하세요.",
"sessionExpiredFile": "로그인이 만료되었습니다. 다시 로그인한 후 첨부 파일을 업로드하세요.",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/composer.json b/apps/mobile/src/i18n/locales/zh-CN/composer.json
index 67c69362ed..223b65ec4e 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/composer.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/composer.json
@@ -45,7 +45,7 @@
"upload": {
"shareReceiveFailed": "未能完成分享文件的接收。请检查存储空间,然后重新打开此页面重试。",
"emptyFile": "这个文件为空,不能作为附件发送。",
- "fileTooLarge": "文件超过 {{size}} MB,暂不能作为附件发送。",
+ "fileTooLarge": "文件超过 {{limit}},只能在与电脑直连时发送,当前未能直连。请确认电脑端 Cindy 已更新到最新版本,并保持 App 在前台后重试。",
"cancelled": "附件上传已取消。",
"incompleteRead": "文件读取不完整:预期 {{expected}} 字节,实际 {{actual}} 字节。",
"integrityUnavailable": "当前附件上传体无法进行完整性校验。",
@@ -55,13 +55,11 @@
"failedHttp": "附件上传失败:HTTP {{status}}{{code}}",
"failedNetwork": "附件上传失败:网络传输异常,请检查网络后重试。({{detail}})",
"timeout": "附件上传超时,请检查网络后重试。",
- "fileTypeUnsupported": "这个本机文件类型暂不支持作为附件发送。",
"snapshotFailedNoCacheDir": "无法创建附件快照:缓存目录不可用",
"snapshotFailed": "无法创建附件快照",
"invalidUploadUrl": "服务端没有返回有效的附件上传地址。",
"noImageRead": "没有读取到可上传的图片。",
"emptyImage": "这个图片为空,不能作为附件发送。",
- "imageTooLarge": "图片超过 {{size}} MB,暂不能作为附件发送。",
"imageTooLargeSend": "图片超过 {{size}} MB,暂不能发送。",
"sessionExpiredImage": "登录已过期,请重新登录后再上传图片。",
"sessionExpiredFile": "登录已过期,请重新登录后再上传附件。",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/composer.json b/apps/mobile/src/i18n/locales/zh-TW/composer.json
index df1d771d10..d2b0c5b15f 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/composer.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/composer.json
@@ -45,7 +45,7 @@
"upload": {
"shareReceiveFailed": "未能完成分享檔案的接收。請檢查儲存空間,然後重新開啟此頁面重試。",
"emptyFile": "這個檔案為空,不能作為附件傳送。",
- "fileTooLarge": "檔案超過 {{size}} MB,暫不能作為附件傳送。",
+ "fileTooLarge": "檔案超過 {{limit}},只能在與電腦直連時傳送,目前未能直連。請確認電腦端 Cindy 已更新到最新版本,並保持 App 在前景後重試。",
"cancelled": "附件上傳已取消。",
"incompleteRead": "檔案讀取不完整:預期 {{expected}} 位元組,實際 {{actual}} 位元組。",
"integrityUnavailable": "當前附件上傳體無法進行完整性校驗。",
@@ -55,13 +55,11 @@
"failedHttp": "附件上傳失敗:HTTP {{status}}{{code}}",
"failedNetwork": "附件上傳失敗:網路傳輸異常,請檢查網路後重試。({{detail}})",
"timeout": "附件上傳超時,請檢查網路後重試。",
- "fileTypeUnsupported": "這個本機檔案型別暫不支援作為附件傳送。",
"snapshotFailedNoCacheDir": "無法建立附件快照:快取目錄不可用",
"snapshotFailed": "無法建立附件快照",
"invalidUploadUrl": "服務端沒有返回有效的附件上傳地址。",
"noImageRead": "沒有讀取到可上傳的圖片。",
"emptyImage": "這個圖片為空,不能作為附件傳送。",
- "imageTooLarge": "圖片超過 {{size}} MB,暫不能作為附件傳送。",
"imageTooLargeSend": "圖片超過 {{size}} MB,暫不能傳送。",
"sessionExpiredImage": "登入已過期,請重新登入後再上傳圖片。",
"sessionExpiredFile": "登入已過期,請重新登入後再上傳附件。",
diff --git a/apps/mobile/src/session/attachments.ts b/apps/mobile/src/session/attachments.ts
index 10afd0e10a..e42b2b6828 100644
--- a/apps/mobile/src/session/attachments.ts
+++ b/apps/mobile/src/session/attachments.ts
@@ -2,18 +2,34 @@ import { stripTrailingPathSeparators } from '@cindy/maker-shared/path-text';
import { i18n } from '@/i18n';
import type { RemoteFileRef, RemoteImageRef, RemoteSerializedAttachment } from '@/session/types';
import { buildLegacyAttachmentOssRef } from '@/session/attachmentOssRef';
-import { parsePeerAttachmentRef } from '@cindy/device-link';
+import { OSS_ATTACHMENT_MAX_BYTES, parsePeerAttachmentRef } from '@cindy/device-link';
export type MobileAttachmentCategory = RemoteSerializedAttachment['category'];
export const MOBILE_MAX_ATTACHMENTS = 20;
-export const MOBILE_MAX_ATTACHMENT_BYTES = 30 * 1024 * 1024;
+
+/**
+ * 与桌面一致,附件不设产品层体积上限。直连只受电脑磁盘空间约束;只有 OSS 保底中转有
+ * 服务端单对象上限,超过它的附件没有保底、只能直连发送。
+ */
+export function isWithinMobileOssAttachmentLimit(size: number): boolean {
+ return size <= OSS_ATTACHMENT_MAX_BYTES;
+}
+
+/** 走 OSS 中转前的体积校验:超限时说明只能直连发送。 */
+export function assertMobileOssAttachmentSize(size: number): void {
+ if (!isWithinMobileOssAttachmentLimit(size)) {
+ throw new Error(i18n.t('composer.upload.fileTooLarge', {
+ limit: `${Math.round(OSS_ATTACHMENT_MAX_BYTES / 1024 ** 3)} GB`,
+ }));
+ }
+}
const SUPPORTED_IMAGE_EXTS = new Set(['.jpeg', '.jpg', '.png', '.gif', '.webp']);
const SUPPORTED_DOC_EXTS = new Set(['.pdf']);
const SUPPORTED_OFFICE_EXTS = new Set(['.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx']);
-// Mirrors desktop shared/textFileExts.ts for the mobile remote-path attachment path.
+// Mirrors desktop shared/textFileExts.ts; only refines the category, never gates sending.
const SUPPORTED_TEXT_EXTS = new Set([
'.js', '.ts', '.tsx', '.jsx', '.mjs', '.cjs', '.py', '.go', '.rs', '.java',
'.c', '.cpp', '.cc', '.cxx', '.h', '.hpp', '.hh', '.cs', '.rb', '.php',
@@ -83,14 +99,11 @@ export function mergeAttachmentsWithinLimit(
return { merged, dropped };
}
-/** 本机文件附件的体积校验(乐观上传后台任务里执行,超限 throw 由失败回调呈现)。 */
+/** 本机文件附件的空文件校验(乐观上传后台任务里执行,throw 由失败回调呈现)。 */
export function assertMobileDocumentSize(size: number): void {
if (!Number.isFinite(size) || size <= 0) {
throw new Error(i18n.t('composer.upload.emptyFile'));
}
- if (size > MOBILE_MAX_ATTACHMENT_BYTES) {
- throw new Error(i18n.t('composer.upload.fileTooLarge', { size: Math.round(MOBILE_MAX_ATTACHMENT_BYTES / 1024 / 1024) }));
- }
}
export function normalizeAttachmentDraftInput(value: string): string | null {
@@ -115,20 +128,22 @@ export function extractRemoteFileExt(name: string): string {
return lower.slice(dotIdx);
}
-export function categorizeMobileAttachment(name: string): MobileAttachmentCategory | null {
+/** 与桌面 fileTypes 同口径:认不出的类型归为通用 'file',不拒收。 */
+export function categorizeMobileAttachment(name: string): MobileAttachmentCategory {
const ext = extractRemoteFileExt(name);
if (SUPPORTED_IMAGE_EXTS.has(ext)) return 'image';
if (SUPPORTED_DOC_EXTS.has(ext)) return 'pdf';
if (SUPPORTED_OFFICE_EXTS.has(ext)) return 'office';
if (SUPPORTED_TEXT_EXTS.has(ext)) return 'text';
if (!ext && KNOWN_TEXT_FILENAMES.has(name.toLowerCase())) return 'text';
- return null;
+ return 'file';
}
export function mimeTypeForMobileAttachment(
ext: string,
category: MobileAttachmentCategory,
): string {
+ if (category === 'file') return 'application/octet-stream';
if (category === 'pdf') return 'application/pdf';
if (category === 'text') return 'text/plain';
if (category === 'office') {
@@ -158,7 +173,6 @@ export function buildMobileRemoteFileAttachment(
const name = basenameRemotePath(path);
if (!name) return null;
const category = categorizeMobileAttachment(name);
- if (!category) return null;
const ext = extractRemoteFileExt(name);
return {
id: opts.id ?? `mobile-remote-file:${path}`,
@@ -181,11 +195,11 @@ export function buildMobileUploadedAttachment(input: {
id?: string;
}): RemoteSerializedAttachment | null {
if (input.peerRef ? !parsePeerAttachmentRef(input.peerRef) : !input.ossKey?.trim()) return null;
- if (!Number.isFinite(input.size) || input.size <= 0 || input.size > MOBILE_MAX_ATTACHMENT_BYTES) return null;
+ if (!Number.isSafeInteger(input.size) || input.size <= 0) return null;
+ if (!input.peerRef && !isWithinMobileOssAttachmentLimit(input.size)) return null;
const name = basenameRemotePath(input.name).trim();
if (!name) return null;
const category = categorizeMobileAttachment(name);
- if (!category) return null;
const ext = extractRemoteFileExt(name);
const mimeType = input.mimeType?.trim() || mimeTypeForMobileAttachment(ext, category);
const ref = input.peerRef ?? buildLegacyAttachmentOssRef({
diff --git a/apps/mobile/src/session/incomingShare.ts b/apps/mobile/src/session/incomingShare.ts
index 799c1cdafe..161d3deb55 100644
--- a/apps/mobile/src/session/incomingShare.ts
+++ b/apps/mobile/src/session/incomingShare.ts
@@ -250,19 +250,20 @@ export function selectIncomingShareUploadCandidates(
if (!uri || !uri.startsWith('file://')) continue;
const name = payload.originalName?.trim() || basenameFromUri(uri);
- const category = name ? categorizeMobileAttachment(name) : null;
- const isImage = payload.contentType === 'image' || payload.shareType === 'image';
- if (!name || (!category && !isImage)) {
+ if (!name) {
rejectedUris.push(uri);
continue;
}
+ const category = categorizeMobileAttachment(name);
+ const isImage = payload.contentType === 'image' || payload.shareType === 'image';
const size = typeof payload.contentSize === 'number'
&& Number.isFinite(payload.contentSize)
&& payload.contentSize > 0
? payload.contentSize
: 0;
- if (!category && isImage) {
+ // 系统判定为图片、但扩展名不是可直传的图片格式(如 HEIC):转 JPEG 后按图片发送。
+ if (category === 'file' && isImage) {
const index = candidates.length;
candidates.push({
kind: 'image',
@@ -284,7 +285,7 @@ export function selectIncomingShareUploadCandidates(
continue;
}
candidates.push({
- kind: candidateKind(category!),
+ kind: candidateKind(category),
uri,
name,
size,
diff --git a/apps/mobile/src/session/mobileAttachmentUpload.ts b/apps/mobile/src/session/mobileAttachmentUpload.ts
index e96e4706d7..720476a78a 100644
--- a/apps/mobile/src/session/mobileAttachmentUpload.ts
+++ b/apps/mobile/src/session/mobileAttachmentUpload.ts
@@ -1,5 +1,5 @@
import { apiFetchRaw } from '@/api/client';
-import { tryMobilePeerUpload } from '@/device-link/peerFileRegistry';
+import { canMobilePeerUpload, tryMobilePeerUpload } from '@/device-link/peerFileRegistry';
import { DEVICE_LINK_API_BASE_URL } from '@/config/env';
import { i18n } from '@/i18n';
import { withTransientRemoteRetry } from '@/device-link/remoteRetry';
@@ -7,7 +7,8 @@ import { isAttachmentOssRef, parseAttachmentOssRef } from '@/session/attachmentO
import {
buildMobileUploadedAttachment,
assertMobileDocumentSize,
- categorizeMobileAttachment,
+ assertMobileOssAttachmentSize,
+ isWithinMobileOssAttachmentLimit,
extractRemoteFileExt,
} from '@/session/attachments';
import type { RemoteSerializedAttachment } from '@/session/types';
@@ -215,8 +216,9 @@ async function putAttachmentWithRecovery(
rejectWait(new Error(uploadTimeoutMessage()));
controller.abort();
};
- const timer = setTimeout(expire, PUT_ATTEMPT_TIMEOUT_MS);
- // fetch 没有进度事件,保留完整单次预算;原生上传只在字节停滞时提前恢复。
+ // fetch 没有进度事件,保留完整单次预算;原生上传有进度,只在字节停滞时判超时,
+ // 不设总时限——附件不限大小,持续有进度的大文件不能被固定预算掐断。
+ const timer = reportsProgress ? undefined : setTimeout(expire, PUT_ATTEMPT_TIMEOUT_MS);
let idleTimer = setTimeout(expire, reportsProgress ? PUT_IDLE_TIMEOUT_MS : PUT_ATTEMPT_TIMEOUT_MS);
let lastBytesSent = 0;
let settled = false;
@@ -298,14 +300,10 @@ export async function uploadMobileAttachment(
body: MobileAttachmentUploadBody,
options: { token: string | null; sharedTaskId?: string; id?: string; deps?: UploadDeps },
): Promise<RemoteSerializedAttachment> {
- // 上传前先校验类型:不支持的本机文件(如 .zip)若先 presign + PUT、再在
- // buildMobileUploadedAttachment 处被拒,会在 device-link OSS 桶里留下一个永不被引用、
- // 也没有 delete 回收的孤儿对象(泄漏用户数据 + 占用存储)。类型判定复用
- // categorizeMobileAttachment 这一唯一真源,保证与下面最终校验同口径。
- if (!categorizeMobileAttachment(candidate.name)) {
- throw new Error(i18n.t('composer.upload.fileTypeUnsupported'));
- }
+ // presign 前先校验体积:超出 OSS 上限的文件若先 presign + PUT、再在
+ // buildMobileUploadedAttachment 处被拒,会在 device-link OSS 桶里留下永不被引用的孤儿对象。
assertMobileDocumentSize(candidate.size);
+ assertMobileOssAttachmentSize(candidate.size);
const sha256 = await sha256MobileAttachmentBody(body, candidate.size);
const presigned = await presignMobileAttachmentUpload(candidate, options);
await putMobileAttachmentUpload(presigned.putUrl, body, candidate.mimeType, options.deps);
@@ -318,7 +316,7 @@ export async function uploadMobileAttachment(
mimeType: candidate.mimeType,
});
if (!attachment) {
- throw new Error(i18n.t('composer.upload.fileTypeUnsupported'));
+ throw new Error(i18n.t('composer.upload.noFileRead'));
}
return attachment;
}
@@ -336,11 +334,16 @@ export async function uploadMobileAttachmentFromFile(
signal?: AbortSignal;
},
): Promise<RemoteSerializedAttachment> {
- // 同 uploadMobileAttachment:presign 前先拦不支持的类型,避免 OSS 孤儿对象。
- if (!categorizeMobileAttachment(candidate.name)) {
- throw new Error(i18n.t('composer.upload.fileTypeUnsupported'));
- }
assertMobileDocumentSize(candidate.size);
+ // 直连不设体积上限;超过 OSS 上限的附件只能直连——先确认直连可用(只查对端能力),
+ // 不可用就在快照和摘要之前失败,不白复制、白读一遍数 GB 的文件。
+ const peerCandidate = !!options.deviceId && !options.sharedTaskId;
+ if (
+ !isWithinMobileOssAttachmentLimit(candidate.size) &&
+ !(peerCandidate && await canMobilePeerUpload(options.deviceId!, candidate.size))
+ ) {
+ assertMobileOssAttachmentSize(candidate.size);
+ }
const snapshot = options.deps?.snapshotFile
? await options.deps.snapshotFile(fileUri)
: options.deps?.readFileChunk
@@ -354,15 +357,17 @@ export async function uploadMobileAttachmentFromFile(
readChunk: options.deps?.readFileChunk,
signal: options.signal,
});
- if (options.deviceId && !options.sharedTaskId) {
- const peerRef = await tryMobilePeerUpload(options.deviceId, snapshot.uri, {
+ if (peerCandidate) {
+ const peerRef = await tryMobilePeerUpload(options.deviceId!, snapshot.uri, {
size: candidate.size, sha256, mimeType: candidate.mimeType, originalName: candidate.name,
}, options.signal);
if (peerRef) {
const attachment = buildMobileUploadedAttachment({ ...candidate, sha256, peerRef, id: options.id });
- if (!attachment) throw new Error(i18n.t('composer.upload.fileTypeUnsupported'));
+ if (!attachment) throw new Error(i18n.t('composer.upload.noFileRead'));
return attachment;
}
+ // 直连没走通:OSS 保底只收上限以内的附件,presign 前拦下,避免孤儿对象。
+ assertMobileOssAttachmentSize(candidate.size);
}
const presigned = await presignMobileAttachmentUpload(candidate, options);
try {
@@ -389,7 +394,7 @@ export async function uploadMobileAttachmentFromFile(
mimeType: candidate.mimeType,
});
if (!attachment) {
- throw new Error(i18n.t('composer.upload.fileTypeUnsupported'));
+ throw new Error(i18n.t('composer.upload.noFileRead'));
}
return attachment;
} finally {
diff --git a/apps/mobile/src/session/mobileImageAttachment.ts b/apps/mobile/src/session/mobileImageAttachment.ts
index cc2be97146..d818947e53 100644
--- a/apps/mobile/src/session/mobileImageAttachment.ts
+++ b/apps/mobile/src/session/mobileImageAttachment.ts
@@ -1,5 +1,5 @@
import { i18n } from '@/i18n';
-import { MOBILE_MAX_ATTACHMENT_BYTES, extractRemoteFileExt } from '@/session/attachments';
+import { extractRemoteFileExt } from '@/session/attachments';
import type { MobileAttachmentUploadCandidate } from '@/session/mobileAttachmentUpload';
export type MobileImagePickerAssetLike = {
@@ -106,9 +106,6 @@ export function assertMobileImageSize(size: number): void {
if (!Number.isFinite(size) || size <= 0) {
throw new Error(i18n.t('composer.upload.emptyImage'));
}
- if (size > MOBILE_MAX_ATTACHMENT_BYTES) {
- throw new Error(i18n.t('composer.upload.imageTooLarge', { size: Math.round(MOBILE_MAX_ATTACHMENT_BYTES / 1024 / 1024) }));
- }
}
function normalizeImageMimeType(mimeType: string | null | undefined, uri: string): string {
diff --git a/apps/mobile/src/session/mobileImagePreprocess.ts b/apps/mobile/src/session/mobileImagePreprocess.ts
index c0c3051129..4d1bed8d65 100644
--- a/apps/mobile/src/session/mobileImagePreprocess.ts
+++ b/apps/mobile/src/session/mobileImagePreprocess.ts
@@ -42,6 +42,11 @@ export const MOBILE_IMAGE_UPLOAD_MAX_LONG_EDGE = 2048;
export const MOBILE_IMAGE_UPLOAD_JPEG_QUALITY = 0.8;
/** 文件小于此值时不值得重编码,直接原样上传。 */
export const MOBILE_IMAGE_UPLOAD_SKIP_BYTES = 400 * 1024;
+/**
+ * 文件超过此值不在手机上解码处理,原样上传:整图解码的内存随像素增长,超大图可能让进程被系统终止。
+ * 与放开附件体积前的解码范围一致(当时超过 30 MB 的图片不会进入这里)。
+ */
+export const MOBILE_IMAGE_PREPROCESS_MAX_BYTES = 30 * 1024 * 1024;
/**
* 决定一张图要不要 / 怎么在上传前处理。返回 null = 原样上传。
@@ -51,6 +56,7 @@ export function planMobileImageUploadPreprocess(
): MobileImagePreprocessPlan | null {
const mime = (input.mimeType ?? '').trim().toLowerCase();
if (mime === 'image/gif') return null;
+ if (input.size > MOBILE_IMAGE_PREPROCESS_MAX_BYTES) return null;
const width = normalizeDim(input.width);
const height = normalizeDim(input.height);
diff --git a/apps/mobile/src/session/mobileLocalAttachmentUpload.ts b/apps/mobile/src/session/mobileLocalAttachmentUpload.ts
index 5cc38ad57b..6b433d1ed9 100644
--- a/apps/mobile/src/session/mobileLocalAttachmentUpload.ts
+++ b/apps/mobile/src/session/mobileLocalAttachmentUpload.ts
@@ -398,10 +398,15 @@ export function createMobileLocalAttachmentUploadController(
const interrupted = new Promise<never>((_resolve, reject) => { rejectWait = reject; });
const onAbort = () => rejectWait(new Error(i18n.t(timedOut ? 'composer.upload.timeout' : 'composer.upload.cancelled')));
signal.addEventListener('abort', onAbort);
- const timer = setTimeout(() => {
- timedOut = true;
- task.abort.abort();
- }, 180_000);
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const armTimeout = () => {
+ clearTimeout(timer);
+ timer = setTimeout(() => {
+ timedOut = true;
+ task.abort.abort();
+ }, 180_000);
+ };
+ armTimeout();
const step = <T>(value: T | Promise<T>, late?: (result: T) => void): Promise<T> => Promise.race([
Promise.resolve(value).then((result) => {
if (signal.aborted) late?.(result);
@@ -434,11 +439,15 @@ export function createMobileLocalAttachmentUploadController(
outcome = 'discarded';
return;
}
+ // 上传阶段不受总时限约束:附件不限大小,传输层各自按无进度/单次请求判超时
+ //(OSS 60 秒无进度、直连逐请求超时、presign 12 秒),用户取消仍即时生效。
+ clearTimeout(timer);
const attachment = uploadedAttachment = await step(deps.upload(
{ name: prepared.name, size, mimeType: prepared.mimeType || undefined, ...(source.sharedTaskId ? { sharedTaskId: source.sharedTaskId } : {}), ...(source.deviceId ? { deviceId: source.deviceId } : {}) },
prepared.uri,
{ token, signal },
), (late) => deps.discard(late, token));
+ armTimeout();
if (task.handoff) await task.handoff.promise;
task.delivering = true;
if (task.discarded) {
diff --git a/apps/mobile/src/session/types.ts b/apps/mobile/src/session/types.ts
index 14e90cb0cb..8017735d59 100644
--- a/apps/mobile/src/session/types.ts
+++ b/apps/mobile/src/session/types.ts
@@ -126,7 +126,7 @@ export interface RemoteMessage {
| 'help' | 'context' | 'cost' | 'pwd' | 'status' | 'compact' | 'cmd' | 'goal-complete' | 'goal-resumed' | 'context-rebuild' | 'auto-resume' | 'learn' | 'agent-switch';
}
-export type RemoteAttachmentCategory = 'image' | 'pdf' | 'text' | 'office';
+export type RemoteAttachmentCategory = 'image' | 'pdf' | 'text' | 'office' | 'file';
export interface RemoteFileRef {
name: string;
diff --git a/apps/mobile/src/session/useComposerImageAnnotations.ts b/apps/mobile/src/session/useComposerImageAnnotations.ts
index 8cfb6cf86e..7ffee6bbfc 100644
--- a/apps/mobile/src/session/useComposerImageAnnotations.ts
+++ b/apps/mobile/src/session/useComposerImageAnnotations.ts
@@ -37,13 +37,19 @@ import {
type AnnotationBurnSourcePlan,
type AnnotationStroke,
} from '@/session/imageAnnotationModel';
-import { MOBILE_MAX_ATTACHMENTS, MOBILE_MAX_ATTACHMENT_BYTES } from '@/session/attachments';
+import { MOBILE_MAX_ATTACHMENTS } from '@/session/attachments';
import type { ImageLightboxAnnotationConfig } from '@/session/ImageLightbox';
import type {
MobileLocalAttachmentUploadCandidate,
} from '@/session/mobileLocalAttachmentUpload';
import type { RemoteSerializedAttachment } from '@/session/types';
+/**
+ * 标注烧录要把整张图 base64 读进 JS 内存,这是防 OOM 的上限,与附件本身的发送上限无关
+ *(附件与桌面一致只受传输通道限制)。
+ */
+const ANNOTATION_SOURCE_MAX_BYTES = 30 * 1024 * 1024;
+
/** 标注附件的再编辑真相(attachmentId → 矢量笔迹 + 原图)。 */
interface AnnotationEditMeta {
strokes: AnnotationStroke[];
@@ -296,7 +302,7 @@ export function useComposerImageAnnotations(
if (
!isAnnotationBurnSourceResultUsable(plan, result, hint)
|| !(resultSize > 0)
- || resultSize > MOBILE_MAX_ATTACHMENT_BYTES
+ || resultSize > ANNOTATION_SOURCE_MAX_BYTES
) {
void FileSystem.deleteAsync(result.uri, { idempotent: true }).catch(() => undefined);
return original;
@@ -329,8 +335,8 @@ export function useComposerImageAnnotations(
const size = info.exists && typeof info.size === 'number' && Number.isFinite(info.size)
? info.size
: 0;
- if (size > MOBILE_MAX_ATTACHMENT_BYTES) {
- throw new Error(t('composer.upload.imageTooLargeSend', { size: Math.round(MOBILE_MAX_ATTACHMENT_BYTES / 1024 / 1024) }));
+ if (size > ANNOTATION_SOURCE_MAX_BYTES) {
+ throw new Error(t('composer.upload.imageTooLargeSend', { size: Math.round(ANNOTATION_SOURCE_MAX_BYTES / 1024 / 1024) }));
}
const head = await FileSystem.readAsStringAsync(fileUri, {
encoding: FileSystem.EncodingType.Base64,
diff --git a/apps/mobile/src/session/useMobileLocalAttachments.ts b/apps/mobile/src/session/useMobileLocalAttachments.ts
index 2c1bd991a8..a9addf46af 100644
--- a/apps/mobile/src/session/useMobileLocalAttachments.ts
+++ b/apps/mobile/src/session/useMobileLocalAttachments.ts
@@ -26,7 +26,6 @@ import { canBrowsePhotoLibraryDirectly } from '@/session/photoLibraryPolicy';
import {
MOBILE_MAX_ATTACHMENTS,
assertMobileDocumentSize,
- categorizeMobileAttachment,
} from '@/session/attachments';
import { assertMobileImageSize, buildMobileImageAttachmentCandidate } from '@/session/mobileImageAttachment';
import { preprocessMobileImageForUpload } from '@/session/mobileImagePreprocess';
@@ -510,13 +509,6 @@ export function useMobileLocalAttachments(
optionsRef.current.onError(t('composer.upload.noFileRead'));
return;
}
- // 类型白名单同步校验:不支持的类型即时报错,不进托盘、不触发上传
- // (上传层还有同口径兜底,防 OSS 孤儿)。
- if (!categorizeMobileAttachment(name)) {
- optionsRef.current.onError(t('composer.upload.fileTypeUnsupported'));
- return;
- }
-
const size = typeof asset.size === 'number' && Number.isFinite(asset.size) && asset.size > 0
? asset.size
: 0;
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 74a508273c..f96d266380 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -203,6 +203,22 @@ link-accept 双向声明,不改 relay)。Desktop 控制端在本机没有订
Mobile 以同一归纳算法在上传后的附件(含持久发件箱 `DurableUpload`,可选字段、旧记录缺省)
上携带该字段;底图本身已是烧录图、旧红线位置不可知时不带区域。服务端无需改动。
+## 附件类型与直连附件体积
+
+Mobile 发送的队列附件(`RemoteSerializedAttachment.category`)与 Desktop `AgentInputFileCategory`
+对齐,追加 `'file'`:认不出的扩展名不再拒收,按通用文件以 `application/octet-stream` 上传。
+主机只按 `category === 'image'` 分流,其余一律作为文件路径交给 Agent,并以 `originalName`
+落地保留扩展名,新旧主机都已认得 `'file'`。
+
+附件不设产品层体积上限。直连附件(`cindy-peer-attach://`)的引用去掉固定 2GB 上限,只要求
+安全整数;接收端不设收件箱总量上限,只按剩余磁盘空间准入(未写完的上传按剩余待写字节预留)。
+OSS 保底仍受服务端 presign 单对象上限(`OSS_ATTACHMENT_MAX_BYTES`,2GB),超过它的附件
+没有保底,只能直连发送。`device-link:file-peer` 的 `caps` 追加可选 `largeAttachments: true`;
+发送端(Mobile 与 Desktop 控制端)仅在对端声明该能力时直连超过 2GB 的附件,旧主机未声明时
+直接放弃直连且不计入失败冷却,随后按 OSS 上限提示失败。旧控制端忽略新增字段,行为不变。
+文件读取(`open`)仍沿用 `FILE_PEER_MAX_BYTES`。不新增 channel、relay 类型或持久化 schema,
+服务端无需改动。
+
## 事实来源
| 内容 | 权威来源 |
diff --git a/packages/device-link/src/__tests__/peerAcceleration.test.ts b/packages/device-link/src/__tests__/peerAcceleration.test.ts
index e8013a0814..675c65866b 100644
--- a/packages/device-link/src/__tests__/peerAcceleration.test.ts
+++ b/packages/device-link/src/__tests__/peerAcceleration.test.ts
@@ -5,6 +5,7 @@ import { REMOTE_DESKTOP_CHANNEL } from "../remoteDesktop.js";
import {
uploadPeerAttachment,
parsePeerAttachmentRef,
+ peerAttachmentFinishTimeoutMs,
buildPeerAttachmentRef,
} from "../peerAttachment.js";
@@ -66,9 +67,11 @@ describe("peer acceleration policy", () => {
it("finishes byte staging before returning a reference; cancellation never finishes", async () => {
const ticket = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
const metadata = { size: 1, sha256: "a".repeat(64), originalName: "a.txt" };
- const invoke = vi.fn(async (_request: Record<string, unknown>) => ({
- ticket,
- }));
+ const invoke = vi.fn(
+ async (_request: Record<string, unknown>, _timeoutMs?: number) => ({
+ ticket,
+ }),
+ );
const ref = await uploadPeerAttachment(
metadata,
async () => "YQ==",
@@ -81,7 +84,21 @@ describe("peer acceleration policy", () => {
"write",
"finish",
]);
+ // 只有 finish(接收端整读重算摘要)按体积放宽等待,其余请求用默认超时。
+ expect(invoke.mock.calls.map(([, timeoutMs]) => timeoutMs)).toEqual([
+ undefined,
+ undefined,
+ peerAttachmentFinishTimeoutMs(metadata.size),
+ ]);
+ expect(peerAttachmentFinishTimeoutMs(1)).toBe(16_000);
+ expect(peerAttachmentFinishTimeoutMs(10 * 1024 ** 3)).toBe(15_000 + 512_000);
expect(parsePeerAttachmentRef("cindy-peer-attach://bad")).toBeNull();
+ // 直连附件不设固定体积上限(只受接收端磁盘约束),但仍要求安全整数。
+ const large = { ...metadata, size: 64 * 1024 ** 3, ticket };
+ expect(parsePeerAttachmentRef(buildPeerAttachmentRef(large))).toEqual(large);
+ expect(() =>
+ buildPeerAttachmentRef({ ...metadata, size: Number.MAX_SAFE_INTEGER + 1, ticket }),
+ ).toThrow();
expect(() =>
buildPeerAttachmentRef({ ...metadata, ticket: "../evil" }),
).toThrow();
diff --git a/packages/device-link/src/filePeerRuntime.ts b/packages/device-link/src/filePeerRuntime.ts
index bb0be1de13..db3fee4b4b 100644
--- a/packages/device-link/src/filePeerRuntime.ts
+++ b/packages/device-link/src/filePeerRuntime.ts
@@ -12,6 +12,13 @@ export interface FilePeerRuntimeBridge {
* V2 keeps a bounded 1 MiB credit window in flight; disk writes replenish credit.
* V1 remains available for peers that did not advertise streaming support.
*/
+/** 调用方只能在默认 15 秒与 1 小时之间放宽单次 RPC 等待(大附件 finish 要整读重算摘要)。 */
+function rpcTimeoutMs(value: unknown): number {
+ return Number.isSafeInteger(value) && (value as number) > 15000
+ ? Math.min(value as number, 60 * 60_000)
+ : 15000;
+}
+
export function createFilePeerRuntime(bridge: FilePeerRuntimeBridge) {
const peers = new Map<
string,
@@ -23,7 +30,7 @@ export function createFilePeerRuntime(bridge: FilePeerRuntimeBridge) {
string,
{
channel: RTCDataChannel;
- request(payload: string): Promise<string>;
+ request(payload: string, timeoutMs?: number): Promise<string>;
close(): void;
}
>();
@@ -117,15 +124,18 @@ export function createFilePeerRuntime(bridge: FilePeerRuntimeBridge) {
rpcPeers.set(id, {
channel: dc,
close: shutdown,
- request(payload) {
+ request(payload, timeoutMs) {
if (pending.size >= 4 || dc.readyState !== "open")
return Promise.reject(new Error("FILE_PEER_UNAVAILABLE"));
return new Promise((resolve, reject) => {
const key = String(++sequence);
- const timer = setTimeout(() => {
- pending.delete(key);
- reject(new Error("FILE_PEER_TIMEOUT"));
- }, 15000);
+ 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);
@@ -510,10 +520,10 @@ export function createFilePeerRuntime(bridge: FilePeerRuntimeBridge) {
}
}
return {
- async invoke(id: string, payload: string) {
+ async invoke(id: string, payload: string, timeoutMs?: number) {
const rpc = rpcPeers.get(id);
if (!rpc) throw new Error("FILE_PEER_UNAVAILABLE");
- return rpc.request(payload);
+ return rpc.request(payload, timeoutMs);
},
async stats(id: string) {
const p = peers.get(id);
diff --git a/packages/device-link/src/filePeerRuntimeSource.ts b/packages/device-link/src/filePeerRuntimeSource.ts
index b6cedf6336..ff0370487e 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 O=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var $=Object.prototype.hasOwnProperty;var V=(u,f)=>{for(var p in f)O(u,p,{get:f[p],enumerable:!0})},x=(u,f,p,v)=>{if(f&&typeof f==\"object\"||typeof f==\"function\")for(let g of Z(f))!$.call(u,g)&&g!==p&&O(u,g,{get:()=>f[g],enumerable:!(v=K(f,g))||v.enumerable});return u};var G=u=>x(O({},\"__esModule\",{value:!0}),u);var Y={};V(Y,{createFilePeerRuntime:()=>j});function j(u){let f=new Map,p=16384,v=2147483648,g=new Map;function k(e,a){let o=new Map,r=new Map,i=0,n=0,c=(s,t,E)=>{if(E.length>4*1024*1024||a.readyState!==\"open\")throw new Error(\"FILE_PEER_RPC_SIZE\");for(let l=0;l<Math.max(1,E.length);l+=16384)a.send(JSON.stringify({key:s,response:t,data:E.slice(l,l+16384),last:l+16384>=E.length}))},d=()=>{for(let s of o.values())clearTimeout(s.timer),s.reject(new Error(\"FILE_PEER_CLOSED\"));for(let s of r.values())clearTimeout(s.timer);o.clear(),r.clear(),a.close()};a.onclose=d,a.onmessage=({data:s})=>{try{if(typeof s!=\"string\"||s.length>1e5)throw new Error;let t=JSON.parse(s);if(typeof t.key!=\"string\"||!/^\\d{1,12}$/.test(t.key)||typeof t.response!=\"boolean\"||typeof t.last!=\"boolean\"||typeof t.data!=\"string\"||t.data.length>16384)throw new Error;if(t.response&&!o.has(t.key))return;let E=`${t.response}:${t.key}`,l=r.get(E);if(!l){if(r.size>=8)throw new Error;l={data:\"\",timer:setTimeout(()=>w(e),15e3)},r.set(E,l)}if(l.data+=t.data,l.data.length>4*1024*1024)throw new Error;if(!t.last)return;if(clearTimeout(l.timer),r.delete(E),t.response){let m=o.get(t.key);o.delete(t.key),clearTimeout(m.timer),m.resolve(l.data)}else{if(!u.invoke||n>=4)throw new Error;n++,u.invoke(e,l.data).then(m=>{f.has(e)&&c(t.key,!0,m)}).catch(()=>w(e)).finally(()=>{n--})}}catch{w(e)}},g.set(e,{channel:a,close:d,request(s){return o.size>=4||a.readyState!==\"open\"?Promise.reject(new Error(\"FILE_PEER_UNAVAILABLE\")):new Promise((t,E)=>{let l=String(++i),m=setTimeout(()=>{o.delete(l),E(new Error(\"FILE_PEER_TIMEOUT\"))},15e3);o.set(l,{resolve:t,reject:E,timer:m});try{c(l,!1,s)}catch(y){o.delete(l),clearTimeout(m),E(y)}})}})}function w(e){let a=g.get(e);g.delete(e),a?.close();let o=f.get(e);f.delete(e),o?.dc?.close(),o?.pc.close()}function D(e,a){if(f.has(e)||f.size>=4)throw new Error(\"FILE_PEER_BUSY\");let o=new RTCPeerConnection({iceServers:a}),r={pc:o,dc:null,busy:!1};return f.set(e,r),o.onconnectionstatechange=()=>{[\"failed\",\"closed\",\"disconnected\"].includes(o.connectionState)&&w(e)},r}async function A(e,a){if(await e.setLocalDescription(a),e.iceGatheringState!==\"complete\"&&await new Promise(o=>{let r=setTimeout(i,4e3);function i(){clearTimeout(r),e.removeEventListener(\"icegatheringstatechange\",n),o()}function n(){e.iceGatheringState===\"complete\"&&i()}e.addEventListener(\"icegatheringstatechange\",n),n()}),!e.localDescription?.sdp||e.signalingState===\"closed\")throw new Error(\"FILE_PEER_CLOSED\");return e.localDescription.sdp}function M(e){if(e.length>22e3||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw new Error(\"FILE_PEER_BLOCK\");let a=atob(e);if(a.length>p)throw new Error(\"FILE_PEER_BLOCK\");return Uint8Array.from(a,o=>o.charCodeAt(0))}async function N(e,a,o=!1){let r=D(e,a);r.dc=r.pc.createDataChannel(o?\"files-v2\":\"files-v1\",{ordered:!0}),r.dc.binaryType=\"arraybuffer\",o&&k(e,r.pc.createDataChannel(\"reads-v1\",{ordered:!0}));try{return await A(r.pc,await r.pc.createOffer())}catch(i){throw w(e),i}}async function U(e,a,o){let r=D(e,a);r.pc.ondatachannel=({channel:i})=>{if(i.label===\"reads-v1\"&&!g.has(e)){k(e,i);return}if(![\"files-v1\",\"files-v2\"].includes(i.label)||r.dc){i.close();return}if(r.dc=i,i.binaryType=\"arraybuffer\",i.label===\"files-v2\"){let n,c=!1,d=async()=>{if(!c){c=!0;try{for(;n&&n.credit>0;){let s=n;s.credit--;let t=M(await u.read(e,s.ticket,s.offset));if(f.get(e)!==r||i.readyState!==\"open\")return;i.send(t.buffer),s.offset+=t.length,t.length||(n=void 0)}}catch{w(e)}finally{c=!1}}};i.onmessage=({data:s})=>{try{if(typeof s!=\"string\"||s.length>256)throw new Error;let t=JSON.parse(s);if(!Number.isSafeInteger(t.credit)||t.credit<1||t.credit>64)throw new Error;if(t.ticket!==void 0){if(n||!/^[a-f0-9-]{36}$/.test(t.ticket)||t.offset!==0)throw new Error;n={ticket:t.ticket,offset:0,credit:t.credit}}else{if(!n||n.credit+t.credit>64)throw new Error;n.credit+=t.credit}d()}catch{w(e)}};return}i.onmessage=async({data:n})=>{try{if(f.get(e)!==r||r.busy||typeof n!=\"string\"||n.length>256)throw new Error(\"FILE_PEER_BLOCK\");let c=JSON.parse(n);if(!/^[a-f0-9-]{36}$/.test(c.ticket)||!Number.isSafeInteger(c.offset)||c.offset<0||c.offset>v||c.credit!==16)throw new Error(\"FILE_PEER_BLOCK\");r.busy=!0;let d=c.offset;for(let s=0;s<16;s++){let t=M(await u.read(e,c.ticket,d));if(f.get(e)!==r||i.readyState!==\"open\")return;if(i.send(t.buffer),d+=t.length,!t.length)break}}catch{w(e)}finally{r.busy=!1}}};try{return await r.pc.setRemoteDescription({type:\"offer\",sdp:o}),await A(r.pc,await r.pc.createAnswer())}catch(i){throw w(e),i}}async function J(e,a){let o=f.get(e);if(!o)throw new Error(\"FILE_PEER_CLOSED\");await o.pc.setRemoteDescription({type:\"answer\",sdp:a}),await Promise.all([o.dc,g.get(e)?.channel].filter(r=>!!r).map(r=>new Promise((i,n)=>{let c=setTimeout(()=>d(new Error(\"FILE_PEER_TIMEOUT\")),8e3);function d(E){clearTimeout(c),r.removeEventListener(\"open\",s),r.removeEventListener(\"close\",t),E?n(E):i()}function s(){d()}function t(){d(new Error(\"FILE_PEER_CLOSED\"))}r.addEventListener(\"open\",s),r.addEventListener(\"close\",t),r.readyState===\"open\"?d():r.readyState===\"closed\"&&t()})))}async function q(e,a,o,r){let i=f.get(e),n=i?.dc;if(!i||!n||n.readyState!==\"open\"||i.busy||!Number.isSafeInteger(o)||o<0||o>v)throw new Error(\"FILE_PEER_UNAVAILABLE\");i.busy=!0;try{if(n.label===\"files-v2\"){await new Promise((d,s)=>{let t=0,E=0,l=0,m=0,y=Math.ceil(o/p)+1,L=Math.min(64,y),C=!1,h=!1,T=Promise.resolve(),b=setTimeout(()=>R(new Error(\"FILE_PEER_TIMEOUT\")),6e4);function R(I){h||(h=!0,clearTimeout(b),n.removeEventListener(\"message\",B),n.removeEventListener(\"close\",F),I?s(I):d())}function F(){R(new Error(\"FILE_PEER_CLOSED\"))}function B(I){if(C||!(I.data instanceof ArrayBuffer)||++l>64){R(new Error(\"FILE_PEER_BLOCK\"));return}let _=new Uint8Array(I.data);if(_.length!==Math.min(p,o-t)){R(new Error(\"FILE_PEER_SIZE\"));return}t+=_.length,C=_.length===0,T=T.then(async()=>{if(h)return;if(!_.length){R();return}let P=\"\";for(let S of _)P+=String.fromCharCode(S);if(await u.write(r,E,btoa(P)),!h){if(f.get(e)!==i)throw new Error(\"FILE_PEER_CLOSED\");if(E+=_.length,l--,clearTimeout(b),b=setTimeout(()=>R(new Error(\"FILE_PEER_TIMEOUT\")),6e4),++m===32&&L<y){let S=Math.min(32,y-L);n.send(JSON.stringify({credit:S})),L+=S,m=0}}}).catch(P=>R(P))}n.addEventListener(\"message\",B),n.addEventListener(\"close\",F);try{n.send(JSON.stringify({ticket:a,offset:0,credit:L}))}catch{F()}});return}let c=0;for(;c<=o;){let d=await new Promise((s,t)=>{let E=[],l=c,m=setTimeout(()=>y(new Error(\"FILE_PEER_TIMEOUT\")),6e4);function y(h){clearTimeout(m),n.removeEventListener(\"message\",C),n.removeEventListener(\"close\",L),h?t(h):s(E)}function L(){y(new Error(\"FILE_PEER_CLOSED\"))}function C(h){if(!(h.data instanceof ArrayBuffer)){y(new Error(\"FILE_PEER_BLOCK\"));return}let T=new Uint8Array(h.data);if(T.length!==Math.min(p,o-l)){y(new Error(\"FILE_PEER_SIZE\"));return}E.push(T),l+=T.length,(!T.length||E.length===16)&&y()}n.addEventListener(\"message\",C),n.addEventListener(\"close\",L);try{n.send(JSON.stringify({ticket:a,offset:c,credit:16}))}catch{L()}});for(let s of d){if(!s.length)return;let t=\"\";for(let E of s)t+=String.fromCharCode(E);if(await u.write(r,c,btoa(t)),f.get(e)!==i)throw new Error(\"FILE_PEER_CLOSED\");c+=s.length}}}catch(c){throw w(e),c}finally{i.busy=!1}}return{async invoke(e,a){let o=g.get(e);if(!o)throw new Error(\"FILE_PEER_UNAVAILABLE\");return o.request(a)},async stats(e){let a=f.get(e);if(!a)throw new Error(\"FILE_PEER_CLOSED\");let o=await a.pc.getStats(),r=new Map;o.forEach(s=>r.set(s.id,s));let i;o.forEach(s=>{s.type===\"transport\"&&s.selectedCandidatePairId&&(i=r.get(s.selectedCandidatePairId))});let n=i,c=n?.localCandidateId?r.get(n.localCandidateId):void 0,d=n?.remoteCandidateId?r.get(n.remoteCandidateId):void 0;return JSON.stringify({path:n?c?.candidateType===\"relay\"||d?.candidateType===\"relay\"?\"relay\":\"direct\":\"unknown\",protocol:c?.protocol??\"unknown\",rttMs:typeof n?.currentRoundTripTime==\"number\"?Math.round(n.currentRoundTripTime*1e3):null,streaming:a.dc?.label===\"files-v2\"})},offer:N,accept:U,answer:J,receive:q,close:w,dispose:()=>{for(let e of f.keys())w(e)}}}return G(Y);})();\n";
+export const FILE_PEER_RUNTIME_SOURCE = "\"use strict\";var CindyFilePeerRuntime=(()=>{var k=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var $=Object.prototype.hasOwnProperty;var V=(u,f)=>{for(var L in f)k(u,L,{get:f[L],enumerable:!0})},x=(u,f,L,C)=>{if(f&&typeof f==\"object\"||typeof f==\"function\")for(let m of Z(f))!$.call(u,m)&&m!==L&&k(u,m,{get:()=>f[m],enumerable:!(C=K(f,m))||C.enumerable});return u};var G=u=>x(k({},\"__esModule\",{value:!0}),u);var z={};V(z,{createFilePeerRuntime:()=>Y});function j(u){return Number.isSafeInteger(u)&&u>15e3?Math.min(u,60*6e4):15e3}function Y(u){let f=new Map,L=16384,C=2147483648,m=new Map;function O(e,a){let o=new Map,t=new Map,i=0,n=0,c=(s,r,E)=>{if(E.length>4*1024*1024||a.readyState!==\"open\")throw new Error(\"FILE_PEER_RPC_SIZE\");for(let l=0;l<Math.max(1,E.length);l+=16384)a.send(JSON.stringify({key:s,response:r,data:E.slice(l,l+16384),last:l+16384>=E.length}))},d=()=>{for(let s of o.values())clearTimeout(s.timer),s.reject(new Error(\"FILE_PEER_CLOSED\"));for(let s of t.values())clearTimeout(s.timer);o.clear(),t.clear(),a.close()};a.onclose=d,a.onmessage=({data:s})=>{try{if(typeof s!=\"string\"||s.length>1e5)throw new Error;let r=JSON.parse(s);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&&!o.has(r.key))return;let E=`${r.response}:${r.key}`,l=t.get(E);if(!l){if(t.size>=8)throw new Error;l={data:\"\",timer:setTimeout(()=>w(e),15e3)},t.set(E,l)}if(l.data+=r.data,l.data.length>4*1024*1024)throw new Error;if(!r.last)return;if(clearTimeout(l.timer),t.delete(E),r.response){let g=o.get(r.key);o.delete(r.key),clearTimeout(g.timer),g.resolve(l.data)}else{if(!u.invoke||n>=4)throw new Error;n++,u.invoke(e,l.data).then(g=>{f.has(e)&&c(r.key,!0,g)}).catch(()=>w(e)).finally(()=>{n--})}}catch{w(e)}},m.set(e,{channel:a,close:d,request(s,r){return o.size>=4||a.readyState!==\"open\"?Promise.reject(new Error(\"FILE_PEER_UNAVAILABLE\")):new Promise((E,l)=>{let g=String(++i),h=setTimeout(()=>{o.delete(g),l(new Error(\"FILE_PEER_TIMEOUT\"))},j(r));o.set(g,{resolve:E,reject:l,timer:h});try{c(g,!1,s)}catch(y){o.delete(g),clearTimeout(h),l(y)}})}})}function w(e){let a=m.get(e);m.delete(e),a?.close();let o=f.get(e);f.delete(e),o?.dc?.close(),o?.pc.close()}function M(e,a){if(f.has(e)||f.size>=4)throw new Error(\"FILE_PEER_BUSY\");let o=new RTCPeerConnection({iceServers:a}),t={pc:o,dc:null,busy:!1};return f.set(e,t),o.onconnectionstatechange=()=>{[\"failed\",\"closed\",\"disconnected\"].includes(o.connectionState)&&w(e)},t}async function D(e,a){if(await e.setLocalDescription(a),e.iceGatheringState!==\"complete\"&&await new Promise(o=>{let t=setTimeout(i,4e3);function i(){clearTimeout(t),e.removeEventListener(\"icegatheringstatechange\",n),o()}function n(){e.iceGatheringState===\"complete\"&&i()}e.addEventListener(\"icegatheringstatechange\",n),n()}),!e.localDescription?.sdp||e.signalingState===\"closed\")throw new Error(\"FILE_PEER_CLOSED\");return e.localDescription.sdp}function A(e){if(e.length>22e3||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw new Error(\"FILE_PEER_BLOCK\");let a=atob(e);if(a.length>L)throw new Error(\"FILE_PEER_BLOCK\");return Uint8Array.from(a,o=>o.charCodeAt(0))}async function N(e,a,o=!1){let t=M(e,a);t.dc=t.pc.createDataChannel(o?\"files-v2\":\"files-v1\",{ordered:!0}),t.dc.binaryType=\"arraybuffer\",o&&O(e,t.pc.createDataChannel(\"reads-v1\",{ordered:!0}));try{return await D(t.pc,await t.pc.createOffer())}catch(i){throw w(e),i}}async function U(e,a,o){let t=M(e,a);t.pc.ondatachannel=({channel:i})=>{if(i.label===\"reads-v1\"&&!m.has(e)){O(e,i);return}if(![\"files-v1\",\"files-v2\"].includes(i.label)||t.dc){i.close();return}if(t.dc=i,i.binaryType=\"arraybuffer\",i.label===\"files-v2\"){let n,c=!1,d=async()=>{if(!c){c=!0;try{for(;n&&n.credit>0;){let s=n;s.credit--;let r=A(await u.read(e,s.ticket,s.offset));if(f.get(e)!==t||i.readyState!==\"open\")return;i.send(r.buffer),s.offset+=r.length,r.length||(n=void 0)}}catch{w(e)}finally{c=!1}}};i.onmessage=({data:s})=>{try{if(typeof s!=\"string\"||s.length>256)throw new Error;let r=JSON.parse(s);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}}else{if(!n||n.credit+r.credit>64)throw new Error;n.credit+=r.credit}d()}catch{w(e)}};return}i.onmessage=async({data:n})=>{try{if(f.get(e)!==t||t.busy||typeof n!=\"string\"||n.length>256)throw new Error(\"FILE_PEER_BLOCK\");let c=JSON.parse(n);if(!/^[a-f0-9-]{36}$/.test(c.ticket)||!Number.isSafeInteger(c.offset)||c.offset<0||c.offset>C||c.credit!==16)throw new Error(\"FILE_PEER_BLOCK\");t.busy=!0;let d=c.offset;for(let s=0;s<16;s++){let r=A(await u.read(e,c.ticket,d));if(f.get(e)!==t||i.readyState!==\"open\")return;if(i.send(r.buffer),d+=r.length,!r.length)break}}catch{w(e)}finally{t.busy=!1}}};try{return await t.pc.setRemoteDescription({type:\"offer\",sdp:o}),await D(t.pc,await t.pc.createAnswer())}catch(i){throw w(e),i}}async function J(e,a){let o=f.get(e);if(!o)throw new Error(\"FILE_PEER_CLOSED\");await o.pc.setRemoteDescription({type:\"answer\",sdp:a}),await Promise.all([o.dc,m.get(e)?.channel].filter(t=>!!t).map(t=>new Promise((i,n)=>{let c=setTimeout(()=>d(new Error(\"FILE_PEER_TIMEOUT\")),8e3);function d(E){clearTimeout(c),t.removeEventListener(\"open\",s),t.removeEventListener(\"close\",r),E?n(E):i()}function s(){d()}function r(){d(new Error(\"FILE_PEER_CLOSED\"))}t.addEventListener(\"open\",s),t.addEventListener(\"close\",r),t.readyState===\"open\"?d():t.readyState===\"closed\"&&r()})))}async function q(e,a,o,t){let i=f.get(e),n=i?.dc;if(!i||!n||n.readyState!==\"open\"||i.busy||!Number.isSafeInteger(o)||o<0||o>C)throw new Error(\"FILE_PEER_UNAVAILABLE\");i.busy=!0;try{if(n.label===\"files-v2\"){await new Promise((d,s)=>{let r=0,E=0,l=0,g=0,h=Math.ceil(o/L)+1,y=Math.min(64,h),I=!1,p=!1,T=Promise.resolve(),S=setTimeout(()=>_(new Error(\"FILE_PEER_TIMEOUT\")),6e4);function _(v){p||(p=!0,clearTimeout(S),n.removeEventListener(\"message\",B),n.removeEventListener(\"close\",F),v?s(v):d())}function F(){_(new Error(\"FILE_PEER_CLOSED\"))}function B(v){if(I||!(v.data instanceof ArrayBuffer)||++l>64){_(new Error(\"FILE_PEER_BLOCK\"));return}let R=new Uint8Array(v.data);if(R.length!==Math.min(L,o-r)){_(new Error(\"FILE_PEER_SIZE\"));return}r+=R.length,I=R.length===0,T=T.then(async()=>{if(p)return;if(!R.length){_();return}let b=\"\";for(let P of R)b+=String.fromCharCode(P);if(await u.write(t,E,btoa(b)),!p){if(f.get(e)!==i)throw new Error(\"FILE_PEER_CLOSED\");if(E+=R.length,l--,clearTimeout(S),S=setTimeout(()=>_(new Error(\"FILE_PEER_TIMEOUT\")),6e4),++g===32&&y<h){let P=Math.min(32,h-y);n.send(JSON.stringify({credit:P})),y+=P,g=0}}}).catch(b=>_(b))}n.addEventListener(\"message\",B),n.addEventListener(\"close\",F);try{n.send(JSON.stringify({ticket:a,offset:0,credit:y}))}catch{F()}});return}let c=0;for(;c<=o;){let d=await new Promise((s,r)=>{let E=[],l=c,g=setTimeout(()=>h(new Error(\"FILE_PEER_TIMEOUT\")),6e4);function h(p){clearTimeout(g),n.removeEventListener(\"message\",I),n.removeEventListener(\"close\",y),p?r(p):s(E)}function y(){h(new Error(\"FILE_PEER_CLOSED\"))}function I(p){if(!(p.data instanceof ArrayBuffer)){h(new Error(\"FILE_PEER_BLOCK\"));return}let T=new Uint8Array(p.data);if(T.length!==Math.min(L,o-l)){h(new Error(\"FILE_PEER_SIZE\"));return}E.push(T),l+=T.length,(!T.length||E.length===16)&&h()}n.addEventListener(\"message\",I),n.addEventListener(\"close\",y);try{n.send(JSON.stringify({ticket:a,offset:c,credit:16}))}catch{y()}});for(let s of d){if(!s.length)return;let r=\"\";for(let E of s)r+=String.fromCharCode(E);if(await u.write(t,c,btoa(r)),f.get(e)!==i)throw new Error(\"FILE_PEER_CLOSED\");c+=s.length}}}catch(c){throw w(e),c}finally{i.busy=!1}}return{async invoke(e,a,o){let t=m.get(e);if(!t)throw new Error(\"FILE_PEER_UNAVAILABLE\");return t.request(a,o)},async stats(e){let a=f.get(e);if(!a)throw new Error(\"FILE_PEER_CLOSED\");let o=await a.pc.getStats(),t=new Map;o.forEach(s=>t.set(s.id,s));let i;o.forEach(s=>{s.type===\"transport\"&&s.selectedCandidatePairId&&(i=t.get(s.selectedCandidatePairId))});let n=i,c=n?.localCandidateId?t.get(n.localCandidateId):void 0,d=n?.remoteCandidateId?t.get(n.remoteCandidateId):void 0;return JSON.stringify({path:n?c?.candidateType===\"relay\"||d?.candidateType===\"relay\"?\"relay\":\"direct\":\"unknown\",protocol:c?.protocol??\"unknown\",rttMs:typeof n?.currentRoundTripTime==\"number\"?Math.round(n.currentRoundTripTime*1e3):null,streaming:a.dc?.label===\"files-v2\"})},offer:N,accept:U,answer:J,receive:q,close:w,dispose:()=>{for(let e of f.keys())w(e)}}}return G(z);})();\n";
diff --git a/packages/device-link/src/peerAttachment.ts b/packages/device-link/src/peerAttachment.ts
index 5d049cbaff..03041320b1 100644
--- a/packages/device-link/src/peerAttachment.ts
+++ b/packages/device-link/src/peerAttachment.ts
@@ -7,6 +7,24 @@ export interface PeerAttachment {
mimeType?: string;
originalName?: string;
}
+/**
+ * OSS 中转的单对象上限(与服务端 presign-put 对齐)。直连附件不受此限,只受接收端磁盘空间约束;
+ * 超过此值的附件没有 OSS 保底,只能直连发送。
+ */
+export const OSS_ATTACHMENT_MAX_BYTES = 2 * 1024 ** 3;
+/**
+ * 对端能否收这份直连附件(依据 file-peer caps):需支持附件 RPC;超过 OSS 上限还要求对端声明
+ * largeAttachments(旧端仍按 2GB 拒收)。发送端在读整份文件之前与建链之后都用这一判据。
+ */
+export function canSendPeerAttachment(
+ caps: { attachments?: boolean; largeAttachments?: boolean } | null | undefined,
+ size: number,
+): boolean {
+ return (
+ !!caps?.attachments &&
+ (size <= OSS_ATTACHMENT_MAX_BYTES || !!caps.largeAttachments)
+ );
+}
const prefix = "cindy-peer-attach://";
export const isPeerAttachmentRef = (value: unknown): value is string =>
typeof value === "string" && value.startsWith(prefix);
@@ -20,7 +38,6 @@ export function parsePeerAttachmentRef(value: string): PeerAttachment | null {
!r ||
!/^[a-f0-9-]{36}$/.test(r.ticket) ||
!isValidAttachmentIntegrity(r) ||
- r.size > 2 * 1024 ** 3 ||
(r.mimeType !== undefined &&
(typeof r.mimeType !== "string" ||
!/^[\w.+-]+\/[\w.+-]+$/.test(r.mimeType))) ||
@@ -46,11 +63,22 @@ export function buildPeerAttachmentRef(value: PeerAttachment): string {
return result;
}
+/**
+ * 接收端处理 finish 要整读文件重算摘要,耗时随体积增长;按保守的 20 MB/s 放宽这一次请求的等待。
+ * 其余请求沿用 RPC 默认超时。
+ */
+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. */
export async function uploadPeerAttachment(
metadata: Omit<PeerAttachment, "ticket">,
read: (offset: number, length: number) => Promise<string>,
- invoke: (request: Record<string, unknown>) => Promise<unknown>,
+ invoke: (
+ request: Record<string, unknown>,
+ timeoutMs?: number,
+ ) => Promise<unknown>,
check: () => void,
onProgress?: (bytes: number) => void,
): Promise<string> {
@@ -72,7 +100,10 @@ export async function uploadPeerAttachment(
onProgress?.(Math.min(offset + 1024 * 1024, metadata.size));
}
check();
- await invoke({ op: "finish", ticket });
+ await invoke(
+ { op: "finish", ticket },
+ peerAttachmentFinishTimeoutMs(metadata.size),
+ );
check();
return buildPeerAttachmentRef({ ...metadata, ticket });
} catch (error) {