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。

perf(device-link): 合并重复网络探测并保留前台快速恢复 (#4330)

Dash21517bfc46c0
diff --git a/apps/mobile/src/__tests__/historyViewProvider.test.tsx b/apps/mobile/src/__tests__/historyViewProvider.test.tsx
index 8413e22253..9d192d983e 100644
--- a/apps/mobile/src/__tests__/historyViewProvider.test.tsx
+++ b/apps/mobile/src/__tests__/historyViewProvider.test.tsx
@@ -20,11 +20,23 @@ const auth = vi.hoisted(() => ({
apiFetch: vi.fn(async () => ({ devices: [] })),
}));
vi.mock('@/auth/AuthContext', () => ({ useAuth: () => auth }));
+const networkEvents = vi.hoisted(() => ({
+ state: 'active',
+ app: (_next: string) => {},
+ network: (_next: { type: string; isConnected: boolean; isInternetReachable: boolean }) => {},
+}));
vi.mock('react-native', () => ({
Platform: { OS: 'android' },
- AppState: { currentState: 'active', addEventListener: () => ({ remove() {} }) },
+ AppState: {
+ get currentState() { return networkEvents.state; },
+ addEventListener: (_event: string, listener: typeof networkEvents.app) => {
+ networkEvents.app = listener; return { remove() {} };
+ },
+ },
}));
-vi.mock('expo-network', () => ({ addNetworkStateListener: () => ({ remove() {} }) }));
+vi.mock('expo-network', () => ({ addNetworkStateListener: (listener: typeof networkEvents.network) => {
+ networkEvents.network = listener; return { remove() {} };
+} }));
vi.mock('expo-secure-store', () => ({
getItemAsync: vi.fn(async () => null), setItemAsync: vi.fn(async () => {}), deleteItemAsync: vi.fn(async () => {}),
}));
@@ -48,6 +60,8 @@ const transport = vi.hoisted(() => {
invoke = vi.fn(async () => ({ ok: true, result: 'history page' }));
start = vi.fn();
stop = vi.fn();
+ connectNow = vi.fn();
+ notifyNetworkChanged = vi.fn();
getStatus = () => this.status;
isOutboundExplicitlyClosed = () => false;
// No background recovery owner; each test explicitly starts the fresh read.
@@ -89,6 +103,7 @@ async function readHistory() {
}
beforeEach(async () => {
+ networkEvents.state = 'active';
auth.accountGeneration = 1;
transport.clients.length = 0;
root = createRoot(document.createElement('div'));
@@ -96,6 +111,40 @@ beforeEach(async () => {
});
afterEach(async () => { await act(async () => root.unmount()); });
+describe('Provider network recovery priority', () => {
+ const wifi = { type: 'WIFI', isConnected: true, isInternetReachable: true };
+ it('coalesces equal hints but expedites transport changes and offline recovery', async () => {
+ const client = transport.clients[0];
+ await act(async () => {
+ networkEvents.network(wifi);
+ networkEvents.network(wifi);
+ networkEvents.network({ ...wifi, type: 'CELLULAR' });
+ networkEvents.network({ type: 'NONE', isConnected: false, isInternetReachable: false });
+ networkEvents.network(wifi);
+ });
+ expect(client.notifyNetworkChanged.mock.calls).toEqual([
+ [{ urgent: false }], [{ urgent: false }], [{ urgent: true }], [{ urgent: true }],
+ ]);
+ });
+
+ it.each(['online', 'stopped', 'connecting'] as const)('recovers immediately from background with a %s connection', async (status) => {
+ const client = transport.clients[0];
+ client.status = status;
+ await act(async () => {
+ networkEvents.state = 'background'; networkEvents.app('background');
+ networkEvents.network(wifi);
+ });
+ expect(client.notifyNetworkChanged).not.toHaveBeenCalled();
+ await act(async () => {
+ networkEvents.state = 'active'; networkEvents.app('active');
+ });
+ expect(client.connectNow).toHaveBeenCalledWith('appstate-active', { overrideCongestionCooldown: true });
+ if (status === 'online') expect(client.notifyNetworkChanged).toHaveBeenCalledWith({ urgent: true });
+ else expect(client.notifyNetworkChanged).not.toHaveBeenCalled();
+ expect(client.stop).not.toHaveBeenCalled();
+ });
+});
+
describe('Provider history handshake lifetime', () => {
it.each(['presence', 'reconnect', 'peer reset', 'account switch'] as const)(
'rejects a late accept after %s and lets the current handshake read history', async (event) => {
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index 0675e9bb74..bd1727d3ce 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -1198,6 +1198,9 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
// overrideCongestionCooldown:用户显式回前台是拥塞冷却的合法豁免——
// 冷却默认只拦请求路径的 un-park(waitUntilOnline),不拦真人操作。
backgroundConnection.active();
+ // A short background stay can preserve a socket whose route changed.
+ // Probe without the ordinary hint cooldown; never delay content recovery.
+ if (client.getStatus() === 'online') client.notifyNetworkChanged({ urgent: true });
// 快速切换(连接被宽限保住、始终 online)不会有 online 状态转换,这条显式
// 补齐就是断档回填的唯一触发点;其余路径下它因 status 未 online 而空转。
void rehydrateWithClient(client);
@@ -1222,12 +1225,19 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
// existing heartbeat fallback if the optional runtime module is unavailable.
let disposed = false;
let networkSubscription: { remove(): void } | undefined;
+ let previousNetwork: { type?: string; isConnected?: boolean; isInternetReachable?: boolean } | undefined;
void import('expo-network').then(({ addNetworkStateListener }) => {
if (disposed) return;
networkSubscription = addNetworkStateListener((network) => {
- mobileDebugLog('debug', 'device-link', 'network changed', { type: network.type, connected: network.isConnected, reachable: network.isInternetReachable, appState: AppState.currentState });
+ const urgent = previousNetwork !== undefined && (
+ previousNetwork.type !== network.type
+ || previousNetwork.isConnected !== network.isConnected
+ || previousNetwork.isInternetReachable !== network.isInternetReachable
+ );
+ previousNetwork = network;
+ mobileDebugLog('debug', 'device-link', 'network path notification', { type: network.type, connected: network.isConnected, reachable: network.isInternetReachable, appState: AppState.currentState, urgent });
if (AppState.currentState !== 'active' || network.isConnected === false) return;
- client.notifyNetworkChanged();
+ client.notifyNetworkChanged({ urgent });
});
}).catch(() => {
console.warn('[device-link] network listener unavailable; using heartbeat recovery');
diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.ts
index 5a4c5fed58..1399899b2e 100644
--- a/packages/device-link/src/__tests__/client.test.ts
+++ b/packages/device-link/src/__tests__/client.test.ts
@@ -155,7 +155,7 @@ describe('network change probes', () => {
h.client.notifyNetworkChanged();
await vi.advanceTimersByTimeAsync(250);
h.client.notifyNetworkChanged();
- await vi.advanceTimersByTimeAsync(499);
+ await vi.advanceTimersByTimeAsync(249);
expect(socket.sent.filter((e) => e.kind === 'ping')).toHaveLength(0);
await vi.advanceTimersByTimeAsync(1);
expect(socket.sent.filter((e) => e.kind === 'ping')).toHaveLength(1);
@@ -210,6 +210,121 @@ describe('network change probes', () => {
expect(h.sockets).toHaveLength(3);
} finally { h.client.stop(); vi.useRealTimers(); }
});
+
+ it.each([false, true])('bounds repeated hints after a successful probe (post-hint traffic=%s)', async (traffic) => {
+ vi.useFakeTimers();
+ const h = makeHarness({ timing: { pingIntervalMs: 60_000 } });
+ try {
+ h.client.start(); await vi.advanceTimersByTimeAsync(0);
+ const socket = h.current(); socket.ack();
+ h.client.notifyNetworkChanged(); await vi.advanceTimersByTimeAsync(500);
+ socket.push({ v: PROTOCOL_VERSION, kind: 'pong' });
+ // A route can die just after success without changing its Wi-Fi label.
+ for (let i = 0; i < 29; i++) {
+ await vi.advanceTimersByTimeAsync(100);
+ h.client.notifyNetworkChanged();
+ }
+ expect(socket.sent.filter(e => e.kind === 'ping')).toHaveLength(1);
+ if (traffic) {
+ await vi.advanceTimersByTimeAsync(1);
+ socket.push({ v: PROTOCOL_VERSION, kind: 'pong' });
+ }
+ await vi.advanceTimersByTimeAsync(traffic ? 99 : 100);
+ expect(socket.sent.filter(e => e.kind === 'ping')).toHaveLength(traffic ? 1 : 2);
+ if (!traffic) {
+ await vi.advanceTimersByTimeAsync(15_000);
+ expect(h.sockets).toHaveLength(2);
+ } else expect(h.sockets).toHaveLength(1);
+ } finally { h.client.stop(); vi.useRealTimers(); }
+ });
+
+ it('expedites a queued probe on foreground or explicit route change without waiting for cooldown', async () => {
+ vi.useFakeTimers();
+ const h = makeHarness({ timing: { pingIntervalMs: 60_000 } });
+ try {
+ h.client.start(); await vi.advanceTimersByTimeAsync(0);
+ const socket = h.current(); socket.ack();
+ h.client.notifyNetworkChanged(); await vi.advanceTimersByTimeAsync(500);
+ socket.push({ v: PROTOCOL_VERSION, kind: 'pong' });
+ await vi.advanceTimersByTimeAsync(1);
+ h.client.notifyNetworkChanged();
+ h.client.notifyNetworkChanged({ urgent: true });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(socket.sent.filter(e => e.kind === 'ping')).toHaveLength(2);
+ // Even urgent hints must not restart an in-flight probe's failure deadline.
+ await vi.advanceTimersByTimeAsync(14_000);
+ h.client.notifyNetworkChanged({ urgent: true });
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(h.sockets).toHaveLength(2);
+ } finally { h.client.stop(); vi.useRealTimers(); }
+ });
+
+ it('does not let continuous hints starve the initial probe', async () => {
+ vi.useFakeTimers();
+ const h = makeHarness({ timing: { pingIntervalMs: 60_000 } });
+ try {
+ h.client.start(); await vi.advanceTimersByTimeAsync(0);
+ const socket = h.current(); socket.ack();
+ for (let i = 0; i < 5; i++) {
+ h.client.notifyNetworkChanged();
+ await vi.advanceTimersByTimeAsync(100);
+ }
+ expect(socket.sent.filter(e => e.kind === 'ping')).toHaveLength(1);
+ } finally { h.client.stop(); vi.useRealTimers(); }
+ });
+
+ it('keeps a second peer and its in-flight request alive while the first peer stops ACKing', async () => {
+ vi.useFakeTimers();
+ const h = makeHarness({ timing: {
+ pingIntervalMs: 60_000, requestTimeoutMs: 30_000, transportRetryIntervalMs: 60_000,
+ } });
+ try {
+ h.client.start(); await vi.advanceTimersByTimeAsync(0);
+ const socket = h.current(); socket.ack();
+ for (const peer of ['dev-b', 'dev-c']) {
+ const linked = establishInboundReliableLink(h, `stream-${peer}`, 1, peer);
+ await vi.advanceTimersByTimeAsync(0); await linked;
+ }
+ h.client.sendPush('dev-b', 'maker:event', { waitingForAck: true });
+ const pending = h.client.invoke('dev-c', { channel: 'local-db:sessions:list', args: [] });
+ const request = socket.sent.filter(e => e.kind === 'invoke' && e.dst === 'dev-c').at(-1)!;
+ h.client.notifyNetworkChanged({ urgent: true });
+ await vi.advanceTimersByTimeAsync(14_000);
+ // A peer's valid response proves relay health even without pong or ACKs from dev-b.
+ encodeReliableFrames({
+ v: PROTOCOL_VERSION, kind: 'invoke-result', src: 'dev-c', id: request.id,
+ payload: { ok: true, result: ['healthy'] },
+ }, 'stream-dev-c', 1).forEach(frame => socket.push(frame));
+ await vi.advanceTimersByTimeAsync(0);
+ await expect(pending).resolves.toMatchObject({ result: ['healthy'] });
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(h.sockets).toHaveLength(1);
+ expect(socket.closed).toBeNull();
+ expect(socket.sent.filter(e => e.kind === 'link-close')).toHaveLength(0);
+ h.client.sendPush('dev-c', 'maker:event', { stillLinked: true });
+ expect(socket.sent.at(-1)).toMatchObject({ kind: 'push', dst: 'dev-c' });
+ } finally { h.client.stop(); vi.useRealTimers(); }
+ });
+
+ it('clears a deferred hint and its cooldown when the connection is stopped', async () => {
+ vi.useFakeTimers();
+ const h = makeHarness({ timing: { pingIntervalMs: 60_000 } });
+ try {
+ h.client.start(); await vi.advanceTimersByTimeAsync(0);
+ const old = h.current(); old.ack();
+ h.client.notifyNetworkChanged(); await vi.advanceTimersByTimeAsync(500);
+ old.push({ v: PROTOCOL_VERSION, kind: 'pong' });
+ h.client.notifyNetworkChanged();
+ h.client.stop();
+ h.client.connectNow('appstate-active'); await vi.advanceTimersByTimeAsync(0);
+ const socket = h.current(); socket.ack();
+ h.client.notifyNetworkChanged(); await vi.advanceTimersByTimeAsync(500);
+ expect(socket.sent.filter(e => e.kind === 'ping')).toHaveLength(1);
+ socket.push({ v: PROTOCOL_VERSION, kind: 'pong' });
+ await vi.advanceTimersByTimeAsync(3_000);
+ expect(socket.sent.filter(e => e.kind === 'ping')).toHaveLength(1);
+ } finally { h.client.stop(); vi.useRealTimers(); }
+ });
});
let inboundLinkId = 0;
diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.ts
index 18328d14cc..57bde49381 100644
--- a/packages/device-link/src/client.ts
+++ b/packages/device-link/src/client.ts
@@ -693,6 +693,8 @@ export class DeviceLinkClient {
private networkChangeTimer: ReturnType<typeof setTimeout> | null = null;
private networkProbeTimer: ReturnType<typeof setTimeout> | null = null;
private networkProbeStartedAt = 0;
+ private networkChangeHintedAt = 0;
+ private networkProbeNextAllowedAt = 0;
private connectionStartedAt = 0;
/** 当前连接的代号,用于丢弃过期 socket 的事件回调 */
private connEpoch = 0;
@@ -852,11 +854,19 @@ export class DeviceLinkClient {
/** Network changes are hints, not proof of failure. Probe the shared relay,
* never an individual peer; any valid inbound frame keeps the socket alive.
- * Repeated hints coalesce and cannot extend an already running probe. */
- notifyNetworkChanged(): void {
+ * Repeated hints coalesce without postponing detection indefinitely. Foreground
+ * and explicit network transitions bypass the successful-probe cooldown. */
+ notifyNetworkChanged(options?: { urgent?: boolean }): void {
if (this.stopped || this.networkProbeTimer) return;
- const hintedAt = this.monotonicNow();
- if (this.networkChangeTimer) clearTimeout(this.networkChangeTimer);
+ this.networkChangeHintedAt = this.monotonicNow();
+ if (this.networkChangeTimer) {
+ if (!options?.urgent) return;
+ clearTimeout(this.networkChangeTimer);
+ }
+ const delay = options?.urgent ? 0 : Math.max(
+ 500,
+ this.networkProbeNextAllowedAt - this.networkChangeHintedAt,
+ );
this.networkChangeTimer = setTimeout(() => {
this.networkChangeTimer = null;
if (this.stopped) return;
@@ -867,7 +877,7 @@ export class DeviceLinkClient {
}
// Activity after the latest hint already proves this relay is reachable.
// Do not compare Wi-Fi labels: switching access points can keep them equal.
- if (this.lastInboundAt > hintedAt) return;
+ if (this.lastInboundAt > this.networkChangeHintedAt) return;
const epoch = this.connEpoch;
const socket = this.ws;
const startedAt = this.monotonicNow();
@@ -888,7 +898,7 @@ export class DeviceLinkClient {
// to settle the same bounded probe rather than tearing down immediately.
this.log.debug('network probe send deferred; waiting for inbound activity');
}
- }, 500);
+ }, delay);
}
private clearNetworkProbe(): void {
@@ -896,6 +906,7 @@ export class DeviceLinkClient {
if (this.networkProbeTimer) clearTimeout(this.networkProbeTimer);
this.networkChangeTimer = null;
this.networkProbeTimer = null;
+ this.networkProbeNextAllowedAt = 0;
}
/**
@@ -2045,6 +2056,7 @@ export class DeviceLinkClient {
if (this.networkProbeTimer) {
clearTimeout(this.networkProbeTimer);
this.networkProbeTimer = null;
+ this.networkProbeNextAllowedAt = this.lastInboundAt + 3_000;
this.log.debug(`network probe confirmed relay activity (elapsedMs=${Math.max(0, this.lastInboundAt - this.networkProbeStartedAt)})`);
}
}