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): 减少手机恢复重复同步和误报中断 (#3326)

Chris Zhang111939cf346b
diff --git a/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts
index 2ec4983472..c8e9fe1e29 100644
--- a/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/dispatchWeakNetwork.test.ts
@@ -55,6 +55,7 @@ import * as subscriptions from '../subscriptions';
function mkClient(
over: Partial<{
getConnectionEpoch: ReturnType<typeof vi.fn>;
+ getPeerLinkGeneration: ReturnType<typeof vi.fn>;
getStatus: ReturnType<typeof vi.fn>;
sendInvokeResult: ReturnType<typeof vi.fn>;
sendLinkAccept: ReturnType<typeof vi.fn>;
@@ -62,6 +63,7 @@ function mkClient(
) {
return {
getConnectionEpoch: over.getConnectionEpoch ?? vi.fn(() => 1),
+ getPeerLinkGeneration: over.getPeerLinkGeneration ?? vi.fn(() => 1),
getStatus: over.getStatus ?? vi.fn(() => 'online'),
sendInvokeResult: over.sendInvokeResult ?? vi.fn(),
sendLinkAccept: over.sendLinkAccept ?? vi.fn(),
@@ -727,6 +729,7 @@ describe('[6] active controller 生命周期与故障半径', () => {
deviceId: 'ctrl-a',
state: 'offline',
connectionEpoch: 1,
+ linkGeneration: 1,
});
expect(__testing.getActiveControllers().map((controller) => controller.deviceId)).toEqual([
'ctrl-a',
@@ -736,6 +739,38 @@ describe('[6] active controller 生命周期与故障半径', () => {
deviceId: 'ctrl-a',
state: 'offline',
connectionEpoch: 2,
+ linkGeneration: 1,
+ });
+ expect(__testing.getActiveControllers()).toEqual([]);
+ });
+
+ it('同一 connection 内旧 link 的 offline 事件不能清掉重新打开后的 controller', () => {
+ let linkGeneration = 1;
+ const client = mkClient({
+ getConnectionEpoch: vi.fn(() => 1),
+ getPeerLinkGeneration: vi.fn(() => linkGeneration),
+ });
+ __testing.setActiveClient(client as never);
+
+ __testing.handleLinkOpen(client as never, 'ctrl-a', 'open-old', undefined);
+ linkGeneration = 2;
+ __testing.handleLinkOpen(client as never, 'ctrl-a', 'open-new', undefined);
+
+ handleControllerOffline('ctrl-a', {
+ deviceId: 'ctrl-a',
+ state: 'offline',
+ connectionEpoch: 1,
+ linkGeneration: 1,
+ });
+ expect(__testing.getActiveControllers().map((controller) => controller.deviceId)).toEqual([
+ 'ctrl-a',
+ ]);
+
+ handleControllerOffline('ctrl-a', {
+ deviceId: 'ctrl-a',
+ state: 'offline',
+ connectionEpoch: 1,
+ linkGeneration: 2,
});
expect(__testing.getActiveControllers()).toEqual([]);
});
diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.ts
index 91a51229d0..9f81733854 100644
--- a/apps/desktop/src/main/device-link/dispatch.ts
+++ b/apps/desktop/src/main/device-link/dispatch.ts
@@ -564,6 +564,8 @@ const acceptedLinkControllers = new Set<string>();
* DEVICE_OFFLINE 事件带 generation,旧 socket 的迟到事实不能清掉新链路。
*/
const controllerConnectionEpochByDevice = new Map<string, number>();
+/** 同一 relay connection 内最近一次成功接受的 controller link 代次。 */
+const controllerLinkGenerationByDevice = new Map<string, number>();
/**
* relay presence 按 server 盖章的 deviceId 提供设备数据库展示名。它比控制端在
* link-open / subscribe 里自报的主机名更权威,用于让被控提示与设备列表一致。
@@ -621,6 +623,13 @@ function readConnectionEpoch(client: DeviceLinkClient): number | undefined {
function markControllerLinkActive(client: DeviceLinkClient, deviceId: string): void {
const epoch = readConnectionEpoch(client);
if (epoch !== undefined) controllerConnectionEpochByDevice.set(deviceId, epoch);
+ const candidate = client as DeviceLinkClient & {
+ getPeerLinkGeneration?: (peerDeviceId: string) => number;
+ };
+ const linkGeneration = candidate.getPeerLinkGeneration?.(deviceId);
+ if (linkGeneration !== undefined) {
+ controllerLinkGenerationByDevice.set(deviceId, linkGeneration);
+ }
}
/**
@@ -1540,6 +1549,7 @@ export function dropAllControllers(
topicSubscriptionControllers.clear();
acceptedLinkControllers.clear();
controllerConnectionEpochByDevice.clear();
+ controllerLinkGenerationByDevice.clear();
reportedControllerNameByDevice.clear();
offlinePushQueue.clear();
clearAllSessionActivityStages();
@@ -1551,21 +1561,34 @@ export function dropAllControllers(
function deactivateControllerState(
deviceId: string,
observedConnectionEpoch?: number,
+ observedLinkGeneration?: number,
): boolean {
const activeEpoch = controllerConnectionEpochByDevice.get(deviceId);
+ const activeLinkGeneration = controllerLinkGenerationByDevice.get(deviceId);
if (
observedConnectionEpoch !== undefined
&& activeEpoch !== undefined
- && observedConnectionEpoch < activeEpoch
+ && (
+ observedConnectionEpoch < activeEpoch
+ || (
+ observedConnectionEpoch === activeEpoch
+ && observedLinkGeneration !== undefined
+ && activeLinkGeneration !== undefined
+ && observedLinkGeneration < activeLinkGeneration
+ )
+ )
) {
log.debug(
- `ignoring stale controller offline event for ${shortId(deviceId)} (event=${observedConnectionEpoch}, active=${activeEpoch})`,
+ `ignoring stale controller offline event for ${shortId(deviceId)}`
+ + ` (connection=${observedConnectionEpoch}/${activeEpoch}`
+ + ` link=${observedLinkGeneration ?? 'unknown'}/${activeLinkGeneration ?? 'unknown'})`,
);
return false;
}
let changed = false;
changed = acceptedLinkControllers.delete(deviceId) || changed;
changed = controllerConnectionEpochByDevice.delete(deviceId) || changed;
+ changed = controllerLinkGenerationByDevice.delete(deviceId) || changed;
changed = reportedControllerNameByDevice.has(deviceId) || changed;
changed = subscriptions.getControllerIds().includes(deviceId) || changed;
clearReportedControllerName(deviceId);
@@ -1586,8 +1609,13 @@ export function deactivateController(
deviceId: string,
reason: string,
observedConnectionEpoch?: number,
+ observedLinkGeneration?: number,
): boolean {
- const changed = deactivateControllerState(deviceId, observedConnectionEpoch);
+ const changed = deactivateControllerState(
+ deviceId,
+ observedConnectionEpoch,
+ observedLinkGeneration,
+ );
if (changed) {
log.info(`controller ${shortId(deviceId)} deactivated (${reason})`);
syncForwarding();
@@ -1602,6 +1630,7 @@ export function deactivateAllControllers(reason: string): void {
...topicSubscriptionControllers,
...acceptedLinkControllers,
...controllerConnectionEpochByDevice.keys(),
+ ...controllerLinkGenerationByDevice.keys(),
...reportedControllerNameByDevice.keys(),
]);
let changed = false;
@@ -1623,6 +1652,7 @@ export function handleControllerOffline(
deviceId,
routeChange ? 'relay-device-offline' : 'presence-offline',
routeChange?.connectionEpoch,
+ routeChange?.linkGeneration,
);
}
@@ -3063,6 +3093,7 @@ export const __testing = {
topicSubscriptionControllers.clear();
acceptedLinkControllers.clear();
controllerConnectionEpochByDevice.clear();
+ controllerLinkGenerationByDevice.clear();
controllerDisplayNameByDevice.clear();
reportedControllerNameByDevice.clear();
onSessionsSubscribed = null;
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index 7a8dce78b7..564c472446 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -88,7 +88,19 @@ import {
} from '@/device-link/remoteStatus';
import { agentAuthGateHint, agentAuthGateVerdict } from '@/session/agentAuthGate';
import { isTransientRemoteError, withTransientRemoteRetry } from '@/device-link/remoteRetry';
-import { useRemoteSyncCoordinator, type RemoteSyncRun } from '@/device-link/remoteSyncTask';
+import {
+ createRemoteSyncReopenCoordinator,
+ useRemoteSyncCoordinator,
+ type RemoteSyncRun,
+} from '@/device-link/remoteSyncTask';
+import {
+ runConnectionScopedSessionMetadataRead,
+ runIndependentSnapshotReads,
+ runSessionMessagesSnapshotSingleFlight,
+ runSessionPendingInteractionsSnapshotSingleFlight,
+ runSessionProjectionSnapshotSingleFlight,
+} from '@/device-link/sessionSnapshotSingleFlight';
+import { createTransientTopicSubscriptionCoordinator } from '@/device-link/transientTopicSubscription';
import { useMobileMakerTransport } from '@/device-link/useMobileMakerTransport';
import { createMobileMakerTransport } from '@/device-link/mobileMakerTransport';
import { startFocusedTopicSubscription } from '@/device-link/focusedTopicSubscription';
@@ -939,6 +951,7 @@ export default function SessionScreen() {
getPresenceAvailability,
invoke,
openLink,
+ reopenLink,
status,
subscribe,
unsubscribe,
@@ -1582,8 +1595,25 @@ export default function SessionScreen() {
// lastSyncedAt 不会归零,不能用来判断「当前会话本次连接已同步」。epoch 经 ref 读取,
// 避免把 connectionEpoch 加进 syncSession deps 引发额外整窗重拉。
const [readAckSyncedKey, setReadAckSyncedKey] = useState<string | null>(null);
+ // interrupted 只依赖 getSession 的权威时间戳;兄弟快照失败不能把这道门永久关住。
+ // 已读回执仍继续使用上面的整窗门槛,避免消息未同步就提前清 attention。
+ const [sessionMetadataSyncedKey, setSessionMetadataSyncedKey] = useState<string | null>(null);
const readAckEpochRef = useRef(connectionEpoch);
readAckEpochRef.current = connectionEpoch;
+ // 后台订阅重试不能越过任务/设备/连接代切换,也不能在页面卸载后把已清理的 owner
+ // 重新登记回来。render 阶段先发布最新 identity;旧 effect 的 cleanup 只清自己。
+ const sessionSubscriptionIdentity = JSON.stringify([deviceId, sessionId, connectionEpoch]);
+ const sessionSubscriptionIdentityRef = useRef<string | null>(sessionSubscriptionIdentity);
+ sessionSubscriptionIdentityRef.current = sessionSubscriptionIdentity;
+ useEffect(() => () => {
+ if (sessionSubscriptionIdentityRef.current === sessionSubscriptionIdentity) {
+ sessionSubscriptionIdentityRef.current = null;
+ }
+ }, [sessionSubscriptionIdentity]);
+ const sessionsSubscriptionCoordinatorRef = useRef<ReturnType<
+ typeof createTransientTopicSubscriptionCoordinator
+ > | null>(null);
+ sessionsSubscriptionCoordinatorRef.current ??= createTransientTopicSubscriptionCoordinator();
// 门槛代号:每次「作废门槛」(原地切 session / liveAttention 上升沿)都递增。
// sync 尾部只有代号与自己启动时一致才允许落 key——否则 A→B→A 场景下,visit-1
// 的在途旧 load 会在重置之后用**相同的** `${sessionId}:${connectionEpoch}` 把门槛
@@ -1598,6 +1628,7 @@ export default function SessionScreen() {
if (prevReadAckSessionId !== sessionId) {
setPrevReadAckSessionId(sessionId);
setReadAckSyncedKey(null);
+ setSessionMetadataSyncedKey(null);
readAckGateGenRef.current += 1;
}
// 远程媒体取件队列:屏实例级缓存 + 同 url 去重 + 并发上限(每次取件都让桌面端
@@ -3637,9 +3668,33 @@ export default function SessionScreen() {
// 旧连接代的 in-flight load 若在尾部读 ref 的最新值,会把旧窗口数据标成新代已同步,
// 抢在排队的 resync 之前放行回执。开始时捕获则旧 load 落的是旧代 key,门槛不放行。
const readAckEpochAtStart = readAckEpochRef.current;
+ const subscriptionIdentityAtStart = JSON.stringify([
+ deviceId,
+ sessionId,
+ readAckEpochAtStart,
+ ]);
+ const subscriptionRetryIsStale = () => (
+ syncRun.isStale()
+ || sessionSubscriptionIdentityRef.current !== subscriptionIdentityAtStart
+ );
+ const syncReopenCoordinator = createRemoteSyncReopenCoordinator(async () => {
+ await reopenLink(deviceId);
+ });
// 门槛代号同理在开始时捕获:切会话 / attention 上升沿会递增代号,启动更早的
// in-flight load 在尾部发现代号已变,放弃落 key(它的数据不含触发点之后的内容)。
const readAckGateGenAtStart = readAckGateGenRef.current;
+ const fetchSessionMetadata = () => runConnectionScopedSessionMetadataRead(
+ () => maker.getSession(sessionId),
+ () => (
+ !subscriptionRetryIsStale()
+ && messageAuthorityCurrent()
+ && readAckGateGenRef.current === readAckGateGenAtStart
+ ),
+ (sessionMeta) => {
+ remoteSessionStore.upsertDeviceSession(deviceId, deviceName, sessionMeta);
+ setSessionMetadataSyncedKey(`${sessionId}:${readAckEpochAtStart}`);
+ },
+ );
// 重开判定:store 已有该会话消息 + currentSession(返回再点进,内存没清)→ 走"廉价校验、按
// updatedAt/_count/消息窗口同步标记决定是否重拉消息";首开(store 无消息)保持 A1 全量并行不回退;
// replaceMessages(rewind 提交)强制整窗替换。imperative 读 store,避免给 syncSession 加 deps。
@@ -3648,10 +3703,42 @@ export default function SessionScreen() {
const isReopen = !options.replaceMessages
&& storedMessagesAtStart.length > 0
&& storedSessionAtStart !== null;
- const openAndSubscribe = async () => {
- await openLink(deviceId);
- // subscribe 只负责之后的实时推送,不该挡数据读;失败不影响 open,重连 rehydration 会补订阅。
- void subscribe(`session:${sessionId}`, deviceId, ['sessions']).catch(() => undefined);
+ const prepareLinkAndSubscription = async () => {
+ await withTransientRemoteRetry(() => openLink(deviceId));
+ if (subscriptionRetryIsStale()) return;
+ let subscriptionAttemptVersion = syncReopenCoordinator.captureVersion();
+ // sessions topic 只负责之后的实时推送,不挡快照读。自己在后台
+ // 处理瞬时 route / ACK 失败;重试前重开 peer link,不再等未来 rehydrate 碰运气。
+ void sessionsSubscriptionCoordinatorRef.current?.start({
+ identity: subscriptionIdentityAtStart,
+ isStale: subscriptionRetryIsStale,
+ reopenLink: () => syncReopenCoordinator.reopenAfter(subscriptionAttemptVersion),
+ subscribe: () => {
+ subscriptionAttemptVersion = syncReopenCoordinator.captureVersion();
+ return subscribe(`session:${sessionId}`, deviceId, ['sessions']);
+ },
+ });
+ };
+ const retryRead = <T,>(read: () => Promise<T>): Promise<T> => {
+ let failedAtVersion: number | null = null;
+ return withTransientRemoteRetry(async () => {
+ // 首轮复用上面统一完成的 link-open。只有本项真的因瞬态错误重试时才
+ // 按失败请求开始时的恢复版本重开:同一旧代的错峰失败会合并;重开后
+ // 发出的请求若再次断链,则以新版本触发下一次真正 reopen。
+ if (failedAtVersion !== null) {
+ await syncReopenCoordinator.reopenAfter(failedAtVersion);
+ }
+ const attemptVersion = syncReopenCoordinator.captureVersion();
+ return read().catch((err) => {
+ failedAtVersion = attemptVersion;
+ throw err;
+ });
+ });
+ };
+ const snapshotScope = {
+ deviceId,
+ sessionId,
+ connectionEpoch: readAckEpochAtStart,
};
const fetchActiveSessionSnapshot = async () => {
// Capture immediately before every request. Because this helper is invoked inside
@@ -3665,27 +3752,39 @@ export default function SessionScreen() {
// withTransientRemoteRetry, each retry receives a fresh projection authority fence.
const authorityEpochAtStart =
remoteSessionStore.captureInputProjectionAuthorityEpoch(sessionId);
- const projection = await maker.input.getProjection(sessionId);
+ const projection = await runSessionProjectionSnapshotSingleFlight(
+ snapshotScope,
+ authorityEpochAtStart,
+ () => maker.input.getProjection(sessionId),
+ );
return { projection, authorityEpochAtStart };
};
+ const fetchPendingInteractions = () => runSessionPendingInteractionsSnapshotSingleFlight(
+ snapshotScope,
+ remoteSessionStore.getPendingInteractions(sessionId),
+ () => maker.getPendingInteractions(sessionId),
+ );
if (syncRun.isStale()) return;
setLoading(true);
setError(null);
try {
+ await prepareLinkAndSubscription();
if (!isReopen) {
- // 首开 / 强制替换:A1 全量并行(含整窗 listMessages),不回退。
- const [sessionMeta, history, pendingInteractions, projectionResult, activeSessionSnapshot] = await withTransientRemoteRetry(async () => {
- await openAndSubscribe();
- return Promise.all([
- maker.getSession(sessionId),
- listMessagesWithPayloadRetry((limit) => maker.listMessages(sessionId, { limit })),
- maker.getPendingInteractions(sessionId),
- fetchProjection(),
- fetchActiveSessionSnapshot(),
- ]);
- });
+ // 首开 / 强制替换:A1 仍保持并行,但每一项独立重试。一个 ACK timeout
+ // 不再把已经成功的 meta / history / pending / projection / active 全部重发。
+ const [sessionMeta, history, pendingInteractions, projectionResult, activeSessionSnapshot] = await runIndependentSnapshotReads([
+ fetchSessionMetadata,
+ () => listMessagesWithPayloadRetry((limit) => runSessionMessagesSnapshotSingleFlight(
+ snapshotScope,
+ limit,
+ { kind: 'detail', generation: messageAuthority.generation },
+ () => maker.listMessages(sessionId, { limit }),
+ )),
+ fetchPendingInteractions,
+ fetchProjection,
+ () => fetchActiveSessionSnapshot(),
+ ] as const, retryRead);
if (syncRun.isStale() || !messageAuthorityCurrent()) return;
- remoteSessionStore.upsertDeviceSession(deviceId, deviceName, sessionMeta);
remoteSessionStore.setActiveSessionSnapshots(
deviceId,
Array.isArray(activeSessionSnapshot.activeSessions)
@@ -3716,15 +3815,12 @@ export default function SessionScreen() {
);
} else {
// 重开:便宜并行(不含整窗 listMessages)拿 meta + pending + projection + active。
- const [sessionMeta, pendingInteractions, projectionResult, activeSessionSnapshot] = await withTransientRemoteRetry(async () => {
- await openAndSubscribe();
- return Promise.all([
- maker.getSession(sessionId),
- maker.getPendingInteractions(sessionId),
- fetchProjection(),
- fetchActiveSessionSnapshot(),
- ]);
- });
+ const [sessionMeta, pendingInteractions, projectionResult, activeSessionSnapshot] = await runIndependentSnapshotReads([
+ fetchSessionMetadata,
+ fetchPendingInteractions,
+ fetchProjection,
+ () => fetchActiveSessionSnapshot(),
+ ] as const, retryRead);
// 廉价对账:updatedAt 主信号(任何消息变化都会 bump),_count 仅在两侧都有时作辅助;
// 另外要求消息窗口已被详情页同步到当前 meta,避免首页先刷新 session preview 后,
// 详情页把旧消息缓存误判成最新。任一变化 → 拉取权威最新窗口并对账;
@@ -3744,9 +3840,14 @@ export default function SessionScreen() {
activeSessionSnapshot.activityEpochAtFetchStart,
);
if (metaChanged) {
- const history = await withTransientRemoteRetry(() =>
+ const history = await retryRead(() =>
listMessagesWithPayloadRetry(
- (limit) => maker.listMessages(sessionId, { limit }),
+ (limit) => runSessionMessagesSnapshotSingleFlight(
+ snapshotScope,
+ limit,
+ { kind: 'detail', generation: messageAuthority.generation },
+ () => maker.listMessages(sessionId, { limit }),
+ ),
REOPEN_MESSAGE_WINDOW_LIMITS,
),
);
@@ -3766,7 +3867,6 @@ export default function SessionScreen() {
// 真实消息数推断(getSession 没给总数时退化为窗口启发式)。
setHasOlderMessages(hasOlderMessagesAfterReopen(freshCount, remoteSessionStore.getMessages(sessionId)));
}
- remoteSessionStore.upsertDeviceSession(deviceId, deviceName, sessionMeta);
remoteSessionStore.setPendingInteractions(sessionId, Array.isArray(pendingInteractions) ? pendingInteractions : []);
remoteSessionStore.setInputProjectionIfCurrent(
sessionId,
@@ -3799,7 +3899,7 @@ export default function SessionScreen() {
} finally {
if (!syncRun.isStale() && messageAuthorityCurrent()) setLoading(false);
}
- }, [deviceId, deviceName, latchOutboxTransportHold, maker, openLink, sessionId, subscribe]);
+ }, [deviceId, deviceName, latchOutboxTransportHold, maker, openLink, reopenLink, sessionId, subscribe]);
// 任一连接恢复身份变化都会让旧读取失去提交资格。否则断线前启动的同步可能在
// 新 hold 锁存后迟到,并从成功尾误清恢复屏障。
const remoteSyncContextKey = JSON.stringify([
@@ -4042,6 +4142,7 @@ export default function SessionScreen() {
const prevSig = prevLiveActivitySigRef.current ?? liveActivitySig;
if (liveAttention && liveActivitySig !== prevSig) {
setReadAckSyncedKey(null);
+ setSessionMetadataSyncedKey(null);
// 代号递增:变化点之前启动的 in-flight load / 在飞重试(数据不含本 turn 终帧)
// 不得重新落 key / 不得继续发送。
readAckGateGenRef.current += 1;
@@ -7355,9 +7456,10 @@ export default function SessionScreen() {
projection: inputProjection,
isSessionStreaming,
continuationInFlight: tailContinuationInFlight,
+ sessionMetadataSyncedForConnection: sessionMetadataSyncedKey === `${sessionId}:${connectionEpoch}`,
interruptAcked: tailInterruptAcked,
hiddenErrorClientIds: tailHiddenForBanner,
- }), [messages, currentSession, inputProjection, isSessionStreaming, tailContinuationInFlight, tailInterruptAcked, tailHiddenForBanner]);
+ }), [messages, currentSession, inputProjection, isSessionStreaming, tailContinuationInFlight, sessionMetadataSyncedKey, sessionId, connectionEpoch, tailInterruptAcked, tailHiddenForBanner]);
// 主按钮(重试 / 继续任务):发隐藏续跑指令(带 [UI_ACTION_TRIGGER] 前缀,消息流
// 不渲染;排队区显示「继续未完成的任务(系统指令)」遮蔽气泡)。planMode 强制 false:
diff --git a/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts b/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts
index dfd13e2840..a65ef759a2 100644
--- a/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts
+++ b/apps/mobile/src/__tests__/optimisticSessionComposer.test.ts
@@ -105,7 +105,8 @@ describe('mobile optimistic composer while session is not ready', () => {
expect((source.match(
/publishPresenceAvailabilityMutation\(deviceId, \(availabilityByDevice\) =>/g,
) ?? [])).toHaveLength(5);
- expect(source).toContain('setConnectionEpoch((n) => n + 1);');
+ expect(source).toContain('connectionEpochRef.current = ++nextDeviceLinkConnectionEpoch;');
+ expect(source).toContain('setConnectionEpoch(connectionEpochRef.current);');
expect(source).toContain('setPresenceVersion((n) => n + 1);\n const presence = updatePresenceAvailability(');
});
@@ -276,6 +277,18 @@ describe('mobile optimistic composer while session is not ready', () => {
expect(source).toContain('error={connectionRecoveryError}');
});
+ it('separates the interrupted metadata fence from the full read-ack sync gate', () => {
+ const source = readSource(SCREEN);
+
+ expect(source).toContain('const [sessionMetadataSyncedKey, setSessionMetadataSyncedKey]');
+ expect(source).toContain('const fetchSessionMetadata = () => runConnectionScopedSessionMetadataRead(');
+ expect(source).toContain('setSessionMetadataSyncedKey(`${sessionId}:${readAckEpochAtStart}`);');
+ expect(source).toContain(
+ 'sessionMetadataSyncedForConnection: sessionMetadataSyncedKey === `${sessionId}:${connectionEpoch}`',
+ );
+ expect(source).toContain('setReadAckSyncedKey(`${sessionId}:${readAckEpochAtStart}`);');
+ });
+
it('fences every pre-outbox await against an in-place session switch', () => {
const source = readSource(SCREEN);
diff --git a/apps/mobile/src/__tests__/presenceRecovery.test.ts b/apps/mobile/src/__tests__/presenceRecovery.test.ts
index c7929f1c9e..d4c6161be9 100644
--- a/apps/mobile/src/__tests__/presenceRecovery.test.ts
+++ b/apps/mobile/src/__tests__/presenceRecovery.test.ts
@@ -495,6 +495,52 @@ describe('presence availability epochs', () => {
expect(create).toHaveBeenCalledTimes(2);
});
+ it('refreshes a settled retained link without duplicating an in-flight reopen', async () => {
+ const epochs = createPresenceAvailabilityEpochs();
+ const responseEvidenceEpochs = createPresenceAvailabilityEpochs();
+ const tracked = new Map();
+ let resolveReopen!: (value: string) => void;
+ const reopenPending = new Promise<string>((resolve) => {
+ resolveReopen = resolve;
+ });
+ const create = vi.fn()
+ .mockResolvedValueOnce('first-accept')
+ .mockReturnValueOnce(reopenPending);
+
+ const first = getOrCreatePresenceTrackedRequest(
+ tracked,
+ epochs,
+ responseEvidenceEpochs,
+ 'dev-1',
+ create,
+ { retainSuccessful: true },
+ );
+ await expect(first.request).resolves.toBe('first-accept');
+
+ const reopened = getOrCreatePresenceTrackedRequest(
+ tracked,
+ epochs,
+ responseEvidenceEpochs,
+ 'dev-1',
+ create,
+ { retainSuccessful: true, refreshSettled: true },
+ );
+ const deduped = getOrCreatePresenceTrackedRequest(
+ tracked,
+ epochs,
+ responseEvidenceEpochs,
+ 'dev-1',
+ create,
+ { retainSuccessful: true, refreshSettled: true },
+ );
+
+ expect(reopened).not.toBe(first);
+ expect(deduped).toBe(reopened);
+ expect(create).toHaveBeenCalledTimes(2);
+ resolveReopen('second-accept');
+ await expect(reopened.request).resolves.toBe('second-accept');
+ });
+
it('does not retain failed requests when successful reuse is enabled', async () => {
const epochs = createPresenceAvailabilityEpochs();
const responseEvidenceEpochs = createPresenceAvailabilityEpochs();
diff --git a/apps/mobile/src/__tests__/remoteSyncTask.test.ts b/apps/mobile/src/__tests__/remoteSyncTask.test.ts
index fa53126980..a9517bff0c 100644
--- a/apps/mobile/src/__tests__/remoteSyncTask.test.ts
+++ b/apps/mobile/src/__tests__/remoteSyncTask.test.ts
@@ -1,7 +1,11 @@
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
-import { describe, expect, it } from 'vitest';
-import { createRemoteSyncCoordinator, createRemoteSyncRunner } from '@/device-link/remoteSyncTask';
+import { describe, expect, it, vi } from 'vitest';
+import {
+ createRemoteSyncCoordinator,
+ createRemoteSyncReopenCoordinator,
+ createRemoteSyncRunner,
+} from '@/device-link/remoteSyncTask';
function deferred() {
let resolve!: () => void;
@@ -20,6 +24,44 @@ function readSessionScreenSource(): string {
}
describe('remote sync task runner', () => {
+ it('shares one successful peer reopen across staggered retries in the same sync run', async () => {
+ const reopen = vi.fn(async () => undefined);
+ const coordinator = createRemoteSyncReopenCoordinator(reopen);
+ const failedAtVersion = coordinator.captureVersion();
+
+ const first = coordinator.reopenAfter(failedAtVersion);
+ await first;
+ const later = coordinator.reopenAfter(failedAtVersion);
+
+ expect(later).toBe(first);
+ await later;
+ expect(reopen).toHaveBeenCalledTimes(1);
+ });
+
+ it('allows a new reopen when an operation fails after the previous recovery', async () => {
+ const reopen = vi.fn(async () => undefined);
+ const coordinator = createRemoteSyncReopenCoordinator(reopen);
+
+ await coordinator.reopenAfter(coordinator.captureVersion());
+ const requestStartedAfterRecovery = coordinator.captureVersion();
+ await coordinator.reopenAfter(requestStartedAfterRecovery);
+
+ expect(reopen).toHaveBeenCalledTimes(2);
+ expect(coordinator.captureVersion()).toBe(2);
+ });
+
+ it('allows the same sync run to retry after a failed peer reopen', async () => {
+ const reopen = vi.fn()
+ .mockRejectedValueOnce(new Error('offline'))
+ .mockResolvedValueOnce(undefined);
+ const coordinator = createRemoteSyncReopenCoordinator(reopen);
+ const failedAtVersion = coordinator.captureVersion();
+
+ await expect(coordinator.reopenAfter(failedAtVersion)).rejects.toThrow('offline');
+ await expect(coordinator.reopenAfter(failedAtVersion)).resolves.toBeUndefined();
+ expect(reopen).toHaveBeenCalledTimes(2);
+ });
+
it('coalesces repeated triggers into one in-flight run and one follow-up run', async () => {
const gates = [deferred(), deferred()];
const starts: number[] = [];
@@ -179,6 +221,22 @@ describe('remote sync coordinator', () => {
);
});
+ it('uses the force-reopen callback for subscription and snapshot retries', () => {
+ const source = readSessionScreenSource();
+ expect(source).toContain(
+ 'reopenLink: () => syncReopenCoordinator.reopenAfter(subscriptionAttemptVersion)',
+ );
+ expect(source).toContain(
+ 'await syncReopenCoordinator.reopenAfter(failedAtVersion);',
+ );
+ expect(source).toContain(
+ 'const syncReopenCoordinator = createRemoteSyncReopenCoordinator(',
+ );
+ expect(source).not.toContain(
+ 'reopenLink: async () => {\n await openLink(deviceId);\n }',
+ );
+ });
+
it('applies coordinator context and task changes after render commits', () => {
const source = readFileSync(
resolve(process.cwd(), 'src/device-link/remoteSyncTask.ts'),
diff --git a/apps/mobile/src/__tests__/sessionSnapshotSingleFlight.test.ts b/apps/mobile/src/__tests__/sessionSnapshotSingleFlight.test.ts
new file mode 100644
index 0000000000..43396cc6f9
--- /dev/null
+++ b/apps/mobile/src/__tests__/sessionSnapshotSingleFlight.test.ts
@@ -0,0 +1,197 @@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ runConnectionScopedSessionMetadataRead,
+ runIndependentSnapshotReads,
+ runSessionMessagesSnapshotSingleFlight,
+ runSessionPendingInteractionsSnapshotSingleFlight,
+ runSessionProjectionSnapshotSingleFlight,
+ runSessionSnapshotSingleFlight,
+ sessionPendingInteractionsSnapshotVariant,
+} from '@/device-link/sessionSnapshotSingleFlight';
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (reason?: unknown) => void;
+ const promise = new Promise<T>((done, fail) => {
+ resolve = done;
+ reject = fail;
+ });
+ return { promise, reject, resolve };
+}
+
+describe('session snapshot single-flight', () => {
+ it('shares one identical physical read and drops the entry after settle', async () => {
+ const gate = deferred<string>();
+ const read = vi.fn(() => gate.promise);
+ const identity = {
+ deviceId: 'device-1',
+ sessionId: 'session-1',
+ connectionEpoch: 3,
+ resource: 'messages' as const,
+ variant: 'limit=80;authority=detail:9',
+ };
+
+ const first = runSessionSnapshotSingleFlight(identity, read);
+ const second = runSessionSnapshotSingleFlight(identity, read);
+ expect(second).toBe(first);
+ expect(read).toHaveBeenCalledTimes(1);
+
+ gate.resolve('snapshot');
+ await expect(first).resolves.toBe('snapshot');
+ await runSessionSnapshotSingleFlight(identity, read);
+ expect(read).toHaveBeenCalledTimes(2);
+ });
+
+ it('shares page and rehydrate reads when their scope and authority fences match', async () => {
+ const scope = {
+ deviceId: 'device-1',
+ sessionId: 'session-1',
+ connectionEpoch: 7,
+ };
+ const pendingSnapshot: unknown[] = [];
+ const callers = [
+ (read: () => Promise<string>) =>
+ runSessionMessagesSnapshotSingleFlight(
+ scope,
+ 80,
+ { kind: 'detail', generation: 4 },
+ read,
+ ),
+ (read: () => Promise<string>) =>
+ runSessionPendingInteractionsSnapshotSingleFlight(
+ scope,
+ pendingSnapshot,
+ read,
+ ),
+ (read: () => Promise<string>) =>
+ runSessionProjectionSnapshotSingleFlight(scope, 9, read),
+ ];
+
+ for (const run of callers) {
+ const gate = deferred<string>();
+ const pageRead = vi.fn(() => gate.promise);
+ const rehydrateRead = vi.fn(async () => 'duplicate');
+ const page = run(pageRead);
+ const rehydrate = run(rehydrateRead);
+ expect(rehydrate).toBe(page);
+ expect(pageRead).toHaveBeenCalledTimes(1);
+ expect(rehydrateRead).not.toHaveBeenCalled();
+ gate.resolve('shared');
+ await expect(page).resolves.toBe('shared');
+ }
+ });
+
+ it('does not share across connection epochs, request variants, or authority fences', async () => {
+ const read = vi.fn(async () => 'snapshot');
+ const base = {
+ deviceId: 'device-1',
+ sessionId: 'session-1',
+ resource: 'input-projection' as const,
+ };
+
+ await Promise.all([
+ runSessionSnapshotSingleFlight(
+ { ...base, connectionEpoch: 1, variant: 'authority=4' },
+ read,
+ ),
+ runSessionSnapshotSingleFlight(
+ { ...base, connectionEpoch: 2, variant: 'authority=4' },
+ read,
+ ),
+ runSessionSnapshotSingleFlight(
+ { ...base, connectionEpoch: 1, variant: 'authority=5' },
+ read,
+ ),
+ ]);
+ expect(read).toHaveBeenCalledTimes(3);
+ });
+
+ it('uses pending snapshot identity as a content-free freshness fence', () => {
+ const first: unknown[] = [];
+ const second: unknown[] = [];
+ expect(sessionPendingInteractionsSnapshotVariant(first)).toBe(
+ sessionPendingInteractionsSnapshotVariant(first),
+ );
+ expect(sessionPendingInteractionsSnapshotVariant(second)).not.toBe(
+ sessionPendingInteractionsSnapshotVariant(first),
+ );
+ });
+
+ it('clears a rejected request so the next recovery attempt can run', async () => {
+ const identity = {
+ deviceId: 'device-1',
+ sessionId: 'session-1',
+ connectionEpoch: 1,
+ resource: 'input-projection' as const,
+ variant: 'snapshot',
+ };
+ const read = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('timeout'))
+ .mockResolvedValueOnce('recovered');
+
+ await expect(
+ runSessionSnapshotSingleFlight(identity, read),
+ ).rejects.toThrow('timeout');
+ await expect(runSessionSnapshotSingleFlight(identity, read)).resolves.toBe(
+ 'recovered',
+ );
+ expect(read).toHaveBeenCalledTimes(2);
+ });
+});
+
+describe('independent snapshot retries', () => {
+ it('retries only the failed item instead of replaying the whole batch', async () => {
+ const attempts = [0, 0, 0];
+ const retry = async <T>(read: () => Promise<T>): Promise<T> => {
+ try {
+ return await read();
+ } catch {
+ return read();
+ }
+ };
+ const reads = [
+ async () => {
+ attempts[0] += 1;
+ return 'meta';
+ },
+ async () => {
+ attempts[1] += 1;
+ if (attempts[1] === 1) throw new Error('transient');
+ return 'messages';
+ },
+ async () => {
+ attempts[2] += 1;
+ return 'projection';
+ },
+ ] as const;
+
+ await expect(runIndependentSnapshotReads(reads, retry)).resolves.toEqual([
+ 'meta',
+ 'messages',
+ 'projection',
+ ]);
+ expect(attempts).toEqual([1, 2, 1]);
+ });
+
+ it('commits session metadata even when a sibling snapshot later fails', async () => {
+ const sibling = deferred<string>();
+ const committed: string[] = [];
+ const retry = <T,>(read: () => Promise<T>): Promise<T> => read();
+ const reads = [
+ () => runConnectionScopedSessionMetadataRead(
+ async () => 'authoritative-meta',
+ () => true,
+ (value) => committed.push(value),
+ ),
+ () => sibling.promise,
+ ] as const;
+
+ const batch = runIndependentSnapshotReads(reads, retry);
+ await vi.waitFor(() => expect(committed).toEqual(['authoritative-meta']));
+ sibling.reject(new Error('projection retry exhausted'));
+
+ await expect(batch).rejects.toThrow('projection retry exhausted');
+ expect(committed).toEqual(['authoritative-meta']);
+ });
+});
diff --git a/apps/mobile/src/__tests__/sessionTailBannerModel.test.ts b/apps/mobile/src/__tests__/sessionTailBannerModel.test.ts
index 2653f6698f..8409f6ddf4 100644
--- a/apps/mobile/src/__tests__/sessionTailBannerModel.test.ts
+++ b/apps/mobile/src/__tests__/sessionTailBannerModel.test.ts
@@ -37,6 +37,7 @@ function baseInput(patch: Partial<ResolveSessionTailBannerInput> = {}): ResolveS
projection: { error: null, credentialSwitchWait: null },
isSessionStreaming: false,
continuationInFlight: false,
+ sessionMetadataSyncedForConnection: true,
interruptAcked: false,
hiddenErrorClientIds: new Set(),
...patch,
@@ -60,6 +61,14 @@ describe('resolveSessionTailBanner — error-tail', () => {
});
});
+ it('keeps a persisted error tail visible before current-connection metadata sync', () => {
+ const state = resolveSessionTailBanner(baseInput({
+ messages: [errorRow('e1', '2026-01-01T00:00:02.000Z', { message: 'boom' })],
+ sessionMetadataSyncedForConnection: false,
+ }));
+ expect(state).toMatchObject({ kind: 'error-tail', clientId: 'e1' });
+ });
+
it('maps legacy app-exit marker rows to the continue-task semantics', () => {
const state = resolveSessionTailBanner(baseInput({
messages: [errorRow('e1', '2026-01-01T00:00:02.000Z', {
@@ -163,6 +172,13 @@ describe('resolveSessionTailBanner — error-tail', () => {
});
describe('resolveSessionTailBanner — interrupted(session 双时间戳)', () => {
+ it('stays quiet until metadata is synced for the current connection', () => {
+ expect(resolveSessionTailBanner(baseInput({
+ session: { activeTurnStartedAt: 2000, lastTurnEndedAt: 1000, clearedAt: null },
+ sessionMetadataSyncedForConnection: false,
+ }))).toBeNull();
+ });
+
it('fires when the active turn started after it last ended and nothing acked it', () => {
const state = resolveSessionTailBanner(baseInput({
session: { activeTurnStartedAt: 2000, lastTurnEndedAt: 1000, clearedAt: null },
diff --git a/apps/mobile/src/__tests__/transientTopicSubscription.test.ts b/apps/mobile/src/__tests__/transientTopicSubscription.test.ts
new file mode 100644
index 0000000000..a5aa3357c5
--- /dev/null
+++ b/apps/mobile/src/__tests__/transientTopicSubscription.test.ts
@@ -0,0 +1,150 @@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ createTransientTopicSubscriptionCoordinator,
+} from '@/device-link/transientTopicSubscription';
+
+type RetryOperation = <T>(operation: () => Promise<T>) => Promise<T>;
+
+function deferred<T = void>() {
+ let resolve!: (value: T | PromiseLike<T>) => void;
+ let reject!: (reason?: unknown) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, reject, resolve };
+}
+
+const retryOnce: RetryOperation = async <T>(operation: () => Promise<T>): Promise<T> => {
+ try {
+ return await operation();
+ } catch {
+ return operation();
+ }
+};
+
+describe('transient topic subscription coordinator', () => {
+ it('reopens the peer link before independently retrying a failed subscription', async () => {
+ const order: string[] = [];
+ const subscribe = vi.fn(async () => {
+ order.push('subscribe');
+ if (subscribe.mock.calls.length === 1) throw new Error('transient');
+ });
+ const reopenLink = vi.fn(async () => {
+ order.push('reopen');
+ });
+ const coordinator = createTransientTopicSubscriptionCoordinator(retryOnce);
+
+ await coordinator.start({
+ identity: 'device-1:session-1:epoch-1',
+ isStale: () => false,
+ reopenLink,
+ subscribe,
+ });
+
+ expect(order).toEqual(['subscribe', 'reopen', 'subscribe']);
+ expect(subscribe).toHaveBeenCalledTimes(2);
+ expect(reopenLink).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps one retry loop per recovery identity', async () => {
+ const pending = deferred();
+ const subscribe = vi.fn(() => pending.promise);
+ const coordinator = createTransientTopicSubscriptionCoordinator(retryOnce);
+ const request = {
+ identity: 'device-1:session-1:epoch-1',
+ isStale: () => false,
+ reopenLink: vi.fn(async () => undefined),
+ subscribe,
+ };
+
+ const first = coordinator.start(request);
+ const second = coordinator.start(request);
+
+ expect(second).toBe(first);
+ expect(subscribe).toHaveBeenCalledTimes(1);
+ pending.resolve();
+ await first;
+
+ await coordinator.start(request);
+ expect(subscribe).toHaveBeenCalledTimes(2);
+ });
+
+ it('lets a current run replace a stale loop without the old settle clearing it', async () => {
+ const firstPending = deferred();
+ const secondPending = deferred();
+ let firstStale = false;
+ const coordinator = createTransientTopicSubscriptionCoordinator(retryOnce);
+
+ const first = coordinator.start({
+ identity: 'device-1:session-1:epoch-1',
+ isStale: () => firstStale,
+ reopenLink: vi.fn(async () => undefined),
+ subscribe: vi.fn(() => firstPending.promise),
+ });
+ firstStale = true;
+ const second = coordinator.start({
+ identity: 'device-1:session-1:epoch-1',
+ isStale: () => false,
+ reopenLink: vi.fn(async () => undefined),
+ subscribe: vi.fn(() => secondPending.promise),
+ });
+
+ expect(second).not.toBe(first);
+ firstPending.resolve();
+ await first;
+
+ const duplicateOfSecond = coordinator.start({
+ identity: 'device-1:session-1:epoch-1',
+ isStale: () => false,
+ reopenLink: vi.fn(async () => undefined),
+ subscribe: vi.fn(async () => undefined),
+ });
+ expect(duplicateOfSecond).toBe(second);
+
+ secondPending.resolve();
+ await second;
+ });
+
+ it('does not retry or re-register an owner after the recovery scope becomes stale', async () => {
+ let stale = false;
+ const subscribe = vi.fn(async () => {
+ stale = true;
+ throw new Error('transient');
+ });
+ const reopenLink = vi.fn(async () => undefined);
+ const coordinator = createTransientTopicSubscriptionCoordinator(retryOnce);
+
+ await coordinator.start({
+ identity: 'device-1:session-1:epoch-1',
+ isStale: () => stale,
+ reopenLink,
+ subscribe,
+ });
+
+ expect(subscribe).toHaveBeenCalledTimes(1);
+ expect(reopenLink).not.toHaveBeenCalled();
+ });
+
+ it('rechecks staleness after reopening before it subscribes again', async () => {
+ let stale = false;
+ const subscribe = vi
+ .fn<() => Promise<void>>()
+ .mockRejectedValueOnce(new Error('transient'))
+ .mockResolvedValue(undefined);
+ const reopenLink = vi.fn(async () => {
+ stale = true;
+ });
+ const coordinator = createTransientTopicSubscriptionCoordinator(retryOnce);
+
+ await coordinator.start({
+ identity: 'device-1:session-1:epoch-1',
+ isStale: () => stale,
+ reopenLink,
+ subscribe,
+ });
+
+ expect(reopenLink).toHaveBeenCalledTimes(1);
+ expect(subscribe).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/mobile/src/debug/visualMock.ts b/apps/mobile/src/debug/visualMock.ts
index 325fa16553..e02b2c42f7 100644
--- a/apps/mobile/src/debug/visualMock.ts
+++ b/apps/mobile/src/debug/visualMock.ts
@@ -154,6 +154,10 @@ export function createVisualMockDeviceLinkContext(): DeviceLinkContextValue {
appVersion: '0.0.0-visual-mock',
allowlistHash: 'visual-mock',
}),
+ reopenLink: async (): Promise<LinkAcceptPayload> => ({
+ appVersion: '0.0.0-visual-mock',
+ allowlistHash: 'visual-mock',
+ }),
closeLink: () => undefined,
invoke: visualMockInvoke,
subscribe: async () => undefined,
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index d30b869be6..de9973d6b7 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -62,6 +62,11 @@ import {
invalidateTransientScheduleIndexFailures,
} from '@/session/scheduleIndex';
import { isTransientRemoteError } from '@/device-link/remoteRetry';
+import {
+ runSessionMessagesSnapshotSingleFlight,
+ runSessionPendingInteractionsSnapshotSingleFlight,
+ runSessionProjectionSnapshotSingleFlight,
+} from '@/device-link/sessionSnapshotSingleFlight';
import { createRnWebSocket } from '@/device-link/rnWebSocket';
import {
DEVICE_LINK_VOICE_DICTIONARY_SNAPSHOT_CHANNEL,
@@ -134,6 +139,8 @@ export interface DeviceLinkContextValue {
/** 当前 relay 连接代内的逐设备 availability;null = 本代尚无权威 verdict。 */
getPresenceAvailability(deviceId: string): boolean | null;
openLink(deviceId: string): Promise<LinkAcceptPayload>;
+ /** 丢弃已结算的开链缓存并真正重开;并发重开仍按设备单飞。 */
+ reopenLink(deviceId: string): Promise<LinkAcceptPayload>;
closeLink(deviceId: string): void;
/**
* opts.preSend:在连接就绪之后、真正 client.invoke 之前的最后同步检查点。抛错即
@@ -232,6 +239,9 @@ const RECONNECT_MIN_WIPE_GRACE_MS = 3_000;
* 与 #1222)。
*/
const RECONNECT_MESSAGE_WINDOW_LIMIT = 80;
+// Provider remount / account switch must not reuse an in-flight snapshot key
+// from an older DeviceLinkClient instance. Keep epochs process-monotonic.
+let nextDeviceLinkConnectionEpoch = 0;
const SESSION_TOPIC_PREFIX = 'session:';
@@ -308,6 +318,9 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
const [connectionIssue, setConnectionIssue] = useState<DeviceLinkConnectionIssue | null>(null);
const [presenceVersion, setPresenceVersion] = useState(0);
const [connectionEpoch, setConnectionEpoch] = useState(0);
+ // status callback 中先同步推进 ref,再触发 rehydrate;React state 的下一次 render
+ // 才会把同一代暴露给页面。这样全局补齐与页面首开使用完全相同的 single-flight key。
+ const connectionEpochRef = useRef(0);
const [lastPresenceSnapshot, setLastPresenceSnapshot] = useState<PresenceSnapshot | null>(null);
/**
@@ -331,6 +344,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
client: DeviceLinkClient,
deviceId: string,
allowProbe = false,
+ refreshSettled = false,
) => {
return getOrCreatePresenceTrackedRequest(
openLinkInFlightRef.current,
@@ -338,7 +352,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
remoteResponseEvidenceEpochs,
deviceId,
() => sendOpenLinkWithAccessHandling(client, deviceId, allowProbe),
- { retainSuccessful: true },
+ { retainSuccessful: true, refreshSettled },
);
}, []);
@@ -590,7 +604,13 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
presenceWipeTimerDeps,
);
},
- rebuildSessionSnapshot: (deviceId, sessionId, opts) => rebuildSessionSnapshot(client, deviceId, sessionId, opts),
+ rebuildSessionSnapshot: (deviceId, sessionId, opts) => rebuildSessionSnapshot(
+ client,
+ deviceId,
+ sessionId,
+ connectionEpochRef.current,
+ opts,
+ ),
});
await probeRun;
// 探测后仍 open 的设备持续计入"未完成"信号(review P1:不能在探测
@@ -730,7 +750,8 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
presenceWipeTimerDeps,
);
}
- setConnectionEpoch((n) => n + 1);
+ connectionEpochRef.current = ++nextDeviceLinkConnectionEpoch;
+ setConnectionEpoch(connectionEpochRef.current);
resetRemoteProjectOrderPushFence();
void rehydrateWithClient(client);
});
@@ -1066,6 +1087,19 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
[sendOpenLinkOnce],
);
+ const reopenLink = useCallback(
+ async (deviceId: string) => {
+ registryRef.current.trackOpenLink(deviceId);
+ return sendOpenLinkOnce(
+ requireClient(clientRef.current),
+ deviceId,
+ false,
+ true,
+ ).request;
+ },
+ [sendOpenLinkOnce],
+ );
+
const closeLink = useCallback((deviceId: string) => {
registryRef.current.untrackOpenLink(deviceId);
openLinkInFlightRef.current.delete(deviceId);
@@ -1121,6 +1155,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
lastPresenceSnapshot,
getPresenceAvailability,
openLink,
+ reopenLink,
closeLink,
invoke,
subscribe,
@@ -1133,6 +1168,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
invoke,
lastPresenceSnapshot,
openLink,
+ reopenLink,
presenceVersion,
status,
subscribe,
@@ -1225,6 +1261,7 @@ async function rebuildSessionSnapshot(
client: DeviceLinkClient,
deviceId: string,
sessionId: string,
+ connectionEpoch: number,
opts?: DeviceLinkRehydrateSendOptions,
): Promise<void> {
// 这四个并发请求是同一轮补齐:一次路由抖动可能让它们同时等满超时,但这只
@@ -1243,28 +1280,52 @@ async function rebuildSessionSnapshot(
const unenteredMessageAuthorityAtRequestStart = messageDetailEnteredAtRequestStart
? null
: remoteSessionStore.captureUnenteredSessionMessageAuthority(sessionId);
+ const snapshotScope = { deviceId, sessionId, connectionEpoch };
+ const pendingSnapshotAtRequestStart = remoteSessionStore.getPendingInteractions(sessionId);
// 四路快照独立拉取、独立落库:断连补齐窗口本就脆弱,一个子请求失败不应拖垮
// 其余(旧实现共用一个 catch,任一失败三份快照全丢)。goal 覆盖断连窗口内
// 丢失的 maker:goal:status-changed push;model-pref / turn-cost 无对应查询通道,
// 暂不在补齐范围(需扩桌面端 invoke 白名单)。
const [history, pending, projection, goal] = await Promise.allSettled([
- sendInvokeWithAccessHandling<RemoteMessage[]>(client, deviceId, 'local-db:messages:list', [
- sessionId,
- { limit: RECONNECT_MESSAGE_WINDOW_LIMIT },
- ], sendOpts),
- sendInvokeWithAccessHandling<PendingInteraction[]>(
- client,
- deviceId,
- 'maker:get-pending-interactions',
- [sessionId],
- sendOpts,
+ runSessionMessagesSnapshotSingleFlight(
+ snapshotScope,
+ RECONNECT_MESSAGE_WINDOW_LIMIT,
+ messageAuthorityAtRequestStart
+ ? { kind: 'detail', generation: messageAuthorityAtRequestStart.generation }
+ : {
+ kind: 'unentered',
+ generation: unenteredMessageAuthorityAtRequestStart?.generation ?? -1,
+ resetEpoch: unenteredMessageAuthorityAtRequestStart?.resetEpoch ?? -1,
+ },
+ () => sendInvokeWithAccessHandling<RemoteMessage[]>(
+ client,
+ deviceId,
+ 'local-db:messages:list',
+ [sessionId, { limit: RECONNECT_MESSAGE_WINDOW_LIMIT }],
+ sendOpts,
+ ),
),
- sendInvokeWithAccessHandling<InputProjection>(
- client,
- deviceId,
- 'maker:input:get-projection',
- [sessionId],
- sendOpts,
+ runSessionPendingInteractionsSnapshotSingleFlight(
+ snapshotScope,
+ pendingSnapshotAtRequestStart,
+ () => sendInvokeWithAccessHandling<PendingInteraction[]>(
+ client,
+ deviceId,
+ 'maker:get-pending-interactions',
+ [sessionId],
+ sendOpts,
+ ),
+ ),
+ runSessionProjectionSnapshotSingleFlight(
+ snapshotScope,
+ projectionEpochAtRequestStart,
+ () => sendInvokeWithAccessHandling<InputProjection>(
+ client,
+ deviceId,
+ 'maker:input:get-projection',
+ [sessionId],
+ sendOpts,
+ ),
),
sendInvokeWithAccessHandling<MobileGoalStatusPayload | null | undefined>(
client,
diff --git a/apps/mobile/src/device-link/presenceRecovery.ts b/apps/mobile/src/device-link/presenceRecovery.ts
index e3125345b4..23452ab976 100644
--- a/apps/mobile/src/device-link/presenceRecovery.ts
+++ b/apps/mobile/src/device-link/presenceRecovery.ts
@@ -63,10 +63,13 @@ export function getOrCreatePresenceTrackedRequest<T>(
options: {
/** 成功的 link 在当前 presence / 连接代保持可复用;失败仍立即清除。 */
retainSuccessful?: boolean;
+ /** 重试已失效的 link 时替换已结算缓存;仍复用当前在途请求以保持单飞。 */
+ refreshSettled?: boolean;
} = {},
): PresenceTrackedRequest<T> {
const existing = inFlight.get(deviceId);
- if (existing) return existing;
+ if (existing && (!options.refreshSettled || existing.pending)) return existing;
+ if (existing) inFlight.delete(deviceId);
const tracked: PresenceTrackedRequest<T> = {
capturedPresenceEpoch: capturePresenceAvailabilityEpoch(epochs, deviceId),
diff --git a/apps/mobile/src/device-link/remoteSyncTask.ts b/apps/mobile/src/device-link/remoteSyncTask.ts
index e1157625a2..3c1cc85d83 100644
--- a/apps/mobile/src/device-link/remoteSyncTask.ts
+++ b/apps/mobile/src/device-link/remoteSyncTask.ts
@@ -5,6 +5,45 @@ export interface RemoteSyncRunner {
isRunning(): boolean;
}
+export interface RemoteSyncReopenCoordinator {
+ captureVersion(): number;
+ reopenAfter(failedAtVersion: number): Promise<void>;
+}
+
+/**
+ * 同一轮 session sync 按「故障发生时看到的恢复版本」合并 peer 重开。
+ * 同一旧代上错峰返回的失败共用一次 reopen;reopen 后真正发出的请求若再次失败,
+ * 会携带新版本触发下一次 reopen。失败的 reopen 不推进版本,允许后续继续自愈。
+ */
+export function createRemoteSyncReopenCoordinator(
+ reopen: () => Promise<void>,
+): RemoteSyncReopenCoordinator {
+ let successfulVersion = 0;
+ let recovery: {
+ coveredFailureVersion: number;
+ promise: Promise<void>;
+ } | null = null;
+
+ return {
+ captureVersion: () => successfulVersion,
+ reopenAfter(failedAtVersion): Promise<void> {
+ if (recovery && recovery.coveredFailureVersion >= failedAtVersion) {
+ return recovery.promise;
+ }
+ const nextVersion = successfulVersion + 1;
+ const attempt = Promise.resolve().then(reopen).then(() => {
+ successfulVersion = nextVersion;
+ });
+ const entry = { coveredFailureVersion: failedAtVersion, promise: attempt };
+ recovery = entry;
+ void attempt.catch(() => {
+ if (recovery === entry) recovery = null;
+ });
+ return attempt;
+ },
+ };
+}
+
/**
* Coalesces repeated resync triggers into one in-flight run plus at most one
* follow-up run. This matches mobile foreground/reconnect behavior where
diff --git a/apps/mobile/src/device-link/sessionSnapshotSingleFlight.ts b/apps/mobile/src/device-link/sessionSnapshotSingleFlight.ts
new file mode 100644
index 0000000000..716c15a187
--- /dev/null
+++ b/apps/mobile/src/device-link/sessionSnapshotSingleFlight.ts
@@ -0,0 +1,177 @@
+export type SessionSnapshotResource =
+ 'messages' | 'pending-interactions' | 'input-projection';
+
+export interface SessionSnapshotRequestIdentity {
+ deviceId: string;
+ sessionId: string;
+ connectionEpoch: number;
+ resource: SessionSnapshotResource;
+ /**
+ * Exact request semantics and local authority fence. Requests only share a
+ * physical invoke when this value also matches, so a different history
+ * window or a snapshot started before a newer local push never gets reused.
+ */
+ variant: string;
+}
+
+export type SessionSnapshotScope = Pick<
+ SessionSnapshotRequestIdentity,
+ 'deviceId' | 'sessionId' | 'connectionEpoch'
+>;
+
+export type SessionMessageSnapshotFence =
+ | { kind: 'detail'; generation: number }
+ | { kind: 'unentered'; generation: number; resetEpoch: number };
+
+export function sessionMessagesSnapshotVariant(
+ limit: number,
+ fence: SessionMessageSnapshotFence,
+): string {
+ return fence.kind === 'detail'
+ ? `limit=${limit};authority=detail:${fence.generation}`
+ : `limit=${limit};authority=unentered:${fence.generation}:${fence.resetEpoch}`;
+}
+
+export function sessionProjectionSnapshotVariant(
+ authorityEpoch: number,
+): string {
+ return `authority=${authorityEpoch}`;
+}
+
+const snapshotReferenceIds = new WeakMap<object, number>();
+let nextSnapshotReferenceId = 0;
+
+/**
+ * Pending interactions do not expose an authority counter. The store keeps a
+ * stable array reference until its visible snapshot changes, so object identity
+ * is an exact in-process freshness fence without putting card contents in keys
+ * or logs. WeakMap entries disappear with the old snapshot.
+ */
+export function sessionPendingInteractionsSnapshotVariant(
+ snapshot: readonly unknown[],
+): string {
+ let id = snapshotReferenceIds.get(snapshot);
+ if (id === undefined) {
+ id = ++nextSnapshotReferenceId;
+ snapshotReferenceIds.set(snapshot, id);
+ }
+ return `snapshot=${id}`;
+}
+
+const inFlightSessionSnapshotRequests = new Map<string, Promise<unknown>>();
+
+function requestKey(identity: SessionSnapshotRequestIdentity): string {
+ return JSON.stringify([
+ identity.deviceId,
+ identity.sessionId,
+ identity.connectionEpoch,
+ identity.resource,
+ identity.variant,
+ ]);
+}
+
+/**
+ * Shares only an identical in-flight read. Results are not cached: once the
+ * request settles, a later caller performs a fresh authoritative read.
+ */
+export function runSessionSnapshotSingleFlight<T>(
+ identity: SessionSnapshotRequestIdentity,
+ read: () => Promise<T>,
+): Promise<T> {
+ const key = requestKey(identity);
+ const current = inFlightSessionSnapshotRequests.get(key);
+ if (current) return current as Promise<T>;
+
+ let request: Promise<T>;
+ try {
+ request = read();
+ } catch (error) {
+ request = Promise.reject(error);
+ }
+ inFlightSessionSnapshotRequests.set(key, request);
+ const clear = () => {
+ if (inFlightSessionSnapshotRequests.get(key) === request) {
+ inFlightSessionSnapshotRequests.delete(key);
+ }
+ };
+ void request.then(clear, clear);
+ return request;
+}
+
+export function runSessionMessagesSnapshotSingleFlight<T>(
+ scope: SessionSnapshotScope,
+ limit: number,
+ fence: SessionMessageSnapshotFence,
+ read: () => Promise<T>,
+): Promise<T> {
+ return runSessionSnapshotSingleFlight(
+ {
+ ...scope,
+ resource: 'messages',
+ variant: sessionMessagesSnapshotVariant(limit, fence),
+ },
+ read,
+ );
+}
+
+export function runSessionPendingInteractionsSnapshotSingleFlight<T>(
+ scope: SessionSnapshotScope,
+ snapshot: readonly unknown[],
+ read: () => Promise<T>,
+): Promise<T> {
+ return runSessionSnapshotSingleFlight(
+ {
+ ...scope,
+ resource: 'pending-interactions',
+ variant: sessionPendingInteractionsSnapshotVariant(snapshot),
+ },
+ read,
+ );
+}
+
+export function runSessionProjectionSnapshotSingleFlight<T>(
+ scope: SessionSnapshotScope,
+ authorityEpoch: number,
+ read: () => Promise<T>,
+): Promise<T> {
+ return runSessionSnapshotSingleFlight(
+ {
+ ...scope,
+ resource: 'input-projection',
+ variant: sessionProjectionSnapshotVariant(authorityEpoch),
+ },
+ read,
+ );
+}
+
+type AsyncRead = () => Promise<unknown>;
+type ReadResults<Reads extends readonly AsyncRead[]> = {
+ [Index in keyof Reads]: Awaited<ReturnType<Reads[Index]>>;
+};
+
+/**
+ * Publishes authoritative session metadata as soon as that read succeeds,
+ * independently from sibling snapshots in the same opening batch.
+ */
+export async function runConnectionScopedSessionMetadataRead<T>(
+ read: () => Promise<T>,
+ isCurrent: () => boolean,
+ commit: (value: T) => void,
+): Promise<T> {
+ const value = await read();
+ if (isCurrent()) commit(value);
+ return value;
+}
+
+/**
+ * Applies retry to each read independently. One timeout therefore retries only
+ * that item instead of replaying every sibling request in the opening batch.
+ */
+export function runIndependentSnapshotReads<Reads extends readonly AsyncRead[]>(
+ reads: Reads,
+ retry: <T>(read: () => Promise<T>) => Promise<T>,
+): Promise<ReadResults<Reads>> {
+ return Promise.all(reads.map((read) => retry(read))) as Promise<
+ ReadResults<Reads>
+ >;
+}
diff --git a/apps/mobile/src/device-link/transientTopicSubscription.ts b/apps/mobile/src/device-link/transientTopicSubscription.ts
new file mode 100644
index 0000000000..5d5dc5714f
--- /dev/null
+++ b/apps/mobile/src/device-link/transientTopicSubscription.ts
@@ -0,0 +1,62 @@
+import { withTransientRemoteRetry } from '@/device-link/remoteRetry';
+
+type RetryOperation = <T>(operation: () => Promise<T>) => Promise<T>;
+
+export interface TransientTopicSubscriptionRequest {
+ /** Same recovery scope shares one retry loop; a new connection/session gets a new identity. */
+ identity: string;
+ /** Stops an old loop after route, connection epoch, or mounted-screen ownership changes. */
+ isStale(): boolean;
+ /** Rebuild the peer link before retrying a subscription that already failed once. */
+ reopenLink(): Promise<void>;
+ /** Register the local owner and wait for the remote subscription acknowledgement. */
+ subscribe(): Promise<void>;
+}
+
+export interface TransientTopicSubscriptionCoordinator {
+ start(request: TransientTopicSubscriptionRequest): Promise<void>;
+}
+
+/**
+ * Runs topic subscription recovery independently from snapshot reads.
+ *
+ * One recovery identity owns at most one physical retry loop. The first attempt
+ * reuses the link already prepared by the caller; later attempts reopen the
+ * peer link before subscribing again. Final failure is intentionally contained:
+ * snapshots remain usable even when the live topic cannot be restored yet.
+ */
+export function createTransientTopicSubscriptionCoordinator(
+ retry: RetryOperation = withTransientRemoteRetry,
+): TransientTopicSubscriptionCoordinator {
+ const inFlight = new Map<string, {
+ isStale(): boolean;
+ task: Promise<void>;
+ }>();
+
+ return {
+ start(request): Promise<void> {
+ const current = inFlight.get(request.identity);
+ if (current && !current.isStale()) return current.task;
+
+ let subscribeAttempted = false;
+ const task = retry(async () => {
+ if (request.isStale()) return;
+ if (subscribeAttempted) {
+ await request.reopenLink();
+ if (request.isStale()) return;
+ }
+ subscribeAttempted = true;
+ await request.subscribe();
+ }).catch(() => undefined);
+
+ const entry = { isStale: request.isStale, task };
+ inFlight.set(request.identity, entry);
+ void task.finally(() => {
+ if (inFlight.get(request.identity) === entry) {
+ inFlight.delete(request.identity);
+ }
+ });
+ return task;
+ },
+ };
+}
diff --git a/apps/mobile/src/session/sessionTailBannerModel.ts b/apps/mobile/src/session/sessionTailBannerModel.ts
index 7e730845ad..058093e912 100644
--- a/apps/mobile/src/session/sessionTailBannerModel.ts
+++ b/apps/mobile/src/session/sessionTailBannerModel.ts
@@ -64,6 +64,8 @@ export interface ResolveSessionTailBannerInput {
* (review P1 第五轮收敛,model 不再自己扫队列)。
*/
continuationInFlight: boolean;
+ /** 当前任务元数据已在本 relay 连接代完成权威同步。只门控双时间戳中断推断。 */
+ sessionMetadataSyncedForConnection: boolean;
/** interrupted 已被本视图操作过(继续/忽略)或本窗口内会话跑起来过 → 熄灭。 */
interruptAcked: boolean;
/**
@@ -104,6 +106,10 @@ export function resolveSessionTailBanner(input: ResolveSessionTailBannerInput):
// 历史中断行优先;无 error-tail 才轮到 session 双时间戳判定(对齐桌面互斥渲染)。
if (tail) return null;
+ // 连接恢复或首次打开时,store 可能先呈现上一代的 activeTurnStartedAt / lastTurnEndedAt。
+ // 在本代 session 元数据完成同步前,这两个时间戳不能证明任务真的中断;持久 error-tail
+ // 已在上面独立处理,不受此门影响。
+ if (!input.sessionMetadataSyncedForConnection) return null;
if (input.interruptAcked || !input.session) return null;
const started = input.session.activeTurnStartedAt ?? null;
if (!started) return null;
diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.ts
index 44eeb61651..3f6057c262 100644
--- a/packages/device-link/src/__tests__/client.test.ts
+++ b/packages/device-link/src/__tests__/client.test.ts
@@ -4,7 +4,12 @@
*/
import { describe, it, expect, vi } from 'vitest';
import { DeviceLinkClient, computeReconnectDelayMs, type WsLike } from '../client.js';
-import { PROTOCOL_VERSION, DeviceLinkError, type Envelope } from '../protocol.js';
+import {
+ PROTOCOL_VERSION,
+ DeviceLinkError,
+ type Envelope,
+ type LinkAcceptPayload,
+} from '../protocol.js';
import {
DEVICE_LINK_CAPABILITY_RELIABLE_LINK_CONFIRM,
DEVICE_LINK_CAPABILITY_RELIABLE_TRANSPORT,
@@ -775,6 +780,7 @@ describe('DeviceLinkClient', () => {
});
it('入站 link 的可靠重试耗尽只重置该 peer link:relay 连接不拆,发 transport-timeout link-close,重开后 live 帧按原 seq 重放', async () => {
+ const warn = vi.fn();
const h = makeHarness({
timing: {
pingIntervalMs: 60_000,
@@ -783,6 +789,7 @@ describe('DeviceLinkClient', () => {
transportRetryIntervalMs: 5,
transportMaxRetryAttempts: 2,
},
+ logger: { debug: vi.fn(), info: vi.fn(), warn, error: vi.fn() },
});
h.client.start();
await tick();
@@ -810,6 +817,9 @@ describe('DeviceLinkClient', () => {
expect(firstSocket.terminated).toBe(false);
expect(firstSocket.closed).toBeNull();
expect(h.sockets).toHaveLength(1);
+ expect(warn).toHaveBeenCalledWith(expect.stringMatching(
+ /ACK timeout; resetting peer link .*dst=dev-b seq=1 kind=push attempts=2 sent=true ageMs=\d+ pending=2\/\d+ ack=0 next=3 send=ready receive=true stream=.{8} remoteStream=inbound-/,
+ ));
// 对端重开链路 → 陈旧 push 前缀被清扫,live invoke-result 按原 seq 重放
const sentBefore = firstSocket.sent.length;
@@ -2368,6 +2378,27 @@ describe('DeviceLinkClient', () => {
h.client.stop();
});
+ it('可靠 push 被 latest-wins 驱逐后释放路由账本额度', async () => {
+ const h = makeHarness({
+ timing: { pingIntervalMs: 10_000, transportRetryIntervalMs: 60_000 },
+ });
+ h.client.start();
+ await tick();
+ h.current().ack();
+ await establishInboundReliableLink(h, 'route-ledger-eviction-stream');
+
+ // 不发送 transport ACK:队列保持在 64 条,但每次 latest-wins 驱逐的
+ // 可靠帧都必须从 active route ledger 转入 settled history;否则第
+ // 1025 个唯一 ID 会把后续发送永久打成 BACKPRESSURE。
+ expect(() => {
+ for (let index = 0; index < 1_025; index += 1) {
+ h.client.sendPush('dev-b', 'maker:event', { index });
+ }
+ }).not.toThrow();
+ expect(h.client.getReliableSendQueueDepth('dev-b')).toBe(MAX_TRANSPORT_PENDING_MESSAGES);
+ h.client.stop();
+ });
+
it('push 拥塞腾位不跨 live 帧:队头是 live invoke 时新 push 维持 BACKPRESSURE', async () => {
const warn = vi.fn();
const h = makeHarness({
@@ -3044,6 +3075,7 @@ describe('DeviceLinkClient', () => {
deviceId: 'dev-b',
state: 'offline',
connectionEpoch: expect.any(Number),
+ linkGeneration: expect.any(Number),
});
await expect(invoke).rejects.toMatchObject({ code: 'DEVICE_OFFLINE' });
h.client.stop();
@@ -3071,6 +3103,655 @@ describe('DeviceLinkClient', () => {
h.client.stop();
});
+ it('已移出发送额度的当前代 best-effort 帧仍能用带 id 错误收口 peer', async () => {
+ const h = makeHarness();
+ const routeChanges: unknown[] = [];
+ h.client.onPeerRouteStateChanged((change) => routeChanges.push(change));
+ h.client.start();
+ await tick();
+ h.current().ack();
+
+ h.client.sendPush('dev-b', 'maker:event', { current: true });
+ const sent = h.current().sent.find((env) => env.kind === 'push' && env.dst === 'dev-b')!;
+ h.current().push({
+ v: PROTOCOL_VERSION,
+ kind: 'relay-error',
+ id: sent.id,
+ payload: {
+ code: 'DEVICE_OFFLINE',
+ message: 'current best-effort route failed',
+ dst: 'dev-b',
+ },
+ });
+
+ expect(routeChanges).toHaveLength(1);
+ expect(routeChanges[0]).toMatchObject({ deviceId: 'dev-b', state: 'offline' });
+ h.client.stop();
+ });
+
+ it('同一 WebSocket 内旧可靠帧的迟到 DEVICE_OFFLINE 保留原 link 代次', async () => {
+ const h = makeHarness({ timing: { pingIntervalMs: 60_000 } });
+ const routeChanges: Array<{
+ deviceId: string;
+ state: 'offline';
+ connectionEpoch: number;
+ linkGeneration: number;
+ }> = [];
+ h.client.onPeerRouteStateChanged((change) => routeChanges.push(change));
+ h.client.start();
+ await tick();
+ h.current().ack();
+
+ await establishInboundReliableLink(h, 'controller-stream-old');
+ const oldGeneration = h.client.getPeerLinkGeneration('dev-b');
+ h.client.sendInvokeResult('dev-b', 'route-generation-replay', {
+ ok: true,
+ result: 'stale',
+ });
+ const oldFrame = h.current().sent.filter((env) => (
+ env.kind === 'invoke-result'
+ && env.id === 'route-generation-replay'
+ && parseTransportPayload(env.payload) !== null
+ )).at(-1)!;
+ expect(oldFrame.id).toBeTruthy();
+
+ await establishInboundReliableLink(h, 'controller-stream-new');
+ const currentGeneration = h.client.getPeerLinkGeneration('dev-b');
+ expect(currentGeneration).toBeGreaterThan(oldGeneration);
+ expect(h.client.isLinkReady('dev-b')).toBe(true);
+
+ h.current().push({
+ v: PROTOCOL_VERSION,
+ kind: 'relay-error',
+ id: oldFrame.id,
+ payload: {
+ code: 'DEVICE_OFFLINE',
+ message: 'delayed old route error',
+ dst: 'dev-b',
+ },
+ });
+
+ expect(routeChanges.at(-1)).toMatchObject({
+ deviceId: 'dev-b',
+ state: 'offline',
+ linkGeneration: oldGeneration,
+ });
+ expect(h.client.isLinkReady('dev-b')).toBe(true);
+
+ h.current().push({
+ v: PROTOCOL_VERSION,
+ kind: 'relay-error',
+ id: oldFrame.id,
+ payload: {
+ code: 'DEVICE_OFFLINE',
+ message: 'current replay route error',
+ dst: 'dev-b',
+ },
+ });
+
+ expect(routeChanges.at(-1)).toMatchObject({
+ deviceId: 'dev-b',
+ state: 'offline',
+ linkGeneration: currentGeneration,
+ });
+ expect(h.client.isLinkReady('dev-b')).toBe(false);
+ h.client.stop();
+ });
+
+ it('路由账本按 peer 限流且不淘汰仍未决的旧代归属', async () => {
+ const h = makeHarness({ timing: { pingIntervalMs: 60_000 } });
+ const routeChanges: Array<{
+ deviceId: string;
+ state: 'offline';
+ connectionEpoch: number;
+ linkGeneration: number;
+ }> = [];
+ h.client.onPeerRouteStateChanged((change) => routeChanges.push(change));
+ h.client.start();
+ await tick();
+ h.current().ack();
+
+ const internals = h.client as unknown as {
+ markPeerRouteOnline(deviceId: string): number;
+ rememberOutboundRouteGeneration(
+ id: string,
+ deviceId: string,
+ linkGeneration: number,
+ ): void;
+ };
+ const oldGeneration = internals.markPeerRouteOnline('dev-a');
+ const oldestRouteId = 'route-cap-0';
+ for (let index = 0; index < 1_024; index += 1) {
+ internals.rememberOutboundRouteGeneration(`route-cap-${index}`, 'dev-a', oldGeneration);
+ }
+
+ expect(() => {
+ internals.rememberOutboundRouteGeneration('route-cap-overflow', 'dev-a', oldGeneration);
+ }).toThrow(expect.objectContaining({ code: 'BACKPRESSURE' }));
+ expect(() => {
+ internals.rememberOutboundRouteGeneration('route-cap-independent', 'dev-b', 1);
+ }).not.toThrow();
+
+ const currentGeneration = internals.markPeerRouteOnline('dev-a');
+ expect(currentGeneration).toBeGreaterThan(oldGeneration);
+ h.current().push({
+ v: PROTOCOL_VERSION,
+ kind: 'relay-error',
+ id: oldestRouteId,
+ payload: {
+ code: 'DEVICE_OFFLINE',
+ message: 'delayed oldest route error after per-peer capacity is reached',
+ dst: 'dev-a',
+ },
+ });
+
+ expect(routeChanges.at(-1)).toMatchObject({
+ deviceId: 'dev-a',
+ state: 'offline',
+ linkGeneration: oldGeneration,
+ });
+ h.client.stop();
+ });
+
+ it('健康可靠链路在 ACK 后释放路由历史,不会把 1024 个成功 ID 变成永久配额', async () => {
+ const h = makeHarness({ timing: { pingIntervalMs: 60_000 } });
+ h.client.start();
+ await tick();
+ h.current().ack();
+ await establishInboundReliableLink(h, 'route-history-release');
+
+ for (let index = 0; index < 1_025; index += 1) {
+ const requestId = `route-history-success-${index}`;
+ h.client.sendInvokeResult('dev-b', requestId, { ok: true, result: index });
+ const frame = h.current().sent.filter((env) => (
+ env.kind === 'invoke-result'
+ && env.id === requestId
+ && parseTransportPayload(env.payload) !== null
+ )).at(-1)!;
+ const meta = parseTransportPayload(frame.payload)!.meta;
+ h.current().push({
+ v: PROTOCOL_VERSION,
+ kind: 'push',
+ src: 'dev-b',
+ payload: {
+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,
+ payload: { streamId: meta.streamId, ackSeq: meta.seq },
+ },
+ });
+ }
+
+ expect(h.client.getReliableSendQueueDepth('dev-b')).toBe(0);
+ expect(() => {
+ h.client.sendInvokeResult('dev-b', 'route-history-after-cap', {
+ ok: true,
+ result: 'still-sending',
+ });
+ }).not.toThrow();
+ h.client.stop();
+ });
+
+ it('健康 best-effort 链路持续发送超过 1024 个唯一 ID 也不会永久停发', async () => {
+ const h = makeHarness({ timing: { pingIntervalMs: 60_000 } });
+ h.client.start();
+ await tick();
+ h.current().ack();
+
+ expect(() => {
+ for (let index = 0; index < 1_025; index += 1) {
+ h.client.sendPush('dev-b', 'maker:event', { index });
+ }
+ }).not.toThrow();
+ expect(h.current().sent.filter((env) => env.kind === 'push' && env.dst === 'dev-b'))
+ .toHaveLength(1_025);
+ h.client.stop();
+ });
+
+ it('新代重放已 ACK 后迟到的旧代 DEVICE_OFFLINE 仍不拆当前 link', async () => {
+ const h = makeHarness({ timing: { pingIntervalMs: 60_000 } });
+ const routeChanges: Array<{
+ deviceId: string;
+ state: 'offline';
+ connectionEpoch: number;
+ linkGeneration: number;
+ }> = [];
+ h.client.onPeerRouteStateChanged((change) => routeChanges.push(change));
+ h.client.start();
+ await tick();
+ h.current().ack();
+
+ await establishInboundReliableLink(h, 'controller-stream-before-ack');
+ const oldGeneration = h.client.getPeerLinkGeneration('dev-b');
+ h.client.sendInvokeResult('dev-b', 'acked-replay-with-late-error', {
+ ok: true,
+ result: 'pending',
+ });
+ const oldFrame = h.current().sent.filter((env) => (
+ env.kind === 'invoke-result'
+ && env.id === 'acked-replay-with-late-error'
+ && parseTransportPayload(env.payload) !== null
+ )).at(-1)!;
+
+ await establishInboundReliableLink(h, 'controller-stream-after-ack');
+ const currentGeneration = h.client.getPeerLinkGeneration('dev-b');
+ expect(currentGeneration).toBeGreaterThan(oldGeneration);
+ const replayedFrame = h.current().sent.filter((env) => (
+ env.kind === 'invoke-result'
+ && env.id === oldFrame.id
+ && parseTransportPayload(env.payload) !== null
+ )).at(-1)!;
+ const replayedMeta = parseTransportPayload(replayedFrame.payload)!.meta;
+
+ h.current().push({
+ v: PROTOCOL_VERSION,
+ kind: 'push',
+ src: 'dev-b',
+ payload: {
+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,
+ payload: {
+ streamId: replayedMeta.streamId,
+ ackSeq: replayedMeta.seq,
+ },
+ },
+ });
+ expect(h.client.getReliableSendQueueDepth('dev-b')).toBe(0);
+
+ h.current().push({
+ v: PROTOCOL_VERSION,
+ kind: 'relay-error',
+ id: oldFrame.id,
+ payload: {
+ code: 'DEVICE_OFFLINE',
+ message: 'delayed old route error after current ACK',
+ dst: 'dev-b',
+ },
+ });
+
+ expect(routeChanges).toHaveLength(0);
+ expect(h.client.isLinkReady('dev-b')).toBe(true);
+ h.client.stop();
+ });
+
+ it.each(['DEVICE_OFFLINE', 'REMOTE_DISABLED'] as const)(
+ '旧代 %s 不终止新代正在重放的可靠 invoke',
+ async (code) => {
+ const h = makeHarness({ timing: { pingIntervalMs: 60_000, requestTimeoutMs: 1_000 } });
+ h.client.start();
+ await tick();
+ h.current().ack();
+
+ await establishInboundReliableLink(h, 'invoke-route-generation-old');
+ const oldGeneration = h.client.getPeerLinkGeneration('dev-b');
+ const invoke = h.client.invoke('dev-b', { channel: 'maker:write-once', args: ['value'] });
+ let settled = false;
+ void invoke.finally(() => { settled = true; });
+ const oldFrame = h.current().sent.filter((env) => (
+ env.kind === 'invoke'
+ && parseTransportPayload(env.payload) !== null
+ )).at(-1)!;
+
+ await establishInboundReliableLink(h, 'invoke-route-generation-new');
+ const currentGeneration = h.client.getPeerLinkGeneration('dev-b');
+ expect(currentGeneration).toBeGreaterThan(oldGeneration);
+ expect(h.current().sent.filter((env) => (
+ env.kind === 'invoke'
+ && env.id === oldFrame.id
+ && parseTransportPayload(env.payload) !== null
+ )).length).toBeGreaterThanOrEqual(2);
+
+ h.current().push({
+ v: PROTOCOL_VERSION,
+ kind: 'relay-error',
+ id: oldFrame.id,
+ payload: {
+ code,
+ message: 'delayed old invoke route error',
+ dst: 'dev-b',
+ },
+ });
+ await tick();
+
+ expect(settled).toBe(false);
+ expect(h.client.isLinkReady('dev-b')).toBe(true);
+ expect(h.client.getReliableSendQueueDepth('dev-b')).toBe(1);
+
+ h.current().push({
+ v: PROTOCOL_VERSION,
+ kind: 'invoke-result',
+ id: oldFrame.id,
+ src: 'dev-b',
+ payload: { ok: true, result: 'applied-once' },
+ });
+ await expect(invoke).resolves.toMatchObject({ ok: true, result: 'applied-once' });
+ h.client.stop();
+ },
+ );
+
+ it('入站 link confirmation 屏障清掉旧代成功尝试,当前重放错误按当前代收口', async () => {
+ const h = makeHarness({
+ timing: {
+ pingIntervalMs: 60_000,
+ requestTimeoutMs: 1_000,
+ transportRetryIntervalMs: 60_000,
+ },
+ });
+ const routeChanges: Array<{
+ deviceId: string;
+ state: 'offline';
+ connectionEpoch: number;
+ linkGeneration: number;
+ }> = [];
+ h.client.onPeerRouteStateChanged((change) => routeChanges.push(change));
+ h.client.start();
+ await tick();
+ h.current().ack();
+
+ const establishConfirmedInboundLink = async (streamId: string): Promise<void> => {
+ const sentBefore = h.current().sent.length;
+ await establishInboundReliableLink(h, streamId, 1, 'dev-b', [
+ DEVICE_LINK_CAPABILITY_RELIABLE_TRANSPORT,
+ DEVICE_LINK_CAPABILITY_RELIABLE_LINK_CONFIRM,
+ DEVICE_LINK_CAPABILITY_TRANSPORT_TIMEOUT_CLOSE,
+ ]);
+ const accept = h.current().sent.slice(sentBefore).find(
+ (env) => env.kind === 'link-accept',
+ );
+ expect(accept?.id).toBeTruthy();
+ const accepted = accept!.payload as LinkAcceptPayload;
+ expect(accepted.transportStreamId).toBeTruthy();
+ h.current().push({
+ v: PROTOCOL_VERSION,
+ kind: 'push',
+ src: 'dev-b',
+ payload: {
+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,
+ payload: {
+ streamId: accepted.transportStreamId!,
+ ackSeq: (accepted.transportBaseSeq ?? 1) - 1,
+ linkRequestId: accept!.id,
+ },
+ },
+ });
+ await tick();
+ expect(h.client.isLinkReady('dev-b')).toBe(true);
+ };
+
+ await establishConfirmedInboundLink('confirmed-inbound-old');
+ const oldGeneration = h.client.getPeerLinkGeneration('dev-b');
+ h.client.sendInvokeResult('dev-b', 'confirmed-inbound-replay', {
+ ok: true,
+ result: 'pending',
+ });
+ const originalFrame = h.current().sent.filter((env) => (
+ env.kind === 'invoke-result'
+ && env.id === 'confirmed-inbound-replay'
+ && parseTransportPayload(env.payload) !== null
+ )).at(-1)!;
+
+ const sentBeforeReopen = h.current().sent.length;
+ await establishConfirmedInboundLink('confirmed-inbound-new');
+ const currentGeneration = h.client.getPeerLinkGeneration('dev-b');
+ expect(currentGeneration).toBeGreaterThan(oldGeneration);
+ const replayedFrame = h.current().sent.slice(sentBeforeReopen).find((env) => (
+ env.kind === 'invoke-result'
+ && env.id === originalFrame.id
+ && parseTransportPayload(env.payload) !== null
+ ));
+ expect(replayedFrame).toBeTruthy();
+
+ h.current().push({
+ v: PROTOCOL_VERSION,
+ kind: 'relay-error',
+ id: originalFrame.id,
+ payload: {
+ code: 'DEVICE_OFFLINE',
+ message: 'current replay route error after confirmed inbound reopen',
+ dst: 'dev-b',
+ },
+ });
+
+ expect(routeChanges.at(-1)).toMatchObject({
+ deviceId: 'dev-b',
+ state: 'offline',
+ linkGeneration: currentGeneration,
+ });
+ expect(h.client.isLinkReady('dev-b')).toBe(false);
+ h.client.stop();
+ });
+
+ it('出站 link-accept 屏障清掉旧代成功尝试,当前重放的 DEVICE_OFFLINE 按当前代收口', async () => {
+ const h = makeHarness({
+ timing: {
+ pingIntervalMs: 60_000,
+ requestTimeoutMs: 1_000,
+ transportRetryIntervalMs: 60_000,
+ },
+ });
+ const routeChanges: Array<{
+ deviceId: string;
+ state: 'offline';
+ connectionEpoch: number;
+ linkGeneration: number;
+ }> = [];
+ h.client.onPeerRouteStateChanged((change) => routeChanges.push(change));
+ h.client.start();
+ await tick();
+ h.current().ack();
+
+ const open = h.client.openLink(
+ 'dev-b',
+ { controllerName: 'Test', protocolVersion: 1, appVersion: '1' },
+ 100,
+ );
+ const openFrame = h.current().sent.find((env) => env.kind === 'link-open')!;
+ h.current().push({
+ v: PROTOCOL_VERSION,
+ kind: 'link-accept',
+ id: openFrame.id,
+ src: 'dev-b',
+ payload: {
+ appVersion: '1',
+ allowlistHash: 'hash',
+ capabilities: [DEVICE_LINK_CAPABILITY_RELIABLE_TRANSPORT],
+ transportStreamId: 'outbound-route-old',
+ },
+ });
+ await open;
+
+ const oldGeneration = h.client.getPeerLinkGeneration('dev-b');
+ const invoke = h.client.invoke('dev-b', { channel: 'maker:current-route-error', args: [] });
+ const originalFrame = h.current().sent.filter((env) => (
+ env.kind === 'invoke'
+ && parseTransportPayload(env.payload) !== null
+ )).at(-1)!;
+
+ h.current().push({
+ v: PROTOCOL_VERSION,
+ kind: 'link-close',
+ src: 'dev-b',
+ payload: { reason: 'transport-timeout' },
+ });
+ await tick();
+
+ const sentBeforeReopen = h.current().sent.length;
+ const reopen = h.client.openLink(
+ 'dev-b',
+ { controllerName: 'Test', protocolVersion: 1, appVersion: '1' },
+ 100,
+ );
+ const reopenFrame = h.current().sent.slice(sentBeforeReopen).find(
+ (env) => env.kind === 'link-open',
+ )!;
+ h.current().push({
+ v: PROTOCOL_VERSION,
+ kind: 'link-accept',
+ id: reopenFrame.id,
+ src: 'dev-b',
+ payload: {
+ appVersion: '1',
+ allowlistHash: 'hash',
+ capabilities: [DEVICE_LINK_CAPABILITY_RELIABLE_TRANSPORT],
+ transportStreamId: 'outbound-route-old',
+ },
+ });
+ await reopen;
+
+ const currentGeneration = h.client.getPeerLinkGeneration('dev-b');
+ expect(currentGeneration).toBeGreaterThan(oldGeneration);
+ const replayedFrame = h.current().sent.slice(sentBeforeReopen).find((env) => (
+ env.kind === 'invoke'
+ && env.id === originalFrame.id
+ && parseTransportPayload(env.payload) !== null
+ ));
+ expect(replayedFrame).toBeTruthy();
+
+ h.current().push({
+ v: PROTOCOL_VERSION,
+ kind: 'relay-error',
+ id: originalFrame.id,
+ payload: {
+ code: 'DEVICE_OFFLINE',
+ message: 'current replay route error',
+ dst: 'dev-b',
+ },
+ });
+
+ await expect(invoke).rejects.toMatchObject({ code: 'DEVICE_OFFLINE' });
+ expect(routeChanges.at(-1)).toMatchObject({
+ deviceId: 'dev-b',
+ state: 'offline',
+ linkGeneration: currentGeneration,
+ });
+ expect(h.client.isLinkReady('dev-b')).toBe(false);
+ h.client.stop();
+ });
+
+ it('link down 时排队的可靠帧按首次物理发送代次处理 DEVICE_OFFLINE', async () => {
+ const h = makeHarness({ timing: { pingIntervalMs: 60_000 } });
+ const routeChanges: Array<{
+ deviceId: string;
+ state: 'offline';
+ connectionEpoch: number;
+ linkGeneration: number;
+ }> = [];
+ h.client.onPeerRouteStateChanged((change) => routeChanges.push(change));
+ h.client.start();
+ await tick();
+ h.current().ack();
+
+ await establishInboundReliableLink(h, 'controller-stream-before-queue');
+ const queuedGeneration = h.client.getPeerLinkGeneration('dev-b');
+ const internals = h.client as unknown as {
+ peerTransport: Map<string, { sendPhase: string; receiveReady: boolean }>;
+ };
+ internals.peerTransport.get('dev-b')!.sendPhase = 'down';
+ internals.peerTransport.get('dev-b')!.receiveReady = false;
+
+ const sentBeforeQueue = h.current().sent.length;
+ const queuedInvoke = h.client.invoke(
+ 'dev-b',
+ { channel: 'maker:queued-before-reopen', args: [] },
+ 1_000,
+ );
+ expect(h.current().sent.slice(sentBeforeQueue).some((env) => env.kind === 'invoke')).toBe(false);
+
+ await establishInboundReliableLink(h, 'controller-stream-after-queue');
+ const sentGeneration = h.client.getPeerLinkGeneration('dev-b');
+ expect(sentGeneration).toBeGreaterThan(queuedGeneration);
+ const replayedFrame = h.current().sent.slice(sentBeforeQueue).find((env) => (
+ env.kind === 'invoke'
+ && parseTransportPayload(env.payload) !== null
+ ));
+ expect(replayedFrame).toBeTruthy();
+
+ h.current().push({
+ v: PROTOCOL_VERSION,
+ kind: 'relay-error',
+ id: replayedFrame!.id,
+ payload: {
+ code: 'DEVICE_OFFLINE',
+ message: 'first physical send failed',
+ dst: 'dev-b',
+ },
+ });
+
+ expect(routeChanges.at(-1)).toMatchObject({
+ deviceId: 'dev-b',
+ state: 'offline',
+ linkGeneration: sentGeneration,
+ });
+ await expect(queuedInvoke).rejects.toMatchObject({ code: 'DEVICE_OFFLINE' });
+ expect(h.client.isLinkReady('dev-b')).toBe(false);
+ h.client.stop();
+ });
+
+ it('WebSocket 重连后重放帧的 DEVICE_OFFLINE 不消费旧连接发送代次', async () => {
+ const h = makeHarness({
+ timing: {
+ reconnectBaseMs: 5,
+ reconnectMaxMs: 5,
+ pingIntervalMs: 60_000,
+ },
+ });
+ const routeChanges: Array<{
+ deviceId: string;
+ state: 'offline';
+ connectionEpoch: number;
+ linkGeneration: number;
+ }> = [];
+ h.client.onPeerRouteStateChanged((change) => routeChanges.push(change));
+ h.client.start();
+ await tick();
+ h.current().ack();
+
+ await establishInboundReliableLink(h, 'controller-stream-before-reconnect');
+ const oldGeneration = h.client.getPeerLinkGeneration('dev-b');
+ h.client.sendInvokeResult('dev-b', 'replayed-after-websocket-reconnect', {
+ ok: true,
+ result: 'pending',
+ });
+ expect(h.current().sent.some((env) => (
+ env.kind === 'invoke-result'
+ && env.id === 'replayed-after-websocket-reconnect'
+ && parseTransportPayload(env.payload) !== null
+ ))).toBe(true);
+
+ const oldSocketCount = h.sockets.length;
+ h.current().emit('close', 1006);
+ await vi.waitFor(() => expect(h.sockets).toHaveLength(oldSocketCount + 1));
+ const reconnectedSocket = h.current();
+ reconnectedSocket.ack();
+ await tick();
+
+ await establishInboundReliableLink(h, 'controller-stream-after-reconnect');
+ const currentGeneration = h.client.getPeerLinkGeneration('dev-b');
+ expect(currentGeneration).toBeGreaterThan(oldGeneration);
+ const replayedFrame = reconnectedSocket.sent.find((env) => (
+ env.kind === 'invoke-result'
+ && env.id === 'replayed-after-websocket-reconnect'
+ && parseTransportPayload(env.payload) !== null
+ ));
+ expect(replayedFrame).toBeTruthy();
+
+ reconnectedSocket.push({
+ v: PROTOCOL_VERSION,
+ kind: 'relay-error',
+ id: replayedFrame!.id,
+ payload: {
+ code: 'DEVICE_OFFLINE',
+ message: 'replay target offline',
+ dst: 'dev-b',
+ },
+ });
+
+ expect(routeChanges.at(-1)).toMatchObject({
+ deviceId: 'dev-b',
+ state: 'offline',
+ linkGeneration: currentGeneration,
+ });
+ expect(h.client.isLinkReady('dev-b')).toBe(false);
+ h.client.stop();
+ });
+
it('可靠 link 收到 DEVICE_OFFLINE 后清空 pending,下次握手用 baseSeq 跨过', async () => {
const h = makeHarness({ timing: { pingIntervalMs: 1_000 } });
h.client.start();
@@ -3186,6 +3867,7 @@ describe('DeviceLinkClient', () => {
expect(h.current().terminated).toBe(false);
expect(h.client.getStatus()).toBe('online');
+ expect(h.client.isLinkReady('dev-b')).toBe(false);
h.client.stop();
});
diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.ts
index 79f425f682..9f4bc8d1bb 100644
--- a/packages/device-link/src/client.ts
+++ b/packages/device-link/src/client.ts
@@ -78,6 +78,15 @@ const COALESCIBLE_PUSH_CHANNELS: ReadonlySet<string> = new Set([
]);
/** push 拥塞驱逐告警的 per-peer 聚合窗口:洪峰期逐条 warn 本身就是新的风暴。 */
const PUSH_ADMISSION_DROP_LOG_INTERVAL_MS = 5_000;
+/** 单个 peer 的路由账本上限;满时拒绝新发送,绝不淘汰仍可能收到错误的旧记录。 */
+const MAX_OUTBOUND_ROUTE_IDS_PER_PEER = 1_024;
+/** 全 client 的硬上限;达到后同样以背压停发,不用别的 peer 的记录换空间。 */
+const MAX_OUTBOUND_ROUTE_IDS_TOTAL = 16_384;
+/** 同一逻辑帧跨 link generation 的记录上限;同代重发用计数压缩。 */
+const MAX_OUTBOUND_ROUTE_GENERATION_RUNS_PER_ID = 256;
+/** 已结算记录不占发送额度;仅保留近期代次供迟到 relay-error 归属。 */
+const MAX_SETTLED_OUTBOUND_ROUTE_IDS_PER_PEER = 1_024;
+const MAX_SETTLED_OUTBOUND_ROUTE_IDS_TOTAL = 16_384;
/**
* 该 push channel 是否属于可驱逐档(latest-wins 腾位的唯一判据入口)。
@@ -384,6 +393,8 @@ export interface DeviceLinkPeerRouteStateChanged {
deviceId: string;
state: 'offline';
connectionEpoch: number;
+ /** 本地已接受的 peer link 代次;同一 WebSocket 内重开也会递增。 */
+ linkGeneration: number;
}
/**
@@ -420,6 +431,8 @@ interface PendingRequest {
dst?: string;
/** 可靠 invoke 未 ACK 时可跨 relay 短断线继续等;其它请求立即失败。 */
reliableDst?: string;
+ /** 请求真正发出时所属的 peer link 代次,供迟到 relay-error 归属。 */
+ linkGeneration?: number;
}
interface PendingReliableMessage {
@@ -522,6 +535,8 @@ interface PeerTransportState {
pushAdmissionDropCount: number;
/** 上次输出 latest-wins 驱逐告警的单调时刻;0 表示从未输出。 */
pushAdmissionDropLogAt: number;
+ /** 同一 relay WebSocket 内每次接受 link-open/link-accept 都递增。 */
+ linkGeneration: number;
}
interface PendingInboundLinkOffer {
@@ -632,7 +647,24 @@ export class DeviceLinkClient {
(change: DeviceLinkPeerRouteStateChanged) => void
>();
/** Avoid emitting the same authoritative route failure once per queued frame. */
- private peerOfflineNotifiedEpoch = new Map<string, number>();
+ private peerOfflineNotifiedGeneration = new Map<
+ string,
+ { connectionEpoch: number; linkGeneration: number }
+ >();
+ /**
+ * relay-error 回带原帧 id;据此把迟到错误归回消息发出时的 peer link 代次。
+ * 未决记录受硬上限保护并参与发送背压;成功确认后直接释放,无法确认交付的
+ * best-effort / 超时帧移入不占发送额度的近期历史,迟到错误仍能按原代次归属。
+ * 跨 socket 时由 resetLinkStateForReconnect 清空;两份账本都不进入 wire protocol。
+ */
+ private outboundRouteGenerationByPeer = new Map<
+ string,
+ Map<string, Array<{ linkGeneration: number; count: number }>>
+ >();
+ private settledOutboundRouteGenerationByPeer = new Map<
+ string,
+ Map<string, Array<{ linkGeneration: number; count: number }>>
+ >();
constructor(opts: DeviceLinkClientOptions) {
this.opts = opts;
@@ -857,6 +889,11 @@ export class DeviceLinkClient {
return this.connEpoch;
}
+ /** Current accepted link generation for one peer within the WebSocket lifecycle. */
+ getPeerLinkGeneration(deviceId: string): number {
+ return this.peerTransport.get(deviceId)?.linkGeneration ?? 0;
+ }
+
/** Subscribe to typed peer route lifecycle changes (currently authoritative offline). */
onPeerRouteStateChanged(
cb: (change: DeviceLinkPeerRouteStateChanged) => void,
@@ -880,14 +917,24 @@ export class DeviceLinkClient {
return () => this.presenceHandlers.delete(cb);
}
- private notifyPeerRouteOffline(deviceId: string): void {
- if (this.peerOfflineNotifiedEpoch.get(deviceId) === this.connEpoch) return;
- this.peerOfflineNotifiedEpoch.set(deviceId, this.connEpoch);
+ private notifyPeerRouteOffline(deviceId: string, linkGeneration: number): void {
+ const notified = this.peerOfflineNotifiedGeneration.get(deviceId);
+ if (
+ notified?.connectionEpoch === this.connEpoch
+ && notified.linkGeneration === linkGeneration
+ ) {
+ return;
+ }
+ this.peerOfflineNotifiedGeneration.set(deviceId, {
+ connectionEpoch: this.connEpoch,
+ linkGeneration,
+ });
if (this.peerRouteStateHandlers.size === 0) return;
const change: DeviceLinkPeerRouteStateChanged = {
deviceId,
state: 'offline',
connectionEpoch: this.connEpoch,
+ linkGeneration,
};
for (const cb of this.peerRouteStateHandlers) {
try {
@@ -898,8 +945,11 @@ export class DeviceLinkClient {
}
}
- private markPeerRouteOnline(deviceId: string): void {
- this.peerOfflineNotifiedEpoch.delete(deviceId);
+ private markPeerRouteOnline(deviceId: string, linkGeneration?: number): number {
+ const peer = this.getPeerTransport(deviceId);
+ peer.linkGeneration = linkGeneration ?? peer.linkGeneration + 1;
+ this.peerOfflineNotifiedGeneration.delete(deviceId);
+ return peer.linkGeneration;
}
/** 订阅入站隧道帧(invoke / link-open / link-close / push / 未配对的响应帧) */
@@ -1055,7 +1105,7 @@ export class DeviceLinkClient {
// 已经清掉的可靠 pending 也绝不能在下一次 openLink 后复活。
if (this.status !== 'online') return;
try {
- this.sendEnvelope({
+ this.sendBestEffortRoutedEnvelope({
v: PROTOCOL_VERSION,
kind: 'link-close',
dst,
@@ -1088,7 +1138,7 @@ export class DeviceLinkClient {
// 超过单帧上限的大 result 只能靠可靠层分片,回落入队等 link 重建。
if (peer?.reliable && !this.isPeerSendReady(peer) && this.status === 'online') {
try {
- this.sendEnvelope(env);
+ this.sendBestEffortRoutedEnvelope(env);
peer.unlinkedLegacyResponseIds.delete(requestId);
return;
} catch (err) {
@@ -1124,7 +1174,8 @@ export class DeviceLinkClient {
if (peerSupportsReliable) {
this.dropDiscardablePendingPrefix(dst, peer, false, 'before link re-establishment replay');
}
- this.sendEnvelope({
+ const linkGeneration = peer.linkGeneration + 1;
+ const linkAcceptId = this.sendRoutedEnvelope({
v: PROTOCOL_VERSION,
kind: 'link-accept',
id: requestId,
@@ -1144,8 +1195,13 @@ export class DeviceLinkClient {
}
: {}),
},
- });
- this.markPeerRouteOnline(dst);
+ }, linkGeneration);
+ this.markPeerRouteOnline(dst, linkGeneration);
+ if (!peerSupportsLinkConfirm && linkAcceptId) {
+ // 旧端没有可等待的 confirmation;accept 是不可重放的单次控制帧,发送后
+ // 不把它变成永久历史配额;近期迟到错误仍可按原代次归属。
+ this.settleOutboundRouteAttemptsForId(dst, linkAcceptId);
+ }
if (matchingOffer) {
this.pendingInboundLinkOffers.delete(dst);
this.setPeerCapabilities(
@@ -1182,7 +1238,12 @@ export class DeviceLinkClient {
...(ownerStamp ? { ownerStamp } : {}),
};
if (channel === DEVICE_LINK_TRANSPORT_ACK_CHANNEL) {
- this.sendEnvelope({ v: PROTOCOL_VERSION, kind: 'push', dst, payload: pushPayload });
+ this.sendBestEffortRoutedEnvelope({
+ v: PROTOCOL_VERSION,
+ kind: 'push',
+ dst,
+ payload: pushPayload,
+ });
return;
}
this.sendPeerEnvelope({ v: PROTOCOL_VERSION, kind: 'push', dst, payload: pushPayload });
@@ -1236,6 +1297,7 @@ export class DeviceLinkClient {
return new Promise<Envelope>((resolve, reject) => {
const timer = setTimeout(() => {
this.pending.delete(id);
+ if (env.dst) this.settleOutboundRouteAttemptsForId(env.dst, id);
if (env.dst && env.kind === 'invoke') this.dropReliablePendingForRequest(env.dst, id);
logFinished('timeout');
reject(new DeviceLinkError('INVOKE_TIMEOUT', `no ${expectKind} within ${timeout}ms`));
@@ -1255,6 +1317,7 @@ export class DeviceLinkClient {
timer,
expectKind,
dst: env.dst,
+ linkGeneration: env.dst ? this.getPeerLinkGeneration(env.dst) : undefined,
});
try {
@@ -1266,7 +1329,7 @@ export class DeviceLinkClient {
if (pending) pending.reliableDst = outbound.dst;
}
} else {
- this.sendEnvelope(outbound);
+ this.sendRoutedEnvelope(outbound);
}
} catch (err) {
this.pending.delete(id);
@@ -1479,6 +1542,10 @@ export class DeviceLinkClient {
private resetLinkStateForReconnect(): void {
// hello 会从 host 读取完整最新状态;旧连接上尚未发出的覆盖型 patch 不跨世代重放。
this.clearPendingPresence();
+ // 旧 socket 的 relay-error 已被 connection epoch 守卫隔离,不可能再合法到达;
+ // 保留它的物理发送记录只会让新连接重放产生的错误先消费旧代次,误判为 stale。
+ this.outboundRouteGenerationByPeer.clear();
+ this.settledOutboundRouteGenerationByPeer.clear();
for (const peer of this.peerTransport.values()) {
this.markPeerLinkDown(peer);
peer.recoveryNeedsAck = true;
@@ -1902,7 +1969,17 @@ export class DeviceLinkClient {
'outbound-accept',
);
const peer = this.getPeerTransport(env.src);
- this.markPeerRouteOnline(env.src);
+ const acceptedLinkGeneration = this.markPeerRouteOnline(env.src);
+ // 这是本机先发送 link-open、对端收到后才可能返回的 accept。relay 对同一
+ // 来源连接严格按发送顺序处理,因此任何更早物理发送若会产生 route error,
+ // 错误必然排在这次 accept 之前;走到这里仍无错误的旧代记录就是已成功路由
+ // 但未收到 transport ACK 的尝试。重放前清掉它们,避免当前代真实错误被
+ // FIFO 错归给旧代。入站 link-open 的 sendLinkAccept 当下来自另一条来源
+ // 连接、尚不具备此屏障;仅新版 confirmation ACK 到达后再做同类清理。
+ this.discardOutboundRouteAttemptsBeforeGeneration(
+ env.src,
+ acceptedLinkGeneration,
+ );
peer.outboundExplicitlyClosed = false;
// 注意:不得在此将 linkAcceptedInbound 改回 false。互控场景下本机可能
// 既是对端的被控端(入站已 accept)又是其控制端(本帧 accept 出站
@@ -1921,6 +1998,7 @@ export class DeviceLinkClient {
}
}
}
+ if (p.dst && env.id) this.discardOutboundRouteAttemptsForId(p.dst, env.id);
this.pending.delete(env.id!);
p.resolve(env);
return true;
@@ -1935,21 +2013,50 @@ export class DeviceLinkClient {
);
const pending = env.id ? this.pending.get(env.id) : undefined;
const routeDeviceId = payload.dst ?? pending?.dst;
+ const rememberedGeneration = env.id
+ ? this.consumeOutboundRouteGeneration(env.id, routeDeviceId)
+ : undefined;
+ // 所有 routed frame 都在物理发送前登记。未决记录会在成功结算后转入
+ // 不占发送额度的近期历史;transport ACK 则确认逻辑 seq 已交付并释放记录。
+ // ACK / relay-error 都没有物理 attempt id,重试又复用同一逻辑 id:ACK 后再来的
+ // 同 id 错误无法区分「旧发送迟到」与「后续重试失败」。此时 fail-stale 忽略,
+ // 避免拆掉刚恢复的新 link 或让已在对端执行的 invoke 向用户报失败;精确关联需要
+ // wire 携带物理发送标识,由分层传输任务继续处理。
+ // 若两份账本都查不到且没有 legacy request generation,不回退成当前代拆 link。
+ const releasedOrSettledRouteError = !!env.id
+ && rememberedGeneration === undefined
+ && (pending?.reliableDst !== undefined || pending?.linkGeneration === undefined);
+ const routeLinkGeneration = rememberedGeneration
+ ?? (pending?.reliableDst ? undefined : pending?.linkGeneration)
+ ?? (routeDeviceId ? this.getPeerLinkGeneration(routeDeviceId) : 0);
+ const stalePeerRouteError = !!routeDeviceId
+ && (
+ releasedOrSettledRouteError
+ || routeLinkGeneration < this.getPeerLinkGeneration(routeDeviceId)
+ );
// DEVICE_OFFLINE is a peer route transition, not merely a rejected
// request. Emit it before the pending fast path so the host cannot
// miss it when the relay error is paired with an in-flight request.
- if (payload.code === 'DEVICE_OFFLINE' && routeDeviceId) {
- this.notifyPeerRouteOffline(routeDeviceId);
+ if (payload.code === 'DEVICE_OFFLINE' && routeDeviceId && !releasedOrSettledRouteError) {
+ this.notifyPeerRouteOffline(routeDeviceId, routeLinkGeneration);
+ }
+ // 同一个可靠 invoke 会在 peer link 重开后用原 request id 重放。旧代物理发送的
+ // terminal route error 可能晚于新代重放到达;它只负责消费上面的路由代次记录,
+ // 不能 reject 当前逻辑请求或把当前重放帧改成 skip,否则调用方会先看到失败、
+ // 而对端稍后仍可能执行成功。当前代错误仍走下方既有 fail-closed 收口。
+ if (pending?.reliableDst && terminalRouteFailure && stalePeerRouteError) {
+ return true;
}
if (env.id && pending) {
const p = pending;
this.pending.delete(env.id);
+ if (routeDeviceId) this.discardOutboundRouteAttemptsForId(routeDeviceId, env.id);
// relay-error 代表原 invoke 没有交付到 peer。若它占用了可靠 stream 的 seq,
// 不能只 reject 上层后把原请求留到重连重放,否则一个已向用户报错的写操作
// 可能稍后突然执行。永久断链错误丢弃该 peer 全部 pending、靠下次握手 baseSeq
// 跨过;其它单帧错误改成同 seq skip。
if (p.reliableDst) {
- if (terminalRouteFailure) {
+ if (terminalRouteFailure && !stalePeerRouteError) {
this.markPeerLinkDown(this.getPeerTransport(p.reliableDst));
this.abandonReliablePending(
p.reliableDst,
@@ -1962,7 +2069,7 @@ export class DeviceLinkClient {
p.reject(new DeviceLinkError(payload.code, payload.message));
return true;
}
- if (payload.dst && terminalRouteFailure) {
+ if (payload.dst && terminalRouteFailure && !stalePeerRouteError) {
const peer = this.getPeerTransport(payload.dst);
this.markPeerLinkDown(peer);
peer.recoveryNeedsAck = true;
@@ -2397,9 +2504,10 @@ export class DeviceLinkClient {
private sendPeerEnvelope(env: Envelope, allowClosedLegacyResponse = false): boolean {
if (!env.dst || !isReliableKind(env.kind)) {
- this.sendEnvelope(env);
+ this.sendBestEffortRoutedEnvelope(env);
return false;
}
+ const routedEnv: Envelope = env.id ? env : { ...env, id: createRequestId() };
const peer = this.getPeerTransport(env.dst);
if (
peer.explicitlyClosed
@@ -2410,7 +2518,10 @@ export class DeviceLinkClient {
throw new DeviceLinkError('LINK_NOT_OPEN', 'control link is closed');
}
if (!peer.reliable) {
- this.sendEnvelope(env);
+ this.sendRoutedEnvelope(routedEnv);
+ if (!this.pending.has(routedEnv.id!)) {
+ this.settleOutboundRouteAttemptsForId(env.dst, routedEnv.id!);
+ }
return false;
}
@@ -2436,12 +2547,12 @@ export class DeviceLinkClient {
let reservedBytes: number;
try {
frames = encodeReliableFrames(
- env,
+ routedEnv,
peer.streamId,
seq,
this.getTransportBaseSeq(peer),
);
- reservedBytes = this.measurePendingReservation(env, peer.streamId, seq);
+ reservedBytes = this.measurePendingReservation(routedEnv, peer.streamId, seq);
} catch (err) {
throw new DeviceLinkError(
'PAYLOAD_TOO_LARGE',
@@ -2462,12 +2573,12 @@ export class DeviceLinkClient {
this.assertWebSocketCapacity(this.measureReliableFrames(frames));
}
if (!hasPendingCapacity()) {
- if (env.kind === 'invoke-result') {
+ if (routedEnv.kind === 'invoke-result') {
// invoke-result 是控制端确认被控端存活的唯一凭据,绝不能被堆积的可丢弃
// 帧饿死:丢弃整个队头可丢弃前缀(fresh push 一并放弃——单 FIFO 无法同时
// 做到 push 无损与 result 抢占),让 result 成为最早可交付的 live seq。
this.dropDiscardablePendingPrefix(env.dst, peer, false, 'to make room for invoke-result');
- } else if (env.kind === 'push' && isCoalesciblePushEnvelope(env)) {
+ } else if (routedEnv.kind === 'push' && isCoalesciblePushEnvelope(routedEnv)) {
// 可合并镜像 push(COALESCIBLE_PUSH_CHANNELS)是尽力而为的状态镜像
// (控制端重连/回前台会整体 resync + 重新订阅)。拥塞即对端未在 ACK:
// 2026-08-07 线上该形态一小时内 5168 次连续 BACKPRESSURE(maker:event),
@@ -2494,7 +2605,7 @@ export class DeviceLinkClient {
// (ws 容量已在驱逐前预检)。
const pending: PendingReliableMessage = {
seq,
- envelope: env,
+ envelope: routedEnv,
bytes: reservedBytes,
attempts: 0,
lastSentAt: 0,
@@ -2539,7 +2650,9 @@ export class DeviceLinkClient {
let sent = 0;
try {
for (const frame of frames) {
- this.sendEnvelope(frame);
+ // pending 可在 link down 时入队,并在后续 link generation 才首次上网;
+ // 路由错误必须归属每次真实物理发送,而不是逻辑消息的入队代次。
+ this.sendRoutedEnvelope(frame, peer.linkGeneration);
pending.sent = true;
sent += 1;
}
@@ -2603,6 +2716,221 @@ export class DeviceLinkClient {
ws.send(text);
}
+ private sendRoutedEnvelope(env: Envelope, linkGeneration?: number): string | undefined {
+ if (!env.dst) {
+ this.sendEnvelope(env);
+ return env.id;
+ }
+ const routed: Envelope = env.id ? env : { ...env, id: createRequestId() };
+ const generation = linkGeneration ?? this.getPeerLinkGeneration(env.dst);
+ this.rememberOutboundRouteGeneration(routed.id!, env.dst, generation);
+ try {
+ this.sendEnvelope(routed);
+ } catch (err) {
+ this.rollbackOutboundRouteGeneration(routed.id!, env.dst, generation);
+ throw err;
+ }
+ return routed.id;
+ }
+
+ private sendBestEffortRoutedEnvelope(env: Envelope, linkGeneration?: number): void {
+ const routedId = this.sendRoutedEnvelope(env, linkGeneration);
+ if (env.dst && routedId) this.settleOutboundRouteAttemptsForId(env.dst, routedId);
+ }
+
+ private rememberOutboundRouteGeneration(
+ id: string,
+ deviceId: string,
+ linkGeneration: number,
+ ): void {
+ let peerAttempts = this.outboundRouteGenerationByPeer.get(deviceId);
+ const generationRuns = peerAttempts?.get(id);
+ if (!generationRuns) {
+ const totalIds = Array.from(this.outboundRouteGenerationByPeer.values()).reduce(
+ (sum, attempts) => sum + attempts.size,
+ 0,
+ );
+ if (
+ (peerAttempts?.size ?? 0) >= MAX_OUTBOUND_ROUTE_IDS_PER_PEER
+ || totalIds >= MAX_OUTBOUND_ROUTE_IDS_TOTAL
+ ) {
+ throw new DeviceLinkError(
+ 'BACKPRESSURE',
+ `route attempt history is full for peer ${deviceId.slice(0, 8)}`,
+ );
+ }
+ if (!peerAttempts) {
+ peerAttempts = new Map();
+ this.outboundRouteGenerationByPeer.set(deviceId, peerAttempts);
+ }
+ peerAttempts.set(id, [{ linkGeneration, count: 1 }]);
+ return;
+ }
+ const latest = generationRuns.at(-1);
+ if (latest?.linkGeneration === linkGeneration) {
+ latest.count += 1;
+ return;
+ }
+ if (generationRuns.length >= MAX_OUTBOUND_ROUTE_GENERATION_RUNS_PER_ID) {
+ throw new DeviceLinkError(
+ 'BACKPRESSURE',
+ `route generation history is full for peer ${deviceId.slice(0, 8)}`,
+ );
+ }
+ generationRuns.push({ linkGeneration, count: 1 });
+ }
+
+ private consumeOutboundRouteGeneration(id: string, deviceId?: string): number | undefined {
+ const ledgers = [
+ this.settledOutboundRouteGenerationByPeer,
+ this.outboundRouteGenerationByPeer,
+ ];
+ let resolvedDeviceId = deviceId;
+ let owningLedger: typeof this.outboundRouteGenerationByPeer | undefined;
+ let peerAttempts: Map<string, Array<{ linkGeneration: number; count: number }>> | undefined;
+ for (const ledger of ledgers) {
+ if (resolvedDeviceId) {
+ const candidate = ledger.get(resolvedDeviceId);
+ if (candidate?.has(id)) {
+ owningLedger = ledger;
+ peerAttempts = candidate;
+ break;
+ }
+ continue;
+ }
+ for (const [candidateDeviceId, candidateAttempts] of ledger) {
+ if (!candidateAttempts.has(id)) continue;
+ resolvedDeviceId = candidateDeviceId;
+ owningLedger = ledger;
+ peerAttempts = candidateAttempts;
+ break;
+ }
+ if (peerAttempts) break;
+ }
+ const generationRuns = peerAttempts?.get(id);
+ const first = generationRuns?.[0];
+ if (
+ !owningLedger
+ || !peerAttempts
+ || !generationRuns
+ || !first
+ || !resolvedDeviceId
+ ) return undefined;
+ const linkGeneration = first.linkGeneration;
+ first.count -= 1;
+ if (first.count === 0) generationRuns.shift();
+ if (generationRuns.length === 0) peerAttempts.delete(id);
+ if (peerAttempts.size === 0) owningLedger.delete(resolvedDeviceId);
+ return linkGeneration;
+ }
+
+ private discardOutboundRouteAttemptsBeforeGeneration(
+ deviceId: string,
+ minimumGeneration: number,
+ ): void {
+ for (const ledger of [
+ this.outboundRouteGenerationByPeer,
+ this.settledOutboundRouteGenerationByPeer,
+ ]) {
+ const peerAttempts = ledger.get(deviceId);
+ if (!peerAttempts) continue;
+ for (const [id, generationRuns] of peerAttempts) {
+ const retained = generationRuns.filter(
+ (run) => run.linkGeneration >= minimumGeneration,
+ );
+ if (retained.length === 0) {
+ peerAttempts.delete(id);
+ } else if (retained.length !== generationRuns.length) {
+ peerAttempts.set(id, retained);
+ }
+ }
+ if (peerAttempts.size === 0) ledger.delete(deviceId);
+ }
+ }
+
+ private discardOutboundRouteAttemptsForId(deviceId: string, id: string): void {
+ for (const ledger of [
+ this.outboundRouteGenerationByPeer,
+ this.settledOutboundRouteGenerationByPeer,
+ ]) {
+ const peerAttempts = ledger.get(deviceId);
+ if (!peerAttempts) continue;
+ peerAttempts.delete(id);
+ if (peerAttempts.size === 0) ledger.delete(deviceId);
+ }
+ }
+
+ private settleOutboundRouteAttemptsForId(deviceId: string, id: string): void {
+ const activePeerAttempts = this.outboundRouteGenerationByPeer.get(deviceId);
+ const activeRuns = activePeerAttempts?.get(id);
+ if (!activePeerAttempts || !activeRuns) return;
+ activePeerAttempts.delete(id);
+ if (activePeerAttempts.size === 0) this.outboundRouteGenerationByPeer.delete(deviceId);
+
+ let settledPeerAttempts = this.settledOutboundRouteGenerationByPeer.get(deviceId);
+ if (!settledPeerAttempts) {
+ settledPeerAttempts = new Map();
+ this.settledOutboundRouteGenerationByPeer.set(deviceId, settledPeerAttempts);
+ }
+ const settledRuns = settledPeerAttempts.get(id) ?? [];
+ for (const run of activeRuns) {
+ const latest = settledRuns.at(-1);
+ if (latest?.linkGeneration === run.linkGeneration) {
+ latest.count += run.count;
+ } else {
+ settledRuns.push({ ...run });
+ }
+ }
+ while (settledRuns.length > MAX_OUTBOUND_ROUTE_GENERATION_RUNS_PER_ID) {
+ settledRuns.shift();
+ }
+ // Map 插入顺序作为 LRU;已结算历史只用于识别迟到错误,不参与发送背压。
+ settledPeerAttempts.delete(id);
+ settledPeerAttempts.set(id, settledRuns);
+ this.trimSettledOutboundRouteHistory();
+ }
+
+ private trimSettledOutboundRouteHistory(): void {
+ for (const [deviceId, peerAttempts] of this.settledOutboundRouteGenerationByPeer) {
+ while (peerAttempts.size > MAX_SETTLED_OUTBOUND_ROUTE_IDS_PER_PEER) {
+ const oldestId = peerAttempts.keys().next().value as string | undefined;
+ if (!oldestId) break;
+ peerAttempts.delete(oldestId);
+ }
+ if (peerAttempts.size === 0) this.settledOutboundRouteGenerationByPeer.delete(deviceId);
+ }
+ let totalIds = Array.from(this.settledOutboundRouteGenerationByPeer.values()).reduce(
+ (sum, attempts) => sum + attempts.size,
+ 0,
+ );
+ if (totalIds <= MAX_SETTLED_OUTBOUND_ROUTE_IDS_TOTAL) return;
+ for (const [deviceId, peerAttempts] of this.settledOutboundRouteGenerationByPeer) {
+ while (peerAttempts.size > 0 && totalIds > MAX_SETTLED_OUTBOUND_ROUTE_IDS_TOTAL) {
+ const oldestId = peerAttempts.keys().next().value as string | undefined;
+ if (!oldestId) break;
+ peerAttempts.delete(oldestId);
+ totalIds -= 1;
+ }
+ if (peerAttempts.size === 0) this.settledOutboundRouteGenerationByPeer.delete(deviceId);
+ if (totalIds <= MAX_SETTLED_OUTBOUND_ROUTE_IDS_TOTAL) break;
+ }
+ }
+
+ private rollbackOutboundRouteGeneration(
+ id: string,
+ deviceId: string,
+ linkGeneration: number,
+ ): void {
+ const peerAttempts = this.outboundRouteGenerationByPeer.get(deviceId);
+ const generationRuns = peerAttempts?.get(id);
+ const latest = generationRuns?.at(-1);
+ if (!peerAttempts || !generationRuns || latest?.linkGeneration !== linkGeneration) return;
+ latest.count -= 1;
+ if (latest.count === 0) generationRuns.pop();
+ if (generationRuns.length === 0) peerAttempts.delete(id);
+ if (peerAttempts.size === 0) this.outboundRouteGenerationByPeer.delete(deviceId);
+ }
+
private assertWebSocketCapacity(additionalBytes: number): void {
const ws = this.ws;
if (!ws) throw new DeviceLinkError('NOT_CONNECTED', 'no active connection');
@@ -2664,6 +2992,7 @@ export class DeviceLinkClient {
recoveryFramesSent: 0,
pushAdmissionDropCount: 0,
pushAdmissionDropLogAt: 0,
+ linkGeneration: 0,
};
this.peerTransport.set(dst, peer);
}
@@ -2844,9 +3173,15 @@ export class DeviceLinkClient {
: undefined
);
try {
- this.sendEnvelope(makeTransportAck(dst, streamId, ackSeq, effectiveLinkRequestId));
+ this.sendBestEffortRoutedEnvelope(
+ makeTransportAck(dst, streamId, ackSeq, effectiveLinkRequestId),
+ );
} catch (err) {
- this.log.debug('reliable transport ACK send failed', err);
+ this.log.debug(
+ `reliable transport ACK send failed dst=${dst.slice(0, 8)}`
+ + ` stream=${streamId.slice(0, 8)} ack=${ackSeq} conn=${this.connEpoch}`,
+ err,
+ );
}
}
@@ -2923,6 +3258,12 @@ export class DeviceLinkClient {
+ ` stream=${peer.streamId.slice(0, 8)} request=${confirmation.requestId.slice(0, 8)}`
+ ` ack=${ackSeq} conn=${this.connEpoch}`,
);
+ // 新版入站重建的带 request id ACK 是 local → remote 的因果屏障:对端已经
+ // 收到本代 link-accept,旧代成功路由却未 ACK 的尝试不会再产生 relay-error。
+ // 必须在重放前淘汰旧代记录,否则当前重放真实失败会 FIFO 消费旧代并被当
+ // stale。旧端没有 confirmation 能力时没有这个证据,继续保留原兼容路径。
+ this.discardOutboundRouteAttemptsBeforeGeneration(src, peer.linkGeneration);
+ this.discardOutboundRouteAttemptsForId(src, confirmation.requestId);
this.commitReliableSendResume(src, peer, confirmation.resume);
}
if (!this.isPeerSendReady(peer)) return;
@@ -2933,6 +3274,9 @@ export class DeviceLinkClient {
peer.highestAckSeq = ackSeq;
for (const [seq, pending] of peer.pending) {
if (seq > ackSeq) break;
+ if (pending.envelope.id) {
+ this.discardOutboundRouteAttemptsForId(src, pending.envelope.id);
+ }
peer.pending.delete(seq);
peer.pendingBytes -= pending.bytes;
}
@@ -3031,6 +3375,13 @@ export class DeviceLinkClient {
seq: number,
pending: PendingReliableMessage,
): void {
+ // A reliable frame can be evicted without ever receiving a transport ACK
+ // (latest-wins / TTL / skip-prefix cleanup). Keep its physical-send
+ // generations in the bounded settled ledger so a delayed relay error can
+ // still be classified, while releasing the active 1024-ID send budget.
+ if (pending.envelope.dst && pending.envelope.id) {
+ this.settleOutboundRouteAttemptsForId(pending.envelope.dst, pending.envelope.id);
+ }
peer.pending.delete(seq);
peer.pendingBytes -= pending.bytes;
if (peer.pending.size === 0 && peer.retryTimer) {
@@ -3394,7 +3745,8 @@ export class DeviceLinkClient {
return;
}
this.log.warn(
- `reliable transport ACK timeout for ${dst.slice(0, 8)} seq=${seq}; resetting peer link (relay connection kept alive)`,
+ `reliable transport ACK timeout; resetting peer link (relay connection kept alive)`
+ + ` ${this.describeReliableTimeout(dst, seq, peer)}`,
);
this.markPeerLinkDown(peer);
if (peer.retryTimer) {
@@ -3418,7 +3770,7 @@ export class DeviceLinkClient {
*/
private notifyTransportTimeoutClose(dst: string, attempt: number): void {
try {
- this.sendEnvelope({
+ this.sendBestEffortRoutedEnvelope({
v: PROTOCOL_VERSION,
kind: 'link-close',
dst,
@@ -3488,8 +3840,10 @@ export class DeviceLinkClient {
private forceReconnectForReliableTimeout(dst: string, seq: number): void {
if (this.stopped || this.status !== 'online') return;
+ const peer = this.peerTransport.get(dst);
this.log.warn(
- `reliable transport ACK timeout for ${dst.slice(0, 8)} seq=${seq}; forcing reconnect`,
+ `reliable transport ACK timeout; forcing reconnect`
+ + ` ${this.describeReliableTimeout(dst, seq, peer)}`,
);
const ws = this.ws;
this.ws = null;
@@ -3498,6 +3852,36 @@ export class DeviceLinkClient {
this.handleDisconnect(1006, 'reliable transport retry exhausted');
}
+ /**
+ * Final timeout evidence only: no payload or full device identifiers. This
+ * separates "ACK never advanced" from an ACK send exception and records the
+ * exact peer/link phase without adding a warning on every 2s retry tick.
+ */
+ private describeReliableTimeout(
+ dst: string,
+ seq: number,
+ peer: PeerTransportState | undefined,
+ ): string {
+ if (!peer) {
+ return `dst=${dst.slice(0, 8)} seq=${seq} peer=missing conn=${this.connEpoch}`;
+ }
+ const pending = peer.pending.get(seq)
+ ?? (peer.pending.values().next().value as PendingReliableMessage | undefined);
+ const ageMs = pending
+ ? Math.max(0, Math.round(this.monotonicNow() - pending.enqueuedAt))
+ : -1;
+ return `dst=${dst.slice(0, 8)} seq=${seq}`
+ + ` kind=${pending?.envelope.kind ?? 'missing'}`
+ + ` attempts=${pending?.attempts ?? -1} sent=${pending?.sent ?? false} ageMs=${ageMs}`
+ + ` pending=${peer.pending.size}/${peer.pendingBytes}`
+ + ` ack=${peer.highestAckSeq} next=${peer.nextSeq}`
+ + ` send=${peer.sendPhase} receive=${peer.receiveReady}`
+ + ` stream=${peer.streamId.slice(0, 8)}`
+ + ` remoteStream=${peer.remoteStreamId?.slice(0, 8) ?? 'none'}`
+ + ` recovery=${peer.recoveryNeedsAck}/${peer.recoveryFramesSent}`
+ + ` conn=${this.connEpoch}`;
+ }
+
private abandonReliablePending(dst: string, message: string): void {
const peer = this.peerTransport.get(dst);
if (peer) {
@@ -3505,6 +3889,11 @@ export class DeviceLinkClient {
clearInterval(peer.retryTimer);
peer.retryTimer = null;
}
+ for (const pending of peer.pending.values()) {
+ if (pending.envelope.id) {
+ this.settleOutboundRouteAttemptsForId(dst, pending.envelope.id);
+ }
+ }
peer.pending.clear();
peer.pendingBytes = 0;
}
@@ -3525,6 +3914,7 @@ export class DeviceLinkClient {
for (const [id, pending] of this.pending) {
if (pending.expectKind !== 'link-accept' || pending.dst !== dst) continue;
this.pending.delete(id);
+ this.settleOutboundRouteAttemptsForId(dst, id);
pending.reject(new DeviceLinkError(code, message));
}
}
@@ -3538,6 +3928,9 @@ export class DeviceLinkClient {
}
}
this.peerTransport.clear();
+ this.peerOfflineNotifiedGeneration.clear();
+ this.outboundRouteGenerationByPeer.clear();
+ this.settledOutboundRouteGenerationByPeer.clear();
for (const timer of this.timeoutCloseNotifyTimers.values()) clearTimeout(timer);
this.timeoutCloseNotifyTimers.clear();
}