Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(mobile): 合并离线镜像通知并保留排队阶段重连保护 (#5239)

DavidShenXD4485dbc62747
diff --git a/apps/mobile/src/__tests__/offlineMirrorSubscriptions.test.tsx b/apps/mobile/src/__tests__/offlineMirrorSubscriptions.test.tsx
new file mode 100644
index 0000000000..ea1def051d
--- /dev/null
+++ b/apps/mobile/src/__tests__/offlineMirrorSubscriptions.test.tsx
@@ -0,0 +1,58 @@
+// @vitest-environment jsdom
+import { act, createElement, useEffect, useState } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { createOfflineMirrorWipeQueue } from '@/device-link/offlineMirrorWipeQueue';
+import { schedulePresenceWipeTimer, type PresenceWipeTimerEntry } from '@/device-link/presenceRecovery';
+import { remoteScheduleEventStore, useRemoteScheduleMirrorInvalidations } from '@/scheduler/remoteScheduleEvents';
+
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+let root: Root | undefined;
+beforeEach(() => { vi.useFakeTimers(); remoteScheduleEventStore.clearAll(); });
+afterEach(() => { act(() => root?.unmount()); root = undefined; vi.useRealTimers(); });
+
+it.each([1, 60, 100])('settles mounted mirror consumers after %i separately delivered presence timers', async (count) => {
+ const render = vi.fn();
+ function Consumer() {
+ const invalidations = useRemoteScheduleMirrorInvalidations();
+ const [offline, setOffline] = useState<ReadonlyMap<string, number>>(new Map());
+ useEffect(() => { setOffline(invalidations); }, [invalidations]);
+ render();
+ return createElement('span', null, offline.size);
+ }
+ const container = document.createElement('div');
+ root = createRoot(container);
+ act(() => root!.render(createElement(Consumer)));
+ render.mockClear();
+ const notify = vi.fn();
+ const off = remoteScheduleEventStore.subscribe(notify);
+ const queue = createOfflineMirrorWipeQueue(ids => remoteScheduleEventStore.invalidateDeviceMirrors(ids));
+ const timers = new Map<string, PresenceWipeTimerEntry>();
+ const availability = new Map<string, boolean>();
+ try {
+ for (let i = 0; i < count; i++) {
+ const id = `device-${i}`;
+ availability.set(id, false);
+ schedulePresenceWipeTimer(timers, availability, id, 5_000 + i % 10, {
+ now: Date.now, setTimer: setTimeout, clearTimer: clearTimeout, wipe: queue.enqueue,
+ deferWipe: queue.enqueue,
+ });
+ }
+ await act(async () => { await vi.advanceTimersByTimeAsync(5_016); });
+ expect(notify).toHaveBeenCalledTimes(1);
+ expect(container.textContent).toBe(String(count));
+ expect(render.mock.calls.length).toBeLessThanOrEqual(3);
+ const settledRenders = render.mock.calls.length;
+ await act(async () => {
+ for (let i = 0; i < 100; i++) {
+ remoteScheduleEventStore.invalidateDeviceMirrors([...availability.keys()]);
+ await Promise.resolve();
+ }
+ });
+ expect(notify).toHaveBeenCalledTimes(1);
+ expect(render).toHaveBeenCalledTimes(settledRenders);
+ await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });
+ expect(render).toHaveBeenCalledTimes(settledRenders);
+ expect(timers.size).toBe(0);
+ } finally { off(); queue.clear(); }
+});
diff --git a/apps/mobile/src/__tests__/offlineMirrorWipeQueue.test.ts b/apps/mobile/src/__tests__/offlineMirrorWipeQueue.test.ts
index f8784468ef..631fc4c0ce 100644
--- a/apps/mobile/src/__tests__/offlineMirrorWipeQueue.test.ts
+++ b/apps/mobile/src/__tests__/offlineMirrorWipeQueue.test.ts
@@ -1,50 +1,150 @@
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createOfflineMirrorWipeQueue } from '@/device-link/offlineMirrorWipeQueue';
+import {
+ clearPresenceWipeTimer,
+ extendPresenceWipeTimerFloor,
+ resetPresenceAvailabilityForConnection,
+ schedulePresenceWipeTimer,
+ type PresenceWipeTimerEntry,
+} from '@/device-link/presenceRecovery';
describe('offline mirror wipe queue', () => {
- it('coalesces one wave of wipes into a single flush', async () => {
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => vi.useRealTimers());
+
+ function protectedQueue() {
const flush = vi.fn();
const queue = createOfflineMirrorWipeQueue(flush);
- for (let i = 0; i < 80; i += 1) queue.enqueue(`dev-${i}`);
+ const timers = new Map<string, PresenceWipeTimerEntry>();
+ const availability = new Map<string, boolean>();
+ const confirming = new Set<string>();
+ const deps = {
+ now: Date.now, setTimer: setTimeout, clearTimer: clearTimeout,
+ wipe: queue.enqueue, deferWipe: queue.enqueue,
+ isConfirmationInFlight: (id: string) => confirming.has(id),
+ };
+ const offline = (id: string) => {
+ availability.set(id, false);
+ schedulePresenceWipeTimer(timers, availability, id, 5_000, deps);
+ };
+ return { flush, queue, timers, availability, confirming, deps, offline };
+ }
- // 同一 task 内的整波入队:只预约一次 flush,且在微任务里执行。
- expect(queue.pendingCount()).toBe(80);
+ it('extends a queued wipe on reconnect without delaying another offline peer', async () => {
+ const { flush, queue, timers, availability, deps, offline } = protectedQueue();
+ offline('reconnecting');
+ // This peer expires in the same batch, after the reconnect reset.
+ await vi.advanceTimersByTimeAsync(5);
+ offline('offline');
+ await vi.advanceTimersByTimeAsync(4_996);
+ expect(queue.pendingCount()).toBe(1);
+ expect(timers.has('reconnecting')).toBe(true);
+ resetPresenceAvailabilityForConnection(availability, new Set());
+ extendPresenceWipeTimerFloor(timers, availability, 'reconnecting', 3_000, deps);
+ await vi.advanceTimersByTimeAsync(15);
+ expect(flush.mock.calls).toEqual([[['offline']]]);
+ await vi.advanceTimersByTimeAsync(2_985);
+ expect(queue.pendingCount()).toBe(1);
+ expect(flush).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(16);
+ expect(flush.mock.calls).toEqual([[['offline']], [['reconnecting']]]);
+ expect(timers.size).toBe(0);
+ });
+
+ it('defers a queued wipe when link confirmation starts before the batch executes', async () => {
+ const { flush, timers, confirming, offline } = protectedQueue();
+ offline('peer');
+ await vi.advanceTimersByTimeAsync(5_001);
+ confirming.add('peer');
+ await vi.advanceTimersByTimeAsync(15);
+ expect(flush).not.toHaveBeenCalled();
+ expect(timers.has('peer')).toBe(true);
+ await vi.advanceTimersByTimeAsync(1_000);
expect(flush).not.toHaveBeenCalled();
+ confirming.delete('peer');
+ await vi.advanceTimersByTimeAsync(1_016);
+ expect(flush.mock.calls).toEqual([[['peer']]]);
+ expect(timers.size).toBe(0);
+ });
+
+ it.each(['cancel', 'available'] as const)('rejects queued work after %s without losing another peer', async (recovery) => {
+ const { flush, timers, availability, offline } = protectedQueue();
+ offline('recovered');
+ offline('offline');
+ await vi.advanceTimersByTimeAsync(5_001);
+ if (recovery === 'cancel') clearPresenceWipeTimer(timers, 'recovered', clearTimeout);
+ else availability.set('recovered', true);
+ await vi.advanceTimersByTimeAsync(15);
+ expect(flush.mock.calls).toEqual([[['offline']]]);
+ expect(timers.size).toBe(0);
+ });
- await Promise.resolve();
+ it.each([1, 60, 80, 100])('coalesces %i timer callbacks even when microtasks drain between them', async (count) => {
+ const flush = vi.fn();
+ const queue = createOfflineMirrorWipeQueue(flush);
+ for (let i = 0; i < count; i++) {
+ setTimeout(() => queue.enqueue('dev-' + i), 5_000 + i % 10);
+ }
+ // Async advancement drains microtasks between timers, as RN may do.
+ await vi.advanceTimersByTimeAsync(5_010);
+ expect(flush).not.toHaveBeenCalled();
+ expect(queue.pendingCount()).toBe(count);
+ await vi.advanceTimersByTimeAsync(6);
expect(flush).toHaveBeenCalledTimes(1);
- expect(flush.mock.calls[0][0]).toHaveLength(80);
- expect(flush.mock.calls[0][0]).toEqual(
- expect.arrayContaining(['dev-0', 'dev-40', 'dev-79']),
- );
+ expect(new Set(flush.mock.calls[0][0])).toEqual(new Set(Array.from({ length: count }, (_, i) => 'dev-' + i)));
expect(queue.pendingCount()).toBe(0);
});
- it('flushes later tasks separately and dedupes ids within a wave', async () => {
+ it('dedupes ids without postponing the deadline and permits later waves', async () => {
const flush = vi.fn();
const queue = createOfflineMirrorWipeQueue(flush);
+ queue.enqueue('a');
+ await vi.advanceTimersByTimeAsync(15);
+ queue.enqueue('a');
+ queue.enqueue('b');
+ await vi.advanceTimersByTimeAsync(1);
+ expect(flush.mock.calls).toEqual([[['a', 'b']]]);
+ queue.enqueue('a');
+ await vi.advanceTimersByTimeAsync(16);
+ expect(flush.mock.calls).toEqual([[['a', 'b']], [['a']]]);
+ });
- queue.enqueue('dev-a');
- queue.enqueue('dev-a');
- queue.enqueue('dev-b');
- await Promise.resolve();
- expect(flush).toHaveBeenCalledTimes(1);
- expect(flush.mock.calls[0][0]).toEqual(['dev-a', 'dev-b']);
+ it('cancels recovered peers without discarding other offline peers', async () => {
+ const flush = vi.fn();
+ const queue = createOfflineMirrorWipeQueue(flush);
+ queue.enqueue('recovered');
+ queue.enqueue('offline');
+ queue.cancel('recovered');
+ await vi.advanceTimersByTimeAsync(16);
+ expect(flush.mock.calls).toEqual([[['offline']]]);
+ });
- // 后续 task 的 wipe 单独 flush,不与上一波合并(离线清理语义不变)。
- queue.enqueue('dev-c');
- await Promise.resolve();
- expect(flush).toHaveBeenCalledTimes(2);
- expect(flush.mock.calls[1][0]).toEqual(['dev-c']);
+ it('retires queued work on teardown without draining a replacement wave', () => {
+ const callbacks: Array<() => void> = [];
+ const cancel = vi.fn();
+ const flush = vi.fn();
+ const queue = createOfflineMirrorWipeQueue(flush, cb => { callbacks.push(cb); return cancel; });
+ queue.enqueue('old-owner');
+ queue.clear();
+ expect(cancel).toHaveBeenCalledTimes(1);
+ queue.enqueue('new-owner');
+ callbacks[0]();
+ expect(flush).not.toHaveBeenCalled();
+ expect(queue.pendingCount()).toBe(1);
+ callbacks[1]();
+ expect(flush.mock.calls).toEqual([[['new-owner']]]);
});
- it('ignores empty device ids', async () => {
+ it('ignores empty ids and cancels the timer after the last peer recovers', async () => {
const flush = vi.fn();
const queue = createOfflineMirrorWipeQueue(flush);
-
queue.enqueue('');
+ expect(vi.getTimerCount()).toBe(0);
+ queue.enqueue('a');
+ queue.cancel('a');
expect(queue.pendingCount()).toBe(0);
- await Promise.resolve();
+ expect(vi.getTimerCount()).toBe(0);
+ await vi.runAllTimersAsync();
expect(flush).not.toHaveBeenCalled();
});
});
diff --git a/apps/mobile/src/__tests__/remoteScheduleEvents.test.ts b/apps/mobile/src/__tests__/remoteScheduleEvents.test.ts
index 8a402c811d..6bd7b7bfad 100644
--- a/apps/mobile/src/__tests__/remoteScheduleEvents.test.ts
+++ b/apps/mobile/src/__tests__/remoteScheduleEvents.test.ts
@@ -79,15 +79,14 @@ describe('remote schedule event store', () => {
const afterFirst = remoteScheduleEventStore.getMirrorInvalidationSnapshot();
expect(afterFirst).not.toBe(before);
- expect(afterFirst.get('dev-1')).toBe(1);
+ expect(afterFirst.get('dev-1')).toBeGreaterThan(0);
expect(remoteScheduleEventStore.getVersion('dev-1')).toBe(0);
expect(sub).toHaveBeenCalledTimes(1);
remoteScheduleEventStore.invalidateDeviceMirror('dev-1');
const afterSecond = remoteScheduleEventStore.getMirrorInvalidationSnapshot();
- expect(afterSecond).not.toBe(afterFirst);
- expect(afterSecond.get('dev-1')).toBe(2);
- expect(sub).toHaveBeenCalledTimes(2);
+ expect(afterSecond).toBe(afterFirst);
+ expect(sub).toHaveBeenCalledTimes(1);
off();
});
@@ -104,16 +103,41 @@ describe('remote schedule event store', () => {
expect(sub).toHaveBeenCalledTimes(1);
const snapshot = remoteScheduleEventStore.getMirrorInvalidationSnapshot();
expect(snapshot.size).toBe(count);
- for (const deviceId of deviceIds) expect(snapshot.get(deviceId)).toBe(1);
+ for (const deviceId of deviceIds) expect(snapshot.get(deviceId)).toBeGreaterThan(0);
- // 合并只在单波内:另起一波(第二次批量失效)各自再 notify 一轮。
+ // Repeated offline verdicts without fresh data are not new transitions.
remoteScheduleEventStore.invalidateDeviceMirrors(deviceIds);
- expect(sub).toHaveBeenCalledTimes(2);
- expect(remoteScheduleEventStore.getMirrorInvalidationSnapshot().get('wave-dev-0')).toBe(2);
+ expect(sub).toHaveBeenCalledTimes(1);
+ expect(remoteScheduleEventStore.getMirrorInvalidationSnapshot()).toBe(snapshot);
off();
});
+ it('re-arms after a fresh event or recovery, with monotonic generations', () => {
+ remoteScheduleEventStore.invalidateDeviceMirrors(['a', 'a', '', 'b']);
+ const first = remoteScheduleEventStore.getMirrorInvalidationSnapshot();
+ const notify = vi.fn();
+ const off = remoteScheduleEventStore.subscribe(notify);
+ try {
+ for (let i = 0; i < 100; i++) remoteScheduleEventStore.invalidateDeviceMirrors(['a', 'b']);
+ expect(notify).not.toHaveBeenCalled();
+ expect(remoteScheduleEventStore.getMirrorInvalidationSnapshot()).toBe(first);
+ remoteScheduleEventStore.apply('a', { type: 'ready' });
+ remoteScheduleEventStore.invalidateDeviceMirrors(['a', 'b']);
+ const second = remoteScheduleEventStore.getMirrorInvalidationSnapshot();
+ expect(second.get('a')).toBeGreaterThan(first.get('a')!);
+ expect(second.get('b')).toBe(first.get('b'));
+ expect(remoteScheduleEventStore.getVersion('a')).toBe(0);
+ expect(notify).toHaveBeenCalledTimes(2);
+ remoteScheduleEventStore.clearDeviceMirrorInvalidation('a');
+ remoteScheduleEventStore.invalidateDeviceMirror('a');
+ expect(remoteScheduleEventStore.getMirrorInvalidationSnapshot().get('a')).toBeGreaterThan(second.get('a')!);
+ expect(notify).toHaveBeenCalledTimes(4);
+ remoteScheduleEventStore.clearDevice('a');
+ expect(remoteScheduleEventStore.getMirrorInvalidationSnapshot().has('a')).toBe(true);
+ } finally { off(); }
+ });
+
it('projects run lifecycle and read events into targeted refresh versions', () => {
remoteScheduleEventStore.apply('dev-1', { type: 'fired', scheduleId: 'sched-1', runId: 'run-1' });
expect(remoteScheduleEventStore.getSnapshot('dev-1')).toMatchObject({
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index d80adaa0aa..52bedaa4bf 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -401,14 +401,25 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
const presenceWipeTimersRef = useRef(
new Map<string, PresenceWipeTimerEntry>(),
);
+ const [offlineMirrorWipeQueue] = useState(() => createOfflineMirrorWipeQueue(markOfflineDeviceMirrors));
+ const clearOnePresenceWipeTimer = useCallback((timers: Map<string, PresenceWipeTimerEntry>, deviceId: string) => {
+ clearPresenceWipeTimer(timers, deviceId, clearTimeout);
+ offlineMirrorWipeQueue.cancel(deviceId);
+ }, [offlineMirrorWipeQueue]);
+ const clearAllPresenceWipeTimers = useCallback((timers: Map<string, PresenceWipeTimerEntry>) => {
+ clearPresenceWipeTimers(timers, clearTimeout);
+ offlineMirrorWipeQueue.clear();
+ }, [offlineMirrorWipeQueue]);
const openLinkInFlightRef = useRef(
new Map<string, PresenceTrackedRequest<LinkAcceptPayload>>(),
);
const presenceWipeTimerDeps = useMemo(() => ({
...basePresenceWipeTimerDeps,
+ wipe: offlineMirrorWipeQueue.enqueue,
+ deferWipe: offlineMirrorWipeQueue.enqueue,
isConfirmationInFlight: (deviceId: string) =>
openLinkInFlightRef.current.get(deviceId)?.pending === true,
- }), []);
+ }), [offlineMirrorWipeQueue]);
const presenceAvailableByDeviceRef = useRef(new Map<string, boolean>());
const rosterConsumerRef = useRef<(() => (devices: DeviceView[]) => void) | null>(null);
const rosterRequestRef = useRef<{ client: DeviceLinkClient | null; epoch: number; promise: Promise<{ devices: DeviceView[] }> } | null>(null);
@@ -820,6 +831,8 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
};
}, [
probeUnresponsiveDevice,
+ clearOnePresenceWipeTimer,
+ presenceWipeTimerDeps,
hasOutboundPeerRecoveryIntent,
publishPresenceAvailabilityMutation,
sendOpenLinkOnce,
@@ -1139,6 +1152,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
const offFrame = client.onFrame((env) => routeFrame(env, {
currentDataOwnerId: currentDataOwnerIdRef.current,
onAccessRevoked: (deviceId) => {
+ clearOnePresenceWipeTimer(presenceWipeTimersRef.current, deviceId);
if (isSharedTaskPeer(deviceId)) setPresenceVersion((version) => version + 1);
catalogRefresh.cancel(deviceId);
remoteSubscribedTopicsRef.current.delete(deviceId);
@@ -1420,6 +1434,9 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
auth.getAccessToken,
auth.isAuthenticated,
clearPerAccountDeviceLinkState,
+ clearOnePresenceWipeTimer,
+ clearAllPresenceWipeTimers,
+ presenceWipeTimerDeps,
publishPresenceAvailabilityMutation,
rehydrateWithClient,
restorePendingReplyLinks,
@@ -2138,10 +2155,6 @@ function markOfflineDeviceMirrors(deviceIds: readonly string[]): void {
remoteScheduleEventStore.invalidateDeviceMirrors(deviceIds);
}
-function markOfflineDeviceMirror(deviceId: string): void {
- markOfflineDeviceMirrors([deviceId]);
-}
-
function wipeUnavailableDeviceMirror(deviceId: string): void {
evictTaskTagCatalog(deviceId);
resetRemoteProjectOrderPushFence(deviceId);
@@ -2159,23 +2172,18 @@ function wipeUnavailableDeviceMirror(deviceId: string): void {
evictComposerPaletteCacheForDevice(deviceId);
}
-// 离线 wipe 的通知合并:同一 task 内到期/调度的多台设备收拢成一次批量清理。
-// 逐台通知时设备数超过 React 嵌套更新上限即致命退出(2026-09-10 Android)。
-const offlineMirrorWipeQueue = createOfflineMirrorWipeQueue(markOfflineDeviceMirrors);
-
const basePresenceWipeTimerDeps = {
now: Date.now,
setTimer: (callback: () => void, delayMs: number) =>
setTimeout(callback, delayMs),
clearTimer: clearTimeout,
- wipe: offlineMirrorWipeQueue.enqueue,
};
function scheduleUnavailableDeviceMirrorWipe(
timers: Map<string, PresenceWipeTimerEntry>,
availabilityByDevice: ReadonlyMap<string, boolean>,
deviceId: string,
- deps: typeof basePresenceWipeTimerDeps,
+ deps: typeof basePresenceWipeTimerDeps & { wipe(deviceId: string): void },
): void {
schedulePresenceWipeTimer(
timers,
@@ -2186,19 +2194,6 @@ function scheduleUnavailableDeviceMirrorWipe(
);
}
-function clearOnePresenceWipeTimer(
- timers: Map<string, PresenceWipeTimerEntry>,
- deviceId: string,
-): void {
- clearPresenceWipeTimer(timers, deviceId, clearTimeout);
-}
-
-function clearAllPresenceWipeTimers(
- timers: Map<string, PresenceWipeTimerEntry>,
-): void {
- clearPresenceWipeTimers(timers, clearTimeout);
-}
-
function isDeviceLinkTopic(topic: string): boolean {
return topic === 'sessions' || topic.startsWith('session:');
}
diff --git a/apps/mobile/src/device-link/offlineMirrorWipeQueue.ts b/apps/mobile/src/device-link/offlineMirrorWipeQueue.ts
index e76477e07c..867ce77aed 100644
--- a/apps/mobile/src/device-link/offlineMirrorWipeQueue.ts
+++ b/apps/mobile/src/device-link/offlineMirrorWipeQueue.ts
@@ -1,39 +1,57 @@
/**
* 离线镜像清理的通知合并队列。
*
- * presence 整批离线时,每台设备各有一个 5s 宽限定时器;RN 的定时器队列会把同一
- * task 内到期的回调连续投递。若逐台执行清理并通知,每台各触发一轮 React 同步
- * 重渲染,设备数超过嵌套更新上限即致命退出(2026-09-10 Android 冷启动,40/80
- * 台隔离复现;同批处理仅 3 次渲染则正常)。这里把同一 task 内到期的设备收拢成
- * 一次 flush,由调用方一次性更新两个 store 并各 notify 一次。
+ * RN 可以在每个到期 timer 回调后清空微任务,queueMicrotask 因而无法合并
+ * 集中离线的设备。使用固定 16ms 窗口跨回调收拢,不随新设备入队延长等待。
+ * 恢复、撤权或 Provider 清理必须取消尚未执行的项,避免晚到的清理覆盖新状态。
*
* 只合并「通知」,不合并「清理」:flush 时每台设备的离线清理语义原样执行。
*/
export interface OfflineMirrorWipeQueue {
- enqueue(deviceId: string): void;
+ enqueue(deviceId: string, claim?: () => boolean): void;
+ cancel(deviceId: string): void;
+ clear(): void;
pendingCount(): number;
}
export function createOfflineMirrorWipeQueue(
flush: (deviceIds: string[]) => void,
- schedule: (callback: () => void) => void = (callback) => queueMicrotask(callback),
+ schedule: (callback: () => void) => () => void = (callback) => {
+ const timer = setTimeout(callback, 16);
+ return () => clearTimeout(timer);
+ },
): OfflineMirrorWipeQueue {
- let pending: Set<string> | null = null;
+ let pending: Map<string, (() => boolean) | undefined> | null = null;
+ let cancelFlush: (() => void) | null = null;
+ const clear = () => {
+ pending = null;
+ cancelFlush?.();
+ cancelFlush = null;
+ };
return {
- enqueue(deviceId: string): void {
+ enqueue(deviceId: string, claim?: () => boolean): void {
if (!deviceId) return;
if (pending === null) {
- // 首台:登记并预约 flush。同 task 内后续设备只入队,不再预约。
- pending = new Set([deviceId]);
- schedule(() => {
- const deviceIds = [...(pending ?? [])];
+ const wave = new Map([[deviceId, claim]]);
+ pending = wave;
+ cancelFlush = schedule(() => {
+ if (pending !== wave) return;
pending = null;
+ cancelFlush = null;
+ // Claim at execution time: reconnect may have extended or cancelled
+ // the original presence timer while this batch was waiting.
+ const deviceIds = [...wave].filter(([, claim]) => !claim || claim()).map(([id]) => id);
if (deviceIds.length > 0) flush(deviceIds);
});
return;
}
- pending.add(deviceId);
+ pending.set(deviceId, claim);
+ },
+ cancel(deviceId: string): void {
+ pending?.delete(deviceId);
+ if (pending?.size === 0) clear();
},
+ clear,
pendingCount(): number {
return pending?.size ?? 0;
},
diff --git a/apps/mobile/src/device-link/presenceRecovery.ts b/apps/mobile/src/device-link/presenceRecovery.ts
index 23452ab976..4f382d36f5 100644
--- a/apps/mobile/src/device-link/presenceRecovery.ts
+++ b/apps/mobile/src/device-link/presenceRecovery.ts
@@ -109,6 +109,8 @@ export interface PresenceWipeTimerDeps {
setTimer(callback: () => void, delayMs: number): ReturnType<typeof setTimeout>;
clearTimer(timer: ReturnType<typeof setTimeout>): void;
wipe(deviceId: string): void;
+ /** Deferred consumers must claim immediately before wiping, keeping recovery protection alive. */
+ deferWipe?(deviceId: string, claim: () => boolean): void;
isConfirmationInFlight?(deviceId: string): boolean;
}
@@ -204,10 +206,22 @@ function schedulePresenceWipeAt(
);
return;
}
- timers.delete(deviceId);
- if (shouldWipeUnavailableDeviceMirror(availabilityByDevice, deviceId)) {
- deps.wipe(deviceId);
- }
+ const claim = (): boolean => {
+ if (timers.get(deviceId) !== entry) return false;
+ if (deps.isConfirmationInFlight?.(deviceId)) {
+ schedulePresenceWipeAt(
+ timers, availabilityByDevice, deviceId, firstScheduledAt,
+ deps.now() + PRESENCE_WIPE_CONFIRMATION_POLL_MS, deps,
+ );
+ return false;
+ }
+ timers.delete(deviceId);
+ return shouldWipeUnavailableDeviceMirror(availabilityByDevice, deviceId);
+ };
+ // Retain the entry until execution, so reconnect can still extend its
+ // deadline and clear/replacement can invalidate the queued claim.
+ if (deps.deferWipe) deps.deferWipe(deviceId, claim);
+ else if (claim()) deps.wipe(deviceId);
}, delayMs),
};
timers.set(deviceId, entry);
diff --git a/apps/mobile/src/scheduler/remoteScheduleEvents.ts b/apps/mobile/src/scheduler/remoteScheduleEvents.ts
index 84475864f6..4746cd292f 100644
--- a/apps/mobile/src/scheduler/remoteScheduleEvents.ts
+++ b/apps/mobile/src/scheduler/remoteScheduleEvents.ts
@@ -36,6 +36,8 @@ const snapshots = new Map<string, RemoteScheduleEventSnapshot>();
// `clearDevice()` so mounted screens can observe a presence-offline cleanup even when
// that device had not emitted a schedule event in the current process.
const mirrorInvalidationVersions = new Map<string, number>();
+// Keep generations monotonic across recovery/clear without retaining per-device counters.
+let nextMirrorInvalidationGeneration = 0;
let mirrorInvalidationSnapshot: ReadonlyMap<string, number> = new Map();
const subs = new Set<() => void>();
@@ -73,14 +75,7 @@ export const remoteScheduleEventStore = {
},
invalidateDeviceMirror(deviceId: string): void {
- if (!deviceId) return;
- snapshots.delete(deviceId);
- mirrorInvalidationVersions.set(
- deviceId,
- (mirrorInvalidationVersions.get(deviceId) ?? 0) + 1,
- );
- mirrorInvalidationSnapshot = new Map(mirrorInvalidationVersions);
- emit();
+ remoteScheduleEventStore.invalidateDeviceMirrors([deviceId]);
},
/**
@@ -90,12 +85,15 @@ export const remoteScheduleEventStore = {
*/
invalidateDeviceMirrors(deviceIds: readonly string[]): void {
let changed = false;
- for (const deviceId of deviceIds) {
+ for (const deviceId of new Set(deviceIds)) {
if (!deviceId) continue;
+ // Presence and Home may report the same offline state independently. Only
+ // publish again after recovery clears the marker or a fresh event arrives.
+ if (mirrorInvalidationVersions.has(deviceId) && !snapshots.has(deviceId)) continue;
snapshots.delete(deviceId);
mirrorInvalidationVersions.set(
deviceId,
- (mirrorInvalidationVersions.get(deviceId) ?? 0) + 1,
+ ++nextMirrorInvalidationGeneration,
);
changed = true;
}