Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(device-link): 避免恢复时重放过期请求并完善连接诊断 (#5232)
Dashc26033b7b151
diff --git a/apps/mobile/src/__tests__/expo-application.mock.ts b/apps/mobile/src/__tests__/expo-application.mock.tsindex 34ca050bb4..0ff90a1d09 100644--- a/apps/mobile/src/__tests__/expo-application.mock.ts+++ b/apps/mobile/src/__tests__/expo-application.mock.ts@@ -1 +1,2 @@export const nativeApplicationVersion: string | null = null;+export const nativeBuildVersion: string | null = null;diff --git a/apps/mobile/src/__tests__/historyViewProvider.test.tsx b/apps/mobile/src/__tests__/historyViewProvider.test.tsxindex 606e2da127..cd68257d75 100644--- a/apps/mobile/src/__tests__/historyViewProvider.test.tsx+++ b/apps/mobile/src/__tests__/historyViewProvider.test.tsx@@ -43,6 +43,7 @@ vi.mock('expo-network', () => ({ addNetworkStateListener: (listener: typeof netwvi.mock('expo-secure-store', () => ({getItemAsync: vi.fn(async () => null), setItemAsync: vi.fn(async () => {}), deleteItemAsync: vi.fn(async () => {}),}));+vi.mock('expo-updates', () => ({ updateId: null, runtimeVersion: null, isEmbeddedLaunch: true }));vi.mock('@react-native-async-storage/async-storage', () => ({ default: {getItem: vi.fn(async () => null), setItem: vi.fn(async () => {}), removeItem: vi.fn(async () => {}),getAllKeys: vi.fn(async () => []), multiRemove: vi.fn(async () => {}),diff --git a/apps/mobile/src/__tests__/remoteResources.test.ts b/apps/mobile/src/__tests__/remoteResources.test.tsindex f4fe2bb2c1..764a836d27 100644--- a/apps/mobile/src/__tests__/remoteResources.test.ts+++ b/apps/mobile/src/__tests__/remoteResources.test.ts@@ -57,10 +57,24 @@ describe('remote resource discovery', () => {{ deviceId: 'mac-2', name: 'Laptop', canOpen: false, state: 'access_revoked' },{ deviceId: 'mac-3', name: 'Disabled', canOpen: false, state: 'remote_disabled' },], previous);- expect(selected).toEqual([targets[0]]);+ expect(selected).toEqual([{ ...targets[0], offline: true }]);const invoke = vi.fn(async () => { throw new Error('offline'); }) as RemoteInvoke;const collections = await discoverRemoteHomeCollections(invoke, selected, 'en', previous);expect(collections[0]?.targets).toEqual([targets[0]]);+ expect(invoke).not.toHaveBeenCalled();+ });++ it('refreshes an offline cached host when it comes online and removes an empty manifest', async () => {+ const previous = [{ id: 'teammates', title: 'Teammates', resourceKind: 'bot', placement: 'home-scope', targets }];+ const selected = remoteResourceDiscoveryTargets([+ { deviceId: 'mac-1', name: 'Studio', canOpen: true, state: 'online' },+ { deviceId: 'mac-2', name: 'Laptop', canOpen: false, state: 'offline' },+ ], previous);+ const invoke = vi.fn(async () => ({ protocolVersion: 1, collections: [] })) as RemoteInvoke;+ const collections = await discoverRemoteHomeCollections(invoke, selected, 'en', previous);+ expect(invoke).toHaveBeenCalledTimes(1);+ expect(invoke).toHaveBeenCalledWith('mac-1', 'maker:remote-resources:manifest', expect.any(Array));+ expect(collections).toEqual([{ ...previous[0], iconName: undefined, targets: [targets[1]] }]);});it('advertises only primitives implemented by the current mobile shell', () => {diff --git a/apps/mobile/src/debug/diagnosticEvents.ts b/apps/mobile/src/debug/diagnosticEvents.tsindex c5c8d72039..beee044dc1 100644--- a/apps/mobile/src/debug/diagnosticEvents.ts+++ b/apps/mobile/src/debug/diagnosticEvents.ts@@ -33,6 +33,8 @@ const numericKeys = ["operation","elapsedMs","foregroundElapsedMs",+ "wallElapsedMs",+ "lifecycleElapsedMs","count",];const phases = ["subscription", "history", "pending", "projection", "goal"];diff --git a/apps/mobile/src/debug/localDiagnostics.test.ts b/apps/mobile/src/debug/localDiagnostics.test.tsindex 9edf6b3f76..8a29ddb130 100644--- a/apps/mobile/src/debug/localDiagnostics.test.ts+++ b/apps/mobile/src/debug/localDiagnostics.test.ts@@ -56,6 +56,29 @@ beforeEach(() => {files.available.mockReset().mockResolvedValue(true);});describe("local journal persistence", () => {+ it("records both clocks and lifecycle distance for a foreground timer gap", async () => {+ vi.useFakeTimers();+ let now = 100;+ const clock = vi.spyOn(performance, 'now').mockImplementation(() => now);+ const log = await import('./localDiagnostics');+ const stop = log.startLocalDiagnostics();+ try {+ await log.hydrateDiagnostics();+ now += 80_000;+ vi.setSystemTime(Date.now() + 100_000);+ await vi.advanceTimersByTimeAsync(2_000);+ expect((await log.diagnosticSnapshot()).find(event => event.event === 'js stall')?.fields)+ .toEqual({ elapsedMs: 78_000, wallElapsedMs: 100_000, lifecycleElapsedMs: 80_000 });+ const change = lifecycle.listen.mock.calls[0][1];+ change('background');+ now += 600_000;+ await vi.advanceTimersByTimeAsync(2_000);+ change('active');+ now += 2_000;+ await vi.advanceTimersByTimeAsync(2_000);+ expect((await log.diagnosticSnapshot()).filter(event => event.event === 'js stall')).toHaveLength(1);+ } finally { stop(); clock.mockRestore(); }+ });it.each([false, true])("stops collection throughout a delayed opt-out (save fails: %s)",async (fails) => {diff --git a/apps/mobile/src/debug/localDiagnostics.ts b/apps/mobile/src/debug/localDiagnostics.tsindex 805b299546..e204d433d7 100644--- a/apps/mobile/src/debug/localDiagnostics.ts+++ b/apps/mobile/src/debug/localDiagnostics.ts@@ -237,6 +237,8 @@ export function startLocalDiagnostics(): () => void {let stopped = false;let state = AppState.currentState;let lastTick = performance.now();+ let lastWallTick = Date.now();+ let lifecycleAt = lastTick;void hydrateDiagnostics().then(() => {if (!stopped)mobileDebugLog("info", "lifecycle", "app started", { appState: state });@@ -245,6 +247,8 @@ export function startLocalDiagnostics(): () => void {if (next === "active") prune();state = next;lastTick = performance.now();+ lastWallTick = Date.now();+ lifecycleAt = lastTick;mobileDebugLog("info", "lifecycle", `app ${next}`);void flushDiagnostics().catch(() => {});});@@ -254,8 +258,12 @@ export function startLocalDiagnostics(): () => void {if (state === "active" && now - lastTick > 3000)mobileDebugLog("warn", "lifecycle", "js stall", {elapsedMs: now - lastTick - 2000,+ // A timer gap alone cannot distinguish busy JS from process suspension.+ wallElapsedMs: Math.max(0, Date.now() - lastWallTick - 2000),+ lifecycleElapsedMs: Math.max(0, now - lifecycleAt),});lastTick = now;+ lastWallTick = Date.now();if (enabled)mobileDebugLog("debug", "performance", "render metrics", {markdown: getMobileMarkdownRenderMetrics(),@@ -269,6 +277,7 @@ export function startLocalDiagnostics(): () => void {timer = undefined;} else if (timer === undefined) {lastTick = performance.now();+ lastWallTick = Date.now();timer = setInterval(tick, 2000);}};diff --git a/apps/mobile/src/debug/mobileRuntimeIdentity.test.ts b/apps/mobile/src/debug/mobileRuntimeIdentity.test.tsnew file mode 100644index 0000000000..a1730cf192--- /dev/null+++ b/apps/mobile/src/debug/mobileRuntimeIdentity.test.ts@@ -0,0 +1,13 @@+import { afterEach, expect, it, vi } from 'vitest';+vi.mock('expo-application', () => ({ nativeApplicationVersion: '0.1.99', nativeBuildVersion: '123' }));+vi.mock('expo-updates', () => ({ updateId: '12345678-1234-1234-1234-123456789abc', runtimeVersion: 'abc123', isEmbeddedLaunch: false }));+import { mobileRuntimeIdentity } from './mobileRuntimeIdentity';++afterEach(() => vi.unstubAllEnvs());+it('reads native binary metadata without relying on removed Constants fields', () => {+ vi.stubEnv('EXPO_PUBLIC_XDT_GIT_COMMIT', 'abcdef123456');+ expect(mobileRuntimeIdentity()).toEqual({ commit: 'abcdef123456', version: '0.1.99', build: '123',+ updateId: '12345678-1234-1234-1234-123456789abc', runtimeVersion: 'abc123', embedded: false });+ vi.stubEnv('EXPO_PUBLIC_XDT_GIT_COMMIT', 'not-a-commit');+ expect(mobileRuntimeIdentity().commit).toBe('unknown');+});diff --git a/apps/mobile/src/debug/mobileRuntimeIdentity.ts b/apps/mobile/src/debug/mobileRuntimeIdentity.tsnew file mode 100644index 0000000000..7db5cad3ba--- /dev/null+++ b/apps/mobile/src/debug/mobileRuntimeIdentity.ts@@ -0,0 +1,17 @@+import * as Application from 'expo-application';+import * as Updates from 'expo-updates';++/** Native binary identity stays valid after OTA; the bundle commit is separate. */+export function mobileRuntimeIdentity() {+ return {+ commit: /^[a-f0-9]{7,40}$/i.test(process.env.EXPO_PUBLIC_XDT_GIT_COMMIT ?? '')+ ? process.env.EXPO_PUBLIC_XDT_GIT_COMMIT : 'unknown',+ version: Application.nativeApplicationVersion ?? 'unknown',+ build: Application.nativeBuildVersion ?? 'unknown',+ updateId: /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(Updates.updateId ?? '')+ ? Updates.updateId : 'unknown',+ runtimeVersion: /^[a-z0-9._-]{1,128}$/i.test(Updates.runtimeVersion ?? '')+ ? Updates.runtimeVersion : 'unknown',+ embedded: Updates.isEmbeddedLaunch,+ };+}diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsxindex 311de594da..d80adaa0aa 100644--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx@@ -8,6 +8,7 @@ import { createRecoveryDiagnostics, settleMeasuredSnapshot, type RecoveryPhase }import { confirmTrackedSubscription, SubscriptionAcknowledgements } from './subscriptionAcknowledgements';import { AppState, Platform } from 'react-native';import { mobileDebugLog } from '@/debug/mobileDebugLog';+import { mobileRuntimeIdentity } from '@/debug/mobileRuntimeIdentity';import {DeviceLinkClient,isSharedTaskPeer,@@ -963,12 +964,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {catalogRefresh.wake(deviceId);return rehydrateWithClient(client, deviceId);};- mobileDebugLog('debug', 'device-link', 'runtime identity', {- commit: /^[a-f0-9]{7,40}$/i.test(process.env.EXPO_PUBLIC_XDT_GIT_COMMIT ?? '')- ? process.env.EXPO_PUBLIC_XDT_GIT_COMMIT : 'unknown',- version: Constants.nativeAppVersion ?? 'unknown',- build: Constants.nativeBuildVersion ?? 'unknown',- });+ mobileDebugLog('debug', 'device-link', 'runtime identity', mobileRuntimeIdentity());const diagnostics = createRecoveryDiagnostics((event) => mobileDeviceLinkLogger.info('recovery phase', event),() => connectionEpochRef.current,diff --git a/apps/mobile/src/device-link/remoteResources.ts b/apps/mobile/src/device-link/remoteResources.tsindex 026bd5861b..1a1e97da32 100644--- a/apps/mobile/src/device-link/remoteResources.ts+++ b/apps/mobile/src/device-link/remoteResources.ts@@ -60,6 +60,11 @@ export interface RemoteResourceHostTarget {deviceName: string;}+/** Availability applies to discovery only; offline entries retain their cached projection. */+export interface RemoteResourceDiscoveryTarget extends RemoteResourceHostTarget {+ offline?: boolean;+}+export interface RemoteHomeCollection {id: string;title: string;@@ -73,11 +78,13 @@ export interface RemoteHomeCollection {export function remoteResourceDiscoveryTargets(devices: readonly { canOpen: boolean; state: string; deviceId: string; name: string }[],previous: readonly RemoteHomeCollection[],-): RemoteResourceHostTarget[] {+): RemoteResourceDiscoveryTarget[] {const known = new Set(previous.flatMap((collection) => collection.targets.map((host) => host.deviceId)));return devices.filter((device) => device.canOpen || (device.state === 'offline' && known.has(device.deviceId)))- .map((device) => ({ deviceId: device.deviceId, deviceName: device.name }));+ .map((device) => ({ deviceId: device.deviceId, deviceName: device.name,+ ...(!device.canOpen ? { offline: true } : {}),+ }));}function clientDescriptor(locale?: string): RemoteResourceClientDescriptor {@@ -273,37 +280,35 @@ export async function loadRemoteResourceManifest(*/export async function discoverRemoteHomeCollections(invoke: RemoteInvoke,- targets: readonly RemoteResourceHostTarget[],+ targets: readonly RemoteResourceDiscoveryTarget[],locale?: string,previous: readonly RemoteHomeCollection[] = [],): Promise<RemoteHomeCollection[]> {- const settled = await Promise.allSettled(targets.map(async (target) => ({+ const cachedManifest = (target: RemoteResourceHostTarget): RemoteResourceManifestResponse => ({+ protocolVersion: REMOTE_RESOURCE_PROTOCOL_VERSION,+ collections: previous.filter((collection) => collection.targets.some(+ (candidate) => candidate.deviceId === target.deviceId,+ )).map((collection) => ({+ id: collection.id,+ resourceKind: collection.resourceKind,+ title: collection.title,+ ...(collection.placement ? { placement: collection.placement } : {}),+ ...(collection.iconName ? { icon: { name: collection.iconName, fallbackText: '' } } : {}),+ })),+ });+ const settled = await Promise.allSettled(targets.map(async ({ offline, ...target }) => ({target,- manifest: await loadRemoteResourceManifest(invoke, target, locale),+ manifest: offline ? cachedManifest(target) : await loadRemoteResourceManifest(invoke, target, locale),})));const discovered = settled.flatMap((result, index) => {if (result.status === 'fulfilled') {return result.value.manifest ? [result.value] : [];}- const target = targets[index];- if (!target) return [];- return previous.flatMap((collection) => collection.targets.some(- (candidate) => candidate.deviceId === target.deviceId,- ) ? [{- target,- manifest: {- protocolVersion: REMOTE_RESOURCE_PROTOCOL_VERSION,- collections: [{- id: collection.id,- resourceKind: collection.resourceKind,- title: collection.title,- ...(collection.placement ? { placement: collection.placement } : {}),- ...(collection.iconName- ? { icon: { name: collection.iconName, fallbackText: '' } }- : {}),- }],- },- }] : []);+ const selected = targets[index];+ if (!selected) return [];+ const target = { deviceId: selected.deviceId, deviceName: selected.deviceName };+ const manifest = cachedManifest(target);+ return manifest.collections.length ? [{ target, manifest }] : [];});if (targets.length > 0 && discovered.length === 0) {const failure = settled.find((result) => result.status === 'rejected');diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.tsindex efe7f3d99f..51e9c878a9 100644--- a/packages/device-link/src/__tests__/client.test.ts+++ b/packages/device-link/src/__tests__/client.test.ts@@ -26,6 +26,7 @@ import {TRANSPORT_RETRY_PASS_BUDGET,encodeReliableFrames,makeTransportSkipPayload,+ isTransportSkipPayload,parseTransportAck,parseTransportPayload,} from '../transport.js';@@ -1448,6 +1449,47 @@ describe('DeviceLinkClient', () => {} finally { h.client.stop(); clock.mockRestore(); wall.mockRestore(); }});+ it.each([+ [1, 60_000, 0], [8, 60_000, 0],+ [1, 0, 60_000], [8, 0, 60_000],+ [1, 60_000, -60_000], [8, 60_000, -60_000],+ ])('expires a suspended request before replay with retry limit %i (monotonic %i ms, wall %i ms) without resetting another peer', async (transportMaxRetryAttempts, monotonicAdvance, wallAdvance) => {+ const h = makeHarness({ timing: { pingIntervalMs: 60_000, requestTimeoutMs: 30_000, transportMaxRetryAttempts } });+ let now = 100;+ const clock = vi.spyOn(h.client as unknown as { monotonicNow(): number }, 'monotonicNow').mockImplementation(() => now);+ let wallNow = Date.now();+ const wallClock = vi.spyOn(Date, 'now').mockImplementation(() => wallNow);+ try {+ h.client.start(); await tick(); h.current().ack();+ await establishInboundReliableLink(h, 'suspended-stream');+ await establishInboundReliableLink(h, 'healthy-stream', 1, 'dev-c');+ const result = h.client.invoke('dev-b', { channel: 'device-link:unsubscribe', args: ['sessions'] });+ const outcome = result.catch((error: DeviceLinkError) => error.code);+ const request = h.current().sent.filter(e => e.kind === 'invoke' && e.dst === 'dev-b').at(-1)!;+ const healthy = h.client.invoke('dev-c', { channel: 'local-db:sessions:list', args: [] }, 120_000)+ .catch((error: unknown) => error);+ const healthyRequest = h.current().sent.filter(e => e.kind === 'invoke' && e.dst === 'dev-c').at(-1)!;+ const reset = vi.fn();+ h.client.onPeerTransportReset(reset);+ const before = h.current().sent.length;+ // Model suspension without firing any timeout callback. Link recovery wins the callback race.+ now += monotonicAdvance;+ wallNow += wallAdvance;+ await establishInboundReliableLink(h, 'resumed-stream');+ const replay = h.current().sent.slice(before).filter(e => e.id === request.id);+ expect(replay.length).toBeGreaterThan(0);+ expect(replay.every(e => isTransportSkipPayload(JSON.parse(parseTransportPayload(e.payload)!.data)))).toBe(true);+ expect(await outcome).toBe('INVOKE_TIMEOUT');+ encodeReliableFrames({ v: PROTOCOL_VERSION, kind: 'invoke-result', src: 'dev-c', id: healthyRequest.id,+ payload: { ok: true, result: ['healthy'] },+ }, 'healthy-stream', 1).forEach(frame => h.current().push(frame));+ await expect(healthy).resolves.toMatchObject({ result: ['healthy'] });+ expect(reset).not.toHaveBeenCalled();+ expect(h.sockets).toHaveLength(1);+ expect(h.current().closed).toBeNull();+ } finally { h.client.stop(); clock.mockRestore(); wallClock.mockRestore(); }+ });+it('bounds recovery stage logs, measures with monotonic time and records a fresh outbound handshake', async () => {const debug = vi.fn();const h = makeHarness({ timing: { pingIntervalMs: 60_000 },@@ -7005,7 +7047,11 @@ describe('DeviceLinkClient relay 拥塞断连(close 1013)', () => {it('admits an atomic maximum-size reply after draining without pacing a fast empty socket', async () => {vi.useFakeTimers();- const h = makeHarness({ timing: { pingIntervalMs: 600_000 } });+ const debug = vi.fn();+ const h = makeHarness({ timing: { pingIntervalMs: 600_000 },+ logger: { debug, info: vi.fn(), warn: vi.fn(), error: vi.fn() } });+ let now = 100;+ const clock = vi.spyOn(h.client as unknown as { monotonicNow(): number }, 'monotonicNow').mockImplementation(() => now);try {h.client.start();await vi.advanceTimersByTimeAsync(0);@@ -7019,11 +7065,13 @@ describe('DeviceLinkClient relay 拥塞断连(close 1013)', () => {h.client.sendInvokeResult('a', 'max-reply', { ok: true, result: 'x'.repeat(4 * 1024 * 1024 - 1024) });expect(socket.sent).toHaveLength(0);socket.bufferedAmount = 0;+ now += 300;await vi.advanceTimersByTimeAsync(250);const large = socket.sent.filter((env) => env.id === 'max-reply');expect(large.length).toBeGreaterThan(1);const last = parseTransportPayload(large.at(-1)!.payload)!;expect(large.length).toBe(last.meta.segment!.total);+ expect(debug).toHaveBeenCalledWith(expect.stringContaining('lastBlockedBy=socket socketBufferedBytes=0'));socket.push({ v: 1, kind: 'push', src: 'a', payload: {channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,payload: { streamId: last.meta.streamId, ackSeq: last.meta.seq },@@ -7035,7 +7083,7 @@ describe('DeviceLinkClient relay 拥塞断连(close 1013)', () => {for (let i = 0; i < 10; i++) h.client.sendInvokeResult('a', `fast-${i}`, { ok: true, result: 'ok' });expect(socket.sent.length - before).toBe(10);expect(socket.closed).toBeNull();- } finally { h.client.stop(); vi.useRealTimers(); }+ } finally { h.client.stop(); clock.mockRestore(); vi.useRealTimers(); }});it('paces all reliable sends after 1013 without starving another peer or control ACKs', async () => {diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.tsindex ab496ad1bc..2656c3f23e 100644--- a/packages/device-link/src/client.ts+++ b/packages/device-link/src/client.ts@@ -485,6 +485,8 @@ export function classifyConnectionIssue(export type InboundFrameHandler = (env: Envelope) => unknown | Promise<unknown>;interface PendingRequest {+ /** Timers may be suspended; retire an overdue request before replaying its payload. */+ expireIfOverdue(): boolean;/** Diagnostics only: first successful socket write, not a delivery receipt. */noteFirstWrite?: () => void;resolve(env: Envelope): void;@@ -520,6 +522,8 @@ interface PendingReliableMessage {sent: boolean;/** 入队时刻(monotonicNow 单调时钟);push 帧按 TRANSPORT_PENDING_PUSH_MAX_AGE_MS 判定过期。 */enqueuedAt: number;+ /** Last observed gate, diagnostics only; never controls transport scheduling. */+ lastBlockedBy?: 'link' | 'receive-window' | 'recovery-ack' | 'relay-budget' | 'socket' | 'socket-budget' | 'pass-budget';}type ReliableSendPhase = 'down' | 'awaiting-confirm' | 'ready';@@ -1525,12 +1529,13 @@ export class DeviceLinkClient {const requestDescription = `${this.describeRequest(env, expectKind)} request=${id.slice(0, 8)}`;const logFinished = (outcome: 'ok' | 'timeout' | 'error', err?: DeviceLinkError): void => {- const elapsedMs = Date.now() - startedAt;+ const elapsedMs = Math.max(0, Math.round(this.monotonicNow() - startedMonotonicAt));+ const wallElapsedMs = Math.max(0, Date.now() - startedAt);const stages = firstWriteAt === undefined ? ' firstWrite=none': ` firstWriteWaitMs=${Math.round(firstWriteAt - startedMonotonicAt)}`+ ` afterFirstWriteMs=${Math.round(this.monotonicNow() - firstWriteAt)}`;if (outcome === 'timeout') {- this.log.warn(`device-link request timeout ${requestDescription} elapsed=${elapsedMs}ms${stages}`);+ this.log.warn(`device-link request timeout ${requestDescription} elapsed=${elapsedMs}ms${stages} wallElapsedMs=${wallElapsedMs}`);return;}if (outcome === 'error') {@@ -1547,15 +1552,27 @@ export class DeviceLinkClient {};return new Promise<Envelope>((resolve, reject) => {- const timer = setTimeout(() => {- this.pending.delete(id);+ const expire = () => {+ if (!this.pending.delete(id)) return;+ clearTimeout(timer);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`));- }, timeout);+ };+ const timer = setTimeout(expire, timeout);const pendingRequest: PendingRequest = {+ expireIfOverdue: () => {+ // Some native monotonic clocks pause in deep sleep. Either elapsed+ // clock reaching the budget retires this request: wall time covers+ // suspension, monotonic time covers wall-clock rollback. A forward+ // wall correction may expire early, but must not replay stale writes.+ if (this.monotonicNow() - startedMonotonicAt < timeout+ && Date.now() - startedAt < timeout) return false;+ expire();+ return true;+ },noteFirstWrite: () => { firstWriteAt ??= this.monotonicNow(); },resolve: (frame) => {clearTimeout(timer);@@ -3005,6 +3022,9 @@ export class DeviceLinkClient {lastSentAt: 0,sent: false,enqueuedAt: this.monotonicNow(),+ lastBlockedBy: willSendNow ? undefined : !this.isPeerSendReady(peer) ? 'link'+ : this.isOutsideReceiveWindow(peer, seq) ? 'receive-window'+ : this.shouldHoldRecoverySend(peer, additionalFrames) ? 'recovery-ack' : 'relay-budget',};peer.pending.set(seq, pending);peer.pendingBytes += reservedBytes;@@ -3039,7 +3059,15 @@ export class DeviceLinkClient {* 一分片都没写出才抛;中途竞态只返回已上网的帧数,让恢复预算能结算部分突发。*/private sendReliableFrames(peer: PeerTransportState, pending: PendingReliableMessage): number {- if (!pending.sent && this.isOutsideReceiveWindow(peer, pending.seq)) return 0;+ // A resume/ACK callback can run before the overdue timeout callback. The+ // existing timeout path substitutes a skip at the same sequence number;+ // never retransmit an expired command just because its timer ran late.+ if (pending.envelope.kind === 'invoke' && pending.envelope.id+ && this.pending.get(pending.envelope.id)?.expireIfOverdue()) return 0;+ if (!pending.sent && this.isOutsideReceiveWindow(peer, pending.seq)) {+ pending.lastBlockedBy = 'receive-window';+ return 0;+ }const frames = encodeReliableFrames(pending.envelope,peer.streamId,@@ -3052,23 +3080,24 @@ export class DeviceLinkClient {const congestionBudget = this.congestionCloseStreak > 0 ? this.congestionSendBudget : null;if (congestionBudget && !congestionBudget.canTake(pending.envelope.dst!, frames.length, peers, budgetNow,- )) return 0;+ )) { pending.lastBlockedBy = 'relay-budget'; return 0; }// Keep hard-cap errors unchanged. Soft pressure only delays the existing// bounded reliable queue, without consuming attempts or changing sequence IDs.this.assertWebSocketCapacity(wireBytes);- if (!this.canWriteReliableBytes(wireBytes)) return 0;+ if (!this.canWriteReliableBytes(wireBytes)) { pending.lastBlockedBy = 'socket'; return 0; }const localBudget = this.localSendPressure ? this.localSendBudget : null;const byteCredits = Math.ceil(wireBytes / SOCKET_SEND_CREDIT_BYTES);if (localBudget && !localBudget.canTake(pending.envelope.dst!, byteCredits, peers, budgetNow,- )) return 0;+ )) { pending.lastBlockedBy = 'socket-budget'; return 0; }if (congestionBudget) {if (!congestionBudget.take(pending.envelope.dst!, frames.length, peers, budgetNow,- )) return 0;+ )) { pending.lastBlockedBy = 'relay-budget'; return 0; }}if (localBudget && !localBudget.take(pending.envelope.dst!, byteCredits, peers, budgetNow)) {congestionBudget?.refund(pending.envelope.dst!, frames.length);+ pending.lastBlockedBy = 'socket-budget';return 0;}let sent = 0;@@ -3100,8 +3129,10 @@ export class DeviceLinkClient {+ ` dst=${pending.envelope.dst!.slice(0, 8)} seq=${pending.seq}`+ ` ${pending.attempts === 0 ? 'queueMs' : 'ageMs'}=${ageMs}`+ ` attempt=${pending.attempts + 1} frames=${sent} bytes=${pending.bytes}`- + ` pending=${peer.pending.size} congestion=${this.congestionCloseStreak}`);+ + ` pending=${peer.pending.size} congestion=${this.congestionCloseStreak}`+ + ` lastBlockedBy=${pending.lastBlockedBy ?? 'none'} socketBufferedBytes=${this.ws?.bufferedAmount ?? 0}`);}+ pending.lastBlockedBy = undefined;pending.sent = true;pending.attempts++;pending.lastSentAt = Date.now();@@ -4102,6 +4133,10 @@ export class DeviceLinkClient {let framesSpent = 0;const head = peer.pending.values().next().value;for (const pending of peer.pending.values()) {+ // Expiry must precede retry exhaustion too: suspension is a request+ // timeout, not evidence that the peer's transport has failed.+ if (pending.envelope.kind === 'invoke' && pending.envelope.id+ && this.pending.get(pending.envelope.id)?.expireIfOverdue()) continue;if (opts.onlyUnsent && pending.sent) continue;// Cumulative ACK cannot confirm a tail while a byte-paced head is still// missing. Allow one early tail retry to fill the receiver's buffer, but@@ -4140,11 +4175,17 @@ export class DeviceLinkClient {return;}const admittingNew = !pending.sent;- if (admittingNew && this.shouldHoldRecoverySend(peer, this.estimateReliableFrameCount(pending))) break;+ if (admittingNew && this.shouldHoldRecoverySend(peer, this.estimateReliableFrameCount(pending))) {+ pending.lastBlockedBy = 'recovery-ack';+ break;+ }// 发送前先按预估分片数结算:已经发过东西、且这一条会超预算时,把它留到下一趟。// 用预估而非真实编码结果是刻意的 —— 这是流控决策,不需要精确,重新编码一条 4MB// 消息只为数分片数不划算;发送后再用真实帧数扣减。- if (framesSpent > 0 && framesSpent + this.estimateReliableFrameCount(pending) > budget) break;+ if (framesSpent > 0 && framesSpent + this.estimateReliableFrameCount(pending) > budget) {+ pending.lastBlockedBy = 'pass-budget';+ break;+ }let sentFrames = 0;try {const previousAttempts = pending.attempts;