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(device-link): correct burst sampling and SSH preview cancellation

Dashda57287efc29
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.ts
index b3a8a63c13..569dde5e82 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
@@ -3,6 +3,7 @@ import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { EventEmitter } from 'node:events';
+import { FileServiceRpcError } from '@cindy/remote-file-service/client';
const mocks = vi.hoisted(() => ({
handle: vi.fn(),
trusted: vi.fn(),
@@ -22,7 +23,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';
+import { readPreviewMetadata, statSshPreviewMetadata } from '../html-preview-read';
const args = {
origin: { kind: 'device', deviceId: 'remote' },
workdir: '/remote',
@@ -89,25 +90,57 @@ it('backs off read-only metadata across congestion and a short disconnect', asyn
} finally { vi.useRealTimers(); }
});
-it.each(['BACKPRESSURE', 'INVOKE_TIMEOUT', 'NOT_CONNECTED'])('bounds repeated %s failures and preserves the connection error', async (code) => {
+it.each([
+ ['BACKPRESSURE', 'DEVICE_LINK_BUSY'],
+ ['INVOKE_TIMEOUT', 'DEVICE_LINK_TIMEOUT'],
+ ['NOT_CONNECTED', 'DEVICE_LINK_NOT_CONNECTED'],
+ ['TIMEOUT', 'DEVICE_LINK_TIMEOUT'],
+ ['CHANNEL_CLOSED', 'DEVICE_LINK_NOT_CONNECTED'],
+ ['CHANNEL_ERROR', 'DEVICE_LINK_NOT_CONNECTED'],
+])('bounds repeated %s failures and preserves the connection error', async (code, expected) => {
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 });
+ throw new FileServiceRpcError(code, 'transient');
});
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(); }
});
+// PR #6288: cancellation must reach both SSH stat sends, including the manager's
+// internal rebuild. Existing IPC tests inject stat and cannot observe this adapter.
+// Unit tier: a paused request gate models connection setup, with no real network.
+it.each([[1, false], [2, false], [2, true]] as const)('blocks SSH preview send %s after cancellation (rebuild=%s)', async (cancelAt, rebuild) => {
+ const controller = new AbortController();
+ const sent: string[] = [];
+ let gates = 0;
+ const request = vi.fn().mockImplementation(async (_host, _method, params, options) => {
+ const send = async () => {
+ await Promise.resolve();
+ if (++gates === cancelAt) controller.abort();
+ await options?.beforeSend?.();
+ sent.push(params.relPath);
+ };
+ await send();
+ // The manager repeats its gate after a channel loss and rebuild.
+ if (rebuild && params.relPath === 'preview/index.html') await send();
+ return { type: 'file' };
+ });
+ const result = statSshPreviewMetadata({ request }, {
+ ...args, origin: { kind: 'ssh', remoteHostId: 'ssh-1' },
+ }, '/remote/preview', 'style.css', controller.signal);
+ await expect(result).rejects.toMatchObject({ name: 'AbortError' });
+ expect(sent).toHaveLength(cancelAt - 1);
+});
+
it('ends a stalled stat at the total deadline and aborts its downstream signal', async () => {
vi.useFakeTimers();
try {
diff --git a/apps/desktop/src/main/file-browser/html-preview-read.ts b/apps/desktop/src/main/file-browser/html-preview-read.ts
index 2acf5d9847..b724dde214 100644
--- a/apps/desktop/src/main/file-browser/html-preview-read.ts
+++ b/apps/desktop/src/main/file-browser/html-preview-read.ts
@@ -1,4 +1,7 @@
import { createIpcError, type IpcErrorCode } from '../../shared/ipc-errors.js';
+import { toWorkdirRel } from '../../shared/workdirPath.js';
+import type { HtmlPreviewArgs } from './html-preview.js';
+import type { RemoteFileBrowserManager } from './remote.js';
const TRANSPORT_ERRORS = {
BACKPRESSURE: 'DEVICE_LINK_BUSY',
@@ -13,8 +16,30 @@ const TRANSPORT_ERRORS = {
DEVICE_UNRESPONSIVE: 'DEVICE_LINK_DEVICE_UNRESPONSIVE',
DEVICE_LINK_DEVICE_UNRESPONSIVE: 'DEVICE_LINK_DEVICE_UNRESPONSIVE',
PEER_RESET: 'DEVICE_LINK_NOT_CONNECTED',
+ TIMEOUT: 'DEVICE_LINK_TIMEOUT',
+ CHANNEL_CLOSED: 'DEVICE_LINK_NOT_CONNECTED',
+ CHANNEL_ERROR: 'DEVICE_LINK_NOT_CONNECTED',
} satisfies Record<string, IpcErrorCode>;
+/** Keep both SSH reads together so cancellation also covers connection rebuilds. */
+export async function statSshPreviewMetadata(
+ browser: Pick<RemoteFileBrowserManager, 'request'>,
+ args: HtmlPreviewArgs,
+ root: string,
+ relPath: string,
+ signal?: AbortSignal,
+) {
+ signal?.throwIfAborted();
+ if (args.origin.kind !== 'ssh') throw new Error('BAD_ARGS');
+ const options = { beforeSend: () => signal?.throwIfAborted() };
+ await browser.request(args.origin.remoteHostId, 'stat', {
+ workdir: args.workdir,
+ relPath: toWorkdirRel(args.workdir, args.absPath)!,
+ }, options);
+ signal?.throwIfAborted();
+ return browser.request(args.origin.remoteHostId, 'stat', { workdir: root, relPath }, options);
+}
+
/** 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;
diff --git a/apps/desktop/src/main/file-browser/index.ts b/apps/desktop/src/main/file-browser/index.ts
index 22b9db4f0a..154d2ffb90 100644
--- a/apps/desktop/src/main/file-browser/index.ts
+++ b/apps/desktop/src/main/file-browser/index.ts
@@ -71,6 +71,7 @@ import { getRemoteWatchRegistry } from './remote-watch.js';
import { throwRemoteFsIpcError } from './remote.js';
import { watcherManager, type FileTreeEvent } from './watcher.js';
import { registerHtmlPreviewIpc } from './html-preview-ipc.js';
+import { statSshPreviewMetadata } from './html-preview-read.js';
import { toWorkdirRel } from '../../shared/workdirPath.js';
const log = createLogger('file-browser/ipc');
@@ -407,13 +408,7 @@ export function registerFileBrowserIpc(): void {
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 });
+ return statSshPreviewMetadata(getRemoteFileBrowser(), args, root, relPath, signal);
},
read: async (args, root, entry, signal) => {
if (signal?.aborted) throw new Error('PREVIEW_CANCELLED');
diff --git a/apps/desktop/src/renderer/__tests__/htmlPreviewOpening.test.ts b/apps/desktop/src/renderer/__tests__/htmlPreviewOpening.test.ts
index 18653becde..ed5b589eb8 100644
--- a/apps/desktop/src/renderer/__tests__/htmlPreviewOpening.test.ts
+++ b/apps/desktop/src/renderer/__tests__/htmlPreviewOpening.test.ts
@@ -52,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.objectContaining({ action: { label: 'common.cancel', onClick: expect.any(Function) } }));
+ expect(mocks.loading).toHaveBeenCalledWith('chat.remoteFile.previewFetching', expect.objectContaining({ action: { label: 'commonUi.confirmDialog.cancel', onClick: expect.any(Function) } }));
expect(mocks.error).not.toHaveBeenCalled();
settle();
await opening;
diff --git a/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx b/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx
index e1656f2f2f..e343c600f0 100644
--- a/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx
+++ b/apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx
@@ -151,7 +151,7 @@ export async function openHtmlFileByPreference(
const delayed = setTimeout(() => {
if (cancelled) return;
loading = toast.loading(t('chat.remoteFile.previewFetching'), {
- action: { label: t('common.cancel'), onClick: cancel },
+ action: { label: t('commonUi.confirmDialog.cancel'), onClick: cancel },
onClose: cancel,
});
}, 600);
diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.ts
index 3fa00011db..376758e21b 100644
--- a/packages/device-link/src/__tests__/client.test.ts
+++ b/packages/device-link/src/__tests__/client.test.ts
@@ -8913,6 +8913,27 @@ describe('定时重发的单趟预算(TRANSPORT_RETRY_PASS_BUDGET)', () => {
}, { pingIntervalMs: 600_000, transportRetryIntervalMs: 2_000 });
});
+ // PR #6288: one cumulative ACK must measure the whole burst, not interpret
+ // its small tail as a slow link. Unit/fake clock; existing cases ACK one message.
+ it('samples cumulative delivery bytes together so a small tail does not delay a later lost frame', async () => {
+ await withFakeTimers(async (h, advance) => {
+ const ws = h.current();
+ h.client.sendInvokeResult('dev-b', 'burst-head', { ok: true, result: 'x'.repeat(200 * 1024) });
+ h.client.sendInvokeResult('dev-b', 'burst-tail', { ok: true, result: 'x'.repeat(64 * 1024) });
+ const tail = parseTransportPayload(ws.sent.find(e => e.id === 'burst-tail')!.payload)!.meta;
+ await advance(9_000);
+ ws.push({ v: PROTOCOL_VERSION, kind: 'push', src: 'dev-b', payload: {
+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,
+ payload: { streamId: tail.streamId, ackSeq: tail.seq },
+ } });
+ expect(h.client.getReliableSendQueueDepth('dev-b')).toBe(0);
+ h.client.sendInvokeResult('dev-b', 'lost-next', { ok: true, result: 'x'.repeat(200 * 1024) });
+ const next = parseTransportPayload(ws.sent.find(e => e.id === 'lost-next')!.payload)!.meta;
+ await advance(26_000);
+ expect(sendsBySeq(ws).get(next.seq)).toBe(2);
+ }, { 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) });
diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.ts
index c50216297a..9357ef092f 100644
--- a/packages/device-link/src/client.ts
+++ b/packages/device-link/src/client.ts
@@ -3966,6 +3966,10 @@ export class DeviceLinkClient {
peer.highestAckSeq = ackSeq;
this.logRecoveryStage(src, 'ack-received', ` ack=${ackSeq}`, false);
let rttSample: number | null = null;
+ const acknowledgedAt = this.monotonicNow();
+ let deliveryStartedAt = acknowledgedAt;
+ let deliveryBytes = 0;
+ let deliverySampleValid = true;
for (const [seq, pending] of peer.pending) {
if (seq > ackSeq) break;
if (pending.envelope.id) {
@@ -3979,11 +3983,20 @@ export class DeviceLinkClient {
rttSample = this.monotonicNow() - pending.firstSentAt;
}
if (pending.firstSentAt !== undefined && pending.attempts === 1) {
- updateDeliveryEstimate(peer.rtt, pending.bytes, this.monotonicNow() - pending.firstSentAt);
+ deliveryStartedAt = Math.min(deliveryStartedAt, pending.firstSentAt);
+ deliveryBytes += pending.bytes;
+ } else {
+ deliverySampleValid = false;
}
peer.pending.delete(seq);
peer.pendingBytes -= pending.bytes;
}
+ // A cumulative ACK measures the whole acknowledged burst. Sampling its
+ // tail separately counts time spent delivering preceding messages as slowness.
+ // Retransmitted batches have ambiguous timing and cannot teach delivery pace.
+ if (deliverySampleValid) {
+ updateDeliveryEstimate(peer.rtt, deliveryBytes, acknowledgedAt - deliveryStartedAt);
+ }
if (rttSample !== null) updateRetransmitEstimate(peer.rtt, rttSample);
if (peer.recoveryNeedsAck) {
peer.confirmedGapRepair = null;