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): 修复手机连接的同步洪峰与拥塞恢复 (#4080)

Dash3fe2a5f19053
diff --git a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
index 0f8f1c48d4..0108513a9c 100644
--- a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
+++ b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
@@ -266,8 +266,9 @@ describe('session runtime control wiring', () => {
'async function syncLibraryReadonlyExtraDir(',
'let agentInputCoordinatorHolder',
);
- expect(syncLibrary).toContain('listVisibleActiveSessionIds()');
- expect(syncLibrary).toContain('targets.add(focused)');
+ expect(syncLibrary).toContain('listVisibleActiveSessionDirectoryGrants()');
+ expect(syncLibrary).toContain('libraryExtraDirSyncTargets(');
+ expect(syncLibrary).toContain('listActiveSessions()');
expect(syncLibrary).toContain('sessionIsRemote(sessionId)');
expect(syncLibrary).toContain('!remote && grantRoot && sessionId === focused ? grantRoot : null');
expect(syncLibrary).toContain("return 'superseded'");
@@ -275,6 +276,7 @@ describe('session runtime control wiring', () => {
expect(syncLibrary).toContain("throw new Error('library extraDirs not granted to focused session')");
expect(syncLibrary).toContain('if (!remote && nextRoot && sessionId === focused) throw error');
expect(syncLibrary).toContain('libraryExtraDirSyncChain.then(run, run)');
+ expect(syncLibrary).toContain('applied?.some(isLibraryExtraDirSlot)');
expect(syncLibrary).toMatch(
/await applyLibraryReadonlyExtraDir\(sessionId, nextRoot\);[\s\S]*if \(generation !== libraryExtraDirSyncGeneration\) return 'superseded'/,
);
diff --git a/apps/desktop/src/main/device-link/__tests__/dispatchMakerEventBatch.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchMakerEventBatch.test.ts
index 9ec9e92cdf..84b7fb6a93 100644
--- a/apps/desktop/src/main/device-link/__tests__/dispatchMakerEventBatch.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/dispatchMakerEventBatch.test.ts
@@ -136,6 +136,45 @@ afterEach(() => {
});
describe('[1] 能力协商', () => {
+ it('coalesces task patches even for legacy list subscribers and cancels offline peers', async () => {
+ const h = mkClient();
+ __testing.setActiveClient(h.client as never);
+ subscriptions.subscribe('legacy', ['*'], 'old client');
+ subscriptions.subscribe('mobile', ['sessions'], 'mobile');
+ for (let i = 0; i < 2026; i++) {
+ __testing.forwardPush('local-db:sessions:patched', { sessionId: 's1', patch: { title: String(i) } });
+ }
+ __testing.forwardPush('local-db:sessions:patched', { sessionId: 's1', patch: { extraDirs: [] } });
+ handleControllerOffline('mobile');
+ await vi.advanceTimersByTimeAsync(250);
+ expect(h.sent).toEqual([{ dst: 'legacy', channel: 'local-db:sessions:patched',
+ payload: { sessionId: 's1', patch: { title: '2025', extraDirs: [] } }, ownerStamp: undefined }]);
+ });
+
+ it('keeps engine switch and deletion barriers before subsequent events', async () => {
+ const h = mkClient();
+ __testing.setActiveClient(h.client as never);
+ subscriptions.subscribe('legacy', ['*'], 'old client');
+ __testing.forwardPush('local-db:sessions:patched', { sessionId: 's1', patch: { title: 'new' } });
+ __testing.forwardPush('local-db:sessions:patched', { sessionId: 's1', patch: { agentKind: 'codex' } });
+ __testing.forwardPush('maker:event', { sessionId: 's1', event: { type: 'text', data: { text: 'new engine' } } });
+ __testing.forwardPush('local-db:sessions:patched', { sessionId: 's1', patch: { status: 'deleted' } });
+ await vi.advanceTimersByTimeAsync(500);
+ expect(h.sent.map((item) => item.channel)).toEqual(['local-db:sessions:patched', 'maker:event', 'local-db:sessions:patched']);
+ expect(h.sent[0].payload).toEqual({ sessionId: 's1', patch: { title: 'new', agentKind: 'codex' } });
+ });
+
+ it('drops queued global metadata when legacy subscription narrows to one task', async () => {
+ const h = mkClient();
+ __testing.setActiveClient(h.client as never);
+ subscriptions.subscribe('peer', ['*'], 'peer');
+ __testing.forwardPush('local-db:sessions:patched', { sessionId: 'other', patch: { title: 'private' } });
+ subscriptions.subscribe('peer', ['session:s1'], 'peer');
+ subscriptions.unsubscribe('peer', ['*']);
+ await vi.advanceTimersByTimeAsync(500);
+ expect(h.sent).toEqual([]);
+ });
+
it('声明能力的控制端:窗口内多条事件合并成一帧批,不再每事件一帧', () => {
const h = mkClient();
__testing.setActiveClient(h.client as never);
@@ -816,6 +855,23 @@ describe('running session recovery on slow links', () => {
expect(h.sent).toHaveLength(0);
});
+ it('holds deltas and snapshot repair while a known peer is down, then repairs before resuming', () => {
+ const h = mkClient();
+ const canSendPush = vi.fn(() => false);
+ __testing.setActiveClient({ ...h.client, canSendPush } as never);
+ subscriptions.subscribe('phone', ['session:s1'], 'phone', capabilities);
+ setSessionTextSnapshotReader(() => snapshot);
+ __testing.forwardPush('maker:event', delta('missed'));
+ vi.advanceTimersByTime(4_000);
+ expect(h.sent).toHaveLength(0);
+ canSendPush.mockReturnValue(true);
+ vi.advanceTimersByTime(2_000);
+ expect(h.sent.map(p => p.channel)).toEqual([SESSION_SYNC_CHANNEL]);
+ __testing.forwardPush('maker:event', delta('after repair'));
+ vi.advanceTimersByTime(WINDOW_MS);
+ expect(h.sent.map(p => p.channel)).toEqual([SESSION_SYNC_CHANNEL, MAKER_EVENT_BATCH_CHANNEL]);
+ });
+
it('repairs text-only loss without repeatedly requesting a large unchanged history page', () => {
const h = mkClient();
h.client.getReliableSendQueueDepth.mockReturnValue(16);
diff --git a/apps/desktop/src/main/device-link/__tests__/pushFailureLog.test.ts b/apps/desktop/src/main/device-link/__tests__/pushFailureLog.test.ts
new file mode 100644
index 0000000000..a3d97a1ad2
--- /dev/null
+++ b/apps/desktop/src/main/device-link/__tests__/pushFailureLog.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it, vi } from 'vitest';
+import { createPushFailureLog } from '../pushFailureLog';
+
+describe('push failure aggregation', () => {
+ it('keeps exact failure counts with only an initial and summary log', async () => {
+ vi.useFakeTimers();
+ const emit = vi.fn();
+ const log = createPushFailureLog(emit, () => Date.now());
+ try {
+ for (let i = 0; i < 1990; i++) log.record('phone', 'local-db:sessions:patched', 'BACKPRESSURE');
+ expect(emit).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(emit).toHaveBeenCalledTimes(2);
+ expect(emit.mock.calls.map(([event]) => event.count)).toEqual([1, 1989]);
+ expect(emit.mock.calls[1][0].elapsedMs).toBe(5000);
+ } finally { log.flush(); vi.useRealTimers(); }
+ });
+
+ it('separates devices/channels and flushes counts at shutdown without a timer leak', () => {
+ vi.useFakeTimers();
+ const emit = vi.fn();
+ const log = createPushFailureLog(emit);
+ try {
+ log.record('a', 'maker:event', 'BACKPRESSURE');
+ log.record('a', 'maker:event', 'BACKPRESSURE');
+ log.record('b', 'maker:event', 'BACKPRESSURE');
+ log.record('a', 'maker:status-changed', 'NOT_CONNECTED');
+ log.flush();
+ expect(emit).toHaveBeenCalledTimes(4);
+ expect(vi.getTimerCount()).toBe(0);
+ } finally { log.flush(); vi.useRealTimers(); }
+ });
+});
diff --git a/apps/desktop/src/main/device-link/__tests__/sessionPatchStage.test.ts b/apps/desktop/src/main/device-link/__tests__/sessionPatchStage.test.ts
new file mode 100644
index 0000000000..82d7de7adc
--- /dev/null
+++ b/apps/desktop/src/main/device-link/__tests__/sessionPatchStage.test.ts
@@ -0,0 +1,71 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { DeviceLinkError } from '@cindy/device-link';
+import { SessionPatchStage, type SessionPatch } from '../sessionPatchStage';
+
+describe('session patch backpressure', () => {
+ const stages: SessionPatchStage[] = [];
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => { stages.splice(0).forEach((stage) => stage.dispose()); vi.useRealTimers(); });
+ function make(writable = () => true, send = vi.fn(async (_item: SessionPatch, _current: () => boolean) => {})) {
+ const stage = new SessionPatchStage(undefined, writable, send, vi.fn());
+ stages.push(stage);
+ return { stage, send };
+ }
+
+ it('merges fields and explicit nulls while retaining every task terminal state', async () => {
+ const { stage, send } = make();
+ for (let i = 0; i < 2026; i++) stage.enqueue({ sessionId: 'a', patch: { title: String(i) } });
+ stage.enqueue({ sessionId: 'a', patch: { model: null } });
+ stage.enqueue({ sessionId: 'b', patch: { status: 'deleted' } });
+ expect(send).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(250);
+ expect(send.mock.calls.map(([item]) => item)).toEqual([
+ { sessionId: 'a', patch: { title: '2025', model: null } },
+ { sessionId: 'b', patch: { status: 'deleted' } },
+ ]);
+ });
+
+ it('pauses a silent peer while another peer progresses, then paces its backlog', async () => {
+ let writable = false;
+ const slow = make(() => writable);
+ const fast = make();
+ for (let i = 0; i < 40; i++) slow.stage.enqueue({ sessionId: String(i), patch: { status: 'archived' } });
+ fast.stage.enqueue({ sessionId: 'healthy', patch: { title: 'latest' } });
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(slow.send).not.toHaveBeenCalled();
+ expect(fast.send).toHaveBeenCalledOnce();
+ writable = true;
+ await vi.advanceTimersByTimeAsync(250);
+ expect(slow.send).toHaveBeenCalledTimes(8);
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(slow.send).toHaveBeenCalledTimes(40);
+ });
+
+ it('retains a patch rejected by queue admission', async () => {
+ const { stage, send } = make();
+ send.mockRejectedValueOnce(new DeviceLinkError('BACKPRESSURE', 'full'));
+ stage.enqueue({ sessionId: 'a', patch: { status: 'deleted' } });
+ await vi.advanceTimersByTimeAsync(500);
+ expect(send).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not deliver an older authorized patch after a newer update or unsubscribe', async () => {
+ let release!: () => void;
+ const sent: SessionPatch[] = [];
+ const send = vi.fn(async (item: SessionPatch, current: () => boolean) => {
+ await new Promise<void>((resolve) => { release = resolve; });
+ if (current()) sent.push(item);
+ });
+ const { stage } = make(() => true, send);
+ stage.enqueue({ sessionId: 'a', patch: { title: 'old' } });
+ await vi.advanceTimersByTimeAsync(250);
+ stage.enqueue({ sessionId: 'a', patch: { title: 'new' } });
+ release();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(sent).toEqual([]);
+ stage.dispose();
+ release();
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(sent).toEqual([]);
+ });
+});
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 3370cfb660..03a18e0c41 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -88,6 +88,8 @@ import {
} from './broadcast-tap';
import * as broadcastTap from './broadcast-tap';
import { createOfflinePushQueue } from './offlinePushQueue';
+import { SessionPatchStage, type SessionPatch } from './sessionPatchStage';
+import { createPushFailureLog } from './pushFailureLog';
import * as subscriptions from './subscriptions';
import { LEGACY_TOPIC, type ActiveController } from './subscriptions';
import { MAKER_PUSH } from '../maker-ipc/channels.js';
@@ -102,6 +104,10 @@ import {
} from './remote-workdir-guard';
const log = createLogger('device-link-dispatch');
+const pushFailures = createPushFailureLog((summary) => log.warn('push delivery failures', summary));
+function reportPushFailure(dst: string, channel: string, error: unknown): void {
+ pushFailures.record(shortId(dst), channel, error instanceof DeviceLinkError ? error.code : 'UNKNOWN');
+}
/**
* 老版本 mobile 只认识 #527 之前已发布的 logo kind。新 mark 可由同版本客户端按
@@ -153,7 +159,7 @@ const botPushChecks = new Map<string, { tail: Promise<void>; bytes: number; coun
function sendBotCheckedPush(
dst: string, channel: string, payload: unknown, send: (payload: unknown) => void,
failed: (error: unknown) => void,
-): void {
+): void | Promise<void> {
if (!hasRemoteBotSessionLookup()) { send(payload); return; }
let size: number;
try { size = byteLength(JSON.stringify(payload)); } catch (error) { failed(error); return; }
@@ -174,6 +180,7 @@ function sendBotCheckedPush(
if (queue.count === 0 && botPushChecks.get(dst) === queue) botPushChecks.delete(dst);
});
botPushChecks.set(dst, queue);
+ return queue.tail;
}
/** 只排队可由 session snapshot 对账、且不携带权限终态的会话域事件。 */
@@ -965,7 +972,8 @@ function stageSessionSync(dst: string, sessionId: string, historyRequired = true
stage.sessions.delete(sid);
continue;
}
- if ((activeClient.getReliableSendQueueDepth?.(dst) ?? 0) >= MAKER_EVENT_WINDOW_SOFT_CAP) break;
+ if (activeClient.canSendPush?.(dst) === false
+ || (activeClient.getReliableSendQueueDepth?.(dst) ?? 0) >= MAKER_EVENT_WINDOW_SOFT_CAP) break;
// Enqueue older staged deltas before the captured snapshot, then later deltas.
// All three use the same per-peer DB authorization queue before wire delivery.
flushMakerEventBatchesForSession(dst, sid);
@@ -1287,7 +1295,8 @@ function flushMakerEventBatchSession(
}
if (
subscriptions.controllerSupports(dst, CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1)
- && (sessionSyncStages.get(dst)?.sessions.has(sessionId)
+ && (activeClient.canSendPush?.(dst) === false
+ || sessionSyncStages.get(dst)?.sessions.has(sessionId)
|| (activeClient.getReliableSendQueueDepth?.(dst) ?? 0) >= MAKER_EVENT_WINDOW_SOFT_CAP)
) {
// Once any part is skipped, subsequent deltas no longer have a valid
@@ -1388,6 +1397,51 @@ interface SessionActivityStage {
retryTimer: ReturnType<typeof setTimeout> | null;
}
const sessionActivityStages = new Map<string, SessionActivityStage>();
+const sessionPatchStages = new Map<string, SessionPatchStage>();
+
+function clearSessionPatchStage(dst: string): void {
+ sessionPatchStages.get(dst)?.dispose();
+ sessionPatchStages.delete(dst);
+}
+
+function stageSessionPatch(dst: string, payload: unknown, ownerStamp?: PushOwnerStamp): void {
+ const patch = payload as SessionPatch | null;
+ if (!patch || typeof patch.sessionId !== 'string' || !patch.sessionId
+ || !patch.patch || typeof patch.patch !== 'object' || Array.isArray(patch.patch)) return;
+ let stage = sessionPatchStages.get(dst);
+ if (stage && !makerEventBatchOwnerStampEquals(stage.ownerStamp, ownerStamp)) {
+ clearSessionPatchStage(dst);
+ stage = undefined;
+ }
+ if (!stage) {
+ const owner = broadcastTap.captureDataOwnerBroadcastScope();
+ stage = new SessionPatchStage(ownerStamp,
+ () => {
+ if (!broadcastTap.isDataOwnerBroadcastScopeCurrent(owner)
+ || !subscriptions.getControllersForTopic('sessions').includes(dst)) {
+ clearSessionPatchStage(dst);
+ return false;
+ }
+ return !!activeClient && activeClient.getStatus() === 'online'
+ && activeClient.canSendPush?.(dst) !== false
+ && activeClient.getReliableSendQueueDepth(dst) < SESSION_ACTIVITY_WINDOW_SOFT_CAP;
+ },
+ async (item, isCurrent) => {
+ let failure: unknown;
+ await sendBotCheckedPush(dst, 'local-db:sessions:patched', item, (projected) => {
+ if (!isCurrent() || !broadcastTap.isDataOwnerBroadcastScopeCurrent(owner)
+ || !subscriptions.getControllersForTopic('sessions').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);
+ }, (error) => { failure = error; });
+ if (failure) throw failure;
+ }, (error) => reportPushFailure(dst, 'local-db:sessions:patched', error));
+ sessionPatchStages.set(dst, stage);
+ }
+ stage.enqueue(patch);
+}
function sessionActivityKey(payload: unknown): string | null {
if (!payload || typeof payload !== 'object') return null;
@@ -1430,7 +1484,7 @@ function drainSessionActivityStage(dst: string, stage: SessionActivityStage): vo
// 收尾包会永久卡在内存里不再投递(远端列表行挂死在旧状态)。定时器成本
// 有界:每控制端至多一个 250ms 定时器,且控制端真正离线时
// handleControllerOffline 会清空暂存、终止重试。
- if (activeClient.getStatus() !== 'online') {
+ if (activeClient.getStatus() !== 'online' || activeClient.canSendPush?.(dst) === false) {
scheduleSessionActivityRetry(dst, stage);
return;
}
@@ -1489,7 +1543,9 @@ function clearSessionActivityStage(dst: string): void {
}
function clearAllSessionActivityStages(): void {
+ pushFailures.flush();
for (const dst of [...sessionActivityStages.keys()]) clearSessionActivityStage(dst);
+ for (const dst of [...sessionPatchStages.keys()]) clearSessionPatchStage(dst);
}
/**
@@ -1618,6 +1674,21 @@ function forwardPush(channel: string, payload: unknown, ownerStamp?: PushOwnerSt
stageSessionActivityPush(dst, targetPayload, ownerStamp);
continue;
}
+ if (channel === 'local-db:sessions:patched') {
+ const item = targetPayload as SessionPatch;
+ // Engine/lifecycle fields are barriers for following maker events. Only
+ // independent list metadata may wait; fold older metadata into a barrier.
+ if (item?.patch && Object.keys(item.patch).every((key) => key === 'title' || key === 'extraDirs')) {
+ stageSessionPatch(dst, targetPayload, ownerStamp);
+ } else {
+ const stage = sessionPatchStages.get(dst);
+ const older = makerEventBatchOwnerStampEquals(stage?.ownerStamp, ownerStamp)
+ ? stage?.take(item?.sessionId) : undefined;
+ sendPushBestEffort(dst, channel, older
+ ? { ...item, patch: { ...older.patch, ...item.patch } } : targetPayload, ownerStamp);
+ }
+ continue;
+ }
// agent 事件流是本条链路的帧数大头:对声明了微批能力的控制端合并成
// 「每窗口一帧」(见 stageMakerEventPush)。未声明能力的控制端照旧逐帧,
// 因此旧控制端零感知。sessionId 取自 topic 路由所用的同一字段,取不到时
@@ -1651,7 +1722,7 @@ function sendPushBestEffort(
): void {
sendBotCheckedPush(dst, channel, payload,
(projected) => sendPushBestEffortAuthorized(dst, channel, projected, ownerStamp),
- () => log.warn('remote Bot push authorization failed'));
+ (error) => reportPushFailure(dst, channel, error));
}
function sendPushBestEffortAuthorized(
@@ -1672,7 +1743,8 @@ function sendPushBestEffortAuthorized(
// They must obey the same missing-prefix boundary as ordinary deltas.
if (channel === 'maker:event' && sessionId
&& subscriptions.controllerSupports(dst, CONTROLLER_CAPABILITY_SESSION_TEXT_SNAPSHOT_V1)
- && (sessionSyncStages.get(dst)?.sessions.has(sessionId)
+ && (activeClient.canSendPush?.(dst) === false
+ || sessionSyncStages.get(dst)?.sessions.has(sessionId)
|| (activeClient.getReliableSendQueueDepth?.(dst) ?? 0) >= MAKER_EVENT_WINDOW_SOFT_CAP)) {
markForRecovery();
return;
@@ -1684,14 +1756,14 @@ function sendPushBestEffortAuthorized(
} catch (err) {
if (!isPayloadTooLargeError(err)) {
markForRecovery();
- log.warn(`forwardPush to ${shortId(dst)} failed (${channel}): ${String(err)}`);
+ reportPushFailure(dst, channel, err);
return;
}
const compactPayload = compactOversizedPushPayload(channel, payload);
if (!compactPayload) {
markForRecovery();
- log.warn(`forwardPush to ${shortId(dst)} failed (${channel}): ${String(err)}`);
+ reportPushFailure(dst, channel, err);
return;
}
@@ -1869,6 +1941,7 @@ function deactivateControllerState(
changed = subscriptions.getControllerIds().includes(deviceId) || changed;
clearReportedControllerName(deviceId);
clearSessionActivityStage(deviceId);
+ clearSessionPatchStage(deviceId);
clearSessionSyncStage(deviceId);
clearMakerEventBatchStage(deviceId);
cancelLinkAcceptRetry(deviceId);
@@ -3121,7 +3194,10 @@ function handleSubscriptionFrame(src: string, payload: InvokePayload): InvokeRes
} else {
subscriptions.unsubscribe(src, topics);
// 退订 sessions 后暂存里的活动快照不应再投递(含已排期的重试)。
- if (topics.includes('sessions')) clearSessionActivityStage(src);
+ if (topics.includes('sessions')) {
+ clearSessionActivityStage(src);
+ clearSessionPatchStage(src);
+ }
// 退订 session:<id> 后该会话的待发事件批同样不应再投递(控制端已不要这条流)。
for (const topic of topics) {
const sessionId = topic.startsWith('session:') ? topic.slice('session:'.length) : null;
diff --git a/apps/desktop/src/main/device-link/pushFailureLog.ts b/apps/desktop/src/main/device-link/pushFailureLog.ts
new file mode 100644
index 0000000000..60802d96ad
--- /dev/null
+++ b/apps/desktop/src/main/device-link/pushFailureLog.ts
@@ -0,0 +1,29 @@
+/** Aggregate repeated failures without retaining payloads, paths or error messages. */
+export function createPushFailureLog(emit: (summary: {
+ peer: string; channel: string; code: string; count: number; elapsedMs: number;
+}) => void, now = () => performance.now()) {
+ const pending = new Map<string, { peer: string; channel: string; code: string; count: number; started: number }>();
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ const flush = () => {
+ if (timer) clearTimeout(timer);
+ timer = null;
+ for (const item of pending.values()) {
+ if (item.count > 1) emit({ peer: item.peer, channel: item.channel, code: item.code,
+ count: item.count - 1, elapsedMs: Math.max(0, Math.round(now() - item.started)) });
+ }
+ pending.clear();
+ };
+ return {
+ record(peer: string, channel: string, code: string) {
+ const key = JSON.stringify([peer, channel, code]);
+ const existing = pending.get(key);
+ if (existing) existing.count++;
+ else {
+ pending.set(key, { peer, channel, code, count: 1, started: now() });
+ emit({ peer, channel, code, count: 1, elapsedMs: 0 });
+ }
+ if (!timer) timer = setTimeout(flush, 5000);
+ },
+ flush,
+ };
+}
diff --git a/apps/desktop/src/main/device-link/sessionPatchStage.ts b/apps/desktop/src/main/device-link/sessionPatchStage.ts
new file mode 100644
index 0000000000..f91c084525
--- /dev/null
+++ b/apps/desktop/src/main/device-link/sessionPatchStage.ts
@@ -0,0 +1,77 @@
+import { DeviceLinkError, type PushOwnerStamp } from '@cindy/device-link';
+
+export interface SessionPatch {
+ sessionId: string;
+ patch: Record<string, unknown>;
+}
+
+/** One latest field value per task; never evict another task's deletion/revocation. */
+export class SessionPatchStage {
+ private readonly pending = new Map<string, SessionPatch>();
+ private timer: ReturnType<typeof setTimeout> | null = null;
+ private draining = false;
+ private disposed = false;
+
+ constructor(
+ readonly ownerStamp: PushOwnerStamp | undefined,
+ private readonly writable: () => boolean,
+ private readonly send: (payload: SessionPatch, isCurrent: () => boolean) => Promise<void>,
+ private readonly failed: (error: unknown) => void,
+ ) {}
+
+ enqueue(payload: SessionPatch): void {
+ if (this.disposed) return;
+ const previous = this.pending.get(payload.sessionId);
+ this.pending.set(payload.sessionId, {
+ sessionId: payload.sessionId,
+ patch: { ...previous?.patch, ...payload.patch },
+ });
+ this.schedule();
+ }
+
+ take(sessionId: string): SessionPatch | undefined {
+ const item = this.pending.get(sessionId);
+ this.pending.delete(sessionId);
+ return item;
+ }
+
+ dispose(): void {
+ this.disposed = true;
+ if (this.timer) clearTimeout(this.timer);
+ this.timer = null;
+ this.pending.clear();
+ }
+
+ private schedule(): void {
+ if (this.disposed || this.timer || this.draining || this.pending.size === 0) return;
+ this.timer = setTimeout(() => {
+ this.timer = null;
+ void this.drain();
+ }, 250);
+ }
+
+ private async drain(): Promise<void> {
+ if (this.disposed || this.draining) return;
+ this.draining = true;
+ try {
+ // A large task list must not refill a newly recovered reliable window in one tick.
+ for (let count = 0; count < 8 && this.pending.size > 0; count++) {
+ if (this.disposed || !this.writable()) break;
+ const [key, item] = this.pending.entries().next().value!;
+ const isCurrent = () => !this.disposed && this.pending.get(key) === item;
+ try {
+ await this.send(item, isCurrent);
+ } catch (error) {
+ if (error instanceof DeviceLinkError
+ && ['BACKPRESSURE', 'NOT_CONNECTED', 'LINK_NOT_OPEN'].includes(error.code)) break;
+ this.failed(error);
+ }
+ // A newer patch may have arrived while authorization was awaiting SQLite.
+ if (isCurrent()) this.pending.delete(key);
+ }
+ } finally {
+ this.draining = false;
+ this.schedule();
+ }
+ }
+}
diff --git a/apps/desktop/src/main/maker-host/session-storage.ts b/apps/desktop/src/main/maker-host/session-storage.ts
index 61137ae566..e83a4abbe8 100644
--- a/apps/desktop/src/main/maker-host/session-storage.ts
+++ b/apps/desktop/src/main/maker-host/session-storage.ts
@@ -252,15 +252,15 @@ export async function readSessionWritableDirsFromDb(id: string): Promise<string[
}
/** 当前 owner 可见、未删除的桌面会话(含 plugin 入口)。review 不注入 library 槽。 */
-export async function listVisibleActiveSessionIds(): Promise<string[]> {
+export async function listVisibleActiveSessionDirectoryGrants(): Promise<Array<{ id: string; extraDirs: string | null }>> {
const db = getDbClient().drizzle;
const rows = await db
- .select({ id: sessions.id })
+ .select({ id: sessions.id, extraDirs: sessions.extraDirs })
.from(sessions)
.where(and(
inArray(sessions.source, DESKTOP_VISIBLE_SESSION_SOURCES),
eq(sessions.status, 'active'),
ne(sessions.source, 'review'),
));
- return rows.map((row) => row.id);
+ return rows;
}
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/libraryExtraDirSyncTargets.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/libraryExtraDirSyncTargets.test.ts
new file mode 100644
index 0000000000..72f9819917
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/libraryExtraDirSyncTargets.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from 'vitest';
+import { libraryExtraDirSyncTargets } from '../libraryExtraDirSyncTargets.js';
+
+describe('Library directory synchronization targets', () => {
+ it('includes live tasks omitted by the visible active DB query without waking dormant tasks', () => {
+ const rows = Array.from({ length: 2026 }, (_, i) => ({ id: `dormant-${i}`, extraDirs: '[]' }));
+ const live = new Set(['archived-live', 'deleted-live', 'hidden-live']);
+ expect([...libraryExtraDirSyncTargets([], live, null)]).toEqual([...live]);
+ expect([...libraryExtraDirSyncTargets(rows, live, 'focused')]).toEqual([...live, 'focused']);
+ });
+
+ it('does not rewrite 2026 dormant empty tasks on a focus report', () => {
+ const rows = Array.from({ length: 2026 }, (_, i) => ({ id: `task-${i}`, extraDirs: '[]' }));
+ expect([...libraryExtraDirSyncTargets(rows, new Set(), null)]).toEqual([]);
+ expect([...libraryExtraDirSyncTargets(rows, new Set(), 'task-10')]).toEqual(['task-10']);
+ });
+
+ it('keeps persisted old grants after restart and live runtimes that may need revocation', () => {
+ const rows = [
+ { id: 'old-focus', extraDirs: '["cindy-library:/old","/user"]' },
+ { id: 'live', extraDirs: '[]' },
+ { id: 'user-only', extraDirs: '["/user"]' },
+ { id: 'empty', extraDirs: null },
+ ];
+ expect([...libraryExtraDirSyncTargets(rows, new Set(['live']), 'new-focus')])
+ .toEqual(['old-focus', 'live', 'new-focus']);
+ });
+
+ it('does not let malformed legacy grants bypass normal cleanup', () => {
+ expect([...libraryExtraDirSyncTargets([{ id: 'legacy', extraDirs: '[' }], new Set(), null)])
+ .toEqual(['legacy']);
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/remoteDirectoryGrantUpdate.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/remoteDirectoryGrantUpdate.test.ts
index 81ec5868d5..cf3a847658 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/remoteDirectoryGrantUpdate.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/remoteDirectoryGrantUpdate.test.ts
@@ -39,6 +39,38 @@ function createSessionSerializer() {
}
describe('remote directory grant atomic update', () => {
+ it('revokes stale runtime Library access even when the persisted grant is already empty', async () => {
+ const state = createState();
+ state.runtime.extraDirs = ['cindy-library:/old'];
+ expect((await state.update('extraDirs', [])).changed).toBe(false);
+ expect(state.setExtraDirs).toHaveBeenCalledWith([]);
+ expect(state.runtime.extraDirs).toEqual([]);
+ expect(state.persist).not.toHaveBeenCalled();
+ });
+
+ it.each(['extraDirs', 'writableDirs'] as const)('does not rebroadcast identical %s, but restores rebuilt runtime grants', async (axis) => {
+ const state = createState(['/reference'], ['/output']);
+ state.runtime[axis] = [];
+ const result = await state.update(axis, [...state.db[axis]]);
+ expect(result.changed).toBe(false);
+ expect(state.runtime).toEqual(state.db);
+ expect(state.persist).not.toHaveBeenCalled();
+ });
+
+ it('does not write thousands of empty directory updates', async () => {
+ const state = createState();
+ for (let i = 0; i < 2026; i++) await state.update('extraDirs', []);
+ expect(state.persist).not.toHaveBeenCalled();
+ expect(state.setExtraDirs).toHaveBeenCalledTimes(2026);
+ });
+
+ it('still persists a conflict-filtered revocation', async () => {
+ const state = createState(['/shared'], ['/shared']);
+ expect((await state.update('extraDirs', ['/shared'])).changed).toBe(true);
+ expect(state.db.extraDirs).toEqual([]);
+ expect(state.persist).toHaveBeenCalledOnce();
+ });
+
it('accepts exact remote retention/revocation subsets and rejects additions', () => {
expect(isPersistedDirectoryGrantSubset([], ['/shared', '/output'])).toBe(true);
expect(isPersistedDirectoryGrantSubset(['/shared'], ['/shared', '/output'])).toBe(true);
diff --git a/apps/desktop/src/main/maker-ipc/libraryExtraDirSyncTargets.ts b/apps/desktop/src/main/maker-ipc/libraryExtraDirSyncTargets.ts
new file mode 100644
index 0000000000..996c40ff1d
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/libraryExtraDirSyncTargets.ts
@@ -0,0 +1,30 @@
+import { isLibraryExtraDirSlot } from './extraDirsValidator.js';
+
+/** Keep revocation/rebuilt runtimes, without rewriting every dormant task on focus. */
+export function libraryExtraDirSyncTargets(
+ rows: ReadonlyArray<{ id: string; extraDirs: string | null }>,
+ liveIds: ReadonlySet<string>,
+ focused: string | null,
+): Set<string> {
+ const targets = new Set<string>();
+ for (const row of rows) {
+ if (liveIds.has(row.id)) {
+ targets.add(row.id);
+ continue;
+ }
+ try {
+ const dirs: unknown = JSON.parse(row.extraDirs ?? '[]');
+ if (Array.isArray(dirs) && dirs.some((dir) => typeof dir === 'string' && isLibraryExtraDirSlot(dir))) {
+ targets.add(row.id);
+ }
+ } catch {
+ // Preserve normal validation for malformed legacy grant data.
+ targets.add(row.id);
+ }
+ }
+ // Runtime lifetime is independent of DB visibility/status. A live archived or
+ // hidden task must still revoke its old Library slot when focus changes.
+ for (const id of liveIds) targets.add(id);
+ if (focused) targets.add(focused);
+ return targets;
+}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index d25361cd96..c9b5c94c17 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -470,8 +470,9 @@ import {
readSessionExtraDirsFromDb,
readSessionWritableDirsFromDb,
readSessionWorkingDirFromDb,
- listVisibleActiveSessionIds,
+ listVisibleActiveSessionDirectoryGrants,
} from '../maker-host/session-storage.js';
+import { libraryExtraDirSyncTargets } from './libraryExtraDirSyncTargets.js';
import {
clearSessionPersistState,
consumeLastAssistantPersistId,
@@ -2967,7 +2968,7 @@ export function applyDirectoryGrants(
persist: (patch) => persistSessionFields(sessionId, patch),
terminate: () => maker.closeSession(sessionId),
});
- log.info(label, {
+ if (result.changed || result.rejectedCount > 0) log.info(label, {
sessionId,
requested: requestedDirs.length,
kept: result.dirs.length,
@@ -3025,10 +3026,11 @@ async function syncLibraryReadonlyExtraDir(
const grantRoot = libraryExtraDirSyncRoot;
const focused = getFocusedGhostSessionId();
if (generation !== libraryExtraDirSyncGeneration) return 'superseded';
- const visible = await listVisibleActiveSessionIds();
+ const visible = await listVisibleActiveSessionDirectoryGrants();
if (generation !== libraryExtraDirSyncGeneration) return 'superseded';
- const targets = new Set(visible);
- if (focused) targets.add(focused);
+ const targets = libraryExtraDirSyncTargets(
+ visible, new Set(getMaker().listActiveSessions().map((session) => session.id)), focused,
+ );
let granted = false;
for (const sessionId of targets) {
if (generation !== libraryExtraDirSyncGeneration) return 'superseded';
@@ -3036,8 +3038,8 @@ async function syncLibraryReadonlyExtraDir(
if (generation !== libraryExtraDirSyncGeneration) return 'superseded';
const nextRoot = !remote && grantRoot && sessionId === focused ? grantRoot : null;
try {
- await applyLibraryReadonlyExtraDir(sessionId, nextRoot);
- if (nextRoot) granted = true;
+ const applied = await applyLibraryReadonlyExtraDir(sessionId, nextRoot);
+ if (nextRoot && applied?.some(isLibraryExtraDirSlot)) granted = true;
} catch (error) {
log.warn('library extraDirs session sync failed', {
sessionId,
diff --git a/apps/desktop/src/main/maker-ipc/remoteDirectoryGrantUpdate.ts b/apps/desktop/src/main/maker-ipc/remoteDirectoryGrantUpdate.ts
index bafe3f8206..99e50f1eb6 100644
--- a/apps/desktop/src/main/maker-ipc/remoteDirectoryGrantUpdate.ts
+++ b/apps/desktop/src/main/maker-ipc/remoteDirectoryGrantUpdate.ts
@@ -18,6 +18,7 @@ export interface RemoteDirectoryGrantUpdateDeps {
export interface RemoteDirectoryGrantUpdateResult {
dirs: string[];
rejectedCount: number;
+ changed: boolean;
}
/** Remote executors have no native picker on the controller; only retain/revoke exact grants. */
@@ -49,6 +50,8 @@ export async function applyRemoteDirectoryGrantUpdate(
const previousDirs = axis === 'extraDirs' ? previousExtraDirs : previousWritableDirs;
const blockedDirs = axis === 'extraDirs' ? previousWritableDirs : previousExtraDirs;
const nextDirs = await deps.excludeConflicts(validation.valid, blockedDirs);
+ const changed = previousDirs.length !== nextDirs.length
+ || previousDirs.some((dir, index) => dir !== nextDirs[index]);
const applyRuntime = axis === 'extraDirs'
? (dirs: string[]) => session.setExtraDirs(dirs)
: (dirs: string[]) => session.setWritableDirs(dirs);
@@ -77,7 +80,9 @@ export async function applyRemoteDirectoryGrantUpdate(
}
try {
- await deps.persist(patch(nextDirs));
+ // A rebuilt runtime still needs the grants even when SQLite already has them.
+ // Only persistence/mirror broadcasts are redundant in that case.
+ if (changed) await deps.persist(patch(nextDirs));
} catch (persistenceError) {
const rollbackErrors: unknown[] = [];
try {
@@ -107,5 +112,6 @@ export async function applyRemoteDirectoryGrantUpdate(
return {
dirs: nextDirs,
rejectedCount: validation.rejected.length + validation.valid.length - nextDirs.length,
+ changed,
};
}
diff --git a/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.ts b/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.ts
index eb369c4118..b324bc51b1 100644
--- a/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.ts
+++ b/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.ts
@@ -125,7 +125,8 @@ describe('live stream interruption wiring', () => {
);
// 传的是 markHeldRemoteTopicsSubscribed 的返回值(仍被持有的那些),不是原始 toSend ——
// 中途被释放的 topic 不算订阅生效。
- expect(sendSubscribe).toMatch(/noteSessionLiveStreamsAcked\(\s*markHeldRemoteTopicsSubscribed\(/);
+ expect(sendSubscribe).toMatch(/const held = markHeldRemoteTopicsSubscribed\(remoteSubscribedTopicsRef\.current, registryRef\.current, deviceId, toSend\);\s*noteSessionLiveStreamsAcked\(held\);/);
+ expect(sendSubscribe).toContain("if (held.length > 0) record?.('subscription', 'applied', held.length)");
// scope 在 ensureOnline 等待期间变化时,已释放 topic 不能迟到发到主机;仍被其它 owner
// 持有的 topic 必须重新评估,不能和已释放 topic 一起饿死。
expect(sendSubscribe).toContain('.filter((topic) => registryRef.current.hasTopic(deviceId, topic))');
diff --git a/apps/mobile/src/__tests__/recoveryDiagnostics.test.ts b/apps/mobile/src/__tests__/recoveryDiagnostics.test.ts
new file mode 100644
index 0000000000..a12bb255c8
--- /dev/null
+++ b/apps/mobile/src/__tests__/recoveryDiagnostics.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it, vi } from 'vitest';
+import { createRecoveryDiagnostics, settleMeasuredSnapshot } from '../device-link/recoveryDiagnostics';
+
+describe('mobile recovery diagnostics', () => {
+ it('correlates peer phases from foreground without emitting device IDs or content', () => {
+ let now = 100;
+ const emit = vi.fn();
+ const diagnostics = createRecoveryDiagnostics(emit, () => 7, () => now);
+ diagnostics.foreground();
+ now = 200;
+ const a = diagnostics.capture('private-device-a', 7);
+ const b = diagnostics.capture('private-device-b', 7);
+ now = 600;
+ a('subscription', 'applied', 2);
+ now = 900;
+ b('history', 'failed');
+ expect(emit.mock.calls.map(([event]) => event)).toEqual([
+ { generation: 1, connection: 7, peer: 1, operation: 1, phase: 'subscription', outcome: 'applied', count: 2, elapsedMs: 400, foregroundElapsedMs: 500 },
+ { generation: 1, connection: 7, peer: 2, operation: 2, phase: 'history', outcome: 'failed', elapsedMs: 700, foregroundElapsedMs: 800 },
+ ]);
+ expect(JSON.stringify(emit.mock.calls)).not.toContain('private');
+ });
+
+ it('drops late observations from background, replaced connections and old foreground generations', () => {
+ let epoch = 1;
+ const emit = vi.fn();
+ const diagnostics = createRecoveryDiagnostics(emit, () => epoch, () => 0);
+ diagnostics.foreground();
+ const old = diagnostics.capture('device', 1);
+ diagnostics.background();
+ old('history', 'applied');
+ diagnostics.foreground();
+ old('history', 'applied');
+ const disconnected = diagnostics.capture('device', 1);
+ epoch++;
+ disconnected('history', 'applied');
+ expect(emit).not.toHaveBeenCalled();
+ });
+
+ it('reports success only after a snapshot is accepted by the store', async () => {
+ const report = vi.fn();
+ await settleMeasuredSnapshot(Promise.resolve('content'), () => false, report);
+ expect(report).toHaveBeenLastCalledWith('superseded');
+ await settleMeasuredSnapshot(Promise.resolve('content'), () => true, report);
+ expect(report).toHaveBeenLastCalledWith('applied');
+ const error = new Error('private server response');
+ expect(await settleMeasuredSnapshot(Promise.reject(error), () => true, report))
+ .toEqual({ status: 'rejected', reason: error });
+ expect(report).toHaveBeenLastCalledWith('failed');
+ expect(JSON.stringify(report.mock.calls)).not.toContain('private');
+ });
+});
diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
index b2be40cbe1..380b48f8ca 100644
--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts
+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
@@ -4982,6 +4982,21 @@ describe('maker:event 微批拆包(CONTROLLER_CAPABILITY_MAKER_EVENT_BATCH_V1)',
describe('任务消息内存治理', () => {
beforeEach(() => remoteSessionStore.clear());
+ it('补读结果区分已接受的相同窗口与失效代际或过旧窗口', () => {
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', { source: 'scheduler' })]);
+ const first = remoteSessionStore.enterSessionMessageDetail('s1');
+ const latest = [messageAt('latest', 's1', '2026-09-08T00:00:00.000Z')];
+ expect(remoteSessionStore.setLatestMessageWindow('s1', latest, { authority: first })).toBe(true);
+ expect(remoteSessionStore.setLatestMessageWindow('s1', latest, { authority: first })).toBe(true);
+ expect(remoteSessionStore.setLatestMessageWindow('s1', [
+ messageAt('old', 's1', '2026-09-07T00:00:00.000Z'),
+ ], { authority: first })).toBe(false);
+ remoteSessionStore.leaveSessionMessageDetail('s1', 'detail-blur', first);
+ remoteSessionStore.enterSessionMessageDetail('s1');
+ expect(remoteSessionStore.setLatestMessageWindow('s1', latest, { authority: first })).toBe(false);
+ expect(remoteSessionStore.getMessages('s1').map((row) => row.id)).toEqual(['latest']);
+ });
+
const manyMessages = (sessionId: string, count: number): RemoteMessage[] =>
Array.from({ length: count }, (_, index) => messageAt(
`${sessionId}-m-${index}`,
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index 14d4ddc2a7..0b659c40fc 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -1,5 +1,6 @@
import Constants from 'expo-constants';
import { createBackgroundConnection } from './backgroundConnection';
+import { createRecoveryDiagnostics, settleMeasuredSnapshot, type RecoveryPhase } from './recoveryDiagnostics';
import { confirmTrackedSubscription, SubscriptionAcknowledgements } from './subscriptionAcknowledgements';
import { AppState, Platform } from 'react-native';
import {
@@ -77,7 +78,6 @@ import {
import { isTransientRemoteError } from '@/device-link/remoteRetry';
import {
runSessionMessagesSnapshotSingleFlight,
- settleProgressiveSnapshot,
runSessionPendingInteractionsSnapshotSingleFlight,
runSessionProjectionSnapshotSingleFlight,
} from '@/device-link/sessionSnapshotSingleFlight';
@@ -185,6 +185,7 @@ export interface DeviceLinkContextValue {
}
const DeviceLinkContext = createContext<DeviceLinkContextValue | null>(null);
+const recoveryDiagnostics = new WeakMap<DeviceLinkClient, ReturnType<typeof createRecoveryDiagnostics>>();
/**
* 本控制端声明的端到端可选能力(link-open 与 subscribe 两处共用同一份,漏一处会让
@@ -429,7 +430,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
topics: readonly Topic[],
) => {
const releaseGeneration = backgroundReleaseGenerationRef.current;
- const startedAt = Date.now();
+ const record = recoveryDiagnostics.get(client)?.capture(deviceId, connectionEpochRef.current);
await confirmTrackedSubscription({
isCurrent: () => !backgroundReleaseInFlightRef.current
&& backgroundReleaseGenerationRef.current === releaseGeneration && clientRef.current === client,
@@ -447,10 +448,9 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
),
acknowledge: (toSend) => {
// 只有仍被持有、真正记进 ACK 表的 topic 才算订阅生效(中途被释放的那些不算)。
- noteSessionLiveStreamsAcked(
- markHeldRemoteTopicsSubscribed(remoteSubscribedTopicsRef.current, registryRef.current, deviceId, toSend),
- );
- console.debug('[device-link] recovery subscription acknowledged', { elapsedMs: Date.now() - startedAt });
+ const held = markHeldRemoteTopicsSubscribed(remoteSubscribedTopicsRef.current, registryRef.current, deviceId, toSend);
+ noteSessionLiveStreamsAcked(held);
+ if (held.length > 0) record?.('subscription', 'applied', held.length);
},
});
}, []);
@@ -800,6 +800,12 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
},
});
clientRef.current = client;
+ const diagnostics = createRecoveryDiagnostics(
+ (event) => mobileDeviceLinkLogger.info('recovery phase', event),
+ () => connectionEpochRef.current,
+ );
+ recoveryDiagnostics.set(client, diagnostics);
+ if (AppState.currentState === 'active') diagnostics.foreground();
const offIssue = client.onConnectionIssue(setConnectionIssue);
const offStatus = client.onStatusChange((next) => {
setStatus(next);
@@ -1114,6 +1120,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
});
const sub = AppState.addEventListener('change', (next) => {
if (next === 'active') {
+ diagnostics.foreground();
backgroundReleaseInFlightRef.current = false;
// 回前台立刻重连:绕开断线后遗留的指数退避计时器(可能 park 到 30s),
// 让"打开 App → 打开会话"路径快速恢复在线,而不是干等退避。
@@ -1125,6 +1132,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
void rehydrateWithClient(client);
}
if (next === 'background') {
+ diagnostics.background();
backgroundReleaseInFlightRef.current = true;
backgroundReleaseGenerationRef.current += 1;
// App 生命周期暂停全部恢复执行,但各 peer 状态仍彼此独立;回前台统一
@@ -1155,6 +1163,8 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
return () => {
disposed = true;
+ diagnostics.background();
+ recoveryDiagnostics.delete(client);
networkSubscription?.remove();
sub.remove();
backgroundConnection.dispose();
@@ -1403,6 +1413,9 @@ async function rebuildSessionSnapshot(
opts: DeviceLinkRehydrateSendOptions | undefined,
isCurrent: () => boolean,
): Promise<void> {
+ const record = recoveryDiagnostics.get(client)?.capture(deviceId, connectionEpoch);
+ const measured = <T,>(phase: RecoveryPhase, read: Promise<T>, apply: (value: T) => boolean) =>
+ settleMeasuredSnapshot(read, apply, (outcome) => record?.(phase, outcome));
// 这四个并发请求是同一轮补齐:一次路由抖动可能让它们同时等满超时,但这只
// 代表一个独立故障观测。共享显式 cohort,避免单轮 fan-out 直接凑满 3 次阈值。
const sendOpts: SendInvokeOptions = {
@@ -1426,7 +1439,7 @@ async function rebuildSessionSnapshot(
// 丢失的 maker:goal:status-changed push;model-pref / turn-cost 无对应查询通道,
// 暂不在补齐范围(需扩桌面端 invoke 白名单)。
const applyHistory = (value: RemoteMessage[]) => {
- if (!isCurrent()) return;
+ if (!isCurrent()) return false;
if (Array.isArray(value)) {
// moreBeyondWindow:这一页上沿之外服务端还有历史(满 80 条,或被 device-link 裁过行)。为真时
// store 不保留早于本页的缓存段 —— 断连期间漏收的 push 可能正落在两段之间,保留就在窗口里
@@ -1435,7 +1448,7 @@ async function rebuildSessionSnapshot(
moreBeyondWindow: hasMoreOlderMessages(value, RECONNECT_MESSAGE_WINDOW_LIMIT),
};
if (messageAuthorityAtRequestStart) {
- remoteSessionStore.setLatestMessageWindow(sessionId, value, {
+ return remoteSessionStore.setLatestMessageWindow(sessionId, value, {
...windowOptions,
authority: messageAuthorityAtRequestStart,
});
@@ -1450,36 +1463,42 @@ async function rebuildSessionSnapshot(
// enter / leave / forget / clear,生命周期 fence 就会失效,旧重连响应不得越过
// 新生命周期。Store 同时校验 regular retention 与物理设备归属,避免旧设备响应
// 写回新 shard。
- remoteSessionStore.setLatestMessageWindow(sessionId, value, windowOptions);
+ return remoteSessionStore.setLatestMessageWindow(sessionId, value, windowOptions);
}
}
+ return false;
};
const applyPending = (value: PendingInteraction[]) => {
- if (!isCurrent()) return;
+ if (!isCurrent()) return false;
if (Array.isArray(value)) {
remoteSessionStore.setPendingInteractions(sessionId, value, { finalizeStreaming: true });
+ return true;
}
+ return false;
};
const applyProjection = (value: InputProjection) => {
- if (!isCurrent()) return;
+ if (!isCurrent()) return false;
if (value) {
- remoteSessionStore.setInputProjectionIfCurrent(
+ return remoteSessionStore.setInputProjectionIfCurrent(
sessionId,
value,
projectionEpochAtRequestStart,
);
}
+ return false;
};
const applyGoal = (value: MobileGoalStatusPayload | null | undefined) => {
- if (!isCurrent()) return;
+ if (!isCurrent()) return false;
// undefined = 未拿到/未知(兼容形态的空返回),不能当作权威「无 goal」落库——
// 那会把在世的 goal 卡清掉直到下一条 push;只有显式 null 才代表确认无 goal。
if (value !== undefined) {
remoteSessionStore.setGoalStatus(sessionId, value);
+ return true;
}
+ return false;
};
const [history, pending, projection, goal] = await Promise.all([
- settleProgressiveSnapshot(runSessionMessagesSnapshotSingleFlight(
+ measured('history', runSessionMessagesSnapshotSingleFlight(
snapshotScope,
RECONNECT_MESSAGE_WINDOW_LIMIT,
messageAuthorityAtRequestStart
@@ -1497,7 +1516,7 @@ async function rebuildSessionSnapshot(
sendOpts,
),
), applyHistory),
- settleProgressiveSnapshot(runSessionPendingInteractionsSnapshotSingleFlight(
+ measured('pending', runSessionPendingInteractionsSnapshotSingleFlight(
snapshotScope,
pendingSnapshotAtRequestStart,
() => sendInvokeWithAccessHandling<PendingInteraction[]>(
@@ -1508,7 +1527,7 @@ async function rebuildSessionSnapshot(
sendOpts,
),
), applyPending),
- settleProgressiveSnapshot(runSessionProjectionSnapshotSingleFlight(
+ measured('projection', runSessionProjectionSnapshotSingleFlight(
snapshotScope,
projectionEpochAtRequestStart,
() => sendInvokeWithAccessHandling<InputProjection>(
@@ -1519,7 +1538,7 @@ async function rebuildSessionSnapshot(
sendOpts,
),
), applyProjection),
- settleProgressiveSnapshot(sendInvokeWithAccessHandling<MobileGoalStatusPayload | null | undefined>(
+ measured('goal', sendInvokeWithAccessHandling<MobileGoalStatusPayload | null | undefined>(
client,
deviceId,
'maker:goal:get-status',
diff --git a/apps/mobile/src/device-link/recoveryDiagnostics.ts b/apps/mobile/src/device-link/recoveryDiagnostics.ts
new file mode 100644
index 0000000000..fb164fac75
--- /dev/null
+++ b/apps/mobile/src/device-link/recoveryDiagnostics.ts
@@ -0,0 +1,61 @@
+export type RecoveryPhase = 'subscription' | 'history' | 'pending' | 'projection' | 'goal';
+export interface RecoveryDiagnostic {
+ generation: number;
+ connection: number;
+ peer: number;
+ operation: number;
+ phase: RecoveryPhase;
+ outcome: 'applied' | 'superseded' | 'failed';
+ elapsedMs: number;
+ foregroundElapsedMs: number;
+ count?: number;
+}
+
+export async function settleMeasuredSnapshot<T>(
+ read: Promise<T>, apply: (value: T) => boolean,
+ report: (outcome: RecoveryDiagnostic['outcome']) => void,
+): Promise<PromiseSettledResult<T>> {
+ try {
+ const value = await read;
+ report(apply(value) ? 'applied' : 'superseded');
+ return { status: 'fulfilled', value };
+ } catch (reason) {
+ report('failed');
+ return { status: 'rejected', reason };
+ }
+}
+
+/** Local numeric correlations only. Never emit topics, content or error messages. */
+export function createRecoveryDiagnostics(
+ emit: (event: RecoveryDiagnostic) => void,
+ currentConnection: () => number,
+ now = () => performance.now(),
+) {
+ let generation = 0;
+ let nextOperation = 0;
+ let foregroundAt: number | null = null;
+ const peers = new Map<string, number>();
+ return {
+ foreground() {
+ if (foregroundAt !== null) return;
+ generation++;
+ foregroundAt = now();
+ },
+ background() { foregroundAt = null; generation++; },
+ capture(deviceId: string, connection: number) {
+ const captured = generation;
+ const operation = ++nextOperation;
+ const startedAt = now();
+ if (!peers.has(deviceId)) peers.set(deviceId, peers.size + 1);
+ const peer = peers.get(deviceId)!;
+ return (phase: RecoveryPhase, outcome: RecoveryDiagnostic['outcome'], count?: number) => {
+ if (foregroundAt === null || captured !== generation || connection !== currentConnection()) return;
+ emit({ generation, connection, peer, operation, phase, outcome,
+ elapsedMs: Math.max(0, Math.round(now() - startedAt)),
+ foregroundElapsedMs: Math.max(0, Math.round(now() - foregroundAt)),
+ ...(count === undefined ? {} : { count }),
+ });
+ };
+ },
+ };
+}
diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.ts
index 45dfba018c..e6d9239766 100644
--- a/apps/mobile/src/session/remoteSessionStore.ts
+++ b/apps/mobile/src/session/remoteSessionStore.ts
@@ -3307,8 +3307,8 @@ export const remoteSessionStore = {
sessionId: string,
list: readonly RemoteMessage[],
options: SetLatestMessageWindowOptions = {},
- ): void {
- if (!messageWriteAllowed(sessionId, options.authority)) return;
+ ): boolean {
+ if (!messageWriteAllowed(sessionId, options.authority)) return false;
const textFlushed = flushPendingTextDelta(sessionId);
const latestWindow = normalizeWindowForRetention(sessionId, normalizeMessages(list));
const projectionSettled = settleInputProjectionFromMessages(sessionId, latestWindow);
@@ -3321,7 +3321,7 @@ export const remoteSessionStore = {
// while the persistence push is still in flight.
if (hasLiveAssistantMessage(sessionId)) {
if (textFlushed || projectionSettled) emit();
- return;
+ return false;
}
const preserved = existing.filter((item) => messageKey(item).startsWith('mobile-system-'));
const next = preserved.length > 0 ? preserved : [];
@@ -3336,7 +3336,7 @@ export const remoteSessionStore = {
} else if (textFlushed || projectionSettled) {
emit();
}
- return;
+ return true;
}
const latestOldestCreatedAt = latestWindow[0].createdAt;
@@ -3348,7 +3348,7 @@ export const remoteSessionStore = {
// retained newer rows, then trusting live pushes, would certify the gap.
// Rewind/clear invalidates coverage explicitly, so it does not use this path.
if (textFlushed || projectionSettled) emit();
- return;
+ return false;
}
// A triggering user row must be inserted before its live assistant reply is
// tied to the same host timestamp. Other authoritative tail rows keep the
@@ -3498,7 +3498,7 @@ export const remoteSessionStore = {
);
if (liveRowsReanchoredBeforeMerge || liveRowsReanchoredAfterMerge) bumpMessageVersion(sessionId);
if (textFlushed || liveRowsReanchoredBeforeMerge || liveRowsReanchoredAfterMerge) emit();
- return;
+ return true;
}
messages.set(sessionId, next);
if (reanchorAfterMerge) {
@@ -3516,6 +3516,7 @@ export const remoteSessionStore = {
applyMessageWriteRetention(sessionId);
bumpMessageVersion(sessionId);
emit();
+ return true;
},
markSessionMessagesSynced(sessionId: string, session: Pick<RemoteSession, '_count' | 'updatedAt'>): void {
diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.ts
index bcc86819bc..12148e04aa 100644
--- a/packages/device-link/src/__tests__/client.test.ts
+++ b/packages/device-link/src/__tests__/client.test.ts
@@ -5913,6 +5913,200 @@ describe('computeReconnectDelayMs(relay 拥塞冷却下限)', () => {
});
describe('DeviceLinkClient relay 拥塞断连(close 1013)', () => {
+ it('excludes idle and inbound-closed peers while admitting a new active target', async () => {
+ vi.useFakeTimers();
+ const h = makeHarness({ timing: {
+ pingIntervalMs: 600_000, congestionBackoffBaseMs: 1, congestionBackoffMaxMs: 1,
+ } });
+ try {
+ h.client.start();
+ await vi.advanceTimersByTimeAsync(0);
+ h.current().ack();
+ h.current().emit('close', 1013, 'inbound backpressure');
+ await vi.advanceTimersByTimeAsync(50);
+ h.current().ack();
+ for (let i = 0; i < 12; i++) {
+ const peer = `peer-${i}`;
+ const opened = establishInboundReliableLink(h, `stream-${peer}`, 1, peer);
+ await vi.advanceTimersByTimeAsync(0);
+ await opened;
+ if (i < 6) h.client.closeLink(peer, 'user', 'inbound');
+ }
+ const socket = h.current();
+ socket.sent.length = 0;
+ for (let i = 0; i < 8; i++) h.client.sendPush('peer-11', 'maker:event', { part: i });
+ expect(socket.sent).toHaveLength(8);
+ const last = parseTransportPayload(socket.sent.at(-1)!.payload)!.meta;
+ socket.push({ v: 1, kind: 'push', src: 'peer-11', payload: {
+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL, payload: { streamId: last.streamId, ackSeq: last.seq },
+ } });
+ await vi.advanceTimersByTimeAsync(250);
+ expect(h.client.getReliableSendQueueDepth('peer-11')).toBe(0);
+ // A previously idle target must be included before initial admission, even
+ // for an oversized response, without waiting for historical peers' turns.
+ const before = socket.sent.length;
+ h.client.sendInvokeResult('peer-10', 'large-active', { ok: true, result: 'x'.repeat(12 * 128 * 1024) });
+ expect(socket.sent.length - before).toBeGreaterThan(8);
+ expect(socket.sent.slice(before).every((env) => env.dst === 'peer-10')).toBe(true);
+ expect(h.client.getStatus()).toBe('online');
+ } finally { h.client.stop(); vi.useRealTimers(); }
+ });
+
+ it('queues paced sends despite a full socket and refunds failed retry capacity checks', async () => {
+ vi.useFakeTimers();
+ const debug = vi.fn();
+ const h = makeHarness({ logger: { debug, warn: vi.fn(), info: vi.fn(), error: vi.fn() }, timing: {
+ pingIntervalMs: 600_000, congestionBackoffBaseMs: 1, congestionBackoffMaxMs: 1,
+ } });
+ try {
+ h.client.start();
+ await vi.advanceTimersByTimeAsync(0);
+ h.current().ack();
+ h.current().emit('close', 1013, 'inbound backpressure');
+ await vi.advanceTimersByTimeAsync(50);
+ h.current().ack();
+ for (const peer of ['a', 'b']) {
+ const opened = establishInboundReliableLink(h, `stream-${peer}`, 1, peer);
+ await vi.advanceTimersByTimeAsync(0);
+ await opened;
+ }
+ const socket = h.current();
+ // Keep b genuinely active so a receives half of the shared window.
+ h.client.sendPush('b', 'maker:event', { pending: true });
+ socket.sent.length = 0;
+ for (let i = 0; i < 4; i++) h.client.sendPush('a', 'maker:event', { part: i });
+ expect(socket.sent).toHaveLength(4);
+ const last = parseTransportPayload(socket.sent.at(-1)!.payload)!.meta;
+ socket.bufferedAmount = MAX_TRANSPORT_WEBSOCKET_BUFFERED_BYTES;
+ expect(() => h.client.sendPush('a', 'maker:event', { part: 'queued' })).not.toThrow();
+ expect(() => h.client.sendInvokeResult('a', 'queued-result', { ok: true, result: 'ok' })).not.toThrow();
+ expect(h.client.getReliableSendQueueDepth('a')).toBe(6);
+ // A peer with remaining credit still checks capacity and preserves its old queue.
+ expect(() => h.client.sendInvokeResult('b', 'full', { ok: true, result: 'ok' })).toThrow();
+ expect(h.client.getReliableSendQueueDepth('b')).toBe(1);
+ debug.mockClear();
+ socket.push({ v: 1, kind: 'push', src: 'a', payload: {
+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL, payload: { streamId: last.streamId, ackSeq: last.seq },
+ } });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(debug.mock.calls.some(([message]) => String(message).includes('retry failed'))).toBe(false);
+ // The next window permits a retry but the full socket rejects it; no credit
+ // may remain charged when capacity subsequently recovers in the same window.
+ await vi.advanceTimersByTimeAsync(250);
+ expect(debug.mock.calls.some(([message]) => String(message).includes('retry failed'))).toBe(true);
+ socket.bufferedAmount = 0;
+ const before = socket.sent.length;
+ for (let i = 0; i < 4; i++) h.client.sendPush('a', 'maker:event', { afterCapacity: i });
+ expect(socket.sent.length - before).toBe(4);
+ await vi.advanceTimersByTimeAsync(250);
+ expect(socket.sent.some((env) => env.id === 'queued-result')).toBe(true);
+ expect(h.client.getStatus()).toBe('online');
+ } finally { h.client.stop(); vi.useRealTimers(); }
+ });
+
+ it.each([0, 2])('refunds a failed fragmented send after %s physical frames so another peer can reply', async (written) => {
+ vi.useFakeTimers();
+ const h = makeHarness({ timing: {
+ pingIntervalMs: 600_000, congestionBackoffBaseMs: 1, congestionBackoffMaxMs: 1,
+ } });
+ try {
+ h.client.start();
+ await vi.advanceTimersByTimeAsync(0);
+ h.current().ack();
+ h.current().emit('close', 1013, 'inbound backpressure');
+ await vi.advanceTimersByTimeAsync(50);
+ h.current().ack();
+ for (const peer of ['a', 'b']) {
+ const opened = establishInboundReliableLink(h, `stream-${peer}`, 1, peer);
+ await vi.advanceTimersByTimeAsync(0);
+ await opened;
+ }
+ const socket = h.current();
+ socket.sent.length = 0;
+ const send = socket.send.bind(socket);
+ let sent = 0;
+ socket.send = (data) => {
+ const env = JSON.parse(data) as Envelope;
+ if (env.dst === 'a' && parseTransportPayload(env.payload)) {
+ if (sent === written) throw new Error('socket raced');
+ sent++;
+ }
+ send(data);
+ };
+ const attempt = () => h.client.sendInvokeResult('a', 'large', { ok: true, result: 'x'.repeat(12 * 128 * 1024) });
+ if (written === 0) expect(attempt).toThrow('socket raced');
+ else expect(attempt).not.toThrow();
+ expect(sent).toBe(written);
+ socket.send = send;
+ h.client.sendInvokeResult('b', 'healthy', { ok: true, result: 'ok' });
+ expect(socket.sent.some((env) => env.dst === 'b' && env.kind === 'invoke-result')).toBe(true);
+ expect(h.client.getStatus()).toBe('online');
+ } finally { h.client.stop(); vi.useRealTimers(); }
+ });
+
+ it('paces all reliable sends after 1013 without starving another peer or control ACKs', async () => {
+ vi.useFakeTimers();
+ const h = makeHarness({ timing: {
+ pingIntervalMs: 600_000, congestionBackoffBaseMs: 1, congestionBackoffMaxMs: 1,
+ } });
+ try {
+ h.client.start();
+ await vi.advanceTimersByTimeAsync(0);
+ h.current().ack();
+ h.current().emit('close', 1013, 'inbound backpressure');
+ await vi.advanceTimersByTimeAsync(50);
+ h.current().ack();
+ for (const peer of ['a', 'b']) {
+ const opened = establishInboundReliableLink(h, `stream-${peer}`, 1, peer);
+ await vi.advanceTimersByTimeAsync(0);
+ await opened;
+ expect(h.client.canSendPush(peer)).toBe(true);
+ }
+ const socket = h.current();
+ socket.sent.length = 0;
+ for (let i = 0; i < 24; i++) h.client.sendPush('a', 'local-db:sessions:patched', { sessionId: String(i), patch: { title: 'new' } });
+ h.client.sendInvokeResult('b', 'healthy-result', { ok: true, result: 'ok' });
+ const reliable = () => socket.sent.filter((env) => parseTransportPayload(env.payload));
+ expect(reliable().length).toBeLessThanOrEqual(8);
+ // b became active after a used the idle window; it progresses next window.
+ await vi.advanceTimersByTimeAsync(250);
+ expect(reliable().some((env) => env.dst === 'b' && env.kind === 'invoke-result')).toBe(true);
+ socket.push(encodeReliableFrames({ v: 1, kind: 'push', src: 'a', payload: { channel: 'maker:event', payload: {} } }, 'stream-a', 1)[0]);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(socket.sent.some((env) => (env.payload as { channel?: string })?.channel === DEVICE_LINK_TRANSPORT_ACK_CHANNEL)).toBe(true);
+ for (let window = 0; window < 8; window++) {
+ for (const peer of ['a', 'b']) {
+ const last = reliable().filter((env) => env.dst === peer).at(-1);
+ if (!last) continue;
+ const { streamId, seq } = parseTransportPayload(last.payload)!.meta;
+ socket.push({ v: 1, kind: 'push', src: peer, payload: {
+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL, payload: { streamId, ackSeq: seq },
+ } });
+ }
+ await vi.advanceTimersByTimeAsync(250);
+ }
+ expect(new Set(reliable().filter((env) => env.dst === 'a').map((env) => parseTransportPayload(env.payload)!.meta.seq)).size).toBe(24);
+ expect(h.client.getStatus()).toBe('online');
+ expect(socket.closed).toBeNull();
+ } finally { h.client.stop(); vi.useRealTimers(); }
+ });
+
+ it('allows legacy listing pushes but pauses a known reliable peer after reset', async () => {
+ const h = makeHarness({ timing: { pingIntervalMs: 60_000 } });
+ h.client.start();
+ await tick();
+ h.current().ack();
+ try {
+ expect(h.client.canSendPush('listing-only')).toBe(true);
+ await establishInboundReliableLink(h, 'remote-stream');
+ expect(h.client.canSendPush('dev-b')).toBe(true);
+ h.current().push({ v: 1, kind: 'link-close', src: 'dev-b', payload: { reason: 'transport-timeout' } });
+ expect(h.client.canSendPush('dev-b')).toBe(false);
+ expect(h.client.canSendPush('listing-only')).toBe(true);
+ expect(h.client.getStatus()).toBe('online');
+ } finally { h.client.stop(); }
+ });
+
it('1013 计入拥塞连击,握手成功不清零,稳定在线满窗口才清零;普通断线不计入', async () => {
const h = makeHarness({
timing: {
diff --git a/packages/device-link/src/__tests__/congestionSendBudget.test.ts b/packages/device-link/src/__tests__/congestionSendBudget.test.ts
new file mode 100644
index 0000000000..82b594d7d0
--- /dev/null
+++ b/packages/device-link/src/__tests__/congestionSendBudget.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it } from 'vitest';
+import { CongestionSendBudget } from '../congestionSendBudget.js';
+
+describe('relay congestion frame budget', () => {
+ it('uses the same admission gate without charging previews', () => {
+ const budget = new CongestionSendBudget();
+ const peers = ['a', 'b'];
+ for (let i = 0; i < 20; i++) expect(budget.canTake('a', 4, peers, 0)).toBe(true);
+ expect(budget.take('a', 4, peers, 0)).toBe(true);
+ expect(budget.canTake('a', 1, peers, 0)).toBe(false);
+ expect(budget.take('a', 1, peers, 0)).toBe(false);
+ expect(budget.canTake('a', 4, peers, 250)).toBe(true);
+ expect(budget.take('a', 4, peers, 250)).toBe(true);
+ });
+
+ it('refunds unwritten frames without erasing the cost of a partial send', () => {
+ const budget = new CongestionSendBudget();
+ const peers = ['a', 'b'];
+ expect(budget.take('a', 32, peers, 0)).toBe(true);
+ budget.refund('a', 32);
+ expect(budget.take('a', 32, peers, 0)).toBe(true);
+ budget.refund('a', 30);
+ expect(budget.take('b', 4, peers, 0)).toBe(true);
+ expect(budget.take('a', 2, peers, 0)).toBe(true);
+ expect(budget.take('a', 1, peers, 0)).toBe(false);
+ expect(budget.take('b', 4, peers, 250)).toBe(true);
+ });
+
+ it('bounds combined peer bursts including repeated ACK-triggered passes', () => {
+ const budget = new CongestionSendBudget();
+ const peers = ['a', 'b'];
+ let sent = 0;
+ for (let i = 0; i < 100; i++) for (const peer of peers) sent += Number(budget.take(peer, 1, peers, 0));
+ expect(sent).toBe(8);
+ expect(budget.take('a', 1, peers, 249)).toBe(false);
+ expect(budget.take('a', 1, peers, 250)).toBe(true);
+ });
+
+ it('reserves progress for another peer even when the first monopolizes callbacks', () => {
+ const budget = new CongestionSendBudget();
+ const peers = ['slow', 'healthy'];
+ for (let i = 0; i < 100; i++) budget.take('slow', 1, peers, 0);
+ expect(budget.take('healthy', 1, peers, 0)).toBe(true);
+ });
+
+ it('rotates more peers than available slots and oversized atomic heads', () => {
+ const budget = new CongestionSendBudget();
+ const peers = Array.from({ length: 12 }, (_, i) => String(i));
+ const served = new Set<string>();
+ for (let window = 0; window < 60; window++) {
+ for (const peer of peers) if (budget.take(peer, 32, peers, window * 250)) served.add(peer);
+ }
+ expect(served.size).toBe(12);
+ });
+
+ it('does not starve a large response when small sends always run first', () => {
+ const budget = new CongestionSendBudget();
+ const peers = ['small', 'large'];
+ let largeSent = 0;
+ let smallSent = 0;
+ for (let window = 0; window < 40; window++) {
+ smallSent += Number(budget.take('small', 1, peers, window * 250));
+ if (budget.take('large', 32, peers, window * 250)) largeSent += 32;
+ }
+ expect(largeSent).toBeGreaterThan(0);
+ expect(smallSent).toBeGreaterThan(1);
+ expect(largeSent + smallSent).toBeLessThanOrEqual(40 * 8 + 32);
+ });
+
+ it('resets a spent window when the host stops', () => {
+ const budget = new CongestionSendBudget();
+ expect(budget.take('a', 8, ['a'], 0)).toBe(true);
+ expect(budget.take('a', 1, ['a'], 0)).toBe(false);
+ budget.reset();
+ expect(budget.take('a', 1, ['a'], 0)).toBe(true);
+ });
+});
diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.ts
index 910ac6b299..34f71ebf37 100644
--- a/packages/device-link/src/client.ts
+++ b/packages/device-link/src/client.ts
@@ -1,3 +1,4 @@
+import { CongestionSendBudget } from './congestionSendBudget.js';
import {
PROTOCOL_VERSION,
MAX_FRAME_BYTES,
@@ -623,6 +624,7 @@ export class DeviceLinkClient {
* 但不清本计数:立即重连可以,但若再被踢,冷却按更深一档生效。
*/
private congestionCloseStreak = 0;
+ private readonly congestionSendBudget = new CongestionSendBudget();
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private reconnectStableTimer: ReturnType<typeof setTimeout> | null = null;
private congestionStableTimer: ReturnType<typeof setTimeout> | null = null;
@@ -888,6 +890,7 @@ export class DeviceLinkClient {
this.handshakeTimeoutStreak = 0;
this.failAllPending(new DeviceLinkError('NOT_CONNECTED', 'client stopped'));
this.clearPeerTransport();
+ this.congestionSendBudget.reset();
this.pendingInboundLinkOffers.clear();
this.staleLinkNotifiedAt.clear();
this.resetLegacyInboundQueue();
@@ -924,6 +927,13 @@ export class DeviceLinkClient {
return !!peer && this.isPeerSendReady(peer) && peer.receiveReady;
}
+ /** Mirror admission only: listing-only/legacy peers need no bidirectional link. */
+ canSendPush(dst: string): boolean {
+ if (this.status !== 'online') return false;
+ const peer = this.peerTransport.get(dst);
+ return !peer || !peer.reliable || this.isPeerSendReady(peer);
+ }
+
/**
* 本机是否有仍在等该设备回包的**业务**请求(invoke,等 invoke-result)。
*
@@ -2700,7 +2710,10 @@ export class DeviceLinkClient {
// 真会发送时仍在驱逐/腾位之前预检(旧 P1:先驱逐再拒会清空镜像历史)。
const additionalFrames = Math.max(1, frames.length);
const willSendNow = this.isPeerSendReady(peer)
- && !this.shouldHoldRecoverySend(peer, additionalFrames);
+ && !this.shouldHoldRecoverySend(peer, additionalFrames)
+ && (this.congestionCloseStreak === 0 || this.congestionSendBudget.canTake(
+ env.dst, additionalFrames, this.getReadyReliablePeers(env.dst), this.monotonicNow(),
+ ));
if (willSendNow) {
this.assertWebSocketCapacity(this.measureReliableFrames(frames));
}
@@ -2778,9 +2791,15 @@ export class DeviceLinkClient {
pending.seq,
this.getTransportBaseSeq(peer),
);
- this.assertWebSocketCapacity(this.measureReliableFrames(frames));
+ const congestionBudget = this.congestionCloseStreak > 0 ? this.congestionSendBudget : null;
+ if (congestionBudget) {
+ if (!congestionBudget.take(
+ pending.envelope.dst!, frames.length, this.getReadyReliablePeers(pending.envelope.dst!), this.monotonicNow(),
+ )) return 0;
+ }
let sent = 0;
try {
+ this.assertWebSocketCapacity(this.measureReliableFrames(frames));
for (const frame of frames) {
// pending 可在 link down 时入队,并在后续 link generation 才首次上网;
// 路由错误必须归属每次真实物理发送,而不是逻辑消息的入队代次。
@@ -2795,6 +2814,7 @@ export class DeviceLinkClient {
err,
);
} finally {
+ congestionBudget?.refund(pending.envelope.dst!, frames.length - sent);
if (sent > 0) {
pending.sent = true;
pending.attempts++;
@@ -2804,6 +2824,14 @@ export class DeviceLinkClient {
return sent;
}
+ private getReadyReliablePeers(target: string): string[] {
+ return [...this.peerTransport.entries()]
+ // Include the initial target before enqueue; unacknowledged data still needs retries.
+ .filter(([id, peer]) => peer.reliable && this.isPeerSendReady(peer)
+ && (id === target || peer.pending.size > 0))
+ .map(([id]) => id);
+ }
+
private measureReliableFrames(frames: readonly Envelope[]): number {
return frames.reduce((sum, frame) => sum + byteLength(JSON.stringify(frame)), 0);
}
@@ -3587,7 +3615,9 @@ export class DeviceLinkClient {
if (peer.retryTimer) return;
peer.retryTimer = setInterval(
() => this.retryPending(dst, { ignoreInterval: false }),
- this.timing.transportRetryIntervalMs,
+ this.congestionCloseStreak > 0
+ ? Math.min(250, this.timing.transportRetryIntervalMs)
+ : this.timing.transportRetryIntervalMs,
);
}
@@ -3684,7 +3714,8 @@ export class DeviceLinkClient {
this.log.debug(`reliable transport retry failed for ${dst.slice(0, 8)}`, err);
break;
}
- framesSpent += Math.max(1, sentFrames);
+ if (sentFrames === 0) break; // Paced locally: no attempt/ACK failure has occurred.
+ framesSpent += sentFrames;
// 首趟恢复 replay(ignoreInterval)要把已在途的探针也记进预算,
// 否则 sent===true 的重放不占额度,新入队帧还能再灌一整批。
// 后续定时重发只给新帧记账,同一批探针可继续重传。
diff --git a/packages/device-link/src/congestionSendBudget.ts b/packages/device-link/src/congestionSendBudget.ts
new file mode 100644
index 0000000000..18d55d8e2c
--- /dev/null
+++ b/packages/device-link/src/congestionSendBudget.ts
@@ -0,0 +1,53 @@
+/** Shared physical-frame budget after relay 1013; control frames never enter this gate. */
+export class CongestionSendBudget {
+ private window = -1;
+ private spent = 0;
+ private turn = -1;
+ private readonly byPeer = new Map<string, number>();
+
+ reset(): void {
+ this.window = -1;
+ this.spent = 0;
+ this.turn = -1;
+ this.byPeer.clear();
+ }
+
+ /** Settle the synchronous send attempt: only frames actually written cost credit. */
+ refund(peer: string, unsentFrames: number): void {
+ this.spent = Math.max(0, this.spent - unsentFrames);
+ this.byPeer.set(peer, Math.max(0, (this.byPeer.get(peer) ?? 0) - unsentFrames));
+ }
+
+ take(peer: string, frames: number, peers: readonly string[], now: number): boolean {
+ if (!this.canTake(peer, frames, peers, now)) return false;
+ this.spent += frames;
+ this.byPeer.set(peer, (this.byPeer.get(peer) ?? 0) + frames);
+ return true;
+ }
+
+ /** Check admission without reserving credit; take uses exactly the same gate. */
+ canTake(peer: string, frames: number, peers: readonly string[], now: number): boolean {
+ const window = Math.floor(now / 250);
+ if (window !== this.window) {
+ this.spent = this.window >= 0 && window > this.window
+ ? Math.max(0, this.spent - 8 * (window - this.window)) : 0;
+ if (this.spent < 8) this.turn++;
+ this.window = window;
+ this.byPeer.clear();
+ }
+ const index = peers.indexOf(peer);
+ const count = Math.max(1, peers.length);
+ // Rotate turns when there are more peers than slots, including oversized heads.
+ const offset = (Math.max(0, index) - this.turn % count + count) % count;
+ if (offset >= 8) return false;
+ const share = Math.max(1, Math.floor(8 / Math.min(8, count)));
+ const used = this.byPeer.get(peer) ?? 0;
+ // A logical message's chunks are atomic. Let an oversized head occupy one turn,
+ // even if a small peer ran first. Charge its overflow to future windows and
+ // rotate only when credit returns (wall-clock rotation can starve whole peers).
+ if (frames > share) {
+ if (offset !== 0 || used !== 0 || this.spent >= 8) return false;
+ } else if (this.spent + frames > 8 || used + frames > share) return false;
+ return true;
+ }
+}