Skip to content

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io

9.7 KB
Raw Blame
import { useCallback, useSyncExternalStore } from "react";
import { useQueryClient, type QueryClient } from "@tanstack/react-query";
import { readLocalCache, writeLocalCache } from "@/lib/localCache";
import { extractErrorMessage } from "@/utils/errorUtils";
import {
  PLUGIN_CLI_NOT_INSTALLED,
  pluginsApi,
  type PluginActionOutcome,
  type PluginApp,
  type PluginEntry,
} from "@/lib/api/plugins";

/**
 * 插件页的数据:已安装、市场目录、市场三份查询,外加带乐观更新的写操作。
 *
 * 每次查询都要起一次 CLI(Claude Code 约 1s),所以:
 * - 已安装列表小,存一份本地缓存,打开页面先显示上次的结果,后台再刷新;
 * - 目录大(Claude Code 官方目录几千项)且只随市场变,只放内存,装、卸都不重读;
 * - 启停、卸载先改界面,失败再改回;装好后直接把条目加进已安装;
 * - 同一应用的操作全部结束后才在后台对一次账,中途不让刷新覆盖掉乐观状态。
 */

export const pluginKeys = {
  all: ["plugins"] as const,
  installed: (app: PluginApp) => ["plugins", app, "installed"] as const,
  catalog: (app: PluginApp) => ["plugins", app, "catalog"] as const,
  marketplaces: (app: PluginApp) => ["plugins", app, "marketplaces"] as const,
};

const installedCacheKey = (app: PluginApp) => `plugins:${app}:installed`;

/** 每个应用进行中的写操作数、各条目的转圈状态,和操作结束后要重读的查询。 */
const pending = new Map<PluginApp, number>();
const reconcileTargets = new Map<PluginApp, Set<ReconcileTarget>>();
const EMPTY_BUSY: Readonly<Record<string, string>> = Object.freeze({});
const busyByApp = new Map<PluginApp, Readonly<Record<string, string>>>();
const busyListeners = new Set<() => void>();

function emitBusy() {
  for (const listener of busyListeners) listener();
}

function subscribeBusy(listener: () => void) {
  busyListeners.add(listener);
  return () => {
    busyListeners.delete(listener);
  };
}

function busySnapshot(app: PluginApp): Readonly<Record<string, string>> {
  return busyByApp.get(app) ?? EMPTY_BUSY;
}

function setBusyKey(app: PluginApp, key: string, action: string) {
  busyByApp.set(app, { ...busySnapshot(app), [key]: action });
  emitBusy();
}

function clearBusyKey(app: PluginApp, key: string) {
  const prev = busyByApp.get(app);
  if (!prev || !(key in prev)) return;
  const next = { ...prev };
  delete next[key];
  if (Object.keys(next).length === 0) {
    busyByApp.delete(app);
  } else {
    busyByApp.set(app, next);
  }
  emitBusy();
}

export const isPluginWriteBusy = (app: PluginApp, key: string) =>
  Boolean(busySnapshot(app)[key]);

export const hasPendingPluginWrites = (app: PluginApp) =>
  (pending.get(app) ?? 0) > 0;

/** 只给测试用:用例之间清掉模块级状态。 */
export function resetPluginWriteState() {
  pending.clear();
  reconcileTargets.clear();
  busyByApp.clear();
  emitBusy();
}

/** 有写操作在跑时不自动刷新:刷新读到的是操作前的状态,会把乐观结果盖回去。 */
const idleOnly = (app: PluginApp) => () => !hasPendingPluginWrites(app);

export const installedPluginsQuery = (app: PluginApp) => ({
  queryKey: pluginKeys.installed(app),
  queryFn: async () => {
    const result = await pluginsApi.listInstalled(app);
    if (!hasPendingPluginWrites(app)) {
      writeLocalCache(installedCacheKey(app), result);
    }
    return result;
  },
  initialData: () => readLocalCache<PluginEntry[]>(installedCacheKey(app)),
  // 本地缓存是旧数据:时间记成 0,挂载时照常在后台刷新
  initialDataUpdatedAt: 0,
  staleTime: 15_000,
  retry: false,
  refetchOnMount: idleOnly(app),
  // 用户可能在终端里用 CLI 改过:切回窗口时重读(CLI 未装时不反复重探)
  refetchOnWindowFocus: (query: { state: { error: unknown } }) =>
    !hasPendingPluginWrites(app) &&
    extractErrorMessage(query.state.error) !== PLUGIN_CLI_NOT_INSTALLED,
});

export const pluginCatalogQuery = (app: PluginApp) => ({
  queryKey: pluginKeys.catalog(app),
  queryFn: () => pluginsApi.listCatalog(app),
  staleTime: 5 * 60_000,
  retry: false,
  refetchOnWindowFocus: false,
});

export const pluginMarketplacesQuery = (app: PluginApp) => ({
  queryKey: pluginKeys.marketplaces(app),
  queryFn: () => pluginsApi.listMarketplaces(app),
  staleTime: 60_000,
  retry: false,
  refetchOnWindowFocus: false,
});

type ReconcileTarget = "installed" | "catalog" | "marketplaces";
type InstalledPatch = (entries: PluginEntry[]) => PluginEntry[];

/** Claude Code 非 user 范围(project / local)条目的项目路径;其它范围和应用返回 null。 */
export const projectPathOf = (entry: PluginEntry): string | null =>
  entry.scope === "user" ? null : entry.projectPath?.trim() || null;

