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(mobile): replace stale connections after network path changes

DavidShen90b8b859d8f5
diff --git a/apps/mobile/src/__tests__/historyViewProvider.test.tsx b/apps/mobile/src/__tests__/historyViewProvider.test.tsx
index b116517213..ee436741b2 100644
--- a/apps/mobile/src/__tests__/historyViewProvider.test.tsx
+++ b/apps/mobile/src/__tests__/historyViewProvider.test.tsx
@@ -62,6 +62,7 @@ const transport = vi.hoisted(() => {
start = vi.fn();
stop = vi.fn();
connectNow = vi.fn();
+ restartConnection = vi.fn();
notifyNetworkChanged = vi.fn();
getStatus = () => this.status;
serverCapabilities: string[] = [];
@@ -132,7 +133,7 @@ describe('Provider shared-task relay compatibility', () => {
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 () => {
+ it('replaces an online socket on physical route changes and retains probes for equal hints', async () => {
const client = transport.clients[0];
await act(async () => {
networkEvents.network(wifi);
@@ -142,8 +143,62 @@ describe('Provider network recovery priority', () => {
networkEvents.network(wifi);
});
expect(client.notifyNetworkChanged.mock.calls).toEqual([
- [{ urgent: false }], [{ urgent: false }], [{ urgent: true }], [{ urgent: true }],
+ [{ urgent: false }], [{ urgent: false }],
]);
+ expect(client.restartConnection.mock.calls).toEqual([
+ ['network-path-changed'], ['network-path-changed'],
+ ]);
+ });
+
+ it('does not replace a slow socket for reachability changes or repeated network capabilities', async () => {
+ const client = transport.clients[0];
+ await act(async () => {
+ networkEvents.network(wifi);
+ networkEvents.network({ ...wifi, isInternetReachable: false });
+ networkEvents.network(wifi);
+ networkEvents.network(wifi);
+ });
+ expect(client.restartConnection).not.toHaveBeenCalled();
+ expect(client.notifyNetworkChanged.mock.calls).toEqual([
+ [{ urgent: false }], [{ urgent: true }], [{ urgent: true }], [{ urgent: false }],
+ ]);
+ });
+
+ it('remembers a lost route even when the replacement has the same network type', async () => {
+ const client = transport.clients[0];
+ await act(async () => {
+ networkEvents.network(wifi);
+ networkEvents.network({ type: 'NONE', isConnected: false, isInternetReachable: false });
+ networkEvents.network(wifi);
+ networkEvents.network(wifi);
+ });
+ expect(client.restartConnection).toHaveBeenCalledTimes(1);
+ });
+
+ it.each(['connecting', 'stopped'] as const)('does not bypass handshakes or congestion backoff while %s', async status => {
+ const client = transport.clients[0];
+ client.status = status;
+ await act(async () => {
+ networkEvents.network(wifi);
+ networkEvents.network({ ...wifi, type: 'CELLULAR' });
+ });
+ expect(client.restartConnection).not.toHaveBeenCalled();
+ expect(client.notifyNetworkChanged).toHaveBeenLastCalledWith({ urgent: true });
+ });
+
+ it.each([false, true])('defers a background route change unless a new connection supersedes it (connected=%s)', async connected => {
+ const client = transport.clients[0];
+ await act(async () => {
+ networkEvents.network(wifi);
+ networkEvents.state = 'background'; networkEvents.app('background');
+ networkEvents.network({ ...wifi, type: 'CELLULAR' });
+ if (connected) client.statusChanged('online');
+ });
+ expect(client.restartConnection).not.toHaveBeenCalled();
+ await act(async () => {
+ networkEvents.state = 'active'; networkEvents.app('active');
+ });
+ expect(client.restartConnection).toHaveBeenCalledTimes(connected ? 0 : 1);
});
it.each(['online', 'stopped', 'connecting'] as const)('recovers immediately from background with a %s connection', async (status) => {
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index 577ca7a978..b0b93ed4c0 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -924,6 +924,19 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
);
recoveryDiagnostics.set(client, diagnostics);
if (AppState.currentState === 'active') diagnostics.foreground();
+ let networkPathChanged = false;
+ let lastConnectedNetworkType: string | undefined;
+ const recoverNetwork = (urgent: boolean) => {
+ const replaceOldPath = networkPathChanged;
+ networkPathChanged = false;
+ // Only this phone's established connection used the lost route. Keep
+ // handshakes and congestion backoff on their existing recovery path.
+ if (replaceOldPath && client.getStatus() === 'online') {
+ client.restartConnection('network-path-changed');
+ } else {
+ client.notifyNetworkChanged({ urgent });
+ }
+ };
const offIssue = client.onConnectionIssue(setConnectionIssue);
const offStatus = client.onStatusChange((next) => {
setStatus(next);
@@ -938,6 +951,8 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
peerRecoverySchedulerRef.current?.pause();
return;
}
+ // A new authenticated connection already supersedes any retained old path.
+ networkPathChanged = false;
// presence 是当前在线控制端收到的 delta,server 不会在 hello-ack 后重放
// 全量快照。进入新连接代际先丢弃旧 verdict:后台期间若设备从 unavailable
// 恢复,旧 false 不能永久挡住本轮 rehydrate。上一代仍 pending 的镜像清理
@@ -1255,8 +1270,8 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
// 冷却默认只拦请求路径的 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 });
+ // Replace a known old path; otherwise probe without the hint cooldown.
+ if (client.getStatus() === 'online') recoverNetwork(true);
// 快速切换(连接被宽限保住、始终 online)不会有 online 状态转换,这条显式
// 补齐就是断档回填的唯一触发点;其余路径下它因 status 未 online 而空转。
void rehydrateWithClient(client);
@@ -1291,9 +1306,19 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
|| previousNetwork.isInternetReachable !== network.isInternetReachable
);
previousNetwork = network;
+ // Reachability/capability notifications alone are not route changes:
+ // preserve the full weak-network probe budget for those hints.
+ if (network.isConnected === false) networkPathChanged = true;
+ if (network.isConnected === true && network.type
+ && network.type !== 'NONE' && network.type !== 'UNKNOWN') {
+ if (lastConnectedNetworkType !== undefined && lastConnectedNetworkType !== network.type) {
+ networkPathChanged = true;
+ }
+ lastConnectedNetworkType = network.type;
+ }
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({ urgent });
+ recoverNetwork(urgent);
});
}).catch(() => {
console.warn('[device-link] network listener unavailable; using heartbeat recovery');
diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.md
index dc128bcaef..204abb8bfd 100644
--- a/docs/dev-rules/remote-and-mobile-adaptation.md
+++ b/docs/dev-rules/remote-and-mobile-adaptation.md
@@ -87,6 +87,14 @@ Mobile 历史读取在 relay 已在线且目标 presence 不是明确不可用
历史控制器与页面同步;也不能为了放行读取伪造在线快照。明确离线/停用或 relay 未在线时
仍只展示缓存,授权、撤权和旧代结果拦截继续由原链路处理。
+Mobile 明确观察到断网后恢复,或已连接网络类型切换(如蜂窝 → Wi-Fi)时,
+替换本机仍显示 online 的旧连接,避免旧路径上的半开连接额外等待探测超时。
+相同类型的能力通知、仅 Internet reachability 变化和未知网络仍走原探测预算;
+不打断在途握手、不绕过拥塞退避。后台只记录路径变化,回前台再处理;
+期间若新连接已完成握手,则不重复替换。此动作只影响该手机的 relay 连接,
+不由单 peer 超时触发,也不重启被控端与其它控制端的共享连接。
+实现与回归见 Mobile `DeviceLinkContext.tsx`、`historyViewProvider.test.tsx`。
+
`packages/device-link/src/invokePolicy.ts` 集中维护请求策略,三个边界独立判断:
- 通道执行预算:保留 Desktop / Mobile 的超时差异,超时不代表主机操作未执行。