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): 为请求回包保留状态推送窗口
Dashcf2279d40825
diff --git a/apps/desktop/src/main/device-link/__tests__/dispatchMakerEventBatch.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchMakerEventBatch.test.tsindex 714bce72ea..88b747e377 100644--- a/apps/desktop/src/main/device-link/__tests__/dispatchMakerEventBatch.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/dispatchMakerEventBatch.test.ts@@ -12,6 +12,12 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import {DeviceLinkError,+ DeviceLinkClient,+ DEVICE_LINK_CAPABILITY_RELIABLE_TRANSPORT,+ DEVICE_LINK_TRANSPORT_ACK_CHANNEL,+ parseTransportPayload,+ type Envelope,+ type WsLike,DEVICE_LINK_CAPABILITY_COMPACT_MESSAGE_HISTORY_V1,CONTROLLER_CAPABILITY_MAKER_EVENT_BATCH_V1,CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1,@@ -136,6 +142,122 @@ afterEach(() => {vi.useRealTimers();});+// Real transport regression: the previous client stub always reported depth zero,+// hiding both the 32-vs-16 window mismatch and authorization's async admission gap.+// Unit tier: no sockets or wall-clock waits; forwardPush drives production dispatch.+class StatePushSocket implements WsLike {+ sent: Envelope[] = [];+ bufferedAmount = 0;+ private handlers = new Map<string, Array<(...args: unknown[]) => void>>();+ on(event: string, callback: (...args: never[]) => void): void {+ this.handlers.set(event, [...(this.handlers.get(event) ?? []), callback as (...args: unknown[]) => void]);+ }+ send(data: string): void { this.sent.push(JSON.parse(data)); }+ close(): void { this.emit('close', 1000); }+ emit(event: string, ...args: unknown[]): void {+ for (const callback of this.handlers.get(event) ?? []) callback(...args);+ }+ push(frame: Envelope): void { this.emit('message', { toString: () => JSON.stringify(frame) }); }+ acknowledge(dst: string): void {+ const tail = this.sent.filter(frame => frame.dst === dst && parseTransportPayload(frame.payload)).at(-1);+ if (!tail) return;+ const { meta } = parseTransportPayload(tail.payload)!;+ this.push({ v: 1, kind: 'push', src: dst, payload: {+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL, payload: { streamId: meta.streamId, ackSeq: meta.seq },+ } });+ }+}++it.each(['sync', 'async'] as const)('reserves real transport slots for replies during %s-authorized activity replay', async (authorization) => {+ const socket = new StatePushSocket();+ const client = new DeviceLinkClient({+ getWsUrl: () => 'ws://fixture', getToken: async () => 'fixture',+ getHello: () => ({ deviceName: 'host', platform: 'darwin', appVersion: '1', remoteControlEnabled: true, busy: false }),+ createWebSocket: () => socket,+ });+ try {+ client.start();+ await vi.advanceTimersByTimeAsync(0);+ socket.emit('open');+ socket.push({ v: 1, kind: 'hello-ack', payload: { serverProtocolVersion: 1, deviceId: 'host', userId: 'fixture' } });+ client.onFrame(frame => {+ if (frame.kind === 'link-open' && frame.src && frame.id) client.sendLinkAccept(frame.src, frame.id, { appVersion: '1', allowlistHash: 'fixture' });+ });+ for (const dst of ['phone', 'desktop']) {+ socket.push({ v: 1, kind: 'link-open', src: dst, id: `open-${dst}`, payload: {+ controllerName: dst, protocolVersion: 1, appVersion: '1',+ capabilities: [DEVICE_LINK_CAPABILITY_RELIABLE_TRANSPORT], transportStreamId: `${dst}-stream`, transportBaseSeq: 1,+ } });+ subscriptions.subscribe(dst, ['sessions'], dst);+ }+ __testing.setActiveClient(client);+ if (authorization === 'async') setRemoteBotSessionLookup(async () => 'visible');+ for (let i = 0; i < 48; i++) __testing.forwardPush(SESSION_ACTIVITY_CHANNEL, { sessionId: `s${i}`, phase: 'working' });+ await vi.advanceTimersByTimeAsync(0);+ client.sendInvokeResult('phone', 'subscription-response', { ok: true, result: { ok: true } });+ expect(socket.sent.some(frame => frame.id === 'subscription-response')).toBe(true);+ // Phone stops ACKing; the second peer must still drain, without a relay reset.+ __testing.forwardPush(SESSION_ACTIVITY_CHANNEL, { sessionId: 's47', phase: 'completed' });+ for (let i = 0; i < 8; i++) {+ socket.acknowledge('desktop');+ await vi.advanceTimersByTimeAsync(250);+ }+ const activities = (dst: string) => [...new Map(socket.sent.filter(frame => frame.dst === dst)+ .map(frame => parseTransportPayload(frame.payload))+ .filter(transport => transport !== null)+ .map(transport => [transport.meta.seq, JSON.parse(transport.data)] as const)).values()]+ .filter(body => body?.channel === SESSION_ACTIVITY_CHANNEL)+ .map(body => body!.payload as { sessionId: string; phase: string });+ expect(activities('desktop')).toHaveLength(48);+ expect(activities('desktop').at(-1)).toEqual({ sessionId: 's47', phase: 'completed' });+ expect(activities('phone').length).toBeLessThan(16);+ for (let i = 0; i < 8; i++) {+ socket.acknowledge('phone');+ await vi.advanceTimersByTimeAsync(250);+ }+ expect(activities('phone')).toHaveLength(48);+ expect(activities('phone').at(-1)).toEqual({ sessionId: 's47', phase: 'completed' });+ expect(client.getStatus()).toBe('online');+ } finally { client.stop(); }+});++it.each([SESSION_ACTIVITY_CHANNEL, 'local-db:sessions:patched'])('rechecks %s capacity after authorization and retains the newer final value', async (channel) => {+ const h = mkClient();+ __testing.setActiveClient(h.client as never);+ subscriptions.subscribe('phone', ['sessions']);+ let release!: () => void;+ const pending = new Promise<void>(resolve => { release = resolve; });+ setRemoteBotSessionLookup(async () => { await pending; return 'visible'; });+ const payload = (value: string) => channel === SESSION_ACTIVITY_CHANNEL+ ? { sessionId: 's1', phase: value } : { sessionId: 's1', patch: { title: value } };+ __testing.forwardPush(channel, payload('working'));+ await vi.advanceTimersByTimeAsync(250);+ // Other traffic consumes capacity while SQLite authorization is in flight.+ h.client.getReliableSendQueueDepth.mockReturnValue(8);+ release();+ await vi.advanceTimersByTimeAsync(0);+ expect(h.sent).toEqual([]);+ __testing.forwardPush(channel, payload('completed'));+ h.client.getReliableSendQueueDepth.mockReturnValue(0);+ await vi.advanceTimersByTimeAsync(500);+ expect(h.sent.map(push => push.payload)).toEqual([payload('completed')]);+});++it.each(['superseded', 'offline', 'hidden'] as const)('discards %s activity while authorization is pending', async (outcome) => {+ const h = mkClient();+ __testing.setActiveClient(h.client as never);+ subscriptions.subscribe('phone', ['sessions']);+ let release!: () => void;+ const pending = new Promise<void>(resolve => { release = resolve; });+ setRemoteBotSessionLookup(async () => { await pending; return outcome === 'hidden' ? 'hidden' : 'visible'; });+ __testing.forwardPush(SESSION_ACTIVITY_CHANNEL, { sessionId: 's1', phase: 'working' });+ if (outcome === 'offline') handleControllerOffline('phone');+ else __testing.forwardPush(SESSION_ACTIVITY_CHANNEL, { sessionId: 's1', phase: 'completed' });+ release();+ await vi.advanceTimersByTimeAsync(1_000);+ expect(h.sent.map(push => push.payload)).toEqual(outcome === 'superseded' ? [{ sessionId: 's1', phase: 'completed' }] : []);+});+describe('[1] 能力协商', () => {it('keeps SDK done off the list subscription while retaining full detail events', async () => {const h = mkClient();@@ -943,14 +1065,17 @@ describe('running session recovery on slow links', () => {let finish!: () => void;const pending = new Promise<void>((resolve) => { finish = resolve; });setRemoteBotSessionLookup(async () => { await pending; return 'visible'; });- subscriptions.subscribe('phone', ['sessions']);+ subscriptions.subscribe('phone', ['sessions', 'session:busy']);+ for (let index = 0; index < 64; index++) {+ __testing.forwardPush('maker:status-changed', { sessionId: 'busy', status: 'running' });+ }for (let index = 0; index < 65; index++) {__testing.forwardPush(SESSION_ACTIVITY_CHANNEL, { sessionId: `s${index}`, phase: 'completed' });}expect(h.sent).toHaveLength(0);finish();await vi.advanceTimersByTimeAsync(1_000);- expect(h.sent).toHaveLength(65);+ expect(h.sent.filter(push => push.channel === SESSION_ACTIVITY_CHANNEL)).toHaveLength(65);expect(h.sent.at(-1)?.payload).toEqual({ sessionId: 's64', phase: 'completed' });});diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.tsindex 69879beea2..e5ab6f73e0 100644--- a/apps/desktop/src/main/device-link/dispatch.ts+++ b/apps/desktop/src/main/device-link/dispatch.ts@@ -55,6 +55,7 @@ import {ACTION_INVOKE_TIMEOUTS_MS,resolveRemoteInvokeTimeoutMs,MAX_FRAME_BYTES,+ MAX_TRANSPORT_REASSEMBLIES,PROTOCOL_VERSION,REMOTE_INVOKE_ALLOWLIST,REMOTE_REVIEW_EXTERNAL_INPUT_CHANNELS,@@ -1214,7 +1215,7 @@ function notifySessionsSubscribed(controllerDeviceId: string): void {// ─── 会话活动出站整流(latest-wins 键控暂存) ────────────────────────────//// sessions:activity 是纯状态镜像:同一会话只有**最新值**有意义。把每个事件帧-// 直接塞进 per-peer 可靠传输窗口(64 槽单 FIFO)会在 replay/爆发时占满窗口,+// 直接塞进 per-peer 可靠传输窗口会在 replay/爆发时占满窗口,// 把 subscribe 的 invoke-result(控制端判定被控端存活的唯一凭据)挤到饿死——// v0.1.26 线上:一毫秒 76 帧 replay → 回包排不进窗口 → 手机 15s 超时重订阅 →// 每次重订阅再触发一轮 replay,拥塞自放大。这里按 (控制端, sessionId) 键控暂存,@@ -1223,7 +1224,20 @@ function notifySessionsSubscribed(controllerDeviceId: string): void {const SESSION_ACTIVITY_STAGE_MAX_KEYS = 512;const SESSION_ACTIVITY_DRAIN_RETRY_MS = 250;/** 可靠窗口软上限:活动镜像最多占半窗,剩余留给 invoke-result 与其它推送。 */-const SESSION_ACTIVITY_WINDOW_SOFT_CAP = 32;+const SESSION_ACTIVITY_WINDOW_SOFT_CAP = Math.floor(MAX_TRANSPORT_REASSEMBLIES / 2);++function canSendSessionState(dst: string): boolean {+ return !!activeClient && activeClient.getStatus() === 'online'+ && activeClient.canSendPush?.(dst) !== false+ && activeClient.getReliableSendQueueDepth(dst) < SESSION_ACTIVITY_WINDOW_SOFT_CAP;+}++/** Authorization can yield while another channel fills the same peer's window. */+function sendSessionState(dst: string, channel: string, payload: unknown, ownerStamp?: PushOwnerStamp): void {+ if (!canSendSessionState(dst)) throw new DeviceLinkError('BACKPRESSURE', 'peer state window full');+ if (ownerStamp === undefined) activeClient!.sendPush(dst, channel, payload);+ else activeClient!.sendPush(dst, channel, payload, ownerStamp);+}/*** `maker:event` 微批(per-(控制端, sessionId) 累积,与 activity staging 同骨架但@@ -1801,6 +1815,7 @@ interface SessionActivityStage {/** sessionId → 最新 payload + source owner;Map 插入序即更新序。 */queue: Map<string, { payload: unknown; ownerStamp?: PushOwnerStamp }>;retryTimer: ReturnType<typeof setTimeout> | null;+ draining: boolean;}const sessionActivityStages = new Map<string, SessionActivityStage>();const sessionPatchStages = new Map<string, SessionPatchStage>();@@ -1829,19 +1844,14 @@ function stageSessionPatch(dst: string, payload: unknown, ownerStamp?: PushOwnerclearSessionPatchStage(dst);return false;}- return !!activeClient && activeClient.getStatus() === 'online'- && activeClient.canSendPush?.(dst) !== false- && activeClient.getReliableSendQueueDepth(dst) < SESSION_ACTIVITY_WINDOW_SOFT_CAP;+ return canSendSessionState(dst);},async (item, isCurrent) => {let failure: unknown;await sendBotCheckedPush(dst, 'local-db:sessions:patched', item, (projected) => {if (!isCurrent() || !broadcastTap.isDataOwnerBroadcastScopeCurrent(owner)|| !subscriptions.getControllersForTopic(subscriptionTopic).includes(dst)) return;- if (!activeClient || activeClient.canSendPush?.(dst) === false) {- throw new DeviceLinkError('NOT_CONNECTED', 'peer mirror paused');- }- activeClient.sendPush(dst, 'local-db:sessions:patched', projected, ownerStamp);+ sendSessionState(dst, 'local-db:sessions:patched', projected, ownerStamp);}, (error) => { failure = error; });if (failure) throw failure;}, (error) => reportPushFailure(dst, 'local-db:sessions:patched', error));@@ -1867,7 +1877,7 @@ function stageSessionActivityPush(if (!key) return;let stage = sessionActivityStages.get(dst);if (!stage) {- stage = { queue: new Map(), retryTimer: null };+ stage = { queue: new Map(), retryTimer: null, draining: false };sessionActivityStages.set(dst, stage);}stage.queue.delete(key);@@ -1880,61 +1890,62 @@ function stageSessionActivityPush(drainSessionActivityStage(dst, stage);}-function drainSessionActivityStage(dst: string, stage: SessionActivityStage): void {- if (stage.retryTimer) {- clearTimeout(stage.retryTimer);- stage.retryTimer = null;- }- if (!activeClient) return;- // relay 离线时保持退避重试(不清暂存):若只等下一个活动事件/重订阅触发,- // 短暂 relay 闪断(控制端未察觉、不会重订阅)+ 无后续活动的场景下,暂存的- // 收尾包会永久卡在内存里不再投递(远端列表行挂死在旧状态)。定时器成本- // 有界:每控制端至多一个 250ms 定时器,且控制端真正离线时- // handleControllerOffline 会清空暂存、终止重试。- if (activeClient.getStatus() !== 'online' || activeClient.canSendPush?.(dst) === false) {- scheduleSessionActivityRetry(dst, stage);- return;- }- while (stage.queue.size > 0) {- if (activeClient.getReliableSendQueueDepth(dst) >= SESSION_ACTIVITY_WINDOW_SOFT_CAP) {+async function drainSessionActivityStage(dst: string, stage: SessionActivityStage): Promise<void> {+ if (stage.draining || sessionActivityStages.get(dst) !== stage) return;+ stage.draining = true;+ try {+ if (stage.retryTimer) {+ clearTimeout(stage.retryTimer);+ stage.retryTimer = null;+ }+ if (!activeClient) return;+ // relay 离线时保持退避重试(不清暂存):若只等下一个活动事件/重订阅触发,+ // 短暂 relay 闪断(控制端未察觉、不会重订阅)+ 无后续活动的场景下,暂存的+ // 收尾包会永久卡在内存里不再投递(远端列表行挂死在旧状态)。定时器成本+ // 有界:每控制端至多一个 250ms 定时器,且控制端真正离线时+ // handleControllerOffline 会清空暂存、终止重试。+ if (activeClient.getStatus() !== 'online' || activeClient.canSendPush?.(dst) === false) {scheduleSessionActivityRetry(dst, stage);return;}- const next = stage.queue.entries().next().value as- [string, { payload: unknown; ownerStamp?: PushOwnerStamp }]- | undefined;- if (!next) return;- const [key, item] = next;- if (isSharedTaskPeer(dst) && !subscriptions.getControllersForTopic(`session:${key}`).includes(dst)) {- stage.queue.delete(key);- continue;- }- try {- let backpressured = false;- sendBotCheckedPush(dst, SESSION_ACTIVITY_CHANNEL, item.payload, (projected) => {- if (item.ownerStamp === undefined) activeClient?.sendPush(dst, SESSION_ACTIVITY_CHANNEL, projected);- else activeClient?.sendPush(dst, SESSION_ACTIVITY_CHANNEL, projected, item.ownerStamp);- }, (error) => {- if (error instanceof DeviceLinkError && error.code === 'BACKPRESSURE' && sessionActivityStages.get(dst) === stage) {- backpressured = true;- if (!stage.queue.has(key)) stage.queue.set(key, item);- scheduleSessionActivityRetry(dst, stage);- }- });- // Synchronous queue admission failure must retain the staged update too.- if (backpressured) return;- stage.queue.delete(key);- } catch (err) {- if (err instanceof DeviceLinkError && err.code === 'BACKPRESSURE') {+ while (stage.queue.size > 0 && sessionActivityStages.get(dst) === stage) {+ if (!canSendSessionState(dst)) {scheduleSessionActivityRetry(dst, stage);return;}- // 其它错误(LINK_NOT_OPEN / PAYLOAD_TOO_LARGE 等)沿 best-effort 语义丢弃该条,- // 不让一条坏帧堵死整个暂存队列。- stage.queue.delete(key);- log.warn(`session activity push dropped for ${shortId(dst)}: ${String(err)}`);+ const next = stage.queue.entries().next().value as+ [string, { payload: unknown; ownerStamp?: PushOwnerStamp }]+ | undefined;+ if (!next) return;+ const [key, item] = next;+ if (isSharedTaskPeer(dst) && !subscriptions.getControllersForTopic(`session:${key}`).includes(dst)) {+ stage.queue.delete(key);+ continue;+ }+ try {+ let failure: unknown;+ const pending = sendBotCheckedPush(dst, SESSION_ACTIVITY_CHANNEL, item.payload, (projected) => {+ if (sessionActivityStages.get(dst) !== stage || stage.queue.get(key) !== item) return;+ sendSessionState(dst, SESSION_ACTIVITY_CHANNEL, projected, item.ownerStamp);+ }, (error) => { failure = error; });+ // Keep the latest value in the stage while authorization is pending, rather+ // than admitting the entire replay to the separate authorization queue.+ if (pending) await pending;+ if (sessionActivityStages.get(dst) !== stage) return;+ if (failure) throw failure;+ if (stage.queue.get(key) === item) stage.queue.delete(key);+ } catch (err) {+ if (err instanceof DeviceLinkError && err.code === 'BACKPRESSURE') {+ scheduleSessionActivityRetry(dst, stage);+ return;+ }+ // 其它错误(LINK_NOT_OPEN / PAYLOAD_TOO_LARGE 等)沿 best-effort 语义丢弃该条,+ // 不让一条坏帧堵死整个暂存队列。+ if (stage.queue.get(key) === item) stage.queue.delete(key);+ log.warn(`session activity push dropped for ${shortId(dst)}: ${String(err)}`);+ }}- }+ } finally { stage.draining = false; }}function scheduleSessionActivityRetry(dst: string, stage: SessionActivityStage): void {