示例工程 28-project-approval-panel

28-project-approval-panel/app/src/lib/store.ts

typescript · 1.9 KB

import type { ApprovalState, Decision, Risk, Tool } from "../../shared/ipc";

export type RequestInput = {
  tool: Tool;
  risk: Risk;
  detail: string;
  ttlMs: number;
};

export type ApprovalStore = {
  getState: () => ApprovalState;
  subscribe: (fn: () => void) => () => void;
  decide: (id: string, decision: Decision) => Promise<void>;
  request: (input: RequestInput) => Promise<void>;
  reset: () => Promise<void>;
  dispose: () => void;
};

const EMPTY: ApprovalState = {
  pending: [],
  history: [],
  policies: [],
  now: Date.now(),
};

export function createApprovalStore(): ApprovalStore {
  let state: ApprovalState = { ...EMPTY, now: Date.now() };
  const listeners = new Set<() => void>();

  const emit = (): void => {
    for (const listener of [...listeners]) listener();
  };

  const replace = (next: ApprovalState): void => {
    state = next;
    emit();
  };

  const unsubscribe = window.api.approval.onChange(replace);
  void window.api.approval.get().then(replace);

  const ticker = setInterval(() => {
    if (state.pending.length === 0) return;
    state = { ...state, now: Date.now() };
    emit();
  }, 250);

  return {
    getState: () => state,
    subscribe: (fn) => {
      listeners.add(fn);
      return () => {
        listeners.delete(fn);
      };
    },
    decide: async (id, decision) => {
      replace(await window.api.approval.decide(id, decision));
    },
    request: async (input) => {
      replace(await window.api.approval.request(input));
    },
    reset: async () => {
      replace(await window.api.approval.reset());
    },
    dispose: () => {
      clearInterval(ticker);
      unsubscribe();
      listeners.clear();
    },
  };
}

export function remainingSeconds(expiresAt: number, now: number): number {
  return Math.max(0, Math.ceil((expiresAt - now) / 1000));
}

export function riskLabel(risk: Risk): string {
  if (risk === "exec") return "执行";
  if (risk === "write") return "写入";
  return "只读";
}