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): allow owner-safe file connection teardown after cancellation

Dash8d21c8bb98f0
diff --git a/apps/desktop/src/main/device-link/__tests__/fileAccess.test.ts b/apps/desktop/src/main/device-link/__tests__/fileAccess.test.ts
index d29b5e2e3f..ebf65af326 100644
--- a/apps/desktop/src/main/device-link/__tests__/fileAccess.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/fileAccess.test.ts
@@ -1,19 +1,40 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const peer = vi.hoisted(() => vi.fn());
const remove = vi.hoisted(() => vi.fn());
+const owner = vi.hoisted(() => ({ current: true }));
vi.mock('../filePeer', () => ({ tryPeerFile: peer }));
vi.mock('../mediaTransfer', () => ({ removeRemote: remove }));
vi.mock('../broadcast-tap', () => ({
captureDataOwnerBroadcastScope: () => ({}),
- isDataOwnerBroadcastScopeCurrent: () => true,
+ isDataOwnerBroadcastScopeCurrent: () => owner.current,
}));
import { readRemoteDeviceFile } from '../fileAccess';
import { invalidateFilePeerScopes } from '../filePeerScope';
beforeEach(() => {
vi.clearAllMocks();
+ owner.current = true;
peer.mockResolvedValue(null);
});
describe('desktop shared file access', () => {
+ it.each(['abort', 'stop', 'owner'] as const)('keeps business requests cancelled while permitting owner-safe close (%s)', async reason => {
+ const abort = new AbortController();
+ const invoke = vi.fn(async () => ({ ok: true, result: { ossKey: '', size: 5, mimeType: 'text/plain', transferRequired: true } }));
+ peer.mockImplementationOnce(async (device, _url, guarded) => {
+ if (reason === 'abort') abort.abort();
+ if (reason === 'stop') invalidateFilePeerScopes(device);
+ if (reason === 'owner') owner.current = false;
+ for (const action of ['caps', 'offer', 'open'])
+ await expect(guarded(device, 'device-link:file-peer', [{ action }])).rejects.toThrow('FILE_PEER_CANCELLED');
+ await expect(guarded(device, 'device-link:media:fetch', [{ action: 'close' }])).rejects.toThrow('FILE_PEER_CANCELLED');
+ const close = guarded(device, 'device-link:file-peer', [{ action: 'close', connection: 'old-connection' }]);
+ if (reason === 'owner') await expect(close).rejects.toThrow('FILE_PEER_CANCELLED');
+ else await expect(close).resolves.toMatchObject({ ok: true });
+ return null;
+ });
+ await expect(readRemoteDeviceFile('guarded-peer', 'url', invoke, { signal: abort.signal })).rejects.toThrow('FILE_PEER_CANCELLED');
+ expect(invoke).toHaveBeenCalledTimes(reason === 'owner' ? 1 : 2);
+ });
+
it('cancels a late file preparation after unlink without starting peer or OSS', async () => {
let answer!: (value: unknown) => void;
const invoke = vi.fn(() => new Promise<any>(resolve => { answer = resolve; }));
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 62f58d3fe1..ed17d2c1f4 100644
--- a/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/filePeer.test.ts
@@ -38,6 +38,7 @@ vi.mock('../../appSessionState', () => ({
getActiveAppSession: () => ({ mode: 'cloud', dataOwnerId: 'cache-owner' }),
activeOwnerScopeKey: () => 'cache-owner:0',
}));
+vi.mock('../mediaTransfer', () => ({ removeRemote: vi.fn() }));
vi.mock('../mediaFetch', () => ({ resolveAuthorizedMedia: mock.resolve }));
vi.mock('../settings-store', () => ({ readDeviceLinkSettings: () => mock.settings }));
vi.mock('../broadcast-tap', () => ({
@@ -83,6 +84,7 @@ import {
tryPeerFile,
tryUploadPeerAttachment,
} from '../filePeer';
+import { readRemoteDeviceFile } from '../fileAccess';
import { DesktopCaptureWindow } from '../../remote-desktop/captureWindow';
import { createHash } from 'node:crypto';
@@ -395,6 +397,56 @@ describe('authorized file peer source', () => {
expect(result?.size).toBe(5);
await result?.dispose();
});
+ it.each(
+ (['offer', 'receive', 'idle'] as const).flatMap(stage =>
+ (['abort', 'stop', 'owner'] as const).map(reason => ({ stage, reason }))),
+ )('closes only the original owner connection after $reason during $stage', async ({ stage, reason }) => {
+ const peer = `adapter-close-${stage}-${reason}`;
+ const remote = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
+ let answer!: (value: { ok: boolean; result: unknown }) => void;
+ const invoke = vi.fn(async (_peer: string, channel: string, [request]: any[]) => {
+ if (channel === 'device-link:media:fetch')
+ return { ok: true, result: { ossKey: '', size: 5, mimeType: 'text/plain', transferRequired: true } };
+ if (request.action === 'caps') return { ok: true, result: { version: 1, sessionBound: true } };
+ if (request.action === 'offer' && stage === 'offer')
+ return new Promise<{ ok: boolean; result: unknown }>(resolve => { answer = resolve; });
+ if (request.action === 'open')
+ return { ok: true, result: { ticket: 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb', size: 5, mimeType: 'text/plain' } };
+ return { ok: true, result: { connection: remote, sdp: 'v=0' } };
+ });
+ const abort = new AbortController();
+ const fallback = vi.fn();
+ const pending = readRemoteDeviceFile(peer, 'xdt-file://test', invoke, { signal: abort.signal, fallback });
+ const rejected = stage === 'idle' ? undefined : expect(pending).rejects.toThrow('FILE_PEER_CANCELLED');
+ if (stage === 'offer') await vi.waitFor(() => expect(answer).toBeDefined());
+ else {
+ await vi.waitFor(() => expect(mock.receiving).toBeDefined());
+ if (stage === 'idle') {
+ await mock.handlers.get('file-peer:host:write')!({}, mock.receiving!.sink, 0, 'aGVsbG8=');
+ mock.receiving!.reply();
+ const result = await pending;
+ if ('dispose' in result) await result.dispose();
+ }
+ }
+ if (reason === 'owner') mock.current = false;
+ if (reason === 'abort') abort.abort();
+ // Idle connections outlive a completed read; its old signal must not block later teardown.
+ if (reason !== 'abort' || stage === 'idle') stopFilePeers(peer);
+ if (stage === 'offer') answer({ ok: true, result: { connection: remote, sdp: 'v=0' } });
+ await rejected;
+ const closes = invoke.mock.calls.filter(([, channel, [request]]) =>
+ channel === 'device-link:file-peer' && request.action === 'close');
+ if (reason === 'owner') expect(closes).toHaveLength(0);
+ else expect(closes.length).toBeGreaterThan(0);
+ for (const [target, , requests] of closes)
+ expect([target, requests]).toEqual([peer, [{ action: 'close', connection: remote }]]);
+ if (stage === 'offer') {
+ expect(mock.sent).not.toContain('answer');
+ expect(invoke.mock.calls.some(([, , [request]]) => request.action === 'open')).toBe(false);
+ }
+ expect(fallback).not.toHaveBeenCalled();
+ });
+
it('falls back a stalled file while another peer keeps writing and completes', async () => {
vi.useFakeTimers();
try {
diff --git a/apps/desktop/src/main/device-link/fileAccess.ts b/apps/desktop/src/main/device-link/fileAccess.ts
index 279678de0d..62a9023ad8 100644
--- a/apps/desktop/src/main/device-link/fileAccess.ts
+++ b/apps/desktop/src/main/device-link/fileAccess.ts
@@ -1,6 +1,7 @@
import {
readDeviceFile,
DL_MEDIA_FETCH_CHANNEL,
+ FILE_PEER_CHANNEL,
FILE_PEER_MAX_BYTES,
type DeviceFileResult,
} from '@cindy/device-link';
@@ -31,10 +32,16 @@ export function readRemoteDeviceFile(
) {
const owner = captureDataOwnerBroadcastScope();
const isCurrent = captureFilePeerScope(device);
- const invoke: Invoke = async (...args) => {
- if (options.signal?.aborted || !isCurrent())
+ const invoke: Invoke = async (target, channel, args) => {
+ // A connection can outlive this read, including an offer answered after cancellation.
+ // Teardown may cross the read's cancellation boundary, never the account boundary.
+ const closing = channel === FILE_PEER_CHANNEL &&
+ (args[0] as { action?: unknown } | undefined)?.action === 'close';
+ if (closing
+ ? !isDataOwnerBroadcastScopeCurrent(owner)
+ : options.signal?.aborted || !isCurrent())
throw new Error('FILE_PEER_CANCELLED');
- return rawInvoke(...args);
+ return rawInvoke(target, channel, args);
};
const fetch = async (prepareOnly: boolean): Promise<DeviceFileResult> => {
const response = await invoke(device, DL_MEDIA_FETCH_CHANNEL, [
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 6580911c9f..98403c2b59 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -789,6 +789,9 @@ link-accept 双向声明,不改 relay)。Desktop 控制端在本机没有订
采样随传输结束停止,不在空闲文件连接上循环探测。
Desktop 显式断链、账号变化、共享连接离线,以及 Mobile 退后台、设备切换、断链时释放。
取消同时覆盖排队与尚未拿到连接 ID 的请求;迟到的协商结果不能重新建立连接或触发 OSS。
+Desktop 取件取消后仍允许原账号发送已有 `close` 清理通知,包括迟到的 offer 回包与
+已完成读取留下的空闲连接;其他请求继续受取消和设备代次限制。切账号后旧通知不发送,
+不借新账号清理旧连接,不增加重试、心跳或共享 relay 重连。
旧控制端未发送 `sessionBound` 时,新 Host 仍按 5 分钟空闲关闭;新控制端面对未声明
该能力的 Host,按 `idleMs` 提前一个命令预算(15 秒)关闭,最长 4 分 45 秒,未声明