示例工程 58-agent-app-architecture

58-agent-app-architecture/app/src/App.ts

typescript · 9.4 KB

import type { Check, Snapshot } from "../shared/ipc";
import type { ApprovalMode, Decision, Edge, Layer } from "../shared/arch";

function escapeHtml(text: string): string {
  return text.replace(/[&<>"]/g, (char) => {
    if (char === "&") return "&amp;";
    if (char === "<") return "&lt;";
    if (char === ">") return "&gt;";
    return "&quot;";
  });
}

function time(at: number): string {
  return new Date(at).toLocaleTimeString("zh-CN", { hour12: false });
}

function layerCard(layer: Layer): string {
  return `<div class="layer-card" data-testid="layer-${layer.id}">
    <b>${escapeHtml(layer.title)}</b>
    <div class="chips">${layer.items.map((item) => `<span>${escapeHtml(item)}</span>`).join("")}</div>
    <p class="muted small">${escapeHtml(layer.note)}</p>
  </div>`;
}

function edgeRow(edge: Edge): string {
  return `<li class="edge-row" data-testid="edge-row">
    <span class="tag ${edge.kind === "allowed" ? "ok" : "bad"}">${edge.kind === "allowed" ? "允许" : "禁止"}</span>
    <code>${escapeHtml(edge.from)} → ${escapeHtml(edge.to)}</code>
    <span class="muted small">${escapeHtml(edge.label)}</span>
  </li>`;
}

const MODES: ApprovalMode[] = ["never", "once", "session", "always"];

function verdict(decision: Decision): string {
  if (decision.allowed) return '<span class="tag ok">允许</span>';
  if (decision.needApproval) return '<span class="tag warn">审批</span>';
  return '<span class="tag bad">拒绝</span>';
}

function checkRow(check: Check): string {
  return `<li class="check-row" data-testid="check-row">
    <span class="tag ${check.pass ? "ok" : "bad"}">${check.pass ? "PASS" : "FAIL"}</span>
    <span>${escapeHtml(check.label)}</span>
    <code>${escapeHtml(check.detail)}</code>
  </li>`;
}

