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.9 KB
Raw Blame
import { useCallback, useEffect, useState } from 'react';

import {
  getDataOwnerGeneration,
  isDataOwnerGenerationCurrent,
  isDataOwnerPushCurrent,
} from '@/contexts/dataOwnerGeneration';
import { makerApiForSticky } from '@/lib/makerTransport';
import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';
import type { BotDelegationStatus, BotDelegationView } from '../../../shared/botDelegation';

/** 未落终态的后台任务:任务卡按这个集合决定是否仍在执行。 */
const ACTIVE_STATUSES = new Set<BotDelegationStatus>(['queued', 'waiting', 'running']);

export function isActiveDelegationStatus(status: BotDelegationStatus): boolean {
  return ACTIVE_STATUSES.has(status);
}

interface SessionEntry {
  rows: BotDelegationView[];
  /**
   * 首次拉取是否已经**落地**(成功或失败都算)。
   *
   * 「还没读到」和「读完了但没有这一行」是两回事:前者该继续显示进行中的样子,
   * 后者说明这条任务我们暂时核实不了(例如列表拉取失败)。
   * 不区分的话,第二种情况会被当成第一种,卡片就永远停在带呼吸点的「正在开始」。
   */
  resolved: boolean;
  stale: boolean;
  listeners: Set<() => void>;
  unsubscribe: (() => void) | null;
  reloadGeneration: number;
}

/**
 * 每个会话一份委派快照,会话内所有协作卡共用。
 *
 * 存在的理由:一次连环编排里父任务可能挂三四张协作卡,每张都自己 `listBotDelegations`
 * + 订阅推送的话,一条状态变更会引发 N 次全量拉取。这里把「一个会话一次订阅、一次
 * 拉取、广播给所有卡」收在一处;组件侧只按 delegationId 取自己那行。
 *
 * 数据主人切换(登出 / 切账号)沿用既有 dataOwnerGeneration 守卫丢弃旧结果。
 */
const sessions = new Map<string, SessionEntry>();

function ensureEntry(sessionId: string): SessionEntry {
  const existing = sessions.get(sessionId);
  if (existing) return existing;
  const entry: SessionEntry = {
    rows: [],
    resolved: false,
    stale: false,
    listeners: new Set(),
    unsubscribe: null,
    reloadGeneration: 0,
  };
  sessions.set(sessionId, entry);
  return entry;
}

function emit(entry: SessionEntry): void {
  for (const listener of [...entry.listeners]) listener();
}

async function reload(sessionId: string): Promise<void> {
  const entry = sessions.get(sessionId);
  if (!entry) return;
  const owner = getDataOwnerGeneration();
  const generation = ++entry.reloadGeneration;
  try {
    const result = await makerApiForSticky(sessionId).listBotDelegations(sessionId);
    if (!isDataOwnerGenerationCurrent(owner)) return;
    if (sessions.get(sessionId) !== entry || entry.reloadGeneration !== generation) return;
    // 短暂读取失败不能把已经显示的持久任务卡抹掉。成功时才替换快照;失败时
    // 保留上一次可核实的状态,并让卡片继续可见。
    if (result.ok) entry.rows = result.delegations;
    entry.stale = !result.ok;
    entry.resolved = true;
    emit(entry);
  } catch {
    if (!isDataOwnerGenerationCurrent(owner)) return;
    if (sessions.get(sessionId) !== entry || entry.reloadGeneration !== generation) return;
    entry.resolved = true;
    entry.stale = true;
    emit(entry);
  }
}

function subscribe(sessionId: string, listener: () => void): () => void {
  const entry = ensureEntry(sessionId);
  entry.listeners.add(listener);
  if (!entry.unsubscribe) {
    const deviceId = remoteProjectsStore.getSessionDeviceId(sessionId);
    const offPush = deviceId
      ? window.electronAPI.deviceLink.onRemotePush((push, stamp) => {
          if (
            push.deviceId !== deviceId ||
            push.channel !== 'maker:bot-delegation:changed' ||
            !isDeviceLinkRemotePushCurrent(push, stamp)
          )
            return;
          const payload = push.payload as { parentSessionId?: string };
          if (payload?.parentSessionId === sessionId) void reload(sessionId);
        })
      : window.electronAPI.maker.onBotDelegationChanged((payload, ownerStamp) => {
          if (!isDataOwnerPushCurrent(ownerStamp) || payload.parentSessionId !== sessionId) return;
          void reload(sessionId);
        });
    const offStatus = deviceId
      ? window.electronAPI.deviceLink.onStatusChanged((state) => {
          if (state.status === 'online') void reload(sessionId);
          else {
            entry.reloadGeneration += 1;
            entry.stale = true;
            emit(entry);
          }
        })
      : () => {};
    entry.unsubscribe = () => {
      offPush();
      offStatus();
    };
    void reload(sessionId);
  }
  return () => {
    entry.listeners.delete(listener);
    if (entry.listeners.size > 0) return;
    entry.unsubscribe?.();
    sessions.delete(sessionId);
  };
}

export interface BotDelegationLive {
  /** 这一条委派的实时行;还没读到、或读完了但不存在时为 null。 */
  row: BotDelegationView | null;
  /**
   * 本会话的委派列表是否已经拉过一次(成功或失败都算)。
   *
   * `resolved && row === null` 是一个**确定的**结论:这条委派我们核实不了。
   * 调用方必须据此改口,不能继续画「正在进行」。
   */
  resolved: boolean;
  stale: boolean;
}

/** 取本会话发起的某一个委派的实时行,附带「首次拉取是否已落地」。 */
export function useBotDelegation(
  sessionId: string | null,
  delegationId: string,
): BotDelegationLive {
  const [live, setLive] = useState<BotDelegationLive>({ row: null, resolved: false, stale: false });
  const read = useCallback((): BotDelegationLive => {
    if (!sessionId) return { row: null, resolved: false, stale: false };
    const entry = sessions.get(sessionId);
    return {
      row: entry?.rows.find((item) => item.id === delegationId) ?? null,
      resolved: entry?.resolved ?? false,
      stale: entry?.stale ?? false,
    };
  }, [delegationId, sessionId]);

  useEffect(() => {
    if (!sessionId) {
      setLive({ row: null, resolved: false, stale: false });
      return;
    }
    setLive(read());
    return subscribe(sessionId, () => setLive(read()));
  }, [read, sessionId]);

  return live;
}

/** 本会话发起的全部委派(伙伴工作台的进度卡用),与协作卡共用同一份订阅。 */
export function useBotDelegations(sessionId: string | null): readonly BotDelegationView[] {
  const [rows, setRows] = useState<readonly BotDelegationView[]>([]);
  useEffect(() => {
    if (!sessionId) {
      setRows([]);
      return;
    }
    const read = () => setRows(sessions.get(sessionId)?.rows ?? []);
    read();
    return subscribe(sessionId, read);
  }, [sessionId]);
  return rows;
}

/** 测试用:清掉进程内缓存,避免用例之间互相看到对方的订阅。 */
export function __resetBotDelegationLiveForTest(): void {
  for (const entry of sessions.values()) entry.unsubscribe?.();
  sessions.clear();
}