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): 避免重复 link-open 与 listing 把 ACK/DB 打满 (#4350)
Chris Zhangc3ac77b3f0f7
diff --git a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.tsindex b5544a5fef..b754683073 100644--- a/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts+++ b/apps/desktop/src/main/__tests__/deviceLinkDispatch.test.ts@@ -185,6 +185,20 @@ describe('runInvoke 双层校验', () => {});});+ it('DB worker 队列打满时远程 listing 回 BACKPRESSURE', async () => {+ registry.register('local-db:sessions:list', () => {+ throw new Error('db worker RPC queue overloaded: op="rawAll" inFlight=128 queued=512');+ });+ const r = await runInvoke('ctrl', { channel: 'local-db:sessions:list', args: [1, 'all'] });+ expect(r).toMatchObject({+ ok: false,+ error: {+ code: 'BACKPRESSURE',+ message: expect.stringContaining('db worker RPC queue overloaded'),+ },+ });+ });+it('handler 不存在(未注册)→ IPC_ERROR NOT_FOUND', async () => {const r = await runInvoke('ctrl', { channel: 'maker:create-session', args: [] });expect(r).toMatchObject({ ok: false, error: { code: 'IPC_ERROR' } });@@ -1110,6 +1124,148 @@ describe('被控端控制链路生命周期', () => {expect(dispatchTesting.remoteInvokeResultOutboxSize()).toBe(0);});+ it('同一控制端相同 listing 并发只执行一次并把结果复用到各 requestId', async () => {+ remoteControlEnabled = true;+ let resolveList: ((value: unknown[]) => void) | undefined;+ const handler = vi.fn(() => new Promise<unknown[]>((resolve) => {+ resolveList = resolve;+ }));+ registry.register('local-db:sessions:list', handler);+ const { client, calls, feed } = makeFakeClient();+ wireInboundDispatch(client);+ const payload = {+ channel: 'local-db:sessions:list',+ args: [20, 'all', { includePinned: true }],+ };+ feed({+ v: 1,+ kind: 'invoke',+ id: 'list-1',+ src: 'ctrl-a',+ payload,+ });+ feed({+ v: 1,+ kind: 'invoke',+ id: 'list-2',+ src: 'ctrl-a',+ payload,+ });+ await vi.waitFor(() => expect(handler).toHaveBeenCalledTimes(1));+ resolveList?.([{ id: 's1' }]);+ await vi.waitFor(() => {+ expect(calls.invokeResult.filter(+ (call) => call.requestId === 'list-1' || call.requestId === 'list-2',+ )).toHaveLength(2);+ });+ expect(handler).toHaveBeenCalledTimes(1);+ expect(calls.invokeResult).toEqual(expect.arrayContaining([+ expect.objectContaining({+ requestId: 'list-1',+ payload: { ok: true, result: [{ id: 's1' }] },+ }),+ expect.objectContaining({+ requestId: 'list-2',+ payload: { ok: true, result: [{ id: 's1' }] },+ }),+ ]));+ });++ it('listing 合并 waiter 仍计入 per-controller 准入上限', async () => {+ remoteControlEnabled = true;+ let resolveList: ((value: unknown[]) => void) | undefined;+ const handler = vi.fn(() => new Promise<unknown[]>((resolve) => {+ resolveList = resolve;+ }));+ registry.register('local-db:sessions:list', handler);+ const { client, calls, feed } = makeFakeClient();+ wireInboundDispatch(client);+ const payload = { channel: 'local-db:sessions:list', args: [20, 'all'] };+ const limit = dispatchTesting.remoteInvokeInFlightPerControllerLimit;+ for (let index = 0; index < limit + 1; index += 1) {+ feed({+ v: 1,+ kind: 'invoke',+ id: `list-admit-${index}`,+ src: 'ctrl-a',+ payload,+ });+ }+ await vi.waitFor(() => expect(handler).toHaveBeenCalledTimes(1));+ await vi.waitFor(() => expect(calls.invokeResult).toContainEqual({+ dst: 'ctrl-a',+ requestId: `list-admit-${limit}`,+ payload: {+ ok: false,+ error: {+ code: 'BACKPRESSURE',+ message: 'remote invoke execution queue is full',+ },+ },+ }));+ resolveList?.([{ id: 's1' }]);+ await vi.waitFor(() => {+ expect(calls.invokeResult.filter((call) => call.payload && (call.payload as { ok?: boolean }).ok === true))+ .toHaveLength(limit);+ });+ expect(handler).toHaveBeenCalledTimes(1);+ });++ it('sessions:list fresh 请求不并入已有 listing 单飞', async () => {+ remoteControlEnabled = true;+ let resolvers: Array<(value: unknown[]) => void> = [];+ const handler = vi.fn(() => new Promise<unknown[]>((resolve) => {+ resolvers.push(resolve);+ }));+ registry.register('local-db:sessions:list', handler);+ const { client, calls, feed } = makeFakeClient();+ wireInboundDispatch(client);+ const payload = {+ channel: 'local-db:sessions:list',+ args: [20, 'all', { includePinned: true, fresh: true }],+ };+ feed({ v: 1, kind: 'invoke', id: 'fresh-1', src: 'ctrl-a', payload });+ feed({ v: 1, kind: 'invoke', id: 'fresh-2', src: 'ctrl-a', payload });+ await vi.waitFor(() => expect(handler).toHaveBeenCalledTimes(2));+ resolvers[0]?.([{ id: 'old' }]);+ resolvers[1]?.([{ id: 'new' }]);+ await vi.waitFor(() => {+ expect(calls.invokeResult.filter(+ (call) => call.requestId === 'fresh-1' || call.requestId === 'fresh-2',+ )).toHaveLength(2);+ });+ expect(calls.invokeResult).toEqual(expect.arrayContaining([+ expect.objectContaining({ requestId: 'fresh-1', payload: { ok: true, result: [{ id: 'old' }] } }),+ expect.objectContaining({ requestId: 'fresh-2', payload: { ok: true, result: [{ id: 'new' }] } }),+ ]));+ });++ it('sessions:get 写后回读不并入已有查询', async () => {+ remoteControlEnabled = true;+ const resolvers: Array<(value: unknown) => void> = [];+ const handler = vi.fn(() => new Promise<unknown>((resolve) => {+ resolvers.push(resolve);+ }));+ registry.register('local-db:sessions:get', handler);+ const { client, calls, feed } = makeFakeClient();+ wireInboundDispatch(client);+ const payload = { channel: 'local-db:sessions:get', args: ['sess-1'] };+ feed({ v: 1, kind: 'invoke', id: 'get-stale', src: 'ctrl-a', payload });+ feed({ v: 1, kind: 'invoke', id: 'get-after-write', src: 'ctrl-a', payload });+ await vi.waitFor(() => expect(handler).toHaveBeenCalledTimes(2));+ resolvers[0]?.({ id: 'sess-1', model: 'old' });+ resolvers[1]?.({ id: 'sess-1', model: 'new' });+ await vi.waitFor(() => {+ expect(calls.invokeResult.filter(+ (call) => call.requestId === 'get-stale' || call.requestId === 'get-after-write',+ )).toHaveLength(2);+ });+ expect(calls.invokeResult).toEqual(expect.arrayContaining([+ expect.objectContaining({ requestId: 'get-stale', payload: { ok: true, result: { id: 'sess-1', model: 'old' } } }),+ expect.objectContaining({ requestId: 'get-after-write', payload: { ok: true, result: { id: 'sess-1', model: 'new' } } }),+ ]));+ });+it('显式 link-close 后丢弃旧世代晚到 IPC 结果,快速重开也不串进新链路', async () => {remoteControlEnabled = true;let resolveInvoke: ((value: string[]) => void) | undefined;diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.tsindex 09d41a7781..8ae028806f 100644--- a/apps/desktop/src/main/device-link/dispatch.ts+++ b/apps/desktop/src/main/device-link/dispatch.ts@@ -605,6 +605,19 @@ type RemoteInvokeBusyChangedListener = (busy: boolean) => void;let onRemoteInvokeBusyChanged: RemoteInvokeBusyChangedListener | null = null;let inFlightRemoteInvokeCount = 0;const REMOTE_INVOKE_IN_FLIGHT_LIMIT = 64;+/**+ * 控制端周期对账 / 熔断探测会用新 requestId 连打相同 listing。按 requestId 去重+ * 拦不住,16 条并发 sessions:list 会把单线程 DB worker 打到 128/512 硬顶。+ * 同一控制端、同一 channel+args 的只读 listing 合并成一次执行。+ */+const COALESCE_REMOTE_INVOKE_CHANNELS: ReadonlySet<string> = new Set([+ 'local-db:sessions:list',+ // sessions:get 是写后权威回读(mobile 设置失败恢复会复用同一参数),+ // 不能并进仍停在投影 await 的写前查询。+ 'maker:get-capabilities',+ 'maker:provider:list',+ 'maker:git-safety:get',+]);/*** Keep one slow controller from consuming the entire target-device budget.* The global limit still protects the host, while this per-controller slice@@ -681,6 +694,7 @@ interface InFlightRemoteInvoke {}const inFlightRemoteInvokeResults = new Map<string, InFlightRemoteInvoke>();let inFlightRemoteInvokeBytes = 0;+const remoteListingFlights = new Map<string, InFlightRemoteInvoke>();interface QueuedRemoteInvokeResult {src: string;requestId: string;@@ -2430,6 +2444,12 @@ async function handleInvoke(}const invokeBytes = encodedByteLength(fingerprint);+ const listingKey = canCoalesceRemoteListing(payload)+ ? remoteListingFlightKey(src, payload)+ : null;+ const existingListing = listingKey ? remoteListingFlights.get(listingKey) : undefined;+ const joiningExisting = !!(existingListing && existingListing.linkEpoch === invokeLinkEpoch);+const controllerAdmission = remoteInvokeAdmissionState(src);const controllerAtLimit = (controllerAdmission.messages >= REMOTE_INVOKE_IN_FLIGHT_PER_CONTROLLER_LIMIT@@ -2462,6 +2482,39 @@ async function handleInvoke(return;}+ if (joiningExisting && existingListing) {+ const waiterEntry = {+ promise: existingListing.promise,+ bytes: invokeBytes,+ fingerprint,+ linkEpoch: invokeLinkEpoch,+ };+ inFlightRemoteInvokeResults.set(cacheKey, waiterEntry);+ inFlightRemoteInvokeBytes += invokeBytes;+ let joined: InvokeResultPayload;+ try {+ joined = normalizeInvokeResultForWire(await existingListing.promise);+ if ((remoteInvokeLinkEpoch.get(src) ?? 0) !== invokeLinkEpoch) return;+ } finally {+ if (inFlightRemoteInvokeResults.get(cacheKey) === waiterEntry) {+ inFlightRemoteInvokeResults.delete(cacheKey);+ inFlightRemoteInvokeBytes -= invokeBytes;+ }+ }+ if (!await sendAuthorizedInvokeResultSafe(+ client,+ src,+ requestId,+ joined,+ payload?.channel,+ payload?.args,+ fingerprint,+ )) {+ throw new DeviceLinkError('BACKPRESSURE', 'coalesced invoke-result could not be queued');+ }+ return;+ }+const releaseBusyLease = shouldAcquireRemoteInvokeBusyLease(src, payload)? acquireRemoteInvokeBusyLease(): () => undefined;@@ -2471,6 +2524,9 @@ async function handleInvoke(.catch((err): InvokeResultPayload => {const message = err instanceof Error ? err.message : String(err);log.error(`remote invoke escaped execution boundary from ${shortId(src)}: ${message}`);+ if (isDbWorkerOverloadedError(message)) {+ return { ok: false, error: { code: 'BACKPRESSURE', message } };+ }return {ok: false,error: {@@ -2492,6 +2548,7 @@ async function handleInvoke(};inFlightRemoteInvokeResults.set(cacheKey, inFlightEntry);inFlightRemoteInvokeBytes += invokeBytes;+ if (listingKey) remoteListingFlights.set(listingKey, inFlightEntry);let result: InvokeResultPayload;try {result = normalizeInvokeResultForWire(await resultPromise);@@ -2507,6 +2564,9 @@ async function handleInvoke(inFlightRemoteInvokeResults.delete(cacheKey);inFlightRemoteInvokeBytes -= invokeBytes;}+ if (listingKey && remoteListingFlights.get(listingKey) === inFlightEntry) {+ remoteListingFlights.delete(listingKey);+ }}// Fresh execution already includes the DB checks in runInvoke, within its// orphan deadline and busy lease. Only replayed replies need a new async check.@@ -2571,6 +2631,27 @@ function currentRemoteInvokeAdmissionFailure(src: string): InvokeResultPayload |return null;}+function isFreshSessionListInvoke(payload: InvokePayload): boolean {+ if (payload.channel !== 'local-db:sessions:list') return false;+ const options = payload.args?.[2];+ return !!(options && typeof options === 'object' && !Array.isArray(options)+ && (options as { fresh?: unknown }).fresh === true);+}++function canCoalesceRemoteListing(payload: InvokePayload | undefined): payload is InvokePayload {+ return !!payload+ && COALESCE_REMOTE_INVOKE_CHANNELS.has(payload.channel)+ && !isFreshSessionListInvoke(payload);+}++function remoteListingFlightKey(src: string, payload: InvokePayload): string {+ return `${src}\u0000${payload.channel}\u0000${JSON.stringify(payload.args ?? [])}`;+}++function isDbWorkerOverloadedError(message: string): boolean {+ return message.includes('db worker RPC queue overloaded');+}+function remoteInvokeAdmissionState(src: string): { messages: number; bytes: number } {const prefix = `${src}\u0000`;let messages = 0;@@ -3637,6 +3718,9 @@ export async function runInvoke(// 被控端 handler 的 throwIpcError `[CODE] message` 原样透传,// 控制端 renderer 继续用 extractIpcError 解码const message = err instanceof Error ? err.message : String(err);+ if (isDbWorkerOverloadedError(message)) {+ return { ok: false, error: { code: 'BACKPRESSURE', message } };+ }return { ok: false, error: { code: 'IPC_ERROR', message } };}}@@ -3716,6 +3800,7 @@ export const __testing = {completedRemoteInvokeResultBytes = 0;inFlightRemoteInvokeResults.clear();inFlightRemoteInvokeBytes = 0;+ remoteListingFlights.clear();remoteInvokeResultOutbox.clear();remoteInvokeResultOutboxBytes = 0;clearRemoteInvokeResultOutboxTimer();diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.tsindex 1399899b2e..dee0caa8b0 100644--- a/packages/device-link/src/__tests__/client.test.ts+++ b/packages/device-link/src/__tests__/client.test.ts@@ -8107,6 +8107,200 @@ describe('定时重发的单趟预算(TRANSPORT_RETRY_PASS_BUDGET)', () => {h.client.stop();}, 10_000);+ it('发送方向已 ready 时同 stream 重复 open 不再打回 awaiting-confirm', async () => {+ const h = makeHarness({+ timing: {+ pingIntervalMs: 60_000,+ transportRetryIntervalMs: 60_000,+ transportMaxRetryAttempts: 50,+ },+ });+ h.client.start();+ await tick();+ h.current().ack();++ const capabilities = [+ DEVICE_LINK_CAPABILITY_RELIABLE_TRANSPORT,+ DEVICE_LINK_CAPABILITY_RELIABLE_LINK_CONFIRM,+ DEVICE_LINK_CAPABILITY_TRANSPORT_TIMEOUT_CLOSE,+ ];+ const sendInboundOpen = async (id: string): Promise<void> => {+ const off = h.client.onFrame((env) => {+ if (env.kind !== 'link-open' || env.id !== id || !env.src) return;+ h.client.sendLinkAccept(env.src, env.id, {+ appVersion: '1',+ allowlistHash: 'hash',+ });+ });+ h.current().push({+ v: PROTOCOL_VERSION,+ kind: 'link-open',+ id,+ src: 'dev-b',+ payload: {+ controllerName: 'Remote',+ protocolVersion: 1,+ appVersion: '1',+ capabilities,+ transportStreamId: 'same-remote-stream',+ transportBaseSeq: 1,+ },+ });+ await tick();+ off();+ };+ const confirmInboundOpen = (id: string): void => {+ const accept = h.current().sent.filter((env) => (+ env.kind === 'link-accept' && env.id === id+ )).at(-1)!;+ const payload = accept.payload as { transportStreamId?: string };+ h.current().push({+ v: PROTOCOL_VERSION,+ kind: 'push',+ src: 'dev-b',+ payload: {+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,+ payload: {+ streamId: payload.transportStreamId,+ ackSeq: 0,+ linkRequestId: id,+ },+ },+ });+ };++ await sendInboundOpen('ready-open-1');+ confirmInboundOpen('ready-open-1');+ h.client.sendInvokeResult('dev-b', 'live-1', { ok: true, result: 1 });++ await sendInboundOpen('ready-open-2');+ const internals = h.client as unknown as {+ peerTransport: Map<string, { sendPhase: string }>;+ outboundRouteGenerationByPeer: Map<string, Map<string, unknown>>;+ };+ expect(internals.peerTransport.get('dev-b')!.sendPhase).toBe('ready');+ const routeSize = (): number => internals.outboundRouteGenerationByPeer.get('dev-b')?.size ?? 0;+ const afterFirstDup = routeSize();+ for (let index = 0; index < 30; index += 1) {+ await sendInboundOpen(`ready-open-dup-${index}`);+ }+ expect(internals.peerTransport.get('dev-b')!.sendPhase).toBe('ready');+ expect(routeSize()).toBe(afterFirstDup);++ h.client.sendInvokeResult('dev-b', 'live-2', { ok: true, result: 2 });+ const live2 = h.current().sent.filter((env) => (+ env.kind === 'invoke-result' && parseTransportPayload(env.payload)+ )).at(-1)!;+ expect(parseTransportPayload(live2.payload)?.meta).toMatchObject({ seq: expect.any(Number) });++ h.client.stop();+ }, 10_000);++ it('多 peer 拓扑:一个 peer 重复 open 不暂停发送,另一个 peer 的在途请求零感知', async () => {+ const h = makeHarness({+ timing: {+ pingIntervalMs: 60_000,+ transportRetryIntervalMs: 60_000,+ transportMaxRetryAttempts: 50,+ },+ });+ h.client.start();+ await tick();+ h.current().ack();++ const capabilities = [+ DEVICE_LINK_CAPABILITY_RELIABLE_TRANSPORT,+ DEVICE_LINK_CAPABILITY_RELIABLE_LINK_CONFIRM,+ DEVICE_LINK_CAPABILITY_TRANSPORT_TIMEOUT_CLOSE,+ ];+ const sendInboundOpen = async (src: string, streamId: string, id: string): Promise<void> => {+ const off = h.client.onFrame((env) => {+ if (env.kind !== 'link-open' || env.id !== id || env.src !== src) return;+ h.client.sendLinkAccept(env.src, env.id, {+ appVersion: '1',+ allowlistHash: 'hash',+ });+ });+ h.current().push({+ v: PROTOCOL_VERSION,+ kind: 'link-open',+ id,+ src,+ payload: {+ controllerName: src,+ protocolVersion: 1,+ appVersion: '1',+ capabilities,+ transportStreamId: streamId,+ transportBaseSeq: 1,+ },+ });+ await tick();+ off();+ };+ const confirmInboundOpen = (src: string, id: string): void => {+ const accept = h.current().sent.filter((env) => (+ env.kind === 'link-accept' && env.id === id && env.dst === src+ )).at(-1)!;+ const payload = accept.payload as { transportStreamId?: string };+ h.current().push({+ v: PROTOCOL_VERSION,+ kind: 'push',+ src,+ payload: {+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,+ payload: {+ streamId: payload.transportStreamId,+ ackSeq: 0,+ linkRequestId: id,+ },+ },+ });+ };++ await sendInboundOpen('dev-b', 'stream-b', 'b-open-1');+ confirmInboundOpen('dev-b', 'b-open-1');+ await sendInboundOpen('dev-c', 'stream-c', 'c-open-1');+ confirmInboundOpen('dev-c', 'c-open-1');++ h.client.sendInvokeResult('dev-c', 'c-live-1', { ok: true, result: 'c1' });+ const ws = h.current();+ const cReliable = () => ws.sent.filter((env) => (+ env.kind === 'invoke-result'+ && env.dst === 'dev-c'+ && parseTransportPayload(env.payload) !== null+ ));+ expect(cReliable()).toHaveLength(1);+ const cMeta = parseTransportPayload(cReliable()[0]!.payload)!.meta;++ await sendInboundOpen('dev-b', 'stream-b', 'b-open-2');+ await sendInboundOpen('dev-b', 'stream-b', 'b-open-3');++ const internals = h.client as unknown as {+ peerTransport: Map<string, { sendPhase: string }>;+ };+ expect(internals.peerTransport.get('dev-b')!.sendPhase).toBe('ready');+ expect(internals.peerTransport.get('dev-c')!.sendPhase).toBe('ready');++ h.client.sendInvokeResult('dev-c', 'c-live-2', { ok: true, result: 'c2' });+ expect(cReliable()).toHaveLength(2);++ ws.push({+ v: PROTOCOL_VERSION,+ kind: 'push',+ src: 'dev-c',+ payload: {+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,+ payload: { streamId: cMeta.streamId, ackSeq: 2 },+ },+ });+ const afterAck = h.client.getReliableSendQueueDepth('dev-c');+ expect(afterAck).toBe(0);+ expect(h.client.getReliableSendQueueDepth('dev-b')).toBe(0);++ h.client.stop();+ }, 10_000);+it('对端换 stream 视为真正恢复,按探测预算 replay', async () => {const h = makeHarness({timing: {diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.tsindex 57bde49381..4519b15b8b 100644--- a/packages/device-link/src/client.ts+++ b/packages/device-link/src/client.ts@@ -4054,6 +4054,17 @@ export class DeviceLinkClient {resume: ReliableResumePlan,): void {const previousConfirmation = peer.pendingLinkConfirmation;+ // 同 stream 重复 open:发送方向已经 ready 时绝不能再打回 awaiting-confirm,+ // 否则 ACK/重试被暂停,pending 只涨不消,对端超时后再 open,形成死循环。+ if (resume.duplicateOpen && this.isPeerSendReady(peer)) {+ // sendLinkAccept 已把这次 accept 记进 active 路由账本;确认分支才会+ // discard。这里保持 ready、不进 awaiting-confirm,但仍要结算该记录,+ // 否则每次重复 open 泄漏一条,满 1024 后后续 accept 全 BACKPRESSURE。+ this.settleOutboundRouteAttemptsForId(dst, requestId);+ if (peer.pending.size > 0) this.ensureRetryTimer(dst);+ this.logRecoverySend(dst, peer, 'link-replay', true);+ return;+ }if (previousConfirmation?.timer) {clearTimeout(previousConfirmation.timer);}