export function mountApp(root: HTMLElement): void {
  root.innerHTML = `
    <div class="app">
      <header class="header">
        <div class="brand">
          <span class="logo">A</span>
          <div>
            <h1>Agent 客户端架构规划</h1>
            <span class="muted small">分层 · 权限 · 审批 · 失败模式(离线)</span>
          </div>
        </div>
        <div class="header-side">
          <span class="pill ok-pill">offline</span>
          <span class="pill ok-pill" data-testid="score">—</span>
          <button class="btn" data-testid="refresh">重新计算</button>
        </div>
      </header>

      <div class="banner" data-testid="banner">
        渲染进程只发意图;系统能力、provider 与密钥都留在主进程。
      </div>

      <main class="layout">
        <div class="column">
          <section class="card pad layers-card">
            <div class="card-head">
              <h2>架构分层</h2>
              <span class="muted small">6 层</span>
            </div>
            <div class="layers" data-testid="layers"></div>
          </section>

          <section class="card pad edges-card">
            <div class="card-head">
              <h2>数据流</h2>
              <span class="muted small" data-testid="violations">—</span>
            </div>
            <ul class="edges" data-testid="edges"></ul>
          </section>
        </div>

        <div class="column">
          <section class="card pad permissions-card">
            <div class="card-head">
              <h2>权限矩阵</h2>
              <span class="muted small">工具 × 审批模式</span>
            </div>
            <table class="matrix">
              <thead><tr><th>工具</th><th>风险</th><th>never</th><th>once</th><th>session</th><th>always</th></tr></thead>
              <tbody data-testid="matrix"></tbody>
            </table>
            <p class="muted small permission-note">
              read 在受信工作区自动允许;write/network 按模式审批;
              exec 永不自动放行。
            </p>
          </section>

          <section class="card pad failures-card">
            <div class="card-head">
              <h2>失败模式</h2>
              <span class="muted small" data-testid="failure-count">—</span>
            </div>
            <table class="matrix failures">
              <thead><tr><th>现象</th><th>检测</th><th>重试</th><th>兜底</th></tr></thead>
              <tbody data-testid="failures"></tbody>
            </table>
          </section>

          <section class="card pad checks-card">
            <div class="card-head">
              <h2>架构自检</h2>
              <span class="muted small" data-testid="check-count">—</span>
            </div>
            <ul class="checks" data-testid="checks"></ul>
          </section>

          <section class="card pad">
            <div class="card-head">
              <h2>活动</h2>
              <span class="muted small">计算 / 刷新</span>
            </div>
            <ul class="activity" data-testid="events"></ul>
          </section>
        </div>
      </main>
    </div>
  `;

  const score = root.querySelector<HTMLElement>('[data-testid="score"]');
  const layersEl = root.querySelector<HTMLElement>('[data-testid="layers"]');
  const edgesEl = root.querySelector<HTMLElement>('[data-testid="edges"]');
  const violationsEl = root.querySelector<HTMLElement>(
    '[data-testid="violations"]',
  );
  const matrixEl = root.querySelector<HTMLElement>('[data-testid="matrix"]');
  const failureCount = root.querySelector<HTMLElement>(
    '[data-testid="failure-count"]',
  );
  const failuresEl = root.querySelector<HTMLElement>(
    '[data-testid="failures"]',
  );
  const checksEl = root.querySelector<HTMLElement>('[data-testid="checks"]');
  const checkCount = root.querySelector<HTMLElement>(
    '[data-testid="check-count"]',
  );
  const eventsEl = root.querySelector<HTMLElement>('[data-testid="events"]');

  let state: Snapshot | null = null;

  function renderLayers(): void {
    if (!state) return;
    if (layersEl) layersEl.innerHTML = state.layers.map(layerCard).join("");
    if (edgesEl) edgesEl.innerHTML = state.edges.map(edgeRow).join("");
    if (violationsEl) {
      violationsEl.textContent = `${state.violations.length} 条禁止边`;
    }
  }

  function renderPermissions(): void {
    if (!state || !matrixEl) return;
    matrixEl.innerHTML = state.matrix
      .map(
        (row) => `<tr data-testid="matrix-row">
          <td><code>${escapeHtml(row.tool.name)}</code></td>
          <td>${escapeHtml(row.tool.risk)}</td>
          ${MODES.map((mode) => `<td data-mode="${mode}">${verdict(row.decisions[mode])}</td>`).join("")}
        </tr>`,
      )
      .join("");
  }

  function renderFailures(): void {
    if (!state) return;
    if (failureCount) {
      failureCount.textContent = `${state.failures.length} 类`;
    }
    if (failuresEl) {
      failuresEl.innerHTML = state.failures
        .map(
          (row) => `<tr data-testid="failure-row">
            <td>${escapeHtml(row.symptom)}</td>
            <td>${escapeHtml(row.detect)}</td>
            <td>${escapeHtml(row.retry)}</td>
            <td>${escapeHtml(row.fallback)}</td>
          </tr>`,
        )
        .join("");
    }
  }

  function renderChecks(): void {
    if (!state) return;
    if (checksEl) checksEl.innerHTML = state.checks.map(checkRow).join("");
    if (checkCount) {
      const passed = state.checks.filter((check) => check.pass).length;
      checkCount.textContent = `${passed}/${state.checks.length} 通过`;
    }
    if (score) {
      score.textContent = `${state.score} / 100`;
      score.className = `pill ${state.score === 100 ? "ok-pill" : "bad-pill"}`;
    }
  }

  function renderEvents(): void {
    if (!eventsEl || !state) return;
    eventsEl.innerHTML =
      state.events.length === 0
        ? `<li class="muted small">暂无活动</li>`
        : state.events
            .slice(0, 8)
            .map(
              (row) => `
              <li class="event-row" data-testid="event-row">
                <span class="muted">${time(row.at)}</span>
                <span class="kind">${escapeHtml(row.kind)}</span>
                <span>${escapeHtml(row.detail)}</span>
              </li>`,
            )
            .join("");
  }

  function render(next: Snapshot): void {
    state = next;
    renderLayers();
    renderPermissions();
    renderFailures();
    renderChecks();
    renderEvents();
  }

  void window.api.arch.snapshot().then(render);
  window.api.arch.onEvent(() => {
    void window.api.arch.snapshot().then(render);
  });

  root
    .querySelector<HTMLButtonElement>('[data-testid="refresh"]')
    ?.addEventListener("click", async () => {
      render(await window.api.arch.refresh());
    });

  window.__prepareShots = async (stage) => {
    document.body.dataset.shot = stage;
    render(await window.api.arch.refresh());
    window.scrollTo(0, 0);
  };

  window.__demo = async () => {
    const next = await window.api.arch.snapshot();
    state = next;
    const find = (id: string, mode: ApprovalMode) =>
      next.matrix.find((row) => row.tool.id === id)?.decisions[mode];
    return {
      score: next.score,
      checks: next.checks.length,
      passed: next.checks.filter((check) => check.pass).length,
      layers: next.layers.length,
      edges: next.edges.length,
      violations: next.violations.length,
      tools: next.tools.length,
      failures: next.failures.length,
      readAllowed: find("read", "never")?.allowed ?? false,
      writeNeverDenied: !(find("write", "never")?.allowed ?? true),
      execNeedsApproval: find("exec", "always")?.needApproval ?? false,
      matrix: next.matrix.length,
    };
  };
}