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): preserve session cache while offline (#1111)

hushaowu-rheb2b93eb63d9
diff --git a/apps/mobile/app/devices/[deviceId].tsx b/apps/mobile/app/devices/[deviceId].tsx
index 1884f0cca0..f6a7e932ac 100644
--- a/apps/mobile/app/devices/[deviceId].tsx
+++ b/apps/mobile/app/devices/[deviceId].tsx
@@ -75,8 +75,18 @@ import {
useRemoteSessions,
useRemoteSessionStoreVersion,
} from '@/session/remoteSessionStore';
-import { useRemoteScheduleEventSnapshot } from '@/scheduler/remoteScheduleEvents';
-import { loadSessionScheduleIndex, loadSessionScheduleIndexThrottled } from '@/session/scheduleIndex';
+import {
+ remoteScheduleEventStore,
+ useRemoteScheduleEventSnapshot,
+ useRemoteScheduleMirrorInvalidations,
+} from '@/scheduler/remoteScheduleEvents';
+import {
+ getScheduleIndexInvalidationVersion,
+ invalidateOfflineScheduleIndexFailureFor,
+ invalidateRunningSessionScheduleEntries,
+ loadSessionScheduleIndex,
+ loadSessionScheduleIndexThrottled,
+} from '@/session/scheduleIndex';
import { shouldSuppressRemoteListEmptyState } from '@/session/sessionEmptyState';
import type { RemoteSession } from '@/session/types';
import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';
@@ -135,6 +145,7 @@ export default function DeviceDetailScreen() {
const { connectionIssue, invoke, status, subscribe, unsubscribe } = useDeviceLink();
const maker = useMobileMakerTransport(deviceId);
const scheduleEventSnapshot = useRemoteScheduleEventSnapshot(deviceId);
+ const scheduleMirrorInvalidations = useRemoteScheduleMirrorInvalidations();
const allSessions = useRemoteSessions();
// filter 必须 memo:裸 filter 每次渲染都产新数组,会让下游全部 [sessions, ...] 依赖的
// useMemo 逐 emit 失效,派生链(索引 → sections → 全列表行)整体重建(2026-07-18
@@ -169,6 +180,14 @@ export default function DeviceDetailScreen() {
() => new Map(),
);
+ useEffect(() => {
+ if (!deviceId || !scheduleMirrorInvalidations.has(deviceId)) return;
+ setScheduleIndex((current) => invalidateRunningSessionScheduleEntries(
+ current,
+ sessions.map((session) => session.id),
+ ));
+ }, [deviceId, scheduleMirrorInvalidations, sessions]);
+
const syncSessions = useCallback(async () => {
if (!deviceId) return;
setLoading(true);
@@ -185,11 +204,22 @@ export default function DeviceDetailScreen() {
]);
});
remoteSessionStore.setDeviceSessions(deviceId, deviceName, Array.isArray(list) ? list : []);
+ // A successful sessions:list is authoritative reachability evidence even when relay
+ // presence was not replayed. Retire both offline caches before the schedule reload.
+ remoteScheduleEventStore.clearDeviceMirrorInvalidation(deviceId);
+ invalidateOfflineScheduleIndexFailureFor(deviceId);
// 节流缓存与首页共用同一 key(deviceId):两页交替浏览时不重复全量拉取(单飞 + TTL,
// 拥塞背景见 scheduleIndex 注释)。
+ const invalidationVersion = getScheduleIndexInvalidationVersion(deviceId);
void loadSessionScheduleIndexThrottled(deviceId, () => loadSessionScheduleIndex(maker, { isDeviceUnresponsive: () => unresponsiveDevicesStore.has(deviceId) }))
- .then(setScheduleIndex)
- .catch(() => setScheduleIndex(new Map()));
+ .then((nextIndex) => {
+ if (getScheduleIndexInvalidationVersion(deviceId) !== invalidationVersion) return;
+ setScheduleIndex(nextIndex);
+ })
+ .catch(() => {
+ if (getScheduleIndexInvalidationVersion(deviceId) !== invalidationVersion) return;
+ setScheduleIndex(new Map());
+ });
setLastSyncedAt(Date.now());
} catch (err) {
setError(formatRemoteError(err));
@@ -226,8 +256,12 @@ export default function DeviceDetailScreen() {
scheduleEventSnapshot.scheduleListVersion === 0
&& scheduleEventSnapshot.unreadClearVersion === 0
) return;
+ const invalidationVersion = getScheduleIndexInvalidationVersion(deviceId);
void loadSessionScheduleIndexThrottled(deviceId, () => loadSessionScheduleIndex(maker, { isDeviceUnresponsive: () => unresponsiveDevicesStore.has(deviceId) }), { force: true })
- .then(setScheduleIndex)
+ .then((nextIndex) => {
+ if (getScheduleIndexInvalidationVersion(deviceId) !== invalidationVersion) return;
+ setScheduleIndex(nextIndex);
+ })
.catch(() => {
// 失败保留旧徽标,与整页 load 的容错口径一致。
});
diff --git a/apps/mobile/app/devices/index.tsx b/apps/mobile/app/devices/index.tsx
index 4ce6d8af29..8642bc6d68 100644
--- a/apps/mobile/app/devices/index.tsx
+++ b/apps/mobile/app/devices/index.tsx
@@ -66,6 +66,7 @@ import { toDeviceListItems } from '@/device-link/devices';
import {
collectFreshPresenceDeviceIds,
createPresenceFreshnessTracker,
+ deviceMirrorCleanupDisposition,
markPresenceFresh,
mergeDeviceViewsWithFreshPresence,
patchDeviceViewsWithPresence,
@@ -80,7 +81,10 @@ import {
import { withTransientRemoteRetry } from '@/device-link/remoteRetry';
import { revokedDevicesStore, useRevokedDevices } from '@/device-link/revokedDevicesStore';
import { useUnresponsiveDevices } from '@/device-link/unresponsiveDevicesStore';
-import { remoteScheduleEventStore } from '@/scheduler/remoteScheduleEvents';
+import {
+ remoteScheduleEventStore,
+ useRemoteScheduleMirrorInvalidations,
+} from '@/scheduler/remoteScheduleEvents';
import {
buildMobileHomePresentation,
excludeOrcaWorkerSessions,
@@ -119,6 +123,10 @@ import { dataPropsEqual, mapContentEqual } from '@/utils/valueEquality';
import { useStableValue } from '@/utils/useStableValue';
import { useMinuteNow } from '@/utils/useMinuteNow';
import {
+ getScheduleIndexInvalidationVersion,
+ invalidateOfflineScheduleIndexFailureFor,
+ invalidateRunningSessionScheduleEntries,
+ invalidateScheduleIndexForDevice,
loadDeviceSessionScheduleIndex,
loadSessionScheduleIndexThrottled,
replaceSessionScheduleIndexEntries,
@@ -250,6 +258,7 @@ export default function HomeScreen() {
return merged;
}, [rawDeviceConnectionStates, unresponsiveDevices]);
const [scheduleIndex, setScheduleIndex] = useState<Map<string, RemoteSessionScheduleInfo>>(() => new Map());
+ const scheduleMirrorInvalidations = useRemoteScheduleMirrorInvalidations();
const updateDeviceConnectionState = useCallback((deviceId: string, state: HomeDeviceConnectionState) => {
setDeviceConnectionStates((current) => updateHomeDeviceConnectionState(current, deviceId, state));
@@ -262,14 +271,26 @@ export default function HomeScreen() {
return result;
}, []);
+ const softInvalidateDeviceMirror = useCallback((deviceId: string) => {
+ const sessionIds = remoteSessionStore.getSessions()
+ .filter((session) => session.deviceLinkDeviceId === deviceId)
+ .map((session) => session.id);
+ invalidateScheduleIndexForDevice(deviceId);
+ remoteScheduleEventStore.invalidateDeviceMirror(deviceId);
+ remoteSessionStore.markDeviceOffline(deviceId);
+ setScheduleIndex((current) => invalidateRunningSessionScheduleEntries(current, sessionIds));
+ }, []);
+
const markDeviceOffline = useCallback((deviceId: string) => {
- remoteSessionStore.removeDevice(deviceId);
+ // 普通离线是可恢复的传输状态:保留 session/messages,只清 live 投影并失效
+ // message marker。恢复后会话立即显示 last-known 内容,后台 reopen 再补最新窗口。
+ softInvalidateDeviceMirror(deviceId);
setDevices((current) => {
const next = reconcileDeviceViews(markDeviceViewsOffline(current, new Set([deviceId]))).devices;
devicesRef.current = next;
return next;
});
- }, [reconcileDeviceViews]);
+ }, [reconcileDeviceViews, softInvalidateDeviceMirror]);
const refreshDeviceScheduleIndex = useCallback((
deviceId: string,
@@ -280,12 +301,14 @@ export default function HomeScreen() {
// 重放 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 },
)
.then((nextIndex) => {
+ if (getScheduleIndexInvalidationVersion(deviceId) !== invalidationVersion) return;
setScheduleIndex((current) => replaceSessionScheduleIndexEntries(
current,
sessionIds,
@@ -400,25 +423,48 @@ export default function HomeScreen() {
current,
new Set(availableRows.map((item) => item.device.deviceId)),
));
- const unavailableDeviceIds = new Set(deviceRows.filter((item) => !item.canOpen).map((item) => item.device.deviceId));
- for (const deviceId of unavailableDeviceIds) remoteSessionStore.removeDevice(deviceId);
- // 整表对账:REST 全量清单是权威。unavailableDeviceIds 只覆盖「在清单里但不可用」,
- // 冷启动从缓存种入、随后被解绑(完全不在清单里)的设备不会出现在其中,不对账
- // 就成了无法消除的幽灵项;快照回写也会把它一直续进缓存。按差集清 shard。
+ // 单次 REST 快照里的 offline 只是可恢复状态,不能硬删刚同步的会话/消息;
+ // 显式关闭远控或撤权才是权限终态,继续清敏感镜像。
+ for (const item of deviceRows) {
+ const disposition = deviceMirrorCleanupDisposition(item.state);
+ if (disposition === 'soft') softInvalidateDeviceMirror(item.device.deviceId);
+ if (disposition === 'hard') {
+ invalidateScheduleIndexForDevice(item.device.deviceId);
+ remoteScheduleEventStore.clearDevice(item.device.deviceId);
+ remoteScheduleEventStore.clearDeviceMirrorInvalidation(item.device.deviceId);
+ remoteSessionStore.removeDevice(item.device.deviceId);
+ }
+ }
+ // 整表对账:REST 全量清单对“设备是否仍绑定”是权威。冷启动从缓存种入、
+ // 随后被解绑(完全不在清单里)的设备不会出现在状态分类里,按差集硬清 shard;
+ // 这与短暂 offline 不同,否则幽灵项会被快照回写无限续存。
const knownDeviceIds = new Set(deviceRows.map((item) => item.device.deviceId));
const ghostDeviceIds = new Set<string>();
for (const session of remoteSessionStore.getSessions()) {
const shardId = session.deviceLinkDeviceId;
if (shardId && !knownDeviceIds.has(shardId)) ghostDeviceIds.add(shardId);
}
- for (const deviceId of ghostDeviceIds) remoteSessionStore.removeDevice(deviceId);
+ for (const deviceId of ghostDeviceIds) {
+ invalidateScheduleIndexForDevice(deviceId);
+ remoteScheduleEventStore.clearDevice(deviceId);
+ remoteScheduleEventStore.clearDeviceMirrorInvalidation(deviceId);
+ remoteSessionStore.removeDevice(deviceId);
+ }
const failures: string[] = [];
const offlineDeviceIds = new Set<string>();
await Promise.all(availableRows.map(async (item) => {
const result = await hydrateDeviceSessions(item.device);
if (result.failure) failures.push(result.failure);
- if (result.offline) offlineDeviceIds.add(item.device.deviceId);
+ if (result.offline) {
+ offlineDeviceIds.add(item.device.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);
+ }
}));
// 收尾再合并一次:hydrate 阶段(可能持续数秒)里新到的 presence 补丁同样不能被覆盖掉。
@@ -447,7 +493,7 @@ export default function HomeScreen() {
return task.finally(() => {
if (visible) setRefreshing(false);
});
- }, [apiFetch, deviceIdentityCacheReady, homeCacheUserId, hydrateDeviceSessions, reconcileDeviceViews, revokedDevices]);
+ }, [apiFetch, deviceIdentityCacheReady, homeCacheUserId, hydrateDeviceSessions, reconcileDeviceViews, revokedDevices, softInvalidateDeviceMirror]);
// 冷启动先画缓存:上次 loadHome 成功的设备+会话快照种入 store,先把列表画出来(消除首屏强制
// spinner);loadHome 返回后由 setDeviceSessions / removeDevice 正常覆盖收敛。缓存为空时列表
@@ -517,6 +563,15 @@ export default function HomeScreen() {
};
}, []);
+ useEffect(() => {
+ if (scheduleMirrorInvalidations.size === 0) return;
+ const invalidatedDeviceIds = new Set(scheduleMirrorInvalidations.keys());
+ const sessionIds = remoteSessionStore.getSessions()
+ .filter((session) => !!session.deviceLinkDeviceId && invalidatedDeviceIds.has(session.deviceLinkDeviceId))
+ .map((session) => session.id);
+ setScheduleIndex((current) => invalidateRunningSessionScheduleEntries(current, sessionIds));
+ }, [scheduleMirrorInvalidations]);
+
useEffect(() => remoteScheduleEventStore.subscribe(() => {
const deviceIds = new Set<string>();
for (const device of devicesRef.current) deviceIds.add(device.deviceId);
diff --git a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
index 36266453d8..1b27614cb1 100644
--- a/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
+++ b/apps/mobile/src/__tests__/homeDesktopFirst.test.ts
@@ -166,6 +166,8 @@ describe('mobile home desktop-first surface', () => {
const scheduleIndexSource = readSource('src/session/scheduleIndex.ts');
expect(source).toContain('const [scheduleIndex, setScheduleIndex]');
+ expect(source).toContain('useRemoteScheduleMirrorInvalidations()');
+ expect(source).toContain('invalidateRunningSessionScheduleEntries(current, sessionIds)');
expect(source).toContain('const [deviceIdentityCacheReady, setDeviceIdentityCacheReady]');
expect(source).toContain('loadDeviceIdentityCache()');
expect(source).toContain('reconcileDeviceIdentities(');
diff --git a/apps/mobile/src/__tests__/presenceDevices.test.ts b/apps/mobile/src/__tests__/presenceDevices.test.ts
index acfa5031b5..429f06c113 100644
--- a/apps/mobile/src/__tests__/presenceDevices.test.ts
+++ b/apps/mobile/src/__tests__/presenceDevices.test.ts
@@ -3,6 +3,7 @@ import type { DeviceView, PresenceSnapshot } from '@cindy/device-link';
import {
collectFreshPresenceDeviceIds,
createPresenceFreshnessTracker,
+ deviceMirrorCleanupDisposition,
markPresenceFresh,
mergeDeviceViewsWithFreshPresence,
patchDeviceViewsWithPresence,
@@ -37,6 +38,26 @@ function presence(patch: Partial<PresenceSnapshot> = {}): PresenceSnapshot {
};
}
+describe('deviceMirrorCleanupDisposition', () => {
+ it('keeps last-known content for recoverable offline devices', () => {
+ expect(deviceMirrorCleanupDisposition('offline')).toBe('soft');
+ });
+
+ it.each(['remote_disabled', 'access_revoked'] as const)(
+ 'hard-clears mirrors for the %s permission terminal state',
+ (state) => {
+ expect(deviceMirrorCleanupDisposition(state)).toBe('hard');
+ },
+ );
+
+ it.each(['ready', 'busy', 'self'] as const)(
+ 'leaves mirrors unchanged for %s devices',
+ (state) => {
+ expect(deviceMirrorCleanupDisposition(state)).toBe('keep');
+ },
+ );
+});
+
describe('patchDeviceViewsWithPresence', () => {
it('patches a known device locally and flags the first controllable transition', () => {
const result = patchDeviceViewsWithPresence([device()], presence(), 'mobile-1');
diff --git a/apps/mobile/src/__tests__/remoteScheduleEvents.test.ts b/apps/mobile/src/__tests__/remoteScheduleEvents.test.ts
index 3cc9dcb7e7..849a0fc0c0 100644
--- a/apps/mobile/src/__tests__/remoteScheduleEvents.test.ts
+++ b/apps/mobile/src/__tests__/remoteScheduleEvents.test.ts
@@ -35,6 +35,28 @@ describe('remote schedule event store', () => {
off();
});
+ it('publishes mirror invalidation even without an existing schedule event snapshot', () => {
+ const before = remoteScheduleEventStore.getMirrorInvalidationSnapshot();
+ const sub = vi.fn();
+ const off = remoteScheduleEventStore.subscribe(sub);
+
+ remoteScheduleEventStore.invalidateDeviceMirror('dev-1');
+
+ const afterFirst = remoteScheduleEventStore.getMirrorInvalidationSnapshot();
+ expect(afterFirst).not.toBe(before);
+ expect(afterFirst.get('dev-1')).toBe(1);
+ 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);
+
+ 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({
@@ -100,5 +122,6 @@ describe('remote schedule event store', () => {
remoteScheduleEventStore.clearAll();
expect(remoteScheduleEventStore.getVersion('dev-2')).toBe(0);
+ expect(remoteScheduleEventStore.getMirrorInvalidationSnapshot().size).toBe(0);
});
});
diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
index 195f4c1d8f..6ae9befb31 100644
--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts
+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts
@@ -2373,6 +2373,60 @@ describe('remoteSessionStore', () => {
});
});
+ it('soft-invalidates an offline device without deleting sessions or messages', () => {
+ const meta = session('s1', {
+ updatedAt: '2026-01-01T00:00:01.000Z',
+ _count: { messages: 1 },
+ });
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [meta]);
+ remoteSessionStore.setDeviceSessions('dev-2', 'Windows', [session('s2')]);
+ remoteSessionStore.setMessages('s1', [message('m1', 's1')]);
+ pushMakerText('s1', 'live-1', 'streaming', false);
+ remoteSessionStore.setMessages('s2', [message('m2', 's2')]);
+ remoteSessionStore.markSessionMessagesSynced('s1', meta);
+ remoteSessionStore.setPendingInteractions('s1', [{ request: { requestId: 'req-1' } }]);
+ remoteSessionStore.setInputProjection('s1', projection('s1'));
+ remoteSessionStore.setSessionRunning('s1', true);
+ remoteSessionStore.setGoalStatus('s1', { status: 'running' } as never);
+
+ remoteSessionStore.markDeviceOffline('dev-1');
+
+ expect(remoteSessionStore.getSessions().map((item) => item.id).sort()).toEqual(['s1', 's2']);
+ expect(remoteSessionStore.getSessionDeviceId('s1')).toBe('dev-1');
+ expect(remoteSessionStore.getMessages('s1')).toEqual([
+ expect.objectContaining({ id: 'm1' }),
+ expect.objectContaining({ content: 'streaming', agentMeta: expect.not.objectContaining({ isStreaming: true }) }),
+ ]);
+ expect(remoteSessionStore.isSessionMessageWindowSynced('s1', meta)).toBe(false);
+ expect(remoteSessionStore.getPendingInteractions('s1')).toEqual([]);
+ expect(remoteSessionStore.getInputProjection('s1').pendingQueue).toEqual([]);
+ expect(remoteSessionStore.getSessionRunStatus('s1').isRunning).toBe(false);
+ expect(remoteSessionStore.getGoalStatus('s1')).toBeUndefined();
+ expect(remoteSessionStore.getMessages('s2')).toHaveLength(1);
+
+ // 重复离线通知幂等,不会清掉保留的 last-known 内容。
+ remoteSessionStore.markDeviceOffline('dev-1');
+ expect(remoteSessionStore.getMessages('s1')).toHaveLength(2);
+ });
+
+ it('emits when soft offline only clears pending-refresh metadata', () => {
+ remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);
+ remoteSessionStore.applyRemotePush('dev-1', 'local-db:session:error-persisted', {
+ sessionId: 's1',
+ });
+ expect(remoteSessionStore.hasPendingRefresh('s1')).toBe(true);
+
+ const notify = vi.fn();
+ const unsubscribe = remoteSessionStore.subscribe(notify);
+ try {
+ remoteSessionStore.markDeviceOffline('dev-1');
+ expect(remoteSessionStore.hasPendingRefresh('s1')).toBe(false);
+ expect(notify).toHaveBeenCalledTimes(1);
+ } finally {
+ unsubscribe();
+ }
+ });
+
it('removes a device shard with its messages and pending interactions', () => {
remoteSessionStore.setDeviceSessions('dev-1', 'Mac', [session('s1')]);
remoteSessionStore.setDeviceSessions('dev-2', 'Windows', [session('s2')]);
diff --git a/apps/mobile/src/__tests__/scheduleIndex.test.ts b/apps/mobile/src/__tests__/scheduleIndex.test.ts
index 49c0da4fc7..322fd24226 100644
--- a/apps/mobile/src/__tests__/scheduleIndex.test.ts
+++ b/apps/mobile/src/__tests__/scheduleIndex.test.ts
@@ -2,7 +2,10 @@ import { describe, expect, it, vi } from 'vitest';
import type { MobileMakerTransport } from '@/device-link/mobileMakerTransport';
import { unresponsiveDevicesStore } from '@/device-link/unresponsiveDevicesStore';
import {
+ getScheduleIndexInvalidationVersion,
invalidateOfflineScheduleIndexFailureFor,
+ invalidateRunningSessionScheduleEntries,
+ invalidateScheduleIndexForDevice,
invalidateTransientScheduleIndexFailures,
loadSessionScheduleIndex,
loadSessionScheduleIndexThrottled,
@@ -222,6 +225,35 @@ describe('scheduleIndex', () => {
});
});
+ it('clears running only for soft-offline device sessions', () => {
+ const current = new Map<string, RemoteSessionScheduleInfo>([
+ ['session-1', { scheduleId: 'sched-1', scheduleName: 'Daily', scheduleStatus: 'active', allSchedulesStopped: false, unreadRunIds: ['run-1'], unreadCount: 1, running: true, latestRunAt: 2 }],
+ ['session-2', { scheduleId: 'sched-2', scheduleName: 'Weekly', scheduleStatus: 'active', allSchedulesStopped: false, unreadRunIds: [], unreadCount: 0, running: false, latestRunAt: 3 }],
+ ['other-device-session', { scheduleId: 'keep', scheduleName: 'Keep', scheduleStatus: 'paused', allSchedulesStopped: true, unreadRunIds: ['keep-run'], unreadCount: 1, running: true, latestRunAt: 4 }],
+ ]);
+
+ const next = invalidateRunningSessionScheduleEntries(current, ['session-1', 'session-2']);
+
+ expect(next).not.toBe(current);
+ expect(next.get('session-1')).toEqual({
+ ...current.get('session-1'),
+ running: false,
+ });
+ expect(next.get('session-2')).toBe(current.get('session-2'));
+ expect(next.get('other-device-session')).toBe(current.get('other-device-session'));
+ });
+
+ it('keeps the existing map reference when no selected schedule is running', () => {
+ const current = new Map<string, RemoteSessionScheduleInfo>([
+ ['session-1', { scheduleId: 'sched-1', scheduleName: 'Daily', scheduleStatus: 'active', allSchedulesStopped: false, unreadRunIds: [], unreadCount: 0, running: false, latestRunAt: 2 }],
+ ['other-device-session', { scheduleId: 'keep', scheduleName: 'Keep', scheduleStatus: 'active', allSchedulesStopped: false, unreadRunIds: [], unreadCount: 0, running: true, latestRunAt: 1 }],
+ ]);
+
+ const next = invalidateRunningSessionScheduleEntries(current, ['session-1', 'missing']);
+
+ expect(next).toBe(current);
+ });
+
it('replaces only entries for the refreshed device sessions', () => {
const current = new Map([
['session-1', { scheduleId: 'old', scheduleName: 'Old', allSchedulesStopped: false, unreadRunIds: ['old-run'], unreadCount: 1, running: false, latestRunAt: 1 }],
@@ -305,6 +337,34 @@ describe('loadSessionScheduleIndexThrottled (单飞 + TTL 节流)', () => {
expect(load).toHaveBeenCalledTimes(2);
});
+ it('offline invalidation evicts success cache and increments generation', async () => {
+ resetScheduleIndexThrottleForTesting();
+ const load = vi.fn()
+ .mockResolvedValueOnce(new Map([['s1', { running: true } as RemoteSessionScheduleInfo]]))
+ .mockResolvedValueOnce(new Map([['s1', { running: false } as RemoteSessionScheduleInfo]]));
+ const now = () => 1000;
+ await loadSessionScheduleIndexThrottled('dev-1', load, { now });
+ const before = getScheduleIndexInvalidationVersion('dev-1');
+ invalidateScheduleIndexForDevice('dev-1');
+ expect(getScheduleIndexInvalidationVersion('dev-1')).toBe(before + 1);
+ const next = await loadSessionScheduleIndexThrottled('dev-1', load, { now });
+ expect(next.get('s1')?.running).toBe(false);
+ expect(load).toHaveBeenCalledTimes(2);
+ });
+
+ it('stale in-flight completion cannot repopulate after offline invalidation', async () => {
+ resetScheduleIndexThrottleForTesting();
+ let resolveLoad!: (value: Map<string, RemoteSessionScheduleInfo>) => void;
+ const load = vi.fn(() => new Promise<Map<string, RemoteSessionScheduleInfo>>((resolve) => {
+ resolveLoad = resolve;
+ }));
+ const first = loadSessionScheduleIndexThrottled('dev-1', load);
+ invalidateScheduleIndexForDevice('dev-1');
+ resolveLoad(new Map([['s1', { running: true } as RemoteSessionScheduleInfo]]));
+ await first;
+ expect(getScheduleIndexInvalidationVersion('dev-1')).toBe(1);
+ });
+
it('失败负缓存:reject 后 TTL 内复用同一次失败不重放批次,过期后正常重试', async () => {
resetScheduleIndexThrottleForTesting();
const load = vi.fn()
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index 010334886c..8bf0f167d4 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -47,7 +47,11 @@ import {
rehydrateDeviceLinkTopics,
type DeviceLinkRehydrateSendOptions,
} from '@/device-link/rehydrate';
-import { invalidateOfflineScheduleIndexFailureFor, invalidateTransientScheduleIndexFailures } from '@/session/scheduleIndex';
+import {
+ invalidateOfflineScheduleIndexFailureFor,
+ invalidateScheduleIndexForDevice,
+ invalidateTransientScheduleIndexFailures,
+} from '@/session/scheduleIndex';
import { isTransientRemoteError } from '@/device-link/remoteRetry';
import { createRnWebSocket } from '@/device-link/rnWebSocket';
import type { MobileGoalStatusPayload } from '@cindy/maker-shared/device-link-contract';
@@ -465,6 +469,8 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
// 目标端真实应答即可证明设备可达,取消上一代 unavailable 留下的宽限清理;
// 不伪造 presence=true,后续权威 false delta 仍可照常过滤并重新计时。
clearOnePresenceWipeTimer(presenceWipeTimersRef.current, deviceId);
+ remoteScheduleEventStore.clearDeviceMirrorInvalidation(deviceId);
+ invalidateOfflineScheduleIndexFailureFor(deviceId);
},
onDeviceRemoteDisabled: (deviceId) => {
// 被控端实时设置已明确关闭远控:这是当前 epoch 的权威终态,
@@ -695,6 +701,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
return;
}
clearOnePresenceWipeTimer(wipeTimers, snap.deviceId);
+ remoteScheduleEventStore.clearDeviceMirrorInvalidation(snap.deviceId);
// 每个「可用」快照都清该设备的 DEVICE_OFFLINE 负缓存(review P1 ×2):
// 主机在手机连上 relay 之前就离线时,presence 只在变化时广播,首个在线
// 快照 recovered=false——只挂 recovered 会漏掉这次恢复,徽标停留到无关
@@ -1304,9 +1311,23 @@ function requireClient(client: DeviceLinkClient | null): DeviceLinkClient {
return client;
}
+function markOfflineDeviceMirror(deviceId: string): void {
+ // 普通离线只清依赖在线连接的 live 投影,保留 session/messages。这样用户切回
+ // 刚看过的会话时先看到 last-known 内容,恢复后 marker 失效会触发后台窗口对账。
+ remoteSessionStore.markDeviceOffline(deviceId);
+ invalidateScheduleIndexForDevice(deviceId);
+ remoteScheduleEventStore.invalidateDeviceMirror(deviceId);
+ evictDeviceProviders(deviceId);
+ evictDeviceModelMeta(deviceId);
+ evictAgentCapabilitiesForDevice(deviceId);
+ evictComposerPaletteCacheForDevice(deviceId);
+}
+
function wipeUnavailableDeviceMirror(deviceId: string): void {
+ invalidateScheduleIndexForDevice(deviceId);
remoteSessionStore.removeDevice(deviceId);
remoteScheduleEventStore.clearDevice(deviceId);
+ remoteScheduleEventStore.clearDeviceMirrorInvalidation(deviceId);
// Drop the cached provider catalog so a returning/re-granted device re-fetches it
// instead of serving a list frozen from a previous connection.
evictDeviceProviders(deviceId);
@@ -1322,7 +1343,7 @@ const basePresenceWipeTimerDeps = {
setTimer: (callback: () => void, delayMs: number) =>
setTimeout(callback, delayMs),
clearTimer: clearTimeout,
- wipe: wipeUnavailableDeviceMirror,
+ wipe: markOfflineDeviceMirror,
};
function scheduleUnavailableDeviceMirrorWipe(
diff --git a/apps/mobile/src/device-link/accessRevoked.ts b/apps/mobile/src/device-link/accessRevoked.ts
index 386d30c9c5..859725d552 100644
--- a/apps/mobile/src/device-link/accessRevoked.ts
+++ b/apps/mobile/src/device-link/accessRevoked.ts
@@ -6,6 +6,8 @@ import { evictAgentCapabilitiesForDevice } from '@/session/agentCapabilitiesCach
import { evictComposerPaletteCacheForDevice } from '@/session/composerPaletteCache';
import { revokedDevicesStore } from '@/device-link/revokedDevicesStore';
import { clearDeviceResponsivenessTrackingFor } from '@/device-link/unresponsiveDevicesStore';
+import { remoteScheduleEventStore } from '@/scheduler/remoteScheduleEvents';
+import { invalidateScheduleIndexForDevice } from '@/session/scheduleIndex';
import {
isAccessRevokedRemoteError,
} from '@cindy/maker-shared/device-link-contract';
@@ -15,6 +17,9 @@ export function markDeviceAccessRevoked(deviceId: string): void {
// 撤权优先于熔断(review P1):清掉该设备的 unresponsive 状态,撤权走自己的
// 专属 UI;后续在途请求的超时也由 settleDeviceSend 按已撤权降级为不定论。
clearDeviceResponsivenessTrackingFor(deviceId);
+ invalidateScheduleIndexForDevice(deviceId);
+ remoteScheduleEventStore.clearDevice(deviceId);
+ remoteScheduleEventStore.clearDeviceMirrorInvalidation(deviceId);
remoteSessionStore.removeDevice(deviceId);
evictDeviceProviders(deviceId);
evictDeviceModelMeta(deviceId);
diff --git a/apps/mobile/src/device-link/presenceDevices.ts b/apps/mobile/src/device-link/presenceDevices.ts
index 243948b51e..34d6840ffe 100644
--- a/apps/mobile/src/device-link/presenceDevices.ts
+++ b/apps/mobile/src/device-link/presenceDevices.ts
@@ -1,4 +1,5 @@
import type { DeviceView, PresenceSnapshot } from '@cindy/device-link';
+import type { DeviceAccessState } from '@cindy/maker-shared/device-list';
import { isControllableDevice } from '@cindy/maker-shared/device-list';
export interface PresenceDevicePatchResult {
@@ -8,6 +9,22 @@ export interface PresenceDevicePatchResult {
becameControllable: boolean;
}
+export type DeviceMirrorCleanupDisposition = 'keep' | 'soft' | 'hard';
+
+/**
+ * 设备列表状态与本地会话镜像的清理边界:
+ * - offline 是可恢复的传输状态,只失效 live 投影,保留最后可见消息;
+ * - remote_disabled / access_revoked 是显式权限终态,必须硬清敏感镜像;
+ * - ready / busy / self 不触碰镜像。
+ */
+export function deviceMirrorCleanupDisposition(
+ state: DeviceAccessState,
+): DeviceMirrorCleanupDisposition {
+ if (state === 'offline') return 'soft';
+ if (state === 'remote_disabled' || state === 'access_revoked') return 'hard';
+ return 'keep';
+}
+
export function patchDeviceViewsWithPresence(
devices: readonly DeviceView[],
snapshot: PresenceSnapshot,
diff --git a/apps/mobile/src/scheduler/remoteScheduleEvents.ts b/apps/mobile/src/scheduler/remoteScheduleEvents.ts
index f11448bc53..f11ad7929c 100644
--- a/apps/mobile/src/scheduler/remoteScheduleEvents.ts
+++ b/apps/mobile/src/scheduler/remoteScheduleEvents.ts
@@ -31,6 +31,11 @@ const emptySnapshot: RemoteScheduleEventSnapshot = Object.freeze({
});
const snapshots = new Map<string, RemoteScheduleEventSnapshot>();
+// Per-device mirror invalidation generation. Unlike event `version`, this survives
+// `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>();
+let mirrorInvalidationSnapshot: ReadonlyMap<string, number> = new Map();
const subs = new Set<() => void>();
function emit(): void {
@@ -61,9 +66,28 @@ export const remoteScheduleEventStore = {
emit();
},
+ invalidateDeviceMirror(deviceId: string): void {
+ if (!deviceId) return;
+ snapshots.delete(deviceId);
+ mirrorInvalidationVersions.set(
+ deviceId,
+ (mirrorInvalidationVersions.get(deviceId) ?? 0) + 1,
+ );
+ mirrorInvalidationSnapshot = new Map(mirrorInvalidationVersions);
+ emit();
+ },
+
+ clearDeviceMirrorInvalidation(deviceId: string): void {
+ if (!mirrorInvalidationVersions.delete(deviceId)) return;
+ mirrorInvalidationSnapshot = new Map(mirrorInvalidationVersions);
+ emit();
+ },
+
clearAll(): void {
- if (snapshots.size === 0) return;
+ if (snapshots.size === 0 && mirrorInvalidationVersions.size === 0) return;
snapshots.clear();
+ mirrorInvalidationVersions.clear();
+ mirrorInvalidationSnapshot = new Map();
emit();
},
@@ -75,12 +99,23 @@ export const remoteScheduleEventStore = {
return this.getSnapshot(deviceId).version;
},
+ getMirrorInvalidationSnapshot(): ReadonlyMap<string, number> {
+ return mirrorInvalidationSnapshot;
+ },
+
subscribe(cb: () => void): () => void {
subs.add(cb);
return () => subs.delete(cb);
},
};
+export function useRemoteScheduleMirrorInvalidations(): ReadonlyMap<string, number> {
+ return useSyncExternalStore(
+ remoteScheduleEventStore.subscribe,
+ remoteScheduleEventStore.getMirrorInvalidationSnapshot,
+ );
+}
+
export function useRemoteScheduleEventSnapshot(deviceId: string): RemoteScheduleEventSnapshot {
return useSyncExternalStore(
remoteScheduleEventStore.subscribe,
diff --git a/apps/mobile/src/session/remoteSessionStore.ts b/apps/mobile/src/session/remoteSessionStore.ts
index b96b067d4d..ee71c3143e 100644
--- a/apps/mobile/src/session/remoteSessionStore.ts
+++ b/apps/mobile/src/session/remoteSessionStore.ts
@@ -2450,6 +2450,34 @@ export const remoteSessionStore = {
if (textFlushed || reconnectCleared) emit();
},
+ /**
+ * 短暂离线只失效依赖实时连接的投影,保留 shard / session / messages / 路由索引。
+ * 恢复后会话页因此走 reopen(旧内容立即可见),而 marker 已删除会强制后台核对
+ * 最新消息窗口,不会把断线前缓存误判为 fresh。
+ */
+ markDeviceOffline(deviceId: string): void {
+ let changed = false;
+ for (const [sessionId, indexedDeviceId] of sessionDeviceIndex) {
+ if (indexedDeviceId !== deviceId) continue;
+ changed = sessionMessageSyncMarkers.delete(sessionId) || changed;
+ changed = livePlanSnapshots.delete(sessionId) || changed;
+ changed = pendingRefreshSessions.delete(sessionId) || changed;
+ changed = pendingInteractions.delete(sessionId) || changed;
+ changed = inputProjections.delete(sessionId) || changed;
+ changed = sessionLiveActivity.delete(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 = streamingAssistantClientIds.delete(sessionId) || changed;
+ changed = pendingLiveAssistantClientIds.delete(sessionId) || changed;
+ changed = writeMakerTurnRunning(sessionId, false) || changed;
+ changed = writeSessionRunStatus(sessionId, EMPTY_SESSION_RUN_STATUS) || changed;
+ }
+ if (changed) emit();
+ },
+
removeDevice(deviceId: string): void {
const hadShard = shards.delete(deviceId);
const hadWorktreePreference = newMakerWorktreePreferences.delete(deviceId);
diff --git a/apps/mobile/src/session/scheduleIndex.ts b/apps/mobile/src/session/scheduleIndex.ts
index 0835cb304d..b0fcc077be 100644
--- a/apps/mobile/src/session/scheduleIndex.ts
+++ b/apps/mobile/src/session/scheduleIndex.ts
@@ -81,6 +81,7 @@ interface ScheduleIndexThrottleEntry {
}
const scheduleIndexThrottleEntries = new Map<string, ScheduleIndexThrottleEntry>();
+const scheduleIndexInvalidationVersions = new Map<string, number>();
/**
* 错误标记匹配:优先结构化 code,兜底 message 文本(review:mobile 各处的
@@ -205,9 +206,29 @@ export function invalidateOfflineScheduleIndexFailureFor(deviceId: string): void
}
}
-/** 测试用:清空节流登记表。 */
+export function invalidateScheduleIndexForDevice(deviceId: string): void {
+ if (!deviceId) return;
+ scheduleIndexThrottleEntries.delete(deviceId);
+ scheduleIndexInvalidationVersions.set(
+ deviceId,
+ (scheduleIndexInvalidationVersions.get(deviceId) ?? 0) + 1,
+ );
+}
+
+/**
+ * Offline invalidation generation for consumers that need to reject a stale
+ * completion from a request which was already in flight when the device went
+ * offline. The generation is monotonic per device and intentionally separate
+ * from the TTL cache entry.
+ */
+export function getScheduleIndexInvalidationVersion(deviceId: string): number {
+ return scheduleIndexInvalidationVersions.get(deviceId) ?? 0;
+}
+
+/** Test-only: clear cache and invalidation generations. */
export function resetScheduleIndexThrottleForTesting(): void {
scheduleIndexThrottleEntries.clear();
+ scheduleIndexInvalidationVersions.clear();
}
export function loadDeviceSessionScheduleIndex(
@@ -219,6 +240,20 @@ export function loadDeviceSessionScheduleIndex(
});
}
+export function invalidateRunningSessionScheduleEntries(
+ current: Map<string, RemoteSessionScheduleInfo>,
+ sessionIds: Iterable<string>,
+): Map<string, RemoteSessionScheduleInfo> {
+ let next: Map<string, RemoteSessionScheduleInfo> | null = null;
+ for (const sessionId of sessionIds) {
+ const info = current.get(sessionId);
+ if (!info?.running) continue;
+ next ??= new Map(current);
+ next.set(sessionId, { ...info, running: false });
+ }
+ return next ?? current;
+}
+
export function replaceSessionScheduleIndexEntries(
current: Map<string, RemoteSessionScheduleInfo>,
sessionIds: Iterable<string>,
diff --git a/packages/maker-shared/src/__tests__/deviceList.test.ts b/packages/maker-shared/src/__tests__/deviceList.test.ts
index 2a893c82ac..75868ce7ef 100644
--- a/packages/maker-shared/src/__tests__/deviceList.test.ts
+++ b/packages/maker-shared/src/__tests__/deviceList.test.ts
@@ -48,6 +48,7 @@ describe('shared device list presentation model', () => {
expect(deviceAccessState(device({ busy: true }))).toBe('busy');
expect(deviceAccessState(device({ deviceId: 'revoked' }), new Set(['revoked']))).toBe('access_revoked');
expect(deviceAccessState(device({ online: false }))).toBe('offline');
+ expect(deviceAccessState(device({ online: false, remoteControlEnabled: false }))).toBe('offline');
expect(deviceAccessState(device({ remoteControlEnabled: false }))).toBe('remote_disabled');
expect(deviceAccessState(device({ isSelf: true }))).toBe('self');
});