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): 区分内容恢复状态并加快前台切网恢复 (#3947)

Dashf70d22d483f6
diff --git a/apps/desktop/src/main/device-link/__tests__/networkChanges.test.ts b/apps/desktop/src/main/device-link/__tests__/networkChanges.test.ts
new file mode 100644
index 0000000000..bb5ec5487f
--- /dev/null
+++ b/apps/desktop/src/main/device-link/__tests__/networkChanges.test.ts
@@ -0,0 +1,35 @@
+import { afterEach, expect, it, vi } from 'vitest';
+import { networkInterfaces } from 'node:os';
+import { watchNetworkChanges } from '../networkChanges';
+vi.mock('node:os', () => ({ networkInterfaces: vi.fn() }));
+afterEach(() => vi.useRealTimers());
+it('ignores stable/reordered interfaces and stops on teardown', () => {
+ vi.useFakeTimers();
+ const read = vi.mocked(networkInterfaces);
+ const wifi = {
+ internal: false,
+ family: 'IPv4' as const,
+ address: '192.0.2.1',
+ netmask: '255.255.255.0',
+ mac: '00:00:00:00:00:00',
+ cidr: '192.0.2.1/24',
+ };
+ const vpn = { ...wifi, address: '192.0.2.2', cidr: '192.0.2.2/24' };
+ read.mockReturnValue({ en0: [wifi], utun: [vpn] });
+ const changed = vi.fn();
+ const stop = watchNetworkChanges(changed);
+ read.mockReturnValue({ utun: [vpn], en0: [wifi] });
+ vi.advanceTimersByTime(2_000);
+ expect(changed).not.toHaveBeenCalled();
+ read.mockReturnValue({ en0: [wifi] });
+ vi.advanceTimersByTime(2_000);
+ expect(changed).toHaveBeenCalledTimes(1);
+ read.mockImplementation(() => {
+ throw new Error('OS unavailable');
+ });
+ vi.advanceTimersByTime(2_000);
+ expect(changed).toHaveBeenCalledTimes(1);
+ stop();
+ vi.advanceTimersByTime(2_000);
+ expect(read).toHaveBeenCalledTimes(4);
+});
diff --git a/apps/desktop/src/main/device-link/__tests__/transportTimeoutReopen.test.ts b/apps/desktop/src/main/device-link/__tests__/transportTimeoutReopen.test.ts
index 3450c1a2e3..525c14069a 100644
--- a/apps/desktop/src/main/device-link/__tests__/transportTimeoutReopen.test.ts
+++ b/apps/desktop/src/main/device-link/__tests__/transportTimeoutReopen.test.ts
@@ -6,6 +6,25 @@ import {
} from '../transportTimeoutReopen';
describe('shouldAbortTransportTimeoutReopen', () => {
+ it('invalidates only the reset peer before reopen, including resets coalesced into an active attempt', () => {
+ const order: string[] = [];
+ const reopen = vi.fn((deviceId: string) => {
+ order.push(`open:${deviceId}`);
+ return new Promise(() => {});
+ });
+ const loop = createTransportTimeoutReopenLoop({
+ reopen,
+ shouldAbort: () => false,
+ onReset: (deviceId) => order.push(`reset:${deviceId}`),
+ });
+ routeLinkCloseForReopen('transport-timeout', loop, 'affected');
+ loop.trigger('affected');
+ expect(order).toEqual(['reset:affected', 'open:affected', 'reset:affected']);
+ expect(reopen).toHaveBeenCalledTimes(1);
+ expect(loop.isActive('neighbor')).toBe(false);
+ loop.dispose();
+ });
+
const base = {
clientOnline: true,
isOwner: true,
diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.ts
index 41197832b7..f6a02080a6 100644
--- a/apps/desktop/src/main/device-link/index.ts
+++ b/apps/desktop/src/main/device-link/index.ts
@@ -11,6 +11,7 @@
*/
import os from 'node:os';
+import { watchNetworkChanges } from './networkChanges';
import path from 'node:path';
import { app, BrowserWindow } from 'electron';
import WebSocket from 'ws';
@@ -353,6 +354,8 @@ let client: DeviceLinkClient | null = null;
* 由 presence 闪断路径接管恢复) / 次数耗尽(用户下次打开远程视图惰性重建)。
*/
const transportTimeoutReopen = createTransportTimeoutReopenLoop({
+ // Local Main→Renderer projection only; the relay and neighboring peers remain online.
+ onReset: (deviceId) => broadcast(DEVICE_LINK_PUSH.PEER_LINK_RESET, { deviceId }),
reopen: async (deviceId) => {
await openRemoteLink(deviceId);
// link 重建成功后定向补一次订阅重放:transport-timeout 场景被控端保留了
@@ -624,6 +627,8 @@ export interface DeviceLinkServiceOptions {
onUpdateRelaunchBusyChanged?: (busy: boolean) => void;
}
+let stopNetworkWatch: (() => void) | null = null;
+
export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): void {
// 「保持电脑唤醒」按持久化偏好在启动时应用(与登录 / relay 无关,幂等)。
const initialKeepAwake = readDeviceLinkSettings().keepAwake;
@@ -739,6 +744,11 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v
handleControllerOffline(change.deviceId, change);
}
});
+ client.onPeerTransportReset(({ deviceId }) => {
+ // Mutual control shares one peer link: a locally exhausted inbound stream
+ // also invalidates this Desktop's remote view, without reopening other peers.
+ broadcast(DEVICE_LINK_PUSH.PEER_LINK_RESET, { deviceId });
+ });
client.onStatusChange((status) => {
if (status !== 'online') {
@@ -1059,6 +1069,11 @@ export function initDeviceLinkService(options: DeviceLinkServiceOptions = {}): v
if (!authManager.getAuthState().isAuthenticated) return;
linkTornDown = false;
client?.start();
+ stopNetworkWatch?.();
+ stopNetworkWatch = watchNetworkChanges(() => {
+ if (linkTornDown || !arbiter?.isOwner() || !authManager.getAuthState().isAuthenticated) return;
+ client?.notifyNetworkChanged();
+ });
// 可靠帧可能在 ownership 接管前到达(那时非持有者,重建被 shouldAbort 挡掉):
// 接管后对本机仍在控制、且 link 未就绪的设备补发一次重建,避免启动竞态留下
// 半开链路,不必等对端下一帧。
@@ -1227,6 +1242,8 @@ export function getMobileNotifyGeneration(): number {
* 同进程换账号登录还会把上一账号的控制端串到新账号。
*/
function teardownActiveLink(): void {
+ stopNetworkWatch?.();
+ stopNetworkWatch = null;
if (!client || linkTornDown) return;
linkTornDown = true;
controllerDisplayNameRefreshGeneration += 1;
diff --git a/apps/desktop/src/main/device-link/networkChanges.ts b/apps/desktop/src/main/device-link/networkChanges.ts
new file mode 100644
index 0000000000..b4c4b716be
--- /dev/null
+++ b/apps/desktop/src/main/device-link/networkChanges.ts
@@ -0,0 +1,31 @@
+import { networkInterfaces } from 'node:os';
+
+/** Observe interface/address changes without recording addresses in logs. Some
+ * route-only VPN/proxy changes remain covered by the regular relay heartbeat. */
+export function watchNetworkChanges(onChange: () => void): () => void {
+ const snapshot = (): string =>
+ JSON.stringify(
+ Object.entries(networkInterfaces())
+ .flatMap(([name, addresses]) =>
+ (addresses ?? [])
+ .filter((address) => !address.internal)
+ .map((address) => `${name}:${address.family}:${address.address}`),
+ )
+ .sort(),
+ );
+ let previous: string | undefined;
+ const poll = (): void => {
+ try {
+ const next = snapshot();
+ const changed = previous !== undefined && previous !== next;
+ previous = next;
+ if (changed) onChange();
+ } catch {
+ // An OS enumeration failure is not evidence that the relay is broken.
+ }
+ };
+ poll();
+ const timer = setInterval(poll, 2_000);
+ timer.unref?.();
+ return () => clearInterval(timer);
+}
diff --git a/apps/desktop/src/main/device-link/transportTimeoutReopen.ts b/apps/desktop/src/main/device-link/transportTimeoutReopen.ts
index 43ef1c46a4..1f727c9438 100644
--- a/apps/desktop/src/main/device-link/transportTimeoutReopen.ts
+++ b/apps/desktop/src/main/device-link/transportTimeoutReopen.ts
@@ -15,6 +15,8 @@
type Timer = ReturnType<typeof setTimeout>;
export interface TransportTimeoutReopenDeps {
+ /** Local view invalidation, including another reset while reopen is already pending. */
+ onReset?(deviceId: string): void;
/** 重开链路(通常是 openRemoteLink;自带同 device in-flight 去重)。 */
reopen(deviceId: string): Promise<unknown>;
/** 返回 true 则终止该设备的循环(撤权 / client 不在 / 待命态 / relay 离线)。 */
@@ -172,6 +174,7 @@ export function createTransportTimeoutReopenLoop(
return {
trigger(deviceId: string): void {
+ deps.onReset?.(deviceId);
if (entries.has(deviceId)) return;
const entry: ReopenEntry = { timer: null };
entries.set(deviceId, entry);
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index f0d91bbf1e..b80d9e0b07 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -1,4 +1,5 @@
import { contextBridge, ipcRenderer, webUtils } from 'electron';
+import { DEVICE_LINK_PUSH } from '../shared/deviceLinkIpc';
import type { MobileCodexRateLimitsResult } from '@cindy/maker-shared/device-link-contract';
import type { AppearanceSettings } from '../shared/appearanceSettings';
import type {
@@ -788,6 +789,7 @@ const fanOutDeviceLinkKeepAwakeChanged = createIpcFanOut('device-link:keep-awake
const fanOutDeviceLinkOwnershipChanged = createIpcFanOut('device-link:ownership-changed');
// 控制端:目标设备「无响应」熔断状态翻转(payload = { deviceId, unresponsive })
const fanOutDeviceLinkResponsivenessChanged = createIpcFanOut('device-link:responsiveness-changed');
+const fanOutDeviceLinkPeerLinkReset = createIpcFanOut(DEVICE_LINK_PUSH.PEER_LINK_RESET);
// device-link 模型列表写穿:被控端本地 main → 自身 renderer,把控制端写穿的草稿 / 会话 pref
// 交给 renderer 调它原来的本地 setter。仅被控端进程会收到(控制端从不收 → 监听不误触发)。
@@ -4251,6 +4253,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
onOwnershipChanged: fanOutDeviceLinkOwnershipChanged,
/** 控制端:目标设备「无响应」熔断状态翻转,payload: { deviceId, unresponsive } */
onResponsivenessChanged: fanOutDeviceLinkResponsivenessChanged,
+ onPeerLinkReset: fanOutDeviceLinkPeerLinkReset,
/**
* 控制端:远程会话镜像的本地冷缓存(main 落 userData,见 main/device-link/mirrorCacheStore.ts)。
* 只做首屏加速,非权威;fresh 数据一到由 renderer 整体接管。
diff --git a/apps/desktop/src/preload/sidebarWindowPreload.ts b/apps/desktop/src/preload/sidebarWindowPreload.ts
index ebd34c9dc5..826086aeb5 100644
--- a/apps/desktop/src/preload/sidebarWindowPreload.ts
+++ b/apps/desktop/src/preload/sidebarWindowPreload.ts
@@ -147,6 +147,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
onPayload(DEVICE_LINK_PUSH.CONTROL_TARGET_CHANGED, cb),
onResponsivenessChanged: (cb: (payload: unknown) => void): (() => void) =>
onPayload(DEVICE_LINK_PUSH.RESPONSIVENESS_CHANGED, cb),
+ onPeerLinkReset: (cb: (payload: unknown) => void): (() => void) =>
+ onPayload(DEVICE_LINK_PUSH.PEER_LINK_RESET, cb),
mirrorCache: {
getMessages: (deviceId: string, sessionId: string): Promise<unknown> =>
ipcRenderer.invoke(DEVICE_LINK_INVOKE.MIRROR_CACHE_GET_MESSAGES, { deviceId, sessionId }),
diff --git a/apps/desktop/src/renderer/__tests__/reconcileRemoteMessages.test.ts b/apps/desktop/src/renderer/__tests__/reconcileRemoteMessages.test.ts
index bcf2b840c4..445acd06f2 100644
--- a/apps/desktop/src/renderer/__tests__/reconcileRemoteMessages.test.ts
+++ b/apps/desktop/src/renderer/__tests__/reconcileRemoteMessages.test.ts
@@ -1017,6 +1017,28 @@ describe('makerChatStore.reconcileRemoteMessages', () => {
expect(calls).toBe(2);
});
+ it.each([true, false])('returns the final applied result to coalesced callers (first stale=%s)', async (firstStale) => {
+ const s = sid();
+ const keep = dbMessage(s, 'keep', 'keep', '2026-06-15T00:00:00.000Z');
+ const cut = dbMessage(s, 'cut', 'cut', '2026-06-16T00:00:00.000Z');
+ await openRemoteWithHistory(s, [keep, cut]);
+ const first = deferred<Message[]>();
+ const trailing = deferred<Message[]>();
+ let calls = 0;
+ remoteListResolver = () => ++calls === 1 ? first.promise : trailing.promise;
+ const result = makerChatStore.reconcileRemoteMessages(s);
+ await flush();
+ const coalesced = makerChatStore.reconcileRemoteMessages(s);
+ if (firstStale) makerChatStore.dropMessagesFromClientId(s, 'client-cut');
+ first.resolve([keep, cut]);
+ await flushMany(REMOTE_RECONCILE_FLUSH_TICKS);
+ expect(calls).toBe(2);
+ if (!firstStale) makerChatStore.dropMessagesFromClientId(s, 'client-cut');
+ trailing.resolve([keep]);
+ expect(await result).toBe(firstStale);
+ expect(await coalesced).toBe(firstStale);
+ });
+
it('远程会话:飞行期间窗口被重置(rewind)时,陈旧对账整体作废;尾随重跑照常补', async () => {
// 单飞之后"代际变了"必然来自真正的窗口重置,不可能是另一次对账 —— 这条守卫因此变成唯一一道。
const s = sid();
diff --git a/apps/desktop/src/renderer/__tests__/remoteContentRecovery.test.ts b/apps/desktop/src/renderer/__tests__/remoteContentRecovery.test.ts
new file mode 100644
index 0000000000..416b0110dc
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/remoteContentRecovery.test.ts
@@ -0,0 +1,94 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { createRemoteContentRecovery } from '../features/cc-agent/hooks/remoteContentRecovery';
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((r) => {
+ resolve = r;
+ });
+ return { promise, resolve };
+}
+afterEach(() => vi.useRealTimers());
+describe('remote content recovery', () => {
+ it('waits for both subscription ACK and an applied snapshot, coalescing triggers', async () => {
+ vi.useFakeTimers();
+ const ack = deferred<void>();
+ const snapshot = deferred<boolean>();
+ const changed = vi.fn();
+ const reconcile = vi.fn(() => snapshot.promise);
+ const subscribe = vi.fn(() => ack.promise);
+ const recovery = createRemoteContentRecovery({
+ subscribe,
+ reconcile,
+ changed,
+ completed: vi.fn(),
+ });
+ recovery.request();
+ recovery.request();
+ expect(subscribe).toHaveBeenCalledTimes(1);
+ expect(reconcile).not.toHaveBeenCalled();
+ ack.resolve();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(changed).not.toHaveBeenCalledWith('ready');
+ snapshot.resolve(true);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(changed).toHaveBeenCalledWith('ready');
+ recovery.dispose();
+ });
+
+ it('retries rejected subscriptions and skipped snapshots without claiming success', async () => {
+ vi.useFakeTimers();
+ const subscribe = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('timeout'))
+ .mockResolvedValue(undefined);
+ const reconcile = vi.fn().mockResolvedValueOnce(false).mockResolvedValue(true);
+ const changed = vi.fn();
+ const recovery = createRemoteContentRecovery({
+ subscribe,
+ reconcile,
+ changed,
+ completed: vi.fn(),
+ retryMs: 10,
+ });
+ recovery.request();
+ await vi.advanceTimersByTimeAsync(10);
+ expect(changed).not.toHaveBeenCalledWith('ready');
+ expect(reconcile).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(20);
+ expect(changed).toHaveBeenCalledWith('ready');
+ recovery.dispose();
+ });
+
+ it('discards an old snapshot after disconnect and retries only when online again', async () => {
+ vi.useFakeTimers();
+ const old = deferred<boolean>();
+ const current = deferred<boolean>();
+ const reconcile = vi
+ .fn()
+ .mockImplementationOnce(() => old.promise)
+ .mockImplementationOnce(() => current.promise);
+ const changed = vi.fn();
+ const recovery = createRemoteContentRecovery({
+ subscribe: async () => {},
+ reconcile,
+ changed,
+ completed: vi.fn(),
+ });
+ recovery.request();
+ await vi.advanceTimersByTimeAsync(0);
+ recovery.invalidate(false);
+ old.resolve(true);
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(changed).not.toHaveBeenCalledWith('ready');
+ expect(reconcile).toHaveBeenCalledTimes(1);
+ recovery.invalidate(true);
+ recovery.request();
+ await vi.advanceTimersByTimeAsync(0);
+ recovery.dispose();
+ current.resolve(true);
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(changed).not.toHaveBeenCalledWith('ready');
+ expect(reconcile).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/remoteContentRecoveryHook.test.ts b/apps/desktop/src/renderer/__tests__/remoteContentRecoveryHook.test.ts
new file mode 100644
index 0000000000..8210b28482
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/remoteContentRecoveryHook.test.ts
@@ -0,0 +1,158 @@
+// @vitest-environment jsdom
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, expect, it, vi } from 'vitest';
+import { useRemoteSessionSync } from '../features/cc-agent/hooks/useRemoteSessionSync';
+
+const mocks = vi.hoisted(() => ({ reconcile: vi.fn(async () => true), running: false }));
+vi.mock('@/lib/makerChatStore', () => ({
+ makerChatStore: {
+ reconcileRemoteMessages: mocks.reconcile,
+ getSnapshot: () => ({ agentStatus: { isRunning: mocks.running } }),
+ subscribe: () => () => {},
+ getLastInboundEventAt: () => Date.now(),
+ },
+}));
+vi.mock('@/lib/logger', () => ({
+ createLogger: () => ({ info: vi.fn(), debug: vi.fn(), warn: vi.fn() }),
+}));
+vi.mock('@/lib/makerTransport', () => ({ isSessionTurnRunningFor: async () => true }));
+vi.mock('@/features/device-link/remoteProjectsStore', () => ({
+ remoteProjectsStore: { getDeviceIds: () => ['host'] },
+}));
+vi.mock('@/features/device-link/refreshRemoteSessions', () => ({
+ refreshRemoteDeviceSessions: vi.fn(),
+}));
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+it('requires a fresh ACK and snapshot after peer-only resets without invalidating neighbors', async () => {
+ vi.useFakeTimers();
+ const resets = new Set<(payload: { deviceId: string }) => void>();
+ const subscribe = vi.fn(async () => {});
+ vi.stubGlobal('electronAPI', {
+ deviceLink: {
+ subscribe,
+ unsubscribe: async () => {},
+ onStatusChanged: () => () => {},
+ onPresenceChanged: () => () => {},
+ onResponsivenessChanged: () => () => {},
+ onPeerLinkReset: (cb: (payload: { deviceId: string }) => void) => {
+ resets.add(cb);
+ return () => resets.delete(cb);
+ },
+ },
+ });
+ mocks.running = false;
+ mocks.reconcile.mockResolvedValue(true);
+ const affected = renderHook(() => useRemoteSessionSync('session', 'host'));
+ const neighbor = renderHook(() => useRemoteSessionSync('neighbor-session', 'neighbor'));
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(affected.result.current.contentState).toBe('ready');
+ expect(neighbor.result.current.contentState).toBe('ready');
+
+ let ack!: () => void;
+ let oldSnapshot!: (value: boolean) => void;
+ let newSnapshot!: (value: boolean) => void;
+ subscribe.mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ ack = resolve;
+ }),
+ );
+ mocks.reconcile
+ .mockImplementationOnce(
+ () =>
+ new Promise<boolean>((resolve) => {
+ oldSnapshot = resolve;
+ }),
+ )
+ .mockImplementationOnce(
+ () =>
+ new Promise<boolean>((resolve) => {
+ newSnapshot = resolve;
+ }),
+ );
+ const callsBeforeReset = mocks.reconcile.mock.calls.length;
+ await act(async () => {
+ resets.forEach((cb) => cb({ deviceId: 'host' }));
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(affected.result.current.contentState).toBe('syncing');
+ expect(neighbor.result.current.contentState).toBe('ready');
+ expect(mocks.reconcile).toHaveBeenCalledTimes(callsBeforeReset);
+ await act(async () => {
+ ack();
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(affected.result.current.contentState).toBe('syncing');
+ await act(async () => {
+ resets.forEach((cb) => cb({ deviceId: 'host' }));
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ await act(async () => {
+ oldSnapshot(true);
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(affected.result.current.contentState).toBe('syncing');
+ expect(neighbor.result.current.contentState).toBe('ready');
+ await act(async () => {
+ newSnapshot(true);
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(affected.result.current.contentState).toBe('ready');
+ affected.unmount();
+ neighbor.unmount();
+ expect(resets.size).toBe(0);
+});
+
+it('does not reset a recovered mounted task on its first busy presence update', async () => {
+ vi.useFakeTimers();
+ let presence!: (snapshot: {
+ deviceId: string;
+ online: boolean;
+ remoteControlEnabled: boolean;
+ busy: boolean;
+ }) => void;
+ vi.stubGlobal('electronAPI', undefined);
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: {
+ deviceLink: {
+ subscribe: async () => {},
+ unsubscribe: async () => {},
+ onStatusChanged: () => () => {},
+ onPresenceChanged: (cb: typeof presence) => {
+ presence = cb;
+ return () => {};
+ },
+ onResponsivenessChanged: () => () => {},
+ },
+ },
+ });
+ mocks.running = false;
+ mocks.reconcile.mockResolvedValue(true);
+ const hook = renderHook(() => useRemoteSessionSync('session', 'host'));
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(hook.result.current.contentState).toBe('ready');
+ mocks.running = true;
+ mocks.reconcile.mockResolvedValue(false);
+ act(() => presence({ deviceId: 'host', online: true, remoteControlEnabled: true, busy: true }));
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(250);
+ });
+ expect(hook.result.current.contentState).toBe('ready');
+ act(() => presence({ deviceId: 'host', online: false, remoteControlEnabled: true, busy: true }));
+ expect(hook.result.current.contentState).toBe('syncing');
+ act(() => presence({ deviceId: 'host', online: true, remoteControlEnabled: true, busy: true }));
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(250);
+ });
+ expect(hook.result.current.contentState).toBe('syncing');
+ hook.unmount();
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index b509afe2c5..f79479df84 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -4518,6 +4518,11 @@ export function CCAgentSessionView({
issue={remoteLinkIssue}
onResync={remoteSync.resync}
/>
+ ) : remoteConn === 'connected' ? (
+ <RemoteSessionBanner
+ status={remoteSync.contentState === 'ready' ? 'recovered' : 'syncing'}
+ onResync={remoteSync.resync}
+ />
) : null}
{/* 远程会话首屏:等被控端经隧道返回历史/元数据期间的 loading(仅远程、延迟防闪)。 */}
diff --git a/apps/desktop/src/renderer/features/cc-agent/RemoteSessionBanner.tsx b/apps/desktop/src/renderer/features/cc-agent/RemoteSessionBanner.tsx
index 8b1007669e..53cecc8395 100644
--- a/apps/desktop/src/renderer/features/cc-agent/RemoteSessionBanner.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/RemoteSessionBanner.tsx
@@ -18,10 +18,11 @@
*/
import { useTranslation } from 'react-i18next';
+import { useEffect, useState } from 'react';
import { RotateCw, Square } from 'lucide-react';
interface Props {
- status: 'reconnecting' | 'host-offline' | 'degraded' | 'suspect-stall';
+ status: 'reconnecting' | 'host-offline' | 'degraded' | 'suspect-stall' | 'syncing' | 'recovered';
/**
* 本机到 relay 的连接问题(鉴权失效/被顶号/超限/版本不符)。仅 reconnecting 态消费:
* 有明确原因时把笼统的「重连中」替换成具体原因文案,避免无限重连横幅无法行动。
@@ -34,6 +35,13 @@ interface Props {
export function RemoteSessionBanner({ status, issue, onResync, onFinalize }: Props) {
const { t } = useTranslation();
+ const [hideRecovered, setHideRecovered] = useState(false);
+ useEffect(() => {
+ setHideRecovered(false);
+ if (status !== 'recovered') return;
+ const timer = setTimeout(() => setHideRecovered(true), 2_000);
+ return () => clearTimeout(timer);
+ }, [status]);
const activeIssue = status === 'reconnecting' ? (issue ?? null) : null;
const dotColor =
status === 'host-offline' || activeIssue
@@ -47,10 +55,16 @@ export function RemoteSessionBanner({ status, issue, onResync, onFinalize }: Pro
? t('ccAgent.remoteSession.hostOffline')
: status === 'degraded'
? t('ccAgent.remoteSession.degraded')
- : t('ccAgent.remoteSession.suspectStall');
+ : status === 'syncing'
+ ? t('ccAgent.remoteSession.syncing')
+ : status === 'recovered'
+ ? t('ccAgent.remoteSession.recovered')
+ : t('ccAgent.remoteSession.suspectStall');
const pulse =
!activeIssue &&
- (status === 'reconnecting' || status === 'degraded' || status === 'suspect-stall');
+ (status === 'reconnecting' || status === 'degraded' || status === 'suspect-stall' || status === 'syncing');
+
+ if (status === 'recovered' && hideRecovered) return null;
return (
<div className="flex select-none items-center gap-2 border-b border-[var(--border-default)] bg-[var(--surface-chip)] px-4 py-1.5">
diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/remoteContentRecovery.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/remoteContentRecovery.ts
new file mode 100644
index 0000000000..198031018c
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/remoteContentRecovery.ts
@@ -0,0 +1,85 @@
+export type RemoteContentRecoveryState = 'syncing' | 'ready';
+
+/** A view's recovery is complete only after its subscription ACK and a snapshot
+ * actually applied. The existing transport owns reconnect; this owns no links. */
+export function createRemoteContentRecovery(deps: {
+ subscribe(): Promise<unknown>;
+ reconcile(): Promise<boolean>;
+ changed(state: RemoteContentRecoveryState): void;
+ completed(elapsedMs: number): void;
+ phaseCompleted?(phase: 'subscription' | 'snapshot', elapsedMs: number): void;
+ now?: () => number;
+ retryMs?: number;
+}) {
+ const now = deps.now ?? Date.now;
+ let generation = 0;
+ let available = true;
+ let disposed = false;
+ let ready = false;
+ let inFlight: number | null = null;
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ let attempt = 0;
+ let startedAt = now();
+ const clearTimer = () => {
+ if (timer) clearTimeout(timer);
+ timer = null;
+ };
+ const request = (): void => {
+ if (disposed || !available || ready || inFlight !== null) return;
+ clearTimer();
+ const current = generation;
+ inFlight = current;
+ void (async () => {
+ try {
+ const subscribeAt = now();
+ await deps.subscribe();
+ if (disposed || generation !== current || !available) return;
+ deps.phaseCompleted?.('subscription', Math.max(0, now() - subscribeAt));
+ const snapshotAt = now();
+ const applied = await deps.reconcile();
+ if (disposed || generation !== current || !available || !applied) return;
+ deps.phaseCompleted?.('snapshot', Math.max(0, now() - snapshotAt));
+ ready = true;
+ attempt = 0;
+ deps.changed('ready');
+ deps.completed(Math.max(0, now() - startedAt));
+ } catch {
+ // Errors stay visible through the existing connection/error surfaces.
+ // Failure must never be translated into a successful content recovery.
+ } finally {
+ inFlight = null;
+ if (disposed || !available || ready) return;
+ if (generation !== current) {
+ request();
+ return;
+ }
+ timer = setTimeout(
+ () => {
+ timer = null;
+ request();
+ },
+ Math.min((deps.retryMs ?? 3_000) * 2 ** Math.min(attempt++, 4), 30_000),
+ );
+ }
+ })();
+ };
+ return {
+ request,
+ isReady: () => ready,
+ invalidate(nextAvailable: boolean) {
+ if (disposed) return;
+ generation++;
+ available = nextAvailable;
+ ready = false;
+ attempt = 0;
+ startedAt = now();
+ clearTimer();
+ deps.changed('syncing');
+ },
+ dispose() {
+ disposed = true;
+ generation++;
+ clearTimer();
+ },
+ };
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useRemoteSessionSync.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useRemoteSessionSync.ts
index 84f6d3a819..2bbaf6e6fc 100644
--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useRemoteSessionSync.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useRemoteSessionSync.ts
@@ -23,6 +23,7 @@ import { makerChatStore } from '@/lib/makerChatStore';
import { isSessionTurnRunningFor } from '@/lib/makerTransport';
import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
import { refreshRemoteDeviceSessions } from '@/features/device-link/refreshRemoteSessions';
+import { createRemoteContentRecovery, type RemoteContentRecoveryState } from './remoteContentRecovery';
const log = createLogger('useRemoteSessionSync');
@@ -336,6 +337,7 @@ export function createRemoteSessionSyncEngine(
// ─── React adapter ────────────────────────────────────────────────────────────
export interface RemoteSessionSync {
+ contentState: RemoteContentRecoveryState;
/** 手动重新同步(banner 按钮):重订阅重 topic + 对账消息 + 重拉会话列表。 */
resync: () => void;
/**
@@ -353,6 +355,7 @@ export function useRemoteSessionSync(
): RemoteSessionSync {
const engineRef = useRef<RemoteSyncEngine | null>(null);
const [suspectStall, setSuspectStall] = useState(false);
+ const [content, setContent] = useState({ sessionId, deviceId, state: 'syncing' as RemoteContentRecoveryState });
const resync = useCallback(() => {
setSuspectStall(false);
@@ -369,12 +372,21 @@ export function useRemoteSessionSync(
engineRef.current = null;
return;
}
+ setContent({ sessionId, deviceId, state: 'syncing' });
+ const recovery = createRemoteContentRecovery({
+ subscribe: () => window.electronAPI.deviceLink.subscribe(deviceId, [`session:${sessionId}`]),
+ reconcile: () => makerChatStore.reconcileRemoteMessages(sessionId),
+ changed: (state) => setContent({ sessionId, deviceId, state }),
+ completed: (elapsedMs) => log.info('remote content recovered', { elapsedMs }),
+ phaseCompleted: (phase, elapsedMs) => log.debug('remote recovery phase completed', { phase, elapsedMs }),
+ });
// 每个 (sessionId, deviceId) 绑定一个 engine;getTarget 返回本 effect 的常量,
// dispose 退订的就是本次订阅的 topic(不受后续 session 切换影响)。
const engine = createRemoteSessionSyncEngine(
() => ({ sessionId, deviceId }),
{
subscribe: (d, topics) => {
+ if (!recovery.isReady()) { recovery.request(); return; }
return window.electronAPI.deviceLink
.subscribe(d, topics)
.catch((err) => log.warn('device-link subscribe(session) failed', err));
@@ -383,6 +395,7 @@ export function useRemoteSessionSync(
return window.electronAPI.deviceLink.unsubscribe(d, topics).catch(() => {});
},
reconcile: (s) => {
+ if (!recovery.isReady()) { recovery.request(); return; }
// 挂起交互(permission/ask/plan)重建已并入 reconcileRemoteMessages 的同一代
// (远程回执的新鲜度语义需要两者同代落地),这里不再单独调用。
void makerChatStore.reconcileRemoteMessages(s);
@@ -416,11 +429,30 @@ export function useRemoteSessionSync(
// 切回时如果 isRunning=true → 可能是切走期间 done 丢了 → 延迟核实被控端
engine.reconcileOnMount();
+ let relayAvailable: boolean | undefined;
+ let peerAvailable: boolean | undefined = remoteProjectsStore.getDeviceIds().includes(deviceId);
+ let peerResponsive: boolean | undefined;
+ const offPeerReset = window.electronAPI.deviceLink.onPeerLinkReset?.((p) => {
+ if (p.deviceId !== deviceId) return;
+ recovery.invalidate(relayAvailable !== false && peerAvailable !== false && peerResponsive !== false);
+ // subscribe already waits for the existing per-peer openLink. Only its new
+ // ACK followed by an applied snapshot can restore this view's readiness.
+ recovery.request();
+ });
const offStatus = window.electronAPI.deviceLink.onStatusChanged((p) => {
+ const online = p.status === 'online';
+ if (relayAvailable !== online) recovery.invalidate(online);
+ relayAvailable = online;
+ if (!online) peerAvailable = undefined;
if (p.status !== 'online') return;
engine.handleOnline();
});
const offPresence = window.electronAPI.deviceLink.onPresenceChanged((snap) => {
+ if (snap.deviceId === deviceId) {
+ const available = snap.online && snap.remoteControlEnabled;
+ if (peerAvailable !== available) recovery.invalidate(available && relayAvailable !== false);
+ peerAvailable = available;
+ }
engine.handlePresence(snap.deviceId, snap.online);
});
// 「设备无响应」熔断恢复(main 权威)→ 与 relay 上线同处理:重订阅 + 对账。
@@ -429,6 +461,11 @@ export function useRemoteSessionSync(
// (relay online / presence online / focus / turn 结束)一个都不会发生,恢复后
// 视图会继续缺消息。连接类状态的恢复必须全自动,不能靠横幅按钮兜(review P2)。
const offResponsiveness = window.electronAPI.deviceLink.onResponsivenessChanged((p) => {
+ if (p.deviceId === deviceId) {
+ const responsive = !p.unresponsive;
+ if (peerResponsive !== responsive) recovery.invalidate(responsive && relayAvailable !== false && peerAvailable !== false);
+ peerResponsive = responsive;
+ }
if (p.unresponsive) return;
engine.handleResponsivenessRecovered(p.deviceId);
});
@@ -441,9 +478,11 @@ export function useRemoteSessionSync(
window.addEventListener('focus', onFocus);
return () => {
+ recovery.dispose();
offStatus();
offPresence();
offResponsiveness();
+ offPeerReset?.();
offStore();
window.removeEventListener('focus', onFocus);
engine.dispose();
@@ -451,5 +490,6 @@ export function useRemoteSessionSync(
};
}, [sessionId, deviceId]);
- return { resync, suspectStall, forceFinalize };
+ const contentState = content.sessionId === sessionId && content.deviceId === deviceId ? content.state : 'syncing';
+ return { resync, suspectStall, forceFinalize, contentState };
}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 6f1c7ffaa3..10f5d35587 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -8597,6 +8597,8 @@
"runningTool": "{{tool}} running…"
},
"remoteSession": {
+ "syncing": "Syncing…",
+ "recovered": "Restored",
"reconnecting": "Connection to the controlled device was lost — reconnecting…",
"hostOffline": "The controlled device is offline; can't sync right now",
"degraded": "Connection to the controlled device is unstable — retrying automatically…",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index aaa39e0259..cbdaf1a130 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -8582,6 +8582,8 @@
"runningTool": "{{tool}} を実行中…"
},
"remoteSession": {
+ "syncing": "同期中…",
+ "recovered": "復旧しました",
"reconnecting": "被制御デバイスとの接続が切れました。再接続中…",
"hostOffline": "被制御デバイスがオフラインのため、現在は同期できません",
"degraded": "被制御デバイスとの接続が不安定です。自動的に再試行中…",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index e2a0e11f54..d84651ce4d 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -8582,6 +8582,8 @@
"runningTool": "{{tool}} 실행 중…"
},
"remoteSession": {
+ "syncing": "동기화 중…",
+ "recovered": "복구됨",
"reconnecting": "제어 대상 기기와 연결이 끊겼습니다. 다시 연결 중…",
"hostOffline": "제어 대상 기기가 오프라인이라 지금은 동기화할 수 없습니다",
"degraded": "제어 대상 기기와 연결이 불안정합니다. 자동으로 다시 시도 중…",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index da1d14590e..98a9647f35 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -8582,6 +8582,8 @@
"runningTool": "{{tool}} 运行中…"
},
"remoteSession": {
+ "syncing": "正在同步…",
+ "recovered": "已恢复",
"reconnecting": "与被控设备的连接中断,正在重连…",
"hostOffline": "被控设备已离线,暂时无法同步",
"degraded": "与被控设备的连接不稳定,正在自动重试…",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 851d10f218..4497c1256b 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -8582,6 +8582,8 @@
"runningTool": "{{tool}} 執行中…"
},
"remoteSession": {
+ "syncing": "正在同步…",
+ "recovered": "已恢復",
"reconnecting": "與被控裝置的連線中斷,正在重連…",
"hostOffline": "被控裝置已離線,暫時無法同步",
"degraded": "與被控裝置的連線不穩定,正在自動重試…",
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 35206f0f9e..0458b86182 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -11048,12 +11048,12 @@ function reconcileOpenSessionOrigins(): void {
*/
const _remoteReconcileInFlight = new Map<
string,
- { run: Promise<void>; rerun: boolean; rerunForce: boolean }
+ { run: Promise<boolean>; rerun: boolean; rerunForce: boolean }
>();
-function reconcileRemoteMessages(sessionId: string, opts?: { force?: boolean }): Promise<void> {
+function reconcileRemoteMessages(sessionId: string, opts?: { force?: boolean }): Promise<boolean> {
// 返回完成 promise 供调用方需要时等待;既有调用方均按 fire-and-forget 使用。
- if (!sessionId || !isRemoteSession(sessionId)) return Promise.resolve();
+ if (!sessionId || !isRemoteSession(sessionId)) return Promise.resolve(false);
const inFlight = _remoteReconcileInFlight.get(sessionId);
if (inFlight) {
inFlight.rerun = true;
@@ -11061,24 +11061,26 @@ function reconcileRemoteMessages(sessionId: string, opts?: { force?: boolean }):
void reconcilePendingInteractions(sessionId).catch(() => undefined);
return inFlight.run;
}
- const entry: { run: Promise<void>; rerun: boolean; rerunForce: boolean } = {
- run: Promise.resolve(),
+ const entry: { run: Promise<boolean>; rerun: boolean; rerunForce: boolean } = {
+ run: Promise.resolve(false),
rerun: false,
rerunForce: false,
};
_remoteReconcileInFlight.set(sessionId, entry);
entry.run = (async () => {
+ let applied = false;
try {
- await runRemoteReconcile(sessionId, opts);
+ applied = await runRemoteReconcile(sessionId, opts);
} finally {
const rerun = entry.rerun;
const rerunForce = entry.rerunForce;
// 先摘掉在飞标记,再补跑 —— 补跑会自己建新的 entry,期间来的触发继续被那一份合并。
_remoteReconcileInFlight.delete(sessionId);
if (rerun && sessions.has(sessionId)) {
- await reconcileRemoteMessages(sessionId, rerunForce ? { force: true } : undefined);
+ applied = await reconcileRemoteMessages(sessionId, rerunForce ? { force: true } : undefined);
}
}
+ return applied;
})();
// 显式挂一个吞掉的 rejection handler:返回的 promise 语义不变(仍然会 reject,需要的调用方照样
// 能 await 到),但 Node / renderer 不再把它当成 unhandled rejection —— 绝大多数调用方是
@@ -11088,7 +11090,7 @@ function reconcileRemoteMessages(sessionId: string, opts?: { force?: boolean }):
return entry.run;
}
-function runRemoteReconcile(sessionId: string, opts?: { force?: boolean }): Promise<void> {
+function runRemoteReconcile(sessionId: string, opts?: { force?: boolean }): Promise<boolean> {
// 挂起交互面板重建**无条件先行**,不受下方 isStreaming 守卫约束:turn 内弹出的
// permission / ask / plan 正是 isStreaming=true 的常见态(pendingPermission 与
// isRunning 共存),断连重连 / 聚焦时若被守卫吞掉,交互面板不重建、用户无法回应,
@@ -11113,8 +11115,8 @@ function runRemoteReconcile(sessionId: string, opts?: { force?: boolean }): Prom
// 映射成 Promise<void> 并吞掉 rejection(engine 路径 fire-and-forget 无 catch;
// 失败已由 reconcilePendingInteractions 内部日志记录)。
return interactionsSync.then(
- () => undefined,
- () => undefined,
+ () => false,
+ () => false,
);
}
const existingIds = new Set(state.messages.map((m) => m.clientId));
@@ -11168,7 +11170,6 @@ function runRemoteReconcile(sessionId: string, opts?: { force?: boolean }): Prom
}
before = oldest.id;
}
- if (collected.length === 0) return;
// 本次对账整体作废的两种情形:
// 1. 代际已变:窗口被 rewind / clear / trim / demote / 另一次对账重建过;
// 2. 已经有一次**更晚启动**的对账成功落地过:它读到的是更新的真相,本次的 existingIds
@@ -11187,6 +11188,7 @@ function runRemoteReconcile(sessionId: string, opts?: { force?: boolean }): Prom
windowApplied = false;
return;
}
+ if (collected.length === 0) return;
const mapped = mapServerMessages(collected);
// 翻满上限仍没接回已知区段 → 下面走权威重建分支:整片旧窗口被换掉、oldestMessageId
// 也被改写。这是第八条"整体重建窗口"的路径,必须 bump epoch 作废 in-flight 的翻页 /
@@ -11309,7 +11311,7 @@ function runRemoteReconcile(sessionId: string, opts?: { force?: boolean }): Prom
},
(err) => log.warn('reconcileRemoteMessages failed', { sessionId, err: String(err) }),
);
- return run;
+ return run.then(() => windowApplied);
}
/**
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 53b4e8a095..eed55341c7 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -3792,6 +3792,8 @@ interface ElectronAPI {
) => () => void;
/** 「保持电脑唤醒」在其它共享 userData 实例被翻转后推送 */
onKeepAwakeChanged: (cb: (payload: { keepAwake: boolean }) => void) => () => void;
+ /** Main 本地投影:单个 peer 的恢复作废旧内容就绪证据,不代表 relay 离线。 */
+ onPeerLinkReset?: (cb: (payload: { deviceId: string }) => void) => () => void;
/** 控制端:目标设备「无响应」熔断状态翻转(弱网 / 对端卡死;presence 可能仍在线) */
onResponsivenessChanged: (
cb: (payload: { deviceId: string; unresponsive: boolean }) => void,
diff --git a/apps/desktop/src/shared/deviceLinkIpc.ts b/apps/desktop/src/shared/deviceLinkIpc.ts
index 5a6d1987bf..d6b3bfda02 100644
--- a/apps/desktop/src/shared/deviceLinkIpc.ts
+++ b/apps/desktop/src/shared/deviceLinkIpc.ts
@@ -59,6 +59,8 @@ export const DEVICE_LINK_INVOKE = {
/** main → renderer push */
export const DEVICE_LINK_PUSH = {
+ /** Local peer recovery invalidates content readiness; payload: { deviceId }. Not a wire push. */
+ PEER_LINK_RESET: 'device-link:peer-link-reset',
/** 同账号某设备 presence 变化(上线/下线/开关/busy),payload: PresenceSnapshot */
PRESENCE_CHANGED: 'device-link:presence-changed',
/** 本机 relay 连接状态变化,payload: { status: 'stopped'|'connecting'|'online' } */
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index c2595b3d09..fbb89a3f7c 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -984,6 +984,7 @@ export default function SessionScreen() {
connectionEpoch,
connectionIssue,
getPresenceAvailability,
+ getSubscriptionIdentity,
invoke,
openLink,
reopenLink,
@@ -1652,6 +1653,14 @@ export default function SessionScreen() {
// lastSyncedAt 不会归零,不能用来判断「当前会话本次连接已同步」。epoch 经 ref 读取,
// 避免把 connectionEpoch 加进 syncSession deps 引发额外整窗重拉。
const [readAckSyncedKey, setReadAckSyncedKey] = useState<string | null>(null);
+ const [contentSyncedKey, setContentSyncedKey] = useState<string | null>(null);
+ const subscriptionAck = deviceId && sessionId
+ ? getSubscriptionIdentity?.(deviceId, ['sessions', `session:${sessionId}`]) ?? null
+ : null;
+ const contentRecoveryKey = subscriptionAck === null ? null
+ : JSON.stringify([deviceId, sessionId, connectionEpoch, subscriptionAck]);
+ const contentRecoveryKeyRef = useRef(contentRecoveryKey);
+ contentRecoveryKeyRef.current = contentRecoveryKey;
// interrupted 只依赖 getSession 的权威时间戳;兄弟快照失败不能把这道门永久关住。
// 已读回执仍继续使用上面的整窗门槛,避免消息未同步就提前清 attention。
const [sessionMetadataSyncedKey, setSessionMetadataSyncedKey] = useState<string | null>(null);
@@ -1986,11 +1995,22 @@ export default function SessionScreen() {
);
// 弱网普通断线也要有可见信号(消息流静默停更没有任何提示),经防闪延迟后显示
const connectionRecoveryError = activeOutboxTransportError ?? connectionError;
+ const contentRecoveryState = contentRecoveryKey !== null
+ && contentSyncedKey === contentRecoveryKey
+ && readAckSyncedKey === `${sessionId}:${connectionEpoch}`
+ && !outboxRecoverySyncHeld
+ ? 'recovered' : 'syncing';
+ const recoveryStartedAtRef = useRef(Date.now());
+ useEffect(() => {
+ if (contentRecoveryState === 'syncing') recoveryStartedAtRef.current = Date.now();
+ else console.debug('[device-link] content recovered', { elapsedMs: Date.now() - recoveryStartedAtRef.current });
+ }, [contentRecoveryState]);
const showConnectionBanner = useShowConnectionBanner(
status,
connectionRecoveryError,
connectionIssue,
isDeviceUnresponsive,
+ contentRecoveryState,
);
const hasCurrentSession = currentSession !== null;
const currentAgentKind = useMemo(
@@ -3100,6 +3120,8 @@ export default function SessionScreen() {
}, [connectionEpoch, deviceId, lastSyncedAt, maker, openLink, sessionAgentSwitchSupported, sessionId]);
const syncSession = useCallback(async (syncRun: Pick<RemoteSyncRun, 'isStale' | 'replaceMessages'>) => {
+ const contentKeyAtStart = contentRecoveryKeyRef.current;
+ const snapshotStartedAt = Date.now();
const options = { replaceMessages: syncRun.replaceMessages };
if (!deviceId || !sessionId || syncRun.isStale()) return;
const messageAuthority = remoteSessionStore.captureSessionMessageAuthority(sessionId);
@@ -3331,6 +3353,10 @@ export default function SessionScreen() {
// 不在 connectionEpoch 刚推进时提前清,避免同一 commit 的 outbox effect 抢在 resync 前派发。
setOutboxTransportHold((current) => current?.deviceId === deviceId ? null : current);
setLastSyncedAt(Date.now());
+ setContentSyncedKey(contentKeyAtStart);
+ if (contentKeyAtStart !== null && contentRecoveryKeyRef.current === contentKeyAtStart) {
+ console.debug('[device-link] recovery snapshot applied', { elapsedMs: Date.now() - snapshotStartedAt });
+ }
// 已读回执门槛:本会话在当前连接代完成过整窗同步。sessionId / epoch / 门槛代号
// 都取 sync 开始时的快照——原地切 session、重连、attention 上升沿之后,启动更早
// 的 in-flight sync 一律放弃落 key,只有触发点之后启动的 sync 才能重新写开门槛。
@@ -3363,6 +3389,13 @@ export default function SessionScreen() {
(run) => syncSession(run),
remoteSyncContextKey,
);
+ // A snapshot fetched before the subscription ACK can miss the gap between
+ // the two. Reuse the existing coordinator to reconcile after this exact ACK.
+ useEffect(() => {
+ if (!contentRecoveryKey || status !== 'online') return;
+ if (!messageScreenFocusedRef.current || !messageAppActiveRef.current) return;
+ void requestSync({ reason: 'subscription-acked', replaceMessages: false });
+ }, [contentRecoveryKey, requestSync, status]);
const load = useCallback(
() => requestSync({ reason: 'passive-refresh' }),
[requestSync],
@@ -8686,6 +8719,7 @@ export default function SessionScreen() {
loading={loading}
onSync={() => void requestSync({ reason: 'manual', replaceMessages: false })}
status={status}
+ recovery={contentRecoveryState}
variant="inline"
/>
) : null}
diff --git a/apps/mobile/package.json b/apps/mobile/package.json
index abf855e855..b7b57596ad 100644
--- a/apps/mobile/package.json
+++ b/apps/mobile/package.json
@@ -37,6 +37,7 @@
"expo-linking": "^57.0.8",
"expo-localization": "~57.0.1",
"expo-media-library": "~57.0.4",
+ "expo-network": "~57.0.1",
"expo-notifications": "~57.0.15",
"expo-paste-input": "0.2.2",
"expo-router": "^57.0.17",
diff --git a/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.ts b/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.ts
index 55f82ba4d8..eb369c4118 100644
--- a/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.ts
+++ b/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.ts
@@ -130,7 +130,8 @@ describe('live stream interruption wiring', () => {
// 持有的 topic 必须重新评估,不能和已释放 topic 一起饿死。
expect(sendSubscribe).toContain('.filter((topic) => registryRef.current.hasTopic(deviceId, topic))');
expect(sendSubscribe).toContain('toSend.every((topic) => registryRef.current.hasTopic(deviceId, topic))');
- expect(sendSubscribe).toContain('if (!sent) {');
+ // The production loop is behavior-tested in subscriptionAcknowledgements.test.ts.
+ expect(sendSubscribe).toContain('await confirmTrackedSubscription({');
// 反向竞态同样要守住:快速释放后又切回时,旧 unsubscribe 在真正发帧前必须
// 剔除已经重新被 owner 持有的 topic,不能落在新 subscribe 后把实时流再关掉。
expect(source).toContain('(topic) => !registryRef.current.hasTopic(deviceId, topic)');
diff --git a/apps/mobile/src/__tests__/subscriptionAcknowledgements.test.ts b/apps/mobile/src/__tests__/subscriptionAcknowledgements.test.ts
new file mode 100644
index 0000000000..de4cd8b3ef
--- /dev/null
+++ b/apps/mobile/src/__tests__/subscriptionAcknowledgements.test.ts
@@ -0,0 +1,86 @@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ confirmTrackedSubscription,
+ SubscriptionAcknowledgements,
+} from '../device-link/subscriptionAcknowledgements';
+import {
+ DeviceLinkTopicRegistry,
+ markHeldRemoteTopicsSubscribed,
+ markRemoteTopicsSubscribed,
+ markRemoteTopicsUnsubscribed,
+ topicsMissingRemoteAck,
+} from '../device-link/topicRegistry';
+
+describe('subscription recovery identity', () => {
+ it.each([false, true])(
+ 'retries an invalidated ACK only for topics still owned (release B=%s)',
+ async (releaseB) => {
+ const table = new SubscriptionAcknowledgements(() => {});
+ const registry = new DeviceLinkTopicRegistry();
+ registry.trackSubscribe('list', 'host', ['sessions']);
+ registry.trackSubscribe('a', 'host', ['session:a']);
+ registry.trackSubscribe('b', 'host', ['session:b']);
+ markRemoteTopicsSubscribed(table, 'host', ['sessions', 'session:a']);
+ const replies: Array<(sent: boolean) => void> = [];
+ const send = vi.fn(() => new Promise<boolean>((resolve) => replies.push(resolve)));
+ const run = confirmTrackedSubscription({
+ isCurrent: () => true,
+ generation: () => String(table.generation('host')),
+ missing: () =>
+ topicsMissingRemoteAck(table, 'host', ['session:b']).filter((topic) =>
+ registry.hasTopic('host', topic),
+ ),
+ send,
+ acknowledge: (topics) => {
+ markHeldRemoteTopicsSubscribed(table, registry, 'host', topics);
+ },
+ });
+ markRemoteTopicsUnsubscribed(table, 'host', registry.untrackSubscribe('a', 'host'));
+ if (releaseB) registry.untrackSubscribe('b', 'host');
+ replies[0](true);
+ await Promise.resolve();
+ expect(table.identity('host', ['session:b'])).toBeNull();
+ expect(send).toHaveBeenCalledTimes(releaseB ? 1 : 2);
+ if (!releaseB) replies[1](true);
+ await run;
+ expect(table.identity('host', ['session:b']) !== null).toBe(!releaseB);
+ expect(table.identity('host', ['sessions'])).not.toBeNull();
+ },
+ );
+
+ it('requires both ACKs and invalidates only the affected peer on release', () => {
+ const changed = vi.fn();
+ const table = new SubscriptionAcknowledgements(changed);
+ const topics = ['sessions', 'session:a'] as const;
+ markRemoteTopicsSubscribed(table, 'host', ['sessions']);
+ expect(table.identity('host', topics)).toBeNull();
+ markRemoteTopicsSubscribed(table, 'host', ['session:a']);
+ const first = table.identity('host', topics);
+ expect(first).not.toBeNull();
+ markRemoteTopicsSubscribed(table, 'neighbor', topics);
+ const neighbor = table.identity('neighbor', topics);
+ markRemoteTopicsUnsubscribed(table, 'host', ['session:a']);
+ expect(table.identity('host', topics)).toBeNull();
+ expect(table.identity('neighbor', topics)).toBe(neighbor);
+ markRemoteTopicsSubscribed(table, 'host', ['session:a']);
+ expect(table.identity('host', topics)).not.toBe(first);
+ const calls = changed.mock.calls.length;
+ markRemoteTopicsSubscribed(table, 'host', topics);
+ expect(changed).toHaveBeenCalledTimes(calls);
+ });
+
+ it('fences an ACK started before peer reset, background release or relay reconnect', () => {
+ const table = new SubscriptionAcknowledgements(() => {});
+ const pendingGeneration = table.generation('host');
+ table.delete('host'); // even when the pending first ACK has not arrived yet
+ expect(table.generation('host')).not.toBe(pendingGeneration);
+ markRemoteTopicsSubscribed(table, 'host', ['sessions', 'session:a']);
+ const active = table.generation('host');
+ markRemoteTopicsUnsubscribed(table, 'host', ['session:a']);
+ expect(table.generation('host')).not.toBe(active);
+ const released = table.generation('host');
+ table.clear();
+ expect(table.generation('host')).not.toBe(released);
+ expect(table.identity('host', ['sessions'])).toBeNull();
+ });
+});
diff --git a/apps/mobile/src/components/ConnectionBanner.tsx b/apps/mobile/src/components/ConnectionBanner.tsx
index a826892815..0aa12a9491 100644
--- a/apps/mobile/src/components/ConnectionBanner.tsx
+++ b/apps/mobile/src/components/ConnectionBanner.tsx
@@ -37,18 +37,21 @@ export function useShowConnectionBanner(
error: string | null,
issue: DeviceLinkConnectionIssue | null,
deviceUnresponsive = false,
+ recovery?: 'syncing' | 'recovered',
): boolean {
- const offline = status !== 'online';
+ const offline = status !== 'online' || recovery === 'syncing';
+ const showRecovered = recovery !== undefined;
const [offlineLongEnough, setOfflineLongEnough] = useState(false);
useEffect(() => {
if (!offline) {
- setOfflineLongEnough(false);
- return;
+ if (!showRecovered) { setOfflineLongEnough(false); return; }
+ const timer = setTimeout(() => setOfflineLongEnough(false), 2_000);
+ return () => clearTimeout(timer);
}
const timer = setTimeout(() => setOfflineLongEnough(true), OFFLINE_BANNER_DELAY_MS);
return () => clearTimeout(timer);
- }, [offline]);
- return resolveConnectionBannerVisibility({
+ }, [offline, showRecovered]);
+ return (recovery === 'recovered' && offlineLongEnough) || resolveConnectionBannerVisibility({
offline,
offlineLongEnough,
// 熔断已关后屏幕残留的 DEVICE_UNRESPONSIVE 错误按陈旧丢弃(review P1),
@@ -70,6 +73,7 @@ export function ConnectionBanner({
lastSyncedAt,
onSync,
variant = 'bar',
+ recovery,
}: {
status: DeviceLinkStatus;
loading: boolean;
@@ -82,6 +86,7 @@ export function ConnectionBanner({
lastSyncedAt: number | null;
onSync(): void;
variant?: 'bar' | 'inline';
+ recovery?: 'syncing' | 'recovered';
}) {
const styles = useThemedStyles(makeStyles);
const { t } = useTranslation();
@@ -106,7 +111,7 @@ export function ConnectionBanner({
? 'off'
: showUnresponsive
? 'busy'
- : friendlyError ? 'muted' : status === 'online' ? 'ready' : status === 'connecting' ? 'busy' : 'off';
+ : friendlyError ? 'muted' : recovery === 'syncing' ? 'busy' : status === 'online' ? 'ready' : status === 'connecting' ? 'busy' : 'off';
const compact = density === 'compact';
const title = activeIssue
? activeIssue.kind === 'unstable'
@@ -114,14 +119,16 @@ export function ConnectionBanner({
: connectionIssueTitle(activeIssue.kind)
: showUnresponsive
? t('deviceLink.deviceUnresponsiveTitle')
- : friendlyError ? t('deviceLink.syncFailed') : relayStatusLabel(status);
+ : friendlyError ? t('deviceLink.syncFailed') : status === 'online' && recovery
+ ? t(`deviceLink.recovery.${recovery}`) : relayStatusLabel(status);
const copy = activeIssue
? activeIssue.kind === 'unstable'
? t('deviceLink.unstableHint')
: connectionIssueHint(activeIssue.kind)
: showUnresponsive
? t('deviceLink.deviceUnresponsiveHint')
- : friendlyError ?? relayStatusHint(status, lastSyncedAt);
+ : friendlyError ?? (status === 'online' && recovery === 'syncing'
+ ? t('deviceLink.recovery.syncingHint') : relayStatusHint(status, lastSyncedAt));
return (
<View
style={[
@@ -132,7 +139,7 @@ export function ConnectionBanner({
]}
testID="connection.banner"
>
- <StatusDot tone={tone} pulsing={!activeIssue && (status === 'connecting' || showUnresponsive)} />
+ <StatusDot tone={tone} pulsing={!activeIssue && (status === 'connecting' || showUnresponsive || recovery === 'syncing')} />
<View style={[styles.textBlock, compact && styles.textBlockCompact]}>
<Text
ellipsizeMode="tail"
diff --git a/apps/mobile/src/debug/visualMock.ts b/apps/mobile/src/debug/visualMock.ts
index 85e1422ea2..18ad8a027a 100644
--- a/apps/mobile/src/debug/visualMock.ts
+++ b/apps/mobile/src/debug/visualMock.ts
@@ -138,6 +138,7 @@ export function createVisualMockDeviceLinkContext(): DeviceLinkContextValue {
connectionIssue: null,
presenceVersion: 1,
connectionEpoch: 1,
+ getSubscriptionIdentity: () => 1,
lastPresenceSnapshot: {
deviceId,
deviceName,
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index 76ad2319f3..877bc4a3b1 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -1,4 +1,5 @@
import Constants from 'expo-constants';
+import { confirmTrackedSubscription, SubscriptionAcknowledgements } from './subscriptionAcknowledgements';
import { AppState, Platform } from 'react-native';
import {
DeviceLinkClient,
@@ -142,6 +143,8 @@ export interface DeviceLinkContextValue {
connectionIssue: DeviceLinkConnectionIssue | null;
presenceVersion: number;
connectionEpoch: number;
+ /** Current remote ACK identity; null until every requested topic is confirmed. */
+ getSubscriptionIdentity?(deviceId: string, topics: readonly Topic[]): number | null;
lastPresenceSnapshot: PresenceSnapshot | null;
/** 当前 relay 连接代内的逐设备 availability;null = 本代尚无权威 verdict。 */
getPresenceAvailability(deviceId: string): boolean | null;
@@ -286,7 +289,10 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
currentDataOwnerIdRef.current = auth.user?.id ?? null;
const clientRef = useRef<DeviceLinkClient | null>(null);
const registryRef = useRef(new DeviceLinkTopicRegistry());
- const remoteSubscribedTopicsRef = useRef(new Map<string, Set<Topic>>());
+ const [subscriptionVersion, setSubscriptionVersion] = useState(0);
+ const remoteSubscribedTopicsRef = useRef(new SubscriptionAcknowledgements(
+ () => setSubscriptionVersion((version) => version + 1),
+ ));
// A local reliable ACK reset may happen after the last durable topic/open owner is gone,
// while the client still holds an in-flight reliable frame. Preserve a per-peer transient
// open intent until that exact peer is ready again; never promote it to a shared WSS reset.
@@ -392,12 +398,15 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
deviceId: string,
topics: readonly Topic[],
) => {
- while (!backgroundReleaseInFlightRef.current) {
- const releaseGeneration = backgroundReleaseGenerationRef.current;
- const toSend = topicsMissingRemoteAck(remoteSubscribedTopicsRef.current, deviceId, topics)
- .filter((topic) => registryRef.current.hasTopic(deviceId, topic));
- if (toSend.length === 0) return;
- const sent = await sendSubscribeWithAccessHandling(
+ const releaseGeneration = backgroundReleaseGenerationRef.current;
+ const startedAt = Date.now();
+ await confirmTrackedSubscription({
+ isCurrent: () => !backgroundReleaseInFlightRef.current
+ && backgroundReleaseGenerationRef.current === releaseGeneration && clientRef.current === client,
+ generation: () => `${connectionEpochRef.current}:${remoteSubscribedTopicsRef.current.generation(deviceId)}`,
+ missing: () => topicsMissingRemoteAck(remoteSubscribedTopicsRef.current, deviceId, topics)
+ .filter((topic) => registryRef.current.hasTopic(deviceId, topic)),
+ send: (toSend) => sendSubscribeWithAccessHandling(
client,
deviceId,
toSend,
@@ -405,22 +414,15 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
!backgroundReleaseInFlightRef.current
&& toSend.every((topic) => registryRef.current.hasTopic(deviceId, topic))
),
- );
- if (
- backgroundReleaseInFlightRef.current
- || backgroundReleaseGenerationRef.current !== releaseGeneration
- ) return;
- if (!sent) {
- // Scope changed while ensureOnlineForRequest was waiting. Re-evaluate once more so topics
- // still held by another owner are not starved, while released topics never reach the host.
- continue;
- }
- // 只有仍被持有、真正记进 ACK 表的 topic 才算订阅生效(中途被释放的那些不算)。
- noteSessionLiveStreamsAcked(
- markHeldRemoteTopicsSubscribed(remoteSubscribedTopicsRef.current, registryRef.current, deviceId, toSend),
- );
- return;
- }
+ ),
+ acknowledge: (toSend) => {
+ // 只有仍被持有、真正记进 ACK 表的 topic 才算订阅生效(中途被释放的那些不算)。
+ noteSessionLiveStreamsAcked(
+ markHeldRemoteTopicsSubscribed(remoteSubscribedTopicsRef.current, registryRef.current, deviceId, toSend),
+ );
+ console.debug('[device-link] recovery subscription acknowledged', { elapsedMs: Date.now() - startedAt });
+ },
+ });
}, []);
// 熔断 open 设备的显式代表性探测:openLink 建链(成功按不定论,不关熔断),
@@ -1131,7 +1133,23 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
}
});
+ // Loaded inside the authenticated lifecycle; old native builds keep their
+ // existing heartbeat fallback if the optional runtime module is unavailable.
+ let disposed = false;
+ let networkSubscription: { remove(): void } | undefined;
+ void import('expo-network').then(({ addNetworkStateListener }) => {
+ if (disposed) return;
+ networkSubscription = addNetworkStateListener((network) => {
+ if (AppState.currentState !== 'active' || network.isConnected === false) return;
+ client.notifyNetworkChanged();
+ });
+ }).catch(() => {
+ console.warn('[device-link] network listener unavailable; using heartbeat recovery');
+ });
+
return () => {
+ disposed = true;
+ networkSubscription?.remove();
sub.remove();
clearBackgroundStopTimer();
offUnresponsive();
@@ -1246,6 +1264,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
presenceVersion,
connectionEpoch,
lastPresenceSnapshot,
+ getSubscriptionIdentity: (deviceId, topics) => remoteSubscribedTopicsRef.current.identity(deviceId, topics),
getPresenceAvailability,
openLink,
reopenLink,
@@ -1268,6 +1287,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
subscribe,
unsubscribe,
subscribeRemoteAgentRoster,
+ subscriptionVersion,
]);
return <DeviceLinkContext.Provider value={value}>{children}</DeviceLinkContext.Provider>;
diff --git a/apps/mobile/src/device-link/subscriptionAcknowledgements.ts b/apps/mobile/src/device-link/subscriptionAcknowledgements.ts
new file mode 100644
index 0000000000..9ec82b07b9
--- /dev/null
+++ b/apps/mobile/src/device-link/subscriptionAcknowledgements.ts
@@ -0,0 +1,75 @@
+import type { Topic } from '@cindy/device-link';
+
+/** An ACK from an invalidated subscription cannot complete a still-held owner's
+ * request. Re-evaluate ownership and obtain a fresh ACK, without reopening links. */
+export async function confirmTrackedSubscription(deps: {
+ isCurrent(): boolean;
+ generation(): string;
+ missing(): Topic[];
+ send(topics: Topic[]): Promise<boolean>;
+ acknowledge(topics: Topic[]): void;
+}): Promise<void> {
+ while (deps.isCurrent()) {
+ const generation = deps.generation();
+ const topics = deps.missing();
+ if (topics.length === 0) return;
+ const sent = await deps.send(topics);
+ if (!deps.isCurrent()) return;
+ if (!sent || deps.generation() !== generation) continue;
+ deps.acknowledge(topics);
+ return;
+ }
+}
+
+/** Observable projection of the existing ACK table. A release/re-ACK produces a
+ * new identity even when the final topic names are identical. */
+export class SubscriptionAcknowledgements extends Map<string, Set<Topic>> {
+ private revision = 0;
+ private revisions = new Map<string, number>();
+ private invalidations = new Map<string, number>();
+ private clearedAt = 0;
+ constructor(private readonly changed: () => void) {
+ super();
+ }
+
+ identity(deviceId: string, topics: readonly Topic[]): number | null {
+ const held = this.get(deviceId);
+ return held && topics.every((topic) => held.has(topic))
+ ? (this.revisions.get(deviceId) ?? null)
+ : null;
+ }
+
+ generation(deviceId: string): number {
+ return this.invalidations.get(deviceId) ?? this.clearedAt;
+ }
+
+ override set(deviceId: string, topics: Set<Topic>): this {
+ const previous = this.get(deviceId);
+ if (previous?.size === topics.size && [...topics].every((topic) => previous.has(topic)))
+ return this;
+ super.set(deviceId, topics);
+ this.revisions.set(deviceId, ++this.revision);
+ if (previous && [...previous].some((topic) => !topics.has(topic))) {
+ this.invalidations.set(deviceId, this.revision);
+ }
+ this.changed();
+ return this;
+ }
+
+ override delete(deviceId: string): boolean {
+ const deleted = super.delete(deviceId);
+ this.revisions.delete(deviceId);
+ this.invalidations.set(deviceId, ++this.revision);
+ if (deleted) this.changed();
+ return deleted;
+ }
+
+ override clear(): void {
+ const hadTopics = this.size > 0;
+ super.clear();
+ this.revisions.clear();
+ this.invalidations.clear();
+ this.clearedAt = ++this.revision;
+ if (hadTopics) this.changed();
+ }
+}
diff --git a/apps/mobile/src/device-link/topicRegistry.ts b/apps/mobile/src/device-link/topicRegistry.ts
index 33174216a9..8089a5a740 100644
--- a/apps/mobile/src/device-link/topicRegistry.ts
+++ b/apps/mobile/src/device-link/topicRegistry.ts
@@ -130,7 +130,7 @@ export function markRemoteTopicsSubscribed(
topics: readonly Topic[],
): void {
if (!deviceId || topics.length === 0) return;
- const current = acked.get(deviceId) ?? new Set<Topic>();
+ const current = new Set(acked.get(deviceId));
for (const topic of topics) current.add(topic);
acked.set(deviceId, current);
}
@@ -151,10 +151,11 @@ export function markRemoteTopicsUnsubscribed(
deviceId: string,
topics: readonly Topic[],
): void {
- const current = acked.get(deviceId);
- if (!current) return;
+ if (!acked.has(deviceId)) return;
+ const current = new Set(acked.get(deviceId));
for (const topic of topics) current.delete(topic);
if (current.size === 0) acked.delete(deviceId);
+ else acked.set(deviceId, current);
}
/**
diff --git a/apps/mobile/src/i18n/locales/en/deviceLink.json b/apps/mobile/src/i18n/locales/en/deviceLink.json
index 33a335712f..ce96d91ce3 100644
--- a/apps/mobile/src/i18n/locales/en/deviceLink.json
+++ b/apps/mobile/src/i18n/locales/en/deviceLink.json
@@ -1,4 +1,9 @@
{
+ "recovery": {
+ "syncing": "Syncing…",
+ "recovered": "Restored",
+ "syncingHint": "Updating content from your computer."
+ },
"syncFailed": "Sync failed",
"resync": "Resync",
"resyncing": "Resyncing",
diff --git a/apps/mobile/src/i18n/locales/ja/deviceLink.json b/apps/mobile/src/i18n/locales/ja/deviceLink.json
index d2a5078278..e127b01a3a 100644
--- a/apps/mobile/src/i18n/locales/ja/deviceLink.json
+++ b/apps/mobile/src/i18n/locales/ja/deviceLink.json
@@ -1,4 +1,9 @@
{
+ "recovery": {
+ "syncing": "同期中…",
+ "recovered": "復旧しました",
+ "syncingHint": "パソコンの内容を更新しています。"
+ },
"syncFailed": "同期に失敗しました",
"resync": "再同期",
"resyncing": "再同期しています",
diff --git a/apps/mobile/src/i18n/locales/ko/deviceLink.json b/apps/mobile/src/i18n/locales/ko/deviceLink.json
index cf88ddcbe6..9b3feff7b6 100644
--- a/apps/mobile/src/i18n/locales/ko/deviceLink.json
+++ b/apps/mobile/src/i18n/locales/ko/deviceLink.json
@@ -1,4 +1,9 @@
{
+ "recovery": {
+ "syncing": "동기화 중…",
+ "recovered": "복구됨",
+ "syncingHint": "컴퓨터의 내용을 업데이트하고 있습니다."
+ },
"syncFailed": "동기화 실패",
"resync": "다시 동기화",
"resyncing": "다시 동기화하는 중",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/deviceLink.json b/apps/mobile/src/i18n/locales/zh-CN/deviceLink.json
index 41f4db7dc6..bca686786c 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/deviceLink.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/deviceLink.json
@@ -1,4 +1,9 @@
{
+ "recovery": {
+ "syncing": "正在同步…",
+ "recovered": "已恢复",
+ "syncingHint": "正在更新电脑上的内容。"
+ },
"syncFailed": "同步失败",
"resync": "重新同步",
"resyncing": "正在重新同步",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/deviceLink.json b/apps/mobile/src/i18n/locales/zh-TW/deviceLink.json
index 2f159d70fe..8c44c3633a 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/deviceLink.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/deviceLink.json
@@ -1,4 +1,9 @@
{
+ "recovery": {
+ "syncing": "正在同步…",
+ "recovered": "已恢復",
+ "syncingHint": "正在更新電腦上的內容。"
+ },
"syncFailed": "同步失敗",
"resync": "重新同步",
"resyncing": "正在重新同步",
diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.ts
index 17514bf94b..9625455d73 100644
--- a/packages/device-link/src/__tests__/client.test.ts
+++ b/packages/device-link/src/__tests__/client.test.ts
@@ -114,6 +114,76 @@ function makeHarness(opts?: {
}
const tick = (ms = 0): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
+
+describe('network change probes', () => {
+ it.each([true, false])('debounces hints and retains only a responsive socket (responsive=%s)', async (responsive) => {
+ 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(250);
+ h.client.notifyNetworkChanged();
+ await vi.advanceTimersByTimeAsync(499);
+ expect(socket.sent.filter((e) => e.kind === 'ping')).toHaveLength(0);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(socket.sent.filter((e) => e.kind === 'ping')).toHaveLength(1);
+ // More hints cannot extend the probe deadline.
+ h.client.notifyNetworkChanged();
+ if (responsive) socket.push({ v: PROTOCOL_VERSION, kind: 'pong' });
+ await vi.advanceTimersByTimeAsync(15_000);
+ expect(h.sockets).toHaveLength(responsive ? 1 : 2);
+ expect(socket.closed !== null).toBe(!responsive);
+ } finally { h.client.stop(); vi.useRealTimers(); }
+ });
+
+ it.each([15_000, 25_000])('retains a slow healthy relay within its %s ms latency tolerance', async (handshakeTimeoutMs) => {
+ vi.useFakeTimers();
+ const h = makeHarness({ timing: { pingIntervalMs: 60_000, handshakeTimeoutMs } });
+ try {
+ h.client.start();
+ await vi.advanceTimersByTimeAsync(0);
+ const socket = h.current(); socket.ack();
+ h.client.notifyNetworkChanged();
+ await vi.advanceTimersByTimeAsync(500);
+ await vi.advanceTimersByTimeAsync(handshakeTimeoutMs - 1_000);
+ expect(h.sockets).toHaveLength(1);
+ expect(socket.closed).toBeNull();
+ socket.push({ v: PROTOCOL_VERSION, kind: 'pong' });
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(h.sockets).toHaveLength(1);
+ } finally { h.client.stop(); vi.useRealTimers(); }
+ });
+
+ it('cancels a pending probe on stop and ignores an old socket after restart', 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);
+ h.client.restartConnection('test');
+ await vi.advanceTimersByTimeAsync(0);
+ h.current().ack();
+ h.client.notifyNetworkChanged();
+ await vi.advanceTimersByTimeAsync(500);
+ old.push({ v: PROTOCOL_VERSION, kind: 'pong' });
+ await vi.advanceTimersByTimeAsync(15_000);
+ expect(h.sockets).toHaveLength(3);
+ h.current().ack();
+ h.client.notifyNetworkChanged();
+ h.client.stop();
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(h.sockets).toHaveLength(3);
+ } finally { h.client.stop(); vi.useRealTimers(); }
+ });
+});
+
let inboundLinkId = 0;
async function establishInboundReliableLink(
@@ -945,6 +1015,8 @@ describe('DeviceLinkClient', () => {
},
});
const inboundInvokes: Envelope[] = [];
+ const resetDevices: string[] = [];
+ h.client.onPeerTransportReset(({ deviceId }) => resetDevices.push(deviceId));
h.client.onFrame((env) => {
if (env.kind === 'invoke' && env.src === 'ctrl-healthy') inboundInvokes.push(env);
});
@@ -994,6 +1066,9 @@ describe('DeviceLinkClient', () => {
))).toBe(true);
});
expect(h.client.isLinkReady('ctrl-silent')).toBe(false);
+ // A mutual-control view must also invalidate locally, even though the
+ // remote controller receives transport-timeout and owns reopening the link.
+ expect(resetDevices).toEqual(['ctrl-silent']);
expect(h.client.isLinkReady('ctrl-healthy')).toBe(true);
expect(socket.terminated).toBe(false);
expect(socket.closed).toBeNull();
@@ -1112,6 +1187,8 @@ describe('DeviceLinkClient', () => {
requestTimeoutMs: 5_000,
},
});
+ const onReset = vi.fn();
+ h.client.onPeerTransportReset(onReset);
h.client.start();
await tick();
h.current().ack();
@@ -1155,6 +1232,11 @@ describe('DeviceLinkClient', () => {
))).toBe(true);
});
// 共享 relay 连接完好:没有因互控覆盖误走整连接重连
+ expect(onReset).toHaveBeenCalledTimes(1);
+ expect(onReset).toHaveBeenCalledWith(expect.objectContaining({
+ deviceId: 'dev-b', reason: 'ack-timeout',
+ }));
+ expect(h.client.isLinkReady('dev-b')).toBe(false);
expect(socket.terminated).toBe(false);
expect(h.sockets).toHaveLength(1);
h.client.stop();
diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.ts
index e823eb9cbf..3a9ed5516d 100644
--- a/packages/device-link/src/client.ts
+++ b/packages/device-link/src/client.ts
@@ -412,7 +412,8 @@ export interface DeviceLinkPeerRouteStateChanged {
}
/**
- * 单个 peer 的可靠传输已在本地复位,需要 host 独立重建该 peer。
+ * 单个 peer 的可靠传输已在本地复位。Host 应作废该 peer 的内容就绪证据;
+ * 出站隔离策略由 host 重建,入站方向仍通知对端重开。
*
* 该事件不是 relay/WSS 断线信号;其它 peer 必须继续收发。代次字段供 host
* 丢弃排队期间已经过期的恢复任务。`seq` 只用于诊断,不代表业务请求 id。
@@ -627,6 +628,10 @@ export class DeviceLinkClient {
private pongMisses = 0;
/** 最近一次收到任何有效 relay 帧的时刻;避免把有业务流量的 socket 误判为僵死。 */
private lastInboundAt = 0;
+ private networkChangeTimer: ReturnType<typeof setTimeout> | null = null;
+ private networkProbeTimer: ReturnType<typeof setTimeout> | null = null;
+ private networkProbeStartedAt = 0;
+ private connectionStartedAt = 0;
/** 当前连接的代号,用于丢弃过期 socket 的事件回调 */
private connEpoch = 0;
/** 本轮连接的最后一条 socket error message(升级失败 401 只在 error 事件里可见) */
@@ -783,6 +788,50 @@ export class DeviceLinkClient {
void this.connect(reason);
}
+ /** 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 {
+ if (this.stopped || this.networkProbeTimer) return;
+ if (this.networkChangeTimer) clearTimeout(this.networkChangeTimer);
+ this.networkChangeTimer = setTimeout(() => {
+ this.networkChangeTimer = null;
+ if (this.stopped) return;
+ if (this.status !== 'online') {
+ // Do not interrupt a handshake or bypass relay 1013 cool-down.
+ if (this.reconnectTimer) this.connectNow('network-change');
+ return;
+ }
+ const epoch = this.connEpoch;
+ const socket = this.ws;
+ const startedAt = this.monotonicNow();
+ this.networkProbeStartedAt = startedAt;
+ // A network hint cannot narrow the existing weak-network latency envelope.
+ // Allow at least the normal 15s handshake tolerance (or a larger override)
+ // before discarding a shared socket.
+ this.networkProbeTimer = setTimeout(() => {
+ this.networkProbeTimer = null;
+ if (this.stopped || this.connEpoch !== epoch || this.ws !== socket) return;
+ this.log.info(`network probe timed out (elapsedMs=${this.monotonicNow() - startedAt})`);
+ this.restartConnection('network-probe-timeout');
+ }, Math.max(DEFAULT_TIMING.handshakeTimeoutMs, this.timing.handshakeTimeoutMs));
+ try {
+ this.sendEnvelope({ v: PROTOCOL_VERSION, kind: 'ping' });
+ } catch {
+ // A full send buffer is not proof of a dead relay. Allow inbound traffic
+ // to settle the same bounded probe rather than tearing down immediately.
+ this.log.debug('network probe send deferred; waiting for inbound activity');
+ }
+ }, 500);
+ }
+
+ private clearNetworkProbe(): void {
+ if (this.networkChangeTimer) clearTimeout(this.networkChangeTimer);
+ if (this.networkProbeTimer) clearTimeout(this.networkProbeTimer);
+ this.networkChangeTimer = null;
+ this.networkProbeTimer = null;
+ }
+
/**
* 有界等待连接就绪。online 立即 resolve;否则订阅状态变化,在 timeoutMs 内
* 等到 online 就 resolve,超时 / stopped 则 reject(NOT_CONNECTED)。
@@ -933,7 +982,7 @@ export class DeviceLinkClient {
return () => this.peerRouteStateHandlers.delete(cb);
}
- /** 订阅单 peer 可靠传输复位;host 应只重建 `change.deviceId`。 */
+ /** 订阅单 peer 可靠传输复位;host 恢复只能影响 `change.deviceId`。 */
onPeerTransportReset(
cb: (change: DeviceLinkPeerTransportReset) => void,
): () => void {
@@ -1476,7 +1525,9 @@ export class DeviceLinkClient {
private async connect(reason: string): Promise<void> {
if (this.stopped) return;
+ this.clearNetworkProbe();
this.resetLegacyInboundQueue();
+ this.connectionStartedAt = this.monotonicNow();
this.setStatus('connecting');
const epoch = ++this.connEpoch;
this.lastSocketErrorMessage = null;
@@ -1759,6 +1810,7 @@ export class DeviceLinkClient {
}
private clearTimers(): void {
+ this.clearNetworkProbe();
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
@@ -1843,7 +1895,14 @@ export class DeviceLinkClient {
this.log.warn(`dropping invalid device-link frame kind=${env.kind}`);
return;
}
- if (validForHeartbeat) this.lastInboundAt = this.monotonicNow();
+ if (validForHeartbeat) {
+ this.lastInboundAt = this.monotonicNow();
+ if (this.networkProbeTimer) {
+ clearTimeout(this.networkProbeTimer);
+ this.networkProbeTimer = null;
+ this.log.debug(`network probe confirmed relay activity (elapsedMs=${Math.max(0, this.lastInboundAt - this.networkProbeStartedAt)})`);
+ }
+ }
const ack = parseTransportAck(env);
if (ack) {
@@ -1996,7 +2055,7 @@ export class DeviceLinkClient {
if (wasOnline) {
this.log.info(`duplicate hello-ack while already online (protocol=v${ack.serverProtocolVersion})`);
} else {
- this.log.info(`device-link online (protocol=v${ack.serverProtocolVersion})`);
+ this.log.info(`device-link online (protocol=v${ack.serverProtocolVersion}, elapsedMs=${Math.max(0, this.monotonicNow() - this.connectionStartedAt)})`);
}
return true;
}
@@ -3832,9 +3891,10 @@ export class DeviceLinkClient {
// 关闭;host 收到本地事件后用所有版本都支持的 link-open 恢复。
if (peer.linkAcceptedInbound && peer.supportsTransportTimeoutClose) {
this.notifyTransportTimeoutClose(dst, 1);
- } else if (this.opts.peerFailurePolicy === 'isolate-peer') {
- this.notifyPeerTransportReset(dst, seq, peer.linkGeneration);
}
+ // Both directions share this peer state during mutual control. Notify local
+ // views even when the remote controller owns reopening the inbound link.
+ this.notifyPeerTransportReset(dst, seq, peer.linkGeneration);
}
/**
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 260e29340e..b8cf7293f0 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -671,6 +671,9 @@ importers:
expo-media-library:
specifier: ~57.0.4
+ expo-network:
+ specifier: ~57.0.1
expo-notifications:
specifier: ~57.0.15
@@ -6654,6 +6657,12 @@ packages:
peerDependencies:
react-native: '*'
+ resolution: {integrity: sha512-ndg+FbDDlz6XTpQ6aVuVgyvrYQwMkpcUAvZIXbwrGBbLTSWNzYC/gawYu1BAeDN7O6JTGY98GBVJBov/JH7LgQ==}
+ peerDependencies:
+ expo: '*'
+ react: '*'
+
resolution: {integrity: sha512-H91z4WSFukSQP3dThgh6PCPFrT6VHeR+J2f7CuCOE72JV7YEGcBCir103QY58ocKsdgkodQpnkTU2m8LTHkWLg==}
peerDependencies:
@@ -16933,6 +16942,11 @@ snapshots:
dependencies:
react-native: 0.86.3(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected])
+ dependencies:
+ react: 19.2.3
+
dependencies:
'@expo/image-utils': 0.11.5([email protected])