示例工程 60-tool-registry-approval

60-tool-registry-approval/app/.tsc/src/App.js

javascript · 12 KB

function escapeHtml(text) {
    return text.replace(/[&<>"]/g, (char) => {
        if (char === "&")
            return "&amp;";
        if (char === "<")
            return "&lt;";
        if (char === ">")
            return "&gt;";
        return "&quot;";
    });
}
const RISK_CLASS = {
    read: "read",
    write: "write",
    exec: "exec",
    network: "network",
};
const STATUS_CLASS = {
    ok: "done",
    denied: "error",
    "approval-required": "tool",
    timeout: "cancel",
    invalid: "error",
};
function toolRows(snapshot) {
    return snapshot.tools
        .map((tool) => `<tr data-testid="tool-row">
        <td><code>${escapeHtml(tool.name)}</code></td>
        <td><span class="tag ${RISK_CLASS[tool.risk]}">${tool.risk}</span></td>
        <td>${tool.needsApproval ? "审批" : "自动"}</td>
        <td>${tool.timeoutMs}ms</td>
        <td>${tool.fields.length}</td>
        <td class="muted small">${escapeHtml(tool.description)}</td>
      </tr>`)
        .join("");
}
function scenarioButtons(scenarios) {
    return scenarios
        .map((scenario) => `<button class="scenario" data-testid="scenario-${scenario.id}" data-scenario="${scenario.id}">
        <b>${escapeHtml(scenario.label)}</b>
        <span class="muted small">${escapeHtml(scenario.toolId)}</span>
      </button>`)
        .join("");
}
function decisionButton(decision, label, kind = "") {
    return `<button class="btn ${kind}" data-testid="decision-${decision}" data-decision="${decision}">${label}</button>`;
}
function pendingCard(scenario, grants) {
    if (!scenario) {
        return `<p class="muted small">从左侧选择一个场景,审批卡会显示参数与可选决定。</p>`;
    }
    const grant = grants.includes(scenario.toolId);
    return `
    <div class="pending-head">
      <span class="tag ${grant ? "done" : "tool"}">${grant ? "已有会话授权" : "待处理"}</span>
      <b data-testid="pending-label">${escapeHtml(scenario.label)}</b>
      <code data-testid="pending-tool">${escapeHtml(scenario.toolId)}</code>
    </div>
    <pre class="args" data-testid="pending-args">${escapeHtml(JSON.stringify(scenario.args, null, 2))}</pre>
    <p class="muted small pending-note">${escapeHtml(scenario.note)}</p>
    <div class="decisions">
      ${decisionButton("allow-once", "允许一次", "primary")}
      ${decisionButton("allow-session", "本会话允许")}
      ${decisionButton("use-grant", "使用已有授权")}
      ${decisionButton("deny", "拒绝")}
    </div>
  `;
}
function auditRows(audit) {
    if (audit.length === 0) {
        return `<tr><td colspan="7" class="muted small">暂无审计记录</td></tr>`;
    }
    return [...audit]
        .reverse()
        .map((entry) => `<tr data-testid="audit-row">
        <td>${entry.seq}</td>
        <td><code>${escapeHtml(entry.scenarioId)}</code></td>
        <td><span class="tag ${STATUS_CLASS[entry.status]}">${entry.status}</span></td>
        <td>${escapeHtml(entry.decision)}</td>
        <td>${escapeHtml(entry.approvedBy)}</td>
        <td>${entry.durationMs}ms</td>
        <td class="muted small">${escapeHtml(entry.summary)}</td>
      </tr>`)
        .join("");
}
function checkRows(snapshot) {
    return snapshot.checks
        .map((check) => `<li class="check-row" data-testid="check-row">
        <span class="tag ${check.pass ? "done" : "error"}">${check.pass ? "PASS" : "FAIL"}</span>
        <span>${escapeHtml(check.label)}</span>
        <code>${escapeHtml(check.detail)}</code>
      </li>`)
        .join("");
}
export function mountApp(root) {
    root.innerHTML = `
    <div class="app">
      <header class="header">
        <div class="brand">
          <span class="logo">T</span>
          <div>
            <h1>工具注册表与审批</h1>
            <span class="muted small">schema · 风险分级 · 审批 · 超时 · 审计(离线)</span>
          </div>
        </div>
        <div class="header-side">
          <span class="pill ok-pill">offline</span>
          <span class="pill" data-testid="grants">0 grants</span>
          <span class="pill ok-pill" data-testid="score">—</span>
        </div>
      </header>

      <div class="banner">
        工具在主进程执行;审批是用户决定,超时与参数错误在执行前就被拦截。
      </div>

      <main class="layout">
        <div class="column">
          <section class="card pad registry-card">
            <div class="card-head">
              <h2>注册表</h2>
              <span class="muted small" data-testid="tool-count">—</span>
            </div>
            <table class="registry">
              <thead><tr><th>工具</th><th>风险</th><th>审批</th><th>超时</th><th>字段</th><th>说明</th></tr></thead>
              <tbody data-testid="tools"></tbody>
            </table>
          </section>

          <section class="card pad scenarios-card">
            <div class="card-head">
              <h2>场景</h2>
              <span class="muted small">点击后进入审批</span>
            </div>
            <div class="scenarios" data-testid="scenarios"></div>
            <button class="btn reset" data-testid="reset">清空授权与审计</button>
          </section>
        </div>

        <div class="column">
          <section class="card pad approval-card">
            <div class="card-head">
              <h2>审批请求</h2>
              <span class="muted small">allow / deny / grant</span>
            </div>
            <div data-testid="pending"></div>
          </section>

          <section class="card pad audit-card">
            <div class="card-head">
              <h2>审计日志</h2>
              <span class="muted small" data-testid="audit-count">0 条</span>
            </div>
            <table class="audit">
              <thead><tr><th>#</th><th>场景</th><th>状态</th><th>决定</th><th>批准者</th><th>耗时</th><th>摘要</th></tr></thead>
              <tbody data-testid="audit"></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>
        </div>
      </main>
    </div>
  `;
    const score = root.querySelector('[data-testid="score"]');
    const grantsPill = root.querySelector('[data-testid="grants"]');
    const toolCount = root.querySelector('[data-testid="tool-count"]');
    const toolsEl = root.querySelector('[data-testid="tools"]');
    const scenariosEl = root.querySelector('[data-testid="scenarios"]');
    const pendingEl = root.querySelector('[data-testid="pending"]');
    const auditEl = root.querySelector('[data-testid="audit"]');
    const auditCount = root.querySelector('[data-testid="audit-count"]');
    const checksEl = root.querySelector('[data-testid="checks"]');
    const checkCount = root.querySelector('[data-testid="check-count"]');
    let state = null;
    let pending = null;
    let busy = false;
    function render() {
        if (!state)
            return;
        if (toolsEl)
            toolsEl.innerHTML = toolRows(state);
        if (toolCount)
            toolCount.textContent = `${state.tools.length} 个`;
        if (scenariosEl)
            scenariosEl.innerHTML = scenarioButtons(state.scenarios);
        if (pendingEl)
            pendingEl.innerHTML = pendingCard(pending, state.grants);
        if (auditEl)
            auditEl.innerHTML = auditRows(state.audit);
        if (auditCount)
            auditCount.textContent = `${state.audit.length} 条`;
        if (checksEl)
            checksEl.innerHTML = checkRows(state);
        if (checkCount) {
            const passed = state.checks.filter((check) => check.pass).length;
            checkCount.textContent = `${passed}/${state.checks.length} 通过`;
        }
        if (grantsPill)
            grantsPill.textContent = `${state.grants.length} grants`;
        if (score) {
            score.textContent = `${state.score} / 100`;
            score.className = `pill ${state.score === 100 ? "ok-pill" : "bad-pill"}`;
        }
        root
            .querySelectorAll("[data-scenario]")
            .forEach((button) => {
            button.disabled = busy;
            button.classList.toggle("active", button.dataset.scenario === pending?.id);
        });
        root
            .querySelectorAll("[data-decision]")
            .forEach((button) => {
            button.disabled = busy;
        });
    }
    async function refresh() {
        state = await window.api.tools.snapshot();
        render();
    }
    async function runOne(scenarioId, decision) {
        if (busy)
            return null;
        busy = true;
        render();
        try {
            const response = await window.api.tools.run({ scenarioId, decision });
            state = response.snapshot;
            return response.entry;
        }
        finally {
            busy = false;
            pending = null;
            render();
        }
    }
    async function runSequence() {
        await runOne("read-config", "deny");
        await runOne("write-notes", "deny");
        await runOne("write-notes", "allow-once");
        await runOne("write-notes", "allow-session");
        await runOne("write-notes", "use-grant");
        await runOne("run-tests", "use-grant");
        await runOne("bad-args", "allow-once");
        await runOne("outside", "allow-once");
        await runOne("slow-tool", "allow-once");
    }
    void refresh();
    window.api.tools.onChanged(() => {
        void refresh();
    });
    root.addEventListener("click", (event) => {
        const target = event.target;
        const scenarioButton = target.closest("[data-scenario]");
        if (scenarioButton?.dataset.scenario) {
            const id = scenarioButton.dataset.scenario;
            pending = state?.scenarios.find((scenario) => scenario.id === id) ?? null;
            render();
            return;
        }
        const decisionButton = target.closest("[data-decision]");
        if (decisionButton?.dataset.decision && pending) {
            void runOne(pending.id, decisionButton.dataset.decision);
        }
    });
    root
        .querySelector('[data-testid="reset"]')
        ?.addEventListener("click", async () => {
        state = await window.api.tools.reset();
        pending = null;
        render();
    });
    window.__prepareShots = async (stage) => {
        document.body.dataset.shot = stage;
        const reset = await window.api.tools.reset();
        state = reset;
        pending = null;
        await runSequence();
        if (stage === "approval") {
            pending =
                state?.scenarios.find((scenario) => scenario.id === "run-tests") ??
                    null;
        }
        else if (stage === "audit") {
            pending = null;
        }
        window.scrollTo(0, 0);
        render();
    };
    window.__demo = async () => {
        state = await window.api.tools.reset();
        pending = null;
        await runSequence();
        const find = (scenarioId, decision) => state?.audit.find((entry) => entry.scenarioId === scenarioId &&
            (decision ? entry.decision === decision : true));
        return {
            score: state?.score ?? 0,
            checks: state?.checks.length ?? 0,
            passed: state?.checks.filter((check) => check.pass).length ?? 0,
            tools: state?.tools.length ?? 0,
            scenarios: state?.scenarios.length ?? 0,
            audit: state?.audit.length ?? 0,
            grants: state?.grants.length ?? 0,
            readAuto: find("read-config")?.status === "ok",
            writeDenied: find("write-notes", "deny")?.status === "denied",
            grantReuse: find("write-notes", "grant")?.status === "ok",
            execApproval: find("run-tests", "use-grant")?.status === "approval-required",
            invalid: find("bad-args")?.status === "invalid",
            timeout: find("slow-tool")?.status === "timeout",
            outside: find("outside")?.status === "denied",
        };
    };
}
//# sourceMappingURL=App.js.map