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): 回首页不再整份重拉各电脑任务列表与自动化索引 (#5668)

Dash7cdf45d59a21
diff --git a/apps/mobile/app/sessions/[sessionId].tsx b/apps/mobile/app/sessions/[sessionId].tsx
index c246b1fb95..1e8e8efae9 100644
--- a/apps/mobile/app/sessions/[sessionId].tsx
+++ b/apps/mobile/app/sessions/[sessionId].tsx
@@ -567,6 +567,7 @@ import {
} from '@/session/messageRenderStreamingCache';
import { shouldSuppressEmptyMessageState } from '@/session/sessionEmptyState';
import { deferScheduleIndexHydration } from '@/session/scheduleIndexDefer';
+import { sessionMayHaveScheduleRuns } from '@/session/scheduleIndex';
import { markSessionScheduleRunsRead, unreadRunIdFromProjection } from '@/session/scheduleRunRead';
import { useRemoteScheduleEventSnapshot } from '@/scheduler/remoteScheduleEvents';
import { buildSessionNativeShellLayout } from '@/session/mobileNativeShellLayout';
@@ -2305,6 +2306,7 @@ export default function SessionScreen() {
const completedRunId = unreadRunIdFromProjection(scheduleEventSnapshot.lastProjection, sessionId);
// 同一轻量索引同时提供历史失败提示和未读记录;已读不会消除历史失败。
const scheduleNoticeSource = JSON.stringify([getActiveMobileSessionRealm(), auth.user?.id, deviceId, sessionId]);
+ const sessionSourceForSchedule = currentSession?.source;
const [scheduleFailure, setScheduleFailure] = useState<{ source: string; run?: FailedScheduleRunSnapshot } | null>(null);
// —— 会话未读「真实展示即已读」回执 ——
// 手机端打开会话且**本次连接代已完成整窗同步**后,驻留满 dwell 把被控端该会话的
@@ -2362,12 +2364,15 @@ export default function SessionScreen() {
let active = true;
const isActive = () => active && messageScreenFocusedRef.current && messageAppActiveRef.current;
const cancel = deferScheduleIndexHydration(() => {
+ // An ordinary task has no automation runs to mark read or failures to show. Skip the
+ // device-wide index scan when the current index already says this task is unbound.
+ if (!sessionMayHaveScheduleRuns(deviceId, sessionId, sessionSourceForSchedule)) return;
void withTransientRemoteRetry(() => markSessionScheduleRunsRead(maker, sessionId, deviceId, isActive, {
onIndex: (index) => setScheduleFailure({ source: scheduleNoticeSource, run: index.get(sessionId)?.latestFailedRun }),
})).catch(() => undefined);
});
return () => { active = false; cancel(); };
- }, [appStateActive, connectionEpoch, deviceId, invoke, maker, remoteHistoryAvailable, scheduleEventSnapshot.sessionIndexVersion, scheduleNoticeSource, sessionId]));
+ }, [appStateActive, connectionEpoch, deviceId, invoke, maker, remoteHistoryAvailable, scheduleEventSnapshot.sessionIndexVersion, scheduleNoticeSource, sessionId, sessionSourceForSchedule]));
useFocusEffect(useCallback(() => {
if (!appStateActive || !remoteHistoryAvailable || !completedRunId) return;
void maker.schedule.markRunRead(completedRunId).catch(() => undefined);
diff --git a/apps/mobile/src/__tests__/deviceLinkTraffic.test.ts b/apps/mobile/src/__tests__/deviceLinkTraffic.test.ts
new file mode 100644
index 0000000000..c6280401db
--- /dev/null
+++ b/apps/mobile/src/__tests__/deviceLinkTraffic.test.ts
@@ -0,0 +1,63 @@
+import { afterEach, describe, expect, it } from 'vitest';
+import {
+ formatDeviceLinkTrafficReport,
+ meterDeviceLinkInvokes,
+ recordDeviceLinkPush,
+ recordDeviceLinkWireFrame,
+ resetDeviceLinkTraffic,
+ setDeviceLinkTrafficMeterEnabled,
+ snapshotDeviceLinkTraffic,
+} from '@/debug/deviceLinkTraffic';
+
+afterEach(() => {
+ setDeviceLinkTrafficMeterEnabled(false);
+ resetDeviceLinkTraffic();
+});
+
+describe('dev device-link traffic meter', () => {
+ it('stays inert outside dev builds', async () => {
+ setDeviceLinkTrafficMeterEnabled(false);
+ const client = { invoke: async () => ({ ok: true, result: [1, 2, 3] }) };
+ const original = client.invoke;
+ meterDeviceLinkInvokes(client);
+ expect(client.invoke).toBe(original);
+ recordDeviceLinkPush('local-db:sessions:patched', { title: 'x' });
+ recordDeviceLinkWireFrame('in', 'frame');
+ expect(snapshotDeviceLinkTraffic()).toMatchObject({ channels: {}, wire: { inBytes: 0, inFrames: 0 } });
+ });
+
+ it('counts requests, results and pushes per channel without keeping their content', async () => {
+ setDeviceLinkTrafficMeterEnabled(true);
+ const client = {
+ calls: 0,
+ async invoke(_dst: string, payload: { channel: string; args?: unknown[] }) {
+ this.calls += 1;
+ if (payload.channel === 'boom') throw new Error('offline');
+ return { ok: true, result: [{ title: '任务' }] };
+ },
+ };
+ meterDeviceLinkInvokes(client);
+ await client.invoke('dev', { channel: 'local-db:sessions:list', args: [200] });
+ await client.invoke('dev', { channel: 'local-db:sessions:list', args: [200] });
+ await expect(client.invoke('dev', { channel: 'boom' })).rejects.toThrow('offline');
+ recordDeviceLinkPush('local-db:sessions:patched', { sessionId: 's', patch: { title: '标题' } });
+ recordDeviceLinkWireFrame('in', '{"v":1}');
+ recordDeviceLinkWireFrame('out', 'é');
+
+ const snapshot = snapshotDeviceLinkTraffic();
+ expect(client.calls).toBe(3);
+ const list = snapshot.channels['local-db:sessions:list'];
+ expect(list.invokes).toBe(2);
+ expect(list.requestBytes).toBe(2 * JSON.stringify({ channel: 'local-db:sessions:list', args: [200] }).length);
+ // UTF-8 length: "任务" is 6 bytes, not 2 UTF-16 units.
+ expect(list.resultBytes).toBe(2 * (JSON.stringify({ ok: true, result: [{ title: '' }] }).length + 6));
+ expect(snapshot.channels.boom).toMatchObject({ invokes: 1, resultBytes: 0 });
+ expect(snapshot.channels['local-db:sessions:patched']).toMatchObject({ pushes: 1 });
+ expect(snapshot.wire).toEqual({ inBytes: 7, inFrames: 1, outBytes: 2, outFrames: 1 });
+ expect(JSON.stringify(snapshot)).not.toMatch(/任务|标题|sessionId|"dev"/);
+ expect(formatDeviceLinkTrafficReport(snapshot)).toContain('local-db:sessions:list invoke×2');
+
+ resetDeviceLinkTraffic();
+ expect(snapshotDeviceLinkTraffic().channels).toEqual({});
+ });
+});
diff --git a/apps/mobile/src/__tests__/homeListFreshness.test.ts b/apps/mobile/src/__tests__/homeListFreshness.test.ts
new file mode 100644
index 0000000000..32763018bc
--- /dev/null
+++ b/apps/mobile/src/__tests__/homeListFreshness.test.ts
@@ -0,0 +1,266 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { rehydrateDeviceLinkPeer, type DeviceLinkRehydrateDeps } from '@/device-link/rehydrate';
+import {
+ createHomeListFreshness,
+ HOME_LIST_FOCUS_REUSE_MAX_MS,
+ planHomeListFocusReturn,
+} from '@/session/homeListFreshness';
+import { remoteSessionStore } from '@/session/remoteSessionStore';
+
+/**
+ * Drives the freshness planner the way Home does: a successful full pull marks a device fresh,
+ * reseed requests (registered per device, as Home's handler does) invalidate it, and returning
+ * to Home refills only the devices the planner reports as stale.
+ */
+function createHarness(deviceIds: readonly string[]) {
+ const freshness = createHomeListFreshness();
+ const invoke = vi.fn(async (_deviceId: string, _channel: string) => []);
+ const unregister = deviceIds.map((deviceId) => remoteSessionStore.registerReseedHandler(deviceId, () => {
+ freshness.invalidate(deviceId);
+ }));
+ /** Mirrors hydrateDeviceSessionsOnce: capture → list → markFresh (bounded when truncated). */
+ const hydrate = async (deviceId: string, beforeResponse?: () => void, truncated = false) => {
+ const token = freshness.capture(deviceId);
+ await invoke(deviceId, 'local-db:sessions:list');
+ beforeResponse?.();
+ freshness.markFresh(
+ deviceId,
+ token,
+ truncated ? remoteSessionStore.captureDeviceSessionListMutationEpoch(deviceId) : null,
+ );
+ };
+ const returnHome = async (options: { awayMs?: number; forceFull?: boolean } = {}) => {
+ const now = 1_000_000;
+ const plan = planHomeListFocusReturn({
+ forceFull: options.forceFull ?? false,
+ blurredAt: now - (options.awayMs ?? 5_000),
+ lastSyncedAt: now - 60_000,
+ now,
+ deviceIds,
+ freshness,
+ listMutationEpoch: (deviceId) => remoteSessionStore.captureDeviceSessionListMutationEpoch(deviceId),
+ });
+ for (const deviceId of plan.kind === 'full' ? deviceIds : plan.deviceIds) await hydrate(deviceId);
+ return plan;
+ };
+ const listCalls = () => invoke.mock.calls.filter(([, channel]) => channel === 'local-db:sessions:list')
+ .map(([deviceId]) => deviceId);
+ const dispose = () => { for (const off of unregister) off(); };
+ cleanups.push(dispose);
+ return { freshness, hydrate, invoke, listCalls, returnHome };
+}
+
+const cleanups: Array<() => void> = [];
+afterEach(() => { while (cleanups.length) cleanups.pop()!(); });
+
+/** Minimal device-link recovery dependencies: the peer is reachable and every step succeeds. */
+function recoveryDeps(): DeviceLinkRehydrateDeps {
+ return {
+ createDeviceSendCohort: () => 1,
+ capturePresenceEpoch: () => 0,
+ captureResponseEvidenceEpoch: () => 0,
+ isPresenceEpochCurrent: () => true,
+ isResponseEvidenceEpochCurrent: () => true,
+ openLink: () => ({ capturedPresenceEpoch: 0, capturedResponseEvidenceEpoch: 0, request: Promise.resolve() }),
+ subscribe: async () => undefined,
+ requestSessionsReseed: (deviceId) => remoteSessionStore.requestReseed(deviceId),
+ rebuildSessionSnapshot: async () => undefined,
+ };
+}
+
+describe('Home list freshness on return', () => {
+ it('home → task → back does not re-pull any device list', async () => {
+ const home = createHarness(['mac', 'pc']);
+ await home.hydrate('mac');
+ await home.hydrate('pc');
+ home.invoke.mockClear();
+
+ for (let round = 0; round < 3; round += 1) {
+ expect(await home.returnHome()).toEqual({ kind: 'refill', deviceIds: [] });
+ }
+ expect(home.listCalls()).toEqual([]);
+ });
+
+ it('re-pulls only the device whose list asked for a reseed while Home was covered', async () => {
+ const home = createHarness(['mac', 'pc']);
+ await home.hydrate('mac');
+ await home.hydrate('pc');
+ home.invoke.mockClear();
+
+ remoteSessionStore.applyRemotePush('pc', 'local-db:sessions:created', {});
+ expect(await home.returnHome()).toEqual({ kind: 'refill', deviceIds: ['pc'] });
+ expect(home.listCalls()).toEqual(['pc']);
+ expect(await home.returnHome()).toEqual({ kind: 'refill', deviceIds: [] });
+ });
+
+ it('re-pulls a device after device-link recovery replays its sessions subscription', async () => {
+ // Peer reset, reconnect and foreground return all recover through this replay; it ends with
+ // a sessions reseed for that one device only.
+ const home = createHarness(['mac', 'pc', 'mini']);
+ for (const deviceId of ['mac', 'pc', 'mini']) await home.hydrate(deviceId);
+ home.invoke.mockClear();
+
+ await rehydrateDeviceLinkPeer({ deviceId: 'pc', openLink: false, topics: ['sessions'] }, recoveryDeps());
+ expect(await home.returnHome()).toEqual({ kind: 'refill', deviceIds: ['pc'] });
+ expect(home.listCalls()).toEqual(['pc']);
+ });
+
+ it('re-pulls a device whose list was cut at the page limit once any list push arrived', async () => {
+ // Over LIST_LIMIT tasks: an archive or an outside task's activity changes which tasks belong
+ // in the window, which local patches cannot fill in. A complete list keeps reusing patches.
+ const home = createHarness(['big', 'small']);
+ await home.hydrate('big', undefined, true);
+ await home.hydrate('small');
+ home.invoke.mockClear();
+ expect(await home.returnHome()).toEqual({ kind: 'refill', deviceIds: [] });
+
+ for (const deviceId of ['big', 'small']) {
+ remoteSessionStore.applyRemotePush(deviceId, 'local-db:sessions:patched', { sessionId: 'old', patch: { status: 'archived' } });
+ }
+ expect(await home.returnHome()).toEqual({ kind: 'refill', deviceIds: ['big'] });
+ expect(home.listCalls()).toEqual(['big']);
+ });
+
+ it('keeps a device stale when a reseed lands while its list request is in flight', async () => {
+ const home = createHarness(['mac']);
+ await home.hydrate('mac', () => remoteSessionStore.requestReseed('mac'));
+ expect(home.freshness.isFresh('mac')).toBe(false);
+ });
+
+ it('falls back to a full reload after background, reconnect or a long stay away', async () => {
+ const home = createHarness(['mac', 'pc']);
+ await home.hydrate('mac');
+ await home.hydrate('pc');
+ home.invoke.mockClear();
+
+ expect(await home.returnHome({ forceFull: true })).toEqual({ kind: 'full' });
+ expect(await home.returnHome({ awayMs: HOME_LIST_FOCUS_REUSE_MAX_MS })).toEqual({ kind: 'full' });
+ expect(home.listCalls()).toEqual(['mac', 'pc', 'mac', 'pc']);
+
+ home.freshness.invalidateAll(); // app went to the background
+ expect(await home.returnHome()).toEqual({ kind: 'refill', deviceIds: ['mac', 'pc'] });
+ });
+
+ it('needs a completed first sync before reusing the mirror', () => {
+ const freshness = createHomeListFreshness();
+ const input = { forceFull: false, now: 10_000, deviceIds: ['mac'], freshness, listMutationEpoch: () => 0 };
+ expect(planHomeListFocusReturn({ ...input, blurredAt: 9_000, lastSyncedAt: null })).toEqual({ kind: 'full' });
+ expect(planHomeListFocusReturn({ ...input, blurredAt: null, lastSyncedAt: 1 })).toEqual({ kind: 'full' });
+ expect(planHomeListFocusReturn({ ...input, blurredAt: 11_000, lastSyncedAt: 1 })).toEqual({ kind: 'full' });
+ });
+
+ it('forgets a device that leaves the sync scope and re-pulls it when it becomes visible again', async () => {
+ const home = createHarness(['mac']);
+ await home.hydrate('mac');
+ home.freshness.invalidate('mac'); // scope release (hidden / offline) invalidates
+ home.invoke.mockClear();
+ expect(await home.returnHome()).toEqual({ kind: 'refill', deviceIds: ['mac'] });
+ expect(home.listCalls()).toEqual(['mac']);
+ });
+
+ it('starts over for a new account', async () => {
+ const home = createHarness(['mac']);
+ await home.hydrate('mac');
+ home.freshness.clear();
+ expect(home.freshness.isFresh('mac')).toBe(false);
+ });
+});
+
+describe('Home list sync wiring', () => {
+ const source = readFileSync(resolve(process.cwd(), 'src/session/HomeSurface.tsx'), 'utf8').replace(/\r\n/g, '\n');
+
+ it('keeps the visible-device sync scope while Home is covered', () => {
+ const scope = source.slice(source.indexOf('const homeSyncDeviceIds = useMemo('), source.indexOf('const homeSyncDeviceIdSet'));
+ expect(scope).toContain('resolveHomeDeviceSyncIds(');
+ expect(scope).not.toContain('screenFocused');
+ // Devices that stop being visible/usable are still released and unsubscribed.
+ const reconcile = source.slice(source.indexOf('const reconcileHomeDeviceSyncScope'), source.indexOf('useEffect(() => () => {'));
+ expect(reconcile).toMatch(/for \(const deviceId of diff\.release\) \{[\s\S]*homeListFreshnessRef\.current\.invalidate\(deviceId\);[\s\S]*releaseHomeListOwner\(deviceId\);/);
+ expect(source).toContain("void unsubscribe(HOME_LIST_SUBSCRIPTION_OWNER, deviceId, ['sessions']).catch(() => undefined);");
+ });
+
+ it('records freshness only after a successful list pull and invalidates on failure', () => {
+ const hydrate = source.slice(source.indexOf('const hydrateDeviceSessionsOnce = useCallback('), source.indexOf('const hydrateDeviceSessions = useCallback('));
+ const capture = hydrate.indexOf('homeListFreshnessRef.current.capture(device.deviceId)');
+ const subscribe = hydrate.indexOf("await subscribe(HOME_LIST_SUBSCRIPTION_OWNER, device.deviceId, ['sessions']);");
+ const list = hydrate.indexOf("'local-db:sessions:list'");
+ const applied = hydrate.indexOf('remoteSessionStore.setDeviceSessions(');
+ const fresh = hydrate.indexOf('homeListFreshnessRef.current.markFresh(');
+ expect(capture).toBeGreaterThan(-1);
+ expect(capture).toBeLessThan(subscribe);
+ expect(subscribe).toBeLessThan(list);
+ expect(applied).toBeLessThan(fresh);
+ expect(hydrate.slice(hydrate.indexOf('} catch (err) {'))).toContain('homeListFreshnessRef.current.invalidate(device.deviceId);');
+ });
+
+ it('refills only stale devices on focus return and keeps the full sync for other triggers', () => {
+ const focus = source.slice(source.indexOf('const refillStaleHomeDevices = useCallback('), source.indexOf('// 把当前权威设备列表注入 remoteSessionStore'));
+ expect(focus).toContain('screenFocusedRef.current = true;');
+ expect(focus).toContain('const plan = planHomeListFocusReturn({');
+ expect(focus).toMatch(/if \(plan\.kind === 'refill'\) \{\s*refillStaleHomeDevices\(plan\.deviceIds\);\s*if \(scheduleDirty\.size > 0\) refreshHomeScheduleIndexes\(scheduleDirty\);\s*return;\s*\}\s*refreshHomeScheduleIndexes\(\);\s*startSilentHomeSync\(\);/);
+ expect(focus).toContain("if (nextState === 'background') homeListFreshnessRef.current.invalidateAll();");
+ expect(focus).toContain("if (nextState === 'active') startSilentHomeSync();");
+ });
+
+ it('keeps a full-reload request from every full-sync trigger until a loadHome started after it commits', () => {
+ // Invariant: any trigger needing a full sync (mount, foreground, reconnect, a full focus return,
+ // dependency changes) leaves a request that only a later-started, committed loadHome clears.
+ // A sync that fails, is skipped while covered or exits because Home blurred mid-flight keeps it,
+ // so a quick return cannot downgrade to a device-row refill and miss bound/unbound computers.
+ const silent = source.slice(source.indexOf('const startSilentHomeSync = useCallback(() => {'), source.indexOf('}, [deviceIdentityCacheReady, homeListCacheHydrated'));
+ expect(silent.indexOf('requestHomeFullReload();')).toBeGreaterThan(-1);
+ expect(silent.indexOf('requestHomeFullReload();')).toBeLessThan(silent.indexOf('if (!screenFocusedRef.current) return;'));
+ // Single funnel: no other call site sets the request, nothing but a commit or account reset clears it.
+ expect(source.match(/requestHomeFullReload\(\);/g)).toHaveLength(1);
+ expect(source.match(/homeFullReloadOnFocusRef\.current = null/g)).toHaveLength(2);
+ const focus = source.slice(source.indexOf('useFocusEffect(\n useCallback(() => {\n // The focus event'));
+ const focusBody = focus.slice(0, focus.indexOf('}, [refillStaleHomeDevices'));
+ expect(focusBody).toContain('const forceFull = homeFullReloadOnFocusRef.current !== null;');
+ const load = source.slice(source.indexOf('const loadHome = useCallback('), source.indexOf('loadHomeRef.current = loadHome;'));
+ expect(load.indexOf('const fullReloadRequestAtStart = homeFullReloadOnFocusRef.current;'))
+ .toBeLessThan(load.indexOf('const rawTask = (async () => {'));
+ // Blurring after the device-list read exits before the commit, leaving the request in place.
+ expect(load.indexOf('if (!screenFocusedRef.current) return;')).toBeLessThan(load.indexOf('lastSyncedAtRef.current = now;'));
+ const commit = load.slice(load.indexOf('lastSyncedAtRef.current = now;'));
+ expect(commit).toContain('if (homeFullReloadOnFocusRef.current === fullReloadRequestAtStart) homeFullReloadOnFocusRef.current = null;');
+ });
+
+ it('refreshes automation badges on return only for devices that sent schedule events while away', () => {
+ const events = source.slice(source.indexOf('useEffect(() => remoteScheduleEventStore.subscribe('), source.indexOf('const refreshHomeScheduleIndexes = useCallback('));
+ expect(events).toMatch(/if \(!screenFocusedRef\.current\) \{\s*markHomeScheduleIndexDirty\(deviceId\);\s*continue;\s*\}\s*refreshDeviceScheduleIndex\(deviceId, sessionIds\);/);
+ // The old unconditional "refresh every device on focus" effect is gone.
+ expect(source).not.toContain('兜底刷新一次 scheduleIndex');
+ const focus = source.slice(source.indexOf('useFocusEffect(\n useCallback(() => {\n // The focus event'));
+ expect(focus.indexOf('screenFocusedRef.current = true;')).toBeLessThan(focus.indexOf('refreshHomeScheduleIndexes('));
+ expect(focus).toContain('const scheduleDirty = new Set(homeScheduleIndexDirtyRef.current.keys());');
+ });
+
+ it('keeps automation badge refreshes pending until one is applied', () => {
+ const refresh = source.slice(source.indexOf('const refreshDeviceScheduleIndex = useCallback('), source.indexOf('const hydrateDeviceSessionsOnce = useCallback('));
+ // Recorded before the focus gate, so a skipped refresh or a dropped in-flight result is refilled on return.
+ expect(refresh.indexOf('const pendingSeq = markHomeScheduleIndexDirty(deviceId);'))
+ .toBeLessThan(refresh.indexOf("if (!screenFocusedRef.current || AppState.currentState !== 'active') return;"));
+ const apply = refresh.slice(refresh.indexOf('setScheduleIndex((current) => replaceSessionScheduleIndexEntries('));
+ expect(apply).toMatch(/if \(homeScheduleIndexDirtyRef\.current\.get\(deviceId\) === pendingSeq\) \{\s*homeScheduleIndexDirtyRef\.current\.delete\(deviceId\);/);
+ const hydrate = source.slice(source.indexOf('const hydrateDeviceSessionsOnce = useCallback('), source.indexOf('const hydrateDeviceSessions = useCallback('));
+ expect(hydrate.indexOf('markHomeScheduleIndexDirty(device.deviceId);'))
+ .toBeLessThan(hydrate.indexOf('scheduleIndexDeferRegistryRef.current.schedule(device.deviceId'));
+ expect(hydrate).toContain('nextSessions.length >= LIST_LIMIT');
+ expect(hydrate).toContain('remoteSessionStore.captureDeviceSessionListMutationEpoch(device.deviceId)');
+ });
+
+ it('marks a device stale whenever its list asks for a reseed, even while Home is covered', () => {
+ const reseed = source.slice(source.indexOf('remoteSessionStore.registerReseedHandler(item.device.deviceId'));
+ expect(reseed.indexOf('homeListFreshnessRef.current.invalidate(item.device.deviceId);'))
+ .toBeLessThan(reseed.indexOf('void hydrateDeviceSessions(item.device, accountGeneration'));
+ });
+
+ it('clears freshness with the rest of the account-owned Home state', () => {
+ const reset = source.slice(source.indexOf('useLayoutEffect(() => {\n syncInFlightRef.current = null;'), source.indexOf('}, [accountGeneration]);'));
+ expect(reset).toContain('homeListFreshnessRef.current.clear();');
+ expect(reset).toContain('homeFullReloadOnFocusRef.current = null;');
+ expect(reset).toContain('homeScheduleIndexDirtyRef.current.clear();');
+ });
+});
diff --git a/apps/mobile/src/__tests__/homeListPatchWhileCovered.test.tsx b/apps/mobile/src/__tests__/homeListPatchWhileCovered.test.tsx
new file mode 100644
index 0000000000..560fdf04f5
--- /dev/null
+++ b/apps/mobile/src/__tests__/homeListPatchWhileCovered.test.tsx
@@ -0,0 +1,53 @@
+// @vitest-environment jsdom
+import { act, createElement } from 'react';
+import { createRoot } from 'react-dom/client';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { RemoteSessionStoreSubscriptionGate, remoteSessionStore, useRemoteSessions } from '@/session/remoteSessionStore';
+import type { RemoteSession } from '@/session/types';
+
+Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
+const container = document.createElement('div');
+let root: ReturnType<typeof createRoot> | undefined;
+
+beforeEach(() => remoteSessionStore.clear());
+afterEach(() => {
+ act(() => root?.unmount());
+ root = undefined;
+ remoteSessionStore.clear();
+ vi.restoreAllMocks();
+});
+
+function row(id: string, patch: Partial<RemoteSession> = {}): RemoteSession {
+ return {
+ id, userId: 'owner', title: id, status: 'active', workingDir: '/repo', workspaceKind: 'project',
+ model: 'model', agentKind: 'codex', effort: '', permissionMode: 'default', fastMode: false,
+ userSendAt: null, createdAt: '2026-01-01T00:00:00Z', updatedAt: '2026-01-01T00:00:00Z', ...patch,
+ };
+}
+
+function Titles() {
+ return useRemoteSessions().map((session) => session.title).join(',');
+}
+
+// Home keeps its `sessions` subscription while a task page covers it. Pushes that land in that
+// window must be on screen as soon as Home is visible again, without a fresh list pull.
+it('shows list patches received while Home was covered as soon as Home returns', () => {
+ remoteSessionStore.setDeviceSessions('mac', 'Mac', [row('a'), row('b')]);
+ root = createRoot(container);
+ const render = (enabled: boolean) => act(() => root!.render(
+ createElement(RemoteSessionStoreSubscriptionGate, { enabled, children: createElement(Titles) }),
+ ));
+ render(true);
+ expect(container.textContent).toBe('a,b');
+
+ render(false);
+ act(() => {
+ remoteSessionStore.applyRemotePush('mac', 'local-db:sessions:patched', { sessionId: 'a', patch: { title: 'renamed' } });
+ remoteSessionStore.applyRemotePush('mac', 'local-db:sessions:patched', { sessionId: 'b', patch: { status: 'archived' } });
+ });
+ // Covered Home does not re-render for each push.
+ expect(container.textContent).toBe('a,b');
+
+ render(true);
+ expect(container.textContent).toBe('renamed');
+});
diff --git a/apps/mobile/src/__tests__/remoteListIncludePinned.test.ts b/apps/mobile/src/__tests__/remoteListIncludePinned.test.ts
index b5078e6991..d859d31faf 100644
--- a/apps/mobile/src/__tests__/remoteListIncludePinned.test.ts
+++ b/apps/mobile/src/__tests__/remoteListIncludePinned.test.ts
@@ -22,7 +22,11 @@ describe('mobile remote session bootstrap', () => {
expect(detailSource).toContain('loadSharedSessionScheduleIndex(deviceId, maker, canLoadScheduleIndex)');
expect(detailSource).not.toContain('{ force: true }');
expect(eventSource).toContain('projection.refresh.sessionIndex || projection.refresh.scheduleList || clearsUnread');
- expect(eventSource).toContain('invalidateScheduleIndexForDevice(deviceId)');
+ // Events invalidate the shared index centrally (and keep the task-page binding record current).
+ expect(eventSource).toContain('noteScheduleEventInIndexCache(deviceId, {');
+ expect(eventSource).toContain('invalidate: projection.refresh.sessionIndex || projection.refresh.scheduleList || clearsUnread,');
+ const indexSource = readFileSync(resolve(process.cwd(), 'src/session/scheduleIndex.ts'), 'utf8');
+ expect(indexSource).toContain('if (change.invalidate) invalidateScheduleIndexForDevice(deviceId);');
expect(detailSource).toContain('scheduleEventSnapshot.scheduleListVersion,');
expect(detailSource).toContain('scheduleEventSnapshot.unreadClearVersion,');
});
diff --git a/apps/mobile/src/__tests__/scheduleIndexSessionGate.test.ts b/apps/mobile/src/__tests__/scheduleIndexSessionGate.test.ts
new file mode 100644
index 0000000000..9cfd9e69f1
--- /dev/null
+++ b/apps/mobile/src/__tests__/scheduleIndexSessionGate.test.ts
@@ -0,0 +1,110 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import type { MobileMakerTransport } from '@/device-link/mobileMakerTransport';
+import { remoteScheduleEventStore } from '@/scheduler/remoteScheduleEvents';
+import {
+ clearSessionScheduleIndexCache,
+ invalidateScheduleIndexForDevice,
+ loadSharedSessionScheduleIndex,
+ sessionMayHaveScheduleRuns,
+} from '@/session/scheduleIndex';
+
+afterEach(() => clearSessionScheduleIndexCache());
+
+function maker() {
+ const list = vi.fn(async () => [
+ { id: 'heartbeat', name: 'PR heartbeat', status: 'active', targetSessionId: 'pr-task' },
+ { id: 'nightly', name: 'Nightly', status: 'active' },
+ ]);
+ const listSidebarIndexRuns = vi.fn(async () => ({
+ runs: [{ runId: 'r1', scheduleId: 'nightly', scheduleName: 'Nightly', scheduleStatus: 'active', sessionId: 'nightly-run', status: 'success', firedAt: 1 }],
+ }));
+ return { list, listSidebarIndexRuns, maker: { schedule: { list, listSidebarIndexRuns, listRuns: vi.fn() } } as unknown as Pick<MobileMakerTransport, 'schedule'> };
+}
+
+describe('task page schedule index gate', () => {
+ it('loads for any task until the device index is known', () => {
+ expect(sessionMayHaveScheduleRuns('mac', 'ordinary', undefined)).toBe(true);
+ });
+
+ it('skips ordinary tasks once the current index shows they have no automation binding', async () => {
+ const remote = maker();
+ await loadSharedSessionScheduleIndex('mac', remote.maker);
+ expect(sessionMayHaveScheduleRuns('mac', 'ordinary', 'desktop')).toBe(false);
+ // Tasks an automation reuses (targetSessionId) and tasks with runs still load.
+ expect(sessionMayHaveScheduleRuns('mac', 'pr-task', 'desktop')).toBe(true);
+ expect(sessionMayHaveScheduleRuns('mac', 'nightly-run', 'desktop')).toBe(true);
+ // Automation-created tasks always load, even before they appear in an index.
+ expect(sessionMayHaveScheduleRuns('mac', 'brand-new-run', 'scheduler')).toBe(true);
+ // Knowledge is per device.
+ expect(sessionMayHaveScheduleRuns('pc', 'ordinary', 'desktop')).toBe(true);
+ });
+
+ it('stays usable across run events and learns the tasks they bind', async () => {
+ const remote = maker();
+ await loadSharedSessionScheduleIndex('mac', remote.maker);
+ remoteScheduleEventStore.apply('mac', { type: 'completed', scheduleId: 'nightly', runId: 'r2', sessionId: 'nightly-run' });
+ remoteScheduleEventStore.apply('mac', { type: 'read', scheduleId: 'nightly', runId: 'r2' });
+ expect(sessionMayHaveScheduleRuns('mac', 'ordinary', 'desktop')).toBe(false);
+ // A run that lands in a task the index did not know about makes that task load.
+ remoteScheduleEventStore.apply('mac', { type: 'session-bound', scheduleId: 'nightly', runId: 'r3', sessionId: 'ordinary' });
+ expect(sessionMayHaveScheduleRuns('mac', 'ordinary', 'desktop')).toBe(true);
+ expect(sessionMayHaveScheduleRuns('mac', 'other', 'desktop')).toBe(false);
+ // Automation definitions changed (could rebind a task): unknown until the next index.
+ remoteScheduleEventStore.apply('mac', { type: 'changed', scheduleId: 'heartbeat' });
+ expect(sessionMayHaveScheduleRuns('mac', 'other', 'desktop')).toBe(true);
+ remoteScheduleEventStore.clearDevice('mac');
+ });
+
+ it('treats a non-event reset after the index as unknown again', async () => {
+ const remote = maker();
+ await loadSharedSessionScheduleIndex('mac', remote.maker);
+ invalidateScheduleIndexForDevice('mac'); // link recovery / offline
+ expect(sessionMayHaveScheduleRuns('mac', 'ordinary', 'desktop')).toBe(true);
+
+ await loadSharedSessionScheduleIndex('mac', remote.maker);
+ expect(sessionMayHaveScheduleRuns('mac', 'ordinary', 'desktop')).toBe(false);
+ clearSessionScheduleIndexCache(); // account switch
+ expect(sessionMayHaveScheduleRuns('mac', 'ordinary', 'desktop')).toBe(true);
+ });
+
+ it('does not trust an index whose load overlapped a schedule event', async () => {
+ const remote = maker();
+ let release!: () => void;
+ remote.listSidebarIndexRuns.mockImplementationOnce(async () => {
+ await new Promise<void>((resolveRelease) => { release = resolveRelease; });
+ return { runs: [] };
+ });
+ const pending = loadSharedSessionScheduleIndex('mac', remote.maker);
+ await vi.waitFor(() => expect(remote.listSidebarIndexRuns).toHaveBeenCalled());
+ invalidateScheduleIndexForDevice('mac');
+ release();
+ await pending;
+ expect(sessionMayHaveScheduleRuns('mac', 'ordinary', 'desktop')).toBe(true);
+ });
+
+ it('does not let a scan from before an account switch record bindings afterwards', async () => {
+ const remote = maker();
+ let release!: () => void;
+ remote.listSidebarIndexRuns.mockImplementationOnce(async () => {
+ await new Promise<void>((resolveRelease) => { release = resolveRelease; });
+ return { runs: [] };
+ });
+ const oldAccountScan = loadSharedSessionScheduleIndex('mac', remote.maker);
+ await vi.waitFor(() => expect(remote.listSidebarIndexRuns).toHaveBeenCalled());
+ clearSessionScheduleIndexCache(); // account switch: versions restart at 0
+ release();
+ await oldAccountScan;
+ expect(sessionMayHaveScheduleRuns('mac', 'pr-task', 'desktop')).toBe(true);
+ expect(sessionMayHaveScheduleRuns('mac', 'ordinary', 'desktop')).toBe(true);
+ });
+
+ it('gates the task page read-marking scan before it starts', () => {
+ const page = readFileSync(resolve(process.cwd(), 'app/sessions/[sessionId].tsx'), 'utf8').replace(/\r\n/g, '\n');
+ const effect = page.slice(page.indexOf('const cancel = deferScheduleIndexHydration(() => {'));
+ expect(effect.indexOf('if (!sessionMayHaveScheduleRuns(deviceId, sessionId, sessionSourceForSchedule)) return;'))
+ .toBeLessThan(effect.indexOf('markSessionScheduleRunsRead(maker, sessionId, deviceId, isActive'));
+ expect(page).toContain('scheduleNoticeSource, sessionId, sessionSourceForSchedule]));');
+ });
+});
diff --git a/apps/mobile/src/__tests__/scheduleRunRead.test.ts b/apps/mobile/src/__tests__/scheduleRunRead.test.ts
index afa02cde01..f40a051fc3 100644
--- a/apps/mobile/src/__tests__/scheduleRunRead.test.ts
+++ b/apps/mobile/src/__tests__/scheduleRunRead.test.ts
@@ -2,7 +2,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { projectScheduleEvent } from '@cindy/maker-shared/schedule-events';
import type { MobileMakerTransport } from '@/device-link/mobileMakerTransport';
import { markSessionScheduleRunsRead, unreadRunIdFromProjection } from '@/session/scheduleRunRead';
-import { invalidateScheduleIndexForDevice, invalidateScheduleIndexesAfterLinkRecovery, loadSessionScheduleIndex, loadSessionScheduleIndexThrottled, loadSharedSessionScheduleIndex, resetScheduleIndexThrottleForTesting } from '@/session/scheduleIndex';
+import { remoteScheduleEventStore } from '@/scheduler/remoteScheduleEvents';
+import { getScheduleIndexInvalidationVersion, invalidateScheduleIndexForDevice, invalidateScheduleIndexesAfterLinkRecovery, loadSessionScheduleIndex, loadSessionScheduleIndexThrottled, loadSharedSessionScheduleIndex, resetScheduleIndexThrottleForTesting } from '@/session/scheduleIndex';
function makerWith(
runs: readonly Record<string, unknown>[],
@@ -24,6 +25,25 @@ function transientError(message = 'target timed out'): Error & { code: string }
describe('markSessionScheduleRunsRead', () => {
beforeEach(resetScheduleIndexThrottleForTesting);
+ it('applies the read locally so Home reconciles badges even when the host sends no broadcast', async () => {
+ // Already read elsewhere: the host's markRunRead is a no-op and broadcasts nothing.
+ remoteScheduleEventStore.clearDevice('dev-echo');
+ const maker = makerWith(
+ [{ id: 'run-1', scheduleId: 'sched-1', sessionId: 'session-1', status: 'success', firedAt: 1 }],
+ async () => undefined,
+ );
+ const before = remoteScheduleEventStore.getSnapshot('dev-echo').sessionIndexVersion;
+ await expect(markSessionScheduleRunsRead(maker, 'session-1', 'dev-echo')).resolves.toEqual(['run-1']);
+ const after = remoteScheduleEventStore.getSnapshot('dev-echo');
+ expect(after.sessionIndexVersion).toBe(before + 1);
+ expect(after.lastProjection?.runPatch.status).toBe('read');
+ expect(getScheduleIndexInvalidationVersion('dev-echo')).toBeGreaterThan(0);
+
+ // Nothing to mark: no local event.
+ await expect(markSessionScheduleRunsRead(makerWith([], async () => undefined), 'session-2', 'dev-echo')).resolves.toEqual([]);
+ expect(remoteScheduleEventStore.getSnapshot('dev-echo').sessionIndexVersion).toBe(before + 1);
+ remoteScheduleEventStore.clearDevice('dev-echo');
+ });
it('finds runs completed while disconnected even when the old success cache is still fresh', async () => {
const mark = vi.fn(async () => undefined);
const listRuns = vi.fn().mockResolvedValueOnce([]).mockResolvedValue([
diff --git a/apps/mobile/src/debug/deviceLinkTraffic.ts b/apps/mobile/src/debug/deviceLinkTraffic.ts
new file mode 100644
index 0000000000..7e7d2f5b22
--- /dev/null
+++ b/apps/mobile/src/debug/deviceLinkTraffic.ts
@@ -0,0 +1,176 @@
+/**
+ * Dev-only device-link traffic meter.
+ *
+ * Counts how many requests / pushes each channel produced and roughly how many UTF-8 bytes they
+ * carried, so sync changes can be measured on a simulator instead of estimated. It only keeps
+ * per-channel counters in memory: no channel arguments, payload content, device ids or session
+ * ids are stored, and nothing is written to the diagnostic log files or upload pipeline.
+ *
+ * Production builds never enable it, so every record call is a single boolean check there.
+ * Payload sizes are re-serialized JSON lengths (after the transport decoded them), which tracks
+ * the wire size closely; `wire` is the raw WebSocket text frame total including envelopes,
+ * chunk headers and transport ACKs.
+ */
+
+interface ChannelTraffic {
+ invokes: number;
+ requestBytes: number;
+ resultBytes: number;
+ pushes: number;
+ pushBytes: number;
+}
+
+export interface DeviceLinkTrafficSnapshot {
+ since: number;
+ wire: { inBytes: number; inFrames: number; outBytes: number; outFrames: number };
+ channels: Record<string, ChannelTraffic>;
+}
+
+let enabled = typeof __DEV__ !== 'undefined' && __DEV__;
+let since = Date.now();
+let wire = { inBytes: 0, inFrames: 0, outBytes: 0, outFrames: 0 };
+let channels = new Map<string, ChannelTraffic>();
+
+export function deviceLinkTrafficMeterEnabled(): boolean {
+ return enabled;
+}
+
+/** Tests only; release builds keep the compile-time `__DEV__` decision. */
+export function setDeviceLinkTrafficMeterEnabled(next: boolean): void {
+ enabled = next;
+}
+
+function utf8Length(text: string): number {
+ let bytes = 0;
+ for (let index = 0; index < text.length; index += 1) {
+ const code = text.charCodeAt(index);
+ if (code < 0x80) bytes += 1;
+ else if (code < 0x800) bytes += 2;
+ else if (code >= 0xd800 && code <= 0xdbff && index + 1 < text.length) {
+ bytes += 4;
+ index += 1;
+ } else bytes += 3;
+ }
+ return bytes;
+}
+
+function jsonBytes(value: unknown): number {
+ if (value === undefined) return 0;
+ try {
+ return utf8Length(JSON.stringify(value) ?? '');
+ } catch {
+ return 0;
+ }
+}
+
+function channelEntry(channel: string): ChannelTraffic {
+ let entry = channels.get(channel);
+ if (!entry) {
+ entry = { invokes: 0, requestBytes: 0, resultBytes: 0, pushes: 0, pushBytes: 0 };
+ channels.set(channel, entry);
+ }
+ return entry;
+}
+
+export function recordDeviceLinkWireFrame(direction: 'in' | 'out', frame: unknown): void {
+ if (!enabled) return;
+ try {
+ const bytes = utf8Length(String(frame ?? ''));
+ if (direction === 'in') {
+ wire.inBytes += bytes;
+ wire.inFrames += 1;
+ } else {
+ wire.outBytes += bytes;
+ wire.outFrames += 1;
+ }
+ } catch {
+ /* best-effort instrumentation */
+ }
+}
+
+export function recordDeviceLinkInvoke(channel: string, request: unknown, result: unknown): void {
+ if (!enabled) return;
+ const entry = channelEntry(channel);
+ entry.invokes += 1;
+ entry.requestBytes += jsonBytes(request);
+ entry.resultBytes += jsonBytes(result);
+}
+
+export function recordDeviceLinkPush(channel: string, payload: unknown): void {
+ if (!enabled) return;
+ const entry = channelEntry(channel);
+ entry.pushes += 1;
+ entry.pushBytes += jsonBytes(payload);
+}
+
+/**
+ * Wrap a client's `invoke` so every outbound request (business calls, subscribe and unsubscribe
+ * control frames) is counted by channel. A failed request still counts the request it sent.
+ */
+export function meterDeviceLinkInvokes(client: object): void {
+ if (!enabled) return;
+ const target = client as { invoke: (...args: unknown[]) => Promise<unknown> };
+ const original = target.invoke.bind(client);
+ target.invoke = async (...args: unknown[]) => {
+ const payload = args[1] as { channel?: unknown } | undefined;
+ const channel = typeof payload?.channel === 'string' ? payload.channel : '(unknown)';
+ try {
+ const result = await original(...args);
+ recordDeviceLinkInvoke(channel, payload, result);
+ return result;
+ } catch (error) {
+ recordDeviceLinkInvoke(channel, payload, undefined);
+ throw error;
+ }
+ };
+}
+
+export function snapshotDeviceLinkTraffic(): DeviceLinkTrafficSnapshot {
+ return {
+ since,
+ wire: { ...wire },
+ channels: Object.fromEntries([...channels].map(([channel, entry]) => [channel, { ...entry }])),
+ };
+}
+
+export function resetDeviceLinkTraffic(): void {
+ since = Date.now();
+ wire = { inBytes: 0, inFrames: 0, outBytes: 0, outFrames: 0 };
+ channels = new Map();
+}
+
+/** Plain-text table, largest channels first. */
+export function formatDeviceLinkTrafficReport(snapshot = snapshotDeviceLinkTraffic()): string {
+ const kb = (bytes: number) => `${(bytes / 1024).toFixed(1)}KB`;
+ const rows = Object.entries(snapshot.channels)
+ .map(([channel, entry]) => ({ channel, entry, total: entry.requestBytes + entry.resultBytes + entry.pushBytes }))
+ .sort((left, right) => right.total - left.total)
+ .map(({ channel, entry, total }) => (
+ `${channel} invoke×${entry.invokes} req ${kb(entry.requestBytes)} res ${kb(entry.resultBytes)}`
+ + ` push×${entry.pushes} ${kb(entry.pushBytes)} total ${kb(total)}`
+ ));
+ const seconds = Math.round((Date.now() - snapshot.since) / 1000);
+ return [
+ `device-link traffic over ${seconds}s: wire in ${kb(snapshot.wire.inBytes)} (${snapshot.wire.inFrames} frames)`
+ + ` out ${kb(snapshot.wire.outBytes)} (${snapshot.wire.outFrames} frames)`,
+ ...rows,
+ ].join('\n');
+}
+
+declare global {
+ // Dev-only handle for reading the meter from a debugger / inspector session.
+ // eslint-disable-next-line no-var
+ var __cindyDeviceLinkTraffic: {
+ snapshot: typeof snapshotDeviceLinkTraffic;
+ reset: typeof resetDeviceLinkTraffic;
+ report: typeof formatDeviceLinkTrafficReport;
+ } | undefined;
+}
+
+if (enabled) {
+ globalThis.__cindyDeviceLinkTraffic = {
+ snapshot: snapshotDeviceLinkTraffic,
+ reset: resetDeviceLinkTraffic,
+ report: formatDeviceLinkTrafficReport,
+ };
+}
diff --git a/apps/mobile/src/device-link/DeviceLinkContext.tsx b/apps/mobile/src/device-link/DeviceLinkContext.tsx
index e89f7e5551..bb26797615 100644
--- a/apps/mobile/src/device-link/DeviceLinkContext.tsx
+++ b/apps/mobile/src/device-link/DeviceLinkContext.tsx
@@ -164,6 +164,7 @@ import { createOfflineMirrorWipeQueue } from '@/device-link/offlineMirrorWipeQue
import { hasMoreOlderMessages } from '@/session/messagePaging';
import type { InputProjection, PendingInteraction, RemoteMessage } from '@/session/types';
import { prepareVisualMockDeviceLinkContext } from '@/debug/visualMock';
+import { meterDeviceLinkInvokes, recordDeviceLinkPush } from '@/debug/deviceLinkTraffic';
export interface DeviceLinkContextValue {
status: DeviceLinkStatus;
@@ -963,6 +964,7 @@ export function DeviceLinkProvider({ children }: { children: ReactNode }) {
requestTimeoutMs: 15_000,
},
});
+ meterDeviceLinkInvokes(client);
clientRef.current = client;
const catalogRefresh = createDeviceCatalogRefresh({
connectionEpoch: () => connectionEpochRef.current,
@@ -1641,6 +1643,7 @@ export function routeFrame(env: Envelope, handlers: {
if (peerLinkClosed) return;
if (env.kind !== 'push' || !env.src) return;
const push = env.payload as PushPayload;
+ recordDeviceLinkPush(push.channel, push.payload);
dispatchCredentialSwitchOutcome(env.src, push.channel, push.payload);
if (push.channel === 'local-db:task-tags:changed') {
writeTaskTagCatalog(
diff --git a/apps/mobile/src/device-link/rnWebSocket.ts b/apps/mobile/src/device-link/rnWebSocket.ts
index ba417e843f..4262e78afb 100644
--- a/apps/mobile/src/device-link/rnWebSocket.ts
+++ b/apps/mobile/src/device-link/rnWebSocket.ts
@@ -1,4 +1,5 @@
import type { WsLike } from '@cindy/device-link';
+import { recordDeviceLinkWireFrame } from '@/debug/deviceLinkTraffic';
type EventName = 'open' | 'message' | 'close' | 'error';
@@ -29,7 +30,10 @@ class RnWsLike implements WsLike {
) => WebSocket;
this.ws = new WebSocketCtor(url, undefined, { headers });
this.ws.onopen = () => this.emit('open');
- this.ws.onmessage = (event) => this.emit('message', { toString: () => String(event.data ?? '') });
+ this.ws.onmessage = (event) => {
+ recordDeviceLinkWireFrame('in', event.data);
+ this.emit('message', { toString: () => String(event.data ?? '') });
+ };
this.ws.onclose = (event) => this.emit('close', event.code, event.reason);
this.ws.onerror = (event) => {
// RN 的 error 事件带 message(如升级失败的 "Expected HTTP 101 response but
@@ -41,6 +45,7 @@ class RnWsLike implements WsLike {
}
send(data: string): void {
+ recordDeviceLinkWireFrame('out', data);
this.ws.send(data);
}
diff --git a/apps/mobile/src/scheduler/remoteScheduleEvents.ts b/apps/mobile/src/scheduler/remoteScheduleEvents.ts
index 8f26d3ecf1..2b15f331cb 100644
--- a/apps/mobile/src/scheduler/remoteScheduleEvents.ts
+++ b/apps/mobile/src/scheduler/remoteScheduleEvents.ts
@@ -3,7 +3,7 @@ import {
projectScheduleEvent,
type ScheduleEventProjection,
} from '@cindy/maker-shared/schedule-events';
-import { invalidateScheduleIndexForDevice } from '@/session/scheduleIndex';
+import { noteScheduleEventInIndexCache } from '@/session/scheduleIndex';
export interface RemoteScheduleEventSnapshot {
lastProjection: ScheduleEventProjection | null;
@@ -64,9 +64,11 @@ export const remoteScheduleEventStore = {
const prev = snapshots.get(deviceId) ?? emptySnapshot;
// Invalidate once before notifying all screens. Consumer-local force loads
// otherwise launch competing scans for the same authoritative event.
- if (projection.refresh.sessionIndex || projection.refresh.scheduleList || clearsUnread) {
- invalidateScheduleIndexForDevice(deviceId);
- }
+ noteScheduleEventInIndexCache(deviceId, {
+ invalidate: projection.refresh.sessionIndex || projection.refresh.scheduleList || clearsUnread,
+ sessionId: projection.runPatch.sessionId,
+ scheduleListChanged: projection.refresh.scheduleList,
+ });
snapshots.set(deviceId, {
lastProjection: projection,
runsVersion: prev.runsVersion + (projection.refresh.runRefresh.mode === 'none' ? 0 : 1),
diff --git a/apps/mobile/src/session/HomeSurface.tsx b/apps/mobile/src/session/HomeSurface.tsx
index 13daf90e3a..d8bcb860e3 100644
--- a/apps/mobile/src/session/HomeSurface.tsx
+++ b/apps/mobile/src/session/HomeSurface.tsx
@@ -223,6 +223,7 @@ import {
resolveHomeDeviceSyncIds,
runHomeDeviceSyncBatch,
} from '@/session/homeDeviceSync';
+import { createHomeListFreshness, planHomeListFocusReturn } from '@/session/homeListFreshness';
import { serializeNewSessionDeviceOptions } from '@/session/newSession';
import {
buildRemoteSessionCardPreview,
@@ -500,6 +501,28 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
// 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>());
+ // Home 被其它页面盖住时继续持有 `sessions` 订阅、接收增量补丁;回到首页只重拉
+ // 「可能漏了推送」的设备(判据见 homeListFreshness),不再每次整份重拉所有电脑。
+ const homeListFreshnessRef = useRef(createHomeListFreshness());
+ // 最近一次离开首页的时刻;null = 当前在首页(或尚未离开过)。
+ const homeBlurredAtRef = useRef<number | null>(null);
+ // 待完成的整轮重拉(含设备清单),由 startSilentHomeSync 统一登记。值是请求序号,只有在它
+ // 之后开始的 loadHome 整轮成功提交才清除;失败、失焦退出或被跳过时保留,下次回首页仍整轮重拉。
+ const homeFullReloadOnFocusRef = useRef<number | null>(null);
+ const homeFullReloadSeqRef = useRef(0);
+ const requestHomeFullReload = useCallback(() => {
+ homeFullReloadOnFocusRef.current = ++homeFullReloadSeqRef.current;
+ }, []);
+ // 自动化角标待补刷的设备:首页被盖住时收到事件、或刷新被失焦跳过/结果被丢弃。值是登记
+ // 序号,只有同一序号的刷新成功应用后才清除;回首页只刷新这些设备。
+ const homeScheduleIndexDirtyRef = useRef(new Map<string, number>());
+ const homeScheduleIndexDirtySeqRef = useRef(0);
+ const markHomeScheduleIndexDirty = useCallback((deviceId: string) => {
+ const seq = ++homeScheduleIndexDirtySeqRef.current;
+ homeScheduleIndexDirtyRef.current.set(deviceId, seq);
+ return seq;
+ }, []);
+ const homeSyncRowsRef = useRef<ReturnType<typeof toDeviceListItems<DeviceView>>>([]);
const hydrateDeviceSessionsRef = useRef<HydrateDeviceSessions>(async () => ({
failure: null,
offline: false,
@@ -648,6 +671,10 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
homeListOwnedDeviceIdsRef.current.clear();
homeSyncGenerationByDeviceRef.current.clear();
homeHydrateInFlightByDeviceRef.current.clear();
+ homeListFreshnessRef.current.clear();
+ homeBlurredAtRef.current = null;
+ homeFullReloadOnFocusRef.current = null;
+ homeScheduleIndexDirtyRef.current.clear();
scheduleIndexDeferRegistryRef.current.cancelAll();
scheduleEventVersionsRef.current.clear();
presenceFreshnessRef.current = createPresenceFreshnessTracker();
@@ -708,6 +735,7 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
for (const deviceId of diff.release) {
advanceHomeSyncGeneration(deviceId);
+ homeListFreshnessRef.current.invalidate(deviceId);
releaseHomeListOwner(deviceId);
}
for (const deviceId of diff.acquire) {
@@ -757,6 +785,7 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
const markDeviceOffline = useCallback((deviceId: string) => {
// 普通离线是可恢复的传输状态:保留 session/messages,只清 live 投影并失效
// message marker。恢复后会话立即显示 last-known 内容,后台 reopen 再补最新窗口。
+ homeListFreshnessRef.current.invalidate(deviceId);
softInvalidateDeviceMirror(deviceId);
setDevices((current) => {
const next = reconcileDeviceViews(markDeviceViewsOffline(current, new Set([deviceId]))).devices;
@@ -770,11 +799,14 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
sessionIds: readonly string[],
options?: { accountGeneration?: number; homeSyncGeneration?: number },
) => {
- if (!screenFocusedRef.current || AppState.currentState !== 'active') return;
const expectedAccountGeneration = options?.accountGeneration ?? accountGeneration;
+ if (homeAccountGenerationRef.current !== expectedAccountGeneration) return;
+ if (!homeSyncTargetDeviceIdsRef.current.has(deviceId)) return;
+ // 先登记待补刷,成功应用后才清除:失焦跳过、在途结果被丢弃都留给回首页补刷。
+ const pendingSeq = markHomeScheduleIndexDirty(deviceId);
+ if (!screenFocusedRef.current || AppState.currentState !== 'active') return;
const expectedHomeSyncGeneration = options?.homeSyncGeneration
?? homeSyncGenerationByDeviceRef.current.get(deviceId);
- if (homeAccountGenerationRef.current !== expectedAccountGeneration) return;
if (
expectedHomeSyncGeneration === undefined
|| !isCurrentHomeSyncTarget(deviceId, expectedHomeSyncGeneration)
@@ -804,11 +836,14 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
sessionIds,
nextIndex,
));
+ if (homeScheduleIndexDirtyRef.current.get(deviceId) === pendingSeq) {
+ homeScheduleIndexDirtyRef.current.delete(deviceId);
+ }
})
.catch(() => {
// 网络失败时保留旧数据,不清零已有徽标——数据清零只应由明确的"已读"事件触发。
});
- }, [accountGeneration, invoke, isCurrentHomeSyncTarget]);
+ }, [accountGeneration, invoke, isCurrentHomeSyncTarget, markHomeScheduleIndexDirty]);
const hydrateDeviceSessionsOnce = useCallback((
device: DeviceView,
@@ -822,6 +857,7 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
return { failure: null, offline: false, superseded: true };
}
updateDeviceConnectionState(device.deviceId, 'syncing');
+ const freshnessToken = homeListFreshnessRef.current.capture(device.deviceId);
try {
const assertCurrentScope = () => {
if (
@@ -901,6 +937,8 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
// 抢同一条 WS 管道(见 scheduleIndexDefer / issue #324)。home 自动化分组与名称已由 fallbackScheduleInfo
// 兜底,徽标晚半拍出现即可。
// 按设备 id 登记:同设备上一轮还没执行的延后任务会被先取消,避免较早回调用旧 nextSessions 覆盖新状态。
+ // 延后刷新若因首页失焦被跳过,回首页时补刷(列表已标新鲜,不会再触发 hydrate)。
+ markHomeScheduleIndexDirty(device.deviceId);
scheduleIndexDeferRegistryRef.current.schedule(device.deviceId, () => {
void (async () => {
while (syncInFlightRef.current) await syncInFlightRef.current;
@@ -914,6 +952,15 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
});
})();
});
+ // 列表被 LIST_LIMIT 截断时,补丁可能改变前 N 条的成员(如归档后第 N+1 条该补进、
+ // 窗口外任务因活动排进来),本地无法补全:记下 mutation epoch,回首页时有变就重拉。
+ homeListFreshnessRef.current.markFresh(
+ device.deviceId,
+ freshnessToken,
+ nextSessions.length >= LIST_LIMIT
+ ? remoteSessionStore.captureDeviceSessionListMutationEpoch(device.deviceId)
+ : null,
+ );
updateDeviceConnectionState(device.deviceId, 'idle');
// hydrate 成功后去抖回写首页列表缓存(collect 在定时器触发时才读 store,拿届时最新快照;
// 多设备并发 hydrate 只落盘一次)。不在 store 每次变更时写盘。缓存按账号键控。
@@ -928,6 +975,7 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
return { failure: null, offline: false, superseded: true };
}
const offline = isDeviceOfflineError(err);
+ homeListFreshnessRef.current.invalidate(device.deviceId);
if (offline) markDeviceOffline(device.deviceId);
updateDeviceConnectionState(device.deviceId, 'failed');
return {
@@ -936,7 +984,7 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
superseded: false,
};
}
- }, 'foreground'), [HOME_LIST_SUBSCRIPTION_OWNER, homeCacheUserId, invoke, isCurrentHomeSyncTarget, markDeviceOffline, refreshDeviceScheduleIndex, statusFilter, active, subscribe, updateDeviceConnectionState]);
+ }, 'foreground'), [HOME_LIST_SUBSCRIPTION_OWNER, homeCacheUserId, invoke, isCurrentHomeSyncTarget, markDeviceOffline, markHomeScheduleIndexDirty, refreshDeviceScheduleIndex, statusFilter, active, subscribe, updateDeviceConnectionState]);
const hydrateDeviceSessions = useCallback((
device: DeviceView,
@@ -1033,6 +1081,7 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
});
}
+ const fullReloadRequestAtStart = homeFullReloadOnFocusRef.current;
const rawTask = (async () => {
setError(null);
// 记录 REST 请求发起时的 presence 纪元:在请求飞行期间收到过 presence 补丁的设备,
@@ -1141,6 +1190,7 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
setDevices(nextDevices);
lastSyncedAtRef.current = now;
setLastSyncedAt(now);
+ if (homeFullReloadOnFocusRef.current === fullReloadRequestAtStart) homeFullReloadOnFocusRef.current = null;
if (selectedDeviceIdRef.current === selectedDeviceIdAtSyncStart) {
setError(failures.length > 0 ? failures : null);
}
@@ -1349,27 +1399,29 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
remoteSessionStore.requestReseed(deviceId);
continue;
}
+ // 首页被盖住时刷新会被门禁跳过;记下这台,回首页再刷,不在返回时兜底全量刷新。
+ if (!screenFocusedRef.current) {
+ markHomeScheduleIndexDirty(deviceId);
+ continue;
+ }
refreshDeviceScheduleIndex(deviceId, sessionIds);
}
}), [refreshDeviceScheduleIndex]);
- // 从自动化 / 会话页返回首页时,兜底刷新一次 scheduleIndex:
- // markScheduleRunsRead 的桌面广播若在导航切换途中丢失(silent swallow / 弱网 / tap listener
- // 未挂),之前依赖 remoteScheduleEventStore.subscribe 的路径就永远不会补跑,首页那颗
- // "已完成未读"绿点会一直挂着。useFocusEffect 每次 focus 都按当前设备清一遍未读徽标,
- // 命中真实变化才会 setScheduleIndex(entries 等值比较),不触发无谓 re-render。
- 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);
- if (sessionIds.length === 0) continue;
- refreshDeviceScheduleIndex(device.deviceId, sessionIds);
- }
- }, [refreshDeviceScheduleIndex]),
- );
+ // 刷新首页的自动化角标(scheduleIndex)。整轮返回(首次、后台、重连、离开太久)兜底刷新
+ // 所有设备:那些情况下自动化事件可能漏收。普通返回只刷新离开期间收到过事件的设备——
+ // 事件走首页常驻的 `sessions` 订阅,离开期间照常到达(见 homeScheduleIndexDirtyRef)。
+ const refreshHomeScheduleIndexes = useCallback((onlyDeviceIds?: ReadonlySet<string>) => {
+ for (const device of devicesRef.current) {
+ if (!homeSyncTargetDeviceIdsRef.current.has(device.deviceId)) continue;
+ if (onlyDeviceIds && !onlyDeviceIds.has(device.deviceId)) continue;
+ const sessionIds = remoteSessionStore.getSessions()
+ .filter((session) => session.deviceLinkDeviceId === device.deviceId)
+ .map((session) => session.id);
+ if (sessionIds.length === 0) continue;
+ refreshDeviceScheduleIndex(device.deviceId, sessionIds);
+ }
+ }, [refreshDeviceScheduleIndex]);
// 初次加载 + 每次重连(connectionEpoch 变化)都全量刷新。presence 只在状态"变化"时广播、
// 服务端没有面向新连接的全量重放,后台期间(client.stop)漏掉的上/下线事件只能靠重连时
@@ -1377,24 +1429,79 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
// syncInFlight 去重,冷启动时与上线瞬间的两次触发只会实际执行一次。
// 首次触发同时等首页列表缓存种入完成(homeListCacheHydrated,AsyncStorage 读一个小 key,毫秒级):
// 保证缓存先画、fresh 后覆盖的顺序确定,避免 loadHome 清理下线设备后缓存又把 stale shard 种回去。
+ // 所有整轮同步触发(首次、回前台、重连、需整轮的回首页、依赖变化)都经过这里:先登记整轮
+ // 重拉请求,再尝试执行。请求只由在它之后开始的 loadHome 整轮成功提交清除;失焦、缓存未就绪、
+ // 设备清单失败或中途失焦退出都会保留它,下次回首页仍整轮重拉。
const startSilentHomeSync = useCallback(() => {
+ requestHomeFullReload();
if (!screenFocusedRef.current) return;
if (!deviceIdentityCacheReady || !homeListCacheHydrated || !homeViewPreferencesHydrated) return;
void loadHome({ visible: false });
- }, [deviceIdentityCacheReady, homeListCacheHydrated, homeViewPreferencesHydrated, loadHome]);
+ }, [deviceIdentityCacheReady, homeListCacheHydrated, homeViewPreferencesHydrated, loadHome, requestHomeFullReload]);
+
+ useEffect(() => {
+ if (!screenFocused) homeBlurredAtRef.current = Date.now();
+ }, [screenFocused]);
+
+ // 从任务 / 设置等页面返回首页:离开期间订阅一直在、补丁一直在收,只补拉判定为可能漏了
+ // 推送的设备。离开太久或尚未完成首轮同步时退回整轮 loadHome。
+ const refillStaleHomeDevices = useCallback((deviceIds: readonly string[]) => {
+ if (deviceIds.length === 0) return;
+ const expectedAccountGeneration = accountGeneration;
+ const selectedDeviceIdAtStart = selectedDeviceIdRef.current;
+ const stale = new Set(deviceIds);
+ const rows = homeSyncRowsRef.current.filter((item) => stale.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 HomeDeviceFailure);
+ if (failures.length > 0) setError(failures);
+ else if (results.some((result) => !result.superseded)) setError(null);
+ });
+ }, [accountGeneration, hydrateDeviceSessions]);
// Android can recreate the activity or resume the JS runtime without a fresh React
// mount. Foreground is therefore an authoritative trigger alongside the initial mount
// and reconnect; loadHome single-flights these overlapping cold-start calls.
useFocusEffect(
useCallback(() => {
+ // The focus event can fire before useIsFocused re-renders this screen. Navigation has
+ // already confirmed focus, so open the scope gate now instead of skipping this return.
+ screenFocusedRef.current = true;
+ const blurredAt = homeBlurredAtRef.current;
+ const forceFull = homeFullReloadOnFocusRef.current !== null;
+ homeBlurredAtRef.current = null;
+ const plan = planHomeListFocusReturn({
+ forceFull,
+ blurredAt,
+ lastSyncedAt: lastSyncedAtRef.current,
+ now: Date.now(),
+ deviceIds: homeSyncRowsRef.current.map((item) => item.device.deviceId),
+ freshness: homeListFreshnessRef.current,
+ listMutationEpoch: (deviceId) => remoteSessionStore.captureDeviceSessionListMutationEpoch(deviceId),
+ });
+ const scheduleDirty = new Set(homeScheduleIndexDirtyRef.current.keys());
+ if (plan.kind === 'refill') {
+ refillStaleHomeDevices(plan.deviceIds);
+ if (scheduleDirty.size > 0) refreshHomeScheduleIndexes(scheduleDirty);
+ return;
+ }
+ refreshHomeScheduleIndexes();
startSilentHomeSync();
- }, [startSilentHomeSync]),
+ }, [refillStaleHomeDevices, refreshHomeScheduleIndexes, startSilentHomeSync]),
);
useEffect(() => {
startSilentHomeSync();
const subscription = AppState.addEventListener('change', (nextState) => {
+ // 退后台后连接会在宽限期后停掉,期间的推送无从补齐:回前台一律按需重拉。
+ if (nextState === 'background') homeListFreshnessRef.current.invalidateAll();
if (nextState === 'active') startSilentHomeSync();
});
return () => subscription.remove();
@@ -1521,18 +1628,21 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
() => toDeviceListItems(devices, Date.now(), revokedDevices),
[devices, i18nInstance.resolvedLanguage, revokedDevices],
);
- const homeSyncDeviceIds = useMemo(() => screenFocused ? resolveHomeDeviceSyncIds(
+ // 不随首页失焦清空:被任务页等盖住时保留订阅与镜像,增量补丁照常到达;
+ // 不可见 / 不可用的设备仍由 resolveHomeDeviceSyncIds 排除并 release。
+ const homeSyncDeviceIds = useMemo(() => resolveHomeDeviceSyncIds(
deviceRows.map((item) => ({
canOpen: item.canOpen,
deviceId: item.device.deviceId,
})),
active ? selectedDeviceId : null,
- ) : [], [deviceRows, screenFocused, selectedDeviceId, active]);
+ ), [deviceRows, selectedDeviceId, active]);
const homeSyncDeviceIdSet = useMemo(() => new Set(homeSyncDeviceIds), [homeSyncDeviceIds]);
const homeSyncRows = useMemo(
() => deviceRows.filter((item) => homeSyncDeviceIdSet.has(item.device.deviceId)),
[deviceRows, homeSyncDeviceIdSet],
);
+ homeSyncRowsRef.current = homeSyncRows;
useEffect(() => {
const expectedAccountGeneration = accountGeneration;
@@ -1559,6 +1669,8 @@ function HomeScreenContent({ active = true, onModeChange, width, newSessionInSys
useEffect(() => {
const unregisters = homeSyncRows.map((item) =>
remoteSessionStore.registerReseedHandler(item.device.deviceId, () => {
+ // 首页被盖住时 hydrate 会被 scope 门禁跳过;先记下失效,回到首页再补拉这台。
+ homeListFreshnessRef.current.invalidate(item.device.deviceId);
void hydrateDeviceSessions(item.device, accountGeneration, {
trailingIfInFlight: true,
}).then((hydrateResult) => {
diff --git a/apps/mobile/src/session/homeListFreshness.ts b/apps/mobile/src/session/homeListFreshness.ts
new file mode 100644
index 0000000000..7e51c76491
--- /dev/null
+++ b/apps/mobile/src/session/homeListFreshness.ts
@@ -0,0 +1,121 @@
+/**
+ * Decides which devices' Home task lists are still trustworthy when the user comes back to Home.
+ *
+ * Home keeps its `sessions` subscription while another page covers it, so incremental pushes keep
+ * the mirror current. A device is only re-pulled in full when something says a push may have been
+ * missed since its last successful list pull:
+ * - a reseed request (task created elsewhere, unknown-session patch, or the device-link recovery
+ * replay that follows a peer reset / reconnect / foreground return);
+ * - the device left the sync scope, failed, or went offline;
+ * - its last list was cut at the page limit and any list push arrived since: such a push may
+ * change which tasks belong in the window, which the local mirror cannot complete;
+ * - an app-wide reset such as going to the background.
+ *
+ * Tokens are captured when a pull starts, so a reseed that lands while the request is in flight
+ * leaves the device stale even if that older response is applied successfully.
+ */
+export interface HomeListFreshnessToken {
+ readonly epoch: number;
+ readonly invalidation: number;
+}
+
+interface FreshRecord extends HomeListFreshnessToken {
+ /** List mutation epoch after applying a truncated list; null when the list was complete. */
+ readonly boundedListEpoch: number | null;
+}
+
+export interface HomeListFreshness {
+ /** Capture before reading the list; pass it back to `markFresh` after applying the response. */
+ capture(deviceId: string): HomeListFreshnessToken;
+ /**
+ * `boundedListEpoch`: the device's list mutation epoch when the applied list was truncated at
+ * the page limit, otherwise null.
+ */
+ markFresh(deviceId: string, token: HomeListFreshnessToken, boundedListEpoch?: number | null): void;
+ /** True when nothing has invalidated the device since its last successful full pull. */
+ isFresh(deviceId: string, listMutationEpoch?: number): boolean;
+ invalidate(deviceId: string): void;
+ invalidateAll(): void;
+ clear(): void;
+}
+
+export function createHomeListFreshness(): HomeListFreshness {
+ let epoch = 0;
+ const invalidations = new Map<string, number>();
+ const fresh = new Map<string, FreshRecord>();
+ const tokenFor = (deviceId: string): HomeListFreshnessToken => ({
+ epoch,
+ invalidation: invalidations.get(deviceId) ?? 0,
+ });
+ const isCurrent = (deviceId: string, token: HomeListFreshnessToken) => {
+ const current = tokenFor(deviceId);
+ return token.epoch === current.epoch && token.invalidation === current.invalidation;
+ };
+ return {
+ capture: tokenFor,
+ markFresh(deviceId, token, boundedListEpoch = null) {
+ if (isCurrent(deviceId, token)) fresh.set(deviceId, { ...token, boundedListEpoch });
+ else fresh.delete(deviceId);
+ },
+ isFresh(deviceId, listMutationEpoch) {
+ const record = fresh.get(deviceId);
+ if (record === undefined || !isCurrent(deviceId, record)) return false;
+ return record.boundedListEpoch === null || record.boundedListEpoch === listMutationEpoch;
+ },
+ invalidate(deviceId) {
+ invalidations.set(deviceId, (invalidations.get(deviceId) ?? 0) + 1);
+ fresh.delete(deviceId);
+ },
+ invalidateAll() {
+ epoch += 1;
+ fresh.clear();
+ },
+ clear() {
+ epoch += 1;
+ invalidations.clear();
+ fresh.clear();
+ },
+ };
+}
+
+/**
+ * How long Home may stay covered and still reuse its live mirror on return. Pushes keep flowing
+ * meanwhile; the limit only bounds how long an undetected gap could stay on screen.
+ */
+export const HOME_LIST_FOCUS_REUSE_MAX_MS = 10 * 60_000;
+
+export type HomeListFocusReturnPlan =
+ | { kind: 'full' }
+ | { kind: 'refill'; deviceIds: string[] };
+
+/**
+ * What a return to Home should fetch. A short stay away after a completed sync only refills the
+ * devices whose list may have missed a push. A long stay, no completed sync yet, or a background /
+ * reconnect while away falls back to the full device-list + per-device reload.
+ */
+export function planHomeListFocusReturn(input: {
+ /** Set when the app went to the background or the relay reconnected while Home was covered. */
+ forceFull: boolean;
+ blurredAt: number | null;
+ lastSyncedAt: number | null;
+ now: number;
+ deviceIds: readonly string[];
+ freshness: HomeListFreshness;
+ /** Current per-device list mutation epoch (bumped by every list push). */
+ listMutationEpoch(deviceId: string): number;
+}): HomeListFocusReturnPlan {
+ const awayMs = input.blurredAt === null ? null : input.now - input.blurredAt;
+ if (
+ input.forceFull
+ || awayMs === null
+ || input.lastSyncedAt === null
+ || awayMs < 0
+ || awayMs >= HOME_LIST_FOCUS_REUSE_MAX_MS
+ ) return { kind: 'full' };
+ return {
+ kind: 'refill',
+ deviceIds: input.deviceIds.filter((deviceId) => (
+ !input.freshness.isFresh(deviceId, input.listMutationEpoch(deviceId))
+ )),
+ };
+}
diff --git a/apps/mobile/src/session/scheduleIndex.ts b/apps/mobile/src/session/scheduleIndex.ts
index a3b6b0378e..9dd033142e 100644
--- a/apps/mobile/src/session/scheduleIndex.ts
+++ b/apps/mobile/src/session/scheduleIndex.ts
@@ -94,6 +94,16 @@ interface ScheduleIndexThrottleEntry {
const scheduleIndexThrottleEntries = new Map<string, ScheduleIndexThrottleEntry>();
const scheduleIndexInvalidationVersions = new Map<string, number>();
+/**
+ * Sessions the last successful index of each device bound to an automation (target sessions and
+ * sessions with runs), with the invalidation version it was loaded under. Lets a task page skip
+ * the index scan for an ordinary task. Schedule events keep it current (see
+ * noteScheduleEventInIndexCache); any other invalidation (link recovery, offline) makes it unknown.
+ */
+const scheduleBoundSessionsByDevice = new Map<string, { sessionIds: ReadonlySet<string>; invalidationVersion: number }>();
+// Bumped on every clear (account switch). Invalidation versions restart at 0 after a clear and
+// device ids are machine-level, so a scan started before the clear must not record bindings.
+let scheduleIndexCacheGeneration = 0;
/**
* 错误标记匹配:优先结构化 code,兜底 message 文本(review:mobile 各处的
@@ -241,6 +251,33 @@ export function invalidateOfflineScheduleIndexFailureFor(deviceId: string): void
}
}
+/**
+ * Apply one authoritative schedule event to the shared cache. A run event names the task it binds
+ * to, so the binding record stays usable and just learns that task; a schedule definition change
+ * (create / edit / rebind / unknown event) or a record that was already stale makes it unknown.
+ */
+export function noteScheduleEventInIndexCache(
+ deviceId: string,
+ change: { invalidate: boolean; sessionId: string | null; scheduleListChanged: boolean },
+): void {
+ if (!deviceId) return;
+ const known = scheduleBoundSessionsByDevice.get(deviceId);
+ const wasCurrent = known !== undefined
+ && known.invalidationVersion === getScheduleIndexInvalidationVersion(deviceId);
+ if (change.invalidate) invalidateScheduleIndexForDevice(deviceId);
+ if (!known) return;
+ if (!wasCurrent || change.scheduleListChanged) {
+ scheduleBoundSessionsByDevice.delete(deviceId);
+ return;
+ }
+ scheduleBoundSessionsByDevice.set(deviceId, {
+ sessionIds: change.sessionId && !known.sessionIds.has(change.sessionId)
+ ? new Set([...known.sessionIds, change.sessionId])
+ : known.sessionIds,
+ invalidationVersion: getScheduleIndexInvalidationVersion(deviceId),
+ });
+}
+
export function invalidateScheduleIndexForDevice(deviceId: string): void {
if (!deviceId) return;
const entry = scheduleIndexThrottleEntries.get(deviceId);
@@ -262,10 +299,29 @@ export function getScheduleIndexInvalidationVersion(deviceId: string): number {
return scheduleIndexInvalidationVersions.get(deviceId) ?? 0;
}
-/** Test-only: clear cache and invalidation generations. */
+/** Clear cache, invalidation generations and binding knowledge (account switch, tests). */
export function clearSessionScheduleIndexCache(): void {
+ scheduleIndexCacheGeneration += 1;
scheduleIndexThrottleEntries.clear();
scheduleIndexInvalidationVersions.clear();
+ scheduleBoundSessionsByDevice.clear();
+}
+
+/**
+ * Whether opening this task needs the device's schedule index (to mark its runs read and show
+ * its failure notice). Only an ordinary task on a device whose current index is known and has
+ * no binding for it can skip the scan; automation-created tasks, tasks bound to an automation
+ * (including ones a later run event named) and devices without a current record still load it.
+ */
+export function sessionMayHaveScheduleRuns(
+ deviceId: string,
+ sessionId: string,
+ source?: string | null,
+): boolean {
+ if (source === 'scheduler') return true;
+ const known = scheduleBoundSessionsByDevice.get(deviceId);
+ if (!known || known.invalidationVersion !== getScheduleIndexInvalidationVersion(deviceId)) return true;
+ return known.sessionIds.has(sessionId);
}
export function loadDeviceSessionScheduleIndex(
@@ -286,6 +342,8 @@ export async function loadSharedSessionScheduleIndex(
// Check again when an invalidated in-flight scan finishes. Throw before
// creating an entry so an abandoned waiter cannot poison active consumers.
if (!canStart()) throw new Error('Schedule index consumer inactive');
+ const invalidationVersion = getScheduleIndexInvalidationVersion(deviceId);
+ const cacheGeneration = scheduleIndexCacheGeneration;
return withTransientRemoteRetry(() => {
if (!canStart()) {
// Cancellation is not a device failure: discard this pending entry on
@@ -297,6 +355,11 @@ export async function loadSharedSessionScheduleIndex(
throwOnTransientRunListError: true,
isDeviceUnresponsive: () => unresponsiveDevicesStore.has(deviceId),
});
+ }).then((index) => {
+ if (cacheGeneration === scheduleIndexCacheGeneration) {
+ scheduleBoundSessionsByDevice.set(deviceId, { sessionIds: new Set(index.keys()), invalidationVersion });
+ }
+ return index;
});
});
}
diff --git a/apps/mobile/src/session/scheduleRunRead.ts b/apps/mobile/src/session/scheduleRunRead.ts
index 01a199df8b..40cad0fa23 100644
--- a/apps/mobile/src/session/scheduleRunRead.ts
+++ b/apps/mobile/src/session/scheduleRunRead.ts
@@ -3,6 +3,7 @@ import type { ScheduleEventProjection } from '@cindy/maker-shared/schedule-event
import { isTransientRemoteError } from '@/device-link/remoteRetry';
import type { MobileMakerTransport } from '@/device-link/mobileMakerTransport';
import { loadSharedSessionScheduleIndex } from '@/session/scheduleIndex';
+import { remoteScheduleEventStore } from '@/scheduler/remoteScheduleEvents';
/**
* 会话维度的自动化 run「已读」编排(对齐桌面端 CCAgentSidebarUpper 的「激活即已读」语义)。
@@ -32,7 +33,8 @@ export async function markSessionScheduleRunsRead(
const index = await loadSharedSessionScheduleIndex(deviceId, maker, isActive);
if (!isActive()) return [];
options.onIndex?.(index);
- const unreadRunIds = index.get(sessionId)?.unreadRunIds ?? [];
+ const info = index.get(sessionId);
+ const unreadRunIds = info?.unreadRunIds ?? [];
if (unreadRunIds.length === 0) return [];
// 单个永久失败不阻塞其它 run;瞬态失败需要抛出,让外层 retry 重新探测并补标。
// allSettled 后按原 unreadRunIds 顺序收集成功项,返回值保序。
@@ -43,7 +45,12 @@ export async function markSessionScheduleRunsRead(
(result): result is PromiseRejectedResult => result.status === 'rejected' && isTransientRemoteError(result.reason),
)?.reason;
if (transientError) throw transientError;
- return unreadRunIds.filter((_, i) => results[i].status === 'fulfilled');
+ const marked = unreadRunIds.filter((_, i) => results[i].status === 'fulfilled');
+ // The host does not broadcast `read` when the run was already read elsewhere (no-op). Apply
+ // the same event locally so the shared index cache drops its stale unread runs and Home
+ // refreshes (or, while covered, records) this device's badges either way.
+ if (marked.length > 0 && info) remoteScheduleEventStore.apply(deviceId, { type: 'read', scheduleId: info.scheduleId });
+ return marked;
}
/**
diff --git a/docs/dev-rules/remote-and-mobile-adaptation.md b/docs/dev-rules/remote-and-mobile-adaptation.md
index 6eb73d656c..afca704bf2 100644
--- a/docs/dev-rules/remote-and-mobile-adaptation.md
+++ b/docs/dev-rules/remote-and-mobile-adaptation.md
@@ -155,6 +155,17 @@ Desktop 周期列表按设备合并在途读取和退避,健康设备不等待
Mobile 重连先恢复已订阅任务的快照,再请求首页列表;某一步传输失败即退出该设备
本轮恢复,交回按设备退避,不能继续扇出剩余读取或重置其它设备的连接。
+Mobile 首页被任务页、设置页等盖住时仍持有可见设备的 `sessions` 订阅,增量补丁照常进镜像;
+回到首页不再整份重拉所有电脑,只补拉可能漏过推送的设备:离开期间收到 reseed
+(新建任务、未知任务补丁,以及 peer reset/重连/回前台后 device-link 恢复回放发出的重拉)、
+拉取失败或离线、离开时已不在同步范围;列表被分页上限截断的设备离开期间收到任何列表推送也重拉(截断窗口的成员变化本地补不全)。离开期间 App 退过后台、relay 重连过、离开超过
+10 分钟或尚未完成首轮同步时,仍走整轮设备清单 + 列表重拉,且这次整轮成功提交前一直保持整轮(失败不降级为只补拉);不可见设备照旧 release 退订。
+判据见 Mobile `homeListFreshness.ts`,不新增 wire 字段或持久化状态。
+自动化角标(scheduleIndex)同理:自动化事件随 `sessions` 订阅到达,首页被盖住时只记下收到事件的
+设备,因失焦被跳过或结果被丢弃的刷新同样留待补刷(成功应用后才清除),回首页只刷新这些设备,整轮返回时才全量刷新。任务页打开普通任务时,若该设备当前索引表明
+它未绑定任何自动化,就跳过标记已读的索引读取;运行事件会把新绑定的任务补进记录,自动化定义变化、
+重连或离线后记录失效、照常读取(`scheduleIndex.ts` 的 `sessionMayHaveScheduleRuns`)。
+
远程桌面的输入不是可持久重放的工作:本地未发送输入等待达到两秒时丢弃并退出
控制,复用控制释放路径;重新取得控制时清除旧批次等待,以递增序号隔离迟到 ACK。
Mobile 父层同时退役旧输入批次;旧 native 发送的迟到失败不得回落 relay,旧请求的