/** 同一插件可在不同项目装多份 local / project 范围,按 id、scope 和 projectPath 共同识别。 */
export const samePluginEntry = (a: PluginEntry, b: PluginEntry) =>
  a.id === b.id &&
  (a.scope || null) === (b.scope || null) &&
  projectPathOf(a) === projectPathOf(b);

/** 乐观补丁:都按条目身份作用在「当前」数据上,几个操作交错时互不覆盖。 */
export const pluginPatches = {
  setEnabled:
    (target: PluginEntry, enabled: boolean): InstalledPatch =>
    (entries) =>
      entries.map((e) => (samePluginEntry(e, target) ? { ...e, enabled } : e)),
  remove:
    (target: PluginEntry): InstalledPatch =>
    (entries) =>
      entries.filter((e) => !samePluginEntry(e, target)),
  /** 加回(卸载失败时)或加入(装好后);已经在就不重复加。 */
  add:
    (target: PluginEntry, index?: number): InstalledPatch =>
    (entries) => {
      if (entries.some((e) => samePluginEntry(e, target))) return entries;
      const next = [...entries];
      next.splice(index ?? next.length, 0, target);
      return next;
    },
};

/** 目录条目装好后在已安装列表里的 id(OpenClaw 的目录给的是包名)。 */
export const installedIdOf = (entry: PluginEntry) =>
  entry.installedId || entry.id;

/** 能否卸载、更新;旧缓存里的条目没有 removable,按 manageable 算。 */
export const isRemovable = (entry: PluginEntry) =>
  entry.removable ?? entry.manageable;

/** 装好后先放进已安装的那一项;版本、路径等后台对账时补齐。 */
export function installedFromCatalog(
  app: PluginApp,
  entry: PluginEntry,
  enabled = true,
): PluginEntry {
  const id = installedIdOf(entry);
  return {
    ...entry,
    id,
    name: id === entry.id ? entry.name : id,
    // 没有市场概念的应用(OpenClaw、Pi)已装条目不显示来源
    marketplace: app === "openclaw" || app === "pi" ? "" : entry.marketplace,
    installedId: null,
    catalogId: null,
    installed: true,
    enabled,
    manageable: true,
    removable: true,
    scope: app === "claude" ? "user" : null,
    projectPath: null,
  };
}

interface PluginWrite {
  /** 行上转圈用的 key:插件 id,或 `market:*` 这类 */
  key: string;
  action: string;
  task: () => Promise<PluginActionOutcome>;
  /** 发出请求前就改界面;失败时用 revert 改回 */
  optimistic?: { apply: InstalledPatch; revert: InstalledPatch };
  /** 成功后立即改界面(不等对账) */
  onSuccess?: (outcome: PluginActionOutcome) => InstalledPatch;
  /** 操作结束后要在后台重读的查询 */
  reconcile: ReconcileTarget[];
}

function patchInstalled(
  queryClient: QueryClient,
  app: PluginApp,
  patch: InstalledPatch,
) {
  queryClient.setQueryData<PluginEntry[]>(pluginKeys.installed(app), (old) =>
    old ? patch(old) : old,
  );
}

function finishWrite(
  queryClient: QueryClient,
  app: PluginApp,
  targets: ReconcileTarget[],
) {
  const set = reconcileTargets.get(app) ?? new Set<ReconcileTarget>();
  targets.forEach((t) => set.add(t));
  reconcileTargets.set(app, set);
  const left = (pending.get(app) ?? 1) - 1;
  pending.set(app, left);
  if (left > 0) return;
  // 最后一个操作结束:攒下的查询一起对一次账
  reconcileTargets.delete(app);
  for (const target of set) {
    void queryClient.invalidateQueries({
      queryKey: pluginKeys[target](app),
      exact: true,
    });
  }
}

export interface PluginWriteResult {
  ok: boolean;
  outcome?: PluginActionOutcome;
  error?: unknown;
}

/**
 * 插件页的写操作。`busy` 按应用存在模块级,切到别的应用或离开页面再回来时,
 * 还没跑完的操作继续转圈并禁用对应控件。
 */
export function usePluginWrites(app: PluginApp) {
  const queryClient = useQueryClient();
  const busy = useSyncExternalStore(
    subscribeBusy,
    () => busySnapshot(app),
    () => EMPTY_BUSY,
  );

  const run = useCallback(
    async (write: PluginWrite): Promise<PluginWriteResult> => {
      pending.set(app, (pending.get(app) ?? 0) + 1);
      setBusyKey(app, write.key, write.action);
      try {
        if (write.optimistic) {
          // 正在跑的刷新读的是操作前的状态,晚到会把乐观结果盖掉
          await queryClient.cancelQueries({
            queryKey: pluginKeys.installed(app),
            exact: true,
          });
          patchInstalled(queryClient, app, write.optimistic.apply);
        }
        try {
          const outcome = await write.task();
          if (write.onSuccess)
            patchInstalled(queryClient, app, write.onSuccess(outcome));
          return { ok: true, outcome };
        } catch (error) {
          if (write.optimistic) {
            patchInstalled(queryClient, app, write.optimistic.revert);
          }
          return { ok: false, error };
        }
      } finally {
        clearBusyKey(app, write.key);
        finishWrite(queryClient, app, write.reconcile);
      }
    },
    [app, queryClient],
  );

  return { busy, run };
}