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): 批量合并离线镜像通知,修复多设备集中离线崩溃 (#4259)

guyong-zapo48c94b0f92f0
diff --git a/apps/mobile/app/devices/index.tsx b/apps/mobile/app/devices/index.tsx
index 1c7690f76c..3ae23aef6b 100644
--- a/apps/mobile/app/devices/index.tsx
+++ b/apps/mobile/app/devices/index.tsx
@@ -626,16 +626,24 @@ function HomeScreenContent() {
return result;
}, []);
- const softInvalidateDeviceMirror = useCallback((deviceId: string) => {
+ // 批量软失效:同一波(REST 快照整批 offline)只让两个 store 各 notify 一次。
+ // 逐台通知时设备数超过 React 嵌套更新上限即致命退出(2026-09-10 Android)。
+ const softInvalidateDeviceMirrors = useCallback((deviceIds: readonly string[]) => {
+ const idSet = new Set(deviceIds);
+ if (idSet.size === 0) return;
const sessionIds = remoteSessionStore.getSessions()
- .filter((session) => session.deviceLinkDeviceId === deviceId)
+ .filter((session) => !!session.deviceLinkDeviceId && idSet.has(session.deviceLinkDeviceId))
.map((session) => session.id);
- invalidateScheduleIndexForDevice(deviceId);
- remoteScheduleEventStore.invalidateDeviceMirror(deviceId);
- remoteSessionStore.markDeviceOffline(deviceId);
+ for (const deviceId of idSet) invalidateScheduleIndexForDevice(deviceId);
+ remoteScheduleEventStore.invalidateDeviceMirrors([...idSet]);
+ remoteSessionStore.markDevicesOffline([...idSet]);
setScheduleIndex((current) => invalidateRunningSessionScheduleEntries(current, sessionIds));
}, []);
+ const softInvalidateDeviceMirror = useCallback((deviceId: string) => {
+ softInvalidateDeviceMirrors([deviceId]);
+ }, [softInvalidateDeviceMirrors]);
+
const markDeviceOffline = useCallback((deviceId: string) => {
// 普通离线是可恢复的传输状态:保留 session/messages,只清 live 投影并失效
// message marker。恢复后会话立即显示 last-known 内容,后台 reopen 再补最新窗口。
@@ -964,9 +972,11 @@ function HomeScreenContent() {
));
// 单次 REST 快照里的 offline 只是可恢复状态,不能硬删刚同步的会话/消息;
// 显式关闭远控或撤权才是权限终态,继续清敏感镜像。
+ // soft 处先收拢成一批再失效:整批 offline 时逐台通知会击穿 React 嵌套上限。
+ const softInvalidateIds: string[] = [];
for (const item of deviceRows) {
const disposition = deviceMirrorCleanupDisposition(item.state);
- if (disposition === 'soft') softInvalidateDeviceMirror(item.device.deviceId);
+ if (disposition === 'soft') softInvalidateIds.push(item.device.deviceId);
if (disposition === 'hard') {
invalidateScheduleIndexForDevice(item.device.deviceId);
remoteScheduleEventStore.clearDevice(item.device.deviceId);
@@ -974,6 +984,7 @@ function HomeScreenContent() {
remoteSessionStore.removeDevice(item.device.deviceId);
}
}
+ if (softInvalidateIds.length > 0) softInvalidateDeviceMirrors(softInvalidateIds);
// 整表对账:REST 全量清单对“设备是否仍绑定”是权威。冷启动从缓存种入、
// 随后被解绑(完全不在清单里)的设备不会出现在状态分类里,按差集硬清 shard;
// 这与短暂 offline 不同,否则幽灵项会被快照回写无限续存。
diff --git a/apps/mobile/src/__tests__/interactionModel.test.ts b/apps/mobile/src/__tests__/interactionModel.test.ts
index 24a2884b5c..a889176f15 100644
--- a/apps/mobile/src/__tests__/interactionModel.test.ts
+++ b/apps/mobile/src/__tests__/interactionModel.test.ts
@@ -727,11 +727,15 @@ describe('interactionModel', () => {
expect(storeSource).toContain('pendingInteractionsAuthoritative.add(sessionId);');
expect(storeSource).toContain('hasAuthoritativePendingInteractions(sessionId: string): boolean');
expect(storeSource).toContain('export function useSessionPendingInteractionsAuthoritative(');
- // markDeviceOffline 与 removeDevice 都要撤销权威,否则离线期的空列表会被当权威用。
- const offlineStart = storeSource.indexOf('markDeviceOffline(deviceId: string): void {');
+ // markDeviceOffline(经共享清扫 sweepDevicesOffline,批量版 markDevicesOffline
+ // 同样复用)与 removeDevice 都要撤销权威,否则离线期的空列表会被当权威用。
+ const sweepStart = storeSource.indexOf('function sweepDevicesOffline(');
+ const markStart = storeSource.indexOf('markDeviceOffline(deviceId: string): void {');
const offlineEnd = storeSource.indexOf('removeDevice(deviceId: string): void {');
- expect(offlineStart).toBeGreaterThan(0);
- expect(storeSource.slice(offlineStart, offlineEnd)).toContain('pendingInteractionsAuthoritative.delete(sessionId)');
+ expect(sweepStart).toBeGreaterThan(0);
+ expect(markStart).toBeGreaterThan(sweepStart);
+ expect(storeSource.slice(markStart, offlineEnd)).toContain('sweepDevicesOffline([deviceId])');
+ expect(storeSource.slice(sweepStart, offlineEnd)).toContain('pendingInteractionsAuthoritative.delete(sessionId)');
expect(storeSource.slice(offlineEnd)).toContain('pendingInteractionsAuthoritative.delete(sessionId)');
// []→[] 的权威快照必须能通知出去,否则消费方永远等不到清理时机。
expect(storeSource).toContain('if (streamingChanged || authorityChanged) emit();');
diff --git a/apps/mobile/src/__tests__/offlineMirrorWipeQueue.test.ts b/apps/mobile/src/__tests__/offlineMirrorWipeQueue.test.ts
new file mode 100644
index 0000000000..f8784468ef
--- /dev/null
+++ b/apps/mobile/src/__tests__/offlineMirrorWipeQueue.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it, vi } from 'vitest';
+import { createOfflineMirrorWipeQueue } from '@/device-link/offlineMirrorWipeQueue';
+
+describe('offline mirror wipe queue', () => {
+ it('coalesces one wave of wipes into a single flush', async () => {
+ const flush = vi.fn();
+ const queue = createOfflineMirrorWipeQueue(flush);
+ for (let i = 0; i < 80; i += 1) queue.enqueue(`dev-${i}`);
+
+ // 同一 task 内的整波入队:只预约一次 flush,且在微任务里执行。
+ expect(queue.pendingCount()).toBe(80);
+ expect(flush).not.toHaveBeenCalled();
+
+ await Promise.resolve();
+ 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(queue.pendingCount()).toBe(0);
+ });
+
+ it('flushes later tasks separately and dedupes ids within a wave', async () => {
+ const flush = vi.fn();
+ const queue = createOfflineMirrorWipeQueue(flush);
+
+ 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']);
+
+ // 后续 task 的 wipe 单独 flush,不与上一波合并(离线清理语义不变)。
+ queue.enqueue('dev-c');
+ await Promise.resolve();
+ expect(flush).toHaveBeenCalledTimes(2);
+ expect(flush.mock.calls[1][0]).toEqual(['dev-c']);
+ });
+
+ it('ignores empty device ids', async () => {
+ const flush = vi.fn();
+ const queue = createOfflineMirrorWipeQueue(flush);
+
+ queue.enqueue('');
+ expect(queue.pendingCount()).toBe(0);
+ await Promise.resolve();
+ expect(flush).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/mobile/src/__tests__/remoteScheduleEvents.test.ts b/apps/mobile/src/__tests__/remoteScheduleEvents.test.ts
index 90197118f8..8a402c811d 100644
--- a/apps/mobile/src/__tests__/remoteScheduleEvents.test.ts
+++ b/apps/mobile/src/__tests__/remoteScheduleEvents.test.ts
@@ -92,6 +92,28 @@ describe('remote schedule event store', () => {
off();
});
+ it.each([40, 80, 100])('batch-invalidates %i devices with a single notification', (count) => {
+ const sub = vi.fn();
+ const off = remoteScheduleEventStore.subscribe(sub);
+ const deviceIds = Array.from({ length: count }, (_, i) => `wave-dev-${i}`);
+
+ remoteScheduleEventStore.invalidateDeviceMirrors(deviceIds);
+
+ // 整波只 notify 一轮,而不是逐台 N 轮——逐台通知在设备数超过 React 嵌套
+ // 更新上限时致命退出(2026-09-10 Android 冷启动,40/80 台隔离复现)。
+ expect(sub).toHaveBeenCalledTimes(1);
+ const snapshot = remoteScheduleEventStore.getMirrorInvalidationSnapshot();
+ expect(snapshot.size).toBe(count);
+ for (const deviceId of deviceIds) expect(snapshot.get(deviceId)).toBe(1);
+
+ // 合并只在单波内:另起一波(第二次批量失效)各自再 notify 一轮。
+ remoteScheduleEventStore.invalidateDeviceMirrors(deviceIds);
+ expect(sub).toHaveBeenCalledTimes(2);
+ expect(remoteScheduleEventStore.getMirrorInvalidationSnapshot().get('wave-dev-0')).toBe(2);
+
+ 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/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
index b24590f748..d4b53d79c4 100644
--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts
+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
@@ -3034,6 +3034,38 @@ describe('remoteSessionStore', () => {
});
});
+ it('markDevicesOffline sweeps a wave with a single notification', () => {
+ const deviceIds = ['dev-a', 'dev-b', 'dev-c'];
+ deviceIds.forEach((id, i) => {
+ remoteSessionStore.setDeviceSessions(id, `Mac-${i}`, [session(`s-${id}`)]);
+ });
+ for (const id of deviceIds) {
+ pushMakerStatus(`s-${id}`, {
+ isRunning: true,
+ outputTokens: 12,
+ generationDurationMs: 400,
+ generationActive: true,
+ generationReliable: true,
+ });
+ }
+ const notify = vi.fn();
+ const unsubscribe = remoteSessionStore.subscribe(notify);
+
+ remoteSessionStore.markDevicesOffline(deviceIds);
+
+ // 整波只 notify 一轮;逐台 markDeviceOffline 会 notify N 轮,叠加 schedule
+ // store 的逐台失效后在设备多时击穿 React 嵌套上限(2026-09-10)。
+ expect(notify).toHaveBeenCalledTimes(1);
+ for (const id of deviceIds) {
+ expect(remoteSessionStore.isSessionMakerTurnRunning(`s-${id}`)).toBe(false);
+ }
+
+ // 清理已生效:同批重复离线无变化、静默。
+ remoteSessionStore.markDevicesOffline(deviceIds);
+ expect(notify).toHaveBeenCalledTimes(1);
+ unsubscribe();
+ });
+
it('still zeros leftover live metrics when a new turn starts without them', () => {
remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);
pushMakerStatus('s1', {
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index fd5a27eeea..0675e9bb74 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -145,6 +145,7 @@ import {
schedulePresenceWipeTimer,
updatePresenceAvailability,
} from '@/device-link/presenceRecovery';
+import { createOfflineMirrorWipeQueue } from '@/device-link/offlineMirrorWipeQueue';
import { hasMoreOlderMessages } from '@/session/messagePaging';
import type { InputProjection, PendingInteraction, RemoteMessage } from '@/session/types';
import { createVisualMockDeviceLinkContext, seedVisualMockStore } from '@/debug/visualMock';
@@ -1950,16 +1951,24 @@ function requireClient(client: DeviceLinkClient | null): DeviceLinkClient {
return client;
}
-function markOfflineDeviceMirror(deviceId: string): void {
+function markOfflineDeviceMirrors(deviceIds: readonly string[]): void {
// 普通离线只清依赖在线连接的 live 投影,保留 session/messages。这样用户切回
// 刚看过的会话时先看到 last-known 内容,恢复后 marker 失效会触发后台窗口对账。
- remoteSessionStore.markDeviceOffline(deviceId);
- invalidateScheduleIndexForDevice(deviceId);
- remoteScheduleEventStore.invalidateDeviceMirror(deviceId);
- evictDeviceProviders(deviceId);
- evictDeviceModelMeta(deviceId);
- evictAgentCapabilitiesForDevice(deviceId);
- evictComposerPaletteCacheForDevice(deviceId);
+ // 批量入口:同一波离线两个 store 各 notify 一次,而不是每台各 notify 一轮——
+ // 逐台通知时设备数超过 React 嵌套更新上限即致命退出(2026-09-10)。
+ remoteSessionStore.markDevicesOffline(deviceIds);
+ for (const deviceId of deviceIds) {
+ invalidateScheduleIndexForDevice(deviceId);
+ evictDeviceProviders(deviceId);
+ evictDeviceModelMeta(deviceId);
+ evictAgentCapabilitiesForDevice(deviceId);
+ evictComposerPaletteCacheForDevice(deviceId);
+ }
+ remoteScheduleEventStore.invalidateDeviceMirrors(deviceIds);
+}
+
+function markOfflineDeviceMirror(deviceId: string): void {
+ markOfflineDeviceMirrors([deviceId]);
}
function wipeUnavailableDeviceMirror(deviceId: string): void {
@@ -1978,12 +1987,16 @@ 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: markOfflineDeviceMirror,
+ wipe: offlineMirrorWipeQueue.enqueue,
};
function scheduleUnavailableDeviceMirrorWipe(
diff --git a/apps/mobile/src/device-link/offlineMirrorWipeQueue.ts b/apps/mobile/src/device-link/offlineMirrorWipeQueue.ts
new file mode 100644
index 0000000000..e76477e07c
--- /dev/null
+++ b/apps/mobile/src/device-link/offlineMirrorWipeQueue.ts
@@ -0,0 +1,41 @@
+/**
+ * 离线镜像清理的通知合并队列。
+ *
+ * presence 整批离线时,每台设备各有一个 5s 宽限定时器;RN 的定时器队列会把同一
+ * task 内到期的回调连续投递。若逐台执行清理并通知,每台各触发一轮 React 同步
+ * 重渲染,设备数超过嵌套更新上限即致命退出(2026-09-10 Android 冷启动,40/80
+ * 台隔离复现;同批处理仅 3 次渲染则正常)。这里把同一 task 内到期的设备收拢成
+ * 一次 flush,由调用方一次性更新两个 store 并各 notify 一次。
+ *
+ * 只合并「通知」,不合并「清理」:flush 时每台设备的离线清理语义原样执行。
+ */
+export interface OfflineMirrorWipeQueue {
+ enqueue(deviceId: string): void;
+ pendingCount(): number;
+}
+
+export function createOfflineMirrorWipeQueue(
+ flush: (deviceIds: string[]) => void,
+ schedule: (callback: () => void) => void = (callback) => queueMicrotask(callback),
+): OfflineMirrorWipeQueue {
+ let pending: Set<string> | null = null;
+ return {
+ enqueue(deviceId: string): void {
+ if (!deviceId) return;
+ if (pending === null) {
+ // 首台:登记并预约 flush。同 task 内后续设备只入队,不再预约。
+ pending = new Set([deviceId]);
+ schedule(() => {
+ const deviceIds = [...(pending ?? [])];
+ pending = null;
+ if (deviceIds.length > 0) flush(deviceIds);
+ });
+ return;
+ }
+ pending.add(deviceId);
+ },
+ pendingCount(): number {
+ return pending?.size ?? 0;
+ },
+ };
+}
diff --git a/apps/mobile/src/scheduler/remoteScheduleEvents.ts b/apps/mobile/src/scheduler/remoteScheduleEvents.ts
index b2c86cd239..84475864f6 100644
--- a/apps/mobile/src/scheduler/remoteScheduleEvents.ts
+++ b/apps/mobile/src/scheduler/remoteScheduleEvents.ts
@@ -83,6 +83,27 @@ export const remoteScheduleEventStore = {
emit();
},
+ /**
+ * 批量失效:同一波(如 presence 整批离线)只 emit 一次。逐台失效时每台各
+ * notify 一轮,所有挂载屏被同步重渲染 N 次,设备数超过 React 嵌套更新上限
+ * 即致命退出(2026-09-10 Android 冷启动,40/80 台隔离复现)。
+ */
+ invalidateDeviceMirrors(deviceIds: readonly string[]): void {
+ let changed = false;
+ for (const deviceId of deviceIds) {
+ if (!deviceId) continue;
+ snapshots.delete(deviceId);
+ mirrorInvalidationVersions.set(
+ deviceId,
+ (mirrorInvalidationVersions.get(deviceId) ?? 0) + 1,
+ );
+ changed = true;
+ }
+ if (!changed) return;
+ mirrorInvalidationSnapshot = new Map(mirrorInvalidationVersions);
+ emit();
+ },
+
clearDeviceMirrorInvalidation(deviceId: string): void {
if (!mirrorInvalidationVersions.delete(deviceId)) return;
mirrorInvalidationSnapshot = new Map(mirrorInvalidationVersions);
diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.ts
index d497b6479e..856670595c 100644
--- a/apps/mobile/src/session/remoteSessionStore.ts
+++ b/apps/mobile/src/session/remoteSessionStore.ts
@@ -2953,6 +2953,64 @@ function recallParkedTaskUpdates(
return recalled ?? prevMap;
}
+/**
+ * `markDeviceOffline` / `markDevicesOffline` 共用的清扫主体:逐台执行离线清理,
+ * 返回是否有任何投影变化。调用方负责决定 emit 一次(批量)还是逐台 emit。
+ */
+function sweepDevicesOffline(deviceIds: readonly string[]): boolean {
+ let changed = false;
+ const idSet = new Set(deviceIds);
+ if (idSet.size === 0) return false;
+ // A first text delta can still be waiting in the 32ms batch before any session
+ // metadata/index exists. Flush batches from this transport first so they create a
+ // device-owned host anchor, then freeze that identity before reconnect metadata can
+ // bind it to a newer send round.
+ for (const [sessionId, batch] of [...pendingTextDeltaBatches]) {
+ if (batch.deviceId === undefined || !idSet.has(batch.deviceId)) continue;
+ changed = flushAndFinalizeRemoteStreamingMessages(sessionId) || changed;
+ changed = clearStreamingAssistantPointer(sessionId) || changed;
+ changed = freezeUnboundPendingHostAnchorsForOffline(sessionId, batch.deviceId) || changed;
+ }
+ for (const [sessionId, indexedDeviceId] of sessionDeviceIndex) {
+ if (!idSet.has(indexedDeviceId)) continue;
+ if (sessionMessageSyncMarkers.delete(sessionId)) {
+ bumpMessageVersion(sessionId);
+ changed = true;
+ }
+ changed = livePlanSnapshots.delete(sessionId) || changed;
+ changed = pendingRefreshSessions.delete(sessionId) || changed;
+ changed = deletePendingInteractionState(sessionId) || changed;
+ // 投影没了,这份(空)列表就不再权威:重连拿到全量快照前不许据此做清理。
+ changed = pendingInteractionsAuthoritative.delete(sessionId) || changed;
+ changed = invalidateInputProjectionForOffline(sessionId) || changed;
+ bumpInputProjectionAuthorityEpoch(sessionId);
+ changed = deleteSessionLiveActivity(sessionId) || changed;
+ changed = sessionGoalStatus.delete(sessionId) || changed;
+ changed = sessionTaskUpdates.delete(sessionId) || changed;
+ changed = sessionParkedTaskUpdates.delete(sessionId) || changed;
+ changed = sessionMakerActivityEpochs.delete(sessionId) || changed;
+ changed = flushAndFinalizeRemoteStreamingMessages(sessionId) || changed;
+ changed = clearStreamingAssistantPointer(sessionId) || changed;
+ // The message window survives a soft offline transition, so both pending
+ // identities must survive too: one protects the live row during latest-window
+ // reconciliation, and the other lets a reconnecting authoritative user row
+ // restore question → reply order. Persisted reconciliation, explicit window
+ // invalidation, or actual device removal will retire them.
+ changed = freezeUnboundPendingHostAnchorsForOffline(sessionId, indexedDeviceId) || changed;
+ changed = writeMakerTurnRunning(sessionId, false) || changed;
+ changed = writeSessionRunStatus(sessionId, EMPTY_SESSION_RUN_STATUS) || changed;
+ }
+ for (const [sessionId, pendingAnchors] of pendingHostAnchorLiveAssistantClientIds) {
+ for (const identity of pendingAnchors.values()) {
+ for (const deviceId of identity.deviceIds) {
+ if (!idSet.has(deviceId)) continue;
+ changed = freezeUnboundPendingHostAnchorsForOffline(sessionId, deviceId) || changed;
+ }
+ }
+ }
+ return changed;
+}
+
export const remoteSessionStore = {
/** Coalesce notifications for one logically atomic remote snapshot. */
batch<T>(work: () => T): T {
@@ -4807,51 +4865,18 @@ export const remoteSessionStore = {
* 最新消息窗口,不会把断线前缓存误判为 fresh。
*/
markDeviceOffline(deviceId: string): void {
- let changed = false;
- // A first text delta can still be waiting in the 32ms batch before any session
- // metadata/index exists. Flush batches from this transport first so they create a
- // device-owned host anchor, then freeze that identity before reconnect metadata can
- // bind it to a newer send round.
- for (const [sessionId, batch] of [...pendingTextDeltaBatches]) {
- if (batch.deviceId !== deviceId) continue;
- changed = flushAndFinalizeRemoteStreamingMessages(sessionId) || changed;
- changed = clearStreamingAssistantPointer(sessionId) || changed;
- changed = freezeUnboundPendingHostAnchorsForOffline(sessionId, deviceId) || changed;
- }
- for (const [sessionId, indexedDeviceId] of sessionDeviceIndex) {
- if (indexedDeviceId !== deviceId) continue;
- if (sessionMessageSyncMarkers.delete(sessionId)) {
- bumpMessageVersion(sessionId);
- changed = true;
- }
- changed = livePlanSnapshots.delete(sessionId) || changed;
- changed = pendingRefreshSessions.delete(sessionId) || changed;
- changed = deletePendingInteractionState(sessionId) || changed;
- // 投影没了,这份(空)列表就不再权威:重连拿到全量快照前不许据此做清理。
- changed = pendingInteractionsAuthoritative.delete(sessionId) || changed;
- changed = invalidateInputProjectionForOffline(sessionId) || changed;
- bumpInputProjectionAuthorityEpoch(sessionId);
- changed = deleteSessionLiveActivity(sessionId) || changed;
- changed = sessionGoalStatus.delete(sessionId) || changed;
- changed = sessionTaskUpdates.delete(sessionId) || changed;
- changed = sessionParkedTaskUpdates.delete(sessionId) || changed;
- changed = sessionMakerActivityEpochs.delete(sessionId) || changed;
- changed = flushAndFinalizeRemoteStreamingMessages(sessionId) || changed;
- changed = clearStreamingAssistantPointer(sessionId) || changed;
- // The message window survives a soft offline transition, so both pending
- // identities must survive too: one protects the live row during latest-window
- // reconciliation, and the other lets a reconnecting authoritative user row
- // restore question → reply order. Persisted reconciliation, explicit window
- // invalidation, or actual device removal will retire them.
- changed = freezeUnboundPendingHostAnchorsForOffline(sessionId, deviceId) || changed;
- changed = writeMakerTurnRunning(sessionId, false) || changed;
- changed = writeSessionRunStatus(sessionId, EMPTY_SESSION_RUN_STATUS) || changed;
- }
- for (const [sessionId, pendingAnchors] of pendingHostAnchorLiveAssistantClientIds) {
- if (![...pendingAnchors.values()].some((identity) => identity.deviceIds.has(deviceId))) continue;
- changed = freezeUnboundPendingHostAnchorsForOffline(sessionId, deviceId) || changed;
- }
- if (changed) emit();
+ if (!sweepDevicesOffline([deviceId])) return;
+ emit();
+ },
+
+ /**
+ * 批量离线:同一波(如 presence 整批离线)只 emit 一次。逐台 markDeviceOffline
+ * 时每台各 notify 一轮,叠加 schedule store 的逐台失效,设备数超过 React 嵌套
+ * 更新上限即致命退出(2026-09-10 Android 冷启动,40/80 台隔离复现)。
+ */
+ markDevicesOffline(deviceIds: readonly string[]): void {
+ if (!sweepDevicesOffline(deviceIds)) return;
+ emit();
},
removeDevice(deviceId: string): void {