Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(files): 保留持续传输的大文件下载

Dash7d2ff4fc7e64
diff --git a/apps/desktop/src/main/device-link/filePeer.ts b/apps/desktop/src/main/device-link/filePeer.ts
index 72256290f7..f2e278057d 100644
--- a/apps/desktop/src/main/device-link/filePeer.ts
+++ b/apps/desktop/src/main/device-link/filePeer.ts
@@ -870,7 +870,7 @@ async function receivePeerFile(
receiving.reportProgress();
step = 'receive';
const transferStartedAt = Date.now();
- const watch = createFileTransferWatchdog(file.size, () => out.path ?? 'unknown');
+ const watch = createFileTransferWatchdog();
const watchdog = setInterval(() => {
if (signal?.aborted || !isCurrent()) return;
const reason = watch(receiving.offset);
diff --git a/apps/mobile/src/__tests__/peerFileLifecycle.test.tsx b/apps/mobile/src/__tests__/peerFileLifecycle.test.tsx
index b124041f9a..a2e0666c1b 100644
--- a/apps/mobile/src/__tests__/peerFileLifecycle.test.tsx
+++ b/apps/mobile/src/__tests__/peerFileLifecycle.test.tsx
@@ -312,7 +312,7 @@ it("releases a cache hit invalidated just before its promise resumes", async ()
expect(state.open).not.toHaveBeenCalled();
});
-it.each(["unknown", "timeout", "route-change", "debug-enabled"])("samples paths after %s and falls back despite steady progress", async (initial) => {
+it.each(["unknown", "timeout", "route-change", "debug-enabled"])("samples paths after %s without interrupting progress, then detects a stall", async (initial) => {
state.holdReceive = true;
state.debug = initial === "debug-enabled";
const started = Date.now();
@@ -339,16 +339,17 @@ it.each(["unknown", "timeout", "route-change", "debug-enabled"])("samples paths
await vi.advanceTimersByTimeAsync(0);
const receive = state.commands.find((c) => c.action === "receive");
expect(receive).toBeDefined();
- for (let offset = 0; offset < 26 && !settled; offset++) {
+ for (let offset = 0; offset < 75; offset++) {
act(() => message({ type: "write", id: `write-${offset}`, args: [receive.args[0], offset, "YQ=="] }));
await vi.advanceTimersByTimeAsync(1000);
- // A route change must restart the rate sample instead of using old-path throughput.
- if (initial === "route-change" && offset === 15) expect(settled).toBe(false);
+ // Neither an unknown/changing route nor a long total duration ends a live transfer.
+ expect(settled).toBe(false);
}
+ await vi.advanceTimersByTimeAsync(15_000);
expect(settled).toBe(true);
expect(await transfer).toBeNull();
expect(state.stats.mock.calls.length).toBeGreaterThan(1);
- expect(state.log).toHaveBeenCalledWith("debug", "files", "slow transfer fallback", expect.objectContaining({ reason: "slow-relay", path: "relay" }));
+ expect(state.log).toHaveBeenCalledWith("debug", "files", "slow transfer fallback", expect.objectContaining({ reason: "stalled", path: "relay" }));
expect(state.log.mock.calls.some((c) => c[2] === "direct transfer progress")).toBe(state.debug);
expect(state.deleted).toHaveBeenCalledOnce();
const samples = state.stats.mock.calls.length;
diff --git a/apps/mobile/src/device-link/peerFileTransport.tsx b/apps/mobile/src/device-link/peerFileTransport.tsx
index 38fce72e73..5d8dfb5cee 100644
--- a/apps/mobile/src/device-link/peerFileTransport.tsx
+++ b/apps/mobile/src/device-link/peerFileTransport.tsx
@@ -436,13 +436,13 @@ export function PeerFileTransport() {
target.create();
const handle = target.open();
sinks.current.set(id, { handle, size: file.size, offset: 0 });
- // The watchdog needs current route information even with Debug recording off.
- // Detailed network/disk progress is recorded only when diagnostics are enabled.
+ // Detect stalled writes even with Debug recording off. Route sampling is
+ // diagnostic only; a slow route must not interrupt a progressing download.
let sampling = false;
// Set when the receive settles: an already-issued stats reply must not append
// a progress line behind the outcome log with a dropped sink offset.
let ended = false;
- const watch = createFileTransferWatchdog(file.size, () => connection?.path ?? 'unknown');
+ const watch = createFileTransferWatchdog();
let slow = false;
const sampler = setInterval(() => {
if (ended || !current()) return;
diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.md
index fad1404370..54c6de2326 100644
--- a/docs/dev-rules/remote-and-mobile-adaptation.md
+++ b/docs/dev-rules/remote-and-mobile-adaptation.md
@@ -68,12 +68,12 @@ Desktop 与 Mobile 的整文件 peer 下载共用 `fileTransferPolicy.ts`。数
时长决定关闭;旧端继续按已有空闲预算兼容。手机退后台释放原文件 WebView 和电脑端
连接,回前台不立即重建。断链取消排队与建连中的请求,防止迟到结果恢复已关闭的会话。
-连续一个命令预算(15 秒)没有写入进展(含等待 EOF)时回退。对仍在前进的已知路径,
-至少观察完整 15 秒窗口,只有按实际写入速率估算剩余时间超过既有接收预算(60 秒)
-才回退;直接和 TURN 路径使用相同判断,不再设不同 KB/s 下限或固定剩余字节门槛。
-这是一项有界等待策略,不是 OSS 比当前路径快的测量结论。4 MB、150 KB/s 的中继
-传输不会仅因低于旧阈值而被重传。路径未知只判断停滞;路径变化丢弃旧速度窗口。
-每次取件旁路采样实际路径,统计不阻塞握手或文件首字节;进度检查不依赖 Debug 开关。
+连续一个命令预算(15 秒)没有写入进展(含等待 EOF)时回退。只要仍有写入进展,
+不按预计剩余时间、文件大小或速度放弃传输:接收超时约束的是无进度等待,不是整个
+文件的完成时间。没有备用路径的实测速度,就不能以“预计还需超过 60 秒”为由丢弃
+已收字节;这会让 806 MB 等大文件在正常传输 15 秒后被中断,再撞上旧媒体上传接口
+的 30 秒请求超时。直接、TURN 和未知路径使用同一停滞判断,路径变化不影响它。
+每次取件旁路采样实际路径用于诊断,不阻塞握手或文件首字节;进度检查不依赖 Debug 开关。
故障仅影响该 peer 的文件通道;复用已有按设备冷却(30 秒起、最多 5 分钟)避免
紧接着的文件重新走同一慢链路,不重连共享 WSS、不影响另一控制端的文件或请求。
diff --git a/packages/device-link/src/__tests__/fileTransferPolicy.test.ts b/packages/device-link/src/__tests__/fileTransferPolicy.test.ts
index 028954b20e..ab14c09bb2 100644
--- a/packages/device-link/src/__tests__/fileTransferPolicy.test.ts
+++ b/packages/device-link/src/__tests__/fileTransferPolicy.test.ts
@@ -15,29 +15,32 @@ it("uses the advertised lifetime minus a command budget, rejecting invalid capab
for (const value of [undefined, NaN, Infinity, -1])
expect(filePeerReuseMs(value)).toBe(30_000);
});
-it("does not abandon a modest relay transfer just because its KB/s is low", () => {
+it("does not abandon a progressing transfer just because its KB/s is low", () => {
let time = 0;
- const watch = createFileTransferWatchdog(4_000_000, "relay", () => time);
+ const watch = createFileTransferWatchdog(() => time);
for (time = 1000; time <= 25_000; time += 1000)
expect(watch(time * 150)).toBeNull();
expect(fileTransferPath('{"path":"relay","rttMs":300}')).toBe("relay");
expect(fileTransferPath("invalid")).toBe("unknown");
});
-it("uses remaining completion time on known paths instead of separate arbitrary speed floors", () => {
+it("keeps a progressing 806 MB download until completion regardless of route", () => {
let time = 0;
- const paths = ["direct", "relay", "unknown"] as const;
- const watches = paths.map((path) =>
- createFileTransferWatchdog(20_000_000, path, () => time),
- );
- let outcomes: unknown[] = [];
- for (time = 1000; time <= FILE_PEER_COMMAND_TIMEOUT_MS; time += 1000)
- outcomes = watches.map((watch) => watch(time * 150));
- expect(outcomes).toEqual(["slow-direct", "slow-relay", null]);
+ const size = 805_998_643;
+ const watch = createFileTransferWatchdog(() => time);
+ // Reported transfer: 2 MiB received in 15 seconds, with progress every second.
+ // Replay the whole download using a fake clock, including the old 15s cutoff.
+ let written = 0;
+ while (written < size) {
+ time += 1000;
+ written = Math.min(size, Math.floor((2 * 1024 ** 2 * time) / 15_000));
+ expect(watch(written)).toBeNull();
+ }
+ expect(time).toBeGreaterThan(FILE_PEER_RECEIVE_TIMEOUT_MS);
});
it("isolates stalled peers and still detects a missing EOF after all bytes arrived", () => {
let time = 0;
- const stalled = createFileTransferWatchdog(1_000_000, "direct", () => time);
- const healthy = createFileTransferWatchdog(1_000_000, "relay", () => time);
+ const stalled = createFileTransferWatchdog(() => time);
+ const healthy = createFileTransferWatchdog(() => time);
for (time = 1000; time < FILE_PEER_COMMAND_TIMEOUT_MS; time += 1000) {
expect(stalled(0)).toBeNull();
expect(healthy(Math.min(time * 100, 1_000_000))).toBeNull();
@@ -46,22 +49,13 @@ it("isolates stalled peers and still detects a missing EOF after all bytes arriv
time = 10_000 + FILE_PEER_COMMAND_TIMEOUT_MS;
expect(healthy(1_000_000)).toBe("stalled");
});
-it("discards the old sample when the actual route changes", () => {
+it("renews the stall deadline only when more bytes arrive", () => {
let time = 0;
- let path: "direct" | "relay" = "relay";
- const watch = createFileTransferWatchdog(
- 100_000_000,
- () => path,
- () => time,
- );
+ const watch = createFileTransferWatchdog(() => time);
time = FILE_PEER_COMMAND_TIMEOUT_MS - 1;
expect(watch(1_000_000)).toBeNull();
- path = "direct";
+ time += FILE_PEER_COMMAND_TIMEOUT_MS - 1;
+ expect(watch(1_000_000)).toBeNull();
time++;
- expect(watch(2_000_000)).toBeNull();
- time += FILE_PEER_COMMAND_TIMEOUT_MS;
- expect(watch(50_000_000)).toBeNull();
- expect(FILE_PEER_RECEIVE_TIMEOUT_MS).toBeGreaterThan(
- FILE_PEER_COMMAND_TIMEOUT_MS,
- );
+ expect(watch(1_000_000)).toBe("stalled");
});
diff --git a/packages/device-link/src/fileTransferPolicy.ts b/packages/device-link/src/fileTransferPolicy.ts
index 41c31575fc..cca427abbe 100644
--- a/packages/device-link/src/fileTransferPolicy.ts
+++ b/packages/device-link/src/fileTransferPolicy.ts
@@ -32,48 +32,20 @@ export function filePeerReuseMs(advertised: unknown, sessionBound?: unknown): nu
: FILE_PEER_RECEIVE_TIMEOUT_MS / 2;
}
-/** Do not assume TURN is slower than OSS or invent a KB/s floor. Sample for one
- * command budget; only abandon a known path when its remaining work is projected
- * to exceed a full receive budget. No progress uses the shorter command budget.
- * A path change discards the old sample. Unknown paths only detect stalls.
- * This bounds a bad attempt; without OSS measurements it cannot promise a faster route. */
-export function createFileTransferWatchdog(
- size: number,
- path: FileTransferPath | (() => FileTransferPath),
- now = Date.now,
-) {
+/** Only abandon stalled transfers. Receive timeouts bound inactivity, not total
+ * duration: large files may take minutes while making steady progress. Without
+ * measuring the fallback route, a completion estimate cannot justify discarding
+ * bytes already received. The same rule applies to direct and relayed traffic. */
+export function createFileTransferWatchdog(now = Date.now) {
let lastBytes = 0,
- lastProgress = now(),
- sampleAt = lastProgress,
- sampleBytes = 0;
- const getPath = typeof path === "function" ? path : () => path;
- let sampledPath = getPath();
- return (written: number): "stalled" | "slow-relay" | "slow-direct" | null => {
+ lastProgress = now();
+ return (written: number): "stalled" | null => {
const time = now();
if (written > lastBytes) {
lastBytes = written;
lastProgress = time;
}
- if (time - lastProgress >= FILE_PEER_COMMAND_TIMEOUT_MS) return "stalled";
- const currentPath = getPath();
- if (currentPath !== sampledPath) {
- sampledPath = currentPath;
- sampleAt = time;
- sampleBytes = written;
- return null;
- }
- const elapsed = time - sampleAt;
- if (elapsed < FILE_PEER_COMMAND_TIMEOUT_MS) return null;
- const advanced = written - sampleBytes;
- sampleAt = time;
- sampleBytes = written;
- if (advanced <= 0 || currentPath === "unknown") return null;
- const remainingMs = ((size - written) * elapsed) / advanced;
- return remainingMs > FILE_PEER_RECEIVE_TIMEOUT_MS
- ? currentPath === "relay"
- ? "slow-relay"
- : "slow-direct"
- : null;
+ return time - lastProgress >= FILE_PEER_COMMAND_TIMEOUT_MS ? "stalled" : null;
};
}