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(mobile): 隔离 Device Link Peer 恢复与首页同步 (#3590)

Lizid933455d6fa4
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
index 46b72f1d02..930e774021 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
@@ -151,6 +151,7 @@ describe('withCodexUpstreamRecording', () => {
headers: threadId ? { 'thread-id': threadId } : {},
}) as never;
+ // Linux CI shard 下本文件首次 resetModules + import SUT 经常超过默认 5s;断言未变。
it('records the override upstream origin for the request thread', async () => {
const host = await freshCodexProxyHost();
host.resetCodexThreadUpstreamForTest();
diff --git a/apps/mobile/app/devices/index.tsx b/apps/mobile/app/devices/index.tsx
index 5bbcd639ac..6e4a72e06d 100644
--- a/apps/mobile/app/devices/index.tsx
+++ b/apps/mobile/app/devices/index.tsx
@@ -157,12 +157,22 @@ import {
type SyncedProjectOrderSnapshot,
} from '@cindy/maker-shared/project-order-sync';
import { buildHomeSections, homeRowBefore, isFolderHomeRow, type HomeRow, type HomeSection } from '@/session/homeSections';
-import { readHomeViewPreferences, saveHomeViewPreferences } from '@/session/homeViewPreferenceStore';
+import {
+ readHomeViewPreferences,
+ saveHomeViewPreferences,
+ type HomeViewPreferences,
+} from '@/session/homeViewPreferenceStore';
import {
getCachedHomeListSnapshot,
scheduleHomeListSnapshotPersist,
} from '@/session/mobileHomeListCache';
import { startBoundedStartupRead } from '@/session/mobileHomeStartup';
+import {
+ diffHomeDeviceSyncScope,
+ HomeDeviceSyncLimiter,
+ resolveHomeDeviceSyncIds,
+ runHomeDeviceSyncBatch,
+} from '@/session/homeDeviceSync';
import { serializeNewSessionDeviceOptions } from '@/session/newSession';
import {
buildRemoteSessionCardPreview,
@@ -209,6 +219,7 @@ import { fontWeight, iconSize, iconStroke, lineHeight, radius, spacing, typeScal
const LIST_LIMIT = 200;
const DEVICE_LIST_TIMEOUT_MS = 12_000;
+const HOME_LIST_SUBSCRIPTION_OWNER = 'device-list';
// 项目组与自动化组展开后的子列表共用同一个预览限量(设备详情页也 import 复用,避免两处漂移)。
export const PROJECT_PREVIEW_LIMIT = 5;
const HOME_SESSION_ROW_HEIGHT = 78;
@@ -238,10 +249,32 @@ type ProjectDragSession = {
};
type HydrateDeviceSessionsResult = {
failure: string | null;
+ needsRerun?: boolean;
offline: boolean;
superseded: boolean;
};
+type HomeHydrateInFlightEntry = {
+ accountGeneration: number;
+ device: DeviceView;
+ homeSyncGeneration: number;
+ promise: Promise<HydrateDeviceSessionsResult>;
+ rerunRequested: boolean;
+};
+
+type HydrateDeviceSessions = (
+ device: DeviceView,
+ expectedAccountGeneration?: number,
+ options?: { trailingIfInFlight?: boolean },
+) => Promise<HydrateDeviceSessionsResult>;
+
+class HomeSyncScopeSupersededError extends Error {
+ constructor() {
+ super('Home sync scope superseded');
+ this.name = 'HomeSyncScopeSupersededError';
+ }
+}
+
export default function HomeScreen() {
const styles = useThemedStyles(makeStyles);
const { colors } = useTheme();
@@ -254,7 +287,15 @@ export default function HomeScreen() {
const { accountGeneration, apiFetch, deviceId: selfDeviceId, user } = auth;
// 首页列表持久缓存按账号键控(401 掉线换号不串数据);首页仅登录后可达,user 理应非空。
const homeCacheUserId = user?.id ?? '';
- const { connectionEpoch, connectionIssue, invoke, lastPresenceSnapshot, status, subscribe } = useDeviceLink();
+ const {
+ connectionEpoch,
+ connectionIssue,
+ invoke,
+ lastPresenceSnapshot,
+ status,
+ subscribe,
+ unsubscribe,
+ } = useDeviceLink();
const revokedDevices = useRevokedDevices();
const sessions = useRemoteSessions();
const messageVersion = useRemoteMessageVersion();
@@ -271,6 +312,24 @@ export default function HomeScreen() {
// pending 的,避免 800ms 窗口内多次 hydrate 时较早回调用旧快照覆盖新状态(并发覆盖竞态);卸载时 cancelAll。
const scheduleIndexDeferRegistryRef = useRef(createScheduleIndexDeferRegistry());
const scheduleEventVersionsRef = useRef(new Map<string, number>());
+ // Home 只拥有当前显示范围内的 `sessions` topic。target 包含已领取但仍在共享
+ // 六路队列中等待的设备;owned 只包含已经真正调用 subscribe 的设备。两者必须
+ // 分开,否则切换范围会为尚未订阅的排队设备发出一批无意义 unsubscribe。
+ const homeSyncTargetDeviceIdsRef = useRef(new Set<string>());
+ const homeListOwnedDeviceIdsRef = useRef(new Set<string>());
+ // Per-device generation fences A → B → A scope switches. Membership alone is not
+ // sufficient: an old A request may settle after A has been reacquired and must not
+ // overwrite the newer snapshot or release the newer owner's subscription.
+ const homeSyncGenerationByDeviceRef = useRef(new Map<string, number>());
+ // Reconnect rehydrate, presence recovery and Home refresh can all request the same device
+ // at once. Share one authoritative list pull per device + scope generation.
+ const homeHydrateInFlightByDeviceRef = useRef(new Map<string, HomeHydrateInFlightEntry>());
+ const hydrateDeviceSessionsRef = useRef<HydrateDeviceSessions>(async () => ({
+ failure: null,
+ offline: false,
+ superseded: true,
+ }));
+ const homeDeviceSyncLimiterRef = useRef(new HomeDeviceSyncLimiter());
const deviceIdentityCacheRef = useRef(createEmptyDeviceIdentityCache());
// A timed-out SecureStore read may still complete. Do not persist an empty/rebuilt
// cache until that read settles and its stored identities have been reapplied.
@@ -289,10 +348,14 @@ export default function HomeScreen() {
// 首页列表缓存(设备+会话快照)是否已尝试种入:首次 loadHome 等它先落地,保证「先画缓存、
// fresh 回来再覆盖」的顺序确定性(规则 7),缓存为空时该状态同样置 true、行为与现状一致。
const [homeListCacheHydrated, setHomeListCacheHydrated] = useState(false);
+ // 首次网络同步必须等设备筛选偏好恢复,否则单机用户会先按默认“全部”拉一轮所有电脑。
+ const [homeViewPreferencesHydrated, setHomeViewPreferencesHydrated] = useState(false);
const [refreshing, setRefreshing] = useState(false);
const [error, setError] = useState<string | null>(null);
const [lastSyncedAt, setLastSyncedAt] = useState<number | null>(null);
const [selectedDeviceId, setSelectedDeviceId] = useState<string | null>(null);
+ const selectedDeviceIdRef = useRef<string | null>(selectedDeviceId);
+ selectedDeviceIdRef.current = selectedDeviceId;
const [searchOpen, setSearchOpen] = useState(false);
const [searchFilterOpen, setSearchFilterOpen] = useState(false);
// 恢复偏好时暂存的设备名:设备列表尚未同步回来前表头用它兜底,避免显示成占位文案。
@@ -381,6 +444,10 @@ export default function HomeScreen() {
syncInFlightRef.current = null;
syncQueuedRef.current = null;
devicesRef.current = [];
+ homeSyncTargetDeviceIdsRef.current.clear();
+ homeListOwnedDeviceIdsRef.current.clear();
+ homeSyncGenerationByDeviceRef.current.clear();
+ homeHydrateInFlightByDeviceRef.current.clear();
scheduleIndexDeferRegistryRef.current.cancelAll();
scheduleEventVersionsRef.current.clear();
presenceFreshnessRef.current = createPresenceFreshnessTracker();
@@ -414,6 +481,56 @@ export default function HomeScreen() {
setDeviceConnectionStates((current) => updateHomeDeviceConnectionState(current, deviceId, state));
}, []);
+ const isCurrentHomeSyncTarget = useCallback((deviceId: string, generation?: number) => {
+ const selected = selectedDeviceIdRef.current;
+ return (
+ (!selected || selected === deviceId)
+ && homeSyncTargetDeviceIdsRef.current.has(deviceId)
+ && (
+ generation === undefined
+ || homeSyncGenerationByDeviceRef.current.get(deviceId) === generation
+ )
+ );
+ }, []);
+
+ const advanceHomeSyncGeneration = useCallback((deviceId: string) => {
+ const next = (homeSyncGenerationByDeviceRef.current.get(deviceId) ?? 0) + 1;
+ homeSyncGenerationByDeviceRef.current.set(deviceId, next);
+ return next;
+ }, []);
+
+ const releaseHomeListOwner = useCallback((deviceId: string) => {
+ if (!homeListOwnedDeviceIdsRef.current.delete(deviceId)) return;
+ updateDeviceConnectionState(deviceId, 'idle');
+ // unsubscribe 会同步先撤销 registry owner,再等待远端 ACK;即使弱网下 ACK 失败,
+ // 下一次重连也不会恢复这台已不可见设备。缓存刻意不删,切回来先画旧快照。
+ void unsubscribe(HOME_LIST_SUBSCRIPTION_OWNER, deviceId, ['sessions']).catch(() => undefined);
+ }, [unsubscribe, updateDeviceConnectionState]);
+
+ const reconcileHomeDeviceSyncScope = useCallback((desiredDeviceIds: readonly string[]) => {
+ const diff = diffHomeDeviceSyncScope(homeSyncTargetDeviceIdsRef.current, desiredDeviceIds);
+ homeSyncTargetDeviceIdsRef.current = new Set(desiredDeviceIds);
+
+ for (const deviceId of diff.release) {
+ advanceHomeSyncGeneration(deviceId);
+ releaseHomeListOwner(deviceId);
+ }
+ for (const deviceId of diff.acquire) {
+ advanceHomeSyncGeneration(deviceId);
+ }
+ return diff;
+ }, [advanceHomeSyncGeneration, releaseHomeListOwner]);
+
+ useEffect(() => () => {
+ const owned = [...homeListOwnedDeviceIdsRef.current];
+ homeListOwnedDeviceIdsRef.current.clear();
+ homeSyncTargetDeviceIdsRef.current.clear();
+ for (const deviceId of owned) advanceHomeSyncGeneration(deviceId);
+ for (const deviceId of owned) {
+ void unsubscribe(HOME_LIST_SUBSCRIPTION_OWNER, deviceId, ['sessions']).catch(() => undefined);
+ }
+ }, [advanceHomeSyncGeneration, unsubscribe]);
+
const reconcileDeviceViews = useCallback((nextRawDevices: readonly DeviceView[]) => {
const result = reconcileDeviceIdentities(nextRawDevices, deviceIdentityCacheRef.current);
deviceIdentityCacheRef.current = result.cache;
@@ -448,22 +565,36 @@ export default function HomeScreen() {
const refreshDeviceScheduleIndex = useCallback((
deviceId: string,
sessionIds: readonly string[],
- options?: { accountGeneration?: number; force?: boolean },
+ options?: { accountGeneration?: number; force?: boolean; homeSyncGeneration?: number },
) => {
const expectedAccountGeneration = options?.accountGeneration ?? accountGeneration;
+ const expectedHomeSyncGeneration = options?.homeSyncGeneration
+ ?? homeSyncGenerationByDeviceRef.current.get(deviceId);
if (homeAccountGenerationRef.current !== expectedAccountGeneration) return;
+ if (
+ expectedHomeSyncGeneration === undefined
+ || !isCurrentHomeSyncTarget(deviceId, expectedHomeSyncGeneration)
+ ) return;
// 节流(单飞 + 30s TTL):focus / hydrate / schedule 推送三个触发源高频交叠,每次都全量
// 重放 1+N×listRuns 会拥塞 device-link 管道、拖慢会话打开的关键读(见 scheduleIndex 注释)。
// force = 已读类权威信号(read / all-read 推送),必须绕过 TTL 立即重拉——否则「看完
// 返回首页」这个最常见路径永远命中 30s 内的陈旧缓存,未读徽标清不掉(review P1)。
const invalidationVersion = getScheduleIndexInvalidationVersion(deviceId);
- void loadSessionScheduleIndexThrottled(
- deviceId,
- () => loadDeviceSessionScheduleIndex(deviceId, invoke),
- { force: options?.force },
- )
+ void homeDeviceSyncLimiterRef.current.run(async () => {
+ if (
+ homeAccountGenerationRef.current !== expectedAccountGeneration
+ || !isCurrentHomeSyncTarget(deviceId, expectedHomeSyncGeneration)
+ ) return null;
+ return loadSessionScheduleIndexThrottled(
+ deviceId,
+ () => loadDeviceSessionScheduleIndex(deviceId, invoke),
+ { force: options?.force },
+ );
+ })
.then((nextIndex) => {
+ if (!nextIndex) return;
if (homeAccountGenerationRef.current !== expectedAccountGeneration) return;
+ if (!isCurrentHomeSyncTarget(deviceId, expectedHomeSyncGeneration)) return;
if (getScheduleIndexInvalidationVersion(deviceId) !== invalidationVersion) return;
setScheduleIndex((current) => replaceSessionScheduleIndexEntries(
current,
@@ -474,29 +605,48 @@ export default function HomeScreen() {
.catch(() => {
// 网络失败时保留旧数据,不清零已有徽标——数据清零只应由明确的"已读"事件触发。
});
- }, [accountGeneration, invoke]);
+ }, [accountGeneration, invoke, isCurrentHomeSyncTarget]);
- const hydrateDeviceSessions = useCallback(async (
+ const hydrateDeviceSessionsOnce = useCallback((
device: DeviceView,
- expectedAccountGeneration = accountGeneration,
- ): Promise<HydrateDeviceSessionsResult> => {
- if (homeAccountGenerationRef.current !== expectedAccountGeneration) {
+ expectedAccountGeneration: number,
+ expectedHomeSyncGeneration: number,
+ ): Promise<HydrateDeviceSessionsResult> => homeDeviceSyncLimiterRef.current.run(async () => {
+ if (
+ homeAccountGenerationRef.current !== expectedAccountGeneration
+ || !isCurrentHomeSyncTarget(device.deviceId, expectedHomeSyncGeneration)
+ ) {
return { failure: null, offline: false, superseded: true };
}
updateDeviceConnectionState(device.deviceId, 'syncing');
try {
- const [list, activeSessions, activeSessionSnapshotEpoch] = await withTransientRemoteRetry(async () => {
- if (homeAccountGenerationRef.current !== expectedAccountGeneration) {
- throw new Error('Home account generation superseded');
+ const [
+ list,
+ activeSessions,
+ activeSessionSnapshotEpoch,
+ sessionListMutationEpoch,
+ ] = await withTransientRemoteRetry(async () => {
+ if (
+ homeAccountGenerationRef.current !== expectedAccountGeneration
+ || !isCurrentHomeSyncTarget(device.deviceId, expectedHomeSyncGeneration)
+ ) {
+ throw new HomeSyncScopeSupersededError();
}
- await subscribe('device-list', device.deviceId, ['sessions']);
- if (homeAccountGenerationRef.current !== expectedAccountGeneration) {
- throw new Error('Home account generation superseded');
+ homeListOwnedDeviceIdsRef.current.add(device.deviceId);
+ await subscribe(HOME_LIST_SUBSCRIPTION_OWNER, device.deviceId, ['sessions']);
+ if (
+ homeAccountGenerationRef.current !== expectedAccountGeneration
+ || !isCurrentHomeSyncTarget(device.deviceId, expectedHomeSyncGeneration)
+ ) {
+ throw new HomeSyncScopeSupersededError();
}
// Capture inside the retry callback so every maker:list-active attempt gets its own
// fence. A newer retry push received while this request is in flight must survive
// the older snapshot, while progress predating this attempt can be cleared.
const activeSessionSnapshotEpoch = remoteSessionStore.captureActiveSessionSnapshotEpoch();
+ const sessionListMutationEpoch = remoteSessionStore.captureDeviceSessionListMutationEpoch(
+ device.deviceId,
+ );
const [list, activeSessions] = await Promise.all([
invoke<RemoteSession[]>(device.deviceId, 'local-db:sessions:list', [
LIST_LIMIT,
@@ -512,11 +662,33 @@ export default function HomeScreen() {
throw err;
}),
]);
- return [list, activeSessions, activeSessionSnapshotEpoch] as const;
+ return [
+ list,
+ activeSessions,
+ activeSessionSnapshotEpoch,
+ sessionListMutationEpoch,
+ ] as const;
});
- if (homeAccountGenerationRef.current !== expectedAccountGeneration) {
+ if (
+ homeAccountGenerationRef.current !== expectedAccountGeneration
+ || !isCurrentHomeSyncTarget(device.deviceId, expectedHomeSyncGeneration)
+ ) {
return { failure: null, offline: false, superseded: true };
}
+ if (!remoteSessionStore.isDeviceSessionListMutationEpochCurrent(
+ device.deviceId,
+ sessionListMutationEpoch,
+ )) {
+ // A list-level push landed after this snapshot started. Keep the live mutation and
+ // run one trailing authoritative pull; applying this older whole-list response would
+ // roll back sessions:patched or hide a just-created task.
+ return {
+ failure: null,
+ needsRerun: true,
+ offline: false,
+ superseded: true,
+ };
+ }
const nextSessions = Array.isArray(list) ? list : [];
remoteSessionStore.setDeviceSessions(
device.deviceId,
@@ -535,9 +707,17 @@ export default function HomeScreen() {
// 兜底,徽标晚半拍出现即可。
// 按设备 id 登记:同设备上一轮还没执行的延后任务会被先取消,避免较早回调用旧 nextSessions 覆盖新状态。
scheduleIndexDeferRegistryRef.current.schedule(device.deviceId, () => {
- refreshDeviceScheduleIndex(device.deviceId, nextSessions.map((session) => session.id), {
- accountGeneration: expectedAccountGeneration,
- });
+ void (async () => {
+ while (syncInFlightRef.current) await syncInFlightRef.current;
+ if (
+ homeAccountGenerationRef.current !== expectedAccountGeneration
+ || !isCurrentHomeSyncTarget(device.deviceId, expectedHomeSyncGeneration)
+ ) return;
+ refreshDeviceScheduleIndex(device.deviceId, nextSessions.map((session) => session.id), {
+ accountGeneration: expectedAccountGeneration,
+ homeSyncGeneration: expectedHomeSyncGeneration,
+ });
+ })();
});
updateDeviceConnectionState(device.deviceId, 'idle');
// hydrate 成功后去抖回写首页列表缓存(collect 在定时器触发时才读 store,拿届时最新快照;
@@ -545,7 +725,11 @@ export default function HomeScreen() {
scheduleHomeListSnapshotPersist(homeCacheUserId, () => remoteSessionStore.getSessions());
return { failure: null, offline: false, superseded: false };
} catch (err) {
- if (homeAccountGenerationRef.current !== expectedAccountGeneration) {
+ if (
+ err instanceof HomeSyncScopeSupersededError
+ || homeAccountGenerationRef.current !== expectedAccountGeneration
+ || !isCurrentHomeSyncTarget(device.deviceId, expectedHomeSyncGeneration)
+ ) {
return { failure: null, offline: false, superseded: true };
}
const offline = isDeviceOfflineError(err);
@@ -557,7 +741,85 @@ export default function HomeScreen() {
superseded: false,
};
}
- }, [accountGeneration, homeCacheUserId, invoke, markDeviceOffline, refreshDeviceScheduleIndex, statusFilter, subscribe, updateDeviceConnectionState]);
+ }, 'foreground'), [homeCacheUserId, invoke, isCurrentHomeSyncTarget, markDeviceOffline, refreshDeviceScheduleIndex, statusFilter, subscribe, updateDeviceConnectionState]);
+
+ const hydrateDeviceSessions = useCallback((
+ device: DeviceView,
+ expectedAccountGeneration = accountGeneration,
+ options: { trailingIfInFlight?: boolean } = {},
+ ): Promise<HydrateDeviceSessionsResult> => {
+ const expectedHomeSyncGeneration = homeSyncGenerationByDeviceRef.current.get(device.deviceId);
+ if (
+ expectedHomeSyncGeneration === undefined
+ || homeAccountGenerationRef.current !== expectedAccountGeneration
+ || !isCurrentHomeSyncTarget(device.deviceId, expectedHomeSyncGeneration)
+ ) {
+ return Promise.resolve({ failure: null, offline: false, superseded: true });
+ }
+
+ const existing = homeHydrateInFlightByDeviceRef.current.get(device.deviceId);
+ if (
+ existing
+ && existing.accountGeneration === expectedAccountGeneration
+ && existing.homeSyncGeneration === expectedHomeSyncGeneration
+ ) {
+ existing.device = device;
+ if (options.trailingIfInFlight) existing.rerunRequested = true;
+ return existing.promise;
+ }
+
+ const promise = hydrateDeviceSessionsOnce(
+ device,
+ expectedAccountGeneration,
+ expectedHomeSyncGeneration,
+ );
+ const entry: HomeHydrateInFlightEntry = {
+ accountGeneration: expectedAccountGeneration,
+ device,
+ homeSyncGeneration: expectedHomeSyncGeneration,
+ promise,
+ rerunRequested: false,
+ };
+ homeHydrateInFlightByDeviceRef.current.set(device.deviceId, entry);
+ const settle = (needsRerun: boolean) => {
+ if (homeHydrateInFlightByDeviceRef.current.get(device.deviceId) !== entry) return;
+ homeHydrateInFlightByDeviceRef.current.delete(device.deviceId);
+ if (
+ !needsRerun
+ && !entry.rerunRequested
+ ) return;
+ if (
+ homeAccountGenerationRef.current !== entry.accountGeneration
+ || !isCurrentHomeSyncTarget(device.deviceId, entry.homeSyncGeneration)
+ ) return;
+ void hydrateDeviceSessionsRef.current(entry.device, entry.accountGeneration);
+ };
+ void promise.then(
+ (result) => settle(result.needsRerun === true),
+ () => settle(false),
+ );
+ return promise;
+ }, [accountGeneration, hydrateDeviceSessionsOnce, isCurrentHomeSyncTarget]);
+ hydrateDeviceSessionsRef.current = hydrateDeviceSessions;
+
+ const probeRevokedDeviceAccess = useCallback(async (
+ deviceId: string,
+ expectedAccountGeneration = accountGeneration,
+ ): Promise<boolean> => {
+ if (homeAccountGenerationRef.current !== expectedAccountGeneration) return false;
+ try {
+ // sessions:list limit=1 是既有的最小被控端响应性探测;不要为了探测给不可见设备
+ // 持有 `sessions` topic,也不要把这一行写回完整列表缓存。
+ await withTransientRemoteRetry(() => invoke<unknown[]>(deviceId, 'local-db:sessions:list', [
+ 1,
+ 'active',
+ { includePinned: true, fresh: true },
+ ]), { maxAttempts: 3 });
+ return homeAccountGenerationRef.current === expectedAccountGeneration;
+ } catch {
+ return false;
+ }
+ }, [accountGeneration, invoke]);
const loadHome = useCallback(async (options: { visible?: boolean } = {}) => {
const accountGenerationAtStart = accountGeneration;
@@ -608,6 +870,18 @@ export default function HomeScreen() {
const serverDevices = mergeFreshPresence(reconcileDeviceViews(res.devices).devices);
const deviceRows = toDeviceListItems(serverDevices, now, revokedDevices);
const availableRows = deviceRows.filter((item) => item.canOpen);
+ const syncDeviceIds = resolveHomeDeviceSyncIds(
+ availableRows.map((item) => ({ canOpen: true, deviceId: item.device.deviceId })),
+ selectedDeviceIdRef.current,
+ );
+ const syncDeviceIdSet = new Set(syncDeviceIds);
+ const syncRows = availableRows.filter((item) => syncDeviceIdSet.has(item.device.deviceId));
+ const selectedDeviceIdAtSyncStart = selectedDeviceIdRef.current;
+ reconcileHomeDeviceSyncScope(syncDeviceIds);
+ // 设备清单 / presence 不等列表 fan-out:先发布全量设备状态,再用最多 6 个 worker
+ // 补当前显示范围。scope effect 看到的 owner 已在上面领取,不会重复派发。
+ devicesRef.current = serverDevices;
+ setDevices(serverDevices);
setDeviceConnectionStates((current) => pruneHomeDeviceConnectionStates(
current,
new Set(availableRows.map((item) => item.device.deviceId)),
@@ -642,20 +916,23 @@ export default function HomeScreen() {
const failures: string[] = [];
const offlineDeviceIds = new Set<string>();
- await Promise.all(availableRows.map(async (item) => {
+ const hydrateResults = await runHomeDeviceSyncBatch(syncRows, async (item) => {
const result = await hydrateDeviceSessions(item.device, accountGenerationAtStart);
- if (result.superseded || homeAccountGenerationRef.current !== accountGenerationAtStart) return;
+ return { deviceId: item.device.deviceId, result };
+ });
+ for (const { deviceId, result } of hydrateResults) {
+ if (result.superseded || homeAccountGenerationRef.current !== accountGenerationAtStart) continue;
if (result.failure) failures.push(result.failure);
if (result.offline) {
- offlineDeviceIds.add(item.device.deviceId);
+ offlineDeviceIds.add(deviceId);
} else if (!result.failure) {
// REST + hydrate success is authoritative reachability evidence even when relay
// presence was not replayed on this connection. Retire any prior offline marker
// so unrelated device invalidations cannot re-clear this device's running badges.
- remoteScheduleEventStore.clearDeviceMirrorInvalidation(item.device.deviceId);
- invalidateOfflineScheduleIndexFailureFor(item.device.deviceId);
+ remoteScheduleEventStore.clearDeviceMirrorInvalidation(deviceId);
+ invalidateOfflineScheduleIndexFailureFor(deviceId);
}
- }));
+ }
if (homeAccountGenerationRef.current !== accountGenerationAtStart) return;
// 收尾再合并一次:hydrate 阶段(可能持续数秒)里新到的 presence 补丁同样不能被覆盖掉。
@@ -666,7 +943,9 @@ export default function HomeScreen() {
setDevices(nextDevices);
lastSyncedAtRef.current = now;
setLastSyncedAt(now);
- setError(failures.length > 0 ? failures.slice(0, 2).join(';') : null);
+ if (selectedDeviceIdRef.current === selectedDeviceIdAtSyncStart) {
+ setError(failures.length > 0 ? failures.slice(0, 2).join(';') : null);
+ }
// loadHome 整轮成功后也回写一次:覆盖「设备全部下线 / 会话清空」的收敛场景——
// 此时没有任何 hydrate 成功,只有这里能把缓存里的陈旧设备清掉。
scheduleHomeListSnapshotPersist(homeCacheUserId, () => remoteSessionStore.getSessions());
@@ -691,7 +970,7 @@ export default function HomeScreen() {
return task.finally(() => {
if (visible && homeAccountGenerationRef.current === accountGenerationAtStart) setRefreshing(false);
});
- }, [accountGeneration, apiFetch, deviceIdentityCacheReady, homeCacheUserId, hydrateDeviceSessions, reconcileDeviceViews, revokedDevices, softInvalidateDeviceMirror]);
+ }, [accountGeneration, apiFetch, deviceIdentityCacheReady, homeCacheUserId, hydrateDeviceSessions, reconcileDeviceViews, reconcileHomeDeviceSyncScope, revokedDevices, softInvalidateDeviceMirror]);
loadHomeRef.current = loadHome;
// 冷启动先画缓存:上次 loadHome 成功的设备+会话快照种入 store,先把列表画出来(消除首屏强制
@@ -777,7 +1056,12 @@ export default function HomeScreen() {
useEffect(() => {
const expectedAccountGeneration = homeAccountGenerationRef.current;
let cancelled = false;
- void readHomeViewPreferences().then((preferences) => {
+ const read = startBoundedStartupRead<HomeViewPreferences | null>(
+ readHomeViewPreferences(),
+ null,
+ );
+ const applyPreferences = (preferences: HomeViewPreferences | null) => {
+ if (!preferences) return;
if (
cancelled
|| homeAccountGenerationRef.current !== expectedAccountGeneration
@@ -794,7 +1078,26 @@ export default function HomeScreen() {
setRestoredDeviceName(preferences.selectedDevice.name);
restoredSelectionUnvalidatedRef.current = true;
}
- });
+ };
+ void read.initial
+ .then((initial) => {
+ applyPreferences(initial.value);
+ if (initial.timedOut) {
+ // Native storage can occasionally settle after the startup budget. Let Home start
+ // with its safe defaults, then narrow the live scope if the untouched preference
+ // eventually arrives; a permanently stuck read can no longer block networking.
+ void read.completion.then((late) => {
+ if (late.ok) applyPreferences(late.value);
+ });
+ }
+ })
+ .finally(() => {
+ // The preference values are generation-fenced above, but this startup gate belongs to
+ // the mounted Home screen rather than to one account. If the user switches accounts while
+ // the bounded read is settling, the old values must stay ignored while the new account is
+ // still allowed to start networking with safe defaults.
+ if (!cancelled) setHomeViewPreferencesHydrated(true);
+ });
return () => {
cancelled = true;
};
@@ -825,6 +1128,7 @@ export default function HomeScreen() {
}
for (const deviceId of deviceIds) {
+ if (!homeSyncTargetDeviceIdsRef.current.has(deviceId)) continue;
const snapshot = remoteScheduleEventStore.getSnapshot(deviceId);
const version = snapshot.version;
if (version === 0) {
@@ -867,6 +1171,7 @@ export default function HomeScreen() {
useFocusEffect(
useCallback(() => {
for (const device of devicesRef.current) {
+ if (!homeSyncTargetDeviceIdsRef.current.has(device.deviceId)) continue;
const sessionIds = remoteSessionStore.getSessions()
.filter((session) => session.deviceLinkDeviceId === device.deviceId)
.map((session) => session.id);
@@ -883,9 +1188,9 @@ export default function HomeScreen() {
// 首次触发同时等首页列表缓存种入完成(homeListCacheHydrated,AsyncStorage 读一个小 key,毫秒级):
// 保证缓存先画、fresh 后覆盖的顺序确定,避免 loadHome 清理下线设备后缓存又把 stale shard 种回去。
useEffect(() => {
- if (!deviceIdentityCacheReady || !homeListCacheHydrated) return;
+ if (!deviceIdentityCacheReady || !homeListCacheHydrated || !homeViewPreferencesHydrated) return;
void loadHome({ visible: false });
- }, [connectionEpoch, deviceIdentityCacheReady, homeListCacheHydrated, loadHome]);
+ }, [connectionEpoch, deviceIdentityCacheReady, homeListCacheHydrated, homeViewPreferencesHydrated, loadHome]);
// 把当前权威设备列表注入 remoteSessionStore,让 store 给所有 useRemoteSessions 消费者(首页项目卡、
// 设备详情页)统一算展示用 canonicalDeviceId:re-link 后残留的 stale shard 会话按设备名唯一匹配认领回
@@ -911,27 +1216,26 @@ export default function HomeScreen() {
const hydratedDevice = result.device
? reconciled.devices.find((device) => device.deviceId === result.device?.deviceId) ?? result.device
: null;
- if (!hydratedDevice || !result.becameControllable) return;
+ if (!hydratedDevice || !result.becameControllable || !isCurrentHomeSyncTarget(hydratedDevice.deviceId)) return;
void hydrateDeviceSessions(hydratedDevice).then((hydrateResult) => {
if (hydrateResult.superseded) return;
if (hydrateResult.failure) setError(hydrateResult.failure);
else setError(null);
});
- }, [deviceIdentityCacheReady, hydrateDeviceSessions, lastPresenceSnapshot, reconcileDeviceViews, selfDeviceId]);
+ }, [deviceIdentityCacheReady, hydrateDeviceSessions, isCurrentHomeSyncTarget, lastPresenceSnapshot, reconcileDeviceViews, selfDeviceId]);
// Auto-heal revoked access: a host only signals a re-grant by accepting a fresh request, so on
- // every (re)connect silently re-probe each revoked device. hydrateDeviceSessions' invoke clears
- // the in-memory revoked mark on success (withAccessRevokedHandling), returning the device to the
- // controllable list with no user action. Failures stay silent (the device is still revoked).
+ // every (re)connect silently re-probe each revoked device. The one-row invoke clears the
+ // in-memory revoked mark on success (withAccessRevokedHandling) without retaining a hidden
+ // list subscription. Scope reconciliation then hydrates it only when it is actually visible.
useEffect(() => {
if (status !== 'online') return;
const revoked = revokedDevicesStore.getSnapshot();
if (revoked.size === 0) return;
- for (const deviceId of revoked) {
- const device = devicesRef.current.find((item) => item.deviceId === deviceId);
- if (device) void hydrateDeviceSessions(device).catch(() => undefined);
- }
- }, [connectionEpoch, status, hydrateDeviceSessions]);
+ void runHomeDeviceSyncBatch([...revoked], (deviceId) => (
+ homeDeviceSyncLimiterRef.current.run(() => probeRevokedDeviceAccess(deviceId))
+ ));
+ }, [connectionEpoch, probeRevokedDeviceAccess, status]);
// Close the revoked tip automatically once access is restored (auto-heal or manual retry).
useEffect(() => {
@@ -947,15 +1251,18 @@ export default function HomeScreen() {
retryingDeviceIdsRef.current.add(deviceId);
setRetryingDeviceIds(new Set(retryingDeviceIdsRef.current));
try {
- await hydrateDeviceSessions(device, expectedAccountGeneration);
+ await homeDeviceSyncLimiterRef.current.run(
+ () => probeRevokedDeviceAccess(device.deviceId, expectedAccountGeneration),
+ 'foreground',
+ );
} finally {
if (homeAccountGenerationRef.current !== expectedAccountGeneration) return;
// Retry state is scoped per device; only clear this request to avoid clearing another in-flight retry.
retryingDeviceIdsRef.current.delete(deviceId);
setRetryingDeviceIds(new Set(retryingDeviceIdsRef.current));
}
- // hydrate's invoke clears the revoked mark on success; the tip-close effect handles dismissal.
- }, [accountGeneration, hydrateDeviceSessions]);
+ // probe invoke clears the revoked mark on success; the tip-close effect handles dismissal.
+ }, [accountGeneration, probeRevokedDeviceAccess]);
const openRenameDevice = useCallback((item: MobileHomeDeviceFilterItem) => {
if (!item.deviceId) return;
@@ -1070,12 +1377,47 @@ export default function HomeScreen() {
() => toDeviceListItems(devices, Date.now(), revokedDevices),
[devices, i18nInstance.resolvedLanguage, revokedDevices],
);
+ const homeSyncDeviceIds = useMemo(() => resolveHomeDeviceSyncIds(
+ deviceRows.map((item) => ({
+ canOpen: item.canOpen,
+ deviceId: item.device.deviceId,
+ })),
+ selectedDeviceId,
+ ), [deviceRows, selectedDeviceId]);
+ const homeSyncDeviceIdSet = useMemo(() => new Set(homeSyncDeviceIds), [homeSyncDeviceIds]);
+ const homeSyncRows = useMemo(
+ () => deviceRows.filter((item) => homeSyncDeviceIdSet.has(item.device.deviceId)),
+ [deviceRows, homeSyncDeviceIdSet],
+ );
useEffect(() => {
- const availableRows = deviceRows.filter((item) => item.canOpen);
- const unregisters = availableRows.map((item) =>
+ const expectedAccountGeneration = accountGeneration;
+ const selectedDeviceIdAtStart = selectedDeviceId;
+ const diff = reconcileHomeDeviceSyncScope(homeSyncDeviceIds);
+ if (diff.acquire.length === 0) return;
+ const acquireIds = new Set(diff.acquire);
+ const rows = homeSyncRows.filter((item) => acquireIds.has(item.device.deviceId));
+ void runHomeDeviceSyncBatch(rows, async (item) => (
+ hydrateDeviceSessions(item.device, expectedAccountGeneration)
+ )).then((results) => {
+ if (
+ homeAccountGenerationRef.current !== expectedAccountGeneration
+ || selectedDeviceIdRef.current !== selectedDeviceIdAtStart
+ ) return;
+ const failures = results
+ .filter((result) => !result.superseded && result.failure)
+ .map((result) => result.failure as string);
+ if (failures.length > 0) setError(failures.slice(0, 2).join(';'));
+ else if (results.some((result) => !result.superseded)) setError(null);
+ });
+ }, [accountGeneration, homeSyncDeviceIds, homeSyncRows, hydrateDeviceSessions, reconcileHomeDeviceSyncScope, selectedDeviceId]);
+
+ useEffect(() => {
+ const unregisters = homeSyncRows.map((item) =>
remoteSessionStore.registerReseedHandler(item.device.deviceId, () => {
- void hydrateDeviceSessions(item.device).then((hydrateResult) => {
+ void hydrateDeviceSessions(item.device, accountGeneration, {
+ trailingIfInFlight: true,
+ }).then((hydrateResult) => {
if (hydrateResult.superseded) return;
if (hydrateResult.failure) setError(hydrateResult.failure);
else setError(null);
@@ -1085,7 +1427,7 @@ export default function HomeScreen() {
return () => {
for (const unregister of unregisters) unregister();
};
- }, [deviceRows, hydrateDeviceSessions]);
+ }, [accountGeneration, homeSyncRows, hydrateDeviceSessions]);
const deviceModels = useMemo(() => deviceRows.map((item) => ({
canOpen: item.canOpen,
@@ -1150,21 +1492,32 @@ export default function HomeScreen() {
});
useEffect(() => {
const expectedAccountGeneration = accountGeneration;
- const ids = deviceModels.filter((item) => item.canOpen).map((item) => item.deviceId);
- if (ids.length === 0) {
- setHostProjectOrders(new Map());
- return undefined;
- }
+ const ids = homeSyncDeviceIds;
+ if (ids.length === 0) return undefined;
let cancelled = false;
let retryTimer: ReturnType<typeof setTimeout> | undefined;
const fence = createProjectOrderFetchFence();
projectOrderFetchFenceRef.current = fence;
const load = async (attempt: number) => {
+ // Project ordering is secondary Home metadata. Let the bounded sessions-list batch
+ // finish first so cold start/reconnect does not create a second overlapping six-device
+ // fan-out. A queued refresh is included as well; live pushes remain fenced below.
+ while (syncInFlightRef.current) {
+ await syncInFlightRef.current;
+ if (cancelled || homeAccountGenerationRef.current !== expectedAccountGeneration) return;
+ }
const tokens = new Map(ids.map((deviceId) => [deviceId, fence.begin(deviceId)]));
- const entries = await Promise.all(ids.map(async (deviceId) => {
- const result = await fetchHostProjectOrder(invoke, deviceId);
+ const entries = await runHomeDeviceSyncBatch(ids, async (deviceId) => {
+ const result = await homeDeviceSyncLimiterRef.current.run(async () => {
+ if (
+ cancelled
+ || homeAccountGenerationRef.current !== expectedAccountGeneration
+ || !homeSyncTargetDeviceIdsRef.current.has(deviceId)
+ ) return { kind: 'transient' } as const;
+ return fetchHostProjectOrder(invoke, deviceId);
+ });
return [deviceId, result] as const;
- }));
+ });
if (cancelled || homeAccountGenerationRef.current !== expectedAccountGeneration) return;
for (const [deviceId, result] of entries) {
if (!fence.shouldApplyFetch(deviceId, tokens.get(deviceId) ?? 0)) continue;
@@ -1204,7 +1557,7 @@ export default function HomeScreen() {
if (retryTimer) clearTimeout(retryTimer);
unsubscribe();
};
- }, [accountGeneration, deviceModels, invoke]);
+ }, [accountGeneration, homeSyncDeviceIds, invoke]);
const revokedTipDeviceName = useMemo(
() => revokedTipDeviceId
? deviceModels.find((item) => item.deviceId === revokedTipDeviceId)?.name ?? t('devices.list.thisComputer')
diff --git a/apps/mobile/src/__tests__/deviceLinkRehydrate.test.ts b/apps/mobile/src/__tests__/deviceLinkRehydrate.test.ts
index 26924a1c11..cdf42254f9 100644
--- a/apps/mobile/src/__tests__/deviceLinkRehydrate.test.ts
+++ b/apps/mobile/src/__tests__/deviceLinkRehydrate.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from 'vitest';
-import { rehydrateDeviceLinkTopics } from '@/device-link/rehydrate';
+import { rehydrateDeviceLinkPeer, rehydrateDeviceLinkTopics } from '@/device-link/rehydrate';
import type { DeviceLinkRehydrateDeps } from '@/device-link/rehydrate';
function deps() {
@@ -51,6 +51,59 @@ describe('rehydrateDeviceLinkTopics', () => {
]);
});
+ it('does not open a listing-only peer while replaying its subscription', async () => {
+ const { calls, harness } = deps();
+
+ const result = await rehydrateDeviceLinkPeer(
+ { deviceId: 'dev-topic-only', openLink: false, topics: ['sessions'] },
+ harness,
+ );
+
+ expect(calls).toEqual([
+ 'subscribe:dev-topic-only:sessions',
+ 'reseed:dev-topic-only',
+ ]);
+ expect(harness.openLink).not.toHaveBeenCalled();
+ expect(result.linkOpened).toBe(false);
+ });
+
+ it('opens a listing peer only when the recovery plan asks for a control link', async () => {
+ const { calls, harness } = deps();
+
+ const result = await rehydrateDeviceLinkPeer(
+ { deviceId: 'dev-forced', openLink: true, topics: ['sessions'] },
+ harness,
+ );
+
+ expect(calls).toEqual([
+ 'open:dev-forced',
+ 'subscribe:dev-forced:sessions',
+ 'reseed:dev-forced',
+ ]);
+ expect(result.linkOpened).toBe(true);
+ });
+
+ it('reports whether the peer link-open step actually succeeded', async () => {
+ const { harness } = deps();
+ const success = await rehydrateDeviceLinkPeer(
+ { deviceId: 'dev-ok', openLink: true, topics: [] },
+ harness,
+ );
+ expect(success.transientFailures).toBe(0);
+ expect(success.linkOpened).toBe(true);
+
+ vi.mocked(harness.openLink).mockReturnValueOnce({
+ capturedPresenceEpoch: 0,
+ capturedResponseEvidenceEpoch: 0,
+ request: Promise.reject(Object.assign(new Error('offline'), { code: 'DEVICE_OFFLINE' })),
+ });
+ const failed = await rehydrateDeviceLinkPeer(
+ { deviceId: 'dev-failed', openLink: true, topics: [] },
+ harness,
+ );
+ expect(failed.linkOpened).toBe(false);
+ });
+
it('stops the remaining sweep when background release cancels it', async () => {
const { calls, harness } = deps();
let cancelled = false;
diff --git a/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.ts b/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.ts
index 3fd0788d1d..2bb0a76695 100644
--- a/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.ts
+++ b/apps/mobile/src/__tests__/historyWindowBackfillWiring.test.ts
@@ -125,17 +125,41 @@ describe('live stream interruption wiring', () => {
);
// 传的是 markHeldRemoteTopicsSubscribed 的返回值(仍被持有的那些),不是原始 toSend ——
// 中途被释放的 topic 不算订阅生效。
- expect(sendSubscribe).toContain('noteSessionLiveStreamsAcked(\n markHeldRemoteTopicsSubscribed(');
+ expect(sendSubscribe).toMatch(/noteSessionLiveStreamsAcked\(\s*markHeldRemoteTopicsSubscribed\(/);
+ // scope 在 ensureOnline 等待期间变化时,已释放 topic 不能迟到发到主机;仍被其它 owner
+ // 持有的 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) {');
+ // 反向竞态同样要守住:快速释放后又切回时,旧 unsubscribe 在真正发帧前必须
+ // 剔除已经重新被 owner 持有的 topic,不能落在新 subscribe 后把实时流再关掉。
+ expect(source).toContain('(topic) => !registryRef.current.hasTopic(deviceId, topic)');
+ expect(source).toMatch(
+ /const toSend = shouldSendTopic \? topics\.filter\(shouldSendTopic\) : topics;[\s\S]*client\.invoke\(deviceId, \{\s*channel: DL_UNSUBSCRIBE_CHANNEL,\s*args: \[\{ topics: toSend \}\]/,
+ );
});
it('socket 掉线:整体失效(影响所有订阅)', () => {
- const offlineBranch = source.slice(
- source.indexOf("if (next !== 'online') {"),
- source.indexOf('clearRehydrateRetry(true);', source.indexOf("if (next !== 'online') {")),
- );
+ const offlineStart = source.indexOf("if (next !== 'online') {");
+ const offlineEnd = source.indexOf('// presence 是当前在线控制端收到的 delta', offlineStart);
+ expect(offlineStart).toBeGreaterThan(0);
+ expect(offlineEnd).toBeGreaterThan(offlineStart);
+ const offlineBranch = source.slice(offlineStart, offlineEnd);
expect(offlineBranch).toContain('remoteSessionStore.noteLiveStreamInterrupted();');
});
+ it('peer ACK reset:无 durable owner 时仍保留独立 forced-open 恢复意图', () => {
+ expect(source).toContain('const forcedPeerRecoveryIntentRef = useRef(new PeerRecoveryOpenIntentRegistry());');
+ expect(source).toMatch(
+ /onPeerTransportReset[\s\S]*requestForcedPeerRecovery\(client, deviceId\)[\s\S]*rehydrateWithClient\(client, deviceId\)/,
+ );
+ expect(source).toContain('resolvePeerRecoveryPlan(');
+ expect(source).toContain('for (const deviceId of forcedPeerRecoveryIntentRef.current.deviceIds())');
+ expect(source).toContain('forcedPeerRecoveryIntentRef.current.complete(targetDeviceId, forcedGeneration)');
+ expect(source).toContain('client.hasPendingRequestsTo(deviceId)');
+ expect(source).toContain('!client.isOutboundExplicitlyClosed(deviceId)');
+ });
+
it('退后台释放 session 订阅:按被释放的会话失效', () => {
const release = source.slice(
source.indexOf('const releaseHeavyTopics = ()'),
diff --git a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
index d10fabb999..5880911dd4 100644
--- a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
@@ -318,9 +318,9 @@ describe('mobile home desktop-first surface', () => {
expect(source).toContain('if (isAccessRevokedError(error) || isDeviceOfflineError(error)) return false;');
expect(source).toContain("if (text.includes('REMOTE_DISABLED')) return false;");
expect(source).toContain('return true;');
- expect(source).toContain('const [list, activeSessions, activeSessionSnapshotEpoch]');
+ expect(source).toMatch(/const \[\s*list,\s*activeSessions,\s*activeSessionSnapshotEpoch,/);
expect(source).toContain('remoteSessionStore.captureActiveSessionSnapshotEpoch()');
- expect(source).toContain('return [list, activeSessions, activeSessionSnapshotEpoch] as const;');
+ expect(source).toMatch(/return \[\s*list,\s*activeSessions,\s*activeSessionSnapshotEpoch,/);
expect(source).toContain('activeSessionSnapshotEpoch,');
expect(source).toContain('remoteScheduleEventStore.subscribe(() => {');
expect(source).toContain('const snapshot = remoteScheduleEventStore.getSnapshot(deviceId)');
@@ -475,20 +475,50 @@ describe('mobile home desktop-first surface', () => {
expect(stylesSource).not.toContain('automationGroupChildrenCindy');
});
- it('keeps presence updates local and refreshes full home sync on every reconnect', () => {
+ it('keeps presence global while reconnecting only the visible Home sync scope', () => {
const source = readSource('app/devices/index.tsx');
expect(source).toContain('void loadHome({ visible: false });');
expect(source).toMatch(/startBoundedStartupRead\(\s*getCachedHomeListSnapshot\(homeCacheUserId\)/);
expect(source).toContain('await syncInFlightRef.current;');
expect(source).toMatch(/startBoundedStartupRead\(\s*loadDeviceIdentityCache\(\)/);
+ expect(source).toMatch(/startBoundedStartupRead<HomeViewPreferences \| null>\(\s*readHomeViewPreferences\(\)/);
+ const preferenceHydration = source.slice(
+ source.indexOf('// 冷启动恢复上次的首页视图偏好'),
+ source.indexOf('// 卸载时取消所有延后中的 schedule-index hydration'),
+ );
+ expect(preferenceHydration).toContain('homeAccountGenerationRef.current !== expectedAccountGeneration');
+ expect(preferenceHydration).toContain('if (!cancelled) setHomeViewPreferencesHydrated(true);');
expect(source).toContain('const deviceIdentityCachePersistPendingRef = useRef(false);');
- // 重连(connectionEpoch 变化)必须无条件全量刷新:presence 只在变化时广播、无全量重放,
- // 后台漏掉的上/下线事件只能靠重连重拉 REST 快照兜底,不能再用 hydrated 标记门控挡掉。
+ // 重连(connectionEpoch 变化)必须无条件重拉全量设备 REST:presence 只在变化时广播、无全量重放,
+ // 后台漏掉的上/下线事件只能靠重连快照兜底;每设备列表 fan-out 再按可见 scope 收窄。
// homeListCacheHydrated 是一次性 gate(缓存种入完成后永久为 true,种入失败也置 true),
// 只影响首次触发顺序(缓存先画、fresh 后覆盖),不会挡掉任何一次重连刷新。
expect(source).not.toContain('homeSessionHydratedRef');
- expect(source).toContain('}, [connectionEpoch, deviceIdentityCacheReady, homeListCacheHydrated, loadHome]);');
+ expect(source).toContain('!homeViewPreferencesHydrated');
+ expect(source).toContain('}, [connectionEpoch, deviceIdentityCacheReady, homeListCacheHydrated, homeViewPreferencesHydrated, loadHome]);');
+ expect(source).toContain('resolveHomeDeviceSyncIds(');
+ expect(source).toContain('reconcileHomeDeviceSyncScope(syncDeviceIds);');
+ expect(source).toContain('runHomeDeviceSyncBatch(syncRows');
+ expect(source).toContain('while (syncInFlightRef.current)');
+ expect(source).toContain("unsubscribe(HOME_LIST_SUBSCRIPTION_OWNER, deviceId, ['sessions'])");
+ expect(source).toContain('homeSyncGenerationByDeviceRef');
+ expect(source).toContain('diffHomeDeviceSyncScope(homeSyncTargetDeviceIdsRef.current, desiredDeviceIds)');
+ expect(source).toContain('isCurrentHomeSyncTarget(device.deviceId, expectedHomeSyncGeneration)');
+ expect(source).toContain('homeHydrateInFlightByDeviceRef');
+ expect(source).toContain('existing.homeSyncGeneration === expectedHomeSyncGeneration');
+ expect(source).toContain('if (options.trailingIfInFlight) existing.rerunRequested = true;');
+ expect(source).toContain('trailingIfInFlight: true');
+ expect(source).toContain('captureDeviceSessionListMutationEpoch(');
+ expect(source).toContain('isDeviceSessionListMutationEpochCurrent(');
+ expect(source).toContain('needsRerun: true');
+ expect(source).toContain('homeDeviceSyncLimiterRef.current.run');
+ const hydrateSource = source.slice(
+ source.indexOf('const hydrateDeviceSessions = useCallback'),
+ source.indexOf('const probeRevokedDeviceAccess'),
+ );
+ expect(hydrateSource).not.toContain('releaseHomeListOwner(');
+ expect(source).toContain('homeSyncGeneration: expectedHomeSyncGeneration');
// REST 快照与飞行期间的 presence 补丁按新鲜度合并,防止过期快照把刚上线的设备改回离线。
expect(source).toContain('mergeDeviceViewsWithFreshPresence(');
expect(source).toContain('markPresenceFresh(presenceFreshnessRef.current, lastPresenceSnapshot.deviceId);');
diff --git a/apps/mobile/src/__tests__/homeDeviceSync.test.ts b/apps/mobile/src/__tests__/homeDeviceSync.test.ts
new file mode 100644
index 0000000000..61efa7322b
--- /dev/null
+++ b/apps/mobile/src/__tests__/homeDeviceSync.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ diffHomeDeviceSyncScope,
+ HOME_DEVICE_SYNC_CONCURRENCY,
+ HomeDeviceSyncLimiter,
+ resolveHomeDeviceSyncIds,
+ runHomeDeviceSyncBatch,
+} from '@/session/homeDeviceSync';
+
+describe('home device sync scope', () => {
+ const devices = [
+ { canOpen: true, deviceId: 'dev-a' },
+ { canOpen: false, deviceId: 'dev-b' },
+ { canOpen: true, deviceId: 'dev-c' },
+ ];
+
+ it('syncs every controllable device for all tasks and only the selected device otherwise', () => {
+ expect(resolveHomeDeviceSyncIds(devices, null)).toEqual(['dev-a', 'dev-c']);
+ expect(resolveHomeDeviceSyncIds(devices, 'dev-c')).toEqual(['dev-c']);
+ expect(resolveHomeDeviceSyncIds(devices, 'dev-b')).toEqual([]);
+ });
+
+ it('releases hidden owners and acquires only newly visible owners', () => {
+ expect(diffHomeDeviceSyncScope(new Set(['dev-a', 'dev-b']), ['dev-b', 'dev-c'])).toEqual({
+ acquire: ['dev-c'],
+ release: ['dev-a'],
+ });
+ });
+
+ it('limits startup work to six devices and still completes the queued devices', async () => {
+ expect(HOME_DEVICE_SYNC_CONCURRENCY).toBe(6);
+ const releases: Array<() => void> = [];
+ let active = 0;
+ let peak = 0;
+ const items = Array.from({ length: 9 }, (_, index) => index);
+
+ const task = runHomeDeviceSyncBatch(items, async (item) => {
+ active += 1;
+ peak = Math.max(peak, active);
+ await new Promise<void>((resolve) => releases.push(resolve));
+ active -= 1;
+ return item * 2;
+ });
+
+ await Promise.resolve();
+ expect(active).toBe(6);
+ while (releases.length > 0) {
+ releases.shift()?.();
+ await Promise.resolve();
+ }
+
+ await expect(task).resolves.toEqual(items.map((item) => item * 2));
+ expect(peak).toBe(6);
+ });
+
+ it('falls back to a valid worker count for invalid caller limits', async () => {
+ const values = await runHomeDeviceSyncBatch([1, 2], async (item) => item, Number.NaN);
+ expect(values).toEqual([1, 2]);
+ });
+
+ it('drains devices queued after an unexpected worker rejection', async () => {
+ const visited: number[] = [];
+ await expect(runHomeDeviceSyncBatch([1, 2, 3, 4], async (item) => {
+ visited.push(item);
+ if (item === 2) throw new Error('broken peer');
+ return item;
+ }, 2)).rejects.toThrow('broken peer');
+ expect(visited.sort((a, b) => a - b)).toEqual([1, 2, 3, 4]);
+ });
+
+ it('shares six slots across overlapping Home trigger groups and prioritizes visible work', async () => {
+ const limiter = new HomeDeviceSyncLimiter();
+ const releases: Array<() => void> = [];
+ const started: string[] = [];
+ const run = (name: string, priority: 'foreground' | 'background') => limiter.run(async () => {
+ started.push(name);
+ await new Promise<void>((resolve) => releases.push(resolve));
+ return name;
+ }, priority);
+
+ const initial = Array.from({ length: 7 }, (_, index) => run(`background-${index}`, 'background'));
+ const visible = run('visible', 'foreground');
+ expect(started).toEqual(Array.from({ length: 6 }, (_, index) => `background-${index}`));
+
+ releases.shift()?.();
+ for (let index = 0; index < 5; index += 1) await Promise.resolve();
+ expect(started.at(-1)).toBe('visible');
+
+ for (let pass = 0; pass < 10; pass += 1) {
+ for (const release of releases.splice(0)) release();
+ for (let index = 0; index < 5; index += 1) await Promise.resolve();
+ }
+ await Promise.all([...initial, visible]);
+ });
+});
diff --git a/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts b/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts
index aa2c70acc6..09d4ebf915 100644
--- a/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts
+++ b/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts
@@ -775,9 +775,10 @@ describe('mobile auth-server login', () => {
expect(boundaryBody).toContain(
'accountGenerationRef.current !== auth.accountGeneration',
);
- expect(boundaryBody).toContain(
- 'if (accountGenerationChanged) clearPerAccountDeviceLinkState();',
- );
+ expect(boundaryBody).toContain('if (accountGenerationChanged) {');
+ expect(boundaryBody).toContain('clearPerAccountDeviceLinkState();');
+ expect(boundaryBody).toContain('registryRef.current.clear();');
+ expect(boundaryBody).toContain('remoteSubscribedTopicsRef.current.clear();');
});
it('accepts enterprise ID, organization slug, and verified domains up to the API limit', () => {
diff --git a/apps/mobile/src/__tests__/peerRecoveryScheduler.test.ts b/apps/mobile/src/__tests__/peerRecoveryScheduler.test.ts
new file mode 100644
index 0000000000..4f75e2c36d
--- /dev/null
+++ b/apps/mobile/src/__tests__/peerRecoveryScheduler.test.ts
@@ -0,0 +1,158 @@
+import { describe, expect, it, vi } from 'vitest';
+import {
+ PeerRecoveryOpenIntentRegistry,
+ PeerRecoveryScheduler,
+} from '@/device-link/peerRecoveryScheduler';
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+
+async function flush(): Promise<void> {
+ await Promise.resolve();
+ await Promise.resolve();
+}
+
+describe('PeerRecoveryScheduler', () => {
+ it('does not let an old forced-open completion clear a newer intent for the same peer', () => {
+ const intents = new PeerRecoveryOpenIntentRegistry();
+ const first = intents.request('desktop-a');
+ intents.cancel('desktop-a');
+ const second = intents.request('desktop-a');
+
+ expect(second).toBeGreaterThan(first);
+ expect(intents.complete('desktop-a', first)).toBe(false);
+ expect(intents.has('desktop-a')).toBe(true);
+ expect(intents.complete('desktop-a', second)).toBe(true);
+ expect(intents.has('desktop-a')).toBe(false);
+ });
+
+ it('runs up to six peer recoveries by default', () => {
+ const started: string[] = [];
+ const scheduler = new PeerRecoveryScheduler((deviceId) => {
+ started.push(deviceId);
+ return deferred<{ retry: boolean }>().promise;
+ });
+
+ scheduler.requestMany(['a', 'b', 'c', 'd', 'e', 'f', 'g']);
+
+ expect(started).toEqual(['a', 'b', 'c', 'd', 'e', 'f']);
+ expect(scheduler.getSnapshot('g').phase).toBe('queued');
+ });
+
+ it('lets healthy peers recover while one peer is stalled', async () => {
+ const stalled = deferred<{ retry: boolean }>();
+ const completed: string[] = [];
+ const scheduler = new PeerRecoveryScheduler(
+ async (deviceId) => {
+ if (deviceId === 'desktop-a') return stalled.promise;
+ completed.push(deviceId);
+ return { retry: false };
+ },
+ { maxConcurrent: 3 },
+ );
+
+ scheduler.requestMany(['desktop-a', 'desktop-b', 'desktop-c']);
+ await flush();
+
+ expect(completed).toEqual(['desktop-b', 'desktop-c']);
+ expect(scheduler.getSnapshot('desktop-a').phase).toBe('running');
+ expect(scheduler.getSnapshot('desktop-b').phase).toBe('idle');
+ stalled.resolve({ retry: true });
+ await flush();
+ });
+
+ it('bounds recovery concurrency without making peers share lifecycle state', async () => {
+ const releases = new Map<string, ReturnType<typeof deferred<{ retry: boolean }>>>();
+ const started: string[] = [];
+ const scheduler = new PeerRecoveryScheduler(
+ (deviceId) => {
+ started.push(deviceId);
+ const run = deferred<{ retry: boolean }>();
+ releases.set(deviceId, run);
+ return run.promise;
+ },
+ { maxConcurrent: 2 },
+ );
+
+ scheduler.requestMany(['a', 'b', 'c']);
+ expect(started).toEqual(['a', 'b']);
+ expect(scheduler.getSnapshot('c').phase).toBe('queued');
+
+ releases.get('b')?.resolve({ retry: false });
+ await flush();
+ expect(started).toEqual(['a', 'b', 'c']);
+ expect(scheduler.getSnapshot('a').phase).toBe('running');
+ });
+
+ it('keeps retry backoff per peer', async () => {
+ vi.useFakeTimers();
+ const calls: string[] = [];
+ const scheduler = new PeerRecoveryScheduler(
+ async (deviceId) => {
+ calls.push(deviceId);
+ return { retry: deviceId === 'a' };
+ },
+ { retryBaseMs: 2_000, retryMaxMs: 30_000 },
+ );
+
+ scheduler.requestMany(['a', 'b']);
+ await flush();
+ expect(scheduler.getSnapshot('a')).toMatchObject({
+ phase: 'waiting-retry',
+ retryAttempt: 1,
+ });
+ expect(scheduler.getSnapshot('b').phase).toBe('idle');
+
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(calls).toEqual(['a', 'b', 'a']);
+ expect(scheduler.getSnapshot('a').retryAttempt).toBe(2);
+ expect(scheduler.getSnapshot('b').retryAttempt).toBe(0);
+ scheduler.clear();
+ vi.useRealTimers();
+ });
+
+ it('cancels only the selected peer and ignores its late result', async () => {
+ const a = deferred<{ retry: boolean }>();
+ const b = deferred<{ retry: boolean }>();
+ const scheduler = new PeerRecoveryScheduler((deviceId) => (
+ deviceId === 'a' ? a.promise : b.promise
+ ));
+
+ scheduler.requestMany(['a', 'b']);
+ scheduler.cancel('a');
+ a.resolve({ retry: true });
+ b.resolve({ retry: false });
+ await flush();
+
+ expect(scheduler.getSnapshot('a')).toEqual({
+ deviceId: 'a',
+ phase: 'idle',
+ retryAttempt: 0,
+ });
+ expect(scheduler.getSnapshot('b').phase).toBe('idle');
+ });
+
+ it('reruns only the peer requested during its in-flight recovery', async () => {
+ const firstA = deferred<{ retry: boolean }>();
+ const calls: string[] = [];
+ const scheduler = new PeerRecoveryScheduler(async (deviceId) => {
+ calls.push(deviceId);
+ if (deviceId === 'a' && calls.filter((item) => item === 'a').length === 1) {
+ return firstA.promise;
+ }
+ return { retry: false };
+ });
+
+ scheduler.requestMany(['a', 'b']);
+ scheduler.request('a');
+ firstA.resolve({ retry: false });
+ await flush();
+
+ expect(calls).toEqual(['a', 'b', 'a']);
+ });
+});
diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
index 111af62061..4d25598c0f 100644
--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts
+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
@@ -2793,6 +2793,52 @@ describe('remoteSessionStore', () => {
expect(remoteSessionStore.getSessions()[0].title).toBe('New');
});
+ it('fences an older whole-list snapshot after created/patched pushes per device', () => {
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1', { title: 'Old' })]);
+ const dev1Epoch = remoteSessionStore.captureDeviceSessionListMutationEpoch('dev-1');
+ const dev2Epoch = remoteSessionStore.captureDeviceSessionListMutationEpoch('dev-2');
+
+ remoteSessionStore.applyRemotePush('dev-1', 'local-db:sessions:patched', {
+ sessionId: 's1',
+ patch: { title: 'New' },
+ });
+ expect(remoteSessionStore.isDeviceSessionListMutationEpochCurrent('dev-1', dev1Epoch)).toBe(false);
+ expect(remoteSessionStore.isDeviceSessionListMutationEpochCurrent('dev-2', dev2Epoch)).toBe(true);
+
+ const afterPatch = remoteSessionStore.captureDeviceSessionListMutationEpoch('dev-1');
+ remoteSessionStore.applyRemotePush('dev-1', 'local-db:sessions:created', { sessionId: 's2' });
+ expect(remoteSessionStore.isDeviceSessionListMutationEpochCurrent('dev-1', afterPatch)).toBe(false);
+
+ const beforeReset = remoteSessionStore.captureDeviceSessionListMutationEpoch('dev-1');
+ remoteSessionStore.clear();
+ expect(remoteSessionStore.isDeviceSessionListMutationEpochCurrent('dev-1', beforeReset)).toBe(false);
+ });
+
+ it('fences an older whole-list snapshot after valid session usage pushes', () => {
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);
+
+ const beforeSpend = remoteSessionStore.captureDeviceSessionListMutationEpoch('dev-1');
+ remoteSessionStore.applyRemotePush('dev-1', 'usage:session-spend-changed', {
+ sessionId: 's1',
+ totalCostUsd: 1.23,
+ });
+ expect(remoteSessionStore.isDeviceSessionListMutationEpochCurrent('dev-1', beforeSpend)).toBe(false);
+
+ const beforeTokens = remoteSessionStore.captureDeviceSessionListMutationEpoch('dev-1');
+ remoteSessionStore.applyRemotePush('dev-1', 'usage:session-tokens-changed', {
+ sessionId: 's1',
+ totalTokens: 45_000,
+ });
+ expect(remoteSessionStore.isDeviceSessionListMutationEpochCurrent('dev-1', beforeTokens)).toBe(false);
+
+ const beforeInvalid = remoteSessionStore.captureDeviceSessionListMutationEpoch('dev-1');
+ remoteSessionStore.applyRemotePush('dev-1', 'usage:session-tokens-changed', {
+ sessionId: 's1',
+ totalTokens: -1,
+ });
+ expect(remoteSessionStore.isDeviceSessionListMutationEpochCurrent('dev-1', beforeInvalid)).toBe(true);
+ });
+
it('mirrors goal status pushes per session and clears on null goal', () => {
const goal = {
sessionId: 's1',
diff --git a/apps/mobile/src/__tests__/scheduleIndex.test.ts b/apps/mobile/src/__tests__/scheduleIndex.test.ts
index 322fd24226..0894467bbf 100644
--- a/apps/mobile/src/__tests__/scheduleIndex.test.ts
+++ b/apps/mobile/src/__tests__/scheduleIndex.test.ts
@@ -6,6 +6,7 @@ import {
invalidateOfflineScheduleIndexFailureFor,
invalidateRunningSessionScheduleEntries,
invalidateScheduleIndexForDevice,
+ invalidateTransientScheduleIndexFailureFor,
invalidateTransientScheduleIndexFailures,
loadSessionScheduleIndex,
loadSessionScheduleIndexThrottled,
@@ -424,6 +425,33 @@ describe('loadSessionScheduleIndexThrottled (单飞 + TTL 节流)', () => {
},
);
+ it('逐 peer 恢复只清目标设备的瞬态负缓存', async () => {
+ resetScheduleIndexThrottleForTesting();
+ const loadA = vi.fn()
+ .mockRejectedValueOnce(Object.assign(new Error('not connected'), { code: 'NOT_CONNECTED' }))
+ .mockResolvedValueOnce(new Map<string, RemoteSessionScheduleInfo>());
+ const loadB = vi.fn()
+ .mockRejectedValueOnce(Object.assign(new Error('not connected'), { code: 'NOT_CONNECTED' }))
+ .mockResolvedValueOnce(new Map<string, RemoteSessionScheduleInfo>());
+ const now = () => 1000;
+
+ await expect(loadSessionScheduleIndexThrottled('dev-a', loadA, { now })).rejects.toMatchObject({
+ code: 'NOT_CONNECTED',
+ });
+ await expect(loadSessionScheduleIndexThrottled('dev-b', loadB, { now })).rejects.toMatchObject({
+ code: 'NOT_CONNECTED',
+ });
+ await Promise.resolve();
+
+ invalidateTransientScheduleIndexFailureFor('dev-b');
+ await expect(loadSessionScheduleIndexThrottled('dev-a', loadA, { now })).rejects.toMatchObject({
+ code: 'NOT_CONNECTED',
+ });
+ await expect(loadSessionScheduleIndexThrottled('dev-b', loadB, { now })).resolves.toBeInstanceOf(Map);
+ expect(loadA).toHaveBeenCalledTimes(1);
+ expect(loadB).toHaveBeenCalledTimes(2);
+ });
+
it('DEVICE_OFFLINE 负缓存:仅该设备 presence 恢复时失效,全局重连钩子不碰(review P1)', async () => {
// DEVICE_OFFLINE 是逐设备状态:若挂在全局重连钩子上,B 设备的任何 rehydrate
// 都会反复清掉仍离线的 A 设备的 30s 负缓存,请求风暴止损失效。
diff --git a/apps/mobile/src/__tests__/topicRegistry.test.ts b/apps/mobile/src/__tests__/topicRegistry.test.ts
index c73c034ffc..f5d09c8162 100644
--- a/apps/mobile/src/__tests__/topicRegistry.test.ts
+++ b/apps/mobile/src/__tests__/topicRegistry.test.ts
@@ -4,6 +4,7 @@ import {
markHeldRemoteTopicsSubscribed,
markRemoteTopicsSubscribed,
markRemoteTopicsUnsubscribed,
+ resolvePeerRecoveryPlan,
topicsMissingRemoteAck,
} from '@/device-link/topicRegistry';
@@ -20,6 +21,35 @@ describe('DeviceLinkTopicRegistry', () => {
]);
});
+ it('builds one peer recovery plan without reading neighboring peers', () => {
+ const registry = new DeviceLinkTopicRegistry();
+ registry.trackOpenLink('dev-b');
+ registry.trackSubscribe('list-a', 'dev-a', ['sessions']);
+ registry.trackSubscribe('session-b', 'dev-b', ['session:s2']);
+
+ expect(registry.snapshotDevice('dev-a')).toEqual({
+ deviceId: 'dev-a',
+ openLink: false,
+ topics: ['sessions'],
+ });
+ expect(registry.snapshotDevice('dev-b')).toEqual({
+ deviceId: 'dev-b',
+ openLink: true,
+ topics: ['session:s2'],
+ });
+ expect(registry.snapshotDevice('dev-missing')).toBeNull();
+ expect(registry.deviceIds()).toEqual(['dev-a', 'dev-b']);
+ });
+
+ it('queues visible topic holders before historical open-link-only peers', () => {
+ const registry = new DeviceLinkTopicRegistry();
+ registry.trackOpenLink('dev-a-hidden');
+ registry.trackOpenLink('dev-z-visible');
+ registry.trackSubscribe('device-list', 'dev-z-visible', ['sessions']);
+
+ expect(registry.deviceIds()).toEqual(['dev-z-visible', 'dev-a-hidden']);
+ });
+
it('removes topics independently from the open link intent', () => {
const registry = new DeviceLinkTopicRegistry();
@@ -57,6 +87,18 @@ describe('DeviceLinkTopicRegistry', () => {
expect(registry.snapshot()).toEqual([]);
});
+ it('lets Home release a hidden device without interrupting its focused session owner', () => {
+ const registry = new DeviceLinkTopicRegistry();
+
+ registry.trackSubscribe('device-list', 'dev-1', ['sessions']);
+ registry.trackSubscribe('session:s1', 'dev-1', ['sessions', 'session:s1']);
+
+ expect(registry.untrackSubscribe('device-list', 'dev-1', ['sessions'])).toEqual([]);
+ expect(registry.snapshot()).toEqual([
+ { deviceId: 'dev-1', openLink: false, topics: ['session:s1', 'sessions'] },
+ ]);
+ });
+
it('releases a focused session stream without dropping the list subscription', () => {
const registry = new DeviceLinkTopicRegistry();
@@ -136,4 +178,22 @@ describe('DeviceLinkTopicRegistry', () => {
]);
expect(topicsMissingRemoteAck(acked, 'dev-1', ['sessions', 'session:s1'])).toEqual(['sessions']);
});
+
+ it('builds an open-only recovery plan when ACK reset outlives durable owners', () => {
+ expect(resolvePeerRecoveryPlan('dev-1', null, false)).toBeNull();
+ expect(resolvePeerRecoveryPlan('dev-1', null, true)).toEqual({
+ deviceId: 'dev-1',
+ openLink: true,
+ topics: [],
+ });
+ expect(resolvePeerRecoveryPlan(
+ 'dev-1',
+ { deviceId: 'dev-1', openLink: false, topics: ['sessions'] },
+ true,
+ )).toEqual({
+ deviceId: 'dev-1',
+ openLink: true,
+ topics: ['sessions'],
+ });
+ });
});
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index d2f5c409cb..76ad2319f3 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -53,12 +53,18 @@ import {
import { resolveMobileInvokeTimeoutMs } from '@/device-link/invokeTimeouts';
import {
classifySnapshotBatchFailure,
- rehydrateDeviceLinkTopics,
+ rehydrateDeviceLinkPeer,
type DeviceLinkRehydrateSendOptions,
} from '@/device-link/rehydrate';
+import {
+ PeerRecoveryOpenIntentRegistry,
+ PeerRecoveryScheduler,
+ type PeerRecoveryResult,
+} from '@/device-link/peerRecoveryScheduler';
import {
invalidateOfflineScheduleIndexFailureFor,
invalidateScheduleIndexForDevice,
+ invalidateTransientScheduleIndexFailureFor,
invalidateTransientScheduleIndexFailures,
} from '@/session/scheduleIndex';
import { isTransientRemoteError } from '@/device-link/remoteRetry';
@@ -78,6 +84,7 @@ import {
markHeldRemoteTopicsSubscribed,
markRemoteTopicsUnsubscribed,
normalizeDeviceLinkTopics,
+ resolvePeerRecoveryPlan,
topicsMissingRemoteAck,
} from '@/device-link/topicRegistry';
import {
@@ -207,20 +214,6 @@ function subscribeRemoteAgentRoster(
return () => remoteAgentRosterListeners.delete(listener);
}
-interface RehydrateState {
- inFlight: Promise<void> | null;
- rerun: boolean;
-}
-
-interface RehydrateRetryState {
- timer: ReturnType<typeof setTimeout> | null;
- attempt: number;
-}
-
-/** 补齐仍有瞬时失败时的退避重跑曲线:2s → 4s → … → 30s 封顶。 */
-const REHYDRATE_RETRY_BASE_MS = 2_000;
-const REHYDRATE_RETRY_MAX_MS = 30_000;
-
/**
* 退后台断开连接前的宽限:几秒内切回前台的快速 App 切换不触发整套
* 断连 → 重连 → 补齐,弱网下这套循环的代价远高于让 socket 多活两秒。
@@ -294,13 +287,27 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
const clientRef = useRef<DeviceLinkClient | null>(null);
const registryRef = useRef(new DeviceLinkTopicRegistry());
const remoteSubscribedTopicsRef = useRef(new Map<string, Set<Topic>>());
- const rehydrateStateRef = useRef<RehydrateState>({
- inFlight: null,
- rerun: false,
- });
- const rehydrateRetryRef = useRef<RehydrateRetryState>({ timer: null, attempt: 0 });
- // 供退避计时器回调拿到最新的 rehydrateWithClient(二者互相引用,用 ref 解环)
- const rehydrateFnRef = useRef<(client: DeviceLinkClient) => Promise<void>>(() => Promise.resolve());
+ // 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.
+ const forcedPeerRecoveryIntentRef = useRef(new PeerRecoveryOpenIntentRegistry());
+ // 每台远端的补齐任务、rerun 与退避均由自己的状态槽管理;调度器只共享最多
+ // 六个并发恢复名额,不共享失败结论。run callback 经 ref 接最新 React 闭包。
+ const runPeerRecoveryRef = useRef<(deviceId: string) => Promise<PeerRecoveryResult>>(
+ async () => ({ retry: false }),
+ );
+ const peerRecoverySchedulerRef = useRef<PeerRecoveryScheduler | null>(null);
+ if (!peerRecoverySchedulerRef.current) {
+ peerRecoverySchedulerRef.current = new PeerRecoveryScheduler(
+ (deviceId) => runPeerRecoveryRef.current(deviceId),
+ {
+ onError: (deviceId, error) => mobileDeviceLinkLogger.warn(
+ `peer recovery failed unexpectedly device=${deviceId.slice(0, 8)}`,
+ error,
+ ),
+ },
+ );
+ }
const presenceWipeTimersRef = useRef(
new Map<string, PresenceWipeTimerEntry>(),
);
@@ -385,25 +392,35 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
deviceId: string,
topics: readonly Topic[],
) => {
- if (backgroundReleaseInFlightRef.current) return;
- const releaseGeneration = backgroundReleaseGenerationRef.current;
- const toSend = topicsMissingRemoteAck(remoteSubscribedTopicsRef.current, deviceId, topics);
- if (toSend.length === 0) return;
- const sent = await sendSubscribeWithAccessHandling(
- client,
- deviceId,
- toSend,
- () => !backgroundReleaseInFlightRef.current,
- );
- if (
- !sent
- || backgroundReleaseInFlightRef.current
- || backgroundReleaseGenerationRef.current !== releaseGeneration
- ) return;
- // 只有仍被持有、真正记进 ACK 表的 topic 才算订阅生效(中途被释放的那些不算)。
- noteSessionLiveStreamsAcked(
- markHeldRemoteTopicsSubscribed(remoteSubscribedTopicsRef.current, registryRef.current, deviceId, toSend),
- );
+ 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(
+ client,
+ deviceId,
+ toSend,
+ () => (
+ !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;
+ }
}, []);
// 熔断 open 设备的显式代表性探测:openLink 建链(成功按不定论,不关熔断),
@@ -428,248 +445,244 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
[sendOpenLinkOnce],
);
- const clearRehydrateRetry = useCallback((resetAttempt: boolean) => {
- const retry = rehydrateRetryRef.current;
- if (retry.timer) {
- clearTimeout(retry.timer);
- retry.timer = null;
+ const hasOutboundPeerRecoveryIntent = useCallback((
+ client: DeviceLinkClient,
+ deviceId: string,
+ ) => (
+ !client.isOutboundExplicitlyClosed(deviceId)
+ && (
+ registryRef.current.snapshotDevice(deviceId) !== null
+ || client.hasPendingRequestsTo(deviceId)
+ )
+ ), []);
+
+ const requestForcedPeerRecovery = useCallback((
+ client: DeviceLinkClient,
+ deviceId: string,
+ ): boolean => {
+ if (!hasOutboundPeerRecoveryIntent(client, deviceId)) {
+ forcedPeerRecoveryIntentRef.current.cancel(deviceId);
+ return false;
}
- if (resetAttempt) retry.attempt = 0;
- }, []);
+ forcedPeerRecoveryIntentRef.current.request(deviceId);
+ return true;
+ }, [hasOutboundPeerRecoveryIntent]);
- // 补齐通过后(或掉线,online 转换会全量重跑)清退避;仍有瞬时失败则按退避重跑。
- // 补齐是断连窗口 push 断档的唯一回填手段,一次性 best-effort 失败即放弃会把
- // 断档消息静默永久丢在镜像外(用户只能靠手动刷新自救)。
- const scheduleRehydrateRetry = useCallback(
- (client: DeviceLinkClient, transientFailures: number) => {
- const retry = rehydrateRetryRef.current;
- if (retry.timer) {
- clearTimeout(retry.timer);
- retry.timer = null;
- }
- if (transientFailures <= 0 || client.getStatus() !== 'online') {
- retry.attempt = 0;
- return;
- }
- const delay = Math.min(REHYDRATE_RETRY_BASE_MS * 2 ** retry.attempt, REHYDRATE_RETRY_MAX_MS);
- retry.attempt += 1;
- retry.timer = setTimeout(() => {
- retry.timer = null;
- if (client.getStatus() === 'online') void rehydrateFnRef.current(client);
- }, delay);
- },
- [],
- );
+ const runPeerRecovery = useCallback(async (
+ client: DeviceLinkClient,
+ targetDeviceId: string,
+ ): Promise<PeerRecoveryResult> => {
+ if (
+ client !== clientRef.current
+ || client.getStatus() !== 'online'
+ || backgroundReleaseInFlightRef.current
+ ) {
+ return { retry: false };
+ }
+
+ // 撤权、权威离线、远控关闭和永久 link-close 都只终止本 peer 的恢复。
+ if (
+ revokedDevicesStore.has(targetDeviceId)
+ || client.isOutboundExplicitlyClosed(targetDeviceId)
+ || !isPresenceEligibleForRemoteRequest(
+ presenceAvailableByDeviceRef.current,
+ targetDeviceId,
+ )
+ || rehydrateSuppressedDeviceIds.has(targetDeviceId)
+ ) {
+ return { retry: false };
+ }
- const rehydrateWithClient = useCallback(
- (client: DeviceLinkClient): Promise<void> => {
- if (client.getStatus() !== 'online') return Promise.resolve();
- // 退后台时 unsubscribe 的 ack 仍可作为可达性证据修正 stale offline,
- // 但宽限 socket 尚在线期间禁止自动补齐,否则会立即订回刚释放的 heavy topics。
- if (backgroundReleaseInFlightRef.current) return Promise.resolve();
- const state = rehydrateStateRef.current;
- if (state.inFlight) {
- state.rerun = true;
- return state.inFlight;
+ // 熔断 peer 只跑自己的代表性探测;它等待/超时不会占住其它设备的恢复状态。
+ if (unresponsiveDevicesStore.has(targetDeviceId)) {
+ if (isDeviceProbeDue(targetDeviceId)) {
+ await probeUnresponsiveDevice(client, targetDeviceId);
}
+ return { retry: unresponsiveDevicesStore.has(targetDeviceId) };
+ }
- let run!: Promise<void>;
- run = (async () => {
- let lastTransientFailures = 0;
- try {
- // 链路已恢复(rehydrate 只在 online 时运行,重连必经):普通断线期间
- // 产生的 schedule-index 瞬态负缓存立即失效,让本轮 reseed 拉到新数据
- // 而不是吃 30s TTL 内的旧 rejected promise(review P1)。
- invalidateTransientScheduleIndexFailures();
- do {
- state.rerun = false;
- if (backgroundReleaseInFlightRef.current) break;
- if (client.getStatus() !== 'online') return;
- const allPlans = registryRef.current.snapshot();
- // 撤权设备直接出局(review P1):撤权是终态,openLink 只会等来
- // link-close(revoked) + 超时;若不过滤,撤权时清熔断状态触发的这轮
- // rehydrate 会对它重新 openLink,且其超时已按撤权降级为不定论,
- // 熔断兜不住,退避循环会为它无限空转。也不计入 transientFailures。
- const grantedPlans = allPlans.filter(
- (plan) => !revokedDevicesStore.has(plan.deviceId),
- );
- // presence 已权威声明 unavailable 的设备不进入本轮 rehydrate。熔断
- // clear 会触发 store 订阅补跑一轮,若这里仍对离线设备重放 openLink /
- // subscribe / snapshot,只会制造一簇 DEVICE_OFFLINE 并放大弱网抖动。
- // 当前连接尚无该设备的 presence 记录(unknown)仍允许尝试;恢复快照会显式触发下一轮。
- const availablePlans = grantedPlans.filter(
- (plan) =>
- isPresenceEligibleForRemoteRequest(presenceAvailableByDeviceRef.current, plan.deviceId)
- // 永久关闭后的自动重建抑制:只有 transport-timeout/权威恢复/显式
- // 重开才解除,否则在途 openLink 被 LINK_NOT_OPEN 拒后的重试链会
- // 把对方用户刚关掉的链路建回来。
- && !rehydrateSuppressedDeviceIds.has(plan.deviceId),
- );
- // 改走显式代表性探测(review P1 多轮收敛):不能依赖 openLink /
- // subscribe 顺带探测——link-accept 与 subscribe 都在被控端 dispatch
- // 里于 runInvoke 之前特判应答,IPC/DB 卡死时照常回包会误关熔断;
- // 订阅已被 remoteSubscribedTopicsRef 记录或计划里没有 topic 时,
- // subscribe 甚至根本不会发包。探测窗口到点就发一条真正穿过
- // runInvoke → local-db 的最小读(见 DEVICE_RESPONSIVENESS_PROBE_CHANNEL),
- // 由它的回包决定熔断开合;这也是无业务流量时的主动恢复通道。
- // 探测候选取 registry 计划与 unresponsive 集合的并集(review P1):
- // 仅有直接 invoke、从未登记 openLink/subscribe 的设备(如只停留在
- // 首页的设备行)不在 registry 里,熔断 open 后若不纳入,它既收不到
- // 探测也不占未完成信号,会在没有业务流量时永久停留在未响应态。
- const openDeviceIds = new Set<string>();
- for (const plan of availablePlans) {
- if (unresponsiveDevicesStore.has(plan.deviceId)) openDeviceIds.add(plan.deviceId);
- }
- for (const deviceId of unresponsiveDevicesStore.getSnapshot()) {
- if (
- !revokedDevicesStore.has(deviceId)
- && isPresenceEligibleForRemoteRequest(presenceAvailableByDeviceRef.current, deviceId)
- // 探针会 sendOpenLinkOnce:被抑制设备同样不得经探针路径重建链路。
- && !rehydrateSuppressedDeviceIds.has(deviceId)
- ) {
- openDeviceIds.add(deviceId);
- }
- }
- const plans = availablePlans.filter(
- (plan) => !unresponsiveDevicesStore.has(plan.deviceId),
- );
- // 探测与健康设备的 rehydrate 并发跑(review P1):探测一台死设备最长
- // 要等 openLink + DB 读两次超时(~30s),串行在前会把其它健康桌面的
- // 订阅恢复 / 快照回填拖住整轮;多台 open 设备之间仍串行,避免探测
- // 本身成为并发突发。
- const probeRun = (async () => {
- for (const deviceId of openDeviceIds) {
- if (!isDeviceProbeDue(deviceId)) continue;
- await probeUnresponsiveDevice(client, deviceId);
- }
- })();
- const result = await rehydrateDeviceLinkTopics(plans, {
- isCancelled: () => backgroundReleaseInFlightRef.current,
- capturePresenceEpoch: (deviceId) =>
- capturePresenceAvailabilityEpoch(
- presenceAvailabilityEpochsRef.current,
- deviceId,
- ),
- captureResponseEvidenceEpoch: (deviceId) =>
- capturePresenceAvailabilityEpoch(
- remoteResponseEvidenceEpochs,
- deviceId,
- ),
- isPresenceEpochCurrent: (deviceId, capturedPresenceEpoch) =>
- isPresenceAvailabilityEpochCurrent(
- presenceAvailabilityEpochsRef.current,
- deviceId,
- capturedPresenceEpoch,
- ),
- isResponseEvidenceEpochCurrent: (
- deviceId,
- capturedResponseEvidenceEpoch,
- ) => isPresenceAvailabilityEpochCurrent(
- remoteResponseEvidenceEpochs,
- deviceId,
- capturedResponseEvidenceEpoch,
- ),
- createDeviceSendCohort: (deviceId) => createDeviceSendCohort(deviceId),
- openLink: (deviceId) => sendOpenLinkOnce(client, deviceId),
- subscribe: (deviceId, topics) => sendTrackedSubscribe(client, deviceId, topics),
- requestSessionsReseed: (deviceId) => remoteSessionStore.requestReseed(deviceId),
- onDeviceReachable: (deviceId) => {
- // 重连后 presence 是 unknown 且 server 不重放全量快照。补齐步骤已收到
- // 目标端真实应答即可证明设备可达,取消上一代 unavailable 留下的宽限清理;
- // 不伪造 presence=true,后续权威 false delta 仍可照常过滤并重新计时。
- clearOnePresenceWipeTimer(presenceWipeTimersRef.current, deviceId);
- remoteScheduleEventStore.clearDeviceMirrorInvalidation(deviceId);
- invalidateOfflineScheduleIndexFailureFor(deviceId);
- },
- onDeviceRemoteDisabled: (deviceId) => {
- // 被控端实时设置已明确关闭远控:这是当前 epoch 的权威终态,
- // 与 presence 的 remoteControlEnabled=false 一样立即清理,不留宽限。
- clearOnePresenceWipeTimer(
- presenceWipeTimersRef.current,
- deviceId,
- );
- publishPresenceAvailabilityMutation(deviceId, (availabilityByDevice) => {
- availabilityByDevice.set(deviceId, false);
- });
- presenceUnavailableVerdictsRef.current.set(deviceId, {
- kind: 'disabled',
- responseEvidenceEpoch: capturePresenceAvailabilityEpoch(
- remoteResponseEvidenceEpochs,
- deviceId,
- ),
- });
- presencePendingRecoveryDeviceIdsRef.current.add(deviceId);
- clearDeviceResponsivenessTrackingFor(deviceId);
- remoteSubscribedTopicsRef.current.delete(deviceId);
- wipeUnavailableDeviceMirror(deviceId);
- },
- onDeviceUnavailable: (deviceId) => {
- // 新连接按 unknown 乐观探测一次;relay 明确回 DEVICE_OFFLINE 后恢复
- // 当前代 false verdict,让退避重跑过滤该设备而不是持续重放整套计划。
- // rehydrate 已按请求发起时的 presence epoch 丢弃旧路由离线回包,
- // 因此这里不会覆盖更晚的 available=true。
- publishPresenceAvailabilityMutation(deviceId, (availabilityByDevice) => {
- availabilityByDevice.set(deviceId, false);
- });
- presenceUnavailableVerdictsRef.current.set(deviceId, {
- kind: 'offline',
- responseEvidenceEpoch: capturePresenceAvailabilityEpoch(
- remoteResponseEvidenceEpochs,
- deviceId,
- ),
- });
- presencePendingRecoveryDeviceIdsRef.current.add(deviceId);
- clearDeviceResponsivenessTrackingFor(deviceId);
- remoteSubscribedTopicsRef.current.delete(deviceId);
- scheduleUnavailableDeviceMirrorWipe(
- presenceWipeTimersRef.current,
- presenceAvailableByDeviceRef.current,
- deviceId,
- presenceWipeTimerDeps,
- );
- },
- rebuildSessionSnapshot: (deviceId, sessionId, opts) => rebuildSessionSnapshot(
- client,
- deviceId,
- sessionId,
- connectionEpochRef.current,
- opts,
- ),
- });
- await probeRun;
- // 探测后仍 open 的设备持续计入"未完成"信号(review P1:不能在探测
- // 真正跑完并成功前撤掉重试安排),退避重试循环(2s→30s)继续走:
- // 窗口未到的轮次只做本地检查,零管道流量。探测成功关熔断会触发
- // 下方 effect 的 store 订阅,补一轮全量 rehydrate 把该设备的订阅 /
- // 快照拉回来。
- const stillOpenDevices = [...openDeviceIds].filter(
- (deviceId) => unresponsiveDevicesStore.has(deviceId),
- ).length;
- lastTransientFailures = result.transientFailures + stillOpenDevices;
- } while (state.rerun && client.getStatus() === 'online');
- } finally {
- if (state.inFlight === run) {
- state.inFlight = null;
- state.rerun = false;
- }
- scheduleRehydrateRetry(client, lastTransientFailures);
- }
- })();
- state.inFlight = run;
- return run;
- },
- [
- probeUnresponsiveDevice,
- publishPresenceAvailabilityMutation,
- scheduleRehydrateRetry,
- sendOpenLinkOnce,
- sendTrackedSubscribe,
- ],
- );
+ const durablePlan = registryRef.current.snapshotDevice(targetDeviceId);
+ const forcedGeneration = forcedPeerRecoveryIntentRef.current.getGeneration(targetDeviceId);
+ const forcedOpen = forcedGeneration !== undefined
+ && hasOutboundPeerRecoveryIntent(client, targetDeviceId);
+ if (forcedGeneration !== undefined && !forcedOpen) {
+ forcedPeerRecoveryIntentRef.current.cancel(targetDeviceId);
+ }
+ const plan = resolvePeerRecoveryPlan(
+ targetDeviceId,
+ durablePlan,
+ forcedOpen,
+ );
+ if (!plan) return { retry: false };
+
+ // 只清当前 peer 在断线窗口留下的瞬时负缓存,避免 A 的恢复改变 B 的节流状态。
+ invalidateTransientScheduleIndexFailureFor(targetDeviceId);
+ const result = await rehydrateDeviceLinkPeer(plan, {
+ isCancelled: () => (
+ backgroundReleaseInFlightRef.current
+ || client !== clientRef.current
+ || client.getStatus() !== 'online'
+ || revokedDevicesStore.has(targetDeviceId)
+ || client.isOutboundExplicitlyClosed(targetDeviceId)
+ || !isPresenceEligibleForRemoteRequest(
+ presenceAvailableByDeviceRef.current,
+ targetDeviceId,
+ )
+ || rehydrateSuppressedDeviceIds.has(targetDeviceId)
+ || unresponsiveDevicesStore.has(targetDeviceId)
+ ),
+ capturePresenceEpoch: (deviceId) =>
+ capturePresenceAvailabilityEpoch(
+ presenceAvailabilityEpochsRef.current,
+ deviceId,
+ ),
+ captureResponseEvidenceEpoch: (deviceId) =>
+ capturePresenceAvailabilityEpoch(
+ remoteResponseEvidenceEpochs,
+ deviceId,
+ ),
+ isPresenceEpochCurrent: (deviceId, capturedPresenceEpoch) =>
+ isPresenceAvailabilityEpochCurrent(
+ presenceAvailabilityEpochsRef.current,
+ deviceId,
+ capturedPresenceEpoch,
+ ),
+ isResponseEvidenceEpochCurrent: (
+ deviceId,
+ capturedResponseEvidenceEpoch,
+ ) => isPresenceAvailabilityEpochCurrent(
+ remoteResponseEvidenceEpochs,
+ deviceId,
+ capturedResponseEvidenceEpoch,
+ ),
+ createDeviceSendCohort: (deviceId) => createDeviceSendCohort(deviceId),
+ openLink: (deviceId) => sendOpenLinkOnce(client, deviceId),
+ subscribe: (deviceId, topics) => sendTrackedSubscribe(client, deviceId, topics),
+ requestSessionsReseed: (deviceId) => remoteSessionStore.requestReseed(deviceId),
+ onDeviceReachable: (deviceId) => {
+ // 重连后没有全量 presence;目标端真实应答足以收口上一代遗留清理,
+ // 但不伪造 available=true,仍服从之后到达的权威 presence。
+ clearOnePresenceWipeTimer(presenceWipeTimersRef.current, deviceId);
+ remoteScheduleEventStore.clearDeviceMirrorInvalidation(deviceId);
+ invalidateOfflineScheduleIndexFailureFor(deviceId);
+ },
+ onDeviceRemoteDisabled: (deviceId) => {
+ clearOnePresenceWipeTimer(presenceWipeTimersRef.current, deviceId);
+ publishPresenceAvailabilityMutation(deviceId, (availabilityByDevice) => {
+ availabilityByDevice.set(deviceId, false);
+ });
+ presenceUnavailableVerdictsRef.current.set(deviceId, {
+ kind: 'disabled',
+ responseEvidenceEpoch: capturePresenceAvailabilityEpoch(
+ remoteResponseEvidenceEpochs,
+ deviceId,
+ ),
+ });
+ presencePendingRecoveryDeviceIdsRef.current.add(deviceId);
+ clearDeviceResponsivenessTrackingFor(deviceId);
+ remoteSubscribedTopicsRef.current.delete(deviceId);
+ wipeUnavailableDeviceMirror(deviceId);
+ },
+ onDeviceUnavailable: (deviceId) => {
+ publishPresenceAvailabilityMutation(deviceId, (availabilityByDevice) => {
+ availabilityByDevice.set(deviceId, false);
+ });
+ presenceUnavailableVerdictsRef.current.set(deviceId, {
+ kind: 'offline',
+ responseEvidenceEpoch: capturePresenceAvailabilityEpoch(
+ remoteResponseEvidenceEpochs,
+ deviceId,
+ ),
+ });
+ presencePendingRecoveryDeviceIdsRef.current.add(deviceId);
+ clearDeviceResponsivenessTrackingFor(deviceId);
+ remoteSubscribedTopicsRef.current.delete(deviceId);
+ scheduleUnavailableDeviceMirrorWipe(
+ presenceWipeTimersRef.current,
+ presenceAvailableByDeviceRef.current,
+ deviceId,
+ presenceWipeTimerDeps,
+ );
+ },
+ rebuildSessionSnapshot: (deviceId, sessionId, opts) => rebuildSessionSnapshot(
+ client,
+ deviceId,
+ sessionId,
+ connectionEpochRef.current,
+ opts,
+ ),
+ });
+
+ if (
+ forcedGeneration !== undefined
+ && result.linkOpened
+ && client === clientRef.current
+ && forcedPeerRecoveryIntentRef.current.complete(targetDeviceId, forcedGeneration)
+ ) {
+ // `complete` performs the generation-checked removal in the condition above.
+ }
+ const forcedOpenStillPending = forcedPeerRecoveryIntentRef.current.has(targetDeviceId)
+ && client === clientRef.current
+ && client.getStatus() === 'online'
+ && !revokedDevicesStore.has(targetDeviceId)
+ && hasOutboundPeerRecoveryIntent(client, targetDeviceId)
+ && isPresenceEligibleForRemoteRequest(
+ presenceAvailableByDeviceRef.current,
+ targetDeviceId,
+ )
+ && !rehydrateSuppressedDeviceIds.has(targetDeviceId);
+ return {
+ retry: result.transientFailures > 0
+ || unresponsiveDevicesStore.has(targetDeviceId)
+ || forcedOpenStillPending,
+ };
+ }, [
+ probeUnresponsiveDevice,
+ hasOutboundPeerRecoveryIntent,
+ publishPresenceAvailabilityMutation,
+ sendOpenLinkOnce,
+ sendTrackedSubscribe,
+ ]);
+
+ const rehydrateWithClient = useCallback((
+ client: DeviceLinkClient,
+ targetDeviceId?: string,
+ ): Promise<void> => {
+ if (
+ client !== clientRef.current
+ || client.getStatus() !== 'online'
+ || backgroundReleaseInFlightRef.current
+ ) {
+ return Promise.resolve();
+ }
+ const scheduler = peerRecoverySchedulerRef.current;
+ scheduler?.resume();
+ if (targetDeviceId) {
+ scheduler?.request(targetDeviceId);
+ } else {
+ // Relay 重连 / App 回前台是共享生命周期事件:即使某设备此刻没有持有
+ // topic,它此前因 WSS 掉线留下的 NOT_CONNECTED 负缓存也已经失效。
+ // 单 peer 恢复不会走这里,仍只清自己的缓存。
+ invalidateTransientScheduleIndexFailures();
+ const deviceIds = new Set(registryRef.current.deviceIds());
+ for (const deviceId of forcedPeerRecoveryIntentRef.current.deviceIds()) {
+ deviceIds.add(deviceId);
+ }
+ for (const deviceId of unresponsiveDevicesStore.getSnapshot()) {
+ deviceIds.add(deviceId);
+ }
+ scheduler?.requestMany(deviceIds);
+ }
+ return Promise.resolve();
+ }, []);
useEffect(() => {
- rehydrateFnRef.current = rehydrateWithClient;
- }, [rehydrateWithClient]);
+ runPeerRecoveryRef.current = (deviceId) => {
+ const client = clientRef.current;
+ if (!client) return Promise.resolve({ retry: false });
+ return runPeerRecovery(client, deviceId);
+ };
+ }, [runPeerRecovery]);
useEffect(() => {
const accountGenerationChanged =
@@ -680,9 +693,8 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
clientRef.current = null;
registryRef.current.clear();
remoteSubscribedTopicsRef.current.clear();
- rehydrateStateRef.current.inFlight = null;
- rehydrateStateRef.current.rerun = false;
- clearRehydrateRetry(true);
+ forcedPeerRecoveryIntentRef.current.clear();
+ peerRecoverySchedulerRef.current?.clear();
clearAllPresenceWipeTimers(presenceWipeTimersRef.current);
openLinkInFlightRef.current.clear();
presenceAvailableByDeviceRef.current.clear();
@@ -704,8 +716,18 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
// 账号切换期间 isAuthenticated 始终为 true,不能依赖上面的登出分支。
// effect cleanup 只负责 transport;新账号建连前必须同步清掉旧账号的任务、
// 调度、设备与 presence 投影,避免无设备的新账号永远保留旧快照。
- if (accountGenerationChanged) clearPerAccountDeviceLinkState();
+ if (accountGenerationChanged) {
+ clearPerAccountDeviceLinkState();
+ // Topic intent is account-owned too. Keeping the previous account's owners here would make
+ // the new client's first online recovery subscribe device ids that its Home never selected.
+ registryRef.current.clear();
+ remoteSubscribedTopicsRef.current.clear();
+ forcedPeerRecoveryIntentRef.current.clear();
+ }
+ // 新账号/新 client 必须从空的 peer 生命周期表开始;旧连接迟到的恢复结果
+ // 会被 scheduler generation 丢弃,不能写回新账号。
+ peerRecoverySchedulerRef.current?.clear();
const client = new DeviceLinkClient({
getWsUrl: () => deviceLinkWsUrl(),
getToken: auth.getAccessToken,
@@ -718,6 +740,10 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
}),
createWebSocket: createRnWebSocket,
logger: mobileDeviceLinkLogger,
+ // Mobile 具备按 deviceId 独立 openLink/订阅/快照恢复能力。可靠 ACK
+ // 耗尽时只复位该 peer,共享 WSS 和其它远端继续工作;恢复仍只使用所有
+ // Desktop 版本都支持的 link-open,不增加 wire/capability 要求。
+ peerFailurePolicy: 'isolate-peer',
// 手机弱网(切基站 / 弱 WiFi)下 TCP 半开假活远比桌面常见,收紧心跳把
// 半开检测从默认 ~60s(20s×3 tick)压到 ~20s(10s×2 tick);检测到即
// fail 全部 pending invoke,不让用户操作干等 30s 请求超时。仅手机端
@@ -743,8 +769,8 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
remoteSubscribedTopicsRef.current.clear();
// 掉线:所有会话的实时行都可能从此漏收,窗口连续性结论的上界不再可续算。
remoteSessionStore.noteLiveStreamInterrupted();
- // 掉线即取消挂起的补齐重试:重新 online 会触发全量补齐,无需旧计时器
- clearRehydrateRetry(true);
+ // Relay 连接故障才暂停全部 peer;重新 online 后它们各自重新进入恢复队列。
+ peerRecoverySchedulerRef.current?.pause();
return;
}
// presence 是当前在线控制端收到的 delta,server 不会在 hello-ack 后重放
@@ -778,6 +804,19 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
resetRemoteProjectOrderPushFence();
void rehydrateWithClient(client);
});
+ const offPeerTransportReset = client.onPeerTransportReset(({ deviceId }) => {
+ // 这是本地 ACK 超时,不是对端可达证据:只失效该 peer 的建链缓存和
+ // 订阅 ACK,再排该 peer 恢复;presence、其它 peer 与共享 WSS 均不动。
+ resetRemoteProjectOrderPushFence(deviceId);
+ const shouldRecover = requestForcedPeerRecovery(client, deviceId);
+ invalidatePeerLinkState(
+ deviceId,
+ openLinkInFlightRef.current,
+ remoteSubscribedTopicsRef.current,
+ noteSessionLiveStreamsInterrupted,
+ );
+ if (shouldRecover) void rehydrateWithClient(client, deviceId);
+ });
const offPresence = client.onPresenceChanged((snap) => {
markPresenceAvailabilityEpoch(presenceAvailabilityEpochsRef.current, snap.deviceId);
// presence 变化代表目标链路代际变化(offline / remote-disabled / 恢复都一样):
@@ -804,6 +843,8 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
}
const wipeTimers = presenceWipeTimersRef.current;
if (!presence.available) {
+ // 权威离线/关闭远控只取消对应 peer,不碰其它远端的在途恢复与退避。
+ peerRecoverySchedulerRef.current?.cancel(snap.deviceId);
// Relay 的权威 presence 已说明目标离线或关闭远控:此前 INVOKE_TIMEOUT
// 只能视为这次可用性变化的下游症状,不再代表桌面 IPC/DB 卡死。立即清除
// 响应性计数并翻代,让在途请求随后到达的 timeout 也无法重建误熔断。
@@ -843,11 +884,15 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
// ≠ 对方重新授权或本机用户主动重开(对方结束链路后一直在线是常态)。
// 解除点只有:transport-timeout / 新连接代际 / 显式 openLink 成功
// (见 linkClose.ts 的具名 lift 入口)。
- if (presence.recovered) void rehydrateWithClient(client);
+ if (presence.recovered) void rehydrateWithClient(client, snap.deviceId);
});
const offFrame = client.onFrame((env) => routeFrame(env, {
currentDataOwnerId: currentDataOwnerIdRef.current,
- onAccessRevoked: (deviceId) => remoteSubscribedTopicsRef.current.delete(deviceId),
+ onAccessRevoked: (deviceId) => {
+ remoteSubscribedTopicsRef.current.delete(deviceId);
+ forcedPeerRecoveryIntentRef.current.cancel(deviceId);
+ peerRecoverySchedulerRef.current?.cancel(deviceId);
+ },
onLinkClosed: (deviceId, reason) => {
resetRemoteProjectOrderPushFence(deviceId);
updateRehydrateSuppressionOnLinkClose(
@@ -867,6 +912,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
// 其它 reason(user/toggle-off/shutdown/revoked)维持原语义:只失效,
// 不自动重建。
if (reason === 'transport-timeout') {
+ const shouldRecover = requestForcedPeerRecovery(client, deviceId);
// 收到该帧本身就是对端可达的直接证据:先冲销遗留的 presence=false /
// 离线判定(否则本轮 rehydrate 会把该设备从 availablePlans 排除,
// 重建根本不会发起)。两段冲销:markRemoteResponseEvidence 走既有
@@ -890,7 +936,9 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
// (markRemoteResponseEvidence 的证据链只在命中可推翻的 offline
// verdict 时才顺带清 timer,覆盖不了无 verdict 的 stale 路径。)
clearOnePresenceWipeTimer(presenceWipeTimersRef.current, deviceId);
- void rehydrateWithClient(client);
+ if (shouldRecover) void rehydrateWithClient(client, deviceId);
+ } else {
+ forcedPeerRecoveryIntentRef.current.cancel(deviceId);
}
},
onProviderChanged: (deviceId) => {
@@ -944,6 +992,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
remoteSubscribedTopicsRef.current,
noteSessionLiveStreamsInterrupted,
);
+ const shouldRecover = requestForcedPeerRecovery(client, deviceId);
markRemoteResponseEvidence(deviceId);
publishPresenceAvailabilityMutation(deviceId, (availabilityByDevice) => (
reconcileAvailabilityAfterInboundFrame(
@@ -954,7 +1003,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
)
));
clearOnePresenceWipeTimer(presenceWipeTimersRef.current, deviceId);
- void rehydrateWithClient(client);
+ if (shouldRecover) void rehydrateWithClient(client, deviceId);
});
client.start();
@@ -976,7 +1025,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
}
clearOnePresenceWipeTimer(presenceWipeTimersRef.current, deviceId);
- void rehydrateWithClient(client);
+ void rehydrateWithClient(client, deviceId);
});
// 熔断状态变化触发 rehydrate:unresponsive 集合的新增与移除都各触发一次
@@ -989,11 +1038,17 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
let lastUnresponsiveSnapshot = unresponsiveDevicesStore.getSnapshot();
const offUnresponsive = unresponsiveDevicesStore.subscribe(() => {
const next = unresponsiveDevicesStore.getSnapshot();
- const changed =
- next.size !== lastUnresponsiveSnapshot.size
- || [...lastUnresponsiveSnapshot].some((deviceId) => !next.has(deviceId));
+ const changedDeviceIds = new Set<string>();
+ for (const deviceId of next) {
+ if (!lastUnresponsiveSnapshot.has(deviceId)) changedDeviceIds.add(deviceId);
+ }
+ for (const deviceId of lastUnresponsiveSnapshot) {
+ if (!next.has(deviceId)) changedDeviceIds.add(deviceId);
+ }
lastUnresponsiveSnapshot = next;
- if (changed) void rehydrateWithClient(client);
+ for (const deviceId of changedDeviceIds) {
+ void rehydrateWithClient(client, deviceId);
+ }
});
// 退后台的断连宽限状态:stopTimer 挂着表示还没真正 stop;backgroundAt 用于
@@ -1045,6 +1100,9 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
if (next === 'background') {
backgroundReleaseInFlightRef.current = true;
backgroundReleaseGenerationRef.current += 1;
+ // App 生命周期暂停全部恢复执行,但各 peer 状态仍彼此独立;回前台统一
+ // 重新排队,旧代请求的迟到结果不会创建重试。
+ peerRecoverySchedulerRef.current?.pause();
// 立即释放重量级 session:<id> 订阅(趁 socket 还活着、iOS 尚未挂起 JS):
// 被控桌面以「有人订阅该会话流」为防打扰信号压制手机系统推送,锁屏/切后台
// 后若订阅残留(宽限窗、挂起延迟最长可拖到 server 60s 空闲清扫),恰好在
@@ -1081,14 +1139,15 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
offBeforeLink();
offFrame();
offPresence();
+ offPeerTransportReset();
offStatus();
offIssue();
client.stop();
- rehydrateStateRef.current.rerun = false;
- clearRehydrateRetry(true);
+ peerRecoverySchedulerRef.current?.clear();
clearAllPresenceWipeTimers(presenceWipeTimersRef.current);
openLinkInFlightRef.current.clear();
remoteSubscribedTopicsRef.current.clear();
+ forcedPeerRecoveryIntentRef.current.clear();
presenceAvailableByDeviceRef.current.clear();
resetPresenceAvailabilityEpochs(presenceAvailabilityEpochsRef.current);
resetPresenceAvailabilityEpochs(remoteResponseEvidenceEpochs);
@@ -1102,9 +1161,9 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
auth.getAccessToken,
auth.isAuthenticated,
clearPerAccountDeviceLinkState,
- clearRehydrateRetry,
publishPresenceAvailabilityMutation,
rehydrateWithClient,
+ requestForcedPeerRecovery,
]);
const openLink = useCallback(
@@ -1130,6 +1189,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
const closeLink = useCallback((deviceId: string) => {
registryRef.current.untrackOpenLink(deviceId);
+ forcedPeerRecoveryIntentRef.current.cancel(deviceId);
openLinkInFlightRef.current.delete(deviceId);
clientRef.current?.closeLink(deviceId, 'user');
}, []);
@@ -1168,7 +1228,12 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
markRemoteTopicsUnsubscribed(remoteSubscribedTopicsRef.current, deviceId, toSend);
noteSessionLiveStreamsInterrupted(toSend);
if (toSend.length === 0) return;
- await sendUnsubscribe(requireClient(clientRef.current), deviceId, toSend);
+ await sendUnsubscribe(
+ requireClient(clientRef.current),
+ deviceId,
+ toSend,
+ (topic) => !registryRef.current.hasTopic(deviceId, topic),
+ );
}, []);
const getPresenceAvailability = useCallback((deviceId: string): boolean | null => (
@@ -1633,6 +1698,7 @@ async function sendUnsubscribe(
client: DeviceLinkClient,
deviceId: string,
topics: readonly string[],
+ shouldSendTopic?: (topic: string) => boolean,
): Promise<void> {
const slot = acquireDeviceSendSlot(deviceId);
try {
@@ -1641,11 +1707,19 @@ async function sendUnsubscribe(
settleDeviceSend(deviceId, slot, 'inconclusive');
throw err;
}
+ // Scope may be reacquired while ensureOnlineForRequest is waiting. Filter immediately
+ // before client.invoke (there is no await between this check and enqueueing the frame),
+ // so an older cleanup can never land after a newer subscribe and tear it down again.
+ const toSend = shouldSendTopic ? topics.filter(shouldSendTopic) : topics;
+ if (toSend.length === 0) {
+ settleDeviceSend(deviceId, slot, 'inconclusive');
+ return;
+ }
let result: InvokeResultPayload;
try {
result = await client.invoke(deviceId, {
channel: DL_UNSUBSCRIBE_CHANNEL,
- args: [{ topics }],
+ args: [{ topics: toSend }],
});
} catch (err) {
settleDeviceSend(deviceId, slot, classifyDeviceSendFailure(err));
diff --git a/apps/mobile/src/device-link/peerRecoveryScheduler.ts b/apps/mobile/src/device-link/peerRecoveryScheduler.ts
new file mode 100644
index 0000000000..efe8565e96
--- /dev/null
+++ b/apps/mobile/src/device-link/peerRecoveryScheduler.ts
@@ -0,0 +1,301 @@
+export type PeerRecoveryPhase = 'idle' | 'queued' | 'running' | 'waiting-retry';
+
+export interface PeerRecoveryResult {
+ /** True when this peer still has transient work and needs a later retry. */
+ retry: boolean;
+}
+
+export interface PeerRecoverySchedulerOptions {
+ maxConcurrent?: number;
+ retryBaseMs?: number;
+ retryMaxMs?: number;
+ onError?(deviceId: string, error: unknown): void;
+}
+
+export interface PeerRecoverySnapshot {
+ deviceId: string;
+ phase: PeerRecoveryPhase;
+ retryAttempt: number;
+}
+
+interface PeerRecoveryEntry {
+ phase: PeerRecoveryPhase;
+ generation: number;
+ running: boolean;
+ rerun: boolean;
+ retryAttempt: number;
+ retryTimer: ReturnType<typeof setTimeout> | null;
+}
+
+const DEFAULT_MAX_CONCURRENT = 6;
+const DEFAULT_RETRY_BASE_MS = 2_000;
+const DEFAULT_RETRY_MAX_MS = 30_000;
+
+/**
+ * Transient open intent created by a peer-level transport reset. Generations never reuse
+ * within this provider lifetime, so an old A recovery cannot clear a newer A intent after
+ * cancel → reacquire (the same ABA fence used by the scheduler itself).
+ */
+export class PeerRecoveryOpenIntentRegistry {
+ private readonly generations = new Map<string, number>();
+ private nextGeneration = 0;
+
+ request(deviceId: string): number {
+ if (!deviceId) return 0;
+ const generation = ++this.nextGeneration;
+ this.generations.set(deviceId, generation);
+ return generation;
+ }
+
+ getGeneration(deviceId: string): number | undefined {
+ return this.generations.get(deviceId);
+ }
+
+ has(deviceId: string): boolean {
+ return this.generations.has(deviceId);
+ }
+
+ complete(deviceId: string, generation: number): boolean {
+ if (this.generations.get(deviceId) !== generation) return false;
+ this.generations.delete(deviceId);
+ return true;
+ }
+
+ cancel(deviceId: string): void {
+ this.generations.delete(deviceId);
+ }
+
+ clear(): void {
+ // Keep nextGeneration monotonic: a settling pre-clear run must never collide with a
+ // post-clear intent if the provider/client is replaced while its promise unwinds.
+ this.generations.clear();
+ }
+
+ deviceIds(): string[] {
+ return [...this.generations.keys()];
+ }
+}
+
+/**
+ * Runs recovery independently per remote device while sharing a small global
+ * concurrency budget. A slow peer occupies at most one slot, so it cannot hold
+ * every other desktop behind its timeout. Each peer owns its own rerun flag,
+ * retry attempt and timer.
+ */
+export class PeerRecoveryScheduler {
+ private readonly runPeer: (deviceId: string) => Promise<PeerRecoveryResult>;
+ private readonly onError?: PeerRecoverySchedulerOptions['onError'];
+ private readonly maxConcurrent: number;
+ private readonly retryBaseMs: number;
+ private readonly retryMaxMs: number;
+ private readonly entries = new Map<string, PeerRecoveryEntry>();
+ private readonly queue: string[] = [];
+ private readonly queued = new Set<string>();
+ private active = 0;
+ private paused = false;
+
+ constructor(
+ run: (deviceId: string) => Promise<PeerRecoveryResult>,
+ options: PeerRecoverySchedulerOptions = {},
+ ) {
+ this.runPeer = run;
+ this.onError = options.onError;
+ this.maxConcurrent = normalizePositiveInteger(
+ options.maxConcurrent,
+ DEFAULT_MAX_CONCURRENT,
+ );
+ this.retryBaseMs = normalizePositiveInteger(
+ options.retryBaseMs,
+ DEFAULT_RETRY_BASE_MS,
+ );
+ this.retryMaxMs = Math.max(
+ this.retryBaseMs,
+ normalizePositiveInteger(options.retryMaxMs, DEFAULT_RETRY_MAX_MS),
+ );
+ }
+
+ request(deviceId: string): void {
+ if (!deviceId) return;
+ const entry = this.getOrCreateEntry(deviceId);
+ if (entry.retryTimer) {
+ clearTimeout(entry.retryTimer);
+ entry.retryTimer = null;
+ }
+ // A cancelled generation may still be settling. Keep the next generation
+ // serialized behind it so one peer never has two recovery runs in flight.
+ if (entry.running) {
+ entry.rerun = true;
+ return;
+ }
+ this.enqueue(deviceId, entry);
+ }
+
+ requestMany(deviceIds: Iterable<string>): void {
+ for (const deviceId of deviceIds) this.request(deviceId);
+ }
+
+ /** Cancels one peer without touching any other peer's timers or work. */
+ cancel(deviceId: string, resetAttempt = true): void {
+ const entry = this.entries.get(deviceId);
+ if (!entry) return;
+ entry.generation += 1;
+ entry.rerun = false;
+ if (resetAttempt) entry.retryAttempt = 0;
+ if (entry.retryTimer) {
+ clearTimeout(entry.retryTimer);
+ entry.retryTimer = null;
+ }
+ if (this.queued.delete(deviceId)) {
+ const index = this.queue.indexOf(deviceId);
+ if (index >= 0) this.queue.splice(index, 1);
+ }
+ entry.phase = 'idle';
+ }
+
+ /**
+ * Relay/background lifecycle gate. In-flight promises cannot be force-cancelled,
+ * but generation fencing makes their late scheduling result inert.
+ */
+ pause(): void {
+ if (this.paused) return;
+ this.paused = true;
+ this.cancelAll(true);
+ }
+
+ resume(): void {
+ if (!this.paused) {
+ this.drain();
+ return;
+ }
+ this.paused = false;
+ this.drain();
+ }
+
+ /** Clears all queued/timed work while retaining safe fences for settling runs. */
+ clear(): void {
+ this.cancelAll(true);
+ for (const [deviceId, entry] of this.entries) {
+ if (!entry.running) this.entries.delete(deviceId);
+ }
+ }
+
+ getSnapshot(deviceId: string): PeerRecoverySnapshot {
+ const entry = this.entries.get(deviceId);
+ return {
+ deviceId,
+ phase: entry?.phase ?? 'idle',
+ retryAttempt: entry?.retryAttempt ?? 0,
+ };
+ }
+
+ private cancelAll(resetAttempts: boolean): void {
+ this.queue.length = 0;
+ this.queued.clear();
+ for (const [deviceId] of this.entries) this.cancel(deviceId, resetAttempts);
+ }
+
+ private getOrCreateEntry(deviceId: string): PeerRecoveryEntry {
+ let entry = this.entries.get(deviceId);
+ if (!entry) {
+ entry = {
+ phase: 'idle',
+ generation: 0,
+ running: false,
+ rerun: false,
+ retryAttempt: 0,
+ retryTimer: null,
+ };
+ this.entries.set(deviceId, entry);
+ }
+ return entry;
+ }
+
+ private enqueue(deviceId: string, entry: PeerRecoveryEntry): void {
+ if (this.queued.has(deviceId)) return;
+ entry.phase = 'queued';
+ this.queued.add(deviceId);
+ this.queue.push(deviceId);
+ this.drain();
+ }
+
+ private drain(): void {
+ if (this.paused) return;
+ while (this.active < this.maxConcurrent && this.queue.length > 0) {
+ const deviceId = this.queue.shift()!;
+ this.queued.delete(deviceId);
+ const entry = this.entries.get(deviceId);
+ if (!entry || entry.phase !== 'queued' || entry.running) continue;
+ this.start(deviceId, entry);
+ }
+ }
+
+ private start(deviceId: string, entry: PeerRecoveryEntry): void {
+ const generation = entry.generation;
+ entry.phase = 'running';
+ entry.running = true;
+ entry.rerun = false;
+ this.active += 1;
+
+ let run: Promise<PeerRecoveryResult>;
+ try {
+ run = this.runPeer(deviceId);
+ } catch (error) {
+ try {
+ this.onError?.(deviceId, error);
+ } catch {
+ // Diagnostics must never strand the scheduler's active-slot accounting.
+ }
+ this.finish(deviceId, entry, generation, { retry: true });
+ return;
+ }
+ void run.then(
+ (result) => this.finish(deviceId, entry, generation, result),
+ (error: unknown) => {
+ try {
+ this.onError?.(deviceId, error);
+ } catch {
+ // Diagnostics must never strand the scheduler's active-slot accounting.
+ }
+ this.finish(deviceId, entry, generation, { retry: true });
+ },
+ );
+ }
+
+ private finish(
+ deviceId: string,
+ entry: PeerRecoveryEntry,
+ generation: number,
+ result: PeerRecoveryResult,
+ ): void {
+ if (entry.generation === generation && !entry.rerun) {
+ if (!result.retry) {
+ entry.retryAttempt = 0;
+ entry.phase = 'idle';
+ } else {
+ const delay = Math.min(
+ this.retryBaseMs * 2 ** entry.retryAttempt,
+ this.retryMaxMs,
+ );
+ entry.retryAttempt += 1;
+ entry.phase = 'waiting-retry';
+ entry.retryTimer = setTimeout(() => {
+ entry.retryTimer = null;
+ if (entry.generation !== generation) return;
+ this.enqueue(deviceId, entry);
+ }, delay);
+ }
+ }
+ entry.running = false;
+ this.active -= 1;
+ if (entry.rerun) {
+ entry.rerun = false;
+ this.enqueue(deviceId, entry);
+ }
+ this.drain();
+ }
+}
+
+function normalizePositiveInteger(value: number | undefined, fallback: number): number {
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return fallback;
+ return Math.max(1, Math.floor(value));
+}
diff --git a/apps/mobile/src/device-link/rehydrate.ts b/apps/mobile/src/device-link/rehydrate.ts
index 57f1844486..2d02370112 100644
--- a/apps/mobile/src/device-link/rehydrate.ts
+++ b/apps/mobile/src/device-link/rehydrate.ts
@@ -46,6 +46,11 @@ export interface DeviceLinkRehydrateResult {
transientFailures: number;
}
+export interface DeviceLinkPeerRehydrateResult extends DeviceLinkRehydrateResult {
+ /** True only when this peer's link-open step actually resolved successfully. */
+ linkOpened: boolean;
+}
+
/**
* Replays controller intent after mobile foreground/background or relay
* reconnect. Every step is best-effort because the host remains authoritative:
@@ -58,18 +63,36 @@ export async function rehydrateDeviceLinkTopics(
deps: DeviceLinkRehydrateDeps,
): Promise<DeviceLinkRehydrateResult> {
let transientFailures = 0;
+ for (const plan of plans) {
+ if (deps.isCancelled?.()) break;
+ const result = await rehydrateDeviceLinkPeer(plan, deps);
+ transientFailures += result.transientFailures;
+ }
+ return { transientFailures };
+}
+
+/**
+ * Rehydrates one remote machine only. Scheduling peers belongs to the caller,
+ * so a timeout from this plan never serializes unrelated desktops behind it.
+ */
+export async function rehydrateDeviceLinkPeer(
+ plan: RehydratePlan,
+ deps: DeviceLinkRehydrateDeps,
+): Promise<DeviceLinkPeerRehydrateResult> {
+ let transientFailures = 0;
+ let linkOpened = false;
const track = async (
deviceId: string,
capturedPresenceEpoch: number,
capturedResponseEvidenceEpoch: number,
step: Promise<unknown>,
- ): Promise<'continue' | 'unavailable'> => {
+ ): Promise<'succeeded' | 'failed' | 'unavailable'> => {
try {
await step;
if (deps.isPresenceEpochCurrent(deviceId, capturedPresenceEpoch)) {
deps.onDeviceReachable?.(deviceId);
}
- return 'continue';
+ return 'succeeded';
} catch (err) {
const epochCurrent = deps.isPresenceEpochCurrent(
deviceId,
@@ -105,63 +128,66 @@ export async function rehydrateDeviceLinkTopics(
) {
transientFailures += 1;
}
- return unavailable ? 'unavailable' : 'continue';
+ return unavailable ? 'unavailable' : 'failed';
}
};
- for (const plan of plans) {
- if (deps.isCancelled?.()) return { transientFailures };
- if (plan.openLink) {
- // openLink 可能与页面请求共用一条在途请求;它必须连同底层请求真正创建时
- // 捕获的 epoch 一起复用,不能在 dedupe 时补拍一个更新的 epoch。
- const openLinkStep = deps.openLink(plan.deviceId);
- if (await track(
- plan.deviceId,
- openLinkStep.capturedPresenceEpoch,
- openLinkStep.capturedResponseEvidenceEpoch,
- openLinkStep.request,
- ) === 'unavailable') {
- continue;
- }
+ if (deps.isCancelled?.()) return { linkOpened, transientFailures };
+ // Honor plan.openLink. Listing-only owners (Home `sessions`) subscribe without a control
+ // link so Desktop does not show「正在被控」. ACK-reset recovery already promotes the plan
+ // through resolvePeerRecoveryPlan when the peer queue actually needs a reopen.
+ if (plan.openLink) {
+ // openLink 可能与页面请求共用一条在途请求;它必须连同底层请求真正创建时
+ // 捕获的 epoch 一起复用,不能在 dedupe 时补拍一个更新的 epoch。
+ const openLinkStep = deps.openLink(plan.deviceId);
+ const openResult = await track(
+ plan.deviceId,
+ openLinkStep.capturedPresenceEpoch,
+ openLinkStep.capturedResponseEvidenceEpoch,
+ openLinkStep.request,
+ );
+ if (openResult === 'unavailable') {
+ return { linkOpened, transientFailures };
}
+ linkOpened = openResult === 'succeeded';
+ }
+
+ if (plan.topics.length === 0) return { linkOpened, transientFailures };
+ if (deps.isCancelled?.()) return { linkOpened, transientFailures };
+ if (
+ await track(
+ plan.deviceId,
+ deps.capturePresenceEpoch(plan.deviceId),
+ deps.captureResponseEvidenceEpoch(plan.deviceId),
+ deps.subscribe(plan.deviceId, plan.topics),
+ ) === 'unavailable'
+ ) {
+ return { linkOpened, transientFailures };
+ }
- if (plan.topics.length === 0) continue;
- if (deps.isCancelled?.()) return { transientFailures };
- if (
- await track(
+ for (const topic of plan.topics) {
+ if (deps.isCancelled?.()) return { linkOpened, transientFailures };
+ if (topic === 'sessions') {
+ deps.requestSessionsReseed(plan.deviceId);
+ continue;
+ }
+ const sessionId = readSessionTopic(topic);
+ if (sessionId) {
+ // 每个 session snapshot 自身包含四路 Promise.allSettled fan-out;只把
+ // 同一批真正并发的请求合并,不要把多个串行 session 的超时压成一次观测。
+ if (await track(
plan.deviceId,
deps.capturePresenceEpoch(plan.deviceId),
deps.captureResponseEvidenceEpoch(plan.deviceId),
- deps.subscribe(plan.deviceId, plan.topics),
- ) === 'unavailable'
- ) {
- continue;
- }
-
- for (const topic of plan.topics) {
- if (deps.isCancelled?.()) return { transientFailures };
- if (topic === 'sessions') {
- deps.requestSessionsReseed(plan.deviceId);
- continue;
- }
- const sessionId = readSessionTopic(topic);
- if (sessionId) {
- // 每个 session snapshot 自身包含四路 Promise.allSettled fan-out;只把
- // 同一批真正并发的请求合并,不要把多个串行 session 的超时压成一次观测。
- if (await track(
- plan.deviceId,
- deps.capturePresenceEpoch(plan.deviceId),
- deps.captureResponseEvidenceEpoch(plan.deviceId),
- deps.rebuildSessionSnapshot(plan.deviceId, sessionId, {
- responsivenessCohort: deps.createDeviceSendCohort(plan.deviceId),
- }),
- ) === 'unavailable') {
- break;
- }
+ deps.rebuildSessionSnapshot(plan.deviceId, sessionId, {
+ responsivenessCohort: deps.createDeviceSendCohort(plan.deviceId),
+ }),
+ ) === 'unavailable') {
+ break;
}
}
}
- return { transientFailures };
+ return { linkOpened, transientFailures };
}
export function hasDeviceLinkErrorCode(
diff --git a/apps/mobile/src/device-link/topicRegistry.ts b/apps/mobile/src/device-link/topicRegistry.ts
index 128ca4c902..33174216a9 100644
--- a/apps/mobile/src/device-link/topicRegistry.ts
+++ b/apps/mobile/src/device-link/topicRegistry.ts
@@ -69,12 +69,29 @@ export class DeviceLinkTopicRegistry {
}
snapshot(): RehydratePlan[] {
- const ids = new Set<string>([...this.openLinks, ...this.topicOwners.keys()]);
- return [...ids].sort().map((deviceId) => ({
- deviceId,
- openLink: this.openLinks.has(deviceId),
- topics: [...(this.topicOwners.get(deviceId)?.keys() ?? [])].sort(),
- }));
+ return this.deviceIds().map((deviceId) => this.snapshotDevice(deviceId)!);
+ }
+
+ /** Current recovery intent for one peer; null means this peer has no held work. */
+ snapshotDevice(deviceId: string): RehydratePlan | null {
+ const openLink = this.openLinks.has(deviceId);
+ const topics = [...(this.topicOwners.get(deviceId)?.keys() ?? [])].sort();
+ if (!openLink && topics.length === 0) return null;
+ return { deviceId, openLink, topics };
+ }
+
+ /**
+ * Stable peer order used to seed the fair recovery scheduler. Peers with visible
+ * topic work go first; historical open-link-only intent must not delay the machine
+ * whose Home/session content is currently on screen.
+ */
+ deviceIds(): string[] {
+ return [...new Set<string>([...this.openLinks, ...this.topicOwners.keys()])].sort((a, b) => {
+ const aHasTopics = (this.topicOwners.get(a)?.size ?? 0) > 0;
+ const bHasTopics = (this.topicOwners.get(b)?.size ?? 0) > 0;
+ if (aHasTopics !== bHasTopics) return aHasTopics ? -1 : 1;
+ return a < b ? -1 : a > b ? 1 : 0;
+ });
}
hasTopic(deviceId: string, topic: string): boolean {
@@ -139,3 +156,21 @@ export function markRemoteTopicsUnsubscribed(
for (const topic of topics) current.delete(topic);
if (current.size === 0) acked.delete(deviceId);
}
+
+/**
+ * Combines durable screen/topic intent with a transient transport-forced reopen.
+ * ACK reset can happen after the final topic owner has already released, while a reliable
+ * request is still pending in the client. In that case the synthetic open-only plan is the
+ * only way to thaw the peer without rebuilding the shared WSS.
+ */
+export function resolvePeerRecoveryPlan(
+ deviceId: string,
+ durablePlan: RehydratePlan | null,
+ forceOpen: boolean,
+): RehydratePlan | null {
+ if (!durablePlan) {
+ return forceOpen ? { deviceId, openLink: true, topics: [] } : null;
+ }
+ if (!forceOpen || durablePlan.openLink) return durablePlan;
+ return { ...durablePlan, openLink: true };
+}
diff --git a/apps/mobile/src/session/homeDeviceSync.ts b/apps/mobile/src/session/homeDeviceSync.ts
new file mode 100644
index 0000000000..86b092df19
--- /dev/null
+++ b/apps/mobile/src/session/homeDeviceSync.ts
@@ -0,0 +1,138 @@
+export const HOME_DEVICE_SYNC_CONCURRENCY = 6;
+
+export interface HomeDeviceSyncCandidate {
+ canOpen: boolean;
+ deviceId: string;
+}
+
+type HomeDeviceSyncTask<T> = {
+ run: () => Promise<T>;
+ resolve: (value: T | PromiseLike<T>) => void;
+ reject: (reason?: unknown) => void;
+};
+
+/**
+ * Shared Home device-work limiter. Separate list/reseed/schedule/project-order triggers all
+ * enter the same pool, so overlapping effects cannot each create their own six-device burst.
+ */
+export class HomeDeviceSyncLimiter {
+ private readonly maxConcurrent: number;
+ private readonly foregroundQueue: HomeDeviceSyncTask<unknown>[] = [];
+ private readonly backgroundQueue: HomeDeviceSyncTask<unknown>[] = [];
+ private active = 0;
+
+ constructor(maxConcurrent: number = HOME_DEVICE_SYNC_CONCURRENCY) {
+ this.maxConcurrent = normalizeConcurrency(maxConcurrent);
+ }
+
+ run<T>(
+ task: () => Promise<T>,
+ priority: 'foreground' | 'background' = 'background',
+ ): Promise<T> {
+ return new Promise<T>((resolve, reject) => {
+ const queued: HomeDeviceSyncTask<T> = { run: task, resolve, reject };
+ const queue = priority === 'foreground' ? this.foregroundQueue : this.backgroundQueue;
+ queue.push(queued as HomeDeviceSyncTask<unknown>);
+ this.drain();
+ });
+ }
+
+ private drain(): void {
+ while (this.active < this.maxConcurrent) {
+ const task = this.foregroundQueue.shift() ?? this.backgroundQueue.shift();
+ if (!task) return;
+ this.active += 1;
+ let promise: Promise<unknown>;
+ try {
+ promise = task.run();
+ } catch (error) {
+ this.active -= 1;
+ task.reject(error);
+ continue;
+ }
+ void promise.then(task.resolve, task.reject).finally(() => {
+ this.active -= 1;
+ this.drain();
+ });
+ }
+ }
+}
+
+/**
+ * 首页列表级同步范围:
+ * - “所有任务”同步全部当前可控制设备;
+ * - 单设备筛选只同步该设备;
+ * - 不可控制设备只保留设备清单 / presence,不发列表级请求。
+ */
+export function resolveHomeDeviceSyncIds(
+ devices: readonly HomeDeviceSyncCandidate[],
+ selectedDeviceId: string | null,
+): string[] {
+ const ids: string[] = [];
+ const seen = new Set<string>();
+ for (const device of devices) {
+ if (!device.canOpen || !device.deviceId || seen.has(device.deviceId)) continue;
+ if (selectedDeviceId && device.deviceId !== selectedDeviceId) continue;
+ seen.add(device.deviceId);
+ ids.push(device.deviceId);
+ }
+ return ids;
+}
+
+export interface HomeDeviceSyncScopeDiff {
+ acquire: string[];
+ release: string[];
+}
+
+/** Returns the owner changes needed to move an existing list subscription set to `desired`. */
+export function diffHomeDeviceSyncScope(
+ current: ReadonlySet<string>,
+ desired: readonly string[],
+): HomeDeviceSyncScopeDiff {
+ const desiredSet = new Set(desired);
+ return {
+ acquire: desired.filter((deviceId) => !current.has(deviceId)),
+ release: [...current].filter((deviceId) => !desiredSet.has(deviceId)),
+ };
+}
+
+/**
+ * Runs per-device home work with a shared, bounded worker pool while preserving result order.
+ * Peer failures remain values owned by the caller; one slow peer occupies only its own worker.
+ */
+export async function runHomeDeviceSyncBatch<T, R>(
+ items: readonly T[],
+ run: (item: T, index: number) => Promise<R>,
+ maxConcurrent: number = HOME_DEVICE_SYNC_CONCURRENCY,
+): Promise<R[]> {
+ if (items.length === 0) return [];
+ const normalizedMaxConcurrent = normalizeConcurrency(maxConcurrent);
+ const concurrency = Math.min(normalizedMaxConcurrent, items.length);
+ const results = new Array<R>(items.length);
+ let nextIndex = 0;
+ let firstError: unknown;
+ let failed = false;
+
+ await Promise.all(Array.from({ length: concurrency }, async () => {
+ while (nextIndex < items.length) {
+ const index = nextIndex;
+ nextIndex += 1;
+ try {
+ results[index] = await run(items[index], index);
+ } catch (error) {
+ // An unexpected caller error must not strand devices still queued behind this
+ // worker. Drain the batch, then preserve the original rejection semantics.
+ if (!failed) firstError = error;
+ failed = true;
+ }
+ }
+ }));
+ if (failed) throw firstError;
+ return results;
+}
+
+function normalizeConcurrency(value: number): number {
+ return Number.isFinite(value)
+ ? Math.max(1, Math.floor(value))
+ : HOME_DEVICE_SYNC_CONCURRENCY;
+}
diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.ts
index c619dde519..3d1f2f3d29 100644
--- a/apps/mobile/src/session/remoteSessionStore.ts
+++ b/apps/mobile/src/session/remoteSessionStore.ts
@@ -167,6 +167,21 @@ const EMPTY_SESSION_RUN_STATUS: RemoteSessionRunStatus = Object.freeze({
});
const shards = new Map<string, DeviceShard>();
+// Per-device list mutation fence. A sessions:list request may start before a live
+// sessions:created/patched push and settle after it; that older whole-list snapshot must
+// never overwrite the newer push. Epochs stay monotonic across account/store resets.
+const deviceSessionListMutationEpochs = new Map<string, number>();
+let deviceSessionListMutationEpochFloor = 0;
+let nextDeviceSessionListMutationEpoch = 0;
+
+function bumpDeviceSessionListMutationEpoch(deviceId: string): void {
+ if (!deviceId) return;
+ deviceSessionListMutationEpochs.set(deviceId, ++nextDeviceSessionListMutationEpoch);
+}
+
+function readDeviceSessionListMutationEpoch(deviceId: string): number {
+ return deviceSessionListMutationEpochs.get(deviceId) ?? deviceSessionListMutationEpochFloor;
+}
// 工作端拥有的 New Maker worktree 偏好按设备隔离;这里只是不持久化的显示镜像,
// push 属 sessions topic,无 sessionId。唯一持久副本仍在被控端现有 Cindy 配置里。
const newMakerWorktreePreferences = new Map<string, RemoteNewMakerWorktreePreference>();
@@ -3491,6 +3506,14 @@ export const remoteSessionStore = {
return makerActivityEpoch;
},
+ captureDeviceSessionListMutationEpoch(deviceId: string): number {
+ return readDeviceSessionListMutationEpoch(deviceId);
+ },
+
+ isDeviceSessionListMutationEpochCurrent(deviceId: string, epoch: number): boolean {
+ return readDeviceSessionListMutationEpoch(deviceId) === epoch;
+ },
+
setActiveSessionSnapshots(
deviceId: string,
list: readonly unknown[],
@@ -3655,6 +3678,7 @@ export const remoteSessionStore = {
return;
}
if (channel === 'local-db:sessions:created') {
+ bumpDeviceSessionListMutationEpoch(deviceId);
reseedHandlers.get(deviceId)?.forEach((handler) => handler());
return;
}
@@ -3668,6 +3692,7 @@ export const remoteSessionStore = {
const sessionId = readString(payload, 'sessionId');
const patch = isRecord(payload.patch) ? payload.patch : null;
if (sessionId && patch) {
+ bumpDeviceSessionListMutationEpoch(deviceId);
// 遮蔽本机在途写的字段:旧写的无差别 push 回流不得滚回更新的乐观意图,
// 被遮字段的终态由对应写的对账 / 后续 push 收敛;全部被遮时跳过应用。
// localRow 供差异留痕判定:本笔 echo push(同值)不留痕,避免每次成功写
@@ -3815,11 +3840,13 @@ export const remoteSessionStore = {
const totalMoney = normalizeRemoteMoney(payload.totalMoney);
const totalCostUsd = readNumber(payload, 'totalCostUsd');
if (sessionId && totalMoney) {
+ bumpDeviceSessionListMutationEpoch(deviceId);
this.applySessionPatch(deviceId, sessionId, {
totalMoney,
...(totalMoney.currency === 'USD' ? { totalCostUsd: totalMoney.amount } : {}),
});
} else if (sessionId && totalCostUsd !== null && totalCostUsd >= 0) {
+ bumpDeviceSessionListMutationEpoch(deviceId);
this.applySessionPatch(deviceId, sessionId, { totalCostUsd });
}
return;
@@ -3829,6 +3856,7 @@ export const remoteSessionStore = {
const sessionId = readString(payload, 'sessionId');
const totalTokens = readNumber(payload, 'totalTokens');
if (sessionId && totalTokens !== null && totalTokens >= 0) {
+ bumpDeviceSessionListMutationEpoch(deviceId);
this.applySessionPatch(deviceId, sessionId, { totalTokenUsage: totalTokens });
}
return;
@@ -4317,6 +4345,7 @@ export const remoteSessionStore = {
},
removeDevice(deviceId: string): void {
+ bumpDeviceSessionListMutationEpoch(deviceId);
const hadShard = shards.delete(deviceId);
const hadWorktreePreference = newMakerWorktreePreferences.delete(deviceId);
const hadWorktreeBranchPreferences = newMakerWorktreeBranchPreferences.delete(deviceId);
@@ -4393,6 +4422,8 @@ export const remoteSessionStore = {
},
clear(): void {
+ deviceSessionListMutationEpochFloor = ++nextDeviceSessionListMutationEpoch;
+ deviceSessionListMutationEpochs.clear();
shards.clear();
newMakerWorktreePreferences.clear();
newMakerWorktreeBranchPreferences.clear();
diff --git a/apps/mobile/src/session/scheduleIndex.ts b/apps/mobile/src/session/scheduleIndex.ts
index b0fcc077be..11593280e5 100644
--- a/apps/mobile/src/session/scheduleIndex.ts
+++ b/apps/mobile/src/session/scheduleIndex.ts
@@ -183,7 +183,8 @@ export function loadSessionScheduleIndexThrottled(
* 在链路恢复后立即失效——否则 30s 失败 TTL 内重连触发的 reseed 会吃到旧的
* rejected promise,设备详情页把索引替换成空集、首页保留陈旧数据,且没有任何
* 定时器在 TTL 过期后补拉。由 DeviceLinkContext 在每轮 rehydrate(只在 online
- * 时运行,重连必经)开始时调用;熔断类负缓存不受影响(走各自的恢复旁路)。
+ * 时运行,重连必经)的共享生命周期入口调用;单 peer 恢复使用下方逐设备版本,
+ * 熔断类负缓存不受影响(走各自的恢复旁路)。
*/
export function invalidateTransientScheduleIndexFailures(): void {
for (const [key, entry] of scheduleIndexThrottleEntries) {
@@ -193,6 +194,14 @@ export function invalidateTransientScheduleIndexFailures(): void {
}
}
+/** Per-peer variant used by independent Mobile recovery lifecycles. */
+export function invalidateTransientScheduleIndexFailureFor(deviceId: string): void {
+ const entry = scheduleIndexThrottleEntries.get(deviceId);
+ if (entry?.failedAt !== null && entry?.failedTransient) {
+ scheduleIndexThrottleEntries.delete(deviceId);
+ }
+}
+
/**
* 逐设备失效钩子(review P1):DEVICE_OFFLINE 的负缓存只在该设备 presence
* 恢复时清除(DeviceLinkContext 的 presence.recovered 分支调用,key 即
diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.ts
index 909f885324..17514bf94b 100644
--- a/packages/device-link/src/__tests__/client.test.ts
+++ b/packages/device-link/src/__tests__/client.test.ts
@@ -81,6 +81,7 @@ function makeHarness(opts?: {
token?: string | null;
timing?: ConstructorParameters<typeof DeviceLinkClient>[0]['timing'];
logger?: ConstructorParameters<typeof DeviceLinkClient>[0]['logger'];
+ peerFailurePolicy?: ConstructorParameters<typeof DeviceLinkClient>[0]['peerFailurePolicy'];
}): Harness {
const sockets: FakeWs[] = [];
const client = new DeviceLinkClient({
@@ -99,6 +100,7 @@ function makeHarness(opts?: {
sockets.push(ws);
return ws;
},
+ peerFailurePolicy: opts?.peerFailurePolicy,
timing: {
reconnectBaseMs: 5,
reconnectMaxMs: 40,
@@ -779,6 +781,246 @@ describe('DeviceLinkClient', () => {
h.client.stop();
});
+ it('Mobile opt-in:出站 peer ACK 超时只复位该 peer,旧 Desktop 可用既有 link-open 恢复且邻居零感知', async () => {
+ const h = makeHarness({
+ peerFailurePolicy: 'isolate-peer',
+ timing: {
+ pingIntervalMs: 60_000,
+ requestTimeoutMs: 60_000,
+ transportRetryIntervalMs: 5,
+ transportMaxRetryAttempts: 2,
+ },
+ });
+ const resets: Array<{
+ deviceId: string;
+ reason: 'ack-timeout';
+ connectionEpoch: number;
+ linkGeneration: number;
+ seq: number;
+ }> = [];
+ h.client.onPeerTransportReset((change) => resets.push(change));
+ h.client.start();
+ await tick();
+ h.current().ack();
+
+ const establishOutbound = async (deviceId: string, remoteStreamId: string): Promise<void> => {
+ const opening = h.client.openLink(deviceId, {
+ controllerName: 'Mobile',
+ protocolVersion: 1,
+ appVersion: '1',
+ }, 1_000);
+ const openFrame = h.current().sent
+ .filter((env) => env.kind === 'link-open' && env.dst === deviceId)
+ .at(-1)!;
+ h.current().push({
+ v: PROTOCOL_VERSION,
+ kind: 'link-accept',
+ id: openFrame.id,
+ src: deviceId,
+ payload: {
+ appVersion: 'old-desktop',
+ allowlistHash: 'hash',
+ // 旧 Desktop 只理解既有 reliable transport,不声明
+ // transport-timeout-close-v1;Mobile 仍不得靠新 wire 值恢复。
+ capabilities: [DEVICE_LINK_CAPABILITY_RELIABLE_TRANSPORT],
+ transportStreamId: remoteStreamId,
+ transportBaseSeq: 1,
+ },
+ });
+ await opening;
+ };
+
+ await establishOutbound('peer-broken', 'old-desktop-broken-stream');
+ await establishOutbound('peer-healthy', 'old-desktop-healthy-stream');
+ const socket = h.current();
+ const socketCount = h.sockets.length;
+
+ const brokenRequest = h.client.invoke(
+ 'peer-broken',
+ { channel: 'local-db:sessions:list', args: [10] },
+ 60_000,
+ );
+ // 防测试失败提前退出时产生未处理 rejection;正常路径在下方以真实结果收口。
+ void brokenRequest.catch(() => {});
+ const brokenFrame = socket.sent
+ .filter((env) => env.kind === 'invoke' && env.dst === 'peer-broken')
+ .at(-1)!;
+ const brokenMeta = parseTransportPayload(brokenFrame.payload)!.meta;
+
+ const healthyRequest = h.client.invoke(
+ 'peer-healthy',
+ { channel: 'local-db:sessions:list', args: [10] },
+ 60_000,
+ );
+ const healthyFrame = socket.sent
+ .filter((env) => env.kind === 'invoke' && env.dst === 'peer-healthy')
+ .at(-1)!;
+ const healthyMeta = parseTransportPayload(healthyFrame.payload)!.meta;
+ socket.push({
+ v: PROTOCOL_VERSION,
+ kind: 'push',
+ src: 'peer-healthy',
+ payload: {
+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,
+ payload: {
+ streamId: healthyMeta.streamId,
+ ackSeq: healthyMeta.seq,
+ },
+ },
+ });
+ socket.push({
+ v: PROTOCOL_VERSION,
+ kind: 'invoke-result',
+ id: healthyFrame.id,
+ src: 'peer-healthy',
+ payload: { ok: true, result: ['healthy'] },
+ });
+ await expect(healthyRequest).resolves.toMatchObject({ ok: true, result: ['healthy'] });
+
+ // broken peer 永不 ACK;达到预算后只产生本地 peer reset 事件。
+ await vi.waitFor(() => expect(resets).toHaveLength(1));
+ expect(resets[0]).toMatchObject({
+ deviceId: 'peer-broken',
+ reason: 'ack-timeout',
+ connectionEpoch: h.client.getConnectionEpoch(),
+ linkGeneration: expect.any(Number),
+ seq: brokenMeta.seq,
+ });
+ expect(h.client.isLinkReady('peer-broken')).toBe(false);
+ expect(h.client.isLinkReady('peer-healthy')).toBe(true);
+ expect(socket.terminated).toBe(false);
+ expect(socket.closed).toBeNull();
+ expect(h.sockets).toHaveLength(socketCount);
+ expect(socket.sent.some((env) => (
+ env.kind === 'link-close'
+ && env.dst === 'peer-broken'
+ ))).toBe(false);
+
+ // host 用旧版本也支持的 link-open 重建同一 peer;共享 socket 与邻居不动。
+ const sentBeforeReopen = socket.sent.length;
+ await establishOutbound('peer-broken', 'old-desktop-broken-stream');
+ expect(h.client.isLinkReady('peer-broken')).toBe(true);
+ expect(h.client.isLinkReady('peer-healthy')).toBe(true);
+ expect(h.sockets).toHaveLength(socketCount);
+
+ const replay = socket.sent.slice(sentBeforeReopen).find((env) => (
+ env.kind === 'invoke'
+ && env.dst === 'peer-broken'
+ && parseTransportPayload(env.payload)?.meta.seq === brokenMeta.seq
+ ));
+ expect(replay).toBeDefined();
+ socket.push({
+ v: PROTOCOL_VERSION,
+ kind: 'push',
+ src: 'peer-broken',
+ payload: {
+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,
+ payload: {
+ streamId: brokenMeta.streamId,
+ ackSeq: brokenMeta.seq,
+ },
+ },
+ });
+ socket.push({
+ v: PROTOCOL_VERSION,
+ kind: 'invoke-result',
+ id: brokenFrame.id,
+ src: 'peer-broken',
+ payload: { ok: true, result: ['recovered'] },
+ });
+ await expect(brokenRequest).resolves.toMatchObject({ ok: true, result: ['recovered'] });
+ h.client.stop();
+ });
+
+ it('≥2 控制端共享同一被控端:一个停止 ACK 只复位该 peer,邻居 link 与在途请求零感知', async () => {
+ // 故障半径要求的拓扑是「多个控制端共用一台被控桌面」,不是「一个控制端连两台桌面」。
+ // 本用例站在被控 Desktop:ctrl-silent 永不 ACK,ctrl-healthy 的在途 invoke 必须仍能完成,
+ // 且共享 WSS 不得被拆掉。
+ const h = makeHarness({
+ timing: {
+ pingIntervalMs: 60_000,
+ requestTimeoutMs: 60_000,
+ transportRetryIntervalMs: 5,
+ transportMaxRetryAttempts: 2,
+ },
+ });
+ const inboundInvokes: Envelope[] = [];
+ h.client.onFrame((env) => {
+ if (env.kind === 'invoke' && env.src === 'ctrl-healthy') inboundInvokes.push(env);
+ });
+ h.client.start();
+ await tick();
+ h.current().ack();
+
+ await establishInboundReliableLink(h, 'silent-controller-stream', 1, 'ctrl-silent');
+ await establishInboundReliableLink(h, 'healthy-controller-stream', 1, 'ctrl-healthy');
+ const socket = h.current();
+ const socketCount = h.sockets.length;
+
+ h.client.sendInvokeResult('ctrl-silent', 'silent-req', { ok: true, result: ['silent'] });
+ h.client.sendInvokeResult('ctrl-healthy', 'healthy-inflight', { ok: true, result: ['healthy'] });
+ const healthyFrame = socket.sent
+ .filter((env) => env.kind === 'invoke-result' && env.dst === 'ctrl-healthy')
+ .at(-1)!;
+ const healthyMeta = parseTransportPayload(healthyFrame.payload)!.meta;
+ socket.push({
+ v: PROTOCOL_VERSION,
+ kind: 'push',
+ src: 'ctrl-healthy',
+ payload: {
+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,
+ payload: {
+ streamId: healthyMeta.streamId,
+ ackSeq: healthyMeta.seq,
+ },
+ },
+ });
+
+ socket.push(encodeReliableFrames({
+ v: PROTOCOL_VERSION,
+ kind: 'invoke',
+ id: 'healthy-followup',
+ src: 'ctrl-healthy',
+ payload: { channel: 'local-db:sessions:list', args: [10] },
+ }, 'healthy-controller-stream', 1)[0]);
+ await tick();
+ expect(inboundInvokes).toHaveLength(1);
+
+ await vi.waitFor(() => {
+ expect(socket.sent.some((env) => (
+ env.kind === 'link-close'
+ && env.dst === 'ctrl-silent'
+ && (env.payload as { reason?: string } | undefined)?.reason === 'transport-timeout'
+ ))).toBe(true);
+ });
+ expect(h.client.isLinkReady('ctrl-silent')).toBe(false);
+ expect(h.client.isLinkReady('ctrl-healthy')).toBe(true);
+ expect(socket.terminated).toBe(false);
+ expect(socket.closed).toBeNull();
+ expect(h.sockets).toHaveLength(socketCount);
+
+ h.client.sendInvokeResult('ctrl-healthy', 'healthy-followup', { ok: true, result: ['followup'] });
+ const followupFrame = socket.sent
+ .filter((env) => env.kind === 'invoke-result' && env.id === 'healthy-followup')
+ .at(-1)!;
+ const followupMeta = parseTransportPayload(followupFrame.payload)!.meta;
+ socket.push({
+ v: PROTOCOL_VERSION,
+ kind: 'push',
+ src: 'ctrl-healthy',
+ payload: {
+ channel: DEVICE_LINK_TRANSPORT_ACK_CHANNEL,
+ payload: {
+ streamId: followupMeta.streamId,
+ ackSeq: followupMeta.seq,
+ },
+ },
+ });
+ expect(h.client.isLinkReady('ctrl-healthy')).toBe(true);
+ expect(h.client.getReliableSendQueueDepth('ctrl-healthy')).toBe(0);
+ h.client.stop();
+ });
+
it('入站 link 的可靠重试耗尽只重置该 peer link:relay 连接不拆,发 transport-timeout link-close,重开后 live 帧按原 seq 重放', async () => {
const warn = vi.fn();
const h = makeHarness({
diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.ts
index 9f4bc8d1bb..e823eb9cbf 100644
--- a/packages/device-link/src/client.ts
+++ b/packages/device-link/src/client.ts
@@ -195,10 +195,24 @@ export interface DeviceLinkClientOptions {
getHello(): HelloPayload;
createWebSocket: WsFactory;
logger?: DeviceLinkLogger;
+ /**
+ * 可靠传输对单个 peer 重试耗尽后的故障半径。
+ *
+ * - `legacy`(默认):保留既有兼容行为。无法通过已协商的
+ * `transport-timeout` 瞬时重置 peer 时,重建整条 relay 连接。
+ * - `isolate-peer`:只复位该 peer 并通过 `onPeerTransportReset` 通知 host
+ * 使用既有 `link-open` 恢复;不关闭共享 WSS,也不发送旧对端不理解的新
+ * wire 值。仅适合能独立重开每个出站 peer 的纯控制端(当前为 Mobile)。
+ *
+ * 这是 additive、host opt-in 的本地策略;Desktop 不传时行为完全不变。
+ */
+ peerFailurePolicy?: DeviceLinkPeerFailurePolicy;
/** 测试注入:覆盖重连/心跳的时间参数 */
timing?: Partial<DeviceLinkTiming>;
}
+export type DeviceLinkPeerFailurePolicy = 'legacy' | 'isolate-peer';
+
export interface DeviceLinkTiming {
reconnectBaseMs: number;
reconnectMaxMs: number;
@@ -397,6 +411,20 @@ export interface DeviceLinkPeerRouteStateChanged {
linkGeneration: number;
}
+/**
+ * 单个 peer 的可靠传输已在本地复位,需要 host 独立重建该 peer。
+ *
+ * 该事件不是 relay/WSS 断线信号;其它 peer 必须继续收发。代次字段供 host
+ * 丢弃排队期间已经过期的恢复任务。`seq` 只用于诊断,不代表业务请求 id。
+ */
+export interface DeviceLinkPeerTransportReset {
+ deviceId: string;
+ reason: 'ack-timeout';
+ connectionEpoch: number;
+ linkGeneration: number;
+ seq: number;
+}
+
/**
* 从断连信息分类连接问题。返回 null = 普通断线(网络抖动 / 服务重启 / 4401 token
* 轮换),按既有退避重连兜底即可,不打扰用户。
@@ -646,6 +674,9 @@ export class DeviceLinkClient {
private peerRouteStateHandlers = new Set<
(change: DeviceLinkPeerRouteStateChanged) => void
>();
+ private peerTransportResetHandlers = new Set<
+ (change: DeviceLinkPeerTransportReset) => void
+ >();
/** Avoid emitting the same authoritative route failure once per queued frame. */
private peerOfflineNotifiedGeneration = new Map<
string,
@@ -902,6 +933,14 @@ export class DeviceLinkClient {
return () => this.peerRouteStateHandlers.delete(cb);
}
+ /** 订阅单 peer 可靠传输复位;host 应只重建 `change.deviceId`。 */
+ onPeerTransportReset(
+ cb: (change: DeviceLinkPeerTransportReset) => void,
+ ): () => void {
+ this.peerTransportResetHandlers.add(cb);
+ return () => this.peerTransportResetHandlers.delete(cb);
+ }
+
getConnectionIssue(): DeviceLinkConnectionIssue | null {
return this.connectionIssue;
}
@@ -945,6 +984,28 @@ export class DeviceLinkClient {
}
}
+ private notifyPeerTransportReset(
+ deviceId: string,
+ seq: number,
+ linkGeneration: number,
+ ): void {
+ if (this.peerTransportResetHandlers.size === 0) return;
+ const change: DeviceLinkPeerTransportReset = {
+ deviceId,
+ reason: 'ack-timeout',
+ connectionEpoch: this.connEpoch,
+ linkGeneration,
+ seq,
+ };
+ for (const cb of this.peerTransportResetHandlers) {
+ try {
+ cb(change);
+ } catch (err) {
+ this.log.error('device-link peer transport reset handler failed', err);
+ }
+ }
+ }
+
private markPeerRouteOnline(deviceId: string, linkGeneration?: number): number {
const peer = this.getPeerTransport(deviceId);
peer.linkGeneration = linkGeneration ?? peer.linkGeneration + 1;
@@ -3731,16 +3792,29 @@ export class DeviceLinkClient {
* dispatchEnvelope 的 link-close 分支),并由 app 层立即重建:mobile
* 触发 rehydrate,desktop 控制端重新 openLink;真休眠的对端收不到
* 该帧,唤醒后自会 rehydrate → link-open。
- * - 出站发起的 link(本机是控制端,单 peer):维持原语义——整连接重连兼作
- * 恢复探测,与 mobile 现有 rehydrate/熔断流程耦合,不在此改变。
+ * - 出站发起的 link(本机是控制端):默认维持原语义——整连接重连兼作恢复
+ * 探测;Mobile 可显式选择 `peerFailurePolicy='isolate-peer'`,改为只复位
+ * 该 peer 并通知 host 独立 openLink。该路径不发任何新 wire 值,所以目标
+ * Desktop 无需同步升级。
*/
private handleReliableRetryExhausted(dst: string, seq: number): void {
if (this.stopped || this.status !== 'online') return;
const peer = this.peerTransport.get(dst);
+ // retry callback 与显式 close/stop 竞态时 peer 可能已经被回收。Mobile 的
+ // 隔离策略不能把迟到计时器升级成连接级重建;默认策略仍保留历史语义。
+ if (!peer) {
+ if (this.opts.peerFailurePolicy !== 'isolate-peer') {
+ this.forceReconnectForReliableTimeout(dst, seq);
+ }
+ return;
+ }
// 能力门:旧控制端(未声明 transport-timeout-close-v1)把未知 reason 当永久
// 关闭且不会自动重开——relay/presence 保持在线时订阅与在途请求会静默挂死。
// 对这类对端保留整连接重连的兼容恢复路径(presence 闪断触发其既有 rehydrate)。
- if (!peer?.linkAcceptedInbound || !peer.supportsTransportTimeoutClose) {
+ if (
+ (!peer.linkAcceptedInbound || !peer.supportsTransportTimeoutClose)
+ && this.opts.peerFailurePolicy !== 'isolate-peer'
+ ) {
this.forceReconnectForReliableTimeout(dst, seq);
return;
}
@@ -3753,7 +3827,14 @@ export class DeviceLinkClient {
clearInterval(peer.retryTimer);
peer.retryTimer = null;
}
- this.notifyTransportTimeoutClose(dst, 1);
+ // 已协商瞬时关闭语义的入站控制方向仍通知对端主动重开。Mobile 的纯出站
+ // 隔离路径不发送 transport-timeout:旧 Desktop 可能把未知 reason 当永久
+ // 关闭;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);
+ }
}
/**