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): 出队发送前复验取消与归属检查

Dash00ba70737539
diff --git a/apps/desktop/src/main/device-link/__tests__/remoteInvokeSendGuard.test.ts b/apps/desktop/src/main/device-link/__tests__/remoteInvokeSendGuard.test.ts
new file mode 100644
index 0000000000..a925758bce
--- /dev/null
+++ b/apps/desktop/src/main/device-link/__tests__/remoteInvokeSendGuard.test.ts
@@ -0,0 +1,62 @@
+import { readFileSync } from 'node:fs';
+import ts from 'typescript';
+import { expect, it, vi } from 'vitest';
+import { DeviceLinkError, type DeviceLinkClient } from '@cindy/device-link';
+import { invokeWithClosedLinkRecovery } from '../linkRecovery';
+
+// Run the production adapter with only its host dependencies injected, without
+// importing Electron startup. The shared-client tests cover actual queue admission.
+const source = ts.createSourceFile('index.ts', readFileSync(new URL('../index.ts', import.meta.url), 'utf8'), ts.ScriptTarget.Latest, true);
+const declaration = source.statements.find((node): node is ts.FunctionDeclaration =>
+ ts.isFunctionDeclaration(node) && node.name?.text === 'remoteInvoke')!;
+const compiled = ts.transpileModule(declaration.getText(source).replace(/^export /, ''), {
+ compilerOptions: { target: ts.ScriptTarget.ES2022 },
+}).outputText;
+
+it.each(['caller cancelled', 'target disabled', 'link closed', 'still valid'])(
+ 'revalidates %s after the client queue and never reopens an explicitly closed link', async (change) => {
+ let enabled = true;
+ let current = true;
+ const epochs = new Map<string, number>();
+ const send = vi.fn();
+ const reopen = vi.fn();
+ let dispatch!: () => void;
+ const invoke = vi.fn<DeviceLinkClient['invoke']>((_peer, _payload, _timeout, options) => new Promise((resolve, reject) => {
+ dispatch = () => {
+ try { options?.preSend?.(); send(); resolve({ ok: true, result: null }); }
+ catch (error) { reject(error); }
+ };
+ }));
+ const dependencies = {
+ DeviceLinkError, invokeWithClosedLinkRecovery,
+ assertNotStandby: () => {},
+ assertRemoteControlTargetEnabled: () => { if (!enabled) throw new DeviceLinkError('REMOTE_DISABLED', 'disabled'); },
+ openLinkCloseEpochs: epochs,
+ ensureOnlineForRequest: async () => {},
+ client: { invoke },
+ parseSharedTaskPeer: () => null,
+ tryPeerInvoke: async () => null,
+ resolveRemoteInvokeTimeoutMs: () => undefined,
+ openRemoteLink: reopen,
+ closeRemoteLink: vi.fn(),
+ responsivenessTracker: null,
+ };
+ const remoteInvoke = new Function(...Object.keys(dependencies), compiled + '; return remoteInvoke;')(...Object.values(dependencies));
+ const cancelled = new Error('caller cancelled');
+ const pending = remoteInvoke('host', 'maker:send', [], {
+ preSend: () => { if (!current) throw cancelled; },
+ }).catch((error: unknown) => error);
+ await vi.waitFor(() => expect(invoke).toHaveBeenCalledTimes(1));
+ if (change === 'caller cancelled') current = false;
+ if (change === 'target disabled') enabled = false;
+ if (change === 'link closed') epochs.set('host', 1);
+ dispatch();
+ const result = await pending;
+ if (change === 'caller cancelled') expect(result).toBe(cancelled);
+ if (change === 'target disabled') expect(result).toMatchObject({ code: 'REMOTE_DISABLED' });
+ if (change === 'link closed') expect(result).toMatchObject({ code: 'LINK_NOT_OPEN' });
+ if (change === 'still valid') expect(result).toEqual({ ok: true, result: null });
+ expect(send).toHaveBeenCalledTimes(change === 'still valid' ? 1 : 0);
+ expect(reopen).not.toHaveBeenCalled();
+ },
+);
diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.ts
index e21b9bccc2..eb4d1273e5 100644
--- a/apps/desktop/src/main/device-link/index.ts
+++ b/apps/desktop/src/main/device-link/index.ts
@@ -1760,29 +1760,27 @@ export async function remoteInvoke(
throw new DeviceLinkError('LINK_NOT_OPEN', 'link closed while waiting to reconnect');
}
};
+ const preSend = (): void => {
+ assertRemoteControlTargetEnabled(deviceId);
+ assertLinkNotClosedSinceStart();
+ options?.preSend?.();
+ };
const invoke = async (): Promise<InvokeResultPayload> => {
// 熔断门禁(外层 guardInvoke)在连接等待之前:open 态快速失败,不消耗 1.5s 等待。
await ensureOnlineForRequest();
// fail-closed 边界不得跨 await 失效:等待期间用户可能已关闭该设备控制(复验
// 授权),或显式 CLOSE_LINK(复验取消代次)(review P1 ×2)。
- assertRemoteControlTargetEnabled(deviceId);
- assertLinkNotClosedSinceStart();
- options?.preSend?.();
+ preSend();
if (!client) throw new Error('[DEVICE_LINK_NOT_CONNECTED] device-link client not initialized');
if (!parseSharedTaskPeer(deviceId)) {
const accelerated = await tryPeerInvoke(deviceId, channel, args, (peer, nextChannel, nextArgs) => {
- assertLinkNotClosedSinceStart();
- return remoteInvoke(peer, nextChannel, nextArgs, { preSend: () => {
- assertLinkNotClosedSinceStart();
- options?.preSend?.();
- } });
+ preSend();
+ return remoteInvoke(peer, nextChannel, nextArgs, { preSend });
});
- assertRemoteControlTargetEnabled(deviceId);
- assertLinkNotClosedSinceStart();
- options?.preSend?.();
+ preSend();
if (accelerated) return accelerated;
}
- return client.invoke(deviceId, { channel, args }, resolveRemoteInvokeTimeoutMs(channel, args, 'desktop'));
+ return client.invoke(deviceId, { channel, args }, resolveRemoteInvokeTimeoutMs(channel, args, 'desktop'), { preSend });
};
const run = (): Promise<InvokeResultPayload> =>
invokeWithClosedLinkRecovery(
diff --git a/apps/mobile/src/__tests__/historyViewProvider.test.tsx b/apps/mobile/src/__tests__/historyViewProvider.test.tsx
index 86738f6be4..a1a3235370 100644
--- a/apps/mobile/src/__tests__/historyViewProvider.test.tsx
+++ b/apps/mobile/src/__tests__/historyViewProvider.test.tsx
@@ -3,6 +3,7 @@ import { act, createElement } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
+ DeviceLinkError,
DEVICE_LINK_CAPABILITY_HISTORY_VIEW_V1,
SHARED_TASK_CAPABILITY,
type DeviceLinkClient,
@@ -67,7 +68,10 @@ const transport = vi.hoisted(() => {
peerReset: Parameters<DeviceLinkClient['onPeerTransportReset']>[0] = () => {};
frame: Parameters<DeviceLinkClient['onFrame']>[0] = () => {};
openLink = vi.fn<(deviceId: string) => Promise<LinkAcceptPayload>>();
- invoke = vi.fn(async () => ({ ok: true, result: 'history page' }));
+ invoke = vi.fn<DeviceLinkClient['invoke']>(async (_deviceId, _payload, _timeout, options) => {
+ options?.preSend?.();
+ return { ok: true, result: 'history page' };
+ });
start = vi.fn();
stop = vi.fn();
connectNow = vi.fn();
@@ -124,6 +128,39 @@ beforeEach(async () => {
});
afterEach(async () => { await act(async () => root.unmount()); });
+describe('Provider queued send guards', () => {
+ it('rejects a write cancelled after admission without sending or counting a remote timeout', async () => {
+ resetDeviceResponsivenessTracking();
+ const client = transport.clients[0];
+ const send = vi.fn();
+ const cancelled = new DeviceLinkError('INVOKE_TIMEOUT', 'local operation expired');
+ // Two actual remote timeouts: a third would open the breaker if the local
+ // guard rejection were incorrectly classified as a failed remote request.
+ for (let i = 0; i < 2; i++) settleDeviceSend('host', acquireDeviceSendSlot('host'), 'timeout');
+ let current = true;
+ let dispatch!: () => void;
+ client.invoke.mockImplementation((_deviceId, _payload, _timeout, options) => new Promise((resolve, reject) => {
+ dispatch = () => {
+ try { options?.preSend?.(); send(); resolve({ ok: true, result: null }); }
+ catch (error) { reject(error); }
+ };
+ }));
+ let result!: Promise<unknown>;
+ await act(async () => {
+ result = context.invoke('host', 'maker:send', [], {
+ preSend: () => { if (!current) throw cancelled; },
+ }).catch(error => error);
+ });
+ expect(client.invoke).toHaveBeenCalledTimes(1);
+ current = false;
+ await act(async () => dispatch());
+ expect(await result).toBe(cancelled);
+ expect(send).not.toHaveBeenCalled();
+ expect(unresponsiveDevicesStore.getSnapshot().has('host')).toBe(false);
+ resetDeviceResponsivenessTracking();
+ });
+});
+
describe('pending catalog recovery', () => {
it.each(['foreground', 'peer response'] as const)('wakes a blocked invalidation on %s before its long retry timer expires', async (recovery) => {
vi.useFakeTimers();
@@ -145,8 +182,8 @@ describe('pending catalog recovery', () => {
} else unresponsiveDevicesStore.clearUnresponsive('host');
await vi.advanceTimersByTimeAsync(50);
});
- expect(client.invoke).toHaveBeenCalledWith('host', expect.objectContaining({ channel: 'maker:provider:list' }), undefined);
- expect(client.invoke).toHaveBeenCalledWith('host', expect.objectContaining({ channel: 'maker:get-capabilities' }), undefined);
+ expect(client.invoke).toHaveBeenCalledWith('host', expect.objectContaining({ channel: 'maker:provider:list' }), undefined, expect.objectContaining({ preSend: expect.any(Function) }));
+ expect(client.invoke).toHaveBeenCalledWith('host', expect.objectContaining({ channel: 'maker:get-capabilities' }), undefined, expect.objectContaining({ preSend: expect.any(Function) }));
} finally { unresponsiveDevicesStore.clearAll(); vi.useRealTimers(); }
});
});
@@ -169,7 +206,7 @@ describe('pending probe reply recovery', () => {
for (let i = 0; i < 3; i++) settleDeviceSend('host', acquireDeviceSendSlot('host'), 'timeout');
await vi.advanceTimersByTimeAsync(14_000);
});
- expect(client.invoke).toHaveBeenCalledExactlyOnceWith('host', expect.objectContaining({ channel: 'local-db:sessions:list' }), expect.any(Number));
+ expect(client.invoke).toHaveBeenCalledExactlyOnceWith('host', expect.objectContaining({ channel: 'local-db:sessions:list' }), expect.any(Number), expect.objectContaining({ preSend: expect.any(Function) }));
expect(unresponsiveDevicesStore.has('host')).toBe(true);
client.hasPendingRequestsTo.mockImplementation(device => device === 'host');
const freshAccept = deferredAccept();
@@ -434,7 +471,7 @@ describe('Provider history handshake lifetime', () => {
await act(async () => current.resolve(accepted(supported)));
expect(await fresh.result).toBe('history page');
expect(currentClient.invoke).toHaveBeenCalledTimes(1);
- expect(currentClient.invoke).toHaveBeenCalledWith('host', { channel: historyChannel, args: [] }, undefined);
+ expect(currentClient.invoke).toHaveBeenCalledWith('host', { channel: historyChannel, args: [] }, undefined, expect.objectContaining({ preSend: expect.any(Function) }));
// A late old completion must not evict the new successful single-flight.
await act(async () => { expect(await context.invoke('host', historyChannel)).toBe('history page'); });
expect(currentClient.openLink).toHaveBeenCalledTimes(currentClient === client ? 2 : 1);
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index b4f13578d5..2b16a1598a 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -183,10 +183,10 @@ export interface DeviceLinkContextValue {
/** Acquire before background grace ends; always release on settlement/cancellation. Hard deadline enforced by lifecycle. */
beginBackgroundTransition?(): () => void;
/**
- * opts.preSend:在连接就绪之后、真正 client.invoke 之前的最后同步检查点。抛错即
+ * opts.preSend:在连接就绪并从 invoke 队列出队后、实际发送前的同步检查点。抛错即
* 中止本次发送(错误原样上抛)。供写序敏感的调用方(patchHomeSession 的 isLatest
- * 屏障)把「过期即放弃」判定贴到实际发送点——ensureOnlineForRequest 最长 1.5s 的
- * 重连等待期间写可能被同字段新写取代,等待前的检查不够晚。
+ * 屏障)把「过期即放弃」判定贴到实际发送点——重连或排队期间写可能被同字段新写
+ * 取代,等待前的检查不够晚。
*/
invoke<T = unknown>(
deviceId: string,
@@ -1987,7 +1987,7 @@ async function sendInvoke<T>(
});
try {
await ensureOnlineForRequest(client);
- // 连接就绪后、真正发送前的最后检查点:重连等待期间调用方状态可能已失效
+ // 连接就绪后先检查一次:重连等待期间调用方状态可能已失效
// (写被同字段新写取代),抛错即中止发送。
opts?.preSend?.();
} catch (err) {
@@ -1996,6 +1996,7 @@ async function sendInvoke<T>(
throw err;
}
let result: InvokeResultPayload;
+ let preSendFailed = false;
try {
// 长执行通道(desktop-cmd:run / worktree:create 等)按协议契约表放宽超时,
// 与桌面控制端用法对齐,避免 mobile 收紧的默认 15s 误伤合法慢操作。
@@ -2005,9 +2006,18 @@ async function sendInvoke<T>(
// 长通道(media / 文件搜索 / schedule 就绪窗口等)按 invokeTimeouts 解析
// 规则保留更长窗口,避免 mobile 收紧的默认 15s 误伤合法慢操作。
resolveMobileInvokeTimeoutMs(channel, args),
+ { preSend: () => {
+ try {
+ opts?.preSend?.();
+ } catch (err) {
+ preSendFailed = true;
+ throw err;
+ }
+ } },
);
} catch (err) {
- settleDeviceSend(deviceId, slot, classifyDeviceSendFailure(err));
+ // A queued call rejected by its local guard is not a remote timeout.
+ settleDeviceSend(deviceId, slot, preSendFailed ? 'inconclusive' : classifyDeviceSendFailure(err));
throw err;
}
// 收到 invoke-result 帧即为目标设备真实回包(即使 ok:false 的业务错误)。但
diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.md
index 9cfc2d3392..d7f9c93a11 100644
--- a/docs/dev-rules/remote-and-mobile-adaptation.md
+++ b/docs/dev-rules/remote-and-mobile-adaptation.md
@@ -79,6 +79,8 @@ relay 以 close 1013 `inbound backpressure` 主动断连,此时任何「立即
每设备最多等待 128 条,后台最多占前 96 个等待位置;排队预算不超过 30 秒,
排队过期返回 BACKPRESSURE,发送后仍保留原通道执行预算。断连/停止时取消未发送项,
在途项仍由既有 transport 结算,不能把取消或超时当成远端操作未执行。
+调用方的 `preSend` 同步检查在出队后、创建请求前再次执行;排队期间失效的写入
+必须拒绝发送并释放配额,本地检查失败不作为远端无响应的证据。
Desktop 将 BACKPRESSURE 映射为 DEVICE_LINK_BUSY;桌面和手机标签入口显示繁忙与手动重试。
被控端拒收时 Debug 日志记录在途数、待回包数、配额范围和前八个通道计数,
不记录参数/标签/消息内容。原被控端准入上限及 wire 格式不变,可独立升级控制端。
diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.ts
index beaac553b8..fb5faf7556 100644
--- a/packages/device-link/src/__tests__/client.test.ts
+++ b/packages/device-link/src/__tests__/client.test.ts
@@ -126,6 +126,52 @@ function makeHarness(opts?: {
const tick = (ms = 0): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
describe('outbound invoke admission', () => {
+ it('rechecks a queued write before dispatch and releases its slot when the caller cancels', async () => {
+ vi.useFakeTimers();
+ const h = makeHarness({ timing: { pingIntervalMs: 60_000, requestTimeoutMs: 30_000 } });
+ const calls: Promise<unknown>[] = [];
+ try {
+ h.client.start(); await vi.advanceTimersByTimeAsync(1); h.current().ack();
+ for (let i = 0; i < 12; i++) calls.push(h.client.invoke('a', {
+ channel: 'maker:send', args: [i],
+ }).catch(e => e));
+ let current = true;
+ const cancelled = new Error('owner changed while queued');
+ const preSend = vi.fn(() => { if (!current) throw cancelled; });
+ const stale = h.client.invoke('a', { channel: 'maker:send', args: ['stale'] }, undefined, { preSend }).catch(e => e);
+ calls.push(stale);
+ calls.push(h.client.invoke('a', { channel: 'maker:send', args: ['fresh'] }).catch(e => e));
+ const sent = () => h.current().sent.filter(e => e.kind === 'invoke');
+ expect(sent()).toHaveLength(12);
+ expect(preSend).not.toHaveBeenCalled();
+ current = false;
+ h.current().push({ v: PROTOCOL_VERSION, kind: 'invoke-result', src: 'a', id: sent()[0].id,
+ payload: { ok: true, result: null } });
+ await vi.advanceTimersByTimeAsync(1);
+ expect(await stale).toBe(cancelled);
+ expect(preSend).toHaveBeenCalledTimes(1);
+ expect(sent()).toHaveLength(13);
+ expect(sent().at(-1)?.payload).toMatchObject({ channel: 'maker:send', args: ['fresh'] });
+ expect(sent().some(e => (e.payload as { args: unknown[] }).args[0] === 'stale')).toBe(false);
+ } finally {
+ h.client.stop(); await Promise.all(calls); vi.useRealTimers();
+ }
+ });
+
+ it.each(['maker:send', 'device-link:subscribe'])(
+ 'honors the send guard for immediately admitted %s calls', async (channel) => {
+ const h = makeHarness({ timing: { pingIntervalMs: 60_000 } });
+ try {
+ h.client.start(); await tick(); h.current().ack();
+ const cancelled = new Error('cancelled');
+ await expect(h.client.invoke('a', { channel, args: [] }, undefined, {
+ preSend: () => { throw cancelled; },
+ })).rejects.toBe(cancelled);
+ expect(h.current().sent.filter(e => e.kind === 'invoke')).toHaveLength(0);
+ } finally { h.client.stop(); }
+ },
+ );
+
it('sends initial session lists and recovery probes while all background slots are occupied', async () => {
vi.useFakeTimers();
const h = makeHarness({ timing: { pingIntervalMs: 60_000, requestTimeoutMs: 30_000 } });
diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.ts
index bbbe201a2e..b998502bbe 100644
--- a/packages/device-link/src/client.ts
+++ b/packages/device-link/src/client.ts
@@ -1342,13 +1342,23 @@ export class DeviceLinkClient {
}
/** 控制端:远程 invoke,等待 invoke-result */
- async invoke(dst: string, payload: InvokePayload, timeoutMs?: number): Promise<InvokeResultPayload> {
+ async invoke(
+ dst: string,
+ payload: InvokePayload,
+ timeoutMs?: number,
+ options?: { preSend?: () => void },
+ ): Promise<InvokeResultPayload> {
if (this.status !== 'online') throw new DeviceLinkError('NOT_CONNECTED', 'not connected to relay');
- const send = () => this.request(
- { v: PROTOCOL_VERSION, kind: 'invoke', dst, payload: requestSessionTagCatalog(payload) },
- 'invoke-result',
- timeoutMs,
- );
+ const send = () => {
+ // Admission may wait: validate caller ownership/cancellation after dequeue,
+ // synchronously before creating the request or retaining a transport frame.
+ options?.preSend?.();
+ return this.request(
+ { v: PROTOCOL_VERSION, kind: 'invoke', dst, payload: requestSessionTagCatalog(payload) },
+ 'invoke-result',
+ timeoutMs,
+ );
+ };
const env = await (bypassInvokeScheduling(payload) ? send() : this.invokeScheduler.run(
dst, isBackgroundInvoke(payload.channel), Math.min(timeoutMs ?? this.timing.requestTimeoutMs, 30_000), send,
));