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。

6.0 KB
Raw Blame
import { useSyncExternalStore } from 'react';
import {
  projectScheduleEvent,
  type ScheduleEventProjection,
} from '@cindy/maker-shared/schedule-events';
import { noteScheduleEventInIndexCache } from '@/session/scheduleIndex';

export interface RemoteScheduleEventSnapshot {
  lastProjection: ScheduleEventProjection | null;
  runsVersion: number;
  scheduleListVersion: number;
  sessionIndexVersion: number;
  /**
   * 未读清除类事件(unreadImpact = may-clear-schedule / clear-all,即 read / all-read)
   * 的专用计数:事件先使共享索引失效,消费方据此读取同一轮新索引。
   * 单列一个 version 而不让消费方依赖 lastProjection 引用——后者每个事件都换新,
   * 进 effect deps 会让 fired / deferred 等无关事件也触发昂贵的全量拉取。
   */
  unreadClearVersion: number;
  unreadVersion: number;
  version: number;
}

const emptySnapshot: RemoteScheduleEventSnapshot = Object.freeze({
  lastProjection: null,
  runsVersion: 0,
  scheduleListVersion: 0,
  sessionIndexVersion: 0,
  unreadClearVersion: 0,
  unreadVersion: 0,
  version: 0,
});

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>();
// Keep generations monotonic across recovery/clear without retaining per-device counters.
let nextMirrorInvalidationGeneration = 0;
let mirrorInvalidationSnapshot: ReadonlyMap<string, number> = new Map();
const subs = new Set<() => void>();

function emit(): void {
  for (const sub of subs) sub();
}

export const remoteScheduleEventStore = {
  apply(deviceId: string, payload?: unknown): void {
    if (!deviceId) return;
    const projection = projectScheduleEvent(payload);
    const clearsUnread = projection.unreadImpact === 'may-clear-schedule'
      || projection.unreadImpact === 'clear-all';
    // 不要求任何刷新、也不带 run 状态的事件(runtime-state 高频诊断)不换快照:否则挂载屏
    // 每次都重渲染,且会覆盖上一个可操作事件(如 completed)的 lastProjection。
    if (
      projection.refresh.runRefresh.mode === 'none'
      && !projection.refresh.scheduleList
      && !projection.refresh.sessionIndex
      && !projection.refresh.unreadSummary
      && projection.unreadImpact === 'none'
      && projection.runPatch.status === 'unknown'
    ) return;
    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.
    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),
      scheduleListVersion: prev.scheduleListVersion + (projection.refresh.scheduleList ? 1 : 0),
      sessionIndexVersion: prev.sessionIndexVersion + (projection.refresh.sessionIndex ? 1 : 0),
      unreadClearVersion: prev.unreadClearVersion + (clearsUnread ? 1 : 0),
      unreadVersion: prev.unreadVersion + (projection.refresh.unreadSummary ? 1 : 0),
      version: prev.version + 1,
    });
    emit();
  },

  clearDevice(deviceId: string): void {
    if (!snapshots.delete(deviceId)) return;
    emit();
  },

  invalidateDeviceMirror(deviceId: string): void {
    remoteScheduleEventStore.invalidateDeviceMirrors([deviceId]);
  },

  /**
   * 批量失效:同一波(如 presence 整批离线)只 emit 一次。逐台失效时每台各
   * notify 一轮,所有挂载屏被同步重渲染 N 次,设备数超过 React 嵌套更新上限
   * 即致命退出(2026-09-10 Android 冷启动,40/80 台隔离复现)。
   */
  invalidateDeviceMirrors(deviceIds: readonly string[]): void {
    let changed = false;
    for (const deviceId of new Set(deviceIds)) {
      if (!deviceId) continue;
      // Presence and Home may report the same offline state independently. Only
      // publish again after recovery clears the marker or a fresh event arrives.
      if (mirrorInvalidationVersions.has(deviceId) && !snapshots.has(deviceId)) continue;
      snapshots.delete(deviceId);
      mirrorInvalidationVersions.set(
        deviceId,
        ++nextMirrorInvalidationGeneration,
      );
      changed = true;
    }
    if (!changed) return;
    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 && mirrorInvalidationVersions.size === 0) return;
    snapshots.clear();
    mirrorInvalidationVersions.clear();
    mirrorInvalidationSnapshot = new Map();
    emit();
  },

  getSnapshot(deviceId: string): RemoteScheduleEventSnapshot {
    return snapshots.get(deviceId) ?? emptySnapshot;
  },

  getVersion(deviceId: string): number {
    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,
    () => remoteScheduleEventStore.getSnapshot(deviceId),
  );
}