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(remote-desktop): 关闭通知异常不再中断直连清理,暂停剪贴板不再误报失败

Dashcdb43e780cec
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 c7acda53df..2e103691cb 100644
--- a/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts
@@ -78,6 +78,7 @@ import {
tryPeerFile,
tryUploadPeerAttachment,
} from '../filePeer';
+import { DesktopCaptureWindow } from '../../remote-desktop/captureWindow';
import { createHash } from 'node:crypto';
describe('peer attachment upload preflight', () => {
@@ -756,6 +757,68 @@ describe('authorized file peer source', () => {
mock.current = false;
await expect(read(b.connection, fb.ticket, 5)).rejects.toThrow('CLOSED');
});
+ it('finishes every local cleanup when the stored invoke throws on the close notice', async () => {
+ const opened = vi.spyOn(fsPromises, 'open');
+ const dispose = vi.spyOn(DesktopCaptureWindow.prototype, 'dispose');
+ try {
+ const peer = 'stopped-desktop-peer';
+ const remote = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
+ // A stored remote-desktop invoke re-checks its caller first and, once the desktop has
+ // stopped, used to throw synchronously out of stopConnection.
+ const invoke = vi.fn((_peer: string, _channel: string, args: unknown[]) => {
+ const action = (args[0] as { action: string }).action;
+ if (action === 'close') throw new Error('DESKTOP_STOPPED');
+ return Promise.resolve({
+ ok: true,
+ result:
+ action === 'caps'
+ ? { version: 1, streaming: true }
+ : action === 'open'
+ ? { ticket: 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', size: 5, mimeType: 'text/plain' }
+ : { connection: remote, sdp: 'v=0' },
+ });
+ });
+ const tracked = async (index: number) => {
+ const handle = await (opened.mock.results[index].value as ReturnType<
+ typeof fsPromises.open
+ >);
+ const close = handle.close.bind(handle);
+ const state = { closed: false };
+ handle.close = async () => {
+ await close();
+ state.closed = true;
+ };
+ return state;
+ };
+ // Controller side: a receive in flight (open sink file + pending host reply).
+ const transfer = tryPeerFile(peer, 'xdt-file://test', invoke);
+ await vi.waitFor(() => expect(mock.receiving).toBeDefined());
+ const receive = mock.receiving!;
+ await mock.handlers.get('file-peer:host:write')!({}, receive.sink, 0, 'aGU=');
+ const sink = await tracked(opened.mock.calls.findIndex((call) => call[1] === 'wx'));
+ // Host side: another controller's connection with an open source file.
+ const other = await connect('device-b');
+ const before = opened.mock.calls.length;
+ const { ticket } = await open(other.connection, 'device-b');
+ const source = await tracked(before);
+
+ expect(() => stopFilePeers()).not.toThrow();
+
+ expect(invoke).toHaveBeenCalledWith(peer, expect.any(String), [
+ { action: 'close', connection: remote },
+ ]);
+ expect(await transfer).toBeNull();
+ await vi.waitFor(() => expect(sink.closed && source.closed).toBe(true));
+ await expect(read(other.connection, ticket, 0)).rejects.toThrow();
+ await expect(
+ mock.handlers.get('file-peer:host:write')!({}, receive.sink, 2, 'bGxv'),
+ ).rejects.toThrow('FILE_PEER_BLOCK');
+ expect(dispose).toHaveBeenCalled();
+ } finally {
+ opened.mockRestore();
+ dispose.mockRestore();
+ }
+ });
it('keeps a connection alive while a long attachment request is handled, then idles out', async () => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval'] });
try {
diff --git a/apps/desktop/src/main/device-link/filePeer.ts b/apps/desktop/src/main/device-link/filePeer.ts
index 4929fa73a3..4a05096716 100644
--- a/apps/desktop/src/main/device-link/filePeer.ts
+++ b/apps/desktop/src/main/device-link/filePeer.ts
@@ -257,6 +257,20 @@ function track(id: string, peer: string, incoming: boolean) {
timer.unref();
connections.set(id, { peer, incoming, owner: captureDataOwnerBroadcastScope(), timer });
}
+/**
+ * Best-effort close notice. The stored invoke may belong to a caller that has since gone
+ * away (e.g. a stopped remote desktop) and throw synchronously; that must neither skip the
+ * local cleanup nor escape from a timer as an uncaughtException.
+ */
+function notifyPeerClose(invoke: Invoke, peer: string, remote: string): void {
+ try {
+ void invoke(peer, FILE_PEER_CHANNEL, [{ action: 'close', connection: remote }]).catch(
+ () => {},
+ );
+ } catch {
+ // The peer still drops the connection on its own idle timeout.
+ }
+}
function stopConnection(id: string, reason: string) {
const c = connections.get(id);
if (!c) return;
@@ -274,9 +288,7 @@ function stopConnection(id: string, reason: string) {
if (out?.id === id) {
outgoing.delete(c.peer);
if (out.remote && isDataOwnerBroadcastScopeCurrent(c.owner))
- void out
- .invoke(c.peer, FILE_PEER_CHANNEL, [{ action: 'close', connection: out.remote }])
- .catch(() => {});
+ notifyPeerClose(out.invoke, c.peer, out.remote);
}
for (const [ticket, source] of sources)
if (source.connection === id) {
@@ -839,10 +851,7 @@ async function receivePeerFile(
if (!complete) {
stopConnection(id, 'incomplete');
if (outgoing.get(peer) === out) outgoing.delete(peer);
- if (remote && isDataOwnerBroadcastScopeCurrent(owner))
- void invoke(peer, FILE_PEER_CHANNEL, [{ action: 'close', connection: remote }]).catch(
- () => {},
- );
+ if (remote && isDataOwnerBroadcastScopeCurrent(owner)) notifyPeerClose(invoke, peer, remote);
}
if (directory) await fs.rm(directory, { recursive: true, force: true });
}
diff --git a/apps/desktop/src/main/remote-desktop-viewer/__tests__/safety.test.ts b/apps/desktop/src/main/remote-desktop-viewer/__tests__/safety.test.ts
index 734b6843ae..ffdd8f39c8 100644
--- a/apps/desktop/src/main/remote-desktop-viewer/__tests__/safety.test.ts
+++ b/apps/desktop/src/main/remote-desktop-viewer/__tests__/safety.test.ts
@@ -72,6 +72,50 @@ it('pauses until old work settles and discards its late success', async () => {
expect(request).toHaveBeenCalledTimes(1);
});
+it('a window-switch pause keeps the stopped read from updating the notice or failure count', async () => {
+ const { safety, options } = fixture();
+ const now = vi.spyOn(Date, 'now').mockReturnValue(10000);
+ let fail!: (error: Error) => void;
+ const tick = vi
+ .spyOn(ClipboardSync.prototype, 'tick')
+ .mockImplementationOnce(
+ () =>
+ new Promise((_resolve, reject) => {
+ fail = reject;
+ }),
+ )
+ .mockRejectedValueOnce(new Error('DESKTOP_UNAVAILABLE'))
+ .mockResolvedValue(undefined);
+ let focused = true;
+ const sync = {
+ ...options,
+ preferences: { ...options.preferences, clipboardSync: true },
+ clipboardCurrent: () => focused,
+ clipboard: { version: async () => 'v', read: async () => '{}', write: async () => 'v' },
+ };
+ try {
+ const stale = safety.tick(sync);
+ await vi.waitFor(() => expect(tick).toHaveBeenCalledTimes(1));
+ focused = false;
+ const paused = safety.pauseClipboard();
+ // Pausing stops the in-flight read, which then reports the clipboard as unavailable.
+ fail(new Error('DESKTOP_CLIPBOARD_UNAVAILABLE'));
+ expect((await stale).notice).toBeNull();
+ await paused;
+ expect(safety.snapshot().notice).toBeNull();
+
+ // The stale result was not counted: the first real failure backs off 1.5s, not 3s.
+ focused = true;
+ expect((await safety.tick(sync)).notice).toBe('clipboardSyncFailed');
+ now.mockReturnValue(12000);
+ await safety.tick(sync);
+ expect(tick).toHaveBeenCalledTimes(3);
+ } finally {
+ now.mockRestore();
+ tick.mockRestore();
+ }
+});
+
it('keeps conflict feedback until content is actually synchronized', async () => {
const { safety, options } = fixture();
const now = vi.spyOn(Date, 'now').mockReturnValue(10000);
diff --git a/apps/desktop/src/main/remote-desktop-viewer/safety.ts b/apps/desktop/src/main/remote-desktop-viewer/safety.ts
index aa4b5a217d..30c1184abf 100644
--- a/apps/desktop/src/main/remote-desktop-viewer/safety.ts
+++ b/apps/desktop/src/main/remote-desktop-viewer/safety.ts
@@ -165,9 +165,11 @@ export class ViewerSafety {
},
this.baseline,
);
+ // Results of a paused or refocused clipboard generation are stale: pauseClipboard stops
+ // the read (DESKTOP_CLIPBOARD_UNAVAILABLE), which must not count as a sync failure.
try {
await engine.tick();
- if (valid()) {
+ if (current()) {
if (
['clipboardSyncFailed', 'clipboardSyncPermission'].includes(
this.notices.get('clipboardSync') ?? '',
@@ -177,7 +179,7 @@ export class ViewerSafety {
this.failures = 0;
}
} catch (error) {
- if (!valid()) return this.snapshot();
+ if (!current()) return this.snapshot();
const failure = clipboardSyncFailure(error, this.failures++);
if (failure.code === 'DESKTOP_CLIPBOARD_UNAVAILABLE') this.applied.delete('clipboardSync');
this.notices.set('clipboardSync', failure.notice);