Browse Source

feat(paas): add run inspector

241880436@seecoder.cn 3 days ago
parent
commit
76ef796669

+ 29 - 1
packages/app/e2e/paas/panel-fixture.tsx

@@ -6,7 +6,13 @@ import type { PaasPlatform } from "../../src/paas"
 export function PanelFixture() {
   const [state, setState] = createStore({ runID: "run_1" })
   const runs: Record<string, Record<string, unknown>> = {
-    run_1: { run_id: "run_1", agent_id: "research", status: "running", output: "第一项任务" },
+    run_1: {
+      run_id: "run_1",
+      agent_id: "research",
+      status: "running",
+      output: "第一项任务",
+      usage: { duration_ms: 5000, cost_usd: 0.0012 },
+    },
     run_2: { run_id: "run_2", agent_id: "research", status: "completed", output: "第二项任务" },
   }
   const control = {
@@ -46,6 +52,28 @@ export function PanelFixture() {
         if (control.failFiles) throw new Error("HTTP 503:文件服务暂时不可用")
         return { files: control.files }
       }
+      if (request.action === "run-events")
+        return {
+          run_id: request.runID,
+          stages: [
+            {
+              stage_id: "collect",
+              status: "completed",
+              details: { round: 1 },
+              started_at: "2026-11-30T10:00:00Z",
+              completed_at: "2026-11-30T10:00:05Z",
+            },
+          ],
+          events: [
+            {
+              sequence: 1,
+              event_type: "tool_call",
+              stage_id: "collect",
+              data: { tool: "Bash", content: "pwd" },
+              created_at: "2026-11-30T10:00:01Z",
+            },
+          ],
+        }
       if (request.action === "download") return { saved: !control.cancelDownload }
       if (request.action === "pause") {
         if (control.failPause) throw new Error("暂时无法暂停,请稍后再试。")

+ 10 - 0
packages/app/e2e/paas/panel.spec.ts

@@ -56,6 +56,16 @@ test("a slow snapshot cannot undo a pause and obsolete approval fields are remov
   await expect(page.getByRole("button", { name: "同意并继续" })).toHaveCount(0)
 })
 
+test("run inspector shows real stages, events, cost and duration", async ({ page }) => {
+  await page.locator(".paas-run-inspector > summary").click()
+  const inspector = page.locator(".paas-run-inspector")
+  await expect(inspector.getByRole("heading", { name: "阶段", exact: true })).toBeVisible()
+  await expect(inspector.getByLabel("执行阶段").getByText("collect", { exact: true })).toBeVisible()
+  await expect(inspector.getByLabel("执行事件").getByText("工具调用", { exact: true })).toBeVisible()
+  await expect(inspector.getByText("$0.0012", { exact: true })).toBeVisible()
+  await expect(inspector.getByLabel("执行阶段").getByText("5.0 秒", { exact: true })).toBeVisible()
+})
+
 test("work files stay hidden until requested and report an honest empty state", async ({ page }) => {
   await expect(page.getByText("没有可保存的工作文件。", { exact: true })).toHaveCount(0)
   await page.getByRole("button", { name: "查看工作文件", exact: true }).click()

+ 1 - 0
packages/app/src/paas.ts

@@ -67,6 +67,7 @@ export type PaasRequest =
   | { action: "upload-file"; agentID: string; threadID?: string; name: string; data: Uint8Array; uploadID?: string }
   | { action: "upload-selected"; agentID: string; threadID?: string; selectionID: string; uploadID: string }
   | { action: "run-files" | "cancel" | "pause"; agentID: string; runID: string }
+  | { action: "run-events"; agentID: string; runID: string; after?: number; source?: "projection" | "service" }
   | { action: "resume"; agentID: string; runID: string; checkpointID: string }
   | {
       action: "confirm"

+ 8 - 0
packages/app/src/pages/paas/README.md

@@ -45,6 +45,14 @@
 - 未归属任何项目线程的平台任务不进入 v1;需要在 P1 任务中心一并处理。
 - 复用线程仍沿用首次项目的归属,跨项目线程所有权留到后续。
 
+## P1 Run Inspector(2026-12-01)
+
+- 任务面板新增“执行检查器”,按需读取平台阶段与事件投影。
+- 展示真实阶段状态、耗时、事件类型、事件内容和平台返回的任务时长/成本。
+- 投影缺失时明确说明“平台未返回”,不推断执行进度。
+- 可切换到执行服务日志回放;读取失败可重试,不影响任务控制与成果。
+- 不包含跨阶段证据台账、checkpoint 可视化时间线和子智能体关系图。
+
 ---
 
 # AgentPaaS 工作台:第一阶段 GUI

+ 72 - 0
packages/app/src/pages/paas/run-inspector-data.test.ts

@@ -0,0 +1,72 @@
+import { expect, test } from "bun:test"
+import { readRunInspector } from "./run-inspector-data"
+
+test("normalizes stages and events with honest missing values", () => {
+  const data = readRunInspector({
+    events: [
+      { sequence: 2, event_type: "tool_call", stage_id: "collect", data: { tool: "Bash", content: "pwd" }, created_at: "2026-11-30T10:00:02Z" },
+      { sequence: 1, event_type: "started", stage_id: "", data: {}, created_at: "2026-11-30T10:00:00Z" },
+      { sequence: 3, event_type: "tool_result", stage_id: "collect", data: { content: "done" }, created_at: "2026-11-30T10:00:03Z" },
+      null,
+    ],
+    stages: [
+      {
+        stage_id: "collect",
+        status: "completed",
+        details: { round: 1 },
+        started_at: "2026-11-30T10:00:00Z",
+        completed_at: "2026-11-30T10:00:05Z",
+      },
+      { stage_id: "", status: "running" },
+    ],
+  })
+  expect(data.stages).toEqual([
+    {
+      id: "collect",
+      status: "completed",
+      startedAt: "2026-11-30T10:00:00Z",
+      completedAt: "2026-11-30T10:00:05Z",
+      durationMs: 5000,
+      details: { round: 1 },
+    },
+    {
+      id: "",
+      status: "running",
+      startedAt: "",
+      completedAt: "",
+      durationMs: undefined,
+      details: {},
+    },
+  ])
+  expect(data.events).toEqual([
+    {
+      sequence: 1,
+      type: "started",
+      stageID: "",
+      at: "2026-11-30T10:00:00Z",
+      detail: "",
+      data: {},
+    },
+    {
+      sequence: 2,
+      type: "tool_call",
+      stageID: "collect",
+      at: "2026-11-30T10:00:02Z",
+      detail: "pwd",
+      data: { tool: "Bash", content: "pwd" },
+    },
+    {
+      sequence: 3,
+      type: "tool_result",
+      stageID: "collect",
+      at: "2026-11-30T10:00:03Z",
+      detail: "done",
+      data: { content: "done" },
+    },
+  ])
+})
+
+test("bad payloads become empty inspector data", () => {
+  expect(readRunInspector(undefined)).toEqual({ stages: [], events: [] })
+  expect(readRunInspector({ stages: "bad", events: {} })).toEqual({ stages: [], events: [] })
+})

+ 68 - 0
packages/app/src/pages/paas/run-inspector-data.ts

@@ -0,0 +1,68 @@
+import { paasRecord, paasText } from "@/paas"
+
+export type InspectorStage = {
+  id: string
+  status: string
+  startedAt: string
+  completedAt: string
+  durationMs?: number
+  details: Record<string, unknown>
+}
+
+export type InspectorEvent = {
+  sequence: number
+  type: string
+  stageID: string
+  at: string
+  detail: string
+  data: Record<string, unknown>
+}
+
+function duration(startedAt: string, completedAt: string) {
+  const start = Date.parse(startedAt)
+  const end = Date.parse(completedAt)
+  if (!Number.isFinite(start) || !Number.isFinite(end) || end < start) return undefined
+  return end - start
+}
+
+export function readRunInspector(input: unknown) {
+  const record = paasRecord(input)
+  const rawStages = Array.isArray(record?.stages) ? record.stages : []
+  const rawEvents = Array.isArray(record?.events) ? record.events : []
+  const stages = rawStages.flatMap((value): InspectorStage[] => {
+    const stage = paasRecord(value)
+    if (!stage) return []
+    const startedAt = paasText(stage.started_at)
+    const completedAt = paasText(stage.completed_at)
+    return [
+      {
+        id: paasText(stage.stage_id),
+        status: paasText(stage.status) || "unknown",
+        startedAt,
+        completedAt,
+        durationMs: duration(startedAt, completedAt),
+        details: paasRecord(stage.details) || {},
+      },
+    ]
+  })
+  const events = rawEvents
+    .flatMap((value): InspectorEvent[] => {
+      const event = paasRecord(value)
+      if (!event) return []
+      const sequence = typeof event.sequence === "number" ? event.sequence : Number(event.sequence)
+      if (!Number.isFinite(sequence)) return []
+      const data = paasRecord(event.data) || {}
+      return [
+        {
+          sequence,
+          type: paasText(event.event_type) || "unknown",
+          stageID: paasText(event.stage_id),
+          at: paasText(event.created_at),
+          detail: paasText(data.content) || paasText(data.message) || paasText(data.summary),
+          data,
+        },
+      ]
+    })
+    .sort((a, b) => a.sequence - b.sequence)
+  return { stages, events }
+}

+ 216 - 0
packages/app/src/pages/paas/run-inspector.tsx

@@ -0,0 +1,216 @@
+import { For, Show, createEffect, createMemo, createSignal, on, onCleanup } from "solid-js"
+import { paasRecord, paasText, type PaasPlatform } from "@/paas"
+import { readRunInspector, type InspectorEvent } from "./run-inspector-data"
+
+const eventLabels: Record<string, string> = {
+  started: "开始",
+  done: "完成",
+  error: "错误",
+  tool_call: "工具调用",
+  tool_result: "工具结果",
+  progress: "进度",
+  approval_required: "等待确认",
+}
+
+const stageLabels: Record<string, string> = {
+  completed: "已完成",
+  running: "进行中",
+  failed: "失败",
+  cancelled: "已取消",
+  pending: "等待中",
+}
+
+const duration = (value?: number) => {
+  if (value === undefined) return ""
+  if (value < 1000) return `${value} ms`
+  return `${(value / 1000).toFixed(value < 10000 ? 1 : 0)} 秒`
+}
+
+const usage = (run: Record<string, unknown>) => paasRecord(run.usage) || {}
+
+function eventLabel(event: InspectorEvent) {
+  return eventLabels[event.type] || event.type
+}
+
+export function RunInspector(props: {
+  api: PaasPlatform
+  agentID: string
+  runID: string
+  run: Record<string, unknown>
+}) {
+  const [state, setState] = createSignal({
+    source: "projection" as "projection" | "service",
+    loading: false,
+    loaded: false,
+    error: "",
+    data: { stages: [], events: [] } as ReturnType<typeof readRunInspector>,
+  })
+  let request = 0
+  let root: HTMLDetailsElement | undefined
+  onCleanup(() => request++)
+
+  const metrics = createMemo(() => {
+    const value = usage(props.run)
+    const data = state().data
+    return {
+      stages: data.stages.length,
+      events: data.events.length,
+      duration: typeof value.duration_ms === "number" ? value.duration_ms : undefined,
+      cost: typeof value.cost_usd === "number" ? value.cost_usd : undefined,
+    }
+  })
+
+  createEffect(
+    on(
+      () => props.runID,
+      () => {
+        request++
+        setState({
+          source: "projection",
+          loading: false,
+          loaded: false,
+          error: "",
+          data: { stages: [], events: [] },
+        })
+        if (root?.open) void load()
+      },
+      { defer: true },
+    ),
+  )
+
+  const load = async (source: "projection" | "service" = "projection") => {
+    const current = ++request
+    setState((value) => ({ ...value, source, loading: true, loaded: false, error: "" }))
+    try {
+      const result = await props.api.request({
+        action: "run-events",
+        agentID: props.agentID,
+        runID: props.runID,
+        source,
+      })
+      if (current !== request) return
+      setState((value) => ({ ...value, loading: false, loaded: true, data: readRunInspector(result) }))
+    } catch (error) {
+      if (current !== request) return
+      setState((value) => ({
+        ...value,
+        loading: false,
+        loaded: false,
+        error: error instanceof Error ? error.message : "执行事件读取失败。",
+      }))
+    }
+  }
+
+  return (
+    <details
+      ref={root}
+      class="paas-run-inspector"
+      onToggle={(event) => {
+        if (event.currentTarget.open && !state().loaded && !state().loading) void load()
+      }}
+    >
+      <summary>
+        执行检查器
+        <span>
+          {metrics().stages ? `${metrics().stages} 阶段` : "阶段"} · {metrics().events || 0} 事件
+        </span>
+      </summary>
+      <div class="paas-inspector-body">
+        <div class="paas-inspector-metrics">
+          <span>
+            阶段<strong>{metrics().stages}</strong>
+          </span>
+          <span>
+            事件<strong>{metrics().events}</strong>
+          </span>
+          <Show when={metrics().duration !== undefined}>
+            <span>
+              时长<strong>{duration(metrics().duration)}</strong>
+            </span>
+          </Show>
+          <Show when={metrics().cost !== undefined}>
+            <span>
+              成本<strong>${metrics().cost!.toFixed(4)}</strong>
+            </span>
+          </Show>
+          <span>
+            来源<strong>{state().source === "service" ? "执行服务" : "平台投影"}</strong>
+          </span>
+        </div>
+        <Show when={state().loading}>
+          <p class="paas-muted" role="status">
+            正在读取执行事件…
+          </p>
+        </Show>
+        <Show when={state().error}>
+          <div class="paas-notice" role="alert">
+            <strong>执行事件读取失败</strong>
+            <p>{state().error}</p>
+            <button type="button" onClick={() => void load(state().source)}>
+              重试读取
+            </button>
+          </div>
+        </Show>
+        <Show when={state().loaded && !state().error}>
+          <Show when={state().data.stages.length}>
+            <section class="paas-inspector-section" aria-label="执行阶段">
+              <h3>阶段</h3>
+              <ol class="paas-inspector-stages">
+                <For each={state().data.stages}>
+                  {(stage) => (
+                    <li data-status={stage.status}>
+                      <div>
+                        <strong>{stage.id || "未命名阶段"}</strong>
+                        <span>{stageLabels[stage.status] || stage.status}</span>
+                        <small>{duration(stage.durationMs)}</small>
+                      </div>
+                      <Show when={Object.keys(stage.details).length}>
+                        <details>
+                          <summary>技术详情</summary>
+                          <pre>{JSON.stringify(stage.details, null, 2)}</pre>
+                        </details>
+                      </Show>
+                    </li>
+                  )}
+                </For>
+              </ol>
+            </section>
+          </Show>
+          <Show when={state().data.events.length}>
+            <section class="paas-inspector-section" aria-label="执行事件">
+              <h3>事件</h3>
+              <ol class="paas-inspector-events">
+                <For each={state().data.events.slice(-100)}>
+                  {(event) => (
+                    <li data-type={event.type}>
+                      <span>{eventLabel(event)}</span>
+                      <strong>{event.stageID || event.detail || `#${event.sequence}`}</strong>
+                      <Show when={event.detail && event.stageID}>
+                        <small>{event.detail}</small>
+                      </Show>
+                      <time>{event.at}</time>
+                    </li>
+                  )}
+                </For>
+              </ol>
+            </section>
+          </Show>
+          <Show when={!state().data.stages.length && !state().data.events.length}>
+            <p class="paas-muted">平台未返回阶段或事件记录;这不表示任务没有执行。</p>
+          </Show>
+        </Show>
+        <div class="paas-inspector-actions">
+          <button type="button" disabled={state().loading} onClick={() => void load("projection")}>
+            刷新平台投影
+          </button>
+          <button type="button" disabled={state().loading} onClick={() => void load("service")}>
+            回放执行服务日志
+          </button>
+        </div>
+        <Show when={paasText(props.run.checkpoint_id)}>
+          <p class="paas-muted">最近恢复点:{paasText(props.run.checkpoint_id)}</p>
+        </Show>
+      </div>
+    </details>
+  )
+}

+ 2 - 0
packages/app/src/pages/paas/run-panel.tsx

@@ -1,6 +1,7 @@
 import { For, Show, createEffect, createMemo, on, onCleanup } from "solid-js"
 import { ResearchReport } from "./report"
 import { ResearchProgress } from "./progress"
+import { RunInspector } from "./run-inspector"
 import { ResearchIssue } from "./issue"
 import { usePlatform } from "@/context/platform"
 import { createStore, reconcile } from "solid-js/store"
@@ -334,6 +335,7 @@ export function PaasRunPanel(props: {
         </p>
       </Show>
       <ResearchProgress run={state.run} />
+      <RunInspector api={props.api} agentID={props.agentID} runID={props.runID} run={state.run} />
       <Show when={state.busy}>
         <p role="status">{state.busy}…</p>
       </Show>

+ 101 - 0
packages/app/src/pages/paas/studio.css

@@ -1043,3 +1043,104 @@
 .paas-workspace :is(input, textarea)[aria-invalid="true"] {
   border-color: light-dark(#bc665a, #df8e7f);
 }
+
+/* Run Inspector: real stages/events only, with advanced replay kept secondary. */
+.paas-run-inspector {
+  margin-top: 18px;
+  border-top: 1px solid var(--border-weak-base);
+  padding-top: 14px;
+}
+.paas-run-inspector > summary {
+  display: flex;
+  align-items: baseline;
+  justify-content: space-between;
+  gap: 12px;
+  width: 100%;
+  color: var(--text-base);
+  font-size: var(--paas-type-caption);
+}
+.paas-run-inspector > summary span {
+  color: var(--text-weak);
+  font-size: var(--paas-type-meta);
+}
+.paas-inspector-body {
+  display: grid;
+  gap: 14px;
+  margin-top: 14px;
+}
+.paas-inspector-metrics {
+  display: flex;
+  flex-wrap: wrap;
+  gap: 8px 18px;
+  color: var(--text-weak);
+  font-size: var(--paas-type-meta);
+}
+.paas-inspector-metrics span {
+  display: inline-flex;
+  align-items: baseline;
+  gap: 5px;
+}
+.paas-inspector-metrics strong {
+  color: var(--text-base);
+  font-size: var(--paas-type-caption);
+}
+.paas-inspector-section h3 {
+  margin: 0 0 8px;
+  font-size: var(--paas-type-caption);
+}
+.paas-inspector-stages,
+.paas-inspector-events {
+  display: grid;
+  gap: 6px;
+  margin: 0;
+  padding: 0;
+  list-style: none;
+}
+.paas-inspector-stages > li,
+.paas-inspector-events > li {
+  min-width: 0;
+  padding: 8px 10px;
+  border: 1px solid var(--border-weak-base);
+  border-radius: 8px;
+  background: var(--background-base);
+}
+.paas-inspector-stages > li > div {
+  display: flex;
+  align-items: baseline;
+  gap: 8px;
+}
+.paas-inspector-stages > li span,
+.paas-inspector-stages > li small,
+.paas-inspector-events > li > span,
+.paas-inspector-events > li > time {
+  color: var(--text-weak);
+  font-size: var(--paas-type-meta);
+}
+.paas-inspector-stages > li small,
+.paas-inspector-events > li > time {
+  margin-left: auto;
+}
+.paas-inspector-events > li {
+  display: grid;
+  grid-template-columns: auto minmax(0, 1fr) auto;
+  gap: 4px 10px;
+  align-items: baseline;
+}
+.paas-inspector-events > li > strong,
+.paas-inspector-events > li > small {
+  min-width: 0;
+  overflow-wrap: anywhere;
+}
+.paas-inspector-events > li > small {
+  grid-column: 2;
+  color: var(--text-weak);
+  font-size: var(--paas-type-meta);
+}
+.paas-inspector-stages > li pre {
+  max-height: 220px;
+}
+.paas-inspector-actions {
+  display: flex;
+  flex-wrap: wrap;
+  gap: 8px;
+}

+ 33 - 0
packages/desktop/src/main/paas.test.ts

@@ -375,6 +375,39 @@ test("task controls, input files and downloads use the authenticated platform ro
   }
 })
 
+test("run inspector events use the authenticated event route", async () => {
+  const requests: string[] = []
+  const server = Bun.serve({
+    port: 0,
+    hostname: "127.0.0.1",
+    fetch(request) {
+      const url = new URL(request.url)
+      if (url.pathname.endsWith("/auth/me")) return new Response("missing", { status: 404 })
+      expect(request.headers.get("Authorization")).toBe("Bearer test-only")
+      requests.push(`${url.pathname}${url.search}`)
+      if (url.pathname.endsWith("/agents")) return Response.json({ agents: [] })
+      return Response.json({ run_id: "r", events: [], stages: [] })
+    },
+  })
+  const connections = createPaasConnections()
+  try {
+    await connections.connect(1, { url: server.url.origin, apiKey: "test-only" })
+    await connections.request(1, {
+      action: "run-events",
+      agentID: "a",
+      runID: "r",
+      after: 4,
+      source: "service",
+    })
+    expect(requests.at(-1)).toBe("/api/v1/agents/a/runs/r/events?after=4&source=service")
+    await expect(
+      connections.request(1, { action: "run-events", agentID: "a", runID: "r", after: -1 }),
+    ).rejects.toThrow("事件游标无效")
+  } finally {
+    await server.stop(true)
+  }
+})
+
 test("detaching closes only the subscription and keeps the backend job alive", async () => {
   const started = Promise.withResolvers<void>()
   const requests: string[] = []

+ 13 - 1
packages/desktop/src/main/paas.ts

@@ -312,10 +312,22 @@ export function createPaasConnections(fetcher: typeof fetch = fetch) {
             : undefined,
         )
       }
-      if (["run-files", "download", "preview-file", "cancel", "pause", "resume", "confirm"].includes(input?.action)) {
+      if (
+        ["run-files", "run-events", "download", "preview-file", "cancel", "pause", "resume", "confirm"].includes(
+          input?.action,
+        )
+      ) {
         if (!("agentID" in input) || !("runID" in input)) throw new Error("缺少任务编号。")
         const path = `/agents/${identifier(input.agentID)}/runs/${identifier(input.runID)}`
         if (input.action === "run-files") return request(connection, `${path}/workspace`)
+        if (input.action === "run-events") {
+          if (input.after !== undefined && (!Number.isSafeInteger(input.after) || input.after < 0))
+            throw new Error("事件游标无效。")
+          const query = new URLSearchParams()
+          if (input.after !== undefined) query.set("after", String(input.after))
+          if (input.source) query.set("source", input.source)
+          return request(connection, `${path}/events${query.size ? `?${query}` : ""}`)
+        }
         if (input.action === "preview-file") {
           if (!input.path && !input.artifactID) throw new Error("缺少文件路径。")
           const resource = input.artifactID