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): 补齐远程直传进度并统一下载与预览提示 (#5531)

Dashcd064bdef341
diff --git a/apps/desktop/src/main/device-link/__tests__/fileAccess.test.ts b/apps/desktop/src/main/device-link/__tests__/fileAccess.test.ts
index 5f4a7706e8..e2be65322b 100644
--- a/apps/desktop/src/main/device-link/__tests__/fileAccess.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/fileAccess.test.ts
@@ -13,6 +13,78 @@ beforeEach(() => {
peer.mockResolvedValue(null);
});
describe('desktop shared file access', () => {
+ it.each([false, true])(
+ 'forwards direct progress for workdir and media reads (workdir=%s)',
+ async (workdir) => {
+ const metadata = {
+ ossKey: '',
+ size: 100,
+ mimeType: 'application/octet-stream',
+ transferRequired: true,
+ };
+ const invoke = vi.fn(async (_device, _channel, [args]) => ({
+ ok: true,
+ result:
+ args.op === 'caps'
+ ? { fileRead: true }
+ : args.op === 'fileUrl'
+ ? { ok: true, url: 'xdt-file://local/?path=/w/file' }
+ : metadata,
+ }));
+ const progress = vi.fn();
+ const local = {
+ path: '/tmp/received',
+ size: 100,
+ mimeType: metadata.mimeType,
+ dispose: vi.fn(),
+ };
+ peer.mockImplementationOnce(async (_device, _url, _invoke, _signal, onProgress) => {
+ onProgress(0, 100);
+ onProgress(45, 100);
+ onProgress(100, 100);
+ return local;
+ });
+ const fallback = vi.fn();
+ const result = await readRemoteDeviceFile('d', 'xdt-file://test', invoke, {
+ onProgress: progress,
+ ...(workdir ? { workdir: '/w', relPath: 'file', fallback } : {}),
+ });
+ expect(result).toMatchObject({ path: local.path });
+ expect(progress.mock.calls).toEqual([
+ [0, 100],
+ [45, 100],
+ [100, 100],
+ ]);
+ expect(fallback).not.toHaveBeenCalled();
+ },
+ );
+
+ it('resets discarded partial bytes before falling back to OSS', async () => {
+ const progress = vi.fn();
+ peer.mockImplementationOnce(async (_device, _url, _invoke, _signal, onProgress) => {
+ onProgress(40, 100);
+ return null;
+ });
+ const invoke = vi.fn(async () => ({
+ ok: true,
+ result: { ossKey: '', size: 100, mimeType: 'text/plain', transferRequired: true },
+ }));
+ const fallback = vi.fn(async () => {
+ expect(progress).toHaveBeenLastCalledWith(0, 100);
+ return { ossKey: 'fallback', size: 100, mimeType: 'text/plain' };
+ });
+ expect(
+ await readRemoteDeviceFile('d', 'xdt-file://test', invoke, {
+ onProgress: progress,
+ fallback,
+ }),
+ ).toMatchObject({ ossKey: 'fallback' });
+ expect(progress.mock.calls).toEqual([
+ [40, 100],
+ [0, 100],
+ ]);
+ });
+
it('keeps old hosts on two-stage export without synchronous media upload', async () => {
const invoke = vi.fn(async () => ({ ok: true, result: { ok: true, gzip: true } }));
const fallback = vi.fn(async () => ({
@@ -46,7 +118,12 @@ describe('desktop shared file access', () => {
.mockResolvedValueOnce({ ok: true, result: inline });
const fallback = vi.fn();
expect(
- await readRemoteDeviceFile('d', 'unused', invoke, { workdir: '/p', relPath: 'a', maxBytes: 10, fallback }),
+ await readRemoteDeviceFile('d', 'unused', invoke, {
+ workdir: '/p',
+ relPath: 'a',
+ maxBytes: 10,
+ fallback,
+ }),
).toEqual(inline);
expect(peer).not.toHaveBeenCalled();
expect(fallback).not.toHaveBeenCalled();
diff --git a/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts b/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts
index cfc6582cd2..c7acda53df 100644
--- a/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts
@@ -122,20 +122,80 @@ describe('authorized file peer source', () => {
: { connection: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', sdp: 'v=0' },
};
});
- const transfer = tryPeerFile(peer, 'xdt-file://test', invoke);
+ const progress = vi.fn().mockImplementationOnce(() => {
+ throw new Error('observer failed');
+ });
+ const transfer = tryPeerFile(peer, 'xdt-file://test', invoke, undefined, progress);
await vi.waitFor(() => expect(mock.receiving).toBeDefined());
+ expect(progress).toHaveBeenLastCalledWith(0, 5);
mock.replyDelay = delay;
expect(
await tryPeerInvoke(peer, 'file-browser:remote-op', [{ op: 'readFile' }], invoke),
).toBeNull();
- await mock.handlers.get('file-peer:host:write')!({}, mock.receiving!.sink, 0, 'aGVsbG8=');
+ await mock.handlers.get('file-peer:host:write')!({}, mock.receiving!.sink, 0, 'aGU=');
+ // Partial writes must reach the UI before EOF, even when diagnostic RPCs fail.
+ expect(progress).toHaveBeenLastCalledWith(2, 5);
+ await mock.handlers.get('file-peer:host:write')!({}, mock.receiving!.sink, 2, 'bGxv');
+ expect(progress).toHaveBeenLastCalledWith(5, 5);
mock.receiving!.reply();
const result = await transfer;
expect(result?.size).toBe(5);
await result?.dispose();
+ expect(progress.mock.calls.map(([received]) => received)).toEqual([0, 2, 5]);
},
20_000,
);
+ it.each(['abort', 'owner'] as const)(
+ 'stops receive progress after %s invalidation',
+ async (reason) => {
+ const invoke = vi.fn(async (_peer: string, _channel: string, args: unknown[]) => {
+ const action = (args[0] as { action: string }).action;
+ return {
+ ok: true,
+ result:
+ action === 'caps'
+ ? { version: 1, streaming: true }
+ : action === 'open'
+ ? {
+ ticket: 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb',
+ size: 5,
+ mimeType: 'text/plain',
+ }
+ : { connection: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa', sdp: 'v=0' },
+ };
+ });
+ const abort = new AbortController();
+ const progress = vi.fn();
+ const pending = tryPeerFile(
+ `invalidated-${reason}`,
+ 'xdt-file://test',
+ invoke,
+ abort.signal,
+ progress,
+ );
+ const rejected = expect(pending).rejects.toThrow('FILE_PEER_CANCELLED');
+ await vi.waitFor(() => expect(mock.receiving).toBeDefined());
+ const receive = mock.receiving!;
+ await mock.handlers.get('file-peer:host:write')!({}, receive.sink, 0, 'aGU=');
+ if (reason === 'abort') {
+ abort.abort();
+ await expect(
+ mock.handlers.get('file-peer:host:write')!({}, receive.sink, 2, 'bGxv'),
+ ).rejects.toThrow('FILE_PEER_BLOCK');
+ } else {
+ mock.current = false;
+ await expect(
+ mock.handlers.get('file-peer:host:write')!({}, receive.sink, 2, 'bGxv'),
+ ).rejects.toThrow('FILE_PEER_CLOSED');
+ receive.reply();
+ }
+ await rejected;
+ expect(progress.mock.calls).toEqual([
+ [0, 5],
+ [2, 5],
+ ]);
+ },
+ );
it('warms reads, preserves application errors, and retries transport failure only after cooldown', async () => {
const peer = 'warm-recovery-peer';
const invoke = vi.fn(async (_peer: string, _channel: string, args: unknown[]) => {
diff --git a/apps/desktop/src/main/device-link/fileAccess.ts b/apps/desktop/src/main/device-link/fileAccess.ts
index 5b9cd620a2..27e14f4e99 100644
--- a/apps/desktop/src/main/device-link/fileAccess.ts
+++ b/apps/desktop/src/main/device-link/fileAccess.ts
@@ -17,6 +17,8 @@ export function readRemoteDeviceFile(
rawInvoke: Invoke,
options: {
signal?: AbortSignal;
+ /** Bytes actually written by the direct receiver, shared by every file entry point. */
+ onProgress?: (received: number, total: number) => void;
skipCache?: boolean;
maxPeerBytes?: number;
maxBytes?: number;
@@ -79,11 +81,19 @@ export function readRemoteDeviceFile(
},
peer: async (metadata) => {
if (
- metadata.size >
- Math.min(options.maxPeerBytes ?? FILE_PEER_MAX_BYTES, FILE_PEER_MAX_BYTES)
+ metadata.size > Math.min(options.maxPeerBytes ?? FILE_PEER_MAX_BYTES, FILE_PEER_MAX_BYTES)
)
return null;
- const result = await tryPeerFile(device, url, invoke, options.signal);
+ const result = await tryPeerFile(device, url, invoke, options.signal, options.onProgress);
+ // A failed direct attempt is discarded before OSS starts; do not leave its partial
+ // percentage/speed on screen during the fallback preparation.
+ if (!result && !options.signal?.aborted && isDataOwnerBroadcastScopeCurrent(owner)) {
+ try {
+ options.onProgress?.(0, metadata.size);
+ } catch {
+ /* observer only */
+ }
+ }
return result ? { ...result, ossKey: '' } : null;
},
fallback: options.fallback ?? (() => fetch(false)),
diff --git a/apps/desktop/src/main/device-link/filePeer.ts b/apps/desktop/src/main/device-link/filePeer.ts
index 8522c6971d..4929fa73a3 100644
--- a/apps/desktop/src/main/device-link/filePeer.ts
+++ b/apps/desktop/src/main/device-link/filePeer.ts
@@ -60,6 +60,7 @@ interface Sink {
size: number;
offset: number;
busy: boolean;
+ reportProgress(): void;
}
interface Outgoing {
id: string;
@@ -627,6 +628,7 @@ export function registerFilePeerIpc() {
if (written.bytesWritten !== bytes.length || sinks.get(id) !== s)
throw new Error('FILE_PEER_CLOSED');
s.offset += bytes.length;
+ s.reportProgress();
// Same as READ: transfer progress never refreshes diagnostic probe timers.
for (const pending of replies.values())
if (pending.connection === s.connection && !pending.probe) pending.timer.refresh();
@@ -645,7 +647,13 @@ type Invoke = (
) => Promise<{ ok: boolean; result?: unknown }>;
/** A caller owns the returned temporary file and must dispose it after consuming it. */
const queuePeerRead = createFileReadQueue();
-export function tryPeerFile(peer: string, url: string, invoke: Invoke, signal?: AbortSignal) {
+export function tryPeerFile(
+ peer: string,
+ url: string,
+ invoke: Invoke,
+ signal?: AbortSignal,
+ onProgress?: (received: number, total: number) => void,
+) {
const owner = captureDataOwnerBroadcastScope();
if (!cooldownOwner || !isDataOwnerBroadcastScopeCurrent(cooldownOwner)) {
cooldown.clear();
@@ -655,7 +663,7 @@ export function tryPeerFile(peer: string, url: string, invoke: Invoke, signal?:
peer,
() => {
if (!isDataOwnerBroadcastScopeCurrent(owner)) throw new Error('FILE_PEER_CANCELLED');
- return receivePeerFile(peer, url, invoke, signal);
+ return receivePeerFile(peer, url, invoke, signal, onProgress);
},
signal,
);
@@ -665,6 +673,7 @@ async function receivePeerFile(
url: string | null,
invoke: Invoke,
signal?: AbortSignal,
+ onProgress?: (received: number, total: number) => void,
) {
refreshCooldownOwner();
if (signal?.aborted) throw new Error('FILE_PEER_CANCELLED');
@@ -750,7 +759,24 @@ async function receivePeerFile(
const destination = path.join(directory, 'file');
const handle = await fs.open(destination, 'wx', 0o600),
sink = randomUUID();
- sinks.set(sink, { connection: id, file: handle, offset: 0, size: file.size, busy: false });
+ const receiving: Sink = {
+ connection: id,
+ file: handle,
+ offset: 0,
+ size: file.size,
+ busy: false,
+ reportProgress: () => {
+ if (signal?.aborted || !isDataOwnerBroadcastScopeCurrent(owner)) return;
+ // An observer must never fail a disk write or trigger a transport fallback.
+ try {
+ onProgress?.(receiving.offset, receiving.size);
+ } catch {
+ /* observer only */
+ }
+ },
+ };
+ sinks.set(sink, receiving);
+ receiving.reportProgress();
step = 'receive';
const transferStartedAt = Date.now();
const stopProgress = startMonitor(`receive:${sink}`, id, async () => {
diff --git a/apps/desktop/src/main/file-browser/__tests__/chatFile.test.ts b/apps/desktop/src/main/file-browser/__tests__/chatFile.test.ts
index cf229a8492..5e80081c65 100644
--- a/apps/desktop/src/main/file-browser/__tests__/chatFile.test.ts
+++ b/apps/desktop/src/main/file-browser/__tests__/chatFile.test.ts
@@ -27,6 +27,7 @@ vi.mock('../../logger', () => ({
import { isWorkdirRoot } from '../../../shared/workdirPath';
import {
buildDevicePathUrl,
+ chatFileProgressRequestId,
fetchChatFile,
statChatFile,
toWorkdirRel,
@@ -52,6 +53,17 @@ function makeDeps(overrides: Partial<ChatFileDeps> = {}): ChatFileDeps {
const noop = () => undefined;
+describe('chatFileProgressRequestId', () => {
+ it('accepts bounded IDs for fetch and download progress', () => {
+ expect(chatFileProgressRequestId('request-1')).toBe('request-1');
+ expect(chatFileProgressRequestId('a'.repeat(64))).toBe('a'.repeat(64));
+ });
+
+ it.each([undefined, null, 42, {}, '', 'a'.repeat(65)])('ignores invalid ID %j', (value) => {
+ expect(chatFileProgressRequestId(value)).toBeUndefined();
+ });
+});
+
describe('toWorkdirRel', () => {
it('POSIX:workdir 内出相对路径,外/逃逸/自身 → null', () => {
expect(toWorkdirRel('/w/proj', '/w/proj/a/b.txt')).toBe('a/b.txt');
@@ -157,6 +169,27 @@ describe('fetchChatFile — ssh 来源', () => {
describe('fetchChatFile — device 来源', () => {
const origin = { kind: 'device', deviceId: 'd1' } as const;
+ it('reports media transfer bytes while the outside-workdir read is still pending', async () => {
+ let finish!: () => void;
+ const waiting = new Promise<void>((resolve) => { finish = resolve; });
+ const progress = vi.fn();
+ const deps = makeDeps({
+ deviceMediaFetch: vi.fn(async (_device, _url, _signal, onProgress) => {
+ onProgress?.(0, 20);
+ onProgress?.(8, 20);
+ await waiting;
+ onProgress?.(20, 20);
+ return { ossKey: 'k1', size: 20 };
+ }),
+ });
+ const pending = fetchChatFile({ origin, workdir: '/w', absPath: '/other/video.mp4' }, progress, deps);
+ expect(progress.mock.calls).toEqual([[0, 20], [8, 20]]);
+ expect(deps.fetchToCache).not.toHaveBeenCalled();
+ finish();
+ await expect(pending).resolves.toMatchObject({ ok: true });
+ expect(progress).toHaveBeenLastCalledWith(20, 20);
+ });
+
it('workdir 内:deviceStat + fetchBigFile(deviceId 分支)', async () => {
const deps = makeDeps();
const res = await fetchChatFile({ origin, workdir: '/w', absPath: '/w/x/b.png' }, noop, deps);
@@ -188,6 +221,7 @@ describe('fetchChatFile — device 来源', () => {
'd1',
buildDevicePathUrl('/other/c.pdf'),
undefined,
+ noop,
);
expect(deps.downloadToFile).toHaveBeenCalledWith(
'k1',
@@ -259,6 +293,7 @@ describe('fetchChatFile — device 来源', () => {
'd1',
buildDevicePathUrl('/other/c.pdf'),
abort.signal,
+ noop,
);
expect(deps.downloadToFile).toHaveBeenCalledWith(
'k1',
diff --git a/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheVersions.test.ts b/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheVersions.test.ts
index 118a51ddbf..57175bc81b 100644
--- a/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheVersions.test.ts
+++ b/apps/desktop/src/main/file-browser/__tests__/remoteFileCacheVersions.test.ts
@@ -252,3 +252,70 @@ it('does not start work for an already cancelled caller', async () => {
);
expect(executor).not.toHaveBeenCalled();
});
+
+it.each(['first', 'joined'] as const)(
+ 'shares and replays progress, then removes the cancelled %s consumer',
+ async (cancelled) => {
+ const started = barrier();
+ const release = barrier();
+ const firstAbort = new AbortController();
+ const joinedAbort = new AbortController();
+ const firstProgress = vi.fn();
+ const joinedProgress = vi.fn();
+ let report!: import('../remote-file-cache').FetchProgressFn;
+ const executor = vi.fn(async (dest: string, progress: typeof report) => {
+ report = progress;
+ report(1, 3, 'upload');
+ started.resolve();
+ await release.promise;
+ await fs.writeFile(dest, 'new');
+ report(3, 3, 'download');
+ });
+ const first = fetchRemoteFileToCache(id, executor, firstProgress, firstAbort.signal);
+ await started.promise;
+ const joined = fetchRemoteFileToCache(id, executor, joinedProgress, joinedAbort.signal);
+ expect(joinedProgress).toHaveBeenCalledWith(1, 3, 'upload');
+ report(2, 3, 'download');
+ expect(firstProgress).toHaveBeenLastCalledWith(2, 3, 'download');
+ expect(joinedProgress).toHaveBeenLastCalledWith(2, 3, 'download');
+ const cancelledProgress = cancelled === 'first' ? firstProgress : joinedProgress;
+ const survivorProgress = cancelled === 'first' ? joinedProgress : firstProgress;
+ (cancelled === 'first' ? firstAbort : joinedAbort).abort();
+ await expect(cancelled === 'first' ? first : joined).rejects.toThrow('FILE_PEER_CANCELLED');
+ const callsBefore = cancelledProgress.mock.calls.length;
+ release.resolve();
+ await (cancelled === 'first' ? joined : first);
+ expect(executor).toHaveBeenCalledOnce();
+ expect(cancelledProgress).toHaveBeenCalledTimes(callsBefore);
+ expect(survivorProgress).toHaveBeenLastCalledWith(3, 3, 'download');
+ const survivorCalls = survivorProgress.mock.calls.length;
+ report(3, 3, 'download');
+ expect(survivorProgress).toHaveBeenCalledTimes(survivorCalls);
+ },
+);
+
+it('does not let a failing progress observer break another consumer or the transfer', async () => {
+ const started = barrier();
+ const release = barrier();
+ const observer = vi.fn(() => {
+ throw new Error('window closed');
+ });
+ const executor = vi.fn(
+ async (dest: string, report: import('../remote-file-cache').FetchProgressFn) => {
+ report(1, 3);
+ started.resolve();
+ await release.promise;
+ await fs.writeFile(dest, 'new');
+ report(3, 3);
+ },
+ );
+ const first = fetchRemoteFileToCache(id, executor, observer);
+ await started.promise;
+ const progress = vi.fn();
+ const joined = fetchRemoteFileToCache(id, executor, progress);
+ release.resolve();
+ const [a, b] = await Promise.all([first, joined]);
+ expect(a).toBe(b);
+ expect(executor).toHaveBeenCalledOnce();
+ expect(progress).toHaveBeenLastCalledWith(3, 3);
+});
diff --git a/apps/desktop/src/main/file-browser/__tests__/transferProgress.test.ts b/apps/desktop/src/main/file-browser/__tests__/transferProgress.test.ts
new file mode 100644
index 0000000000..6f14d55c1e
--- /dev/null
+++ b/apps/desktop/src/main/file-browser/__tests__/transferProgress.test.ts
@@ -0,0 +1,44 @@
+import { afterEach, expect, it, vi } from 'vitest';
+import { createFileTransferProgressReporter } from '../transfer-progress';
+
+afterEach(() => vi.useRealTimers());
+
+it('throttles byte updates but preserves initial, phase, fallback and final events', () => {
+ vi.useFakeTimers();
+ const publish = vi.fn();
+ const report = createFileTransferProgressReporter(
+ { workdir: '/w', relPath: 'a', requestId: 'r' },
+ publish,
+ );
+ report(0, 100);
+ report(10, 100);
+ vi.advanceTimersByTime(100);
+ report(50, 100);
+ report(0, 100); // Direct attempt discarded, even within the same 100 ms window.
+ report(0, 100, 'upload');
+ report(100, 100, 'upload');
+ report(0, 0, 'extract');
+ expect(publish.mock.calls.map(([e]) => [e.received, e.phase])).toEqual([
+ [0, 'download'],
+ [50, 'download'],
+ [0, 'download'],
+ [0, 'upload'],
+ [100, 'upload'],
+ [0, 'extract'],
+ ]);
+ for (const [e] of publish.mock.calls)
+ expect(e).toMatchObject({ workdir: '/w', relPath: 'a', requestId: 'r' });
+});
+
+it('bounds correlation IDs and throttles unknown-size transfers too', () => {
+ vi.useFakeTimers();
+ const publish = vi.fn();
+ const report = createFileTransferProgressReporter(
+ { workdir: '/w', relPath: 'a', requestId: 'x'.repeat(65) },
+ publish,
+ );
+ report(0, 0);
+ for (let i = 1; i < 100; i++) report(i, 0);
+ expect(publish).toHaveBeenCalledTimes(1);
+ expect(publish.mock.calls[0][0].requestId).toBeUndefined();
+});
diff --git a/apps/desktop/src/main/file-browser/chat-file.ts b/apps/desktop/src/main/file-browser/chat-file.ts
index afe45f7ddb..d7002c58fd 100644
--- a/apps/desktop/src/main/file-browser/chat-file.ts
+++ b/apps/desktop/src/main/file-browser/chat-file.ts
@@ -40,10 +40,15 @@ export interface ChatFileFetchArgs {
workdir: string;
/** 目标文件在远端机器上的绝对路径。 */
absPath: string;
+ /** Local IPC correlation for transfer progress; never forwarded to the remote device. */
+ requestId?: string;
/** Optional generated-command evidence window, using timestamps from the owning device. */
modifiedWindow?: { startMs: number; endMs: number | null };
}
+/** Bound renderer-provided correlation IDs before repeating them in progress events. */
+export { fileTransferRequestId as chatFileProgressRequestId } from './transfer-progress.js';
+
/**
* 返回形态走规则 13 的 `{success}` 例外:失败时 renderer 需要按 code 分流降级
* UX(workdir 外占位 / 不存在 / 可重试失败),throw 编码反而丢结构。
@@ -87,6 +92,7 @@ export interface ChatFileDeps {
deviceId: string,
url: string,
signal?: AbortSignal,
+ onProgress?: FetchProgressFn,
): Promise<
| { ossKey: string; size: number; inlineBase64?: string }
| { ossKey: string; size: number; path: string; dispose(): Promise<void> }
@@ -317,6 +323,7 @@ export async function fetchChatFile(
origin.deviceId,
buildDevicePathUrl(absPath),
signal,
+ onProgress,
);
if ('path' in fetched || fetched.inlineBase64 !== undefined) {
try {
diff --git a/apps/desktop/src/main/file-browser/index.ts b/apps/desktop/src/main/file-browser/index.ts
index 2334c93896..2c57c18f81 100644
--- a/apps/desktop/src/main/file-browser/index.ts
+++ b/apps/desktop/src/main/file-browser/index.ts
@@ -62,6 +62,7 @@ import {
type ChatFileFetchArgs,
buildDevicePathUrl,
} from './chat-file.js';
+import { createFileTransferProgressReporter } from './transfer-progress.js';
import { downloadChatEntry, type ChatDownloadDeps } from './chat-download.js';
import { isTransientDeviceExportStatusError } from './device-export-status-error.js';
import { makeSshChunkExecutor } from './ssh-media.js';
@@ -109,7 +110,7 @@ export const FILE_BROWSER_INVOKE = {
export const FILE_BROWSER_PUSH = {
EVENT: 'maker:file-browser:event',
- /** 大文件取回进度(仅发给发起窗口):{ workdir, relPath, received, total }。 */
+ /** 文件取回进度(仅发给发起窗口),订阅按 requestId 区分设备与并发请求。 */
TRANSFER: 'maker:file-browser:transfer',
} as const;
@@ -296,6 +297,7 @@ async function fetchRemoteBigFile(
return { ossKey: key, size: args.size, mimeType: 'application/octet-stream' };
},
signal: transferSignal,
+ onProgress: progress,
},
);
if ('path' in fetched) {
@@ -416,24 +418,13 @@ export function registerFileBrowserIpc(): void {
mtimeMs: number;
remoteHostId?: string | null;
deviceId?: string | null;
+ requestId?: string;
},
) => {
const wc = event.sender;
- let lastPush = 0;
- const onProgress = (received: number, total: number, phase?: 'upload' | 'download') => {
- const now = Date.now();
- if (now - lastPush < 100 && received < total) return;
- lastPush = now;
- if (!wc.isDestroyed()) {
- wc.send(FILE_BROWSER_PUSH.TRANSFER, {
- workdir: args.workdir,
- relPath: args.relPath,
- received,
- total,
- phase: phase ?? 'download',
- });
- }
- };
+ const onProgress = createFileTransferProgressReporter(args, (progress) => {
+ if (!wc.isDestroyed()) wc.send(FILE_BROWSER_PUSH.TRANSFER, progress);
+ });
try {
const cachePath = await fetchRemoteBigFile(args, onProgress);
return { ok: true as const, cachePath, stale: false };
@@ -462,8 +453,8 @@ export function registerFileBrowserIpc(): void {
);
// ── 聊天流文件取回:远端绝对路径 → 本地缓存副本(chat-file.ts 编排)────
- // 进度沿用 FILE_BROWSER_PUSH.TRANSFER,relPath 键固定用原始 absPath(renderer
- // 不做 abs→rel,单一实现点在 main;订阅方按 absPath 过滤)。
+ // 进度沿用 FILE_BROWSER_PUSH.TRANSFER,relPath 保留原始 absPath;
+ // 订阅以 requestId 关联,同路径跨设备与并发操作不串线。
const chatFileDeps: ChatFileDeps = {
sshStat: (hostId, workdir, relPath) =>
getRemoteFileBrowser().request(hostId, 'stat', { workdir, relPath }) as Promise<{
@@ -478,8 +469,8 @@ export function registerFileBrowserIpc(): void {
relPath,
}),
fetchBigFile: fetchRemoteBigFile,
- deviceMediaFetch: async (deviceId, url, signal) => {
- return readRemoteDeviceFile(deviceId, url, remoteInvoke, signal ? { signal } : {});
+ deviceMediaFetch: async (deviceId, url, signal, onProgress) => {
+ return readRemoteDeviceFile(deviceId, url, remoteInvoke, { signal, onProgress });
},
downloadToFile,
removeRemote: (key) => void removeRemote(key),
@@ -488,21 +479,12 @@ export function registerFileBrowserIpc(): void {
};
ipcMain.handle(FILE_BROWSER_INVOKE.CHAT_FILE_FETCH, async (event, args: ChatFileFetchArgs) => {
const wc = event.sender;
- let lastPush = 0;
- const onProgress = (received: number, total: number, phase?: 'upload' | 'download') => {
- const now = Date.now();
- if (now - lastPush < 100 && received < total) return;
- lastPush = now;
- if (!wc.isDestroyed()) {
- wc.send(FILE_BROWSER_PUSH.TRANSFER, {
- workdir: args?.workdir ?? '',
- relPath: args?.absPath ?? '',
- received,
- total,
- phase: phase ?? 'download',
- });
- }
- };
+ const onProgress = createFileTransferProgressReporter(
+ { workdir: args?.workdir ?? '', relPath: args?.absPath ?? '', requestId: args?.requestId },
+ (progress) => {
+ if (!wc.isDestroyed()) wc.send(FILE_BROWSER_PUSH.TRANSFER, progress);
+ },
+ );
const result = await fetchChatFile(args, onProgress, chatFileDeps);
if (!result.ok) {
log.warn('chat-file fetch failed', {
@@ -591,29 +573,16 @@ export function registerFileBrowserIpc(): void {
const onGone = () => abort.abort();
wc.once('destroyed', onGone);
wc.once('render-process-gone', onGone);
- let lastPush = 0;
// 进度带上发起方的请求 id:同一路径同时有取回 / 下载时 renderer 不串线。
- const requestId =
- typeof args?.requestId === 'string' && args.requestId.length <= 64
- ? args.requestId
- : undefined;
+ const onProgress = createFileTransferProgressReporter(
+ { workdir: args?.workdir ?? '', relPath: args?.absPath ?? '', requestId: args?.requestId },
+ (progress) => {
+ if (!wc.isDestroyed()) wc.send(FILE_BROWSER_PUSH.TRANSFER, progress);
+ },
+ );
const result = await downloadChatEntry(
args,
- (received, total, phase) => {
- const now = Date.now();
- if (now - lastPush < 100 && (total === 0 || received < total)) return;
- lastPush = now;
- if (!wc.isDestroyed()) {
- wc.send(FILE_BROWSER_PUSH.TRANSFER, {
- workdir: args?.workdir ?? '',
- relPath: args?.absPath ?? '',
- received,
- total,
- phase,
- requestId,
- });
- }
- },
+ onProgress,
chatDownloadDeps,
abort.signal,
).finally(() => {
diff --git a/apps/desktop/src/main/file-browser/remote-file-cache.ts b/apps/desktop/src/main/file-browser/remote-file-cache.ts
index 33f3e4a983..ad1c47d400 100644
--- a/apps/desktop/src/main/file-browser/remote-file-cache.ts
+++ b/apps/desktop/src/main/file-browser/remote-file-cache.ts
@@ -262,7 +262,8 @@ export async function putCachedContent(id: RemoteFileIdentity, content: string):
type InflightRead = {
promise: Promise<string>;
controller: AbortController;
- consumers: Set<symbol>;
+ consumers: Map<symbol, FetchProgressFn>;
+ lastProgress?: Parameters<FetchProgressFn>;
};
const inflight = new Map<string, InflightRead>();
@@ -281,12 +282,22 @@ export async function fetchRemoteFileToCache(
if (signal?.aborted) throw new Error('FILE_PEER_CANCELLED');
id = { ...id, scope };
const dest = cachePathFor(id);
+ const consumerProgress: FetchProgressFn = (...args) => {
+ if (signal?.aborted) return;
+ try {
+ onProgress(...args);
+ } catch {
+ // A closed UI consumer must not fail the shared transfer for other readers.
+ log.debug('cache progress consumer unavailable');
+ }
+ };
const existing = inflight.get(dest);
if (existing && !existing.controller.signal.aborted) {
const consumer = Symbol('remote-file-consumer');
- existing.consumers.add(consumer);
+ existing.consumers.set(consumer, consumerProgress);
try {
if (signal?.aborted) throw new Error('FILE_PEER_CANCELLED');
+ if (existing.lastProgress) consumerProgress(...existing.lastProgress);
const result = await raceWithAbort(existing.promise, signal);
assertCacheOwner(scope);
return result;
@@ -305,7 +316,13 @@ export async function fetchRemoteFileToCache(
};
const report: FetchProgressFn = (...args) => {
assertCacheOwner(scope);
- if (!controller.signal.aborted) onProgress(...args);
+ if (controller.signal.aborted) return;
+ owner.lastProgress = args;
+ for (const progress of owner.consumers.values()) {
+ assertCacheOwner(scope);
+ if (controller.signal.aborted) return;
+ progress(...args);
+ }
};
const firstConsumer = Symbol('remote-file-consumer');
const run = (async () => {
@@ -354,7 +371,11 @@ export async function fetchRemoteFileToCache(
return dest;
})();
- const owner: InflightRead = { promise: run, controller, consumers: new Set([firstConsumer]) };
+ const owner: InflightRead = {
+ promise: run,
+ controller,
+ consumers: new Map([[firstConsumer, consumerProgress]]),
+ };
inflight.set(dest, owner);
void run.then(
() => {
diff --git a/apps/desktop/src/main/file-browser/transfer-progress.ts b/apps/desktop/src/main/file-browser/transfer-progress.ts
new file mode 100644
index 0000000000..dc64fad55e
--- /dev/null
+++ b/apps/desktop/src/main/file-browser/transfer-progress.ts
@@ -0,0 +1,41 @@
+export type FileTransferPhase = 'upload' | 'download' | 'pack' | 'extract';
+
+export function fileTransferRequestId(value: unknown): string | undefined {
+ return typeof value === 'string' && value.length > 0 && value.length <= 64 ? value : undefined;
+}
+
+/** All file entry points share correlation and throttling. Phase/reset/final events never wait. */
+export function createFileTransferProgressReporter(
+ identity: { workdir: string; relPath: string; requestId?: unknown },
+ publish: (event: {
+ workdir: string;
+ relPath: string;
+ requestId?: string;
+ received: number;
+ total: number;
+ phase: FileTransferPhase;
+ }) => void,
+) {
+ const requestId = fileTransferRequestId(identity.requestId);
+ let last: { time: number; received: number; phase: FileTransferPhase } | undefined;
+ return (received: number, total: number, phase: FileTransferPhase = 'download') => {
+ const now = Date.now();
+ if (
+ last &&
+ last.phase === phase &&
+ received >= last.received &&
+ now - last.time < 100 &&
+ (total <= 0 || received < total)
+ )
+ return;
+ last = { time: now, received, phase };
+ publish({
+ workdir: identity.workdir,
+ relPath: identity.relPath,
+ requestId,
+ received,
+ total,
+ phase,
+ });
+ };
+}
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index d114d2d2de..1335e23fa2 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -2862,6 +2862,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
mtimeMs: number;
remoteHostId?: string | null;
deviceId?: string | null;
+ requestId?: string;
}): Promise<{ ok: true; cachePath: string; stale: boolean } | { ok: false; message: string }> =>
ipcRenderer.invoke('maker:file-browser:fetch-remote', params),
/** 读缓存副本内容(cached 态文本预览;32MB 显示上限,二进制回 kind:'binary')。 */
@@ -2890,13 +2891,13 @@ contextBridge.exposeInMainWorld('electronAPI', {
received: number;
total: number;
phase?: 'pack' | 'upload' | 'download' | 'extract';
- /** chatDownload 发起时带的请求 id(其它取回不带)。 */
+ /** fetchRemote / chatFetch / chatDownload 发起时带的请求 id。 */
requestId?: string;
}) => void,
): (() => void) => fanOutFileBrowserTransfer(cb as IpcCallback),
/**
* 聊天流文件取回:远端绝对路径 → 本地缓存副本(fetch-到缓存-再操作)。
- * 进度沿用 onTransferProgress,relPath 键 = 原始 absPath。失败按 code 分流:
+ * 进度沿用 onTransferProgress,按 requestId 关联请求。失败按 code 分流:
* OUTSIDE_WORKDIR(SSH workdir 外,明确占位)/ NOT_FOUND / FETCH_FAILED。
*/
previewHtml: (params: {
@@ -2911,6 +2912,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
origin: { kind: 'device'; deviceId: string } | { kind: 'ssh'; remoteHostId: string };
workdir: string;
absPath: string;
+ requestId?: string;
}): Promise<
| { ok: true; cachePath: string; stale: boolean; size: number }
| {
@@ -2921,7 +2923,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
> => ipcRenderer.invoke('maker:chat-file:fetch', params),
/**
* 远程文件 / 文件夹下载到系统「下载」文件夹(重名自动加编号),返回最终路径。
- * 进度沿用 onTransferProgress,relPath 键 = 原始 absPath。
+ * 进度沿用 onTransferProgress,按 requestId 关联请求。
*/
chatDownload: (params: {
origin: { kind: 'device'; deviceId: string } | { kind: 'ssh'; remoteHostId: string };
diff --git a/apps/desktop/src/renderer/__tests__/remoteFileProgress.test.ts b/apps/desktop/src/renderer/__tests__/remoteFileProgress.test.ts
new file mode 100644
index 0000000000..ca13ec93dc
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/remoteFileProgress.test.ts
@@ -0,0 +1,244 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { downloadRemoteChatEntry, fetchChatFileWithToasts } from '../lib/remoteFileOpen';
+import { getToastSnapshot, toast } from '../lib/toast';
+import messages from '../i18n/locales/en/common.json';
+import {
+ createFileTransferProgressValues,
+ observeFileTransferProgressText,
+} from '../lib/fileTransferProgress';
+
+vi.mock('@/i18n', () => ({
+ i18n: {
+ t: (key: string, values: Record<string, unknown> = {}) => {
+ const text =
+ messages.chat.remoteFile[key.split('.').at(-1)! as keyof typeof messages.chat.remoteFile];
+ return (text ?? key).replace(/\{\{(\w+)\}\}/g, (_, name: string) => String(values[name]));
+ },
+ },
+}));
+
+type Progress = Parameters<
+ Parameters<Window['electronAPI']['fileBrowser']['onTransferProgress']>[0]
+>[0];
+const origin = { kind: 'device' as const, deviceId: 'remote-computer' };
+// Remote POSIX paths are protocol values, independent of the test host OS.
+const workdir = '/remote/project';
+const absPath = `${workdir}/file.zip`;
+const listeners = new Set<(e: Progress) => void>();
+const chatFetch = vi.fn();
+const chatDownload = vi.fn();
+const success = { ok: true as const, cachePath: '/cache/file.zip', stale: false, size: 4096 };
+
+function deferred<T>() {
+ let resolve!: (result: T) => void;
+ let reject!: (error: Error) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+}
+
+function emit(
+ requestId: string,
+ received: number,
+ total = 4096,
+ phase: Progress['phase'] = 'download',
+) {
+ for (const listener of listeners)
+ listener({ requestId, workdir, relPath: absPath, received, total, phase });
+}
+
+const active = () => getToastSnapshot().filter((item) => !item.exiting);
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.spyOn(performance, 'now').mockImplementation(() => Date.now());
+ chatFetch.mockReset();
+ chatDownload.mockReset();
+ vi.stubGlobal('window', {
+ electronAPI: {
+ fileBrowser: {
+ chatFetch,
+ chatDownload,
+ onTransferProgress: (listener: (e: Progress) => void) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ },
+ showItemInFolder: vi.fn().mockResolvedValue({ success: true }),
+ },
+ });
+});
+
+afterEach(() => {
+ toast.dismissAll();
+ vi.runAllTimers();
+ listeners.clear();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+});
+
+describe('remote file transfer toasts', () => {
+ it('preview observers ignore other requests and stop immediately on unmount', () => {
+ const a = vi.fn();
+ const b = vi.fn();
+ const first = observeFileTransferProgressText(a);
+ const second = observeFileTransferProgressText(b);
+ emit(first.requestId, 1024);
+ expect(a).toHaveBeenLastCalledWith('Downloading… 25% · —');
+ expect(b).not.toHaveBeenCalled();
+ first.dispose();
+ first.dispose();
+ emit(first.requestId, 2048);
+ emit(second.requestId, 3072);
+ expect(a).toHaveBeenCalledTimes(1);
+ expect(b).toHaveBeenLastCalledWith('Downloading… 75% · —');
+ second.dispose();
+ expect(listeners.size).toBe(0);
+ });
+
+ it('resets speed when bytes fall within a sample window and clamps percentage', () => {
+ const sample = createFileTransferProgressValues();
+ sample({ received: 0, total: 4096 });
+ vi.advanceTimersByTime(1000);
+ expect(sample({ received: 2048, total: 4096 }).speed).toBe('2.0 KB/s');
+ vi.advanceTimersByTime(100);
+ sample({ received: 3072, total: 4096 });
+ // Lower than the latest event but higher than the speed sample's 2048 bytes.
+ expect(sample({ received: 2500, total: 4096 }).speed).toBe('—');
+ expect(sample({ received: 5000, total: 4096 }).percent).toBe(100);
+ expect(sample({ received: 10, total: 0 }).percent).toBeUndefined();
+ });
+
+ it('keeps cache hits silent and removes the progress subscription', async () => {
+ chatFetch.mockResolvedValue(success);
+ await expect(fetchChatFileWithToasts(origin, workdir, absPath)).resolves.toBe(
+ success.cachePath,
+ );
+ await vi.advanceTimersByTimeAsync(600);
+ expect(active()).toEqual([]);
+ expect(listeners.size).toBe(0);
+ });
+
+ it('shows a persistent spinner, updates percentage and measured speed in place, and dismisses on success', async () => {
+ const result = deferred<typeof success>();
+ chatFetch.mockReturnValue(result.promise);
+ const pending = fetchChatFileWithToasts(origin, workdir, absPath);
+ const { requestId } = chatFetch.mock.calls[0][0];
+ emit(requestId, 0);
+ await vi.advanceTimersByTimeAsync(600);
+ const first = active()[0];
+ expect(first).toMatchObject({ variant: 'loading', duration: 0 });
+ expect(first.message).toBe(messages.chat.remoteFile.fetching);
+ await vi.advanceTimersByTimeAsync(400);
+ emit(requestId, 2048);
+ expect(active()[0]).toMatchObject({ id: first.id, message: 'Downloading… 50% · 2.0 KB/s' });
+ result.resolve(success);
+ await pending;
+ expect(active()).toEqual([]);
+ expect(listeners.size).toBe(0);
+ });
+
+ it('restores preparation during peer fallback and resumes real download progress', async () => {
+ const result = deferred<typeof success>();
+ chatFetch.mockReturnValue(result.promise);
+ const pending = fetchChatFileWithToasts(origin, workdir, absPath);
+ const { requestId } = chatFetch.mock.calls[0][0];
+ const preview = vi.fn();
+ const observer = observeFileTransferProgressText(preview);
+ for (const id of [requestId, observer.requestId]) emit(id, 2048);
+ await vi.advanceTimersByTimeAsync(600);
+ expect(active()[0].message).toContain('50%');
+ for (const id of [requestId, observer.requestId]) emit(id, 0);
+ await vi.advanceTimersByTimeAsync(120_000);
+ expect(active()[0]).toMatchObject({
+ variant: 'loading',
+ message: messages.chat.remoteFile.fetching,
+ });
+ expect(preview).toHaveBeenLastCalledWith(messages.chat.remoteFile.fetching);
+ expect(createFileTransferProgressValues()({ received: 0, total: 4096 }).preparing).toBe(true);
+ for (const id of [requestId, observer.requestId]) emit(id, 1024);
+ expect(active()[0].message).toContain('25%');
+ expect(preview.mock.lastCall?.[0]).toContain('25%');
+ observer.dispose();
+ result.resolve(success);
+ await pending;
+ expect(active()).toEqual([]);
+ expect(listeners.size).toBe(0);
+ });
+
+ it('isolates concurrent requests for the same path on different computers', async () => {
+ const a = deferred<typeof success>();
+ const b = deferred<typeof success>();
+ chatFetch.mockReturnValueOnce(a.promise).mockReturnValueOnce(b.promise);
+ const first = fetchChatFileWithToasts(origin, workdir, absPath);
+ const second = fetchChatFileWithToasts(
+ { kind: 'device', deviceId: 'another-computer' },
+ workdir,
+ absPath,
+ );
+ const idA = chatFetch.mock.calls[0][0].requestId;
+ const idB = chatFetch.mock.calls[1][0].requestId;
+ expect(idA).not.toBe(idB);
+ emit(idA, 1024);
+ emit(idB, 3072);
+ emit('unrelated', 4096);
+ await vi.advanceTimersByTimeAsync(600);
+ expect(
+ active()
+ .map((item) => item.message)
+ .sort(),
+ ).toEqual(['Downloading… 25% · —', 'Downloading… 75% · —']);
+ a.resolve(success);
+ b.resolve(success);
+ await Promise.all([first, second]);
+ });
+
+ it('clears the spinner and listener after an IPC failure', async () => {
+ const result = deferred<typeof success>();
+ chatFetch.mockReturnValue(result.promise);
+ const pending = fetchChatFileWithToasts(origin, workdir, absPath);
+ await vi.advanceTimersByTimeAsync(600);
+ result.reject(new Error('offline'));
+ await expect(pending).resolves.toBeNull();
+ expect(active()).toHaveLength(1);
+ expect(active()[0].variant).toBe('error');
+ expect(listeners.size).toBe(0);
+ });
+
+ it('keeps stale-copy warnings separate from loading', async () => {
+ chatFetch.mockResolvedValue({ ...success, stale: true });
+ await fetchChatFileWithToasts(origin, workdir, absPath);
+ expect(active()[0]).toMatchObject({
+ variant: 'warning',
+ message: messages.chat.remoteFile.staleCopy,
+ });
+ });
+
+ it('shows unknown totals as bytes, resets speed between phases, and keeps packing/extraction distinct', async () => {
+ const result = deferred<{ ok: true; path: string; stale: boolean; skipped: number }>();
+ chatDownload.mockReturnValue(result.promise);
+ const pending = downloadRemoteChatEntry(origin, workdir, absPath);
+ const { requestId } = chatDownload.mock.calls[0][0];
+ emit(requestId, 1024, 0, 'pack');
+ await vi.advanceTimersByTimeAsync(600);
+ expect(active()[0].message).toBe('Remote computer is packing… 1.0 KB packed');
+ emit(requestId, 0, 4096, 'upload');
+ await vi.advanceTimersByTimeAsync(1000);
+ emit(requestId, 2048, 4096, 'upload');
+ expect(active()[0].message).toBe('Remote computer is uploading… 50% · 2.0 KB/s');
+ emit(requestId, 0, 0);
+ expect(active()[0].message).toBe(messages.chat.remoteFile.fetching);
+ await vi.advanceTimersByTimeAsync(1000);
+ emit(requestId, 1024, 0);
+ expect(active()[0].message).toBe('Downloading… 1.0 KB · 1.0 KB/s');
+ emit(requestId, 0, 0, 'extract');
+ expect(active()[0].message).toBe('Unpacking…');
+ result.resolve({ ok: true, path: '/downloads/file.zip', stale: false, skipped: 0 });
+ await pending;
+ expect(active()).toEqual([]);
+ expect(listeners.size).toBe(0);
+ });
+});
diff --git a/apps/desktop/src/renderer/components/chat/TextLightbox.tsx b/apps/desktop/src/renderer/components/chat/TextLightbox.tsx
index 6fb77fa272..d95db0ca95 100644
--- a/apps/desktop/src/renderer/components/chat/TextLightbox.tsx
+++ b/apps/desktop/src/renderer/components/chat/TextLightbox.tsx
@@ -32,6 +32,7 @@ import { toast } from '@/lib/toast';
import { Tooltip } from '@/components/ui/tooltip';
import { detectRenderable } from '@/lib/textPreview';
import { isRemoteFileOrigin } from '@/lib/sessionFileOrigin';
+import { observeFileTransferProgressText } from '@/lib/fileTransferProgress';
import {
chatFileErrorText,
downloadRemoteChatEntry,
@@ -122,8 +123,7 @@ export function TextLightbox({ filePath, fileName, initialLine, triggerRef, onCl
const sessionFileCtx = useChatSessionFile();
const remoteOrigin = isRemoteFileOrigin(sessionFileCtx.origin) ? sessionFileCtx.origin : null;
const [remoteCopy, setRemoteCopy] = useState<{ cachePath: string; stale: boolean } | null>(null);
- // 远端取回进度(chat-file:fetch 的 TRANSFER push,relPath 键 = 原始 absPath)。
- const [fetchProgress, setFetchProgress] = useState<{ received: number; total: number } | null>(null);
+ const [fetchProgressText, setFetchProgressText] = useState<string | null>(null);
const isClosingRef = useRef(false);
const bodyScrollRef = useRef<HTMLDivElement | null>(null);
const editorRef = useRef<PlaintextEditorHandle>(null);
@@ -219,11 +219,16 @@ export function TextLightbox({ filePath, fileName, initialLine, triggerRef, onCl
// response so we don't have to re-statically encode the MB number in two places.
useEffect(() => {
let cancelled = false;
+ setFetchProgressText(null);
+ const progress = remoteOrigin ? observeFileTransferProgressText(setFetchProgressText) : null;
(async () => {
try {
// 远程:先取回缓存副本(同 identity 与侧边栏共享,命中秒回),再读副本。
if (remoteOrigin) {
- const fetched = await fetchChatFileToCache(remoteOrigin, sessionFileCtx.workingDir, filePath);
+ const fetched = await fetchChatFileToCache(
+ remoteOrigin, sessionFileCtx.workingDir, filePath, progress?.requestId,
+ );
+ progress?.dispose();
if (cancelled) return;
if (!fetched.ok) {
setLoadState({ phase: 'error', message: chatFileErrorText(fetched.code) });
@@ -272,22 +277,16 @@ export function TextLightbox({ filePath, fileName, initialLine, triggerRef, onCl
phase: 'error',
message: err instanceof Error ? err.message : String(err),
});
+ } finally {
+ progress?.dispose();
}
})();
return () => {
cancelled = true;
+ progress?.dispose();
};
}, [filePath, remoteOrigin, sessionFileCtx.workingDir, t]);
- // 远程取回进度:大文件首拉可能秒级到分钟级,spinner 区显示百分比。
- useEffect(() => {
- if (!remoteOrigin || contentReady) return;
- const off = window.electronAPI.fileBrowser.onTransferProgress((e) => {
- if (e.relPath === filePath) setFetchProgress({ received: e.received, total: e.total });
- });
- return off;
- }, [remoteOrigin, contentReady, filePath]);
-
useEffect(() => {
if (!contentReady || loadState.phase !== 'ready') return;
@@ -556,10 +555,9 @@ export function TextLightbox({ filePath, fileName, initialLine, triggerRef, onCl
>
<Spinner size={32} className="text-[var(--msg-tool-card-chevron)]" />
<div>
- {remoteOrigin ? t('chat.remoteFile.fetching') : t('chat.textLightbox.loading')}
- {remoteOrigin && fetchProgress && fetchProgress.total > 0
- ? ` ${Math.min(100, Math.round((fetchProgress.received / fetchProgress.total) * 100))}%`
- : null}
+ {remoteOrigin
+ ? fetchProgressText ?? t('chat.remoteFile.fetching')
+ : t('chat.textLightbox.loading')}
</div>
</div>
) : (
diff --git a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileBodyView.tsx b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileBodyView.tsx
index e8dc2ff99c..d756a4daa8 100644
--- a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileBodyView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileBodyView.tsx
@@ -50,6 +50,7 @@ import { createPortal } from 'react-dom';
import { Save, Table2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { fileBrowserApiFor } from '@/lib/fileBrowserTransport';
+import { createFileTransferProgressValues } from '@/lib/fileTransferProgress';
import { Spinner } from '@/components/ui/spinner';
import { acquireFindInPage } from '@/components/find-in-page/findInPageOwnership';
@@ -1415,40 +1416,23 @@ function FetchingProgress({
phase?: 'upload' | 'download';
}) {
const { t } = useTranslation();
- const sample = useRef<{ t: number; bytes: number; speed: number; phase?: string }>({
- t: 0,
- bytes: 0,
- speed: 0,
- phase: undefined,
- });
- const now = performance.now();
- const st = sample.current;
- if (st.phase !== phase) {
- st.phase = phase;
- st.t = now;
- st.bytes = received;
- st.speed = 0;
- } else if (now - st.t >= 800) {
- const inst = Math.max(0, received - st.bytes) / ((now - st.t) / 1000);
- st.speed = st.speed > 0 ? st.speed * 0.6 + inst * 0.4 : inst;
- st.t = now;
- st.bytes = received;
- }
- const pct = total > 0 ? Math.floor((received / total) * 100) : 0;
+ const sample = useRef(createFileTransferProgressValues());
+ const values = sample.current({ received, total, phase });
return (
<div className="flex h-full w-full flex-col items-center justify-center gap-3">
<Spinner size={18} className="text-[var(--cmd-palette-item-meta)]" />
<span className="text-13 text-[var(--cmd-palette-item-meta)]">
{t(
- phase === 'upload'
- ? 'ccAgent.workdirBrowse.fileBody.fetchingRemoteUpload'
- : 'ccAgent.workdirBrowse.fileBody.fetchingRemote',
- {
- percent: pct,
- received: formatBytes(received),
- total: formatBytes(total),
- speed: st.speed > 0 ? `${formatBytes(st.speed)}/s` : '—',
- },
+ values.preparing
+ ? 'chat.remoteFile.fetching'
+ : total <= 0
+ ? phase === 'upload'
+ ? 'chat.remoteFile.uploadProgressUnknown'
+ : 'chat.remoteFile.downloadProgressUnknown'
+ : phase === 'upload'
+ ? 'ccAgent.workdirBrowse.fileBody.fetchingRemoteUpload'
+ : 'ccAgent.workdirBrowse.fileBody.fetchingRemote',
+ values,
)}
</span>
</div>
diff --git a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileContent.ts b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileContent.ts
index 91364c48fe..d3aa1e4ec9 100644
--- a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileContent.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileContent.ts
@@ -17,6 +17,7 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { createLogger } from '@/lib/logger';
+import { observeFileTransferProgress } from '@/lib/fileTransferProgress';
import { fileBrowserApiFor, onFileTreeEventFor } from '@/lib/fileBrowserTransport';
import {
getCachedFileContent,
@@ -155,6 +156,7 @@ export function useFileContent(
}
let cancelled = false;
+ let transferProgress: ReturnType<typeof observeFileTransferProgress> | undefined;
setState({ workdir, relPath, content: { kind: 'loading' } });
void (async () => {
@@ -167,8 +169,8 @@ export function useFileContent(
fallback: FileContent,
): Promise<void> => {
setState({ workdir, relPath, content: { kind: 'fetching', received: 0, total: size } });
- const off = window.electronAPI.fileBrowser.onTransferProgress((e) => {
- if (cancelled || e.workdir !== workdir || e.relPath !== relPath) return;
+ const progress = observeFileTransferProgress((e) => {
+ if (cancelled) return;
// 打包 / 解包阶段只出现在文件夹下载(relPath 键为远端绝对路径),这里收不到。
if (e.phase === 'pack' || e.phase === 'extract') return;
setState({
@@ -177,6 +179,7 @@ export function useFileContent(
content: { kind: 'fetching', received: e.received, total: e.total, phase: e.phase },
});
});
+ transferProgress = progress;
try {
const res = await window.electronAPI.fileBrowser.fetchRemote({
workdir,
@@ -185,6 +188,7 @@ export function useFileContent(
mtimeMs,
remoteHostId,
deviceId,
+ requestId: progress.requestId,
});
if (cancelled) return;
if (res.ok) {
@@ -203,7 +207,7 @@ export function useFileContent(
setState({ workdir, relPath, content: fallback });
}
} finally {
- off();
+ progress.dispose();
}
};
@@ -329,6 +333,7 @@ export function useFileContent(
return () => {
cancelled = true;
+ transferProgress?.dispose();
};
}, [workdir, relPath, remoteHostId, deviceId, refreshTick]);
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 29ae23ee81..4d60c7d070 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -9949,8 +9949,10 @@
"staleBadge": "Cached copy",
"downloadToLocal": "Download to this computer",
"downloadPacking": "Remote computer is packing… {{size}} packed",
- "downloadProgress": "Downloading… {{received}} / {{total}}",
- "downloadProgressUnknown": "Downloading… {{received}} received",
+ "downloadProgress": "Downloading… {{percent}}% · {{speed}}",
+ "downloadProgressUnknown": "Downloading… {{received}} · {{speed}}",
+ "uploadProgress": "Remote computer is uploading… {{percent}}% · {{speed}}",
+ "uploadProgressUnknown": "Remote computer is uploading… {{received}} · {{speed}}",
"downloadExtracting": "Unpacking…",
"downloadUnsupported": "The remote computer can't download folders yet. Update Cindy on that computer and try again",
"downloadNoSpace": "Not enough disk space to finish the download",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 4078b90952..ce4e4db6b7 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -9932,8 +9932,10 @@
"staleBadge": "キャッシュ済み",
"downloadToLocal": "このコンピュータにダウンロード",
"downloadPacking": "リモートコンピュータでまとめています…{{size}}",
- "downloadProgress": "ダウンロード中…{{received}} / {{total}}",
- "downloadProgressUnknown": "ダウンロード中…{{received}} 受信済み",
+ "downloadProgress": "ダウンロード中…{{percent}}% · {{speed}}",
+ "downloadProgressUnknown": "ダウンロード中…{{received}} · {{speed}}",
+ "uploadProgress": "リモート側でアップロード中…{{percent}}% · {{speed}}",
+ "uploadProgressUnknown": "リモート側でアップロード中…{{received}} · {{speed}}",
"downloadExtracting": "展開しています…",
"downloadUnsupported": "リモートコンピュータはまだフォルダのダウンロードに対応していません。そのコンピュータの Cindy を更新してから再試行してください",
"downloadNoSpace": "ディスクの空き容量が足りないため、ダウンロードを完了できません",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 03e664b777..55289112e2 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -9932,8 +9932,10 @@
"staleBadge": "캐시 복사본",
"downloadToLocal": "이 컴퓨터로 다운로드",
"downloadPacking": "원격 컴퓨터에서 묶는 중…{{size}} 완료",
- "downloadProgress": "다운로드 중…{{received}} / {{total}}",
- "downloadProgressUnknown": "다운로드 중…{{received}} 받음",
+ "downloadProgress": "다운로드 중…{{percent}}% · {{speed}}",
+ "downloadProgressUnknown": "다운로드 중…{{received}} · {{speed}}",
+ "uploadProgress": "원격 컴퓨터에서 업로드 중…{{percent}}% · {{speed}}",
+ "uploadProgressUnknown": "원격 컴퓨터에서 업로드 중…{{received}} · {{speed}}",
"downloadExtracting": "압축 푸는 중…",
"downloadUnsupported": "원격 컴퓨터가 아직 폴더 다운로드를 지원하지 않습니다. 해당 컴퓨터의 Cindy를 업데이트한 후 다시 시도하세요",
"downloadNoSpace": "디스크 공간이 부족해 다운로드를 완료할 수 없습니다",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 65d6b55de8..6a3b0ef1a0 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -9932,8 +9932,10 @@
"staleBadge": "历史副本",
"downloadToLocal": "下载到本地",
"downloadPacking": "远程电脑正在打包…已打包 {{size}}",
- "downloadProgress": "正在下载…{{received}} / {{total}}",
- "downloadProgressUnknown": "正在下载…已接收 {{received}}",
+ "downloadProgress": "正在下载…{{percent}}% · {{speed}}",
+ "downloadProgressUnknown": "正在下载…{{received}} · {{speed}}",
+ "uploadProgress": "远端正在上传…{{percent}}% · {{speed}}",
+ "uploadProgressUnknown": "远端正在上传…{{received}} · {{speed}}",
"downloadExtracting": "正在解压…",
"downloadUnsupported": "远程电脑暂不支持下载文件夹,请更新该电脑上的 Cindy 后重试",
"downloadNoSpace": "磁盘空间不足,无法完成下载",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index ab95f0ef1d..d86c2fb1a2 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -9931,8 +9931,10 @@
"staleBadge": "歷史副本",
"downloadToLocal": "下載到本機",
"downloadPacking": "遠端電腦正在打包…已打包 {{size}}",
- "downloadProgress": "正在下載…{{received}} / {{total}}",
- "downloadProgressUnknown": "正在下載…已接收 {{received}}",
+ "downloadProgress": "正在下載…{{percent}}% · {{speed}}",
+ "downloadProgressUnknown": "正在下載…{{received}} · {{speed}}",
+ "uploadProgress": "遠端正在上傳…{{percent}}% · {{speed}}",
+ "uploadProgressUnknown": "遠端正在上傳…{{received}} · {{speed}}",
"downloadExtracting": "正在解壓縮…",
"downloadUnsupported": "遠端電腦暫不支援下載資料夾,請更新該電腦上的 Cindy 後重試",
"downloadNoSpace": "磁碟空間不足,無法完成下載",
diff --git a/apps/desktop/src/renderer/lib/fileTransferProgress.ts b/apps/desktop/src/renderer/lib/fileTransferProgress.ts
new file mode 100644
index 0000000000..d956bcd31c
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/fileTransferProgress.ts
@@ -0,0 +1,91 @@
+import { i18n } from '@/i18n';
+import { formatBytes } from '@/features/cc-agent/workdir-browse/lib/fileMeta';
+import { toast } from './toast';
+
+export type FileTransferProgress = {
+ received: number;
+ total: number;
+ phase?: 'pack' | 'upload' | 'download' | 'extract';
+};
+
+/** One sampler per transfer, shared by toasts and previews. No synthetic progress. */
+export function createFileTransferProgressValues() {
+ let sample: { time: number; bytes: number; phase: string; speed: number | null } | undefined;
+ let lastReceived = 0;
+ return (e: FileTransferProgress) => {
+ const phase = e.phase ?? 'download';
+ const now = performance.now();
+ const received = Math.max(0, e.received);
+ if (!sample || sample.phase !== phase || received < lastReceived) {
+ sample = { time: now, bytes: received, phase, speed: null };
+ } else if (now - sample.time >= 800) {
+ const speed = ((received - sample.bytes) * 1000) / (now - sample.time);
+ sample = { time: now, bytes: received, phase, speed };
+ }
+ lastReceived = received;
+ return {
+ // Until bytes arrive, an unavailable peer may be preparing an OSS fallback.
+ preparing: phase === 'download' && received === 0,
+ percent: e.total > 0 ? Math.min(100, Math.floor((received / e.total) * 100)) : undefined,
+ received: formatBytes(received),
+ total: formatBytes(Math.max(0, e.total)),
+ speed: sample.speed === null ? '—' : `${formatBytes(Math.round(sample.speed))}/s`,
+ };
+ };
+}
+
+export function createFileTransferProgressText(): (e: FileTransferProgress) => string {
+ const sample = createFileTransferProgressValues();
+ return (e) => {
+ const values = sample(e);
+ if (e.phase === 'pack')
+ return i18n.t('chat.remoteFile.downloadPacking', { size: values.received });
+ if (e.phase === 'extract') return i18n.t('chat.remoteFile.downloadExtracting');
+ if (values.preparing) return i18n.t('chat.remoteFile.fetching');
+ const key = e.phase === 'upload' ? 'uploadProgress' : 'downloadProgress';
+ return i18n.t(`chat.remoteFile.${key}${e.total > 0 ? '' : 'Unknown'}`, values);
+ };
+}
+
+/** Subscribe before starting IPC. Paths alone cannot distinguish devices or concurrent reads. */
+export function observeFileTransferProgress(onProgress: (event: FileTransferProgress) => void) {
+ const requestId = crypto.randomUUID();
+ let disposed = false;
+ const unsubscribe = window.electronAPI.fileBrowser.onTransferProgress((e) => {
+ if (!disposed && e.requestId === requestId) onProgress(e);
+ });
+ return {
+ requestId,
+ dispose() {
+ if (disposed) return;
+ disposed = true;
+ unsubscribe();
+ },
+ };
+}
+
+export function observeFileTransferProgressText(onProgress: (text: string) => void) {
+ const format = createFileTransferProgressText();
+ return observeFileTransferProgress((e) => onProgress(format(e)));
+}
+
+/** Same delayed, persistent loading toast for open/reveal/copy and explicit downloads. */
+export function createFileTransferToast() {
+ let id: string | null = null;
+ let text = i18n.t('chat.remoteFile.fetching');
+ const progress = observeFileTransferProgressText((next) => {
+ text = next;
+ if (id) toast.update(id, text);
+ });
+ const delayed = setTimeout(() => {
+ id = toast.loading(text);
+ }, 600);
+ return {
+ requestId: progress.requestId,
+ dispose() {
+ clearTimeout(delayed);
+ progress.dispose();
+ if (id) toast.dismiss(id);
+ },
+ };
+}
diff --git a/apps/desktop/src/renderer/lib/remoteFileOpen.ts b/apps/desktop/src/renderer/lib/remoteFileOpen.ts
index a598caa551..9cc704b18f 100644
--- a/apps/desktop/src/renderer/lib/remoteFileOpen.ts
+++ b/apps/desktop/src/renderer/lib/remoteFileOpen.ts
@@ -18,7 +18,7 @@ import { shouldShowOpenPathError } from '../../shared/openPathResult';
*/
import { i18n } from '@/i18n';
-import { formatBytes } from '@/features/cc-agent/workdir-browse/lib/fileMeta';
+import { createFileTransferToast } from './fileTransferProgress';
import { toast } from './toast';
import type { SessionFileOrigin } from './sessionFileOrigin';
@@ -27,10 +27,16 @@ export type RemoteFileOrigin = Exclude<SessionFileOrigin, { kind: 'local' }>;
export type ChatFileFetchOutcome =
| { ok: true; cachePath: string; stale: boolean; size: number }
- | { ok: false; code: 'BAD_ARGS' | 'OUTSIDE_WORKDIR' | 'NOT_FOUND' | 'FETCH_FAILED'; message?: string };
+ | {
+ ok: false;
+ code: 'BAD_ARGS' | 'OUTSIDE_WORKDIR' | 'NOT_FOUND' | 'FETCH_FAILED';
+ message?: string;
+ };
/** 失败 code → i18n 文案。 */
-export function chatFileErrorText(code: Exclude<ChatFileFetchOutcome, { ok: true }>['code']): string {
+export function chatFileErrorText(
+ code: Exclude<ChatFileFetchOutcome, { ok: true }>['code'],
+): string {
if (code === 'OUTSIDE_WORKDIR') return i18n.t('chat.remoteFile.outsideWorkdir');
if (code === 'NOT_FOUND') return i18n.t('chat.remoteFile.notFound');
return i18n.t('chat.remoteFile.fetchFailed');
@@ -41,13 +47,19 @@ export async function fetchChatFileToCache(
origin: RemoteFileOrigin,
workdir: string,
absPath: string,
+ requestId?: string,
): Promise<ChatFileFetchOutcome> {
const wireOrigin =
origin.kind === 'device'
? ({ kind: 'device', deviceId: origin.deviceId } as const)
: ({ kind: 'ssh', remoteHostId: origin.remoteHostId } as const);
try {
- return await window.electronAPI.fileBrowser.chatFetch({ origin: wireOrigin, workdir, absPath });
+ return await window.electronAPI.fileBrowser.chatFetch({
+ origin: wireOrigin,
+ workdir,
+ absPath,
+ ...(requestId ? { requestId } : {}),
+ });
} catch (err) {
return { ok: false, code: 'FETCH_FAILED', message: String(err) };
}
@@ -63,12 +75,9 @@ export async function fetchChatFileWithToasts(
workdir: string,
absPath: string,
): Promise<string | null> {
- let fetchingToastId: string | null = null;
- const delayed = setTimeout(() => {
- fetchingToastId = toast.warning(i18n.t('chat.remoteFile.fetching'), { duration: 120_000 });
- }, 600);
+ const progress = createFileTransferToast();
try {
- const res = await fetchChatFileToCache(origin, workdir, absPath);
+ const res = await fetchChatFileToCache(origin, workdir, absPath, progress.requestId);
if (!res.ok) {
toast.error(chatFileErrorText(res.code));
return null;
@@ -76,8 +85,7 @@ export async function fetchChatFileWithToasts(
if (res.stale) toast.warning(i18n.t('chat.remoteFile.staleCopy'));
return res.cachePath;
} finally {
- clearTimeout(delayed);
- if (fetchingToastId) toast.dismiss(fetchingToastId);
+ progress.dispose();
}
}
@@ -104,23 +112,6 @@ function chatDownloadErrorText(code: ChatDownloadFailureCode): string {
return chatFileErrorText(code);
}
-function chatDownloadProgressText(e: {
- received: number;
- total: number;
- phase?: 'pack' | 'upload' | 'download' | 'extract';
-}): string {
- if (e.phase === 'pack') {
- return i18n.t('chat.remoteFile.downloadPacking', { size: formatBytes(e.received) });
- }
- if (e.phase === 'extract') return i18n.t('chat.remoteFile.downloadExtracting');
- return e.total > 0
- ? i18n.t('chat.remoteFile.downloadProgress', {
- received: formatBytes(Math.min(e.received, e.total)),
- total: formatBytes(e.total),
- })
- : i18n.t('chat.remoteFile.downloadProgressUnknown', { received: formatBytes(e.received) });
-}
-
/**
* 远程会话「下载到本地」:文件或文件夹下载到系统「下载」文件夹(重名自动加编号),
* 完成后在文件管理器中选中。取回超过 600ms 才弹进度 toast(缓存命中秒回时零打扰)。
@@ -130,25 +121,19 @@ export async function downloadRemoteChatEntry(
workdir: string,
absPath: string,
): Promise<void> {
- let progressToastId: string | null = null;
- let progressText = i18n.t('chat.remoteFile.fetching');
- const delayed = setTimeout(() => {
- progressToastId = toast.loading(progressText);
- }, 600);
- const requestId = crypto.randomUUID();
- const offProgress = window.electronAPI.fileBrowser.onTransferProgress((e) => {
- if (e.requestId !== requestId) return;
- progressText = chatDownloadProgressText(e);
- if (progressToastId) toast.update(progressToastId, progressText);
- });
+ const progress = createFileTransferToast();
const wireOrigin =
origin.kind === 'device'
? ({ kind: 'device', deviceId: origin.deviceId } as const)
: ({ kind: 'ssh', remoteHostId: origin.remoteHostId } as const);
try {
const res = await window.electronAPI.fileBrowser
- .chatDownload({ origin: wireOrigin, workdir, absPath, requestId })
- .catch((err: unknown) => ({ ok: false as const, code: 'FETCH_FAILED' as const, message: String(err) }));
+ .chatDownload({ origin: wireOrigin, workdir, absPath, requestId: progress.requestId })
+ .catch((err: unknown) => ({
+ ok: false as const,
+ code: 'FETCH_FAILED' as const,
+ message: String(err),
+ }));
if (!res.ok) {
toast.error(chatDownloadErrorText(res.code));
return;
@@ -158,9 +143,7 @@ export async function downloadRemoteChatEntry(
const shown = await window.electronAPI.showItemInFolder({ filePath: res.path });
if (!shown.success) toast.error(shown.error ?? i18n.t('chat.media.openFolderFailed'));
} finally {
- clearTimeout(delayed);
- offProgress();
- if (progressToastId) toast.dismiss(progressToastId);
+ progress.dispose();
}
}
@@ -241,19 +224,22 @@ function notifyVerdictChange(key: string): void {
function scheduleStaleSweep(delayMs: number): void {
// 已有定时器就复用:它一定排在同一或更早的时刻,醒来后会把剩下的重新排期。
if (staleTimer !== null) return;
- staleTimer = setTimeout(() => {
- staleTimer = null;
- const now = Date.now();
- let earliest = Number.POSITIVE_INFINITY;
- const expired: string[] = [];
- for (const [key, until] of unknownUntil) {
- if (until <= now) expired.push(key);
- else if (until < earliest) earliest = until;
- }
- for (const key of expired) unknownUntil.delete(key);
- if (earliest !== Number.POSITIVE_INFINITY) scheduleStaleSweep(earliest - now);
- for (const key of expired) notifyVerdictChange(key);
- }, Math.max(1, delayMs));
+ staleTimer = setTimeout(
+ () => {
+ staleTimer = null;
+ const now = Date.now();
+ let earliest = Number.POSITIVE_INFINITY;
+ const expired: string[] = [];
+ for (const [key, until] of unknownUntil) {
+ if (until <= now) expired.push(key);
+ else if (until < earliest) earliest = until;
+ }
+ for (const key of expired) unknownUntil.delete(key);
+ if (earliest !== Number.POSITIVE_INFINITY) scheduleStaleSweep(earliest - now);
+ for (const key of expired) notifyVerdictChange(key);
+ },
+ Math.max(1, delayMs),
+ );
}
function verdictKey(
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 6915cca876..687dc1dc74 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -2675,6 +2675,7 @@ interface ElectronAPI {
mtimeMs: number;
remoteHostId?: string | null;
deviceId?: string | null;
+ requestId?: string;
}) => Promise<{ ok: true; cachePath: string; stale: boolean } | { ok: false; message: string }>;
readCached: (params: {
cachePath: string;
@@ -2699,11 +2700,11 @@ interface ElectronAPI {
received: number;
total: number;
phase?: 'pack' | 'upload' | 'download' | 'extract';
- /** chatDownload 发起时带的请求 id(其它取回不带)。 */
+ /** fetchRemote / chatFetch / chatDownload 发起时带的请求 id。 */
requestId?: string;
}) => void,
) => () => void;
- /** 聊天流文件取回:远端绝对路径 → 本地缓存副本(进度经 onTransferProgress,relPath 键 = absPath)。 */
+ /** 聊天流文件取回:远端绝对路径 → 本地缓存副本(进度经 onTransferProgress,按 requestId 关联)。 */
previewHtml: (params: {
origin:
| { kind: 'local' }
@@ -2716,6 +2717,7 @@ interface ElectronAPI {
origin: { kind: 'device'; deviceId: string } | { kind: 'ssh'; remoteHostId: string };
workdir: string;
absPath: string;
+ requestId?: string;
}) => Promise<
| { ok: true; cachePath: string; stale: boolean; size: number }
| {
diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.md
index 58611f1847..6eb73d656c 100644
--- a/docs/dev-rules/remote-and-mobile-adaptation.md
+++ b/docs/dev-rules/remote-and-mobile-adaptation.md
@@ -299,6 +299,31 @@ review 按此检查:功能类 PR 缺这段说明 = P1。
触及 device-link 重试/超时/断链恢复路径的 PR,Description 还必须写明「故障半径
三问」的结论(故障层级、动作层级、多 peer 用例)。缺失同样 = P1。
+## 桌面远程文件获取的进度
+
+- 直传进度来自接收端每次成功写入的字节数,经 `device-link/fileAccess.ts` 的
+ `onProgress` 交给调用方;工作目录内的大文件与目录外的媒体取件都必须接入。
+ 日志采样不是 UI 进度源,不能等整份文件返回后才上报 100%。
+- 聊天打开/定位/复制、下载到本地和侧栏大文件预览,共用
+ `file-browser/transfer-progress.ts` 推送到发起窗口。用本机 IPC 的 `requestId`
+ 关联消费者,不按路径判断归属;它不进入跨设备协议,旧调用可省略。
+- 提示、文本预览与侧栏预览共用 `renderer/lib/fileTransferProgress.ts` 的订阅或采样。
+ 订阅先于请求,完成、失败、卸载时释放;同一路径跨设备、并发获取与下载互不影响。
+ 阶段切换、回退重置和完成不被限频丢弃;字节回退重置速度,总量未知不显示百分比。
+- 文件夹下载仍使用既有打包/发送/下载/解包进度。SSH 使用分片字节或 tar 流字节;
+ 不将播放中的 Range 缓冲当作整文件下载,也不为媒体协议后台预取弹出下载 Toast。
+- 目录外媒体回退旧 `media:fetch` 上传接口时,该接口没有上传字节回调;准备期间不编造
+ 上传百分比,开始本机下载后再显示真实进度。手机版有独立接收与播放器缓冲链路,
+ 不消费桌面本机 IPC;相关界面进度由 [PR #5542](https://github.com/makecindy/cindy/pull/5542)
+ 跟进,桌面修复不代表手机已覆盖。
+
+回归入口:`device-link/__tests__/filePeer.test.ts`(分块、观察者异常、取消与账号失效)、
+`device-link/__tests__/fileAccess.test.ts`(两类入口及回退)、
+`file-browser/__tests__/chatFile.test.ts`、`file-browser/__tests__/transferProgress.test.ts`,
+以及 `renderer/__tests__/remoteFileProgress.test.ts`
+(并发隔离、释放、百分比和速度)。源码路径均相对 `apps/desktop/src/main/`,
+最后一项相对 `apps/desktop/src/`。
+
## Review 清单
1. 涉及 workdir/agent/会话数据的功能,在 SSH 远程下是否走远程通道而非本机 `fs`?