Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(device-link): 改善弱网传输与远程网页预览恢复
Dashb73b8e7c0287
diff --git a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.tsindex d5b82d6830..45105c797b 100644--- a/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkIpc.test.ts@@ -870,6 +870,15 @@ describe('device-link controller handlers', () => {]);});+ it('keeps background admission local and preserves the remote argument list', async () => {+ const deps = makeDeps({ invoke: vi.fn().mockResolvedValue({ ok: true, result: [] }) });+ const args = [200, 'active'];+ await handleInvoke(deps, 'dev-2', 'local-db:sessions:list', args, { background: true });+ expect(deps.invoke).toHaveBeenCalledWith('dev-2', 'local-db:sessions:list', args, { background: true });+ await handleInvoke(deps, 'dev-2', 'local-db:sessions:list', args, { background: 'true' });+ expect(deps.invoke).toHaveBeenLastCalledWith('dev-2', 'local-db:sessions:list', args);+ });+it('invoke:CHANNEL_NOT_ALLOWED → 映射 IpcError', async () => {const deps = makeDeps({invoke: vi.fn().mockResolvedValue({diff --git a/apps/desktop/src/main/device-link/__tests__/ipcDiagnostics.test.ts b/apps/desktop/src/main/device-link/__tests__/ipcDiagnostics.test.tsindex 42268f5fa0..1cdc400c83 100644--- a/apps/desktop/src/main/device-link/__tests__/ipcDiagnostics.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/ipcDiagnostics.test.ts@@ -34,6 +34,12 @@ function harness() {const CHANNEL = 'local-db:sessions:list';describe('device-link IPC diagnostics', () => {+ it('preserves local background admission hints through the diagnostic wrapper', async () => {+ const h = harness();+ await h.observed.invoke('peer', CHANNEL, [], { background: true });+ expect(h.invoke).toHaveBeenCalledExactlyOnceWith('peer', CHANNEL, [], { background: true });+ h.diagnostics.flush();+ });it('aggregates a failure storm and successes without changing transport calls or errors', async () => {const h = harness();const error = new DeviceLinkError('BACKPRESSURE', 'private error');diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.tsindex 88524363ec..0bf73e8d00 100644--- a/apps/desktop/src/main/device-link/index.ts+++ b/apps/desktop/src/main/device-link/index.ts@@ -1838,7 +1838,7 @@ export async function remoteInvoke(deviceId: string,channel: string,args: unknown[],- options?: { preSend?: () => void },+ options?: { preSend?: () => void; background?: boolean },): Promise<InvokeResultPayload> {options?.preSend?.();assertNotStandby();@@ -1864,7 +1864,7 @@ export async function remoteInvoke(preSend();if (!client?.isLinkReady(deviceId))throw new DeviceLinkError('LINK_NOT_OPEN', 'file cleanup requires an existing link');- return client.invoke(deviceId, { channel, args }, resolveRemoteInvokeTimeoutMs(channel, args, 'desktop'), { preSend });+ return client.invoke(deviceId, { channel, args }, resolveRemoteInvokeTimeoutMs(channel, args, 'desktop'), { ...options, preSend });}const invoke = async (): Promise<InvokeResultPayload> => {// 熔断门禁(外层 guardInvoke)在连接等待之前:open 态快速失败,不消耗 1.5s 等待。@@ -1879,7 +1879,7 @@ export async function remoteInvoke(// 必须是 async:失效时返回 rejected promise,不能同步抛出绕过调用方的 .catch。const accelerated = await tryPeerInvoke(deviceId, channel, args, async (peer, nextChannel, nextArgs) => {preSend();- return remoteInvoke(peer, nextChannel, nextArgs, { preSend });+ return remoteInvoke(peer, nextChannel, nextArgs, { ...options, preSend });});preSend();if (accelerated) return accelerated;@@ -1890,7 +1890,7 @@ export async function remoteInvoke(() => openRemoteLink(deviceId, { observed: false }),preSend,);- return invokeClient.invoke(deviceId, { channel, args }, resolveRemoteInvokeTimeoutMs(channel, args, 'desktop'), { preSend });+ return invokeClient.invoke(deviceId, { channel, args }, resolveRemoteInvokeTimeoutMs(channel, args, 'desktop'), { ...options, preSend });};const run = (): Promise<InvokeResultPayload> =>invokeWithClosedLinkRecovery(diff --git a/apps/desktop/src/main/device-link/ipc.ts b/apps/desktop/src/main/device-link/ipc.tsindex 2a18d25efe..212b22e24b 100644--- a/apps/desktop/src/main/device-link/ipc.ts+++ b/apps/desktop/src/main/device-link/ipc.ts@@ -133,7 +133,7 @@ export interface DeviceLinkIpcDeps {apiFetch<T>(path: string, opts?: { method?: string; body?: unknown }): Promise<T>;openLink(deviceId: string): Promise<LinkAcceptPayload>;closeLink(deviceId: string): void;- invoke(deviceId: string, channel: string, args: unknown[]): Promise<InvokeResultPayload>;+ invoke(deviceId: string, channel: string, args: unknown[], options?: { background?: boolean }): Promise<InvokeResultPayload>;/** 分享者电脑的只读请求:先建后台链路再发(relay 只在建链时登记受邀者的电脑)。缺省时用 invoke。 */invokeProviderShareHost?(target: string, channel: string, args: unknown[]): Promise<InvokeResultPayload>;subscribe(deviceId: string, topics: string[]): Promise<InvokeResultPayload>;@@ -593,6 +593,7 @@ export async function handleInvoke(deviceId: unknown,channel: unknown,args: unknown,+ scheduling?: unknown,): Promise<unknown> {if (typeof deviceId !== 'string' || !deviceId.trim()) {throwIpcError('INVALID_PARAMS', 'deviceId is required');@@ -733,7 +734,12 @@ export async function handleInvoke(let result: InvokeResultPayload;try {- result = await deps.invoke(normalizedDeviceId, channel, callArgs);+ // Local admission hint only: never forward this field or change authorization.+ const background = scheduling && typeof scheduling === 'object'+ && 'background' in scheduling && scheduling.background === true;+ result = background+ ? await deps.invoke(normalizedDeviceId, channel, callArgs, { background: true })+ : await deps.invoke(normalizedDeviceId, channel, callArgs);} catch (err) {rethrowDeviceLinkError(err);}@@ -1539,7 +1545,7 @@ export function registerDeviceLinkIpc(deps: DeviceLinkIpcDeps = defaultDeps()):});ipcMain.handle(DEVICE_LINK_INVOKE.INVOKE, (e, payload: unknown) => {requireDeviceLinkCapability();- const p = (payload ?? {}) as { deviceId?: unknown; channel?: unknown; args?: unknown };+ const p = (payload ?? {}) as { deviceId?: unknown; channel?: unknown; args?: unknown; scheduling?: unknown };if (typeof p.deviceId === 'string' && parseProviderShareAgentDeviceId(p.deviceId)) {assertTrustedAppRendererEvent(e);return handleProviderShareInvoke(deps, p.deviceId, p.channel, p.args);@@ -1551,7 +1557,7 @@ export function registerDeviceLinkIpc(deps: DeviceLinkIpcDeps = defaultDeps()):() => handleInvoke(diagnostics.forWindow(deps, e.sender.id), p.deviceId, p.channel, p.args),);}- return handleInvoke(diagnostics.forWindow(deps, e.sender.id), p.deviceId, p.channel, p.args);+ return handleInvoke(diagnostics.forWindow(deps, e.sender.id), p.deviceId, p.channel, p.args, p.scheduling);});// 多窗口订阅引用计数:每个发起订阅的窗口(WebContents)挂一次 'destroyed' 清理,// 窗口关闭时释放它持有的全部引用,聚合出降零 topics 才向 relay 发 unsubscribediff --git a/apps/desktop/src/main/device-link/ipcDiagnostics.ts b/apps/desktop/src/main/device-link/ipcDiagnostics.tsindex 4aa3503614..05a1600c6a 100644--- a/apps/desktop/src/main/device-link/ipcDiagnostics.ts+++ b/apps/desktop/src/main/device-link/ipcDiagnostics.ts@@ -154,8 +154,9 @@ export function createDeviceLinkIpcDiagnostics(return {...deps,openLink: (peer) => observe(windowId, peer, 'open-link', '', () => deps.openLink(peer)),- invoke: (peer, channel, args) =>- observe(windowId, peer, 'invoke', channel, () => deps.invoke(peer, channel, args)),+ invoke: (peer, channel, args, options) =>+ observe(windowId, peer, 'invoke', channel, () => options+ ? deps.invoke(peer, channel, args, options) : deps.invoke(peer, channel, args)),subscribe: (peer, topics) =>observe(windowId, peer, 'subscribe', '', () => deps.subscribe(peer, topics)),unsubscribe: (peer, topics) =>diff --git a/apps/desktop/src/main/file-browser/__tests__/html-preview-ipc.test.ts b/apps/desktop/src/main/file-browser/__tests__/html-preview-ipc.test.tsindex db4deeb3d9..b3a8a63c13 100644--- a/apps/desktop/src/main/file-browser/__tests__/html-preview-ipc.test.ts+++ b/apps/desktop/src/main/file-browser/__tests__/html-preview-ipc.test.ts@@ -2,6 +2,7 @@ import { afterAll, beforeEach, expect, it, vi } from 'vitest';import fs from 'node:fs/promises';import os from 'node:os';import path from 'node:path';+import { EventEmitter } from 'node:events';const mocks = vi.hoisted(() => ({handle: vi.fn(),trusted: vi.fn(),@@ -21,6 +22,7 @@ vi.mock('../../device-link/broadcast-tap.js', () => ({}));vi.mock('../../localDb/client/current.js', () => ({ getDbClient: () => ({ drizzle: mocks.db }) }));import { disposeHtmlPreviews, registerHtmlPreviewIpc } from '../html-preview-ipc';+import { readPreviewMetadata } from '../html-preview-read';const args = {origin: { kind: 'device', deviceId: 'remote' },workdir: '/remote',@@ -64,7 +66,106 @@ it('returns an actionable typed error when the remote cannot read files', asyncawait expect(mocks.handle.mock.calls[0][1]({}, args)).rejects.toMatchObject({code: 'HTML_PREVIEW_UNSUPPORTED',});- expect(stat).toHaveBeenCalledWith(args, '/remote/preview', 'index.html');+ expect(stat).toHaveBeenCalledExactlyOnceWith(args, '/remote/preview', 'index.html', expect.any(AbortSignal));+});++// Unit tier, fake clock: the real metadata reader must survive transient+// congestion without retrying permanent errors or allowing unbounded waiting.+it('backs off read-only metadata across congestion and a short disconnect', async () => {+ vi.useFakeTimers();+ try {+ const stat = vi.fn()+ .mockRejectedValueOnce(Object.assign(new Error('busy'), { code: 'BACKPRESSURE' }))+ .mockRejectedValueOnce(new Error('[NOT_CONNECTED] reconnecting'))+ .mockResolvedValue({ type: 'file' });+ const result = readPreviewMetadata(stat, new AbortController().signal, () => true);+ await vi.advanceTimersByTimeAsync(999);+ expect(stat).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(1);+ expect(stat).toHaveBeenCalledTimes(2);+ await vi.advanceTimersByTimeAsync(2_000);+ await expect(result).resolves.toEqual({ type: 'file' });+ expect(stat).toHaveBeenCalledTimes(3);+ } finally { vi.useRealTimers(); }+});++it.each(['BACKPRESSURE', 'INVOKE_TIMEOUT', 'NOT_CONNECTED'])('bounds repeated %s failures and preserves the connection error', async (code) => {+ vi.useFakeTimers();+ try {+ let started!: () => void;+ const ready = new Promise<void>(resolve => { started = resolve; });+ const stat = vi.fn().mockImplementation(async () => {+ started();+ throw Object.assign(new Error('transient'), { code });+ });+ registerHtmlPreviewIpc({ stat, read: vi.fn() });+ const result = mocks.handle.mock.calls[0][1]({}, args).catch((e: unknown) => e);+ await ready;+ await vi.advanceTimersByTimeAsync(7_000);+ const expected = { BACKPRESSURE: 'DEVICE_LINK_BUSY', INVOKE_TIMEOUT: 'DEVICE_LINK_TIMEOUT', NOT_CONNECTED: 'DEVICE_LINK_NOT_CONNECTED' }[code];+ expect(await result).toMatchObject({ code: expected });+ expect(stat).toHaveBeenCalledTimes(4);+ } finally { vi.useRealTimers(); }+});++it('ends a stalled stat at the total deadline and aborts its downstream signal', async () => {+ vi.useFakeTimers();+ try {+ const stat = vi.fn(() => new Promise(() => {}));+ const result = readPreviewMetadata(stat, new AbortController().signal, () => true).catch(e => e);+ await vi.advanceTimersByTimeAsync(60_000);+ expect(await result).toMatchObject({ code: 'DEVICE_LINK_TIMEOUT' });+ expect(stat).toHaveBeenCalledOnce();+ expect((stat.mock.calls[0] as unknown as [AbortSignal])[0].aborted).toBe(true);+ } finally { vi.useRealTimers(); }+});++it.each(['cancel', 'owner-change'] as const)('does not start another read after %s during backoff', async (cause) => {+ vi.useFakeTimers();+ try {+ const controller = new AbortController();+ let current = true;+ const stat = vi.fn().mockRejectedValue(new Error('[BACKPRESSURE] busy'));+ const result = readPreviewMetadata(stat, controller.signal, () => current).catch(e => e);+ await vi.advanceTimersByTimeAsync(100);+ if (cause === 'cancel') controller.abort();+ else current = false;+ await vi.advanceTimersByTimeAsync(60_000);+ expect(await result).toMatchObject({ code: 'HTML_PREVIEW_CANCELLED' });+ expect(stat).toHaveBeenCalledOnce();+ expect(vi.getTimerCount()).toBe(0);+ } finally { vi.useRealTimers(); }+});++it.each(['cancel', 'destroyed', 'navigation'] as const)('cancels pending metadata on %s and discards its late success', async (trigger) => {+ let resolve!: (value: { relPath: string; type: 'file'; size: number; mtimeMs: number }) => void;+ let started!: () => void;+ const ready = new Promise<void>(done => { started = done; });+ let signal!: AbortSignal;+ const stat = vi.fn((_args, _root, _rel, attemptSignal) => {+ signal = attemptSignal;+ started();+ return new Promise<{ relPath: string; type: 'file'; size: number; mtimeMs: number }>(done => { resolve = done; });+ });+ registerHtmlPreviewIpc({ stat, read: vi.fn() });+ const open = mocks.handle.mock.calls[0][1];+ const cancel = mocks.handle.mock.calls[1][1];+ const sender = Object.assign(new EventEmitter(), { id: 10 });+ const result = open({ sender }, { ...args, requestId: 'preview-1' }).catch((e: unknown) => e);+ await ready;+ // A trusted but different window cannot cancel this sender's allocation.+ await cancel({ sender: { id: 11 } }, 'preview-1');+ expect(signal.aborted).toBe(false);+ if (trigger === 'cancel') await cancel({ sender }, 'preview-1');+ else if (trigger === 'destroyed') sender.emit('destroyed');+ else sender.emit('did-start-navigation', {}, 'https://example.test', false, true);+ expect(await result).toMatchObject({ code: 'HTML_PREVIEW_CANCELLED' });+ expect(signal.aborted).toBe(true);+ resolve({ relPath: 'index.html', type: 'file', size: 0, mtimeMs: 0 });+ await Promise.resolve();+ expect(stat).toHaveBeenCalledOnce();+ expect(sender.listenerCount('destroyed')).toBe(0);+ expect(sender.listenerCount('did-start-navigation')).toBe(0);});it('opens a preview before downloading even a large entry file', async () => {const read = vi.fn();diff --git a/apps/desktop/src/main/file-browser/__tests__/html-preview.test.ts b/apps/desktop/src/main/file-browser/__tests__/html-preview.test.tsindex 96d96d6719..5efeb7ca38 100644--- a/apps/desktop/src/main/file-browser/__tests__/html-preview.test.ts+++ b/apps/desktop/src/main/file-browser/__tests__/html-preview.test.ts@@ -155,7 +155,7 @@ describe('directory HTML preview', () => {cleanups.push(preview.close);expect(read).not.toHaveBeenCalled();expect(stat).toHaveBeenCalledTimes(1);- expect(stat).toHaveBeenCalledWith(args.workdir, 'index.html');+ expect(stat).toHaveBeenCalledWith(args.workdir, 'index.html', expect.any(AbortSignal));const initial = await fetch(preview.url, { redirect: 'manual' });const cookie = initial.headers.get('set-cookie')!.split(';')[0];const load = (p: string) => fetch(new URL(p, preview.url), { headers: { cookie } });diff --git a/apps/desktop/src/main/file-browser/html-preview-ipc.ts b/apps/desktop/src/main/file-browser/html-preview-ipc.tsindex 4066067417..bf59810bd6 100644--- a/apps/desktop/src/main/file-browser/html-preview-ipc.ts+++ b/apps/desktop/src/main/file-browser/html-preview-ipc.ts@@ -19,19 +19,28 @@ import {} from '../device-link/broadcast-tap.js';import { getDbClient } from '../localDb/client/current.js';import { throwIpcError } from '../utils/ipcValidate.js';+import { isIpcError } from '../../shared/ipc-errors.js';+import { previewTransportErrorCode, readPreviewMetadata } from './html-preview-read.js';const log = createLogger('html-preview');export const HTML_PREVIEW_CHANNEL = 'maker:html-preview:open';interface RemoteSource {- stat(args: HtmlPreviewArgs, root: string, rel: string): Promise<Omit<DirEntry, 'name'>>;+ stat(+ args: HtmlPreviewArgs,+ root: string,+ rel: string,+ signal?: AbortSignal,+ ): Promise<Omit<DirEntry, 'name'>>;read(args: HtmlPreviewArgs, root: string, entry: DirEntry, signal?: AbortSignal): Promise<string>;}const active = new Set<() => Promise<void>>();+const requests = new Map<string, { controller: AbortController; close?: () => Promise<void> }>();let preparing = 0;let shuttingDown = false;export async function disposeHtmlPreviews(): Promise<void> {shuttingDown = true;+ for (const request of requests.values()) request.controller.abort();await Promise.allSettled([...active].map((close) => close()));}export function registerHtmlPreviewIpc(remote: RemoteSource): void {@@ -39,11 +48,32 @@ export function registerHtmlPreviewIpc(remote: RemoteSource): void {assertTrustedAppRendererEvent(event);if (shuttingDown || preparing >= 8)throwIpcError('HTML_PREVIEW_TOO_LARGE', 'Preview capacity exceeded');+ if (+ args?.requestId !== undefined &&+ (typeof args.requestId !== 'string' || !/^[a-zA-Z0-9-]{1,128}$/.test(args.requestId))+ )+ throwIpcError('INVALID_PARAMS', 'Invalid preview request');+ const key = args?.requestId ? `${event.sender.id}:${args.requestId}` : undefined;+ if (key && requests.has(key)) throwIpcError('INVALID_PARAMS', 'Preview request already exists');+ const request = {+ controller: new AbortController(),+ close: undefined as (() => Promise<void>) | undefined,+ };+ if (key) requests.set(key, request);+ const cancel = () => request.controller.abort();+ event.sender?.once('destroyed', cancel);+ const onNavigate = (_event: unknown, _url: string, _inPlace: boolean, mainFrame: boolean) => {+ if (mainFrame) cancel();+ };+ event.sender?.on('did-start-navigation', onNavigate);preparing++;try {previewLocation(args);const scope = captureDataOwnerBroadcastScope();- const isCurrent = () => !shuttingDown && isDataOwnerBroadcastScopeCurrent(scope);+ const isCurrent = () =>+ !shuttingDown &&+ !request.controller.signal.aborted &&+ isDataOwnerBroadcastScopeCurrent(scope);const db = getDbClient().drizzle;// Finished snapshots are a bounded cache, not concurrent preparation slots.// External browsers cannot report tab closure; evict the oldest snapshot so@@ -55,11 +85,17 @@ export function registerHtmlPreviewIpc(remote: RemoteSource): void {}if (!isCurrent()) throw new Error('PREVIEW_CANCELLED');const preview = await createHtmlPreview(args, {+ signal: request.controller.signal,isCurrent,// Log status only: paths, signed URLs and page contents are not diagnostics.onResourceError: (status) => log.warn('Preview resource request failed', { status }),- stat: async (root, rel) => {- if (args.origin.kind !== 'local') return remote.stat(args, root, rel);+ stat: async (root, rel, signal) => {+ if (args.origin.kind !== 'local')+ return readPreviewMetadata(+ (attemptSignal) => remote.stat(args, root, rel, attemptSignal),+ signal ?? request.controller.signal,+ isCurrent,+ );const real = await fs.realpath(path.join(root, rel));if (!isPathAllowedAgainst(real, getSensitiveMediaBlocklist()))throw new Error('BAD_ARGS');@@ -112,8 +148,11 @@ export function registerHtmlPreviewIpc(remote: RemoteSource): void {const close = async () => {clearTimeout(expiry);active.delete(close);+ if (key && requests.get(key) === request) requests.delete(key);+ request.controller.abort();await preview.close();};+ request.close = close;active.add(close);// External browser pages outlive a chat tab; retain snapshots until expiry/app shutdown.const expiry = setTimeout(@@ -123,22 +162,45 @@ export function registerHtmlPreviewIpc(remote: RemoteSource): void {2 * 60 * 60 * 1000,);expiry.unref();+ if (!isCurrent()) {+ await close();+ throwIpcError('HTML_PREVIEW_CANCELLED', 'Preview cancelled');+ }return { ok: true as const, url: preview.url };} catch (error) {const message = error instanceof Error ? error.message : '';- const code = /PREVIEW_TOO_LARGE|DIRECTORY_TOO_LARGE/.test(message)- ? 'HTML_PREVIEW_TOO_LARGE'- : /COMPLETE_DIRECTORY_LISTING_UNSUPPORTED|unknown.*(op|method)|METHOD_NOT_FOUND|CHANNEL_NOT_ALLOWED/i.test(- message,- )- ? 'HTML_PREVIEW_UNSUPPORTED'- : /NOT_FOUND|ENOENT/.test(message)- ? 'NOT_FOUND'- : 'BROWSER_FILE_OPEN_FAILED';- log.warn('Preview preparation failed', { code });+ const code =+ request.controller.signal.aborted ||+ /PREVIEW_CANCELLED/.test(message) ||+ (isIpcError(error) && error.code === 'HTML_PREVIEW_CANCELLED')+ ? 'HTML_PREVIEW_CANCELLED'+ : (previewTransportErrorCode(error) ??+ (/PREVIEW_TOO_LARGE|DIRECTORY_TOO_LARGE/.test(message)+ ? 'HTML_PREVIEW_TOO_LARGE'+ : /COMPLETE_DIRECTORY_LISTING_UNSUPPORTED|unknown.*(op|method)|METHOD_NOT_FOUND|CHANNEL_NOT_ALLOWED/i.test(+ message,+ )+ ? 'HTML_PREVIEW_UNSUPPORTED'+ : /NOT_FOUND|ENOENT/.test(message)+ ? 'NOT_FOUND'+ : 'BROWSER_FILE_OPEN_FAILED'));+ if (code !== 'HTML_PREVIEW_CANCELLED') log.warn('Preview preparation failed', { code });throwIpcError(code, 'Could not prepare HTML preview');} finally {preparing--;+ event.sender?.removeListener('destroyed', cancel);+ event.sender?.removeListener('did-start-navigation', onNavigate);+ if (!request.close && key && requests.get(key) === request) requests.delete(key);}});+ ipcMain.handle('maker:html-preview:cancel', async (event, requestId: unknown) => {+ assertTrustedAppRendererEvent(event);+ if (typeof requestId !== 'string' || !/^[a-zA-Z0-9-]{1,128}$/.test(requestId))+ throwIpcError('INVALID_PARAMS', 'Invalid preview request');+ // The sender is authoritative: another window cannot cancel this allocation.+ const request = requests.get(`${event.sender.id}:${requestId}`);+ request?.controller.abort();+ await request?.close?.();+ return { ok: true };+ });}diff --git a/apps/desktop/src/main/file-browser/html-preview-read.ts b/apps/desktop/src/main/file-browser/html-preview-read.tsnew file mode 100644index 0000000000..2acf5d9847--- /dev/null+++ b/apps/desktop/src/main/file-browser/html-preview-read.ts@@ -0,0 +1,91 @@+import { createIpcError, type IpcErrorCode } from '../../shared/ipc-errors.js';++const TRANSPORT_ERRORS = {+ BACKPRESSURE: 'DEVICE_LINK_BUSY',+ DEVICE_LINK_BUSY: 'DEVICE_LINK_BUSY',+ INVOKE_TIMEOUT: 'DEVICE_LINK_TIMEOUT',+ DEVICE_LINK_TIMEOUT: 'DEVICE_LINK_TIMEOUT',+ NOT_CONNECTED: 'DEVICE_LINK_NOT_CONNECTED',+ DEVICE_LINK_NOT_CONNECTED: 'DEVICE_LINK_NOT_CONNECTED',+ LINK_NOT_OPEN: 'DEVICE_LINK_NOT_CONNECTED',+ DEVICE_OFFLINE: 'DEVICE_LINK_DEVICE_OFFLINE',+ DEVICE_LINK_DEVICE_OFFLINE: 'DEVICE_LINK_DEVICE_OFFLINE',+ DEVICE_UNRESPONSIVE: 'DEVICE_LINK_DEVICE_UNRESPONSIVE',+ DEVICE_LINK_DEVICE_UNRESPONSIVE: 'DEVICE_LINK_DEVICE_UNRESPONSIVE',+ PEER_RESET: 'DEVICE_LINK_NOT_CONNECTED',+} satisfies Record<string, IpcErrorCode>;++/** Closed vocabulary; never expose the remote error text or path to the UI. */+export function previewTransportErrorCode(error: unknown): IpcErrorCode | undefined {+ const code = error && typeof error === 'object' && 'code' in error ? error.code : undefined;+ const key =+ typeof code === 'string'+ ? code+ : error instanceof Error+ ? /^\[([A-Z_]+)\]/.exec(error.message)?.[1]+ : undefined;+ return key && Object.hasOwn(TRANSPORT_ERRORS, key)+ ? TRANSPORT_ERRORS[key as keyof typeof TRANSPORT_ERRORS]+ : undefined;+}++/** Retry only the preview's read-only stat, never a whole remote-op channel or download. */+export async function readPreviewMetadata<T>(+ read: (signal: AbortSignal) => Promise<T>,+ signal: AbortSignal,+ isCurrent: () => boolean,+): Promise<T> {+ const budget = new AbortController();+ const timeoutError = createIpcError('DEVICE_LINK_TIMEOUT', 'Preview read timed out');+ const timer = setTimeout(() => budget.abort(timeoutError), 60_000);+ const combined = AbortSignal.any([signal, budget.signal]);+ const started = performance.now();+ const check = () => {+ if (signal.aborted || !isCurrent())+ throw createIpcError('HTML_PREVIEW_CANCELLED', 'Preview cancelled');+ if (budget.signal.aborted || performance.now() - started >= 60_000) throw timeoutError;+ };+ let rejectAbort!: (reason: unknown) => void;+ const aborted = new Promise<never>((_, reject) => {+ rejectAbort = reject;+ });+ const onAbort = () => {+ try {+ check();+ } catch (error) {+ rejectAbort(error);+ }+ };+ combined.addEventListener('abort', onAbort, { once: true });+ try {+ for (let attempt = 0; ; attempt++) {+ check();+ try {+ const value = await Promise.race([read(combined), aborted]);+ check();+ return value;+ } catch (error) {+ check();+ const code = previewTransportErrorCode(error);+ if (!code || attempt >= 3) throw error;+ let retryTimer: ReturnType<typeof setTimeout> | undefined;+ try {+ await Promise.race([+ new Promise<void>((resolve) => {+ retryTimer = setTimeout(resolve, 1_000 * 2 ** attempt);+ }),+ aborted,+ ]);+ } finally {+ clearTimeout(retryTimer);+ }+ }+ }+ } catch (error) {+ check();+ throw error;+ } finally {+ clearTimeout(timer);+ combined.removeEventListener('abort', onAbort);+ }+}diff --git a/apps/desktop/src/main/file-browser/html-preview.ts b/apps/desktop/src/main/file-browser/html-preview.tsindex 36dab192e7..22ebd66524 100644--- a/apps/desktop/src/main/file-browser/html-preview.ts+++ b/apps/desktop/src/main/file-browser/html-preview.ts@@ -17,11 +17,14 @@ export interface HtmlPreviewArgs {| { kind: 'ssh'; remoteHostId: string };workdir: string;absPath: string;+ /** Viewer-local cancellation identity; never sent to the remote computer. */+ requestId?: string;}export interface PreviewSource {+ signal?: AbortSignal;isCurrent?(): boolean;onResourceError?(status: number): void;- stat(root: string, rel: string): Promise<Omit<DirEntry, 'name'>>;+ stat(root: string, rel: string, signal?: AbortSignal): Promise<Omit<DirEntry, 'name'>>;read(root: string, entry: DirEntry, signal?: AbortSignal): Promise<string>;/** Media goes through the existing managed store; other files are copied into staging. */materialize(source: string, destination: string, expectedSize: number): Promise<string>;@@ -134,7 +137,7 @@ export async function createHtmlPreview(args: HtmlPreviewArgs, source: PreviewSoconst pending = new Set<Promise<void>>();const queue = createFileReadQueue();const materialized = new Map<string, { path: string; size: number }>();- const current = () => !closed && source.isCurrent?.() !== false;+ const current = () => !closed && !source.signal?.aborted && source.isCurrent?.() !== false;const close = async () => {closed = true;controller.abort();@@ -148,11 +151,13 @@ export async function createHtmlPreview(args: HtmlPreviewArgs, source: PreviewSo.catch(() => { /* Temporary storage can be reclaimed by the OS if cleanup fails. */ });};try {- const initial = await source.stat(root, entry);+ if (!current()) throw new Error('PREVIEW_CANCELLED');+ const initial = await source.stat(root, entry, source.signal ?? controller.signal);+ if (!current()) throw new Error('PREVIEW_CANCELLED');if (initial.type !== 'file') throw new Error('NOT_FOUND');const materialize = async (relPath: string, directory: string, signal: AbortSignal) => {if (!current() || signal.aborted) throw new Error('PREVIEW_CANCELLED');- const metadata = await source.stat(root, relPath);+ const metadata = await source.stat(root, relPath, signal);if (metadata.type !== 'file' || metadata.relPath !== relPath || !Number.isSafeInteger(metadata.size) || metadata.size < 0)throw new Error('NOT_FOUND');const file = { ...metadata, name: relPath.split('/').pop()! };diff --git a/apps/desktop/src/main/file-browser/index.ts b/apps/desktop/src/main/file-browser/index.tsindex f5aaf31c4a..22b9db4f0a 100644--- a/apps/desktop/src/main/file-browser/index.ts+++ b/apps/desktop/src/main/file-browser/index.ts@@ -176,8 +176,11 @@ interface WatchArgs extends RemoteRoutedArgs {* ({ok,result}|{ok:false,error}),handler 的真实返回值在 result 里——renderer* 通路由 ipc.ts 解包,main 直调必须自己解,否则读信封字段恒错(真机实踩)。*/-async function deviceOpInvoke<T>(deviceId: string, opArgs: Record<string, unknown>): Promise<T> {- const payload = await remoteInvoke(deviceId, FILE_BROWSER_REMOTE_OP_CHANNEL, [opArgs]);+async function deviceOpInvoke<T>(deviceId: string, opArgs: Record<string, unknown>, signal?: AbortSignal): Promise<T> {+ const options = signal ? { preSend: () => signal.throwIfAborted() } : undefined;+ const payload = options+ ? await remoteInvoke(deviceId, FILE_BROWSER_REMOTE_OP_CHANNEL, [opArgs], options)+ : await remoteInvoke(deviceId, FILE_BROWSER_REMOTE_OP_CHANNEL, [opArgs]);if (!payload.ok) {throw new Error(`[${payload.error.code}] ${payload.error.message}`);}@@ -397,17 +400,19 @@ export function registerFileBrowserIpc(): void {// 日志设施由宿主注入——desktop 侧接统一 logger(规则 12),scope 与抽包前一致。setFileBrowserCoreLoggerFactory(createLogger);registerHtmlPreviewIpc({- stat: async (args, root, relPath) => {+ stat: async (args, root, relPath, signal) => {+ signal?.throwIfAborted();if (args.origin.kind === 'device') {return deviceOpInvoke<import('@cindy/file-browser-core').FileStat>(args.origin.deviceId, {op: 'stat', workdir: root, relPath,- });+ }, signal);}if (args.origin.kind !== 'ssh') throw new Error('BAD_ARGS');await getRemoteFileBrowser().request(args.origin.remoteHostId, 'stat', {workdir: args.workdir,relPath: toWorkdirRel(args.workdir, args.absPath)!,});+ signal?.throwIfAborted();return getRemoteFileBrowser().request(args.origin.remoteHostId, 'stat', { workdir: root, relPath });},read: async (args, root, entry, signal) => {diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 133a6ee233..44e7cba38a 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -2938,7 +2938,9 @@ contextBridge.exposeInMainWorld('electronAPI', {| { kind: 'ssh'; remoteHostId: string };workdir: string;absPath: string;+ requestId?: string;}): Promise<{ ok: true; url: string }> => ipcRenderer.invoke('maker:html-preview:open', params),+ cancelHtmlPreview: (requestId: string): Promise<{ ok: true }> => ipcRenderer.invoke('maker:html-preview:cancel', requestId),chatFetch: (params: {origin: { kind: 'device'; deviceId: string } | { kind: 'ssh'; remoteHostId: string };workdir: string;@@ -4669,8 +4671,8 @@ contextBridge.exposeInMainWorld('electronAPI', {closeLink: (deviceId: string): Promise<{ ok: true }> =>ipcRenderer.invoke('device-link:close-link', { deviceId }),/** 远程调用被控端的 allowlist 内 channel;成功直接拿返回值,失败 reject 带 code 的 Error */- invoke: (deviceId: string, channel: string, args: unknown[]): Promise<unknown> =>- ipcRenderer.invoke('device-link:invoke', { deviceId, channel, args }),+ invoke: (deviceId: string, channel: string, args: unknown[], scheduling?: { background?: boolean }): Promise<unknown> =>+ ipcRenderer.invoke('device-link:invoke', { deviceId, channel, args, ...(scheduling ? { scheduling } : {}) }),/** 控制端:订阅被控端某 topic 的变更推送(push 驱动侧边栏 / 会话视图) */subscribe: (deviceId: string, topics: string[]): Promise<{ ok: true }> =>ipcRenderer.invoke('device-link:topic-subscribe', { deviceId, topics }),diff --git a/apps/desktop/src/preload/sidebarWindowPreload.ts b/apps/desktop/src/preload/sidebarWindowPreload.tsindex d7476f3257..a9cd9ea12b 100644--- a/apps/desktop/src/preload/sidebarWindowPreload.ts+++ b/apps/desktop/src/preload/sidebarWindowPreload.ts@@ -139,8 +139,8 @@ contextBridge.exposeInMainWorld('electronAPI', {deviceLink: {getState: (): Promise<unknown> => ipcRenderer.invoke(DEVICE_LINK_INVOKE.GET_STATE),listDevices: (): Promise<unknown> => ipcRenderer.invoke(DEVICE_LINK_INVOKE.LIST_DEVICES),- invoke: (deviceId: string, channel: string, args: unknown[]): Promise<unknown> =>- ipcRenderer.invoke(DEVICE_LINK_INVOKE.INVOKE, { deviceId, channel, args }),+ invoke: (deviceId: string, channel: string, args: unknown[], scheduling?: { background?: boolean }): Promise<unknown> =>+ ipcRenderer.invoke(DEVICE_LINK_INVOKE.INVOKE, { deviceId, channel, args, ...(scheduling ? { scheduling } : {}) }),subscribe: (deviceId: string, topics: string[]): Promise<{ ok: true }> =>ipcRenderer.invoke(DEVICE_LINK_INVOKE.SUBSCRIBE, { deviceId, topics }),unsubscribe: (deviceId: string, topics: string[]): Promise<{ ok: true }> =>@@ -226,6 +226,7 @@ contextBridge.exposeInMainWorld('electronAPI', {cachePut: (params: unknown): Promise<unknown> => ipcRenderer.invoke('maker:file-browser:cache-put', params),onTransferProgress: (cb: (event: unknown) => void): (() => void) => onPayload('maker:file-browser:transfer', cb),previewHtml: (params: unknown): Promise<unknown> => ipcRenderer.invoke('maker:html-preview:open', params),+ cancelHtmlPreview: (requestId: string): Promise<{ ok: true }> => ipcRenderer.invoke('maker:html-preview:cancel', requestId),chatFetch: (params: unknown): Promise<unknown> => ipcRenderer.invoke('maker:chat-file:fetch', params),chatDownload: (params: unknown): Promise<unknown> => ipcRenderer.invoke('maker:chat-file:download', params),chatCancel: (requestId: string): Promise<unknown> => ipcRenderer.invoke('maker:chat-file:cancel', requestId),diff --git a/apps/desktop/src/renderer/__tests__/htmlPreviewOpening.test.ts b/apps/desktop/src/renderer/__tests__/htmlPreviewOpening.test.tsindex c8370d4c69..18653becde 100644--- a/apps/desktop/src/renderer/__tests__/htmlPreviewOpening.test.ts+++ b/apps/desktop/src/renderer/__tests__/htmlPreviewOpening.test.ts@@ -2,7 +2,7 @@import { beforeEach, expect, it, vi } from 'vitest';import type { TFunction } from 'i18next';const mocks = vi.hoisted(() => ({- local: vi.fn(), sidebar: vi.fn(), preference: vi.fn(() => 'sidebar'), preview: vi.fn(), external: vi.fn(), error: vi.fn(), loading: vi.fn(() => 'loading'), dismiss: vi.fn(),+ local: vi.fn(), sidebar: vi.fn(), preference: vi.fn(() => 'sidebar'), preview: vi.fn(), cancel: vi.fn(), external: vi.fn(), error: vi.fn(), loading: vi.fn(() => 'loading'), dismiss: vi.fn(),}));vi.mock('@/features/right-sidebar/lib/openInSidebarBrowser', async (importOriginal) => ({...await importOriginal<typeof import('../features/right-sidebar/lib/openInSidebarBrowser')>(),@@ -19,11 +19,12 @@ beforeEach(() => {mocks.preference.mockReturnValue('sidebar');mocks.preview.mockResolvedValue({ ok: true, url: 'http://127.0.0.1:12345/token/' });mocks.external.mockResolvedValue({ success: true });- Object.defineProperty(window, 'electronAPI', { configurable: true, value: { fileBrowser: { previewHtml: mocks.preview }, openExternal: mocks.external, openFileInBrowser: mocks.local } });+ mocks.cancel.mockResolvedValue({ ok: true });+ Object.defineProperty(window, 'electronAPI', { configurable: true, value: { fileBrowser: { previewHtml: mocks.preview, cancelHtmlPreview: mocks.cancel }, openExternal: mocks.external, openFileInBrowser: mocks.local } });});it('prepares the remote directory before opening the built-in browser', async () => {await openHtmlFileByPreference('session', '/remote/preview/index.html', t, context);- expect(mocks.preview).toHaveBeenCalledWith({ origin: context.origin, workdir: '/remote', absPath: '/remote/preview/index.html' });+ expect(mocks.preview).toHaveBeenCalledWith({ origin: context.origin, workdir: '/remote', absPath: '/remote/preview/index.html', requestId: expect.any(String) });expect(mocks.sidebar).toHaveBeenCalledWith('session', 'http://127.0.0.1:12345/token/');expect(mocks.external).not.toHaveBeenCalled();});@@ -51,7 +52,7 @@ it.each([false, true])('dismisses neutral loading when preview settles (failure=}));const opening = openHtmlFileByPreference('session', '/remote/index.html', t, context);await vi.advanceTimersByTimeAsync(600);- expect(mocks.loading).toHaveBeenCalledWith('chat.remoteFile.previewFetching');+ expect(mocks.loading).toHaveBeenCalledWith('chat.remoteFile.previewFetching', expect.objectContaining({ action: { label: 'common.cancel', onClick: expect.any(Function) } }));expect(mocks.error).not.toHaveBeenCalled();settle();await opening;@@ -83,6 +84,43 @@ it('honors both explicit local menu targets and reports local open failures', asit('keeps SSH HTML on the remote preview path', async () => {const ssh = { origin: { kind: 'ssh' as const, remoteHostId: 'host' }, workingDir: '/remote' };await openHtmlFileByPreference('session', '/remote/index.html', t, ssh);- expect(mocks.preview).toHaveBeenCalledWith({ origin: ssh.origin, workdir: '/remote', absPath: '/remote/index.html' });+ expect(mocks.preview).toHaveBeenCalledWith({ origin: ssh.origin, workdir: '/remote', absPath: '/remote/index.html', requestId: expect.any(String) });expect(mocks.local).not.toHaveBeenCalled();});++// Production opener + deferred IPC: repeated clicks used to allocate multiple+// previews; cancellation must suppress a late result even if IPC already completed.+it('coalesces clicks, cancels waiting, and permits a fresh open without late navigation', async () => {+ vi.useFakeTimers();+ try {+ let finish!: (value: unknown) => void;+ mocks.preview.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));+ const first = openHtmlFileByPreference('session', '/remote/index.html', t, context);+ const duplicate = openHtmlFileByPreference('session', '/remote/index.html', t, context);+ expect(mocks.preview).toHaveBeenCalledOnce();+ await vi.advanceTimersByTimeAsync(600);+ const [, options] = mocks.loading.mock.calls[0] as unknown as [string, { action: { onClick(): void }; onClose(): void }];+ options.action.onClick();+ options.onClose();+ expect(mocks.cancel).toHaveBeenCalledExactlyOnceWith(mocks.preview.mock.calls[0][0].requestId);+ await openHtmlFileByPreference('session', '/remote/index.html', t, context);+ expect(mocks.sidebar).toHaveBeenCalledOnce();+ finish({ url: 'http://127.0.0.1/stale/' });+ await Promise.all([first, duplicate]);+ expect(mocks.sidebar).toHaveBeenCalledOnce();+ expect(mocks.error).not.toHaveBeenCalled();+ } finally { vi.useRealTimers(); }+});++it.each([+ ['DEVICE_LINK_BUSY', 'previewConnectionBusy'],+ ['DEVICE_LINK_TIMEOUT', 'previewTimeout'],+ ['DEVICE_LINK_NOT_CONNECTED', 'previewDisconnected'],+ ['HTML_PREVIEW_CANCELLED', undefined],+])('reports %s without confusing connectivity with a missing file', async (code, key) => {+ mocks.preview.mockRejectedValueOnce(new Error(`[${code}] remote detail`));+ await openHtmlFileByPreference('session', '/remote/index.html', t, context);+ if (key) expect(mocks.error).toHaveBeenCalledWith(`chat.remoteFile.${key}`);+ else expect(mocks.error).not.toHaveBeenCalled();+ expect(mocks.sidebar).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.tsindex ca2f94fb3f..51a6747bf7 100644--- a/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts+++ b/apps/desktop/src/renderer/__tests__/refreshRemoteSessionsRetry.test.ts@@ -65,6 +65,16 @@ it('keeps cached content and leaves recovery probing to main while a device is uexpect(invoke).toHaveBeenCalledOnce();});+it('marks periodic and archived reads as background while keeping initial reads foreground', async () => {+ invoke.mockResolvedValue([]);+ const initial = did();+ const periodic = did();+ await refreshRemoteDeviceSessions(initial);+ await refreshRemoteDeviceSessions(periodic, undefined, { coalescingMode: 'weak' });+ expect(invoke.mock.calls.find(([peer]) => peer === initial)?.[3]).toEqual({ background: false });+ expect(invoke.mock.calls.find(([peer]) => peer === periodic)?.[3]).toEqual({ background: true });+});+it('stops an existing retry chain as soon as main opens the circuit', async () => {const device = did();invoke.mockRejectedValue(new Error('[DEVICE_LINK_TIMEOUT] timeout'));@@ -672,7 +682,7 @@ describe('refreshRemoteDeviceSessions retry', () => {200,'active',{ includePinned: true, fresh: true },- ]);+ ], { background: false });expect(remoteProjectsStore.getMergedRemoteSessions().map((s) => s.id)).toEqual(['recent-1','recent-2',@@ -694,7 +704,7 @@ describe('refreshRemoteDeviceSessions retry', () => {1000,'archived',{ includePinned: true, fresh: true },- ]);+ ], { background: true });expect(remoteProjectsStore.getDeviceSessions(d, 'active').map((s) => s.id)).toEqual(['active-1',]);@@ -771,7 +781,7 @@ describe('refreshRemoteDeviceSessions retry', () => {1000,'archived',{ includePinned: true, fresh: true },- ]);+ ], { background: true });});it('周期有界快照更新命中行但保留 200 条窗口外的有效会话', async () => {@@ -1019,7 +1029,7 @@ describe('refreshRemoteDeviceSessions retry', () => {200,'active',{ includePinned: true, fresh: true },- ]);+ ], { background: false });invoke.mockClear();invoke.mockResolvedValue([]);@@ -1031,7 +1041,7 @@ describe('refreshRemoteDeviceSessions retry', () => {200,'active',{ includePinned: true },- ]);+ ], { background: true });});it('同设备补跑排队时立即作废当前 snapshot,避免旧结果短暂覆盖 push 状态', async () => {@@ -1085,6 +1095,7 @@ describe('refreshRemoteDeviceSessions retry', () => {'active',{ includePinned: true, fresh: true },]);+ expect(invoke.mock.calls[1]?.[3]).toEqual({ background: false });});it('事件型 refresh 在途时弱周期 tick 直接复用,不补跑也不取消当前请求', async () => {diff --git a/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx b/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsxindex c8fb9e7423..e1656f2f2f 100644--- a/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx+++ b/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx@@ -92,6 +92,9 @@ export async function activateMessageUrl(}}+// Repeated clicks share preparation and navigation, not a completed-result cache.+const pendingHtmlPreviews = new Map<string, Promise<void>>();+/** Local HTML opens in place; remote HTML uses the viewer-local HTTP preview. */export async function openHtmlFileByPreference(sessionId: string,@@ -122,36 +125,77 @@ export async function openHtmlFileByPreference(}return;}- let loading: string | null = null;- const delayed = setTimeout(() => {- loading = toast.loading(t('chat.remoteFile.previewFetching'));- }, 600);- try {- const result = await window.electronAPI.fileBrowser.previewHtml({- origin: context.origin,- workdir: context.workingDir,- absPath,- });- if ((target ?? getLinkOpenPreference('local')) === 'sidebar' && sessionId) {- await openInSidebar(sessionId, result.url, t);- } else {- const opened = await window.electronAPI.openExternal(result.url);- if (!opened.success) toast.error(t('chat.markdownRenderer.openInBrowserFailed'));+ const resolvedTarget = target ?? getLinkOpenPreference('local');+ const key = JSON.stringify([sessionId, context.origin, context.workingDir, absPath, resolvedTarget]);+ const pending = pendingHtmlPreviews.get(key);+ if (pending) return pending;+ const opening = prepareRemoteHtml().finally(() => {+ if (pendingHtmlPreviews.get(key) === opening) pendingHtmlPreviews.delete(key);+ });+ pendingHtmlPreviews.set(key, opening);+ return opening;++ async function prepareRemoteHtml(): Promise<void> {+ const requestId = crypto.randomUUID();+ let cancelled = false;+ let finished = false;+ let loading: string | null = null;+ const cancel = () => {+ if (cancelled || finished) return;+ cancelled = true;+ pendingHtmlPreviews.delete(key);+ void window.electronAPI.fileBrowser.cancelHtmlPreview(requestId).catch(() => {});+ if (loading) toast.dismiss(loading);+ };+ window.addEventListener('beforeunload', cancel);+ const delayed = setTimeout(() => {+ if (cancelled) return;+ loading = toast.loading(t('chat.remoteFile.previewFetching'), {+ action: { label: t('common.cancel'), onClick: cancel },+ onClose: cancel,+ });+ }, 600);+ try {+ const result = await window.electronAPI.fileBrowser.previewHtml({+ origin: context.origin,+ workdir: context.workingDir,+ absPath,+ requestId,+ });+ if (cancelled) return;+ finished = true;+ if (resolvedTarget === 'sidebar' && sessionId) {+ await openInSidebar(sessionId, result.url, t);+ } else {+ const opened = await window.electronAPI.openExternal(result.url);+ if (!opened.success) toast.error(t('chat.markdownRenderer.openInBrowserFailed'));+ }+ } catch (error) {+ const code = extractIpcError(error)?.code;+ if (cancelled || code === 'HTML_PREVIEW_CANCELLED') return;+ const key =+ code === 'DEVICE_LINK_BUSY'+ ? 'previewConnectionBusy'+ : code === 'DEVICE_LINK_TIMEOUT'+ ? 'previewTimeout'+ : code === 'DEVICE_LINK_NOT_CONNECTED' ||+ code === 'DEVICE_LINK_DEVICE_OFFLINE' ||+ code === 'DEVICE_LINK_DEVICE_UNRESPONSIVE'+ ? 'previewDisconnected'+ : code === 'HTML_PREVIEW_TOO_LARGE'+ ? 'previewTooLarge'+ : code === 'HTML_PREVIEW_UNSUPPORTED'+ ? 'previewUnsupported'+ : code === 'NOT_FOUND'+ ? 'previewNotFound'+ : 'previewFailed';+ toast.error(t(`chat.remoteFile.${key}`));+ } finally {+ finished = true;+ window.removeEventListener('beforeunload', cancel);+ clearTimeout(delayed);+ if (loading) toast.dismiss(loading);}- } catch (error) {- const code = extractIpcError(error)?.code;- const key =- code === 'HTML_PREVIEW_TOO_LARGE'- ? 'previewTooLarge'- : code === 'HTML_PREVIEW_UNSUPPORTED'- ? 'previewUnsupported'- : code === 'NOT_FOUND'- ? 'previewNotFound'- : 'previewFailed';- toast.error(t(`chat.remoteFile.${key}`));- } finally {- clearTimeout(delayed);- if (loading) toast.dismiss(loading);}}diff --git a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.tsindex 48b77f4432..a0a197a3d6 100644--- a/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts+++ b/apps/desktop/src/renderer/features/device-link/refreshRemoteSessions.ts@@ -365,6 +365,7 @@ async function runRefreshRemoteDeviceSessions(...(opts.coalescingMode === 'weak' ? {} : { fresh: true }),},],+ { background: status === 'archived' || opts.coalescingMode === 'weak' },);// 乱序保护:本次拉取已不是最新一次 → 丢弃,别覆盖更新的结果。if (!remoteProjectsStore.isLatestSnapshotEpoch(deviceId, epoch, status))diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex e4d2229f48..c1f469c6a1 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -11272,6 +11272,9 @@"previewFailed": "Could not prepare the web preview. Check the directory and connection, then try again.","previewNotFound": "The HTML file was not found. Check that it still exists.","previewFetching": "Preparing Web Preview…",+ "previewConnectionBusy": "The connection is busy. The web preview is not ready yet. Please try again shortly.",+ "previewTimeout": "The remote web preview timed out. Please try again shortly.",+ "previewDisconnected": "The remote device is not connected. Try again when the connection returns.","previewTooLarge": "Too many previews are being prepared. Please try again shortly.","previewUnsupported": "Update Cindy on the remote device to preview this directory.","fetching": "Fetching file from remote…",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 6b8f29cebb..1a8c6576f4 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -11222,6 +11222,9 @@"previewFailed": "Web プレビューを準備できませんでした。ディレクトリと接続を確認して再試行してください。","previewNotFound": "HTML ファイルが見つかりません。ファイルが存在するか確認してください。","previewFetching": "Web プレビューを準備しています…",+ "previewConnectionBusy": "接続が混雑しているため、Web プレビューの準備が完了していません。しばらくしてから再試行してください。",+ "previewTimeout": "リモート Web プレビューがタイムアウトしました。しばらくしてから再試行してください。",+ "previewDisconnected": "リモートデバイスに接続できていません。接続が回復したら再試行してください。","previewTooLarge": "準備中のプレビューが多すぎます。しばらくしてから再試行してください。","previewUnsupported": "ディレクトリをプレビューするには、リモート端末の Cindy を更新してください。","fetching": "リモートからファイルを取得しています…",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex bfe5e6423d..cc7e12efbb 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -11222,6 +11222,9 @@"previewFailed": "웹 미리보기를 준비하지 못했습니다. 디렉터리와 연결을 확인한 후 다시 시도하세요.","previewNotFound": "HTML 파일을 찾을 수 없습니다. 파일이 존재하는지 확인하세요.","previewFetching": "웹 미리보기 준비 중…",+ "previewConnectionBusy": "연결이 혼잡하여 웹 미리보기가 아직 준비되지 않았습니다. 잠시 후 다시 시도하세요.",+ "previewTimeout": "원격 웹 미리보기 대기 시간이 초과되었습니다. 잠시 후 다시 시도하세요.",+ "previewDisconnected": "원격 기기에 연결되지 않았습니다. 연결이 복구되면 다시 시도하세요.","previewTooLarge": "준비 중인 미리보기가 너무 많습니다. 잠시 후 다시 시도하세요.","previewUnsupported": "디렉터리를 미리 보려면 원격 기기의 Cindy를 업데이트하세요.","fetching": "원격에서 파일을 가져오는 중…",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 904b91740a..c6a0373b7f 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -11222,6 +11222,9 @@"previewFailed": "无法准备网页预览,请检查目录和连接后重试","previewNotFound": "找不到 HTML 文件,请确认文件仍然存在","previewFetching": "正在准备网页预览…",+ "previewConnectionBusy": "连接拥堵,网页预览暂未完成,请稍后重试",+ "previewTimeout": "等待远程网页超时,请稍后重试",+ "previewDisconnected": "尚未连通远程设备,连接恢复后可重试","previewTooLarge": "正在准备的预览过多,请稍后重试","previewUnsupported": "远程设备暂不支持目录预览,请更新该设备上的 Cindy 后重试","fetching": "正在从远端获取文件…",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 5fc5c33f1d..962a3fbf46 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -11221,6 +11221,9 @@"previewFailed": "無法準備網頁預覽,請檢查目錄和連線後重試","previewNotFound": "找不到 HTML 檔案,請確認檔案仍然存在","previewFetching": "正在準備網頁預覽…",+ "previewConnectionBusy": "連線壅塞,網頁預覽尚未完成,請稍後重試",+ "previewTimeout": "等待遠端網頁逾時,請稍後重試",+ "previewDisconnected": "尚未連通遠端裝置,連線恢復後可重試","previewTooLarge": "正在準備的預覽過多,請稍後重試","previewUnsupported": "遠端裝置暫不支援目錄預覽,請更新該裝置上的 Cindy 後重試","fetching": "正在從遠端獲取檔案…",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 5395d82627..4776ea9259 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -2701,7 +2701,9 @@ interface ElectronAPI {| { kind: 'ssh'; remoteHostId: string };workdir: string;absPath: string;+ requestId?: string;}) => Promise<{ ok: true; url: string }>;+ cancelHtmlPreview: (requestId: string) => Promise<{ ok: true }>;chatFetch: (params: {origin: { kind: 'device'; deviceId: string } | { kind: 'ssh'; remoteHostId: string };workdir: string;@@ -4010,7 +4012,7 @@ interface ElectronAPI {openLink: (deviceId: string) => Promise<{ appVersion: string; allowlistHash: string }>;closeLink: (deviceId: string) => Promise<{ ok: true }>;/** 远程调用被控端 allowlist 内 channel;成功拿返回值,失败 reject 带 code 的 Error */- invoke: (deviceId: string, channel: string, args: unknown[]) => Promise<unknown>;+ invoke: (deviceId: string, channel: string, args: unknown[], scheduling?: { background?: boolean }) => Promise<unknown>;/** 控制端:订阅被控端某 topic 的变更推送(push 驱动侧边栏 / 会话视图) */subscribe: (deviceId: string, topics: string[]) => Promise<{ ok: true }>;/** 控制端:取消订阅某 topic */diff --git a/apps/desktop/src/shared/ipc-errors.ts b/apps/desktop/src/shared/ipc-errors.tsindex 862a339cb8..376ad119d9 100644--- a/apps/desktop/src/shared/ipc-errors.ts+++ b/apps/desktop/src/shared/ipc-errors.ts@@ -297,6 +297,7 @@ export type IpcErrorCode =| 'BROWSER_FILE_UNSUPPORTED_TYPE'| 'BROWSER_FILE_NOT_FOUND'| 'BROWSER_FILE_OPEN_FAILED'+ | 'HTML_PREVIEW_CANCELLED'// 会话分享(.cshare 导出/导入)| 'SHARE_FILE_INVALID' // 不是 .cshare / 头或 manifest 损坏 / payload 不是 zip| 'SHARE_PASSWORD_REQUIRED' // 文件已加密但未提供密码@@ -514,6 +515,7 @@ const IPC_ERROR_CODES: ReadonlySet<IpcErrorCode> = new Set<IpcErrorCode>(['BROWSER_FILE_UNSUPPORTED_TYPE','BROWSER_FILE_NOT_FOUND','BROWSER_FILE_OPEN_FAILED',+ 'HTML_PREVIEW_CANCELLED','SHARE_FILE_INVALID','SHARE_PASSWORD_REQUIRED','SHARE_PASSWORD_WRONG',diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.mdindex 36ceee229e..9662cbe8c9 100644--- a/docs/dev-rules/protocol-compatibility.md+++ b/docs/dev-rules/protocol-compatibility.md@@ -181,6 +181,8 @@ known 是消息 ID 与主机提供的 SHA-256 正文指纹对。支持的主机notModified: true } }`;否则在控制端声明可解且压缩确有收益时回 `{ result: null, transfer:{ tag, gzipBase64 } }`。共享 DeviceLinkClient 在交给调用方之前还原成普通结果,并只用发请求时固定的缓存快照还原,回包前被淘汰也不影响;标签对不上时返回错误,不返回旧数据。+缓存快照在本地准入队列出队、实际发送时读取,结果解码后才释放准入配额:+等待期间已有同键结果到达时,后续请求能携带最新标签,避免重复整包;不跳过远端 handler。解压有输出上限(4M 字符,与传输层单条逻辑消息同量级):解码器边解边计数,超过即中止并返回错误,不先整段展开;被控端对超过上限的结果不编码,仍走原有的超限处理。diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.mdindex d08d5c4dc6..6ea0ddb02e 100644--- a/docs/dev-rules/remote-and-mobile-adaptation.md+++ b/docs/dev-rules/remote-and-mobile-adaptation.md@@ -194,7 +194,10 @@ Desktop 向曾协商可靠传输、当前发送链路未就绪的设备发起新其中 PR 引用/状态、定时任务侧栏和用量同步等后台查询最多 4 个。同一真实设备的普通远控与多个共享任务共用并发和等待配额;取消仍按各自 scoped peer隔离,关闭一个任务不会取消其他任务或普通远控请求,transport 的任务范围保持不变。-任务列表同时用于首拉与恢复探测,统一走前台配额(仍受总并发 12 限制),不被后台配额阻塞。+任务列表首拉与恢复探测走前台配额(仍受总并发 12 限制);Desktop 的周期弱刷新与归档+列表通过本地 scheduling 提示走后台配额,提示不进入 wire,也不改变授权。+socket 缓冲或目标 peer 可靠队列超过 128 KiB、或该 peer 积压至少半个接收窗口时,+后台准入收敛到一路;已发送请求正常结算,压力消退后按原上限推进。前台请求优先于尚未发送的后台请求;不同设备独立推进。PR 的重复聚焦/注册沿用`PrRefsContext` 的单任务在途合并,不额外重试或保存结果。握手、订阅控制与远控心跳不占业务队列,避免业务拥堵阻断连接或 lease 维护。@@ -213,6 +216,17 @@ Desktop 向曾协商可靠传输、当前发送链路未就绪的设备发起新调用方的 `preSend` 同步检查在出队后、创建请求前再次执行;排队期间失效的写入必须拒绝发送并释放配额,本地检查失败不作为远端无响应的证据。Desktop 将 BACKPRESSURE 映射为 DEVICE_LINK_BUSY;桌面和手机标签入口显示繁忙与手动重试。+可靠大回包按体积及该 peer 首次发送后 ACK 的交付速度估算重传等待,超过 512 KiB 再按+次数退避,传输等待封顶 120 秒;小消息保持原 RTT 退避,调用方响应截止时间不延长。+速度估计不从 socket 排空推断,慢 peer 不修改其它 peer 的计时或重置共享连接。++Desktop 远程 HTML 预览仅对只读 stat 的连接类错误做最多四次尝试,间隔 1/2/4 秒,+总预算 60 秒;找不到文件、权限和旧端不支持等错误立即返回。重复点击共享同一次准备,+等待提示可取消;取消按发起窗口和 requestId 隔离,在出队前再次阻止失效 stat,+已发出的 stat 迟到后不得打开页面。窗口关闭、主框架导航或账号代次变化也不得发布旧结果。+下载继续复用已有缓存与取消通路,不整次重跑下载或重试写操作;错误区分拥堵、超时与断线。+故障半径:证据限于目标 peer 的排队/交付及本次预览读取;恢复只调整本机准入和该 peer+重传、重试该预览 stat;第二个健康 peer 不被重置,旧端 wire 格式与权限边界保持不变。被控端拒收时 Debug 日志记录在途数、待回包数、配额范围和前八个通道计数,不记录参数/标签/消息内容。原被控端准入上限及 wire 格式不变,可独立升级控制端。diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.tsindex 2cf3c1b30e..3fa00011db 100644--- a/packages/device-link/src/__tests__/client.test.ts+++ b/packages/device-link/src/__tests__/client.test.ts@@ -160,6 +160,37 @@ describe('outbound invoke admission', () => {} finally { h.client.stop(); }});+ it('uses actual socket pressure to serialize background reads without blocking foreground work', async () => {+ vi.useFakeTimers();+ const h = makeHarness({ timing: { pingIntervalMs: 60_000, requestTimeoutMs: 30_000 } });+ const calls: Promise<unknown>[] = [];+ try {+ h.client.start();+ await vi.advanceTimersByTimeAsync(0);+ const ws = h.current();+ ws.ack();+ ws.bufferedAmount = 200 * 1024;+ for (let i = 0; i < 4; i++) calls.push(h.client.invoke('host', {+ channel: 'local-db:sessions:list', args: [i],+ }, 30_000, { background: true }).catch(e => e));+ expect(ws.sent.filter(e => e.kind === 'invoke')).toHaveLength(1);+ const foreground = h.client.invoke('host', { channel: 'file-browser:remote-op', args: [{ op: 'stat' }] });+ calls.push(foreground.catch(e => e));+ const current = ws.sent.filter(e => e.kind === 'invoke');+ expect(current).toHaveLength(2);+ ws.push({ v: PROTOCOL_VERSION, kind: 'invoke-result', src: 'host', id: current[1].id, payload: { ok: true, result: 'file' } });+ await expect(foreground).resolves.toEqual({ ok: true, result: 'file' });+ ws.bufferedAmount = 0;+ ws.push({ v: PROTOCOL_VERSION, kind: 'invoke-result', src: 'host', id: current[0].id, payload: { ok: true, result: [] } });+ await vi.advanceTimersByTimeAsync(0);+ expect(ws.sent.filter(e => e.kind === 'invoke')).toHaveLength(5);+ } finally {+ h.client.stop();+ await Promise.all(calls);+ vi.useRealTimers();+ }+ });+it('waits for a 20-second mobile history recovery without widening other requests or replaying it', async () => {vi.useFakeTimers();const h = makeHarness({ timing: { pingIntervalMs: 60_000, requestTimeoutMs: 15_000 } });@@ -7932,6 +7963,15 @@ describe('定时重发的单趟预算(TRANSPORT_RETRY_PASS_BUDGET)', () => {await expect(call()).resolves.toEqual({ ok: true, result: rows });expect(handled).toHaveLength(3);+ // Cold-cache burst: the thirteenth call waits for admission. A completed+ // earlier result must supply its validator before that queued call is sent.+ const burst = Array.from({ length: 13 }, () => controller.invoke('desktop', {+ channel: 'local-db:sessions:list', args: [{ filter: 'archived' }],+ }, 1_000));+ await relay.settle();+ expect(await Promise.all(burst)).toEqual(Array.from({ length: 13 }, () => ({ ok: true, result: rows })));+ expect((handled.at(-1)!.payload as InvokePayload).transfer?.ifNoneMatch).toEqual(expect.any(String));+offHost();host.stop();controller.stop();@@ -8833,6 +8873,46 @@ describe('定时重发的单趟预算(TRANSPORT_RETRY_PASS_BUDGET)', () => {}, { pingIntervalMs: 600_000, transportRetryIntervalMs: 2_000 });});+ // Unit tier, production client and a fake clock: reproduce the observed+ // 1.85MB/128Kbit slow delivery, then verify learned pacing on a smaller result.+ it('waits for a two-minute large delivery, learns its rate, and keeps another peer responsive', async () => {+ await withFakeTimers(async (h, advance) => {+ const linked = establishInboundReliableLink(h, 'healthy-stream', 1, 'healthy');+ await advance(1);+ await linked;+ const ws = h.current();+ const resets = vi.fn();+ h.client.onPeerTransportReset(resets);+ h.client.sendInvokeResult('dev-b', 'large-page', { ok: true, result: 'x'.repeat(1_852_521) });+ const first = ws.sent.find(e => e.kind === 'invoke-result')!;+ const meta = parseTransportPayload(first.payload)!.meta;+ const request = h.client.invoke('healthy', { channel: 'file-browser:remote-op', args: [{ op: 'stat' }] });+ const sent = ws.sent.find(e => e.kind === 'invoke' && e.dst === 'healthy')!;+ const healthyMeta = parseTransportPayload(sent.payload)!.meta;+ ws.push({ v: PROTOCOL_VERSION, kind: 'push', src: 'healthy', payload: {+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL, payload: { streamId: healthyMeta.streamId, ackSeq: healthyMeta.seq },+ } });+ ws.push({ v: PROTOCOL_VERSION, kind: 'invoke-result', src: 'healthy', id: sent.id, payload: { ok: true, result: 'ok' } });+ await expect(request).resolves.toEqual({ ok: true, result: 'ok' });+ await advance(116_000);+ expect(sendsBySeq(ws).get(meta.seq)).toBe(1);+ expect(resets).not.toHaveBeenCalled();+ ws.push({ v: PROTOCOL_VERSION, kind: 'push', src: 'dev-b', payload: {+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL, payload: { streamId: meta.streamId, ackSeq: meta.seq },+ } });+ expect(h.client.getReliableSendQueueDepth('dev-b')).toBe(0);+ h.client.sendInvokeResult('dev-b', 'next-page', { ok: true, result: 'y'.repeat(200 * 1024) });+ const next = parseTransportPayload(ws.sent.find(e => e.id === 'next-page')!.payload)!.meta;+ // Size-only pacing would resend at 26s; measured delivery allows ~19s,+ // so the original 26s floor still applies for this faster observation.+ await advance(24_000);+ expect(sendsBySeq(ws).get(next.seq)).toBe(1);+ await advance(2_000);+ expect(sendsBySeq(ws).get(next.seq)).toBe(2);+ expect(ws.closed).toBeNull();+ }, { pingIntervalMs: 600_000, transportRetryIntervalMs: 2_000 });+ });+it('a large response delivered after 18s is not duplicated while waiting for its first ACK', async () => {await withFakeTimers(async (h, advance) => {h.client.sendInvokeResult('dev-b', 'slow-page', { ok: true, result: 'x'.repeat(200 * 1024) });@@ -8853,6 +8933,14 @@ describe('定时重发的单趟预算(TRANSPORT_RETRY_PASS_BUDGET)', () => {await advance(40_000);expect([...sendsBySeq(ws).values()]).toEqual([1]);expect(h.client.getReliableSendQueueDepth('dev-b')).toBe(0);+ h.client.sendInvokeResult('dev-b', 'paced-next', { ok: true, result: 'x'.repeat(200 * 1024) });+ const next = parseTransportPayload(ws.sent.find(e => e.id === 'paced-next')!.payload)!.meta;+ // The previous 18s ACK gives a 27s delivery allowance. Without learning+ // from actual ACKs, size-only pacing would duplicate this at 26s.+ await advance(26_000);+ expect(sendsBySeq(ws).get(next.seq)).toBe(1);+ await advance(2_000);+ expect(sendsBySeq(ws).get(next.seq)).toBe(2);expect(ws.closed).toBeNull();}, { pingIntervalMs: 600_000, transportRetryIntervalMs: 2_000 });});@@ -9066,8 +9154,8 @@ describe('定时重发的单趟预算(TRANSPORT_RETRY_PASS_BUDGET)', () => {// 预算 4 帧、每条 3 片:队头那条发完(3 帧)后,第二条会超预算 → 发送前就被拦下,// 留到下一趟。所以本趟只重发队头 1 条、只写出 3 帧。const framesBefore = framesSent(ws);- // Large messages first receive a bounded transmission budget (15 ticks).- await advance(3_000);+ // ~263KiB needs 17 size intervals before this first retry.+ await advance(3_400);const retried = retriedSeqs(sendsBySeq(ws));expect(retried).toEqual([seqs[0]]);// 本趟真实写出的帧数不超过 max(预算, 队头分片数) —— 这才是「上限」的准确表述@@ -9092,7 +9180,7 @@ describe('定时重发的单趟预算(TRANSPORT_RETRY_PASS_BUDGET)', () => {}const ws = h.current();const seqs = [...sendsBySeq(ws).keys()].sort((a, b) => a - b);- await advance(3_000);+ await advance(5_000);// 队头仍受分片预算约束;小消息不会因队头冷却而饥饿。expect(retriedSeqs(sendsBySeq(ws))).toEqual(seqs);}, {diff --git a/packages/device-link/src/__tests__/invokeScheduler.test.ts b/packages/device-link/src/__tests__/invokeScheduler.test.tsindex 7dcc143536..1069ec4bea 100644--- a/packages/device-link/src/__tests__/invokeScheduler.test.ts+++ b/packages/device-link/src/__tests__/invokeScheduler.test.ts@@ -17,6 +17,31 @@ const flush = async () => {afterEach(() => vi.useRealTimers());describe("invoke admission", () => {+ // A pressured peer previously refilled all four background slots. Exercise+ // production admission with deferred reads: foreground/other peers still run.+ it("reduces pressured background concurrency and recovers after delivery", async () => {+ let pressured = true;+ const scheduler = new InvokeScheduler(peer => peer === "slow" && pressured);+ const jobs = Array.from({ length: 6 }, deferred);+ const started: number[] = [];+ const results = jobs.map((job, i) => scheduler.run("slow", true, 30_000, () => {+ started.push(i);+ return job.promise;+ }));+ expect(started).toEqual([0]);+ await expect(scheduler.run("slow", false, 30_000, async () => "preview")).resolves.toBe("preview");+ await expect(scheduler.run("healthy", true, 30_000, async () => "ok")).resolves.toBe("ok");+ jobs[0].resolve();+ await flush();+ expect(started).toEqual([0, 1]);+ pressured = false;+ jobs[1].resolve();+ await flush();+ expect(started).toEqual([0, 1, 2, 3, 4, 5]);+ jobs.forEach(job => job.resolve());+ await Promise.all(results);+ });+const sameHost = ["host", sharedTaskHostPeer("task-a", "host"), sharedTaskGuestPeer("task-b", "member", "host")];it.each([false, true])("shares physical-host active and waiting limits across scoped peers (background=%s)", async (background) => {diff --git a/packages/device-link/src/__tests__/transport.test.ts b/packages/device-link/src/__tests__/transport.test.tsindex 94dca97a79..a77267df4c 100644--- a/packages/device-link/src/__tests__/transport.test.ts+++ b/packages/device-link/src/__tests__/transport.test.ts@@ -13,6 +13,7 @@ import {retransmitBaseMs,TRANSPORT_ADAPTIVE_RETRY_MAX_MS,updateRetransmitEstimate,+ updateDeliveryEstimate,type RetransmitEstimate,} from '../transport.js';@@ -136,6 +137,22 @@ describe('adaptive retransmit interval', () => {expect(reliableRetryDelayMs(unknown, 2_000, 13, 1)).toBe(26_000);});+ it('paces large retries by confirmed goodput without stretching small requests', () => {+ const slow: RetransmitEstimate = { srttMs: null, rttVarMs: 0 };+ updateDeliveryEstimate(slow, 128 * 1024, 60_000);+ expect(reliableRetryDelayMs(slow, 2_000, 8, 1, 128 * 1024)).toBe(90_000);+ expect(reliableRetryDelayMs(slow, 2_000, 60, 4, 1_852_521)).toBe(120_000);+ expect(reliableRetryDelayMs(slow, 2_000, 1, 1, 100)).toBe(2_000);+ const prior = slow.deliveryBytesPerMs;+ updateDeliveryEstimate(slow, 100, 1);+ updateDeliveryEstimate(slow, 128 * 1024, 0);+ expect(slow.deliveryBytesPerMs).toBe(prior);+ updateDeliveryEstimate(slow, 128 * 1024, 1_000);+ expect(reliableRetryDelayMs(slow, 2_000, 8, 1, 128 * 1024)).toBeLessThan(90_000);+ const healthy: RetransmitEstimate = { srttMs: null, rttVarMs: 0 };+ expect(reliableRetryDelayMs(healthy, 2_000, 8, 1, 128 * 1024)).toBe(16_000);+ });+it('does not multiply byte pacing by the slow round trip', () => {const slow: RetransmitEstimate = { srttMs: 4_000, rttVarMs: 1_000 };expect(reliableRetryDelayMs(slow, 2_000, 1, 1)).toBe(8_000);diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.tsindex d9e3be0580..c50216297a 100644--- a/packages/device-link/src/client.ts+++ b/packages/device-link/src/client.ts@@ -63,6 +63,7 @@ import {reliableRetryDelayMs,retransmitBaseMs,updateRetransmitEstimate,+ updateDeliveryEstimate,byteLength,type RetransmitEstimate,} from './transport.js';@@ -152,10 +153,10 @@ const RELIABLE_ACK_BATCH_MESSAGES = 2;const RELIABLE_ACK_BATCH_BYTES = 256 * 1024;const RECOVERY_TRACE_WINDOW_MS = 30_000;// Allow slow relay -> controller delivery before duplicating an entire message.-// With the default 2s tick this allows 8KiB/s, capped at 30s per attempt. Small+// With the default 2s tick this allows 8KiB/s, capped at 120s per attempt. Small// messages retain their existing retry cadence; dead peers still exhaust retries.const RELIABLE_RETRY_BYTES_PER_INTERVAL = 16 * 1024;-const RELIABLE_RETRY_MAX_SIZE_INTERVALS = 15;+const RELIABLE_RETRY_MAX_SIZE_INTERVALS = 60;/** 连续三次握手成功后仍没撑过稳定期,才把普通抖动升级为可见问题。 */const SHORT_LIVED_STREAK_LIMIT = 3;const MAX_LEGACY_INBOUND_FRAMES = 128;@@ -711,7 +712,12 @@ interface ReceiveStreamState {// ─── 客户端实现 ───────────────────────────────────────────────────────────────export class DeviceLinkClient {- private readonly invokeScheduler = new InvokeScheduler();+ private readonly invokeScheduler = new InvokeScheduler((id) => {+ const peer = this.peerTransport.get(id);+ return (this.ws?.bufferedAmount ?? 0) > SOCKET_DATA_LOW_WATER_BYTES+ || (peer?.pendingBytes ?? 0) > SOCKET_DATA_LOW_WATER_BYTES+ || (peer?.pending.size ?? 0) >= MAX_TRANSPORT_REASSEMBLIES / 2;+ });private readonly opts: DeviceLinkClientOptions;private readonly timing: DeviceLinkTiming;private readonly log: DeviceLinkLogger;@@ -1433,35 +1439,37 @@ export class DeviceLinkClient {dst: string,payload: InvokePayload,timeoutMs?: number,- options?: { preSend?: () => void },+ options?: { preSend?: () => void; background?: boolean },): Promise<InvokeResultPayload> {if (this.status !== 'online') throw new DeviceLinkError('NOT_CONNECTED', 'not connected to relay');- const reuse = this.messageReuse.prepare(dst, payload);- const tagged = requestSessionTagCatalog(reuse.payload);- // Scoped cross-account peers keep the plain wire format.- const transfer = isScopedPeer(dst) ? null : this.invokeResultCache.prepare(dst, tagged);- const send = () => {+ const send = async () => {// Admission may wait: validate caller ownership/cancellation after dequeue,// synchronously before creating the request or retaining a transport frame.options?.preSend?.();- return this.request(+ // Prepare at dispatch, not when joining the admission queue. Earlier+ // reads may have filled the existing cache while this one was waiting.+ const reuse = this.messageReuse.prepare(dst, payload);+ const tagged = requestSessionTagCatalog(reuse.payload);+ const transfer = isScopedPeer(dst) ? null : this.invokeResultCache.prepare(dst, tagged);+ const env = await this.request({ v: PROTOCOL_VERSION, kind: 'invoke', dst, payload: transfer?.payload ?? tagged },'invoke-result',timeoutMs,);+ const result = transfer+ ? transfer.decode(env.payload as InvokeResultPayload)+ : env.payload as InvokeResultPayload;+ return result.ok+ ? {+ ...result,+ result: reuse.decode(decodeSessionTagCatalog(payload.channel, result.result)),+ }+ : result;};- const env = await (bypassInvokeScheduling(payload) ? send() : this.invokeScheduler.run(- dst, isBackgroundInvoke(payload.channel), Math.min(timeoutMs ?? this.timing.requestTimeoutMs, 30_000), send,- ));- const result = transfer- ? transfer.decode(env.payload as InvokeResultPayload)- : env.payload as InvokeResultPayload;- return result.ok- ? {- ...result,- result: reuse.decode(decodeSessionTagCatalog(payload.channel, result.result)),- }- : result;+ return bypassInvokeScheduling(payload) ? send() : this.invokeScheduler.run(+ dst, options?.background ?? isBackgroundInvoke(payload.channel),+ Math.min(timeoutMs ?? this.timing.requestTimeoutMs, 30_000), send,+ );}/** 被控端:回 invoke-result(对应入站 invoke 的 id) */@@ -3970,6 +3978,9 @@ export class DeviceLinkClient {if (pending.firstSentAt !== undefined && pending.bytes <= RELIABLE_RETRY_BYTES_PER_INTERVAL) {rttSample = this.monotonicNow() - pending.firstSentAt;}+ if (pending.firstSentAt !== undefined && pending.attempts === 1) {+ updateDeliveryEstimate(peer.rtt, pending.bytes, this.monotonicNow() - pending.firstSentAt);+ }peer.pending.delete(seq);peer.pendingBytes -= pending.bytes;}@@ -4333,6 +4344,7 @@ export class DeviceLinkClient {this.timing.transportRetryIntervalMs,sizeIntervals,pending.attempts,+ pending.bytes,);if (pending.sent && !opts.ignoreInterval && now - pending.lastSentAt < retryDelayMs) {// A large head frame may still be inside its byte-based cooldown whilediff --git a/packages/device-link/src/invokeScheduler.ts b/packages/device-link/src/invokeScheduler.tsindex 994f6e5e91..9088dadd37 100644--- a/packages/device-link/src/invokeScheduler.ts+++ b/packages/device-link/src/invokeScheduler.ts@@ -23,6 +23,8 @@ interface PeerQueue {export class InvokeScheduler {private readonly peers = new Map<string, PeerQueue>();+ constructor(private readonly isPressured: (peerId: string) => boolean = () => false) {}+run<T>(peerId: string,background: boolean,@@ -124,7 +126,10 @@ export class InvokeScheduler {while (state.active < MAX_ACTIVE && state.jobs.length) {let index = state.jobs.findIndex((job) => !job.background);if (index < 0) {- if (state.background >= MAX_BACKGROUND_ACTIVE) break;+ // Keep one background read progressing, but do not refill a slow+ // transport with four new reads every time old requests time out.+ const limit = this.isPressured(state.jobs[0].peerId) ? 1 : MAX_BACKGROUND_ACTIVE;+ if (state.background >= limit) break;index = 0;}state.jobs.splice(index, 1)[0].start();diff --git a/packages/device-link/src/transport.ts b/packages/device-link/src/transport.tsindex b93fe75c4a..f38a3e8d6f 100644--- a/packages/device-link/src/transport.ts+++ b/packages/device-link/src/transport.ts@@ -114,6 +114,17 @@ export const TRANSPORT_ADAPTIVE_RETRY_MAX_MS = 10_000;export interface RetransmitEstimate {srttMs: number | null;rttVarMs: number;+ /** End-to-end delivery, including relay queues; never inferred from socket drain. */+ deliveryBytesPerMs?: number;+}++/** Only first-attempt ACKs give an unambiguous large-message delivery sample. */+export function updateDeliveryEstimate(estimate: RetransmitEstimate, bytes: number, elapsedMs: number): void {+ if (bytes < 64 * 1024 || !Number.isFinite(elapsedMs) || elapsedMs <= 0) return;+ const sample = bytes / elapsedMs;+ const previous = estimate.deliveryBytesPerMs;+ // Slow down immediately, recover gradually; bursts must not erase a slow-path observation.+ estimate.deliveryBytesPerMs = previous === undefined ? sample : Math.min(sample, previous * 0.75 + sample * 0.25);}export function updateRetransmitEstimate(estimate: RetransmitEstimate, sampleMs: number): void {@@ -138,18 +149,26 @@ export function retransmitBaseMs(estimate: RetransmitEstimate, configuredMs: num}/**- * 单条可靠消息距上次写出后多久可以重发。字节节奏(sizeIntervals)估的是传输耗时,- * 按配置间隔计;实测往返只放宽按次数的退避。两者取大而不相乘,否则慢链路上的- * 大回包要等上百秒才重发。往返未知时与原先 configured × max(size, backoff) 相同。+ * 单条可靠消息距上次写出后多久可以重发。字节节奏和已确认的交付速度估算传输耗时;+ * 超过 512KiB 的回包再按次数退避,传输等待封顶 120s。小消息保留 RTT 退避,+ * 请求自身的响应截止时间不因重传延长。*/export function reliableRetryDelayMs(estimate: RetransmitEstimate,configuredMs: number,sizeIntervals: number,attempts: number,+ bytes = 0,): number {const backoff = Math.min(4, 2 ** Math.max(0, attempts - 1));- return Math.max(configuredMs * sizeIntervals, retransmitBaseMs(estimate, configuredMs) * backoff);+ const measuredDelivery = bytes >= 64 * 1024 && estimate.deliveryBytesPerMs+ ? bytes / estimate.deliveryBytesPerMs * 1.5 : 0;+ // A 1.85 MB result needs roughly two minutes at 128 Kbit/s. The old 30s+ // size ceiling repeatedly copied it before its first ACK. Keep a finite+ // ceiling and retry exhaustion, while leaving small-message timing intact.+ const delivery = Math.min(120_000,+ Math.max(configuredMs * sizeIntervals, measuredDelivery) * (bytes > 512 * 1024 ? backoff : 1));+ return Math.max(delivery, retransmitBaseMs(estimate, configuredMs) * backoff);}const TRANSPORT_MARKER = '__cindyDeviceLinkTransport';