Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat: add verify interaction cost reporting (#16845)

Arvin Xu63dc0eb931c5
diff --git a/.agents/skills/agent-testing/SKILL.md b/.agents/skills/agent-testing/SKILL.md
index 7a150a74da6..ace19e10e1f 100644
--- a/.agents/skills/agent-testing/SKILL.md
+++ b/.agents/skills/agent-testing/SKILL.md
@@ -388,21 +388,23 @@ Surface guides above carry the detailed workflows. Shared infrastructure:
All under `.agents/skills/agent-testing/scripts/`:
-| Script | Usage |
-| --------------------------- | ------------------------------------------------------------------------------------------- |
-| `test-env.sh` | Print/export the resolved local test env and ports |
-| `setup-auth.sh` | One-stop auth setup & status check (`status` / `cli` / `web`) |
-| `init-dev-env.sh` | Self-contained local dev env (`setup-db` / `seed-user` / `dev-next` / `dev`) |
-| `app-probe.sh` | LobeHub app probes: `auth` / `route` / `ops` / `goto <path>` / `errors` |
-| `record-gif.sh` | Frame-sequence → GIF for time-based behavior (streaming, timers, animations) |
-| `report-init.sh` | Scaffold a structured test report (Step 3) |
-| `check-screen-recording.sh` | Preflight: OS screen-capture works (macOS Screen Recording + display awake) |
-| `electron-dev.sh` | Manage Electron dev env (start/stop/status/restart, CDP 9222) |
-| `cdp-screenshot.sh` | Electron/Chrome screenshot via RAW CDP (bypasses agent-browser daemon); `--check` preflight |
-| `capture-app-window.sh` | Screenshot a specific app window (general; used by bot tests) |
-| `record-app-screen.sh` | Record app screen (video + periodic screenshots) |
-| `record-electron-demo.sh` | Record Electron app demo with ffmpeg |
-| `agent-gateway/` | Gateway probe / dump / analyze tools |
+| Script | Usage |
+| ------------------------------- | ------------------------------------------------------------------------------------------- |
+| `test-env.sh` | Print/export the resolved local test env and ports |
+| `setup-auth.sh` | One-stop auth setup & status check (`status` / `cli` / `web`) |
+| `init-dev-env.sh` | Self-contained local dev env (`setup-db` / `seed-user` / `dev-next` / `dev`) |
+| `app-probe.sh` | LobeHub app probes: `auth` / `route` / `ops` / `goto <path>` / `errors` |
+| `agent-browser-klm.mjs` | Wrap `agent-browser`, run the real action, and append a GOMS-KLM interaction atom JSONL |
+| `agent-browser-klm-analyze.mjs` | Summarize interaction JSONL into `result.json.interactionCost` / markdown cost output |
+| `record-gif.sh` | Frame-sequence → GIF for time-based behavior (streaming, timers, animations) |
+| `report-init.sh` | Scaffold a structured test report (Step 3) |
+| `check-screen-recording.sh` | Preflight: OS screen-capture works (macOS Screen Recording + display awake) |
+| `electron-dev.sh` | Manage Electron dev env (start/stop/status/restart, CDP 9222) |
+| `cdp-screenshot.sh` | Electron/Chrome screenshot via RAW CDP (bypasses agent-browser daemon); `--check` preflight |
+| `capture-app-window.sh` | Screenshot a specific app window (general; used by bot tests) |
+| `record-app-screen.sh` | Record app screen (video + periodic screenshots) |
+| `record-electron-demo.sh` | Record Electron app demo with ffmpeg |
+| `agent-gateway/` | Gateway probe / dump / analyze tools |
`app-probe.sh` is the LobeHub-specific fast path into app state — auth check,
current route, running operations, and `goto <path>` quick navigation
@@ -410,6 +412,40 @@ current route, running operations, and `goto <path>` quick navigation
jump straight to the state under test instead of clicking through the UI. See
[ui/electron.md](./ui/electron.md#lobehub-probes--quick-navigation) for usage.
+### Agent-browser interaction-cost tracing
+
+For UI verification runs, drive cost-bearing browser actions through the KLM
+wrapper so the same action also records a user-equivalent interaction atom:
+
+```bash
+TRACE="$DIR/interaction-trace.jsonl"
+
+./.agents/skills/agent-testing/scripts/agent-browser-klm.mjs \
+ --klm-trace "$TRACE" --klm-phase login --klm-check case-1 \
+ --session lobehub-dev click @e3
+
+./.agents/skills/agent-testing/scripts/agent-browser-klm.mjs mental \
+ --klm-trace "$TRACE" --klm-phase first-view --m 2 --score 3 \
+ --confidence 0.75 --reason "First view requires understanding run status and next action"
+```
+
+The wrapper forwards every non-`--klm-*` argument to `agent-browser`. Physical
+actions are inferred from the browser command (`click → P+K`, `fill/type →
+P+T(n)`, `press → K`, `wait → R`). Mental operators (`M`) are explicit agent
+estimates recorded with the `mental` subcommand after the first meaningful page
+view or a decision-heavy inspection step.
+
+Analyze the trace before publishing:
+
+```bash
+./.agents/skills/agent-testing/scripts/agent-browser-klm-analyze.mjs \
+ --trace "$TRACE" --result "$DIR/result.json" --write
+```
+
+This writes `result.json.interactionCost`; `verify ingest-report` stores it on
+the verify run metadata so the report can render a separate interaction-cost
+section.
+
## Step 3 — Structured report (mandatory deliverable)
Every automated test session ends with a structured, evidence-backed report —
diff --git a/.agents/skills/agent-testing/references/agent-browser.md b/.agents/skills/agent-testing/references/agent-browser.md
index 2d0d4cecd72..fa5550ff29d 100644
--- a/.agents/skills/agent-testing/references/agent-browser.md
+++ b/.agents/skills/agent-testing/references/agent-browser.md
@@ -27,6 +27,44 @@ agent-browser wait --load networkidle
agent-browser snapshot -i # Check result
```
+## GOMS-KLM interaction tracing
+
+When a UI verification should report user-side interaction cost, run
+`agent-browser` through the agent-testing wrapper:
+
+```bash
+TRACE="$DIR/interaction-trace.jsonl"
+
+./.agents/skills/agent-testing/scripts/agent-browser-klm.mjs \
+ --klm-trace "$TRACE" --klm-phase settings --klm-check case-1 \
+ --session lobehub-dev click @e4
+```
+
+The wrapper forwards the real command to `agent-browser` and appends one JSONL
+event. Physical actions are inferred from the command (`click → P+K`,
+`fill/type → P+T(n)`, `press → K`, `wait → R`). A click only counts the user
+activation; if it causes loading or async work, follow it with an explicit
+`agent-browser wait ...` so response time is counted as `R`.
+
+Mental effort is intentionally not guessed from DOM shape. After the first
+meaningful page view, add an explicit agent estimate:
+
+```bash
+./.agents/skills/agent-testing/scripts/agent-browser-klm.mjs mental \
+ --klm-trace "$TRACE" --klm-phase first-view --m 2 --score 3 \
+ --confidence 0.75 --reason "Need to understand current page state and choose the verify path"
+```
+
+Before publish, summarize the trace into the structured report:
+
+```bash
+./.agents/skills/agent-testing/scripts/agent-browser-klm-analyze.mjs \
+ --trace "$TRACE" --result "$DIR/result.json" --write
+```
+
+This populates `result.json.interactionCost` with the `goms-klm@lobe-v1`
+summary. The raw trace stays in the local report directory for audit/debug.
+
## Command Chaining
```bash
diff --git a/.agents/skills/agent-testing/references/report.md b/.agents/skills/agent-testing/references/report.md
index 777ca2d876b..3b5c9a89888 100644
--- a/.agents/skills/agent-testing/references/report.md
+++ b/.agents/skills/agent-testing/references/report.md
@@ -185,6 +185,15 @@ missing; a blocked case is not a pass).
],
"commit": "abc1234",
"createdAt": "2026-06-11T15:30:00+08:00",
+ "interactionCost": {
+ "model": "goms-klm@lobe-v1",
+ "scope": "user-equivalent",
+ "totalSeconds": 8.1,
+ "activeSeconds": 6.1,
+ "waitSeconds": 2,
+ "operators": { "K": 1, "P": 2, "H": 0, "M": 2, "T_chars": 5, "R_ms": 2000 },
+ "phases": []
+ },
"summary": {
"total": 1,
"passed": 1,
@@ -202,6 +211,14 @@ missing; a blocked case is not a pass).
polish, copy quality); omit it for purely binary runs. `verdict` is the single
word the user reads first: `pass`, `fail`, or `partial`.
+`interactionCost` is optional and run-level. For UI runs driven through
+`agent-browser`, create `interaction-trace.jsonl` with
+`scripts/agent-browser-klm.mjs`, then run
+`scripts/agent-browser-klm-analyze.mjs --trace "$DIR/interaction-trace.jsonl" --result "$DIR/result.json" --write`. The summary is a user-equivalent GOMS-KLM
+estimate: physical browser actions are derived from agent-browser commands,
+while mental operators (`M`) are explicit agent estimates recorded with the
+wrapper's `mental` subcommand.
+
When published (Step 4), `verify ingest-report` maps each case onto a check
result: `name`→title, `status`/`result`→verdict, `observation` (or
`keyObservation`)→the result's key observation, and `evidence` paths→uploaded
diff --git a/.agents/skills/agent-testing/scripts/agent-browser-klm-analyze.mjs b/.agents/skills/agent-testing/scripts/agent-browser-klm-analyze.mjs
new file mode 100755
index 00000000000..1239ec826c1
--- /dev/null
+++ b/.agents/skills/agent-testing/scripts/agent-browser-klm-analyze.mjs
@@ -0,0 +1,232 @@
+#!/usr/bin/env node
+/**
+ * Analyze agent-browser KLM trace JSONL into a compact interactionCost object.
+ */
+
+import { readFile, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const MODEL = 'goms-klm@lobe-v1';
+const TIMING_SECONDS = {
+ H: 0.4,
+ K: 0.2,
+ M: 1.35,
+ P: 1.1,
+ T_char: 0.2,
+};
+
+const emptyOperators = () => ({
+ H: 0,
+ K: 0,
+ M: 0,
+ P: 0,
+ R_ms: 0,
+ T_chars: 0,
+});
+
+const usage = () => {
+ console.log(`Usage:
+ agent-browser-klm-analyze.mjs --trace interaction-trace.jsonl [--result result.json --write] [--markdown]
+
+Options:
+ --trace <file> JSONL trace from agent-browser-klm.mjs
+ --result <file> result.json to patch with interactionCost
+ --write overwrite --result with interactionCost
+ --markdown print a markdown section instead of JSON
+ --model <id> model id label (default: ${MODEL})`);
+};
+
+const parseArgs = (argv) => {
+ const options = { markdown: false, model: MODEL, write: false };
+
+ for (let index = 0; index < argv.length; index += 1) {
+ const arg = argv[index];
+ if (arg === '--help' || arg === '-h') {
+ usage();
+ process.exit(0);
+ } else if (arg === '--trace') options.trace = argv[++index];
+ else if (arg === '--result') options.result = argv[++index];
+ else if (arg === '--model') options.model = argv[++index] ?? MODEL;
+ else if (arg === '--write') options.write = true;
+ else if (arg === '--markdown') options.markdown = true;
+ else throw new Error(`Unknown option: ${arg}`);
+ }
+
+ if (!options.trace) throw new Error('--trace is required');
+ if (options.write && !options.result) throw new Error('--write requires --result');
+
+ return options;
+};
+
+const addOperators = (target, source = {}) => {
+ target.H += Number(source.H ?? 0);
+ target.K += Number(source.K ?? 0);
+ target.M += Number(source.M ?? 0);
+ target.P += Number(source.P ?? 0);
+ target.R_ms += Number(source.R_ms ?? 0);
+ target.T_chars += Number(source.T_chars ?? 0);
+};
+
+const round = (value) => Math.round(value * 100) / 100;
+
+const secondsFromOperators = (operators) =>
+ round(
+ operators.H * TIMING_SECONDS.H +
+ operators.K * TIMING_SECONDS.K +
+ operators.M * TIMING_SECONDS.M +
+ operators.P * TIMING_SECONDS.P +
+ operators.T_chars * TIMING_SECONDS.T_char +
+ operators.R_ms / 1000,
+ );
+
+const activeSecondsFromOperators = (operators) =>
+ round(
+ operators.H * TIMING_SECONDS.H +
+ operators.K * TIMING_SECONDS.K +
+ operators.M * TIMING_SECONDS.M +
+ operators.P * TIMING_SECONDS.P +
+ operators.T_chars * TIMING_SECONDS.T_char,
+ );
+
+const phaseKey = (event) =>
+ event.phase?.id || event.phase?.checkItemId || event.checkItemId || 'unscoped';
+
+const phaseLabel = (event, key) =>
+ event.phase?.label || (key === 'unscoped' ? event.phase?.checkItemId : key) || 'Unscoped actions';
+
+const parseTrace = async (tracePath) => {
+ const raw = await readFile(tracePath, 'utf8');
+ return raw
+ .split(/\r?\n/)
+ .map((line) => line.trim())
+ .filter(Boolean)
+ .map((line, index) => {
+ try {
+ return JSON.parse(line);
+ } catch (error) {
+ throw new Error(`Invalid JSONL at line ${index + 1}: ${error.message}`, { cause: error });
+ }
+ });
+};
+
+const summarize = (events, { model, tracePath }) => {
+ const operators = emptyOperators();
+ const phases = new Map();
+ const categoryCounts = {};
+ const mentalEstimates = [];
+ let actualAgentMs = 0;
+
+ for (const event of events) {
+ const eventOperators = event.klm?.operators ?? emptyOperators();
+ addOperators(operators, eventOperators);
+
+ const category = event.klm?.category ?? 'unknown';
+ categoryCounts[category] = (categoryCounts[category] ?? 0) + 1;
+ actualAgentMs += Number(event.durationMs ?? 0);
+
+ if (event.type === 'mental_estimate' && event.mentalEstimate) {
+ mentalEstimates.push({
+ confidence: event.mentalEstimate.confidence,
+ mOperators: event.mentalEstimate.mOperators,
+ phaseId: event.phase?.id,
+ reason: event.mentalEstimate.reason,
+ score: event.mentalEstimate.score,
+ });
+ }
+
+ const key = phaseKey(event);
+ const existing = phases.get(key) ?? {
+ actionCount: 0,
+ actualAgentMs: 0,
+ checkItemId: event.phase?.checkItemId,
+ id: key,
+ label: phaseLabel(event, key),
+ operators: emptyOperators(),
+ };
+
+ addOperators(existing.operators, eventOperators);
+ existing.actionCount += 1;
+ existing.actualAgentMs += Number(event.durationMs ?? 0);
+ phases.set(key, existing);
+ }
+
+ const phaseItems = [...phases.values()].map((phase) => ({
+ ...phase,
+ activeSeconds: activeSecondsFromOperators(phase.operators),
+ actualAgentSeconds: round(phase.actualAgentMs / 1000),
+ seconds: secondsFromOperators(phase.operators),
+ waitSeconds: round(phase.operators.R_ms / 1000),
+ }));
+
+ return {
+ actionCount: events.length,
+ activeSeconds: activeSecondsFromOperators(operators),
+ actualAgentSeconds: round(actualAgentMs / 1000),
+ categoryCounts,
+ generatedAt: new Date().toISOString(),
+ mentalEstimates,
+ model,
+ operators,
+ phases: phaseItems.sort((a, b) => b.seconds - a.seconds),
+ scope: 'user-equivalent',
+ sourceTrace: path.basename(tracePath),
+ timingSeconds: TIMING_SECONDS,
+ totalSeconds: secondsFromOperators(operators),
+ waitSeconds: round(operators.R_ms / 1000),
+ };
+};
+
+const toMarkdown = (summary) => {
+ const topPhases = summary.phases.slice(0, 5);
+ const phaseRows = topPhases
+ .map(
+ (phase) =>
+ `| ${phase.label} | ${phase.seconds.toFixed(2)}s | ${phase.activeSeconds.toFixed(2)}s | ${phase.waitSeconds.toFixed(2)}s |`,
+ )
+ .join('\n');
+
+ return `## GOMS-KLM 交互成本
+
+- 模型:\`${summary.model}\`
+- 用户等效总成本:${summary.totalSeconds.toFixed(2)}s
+- 主动操作成本:${summary.activeSeconds.toFixed(2)}s
+- 系统等待成本:${summary.waitSeconds.toFixed(2)}s
+- 操作符:K=${summary.operators.K}, P=${summary.operators.P}, H=${summary.operators.H}, M=${summary.operators.M}, T=${summary.operators.T_chars} chars, R=${summary.operators.R_ms}ms
+
+| 阶段 | 总成本 | 主动 | 等待 |
+| --- | ---: | ---: | ---: |
+${phaseRows || '| 无 | 0.00s | 0.00s | 0.00s |'}
+`;
+};
+
+const patchResult = async (resultPath, summary, write) => {
+ const raw = await readFile(resultPath, 'utf8');
+ const result = JSON.parse(raw);
+ result.interactionCost = summary;
+
+ if (write) {
+ await writeFile(resultPath, `${JSON.stringify(result, null, 2)}\n`, 'utf8');
+ }
+
+ return result;
+};
+
+const main = async () => {
+ const options = parseArgs(process.argv.slice(2));
+ const tracePath = path.resolve(options.trace);
+ const events = await parseTrace(tracePath);
+ const summary = summarize(events, { model: options.model, tracePath });
+
+ if (options.result) await patchResult(path.resolve(options.result), summary, options.write);
+
+ if (options.markdown) console.log(toMarkdown(summary));
+ else console.log(JSON.stringify(summary, null, 2));
+};
+
+if (process.argv[1] === fileURLToPath(import.meta.url)) {
+ main().catch((error) => {
+ console.error('[agent-browser-klm-analyze]', error.message);
+ process.exit(1);
+ });
+}
diff --git a/.agents/skills/agent-testing/scripts/agent-browser-klm.mjs b/.agents/skills/agent-testing/scripts/agent-browser-klm.mjs
new file mode 100755
index 00000000000..0213dbbfac7
--- /dev/null
+++ b/.agents/skills/agent-testing/scripts/agent-browser-klm.mjs
@@ -0,0 +1,426 @@
+#!/usr/bin/env node
+/**
+ * agent-browser-klm.mjs
+ *
+ * Thin wrapper around `agent-browser` that records each executed command as an
+ * interaction atom for GOMS-KLM analysis. Unknown flags are forwarded. Browser
+ * output is intentionally silenced because the agent-browser daemon can keep
+ * inherited stdio descriptors open; run probe/read commands directly when their
+ * output is needed.
+ */
+
+import { spawnSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import { appendFile, mkdir } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const SCHEMA = 'lobehub.agentBrowserKlmTrace@1';
+const DEFAULT_TRACE = '.records/interaction-trace.jsonl';
+
+const optionValueFlags = new Set([
+ '--browser',
+ '--cdp',
+ '--device',
+ '--engine',
+ '--args',
+ '--host',
+ '--port',
+ '--profile',
+ '--proxy',
+ '--proxy-bypass',
+ '--session',
+ '--session-name',
+ '--state',
+ '--timeout',
+ '--url',
+ '--user-data-dir',
+ '--executable-path',
+ '--extension',
+ '--headers',
+ '--user-agent',
+ '--screenshot-dir',
+ '--screenshot-quality',
+ '--screenshot-format',
+ '--download-path',
+ '--allowed-domains',
+ '--action-policy',
+ '--confirm-actions',
+ '--config',
+ '--model',
+]);
+
+const forwardedBooleanGlobalFlags = new Set([
+ '--auto-connect',
+ '--headless',
+ '--headed',
+ '--no-sandbox',
+]);
+
+const defaultOperators = () => ({
+ H: 0,
+ K: 0,
+ M: 0,
+ P: 0,
+ R_ms: 0,
+ T_chars: 0,
+});
+
+const usage = () => {
+ console.log(`Usage:
+ agent-browser-klm.mjs [--klm-trace file] [--klm-phase id] [--klm-check id] [--klm-command-timeout-ms ms] -- <agent-browser args...>
+ agent-browser-klm.mjs mental [--m n] [--reason text] [--confidence n] [--score n] [--klm-trace file]
+
+Examples:
+ AGENT_BROWSER_KLM_TRACE="$DIR/interaction-trace.jsonl" \\
+ agent-browser-klm.mjs --klm-phase login --klm-check case-1 --session lobehub-dev click @e3
+
+ agent-browser-klm.mjs mental --m 2 --score 3 --confidence 0.75 \\
+ --reason "First view requires understanding status and next action"`);
+};
+
+const parseNumber = (value, fallback) => {
+ if (value === undefined) return fallback;
+ const number = Number(value);
+ return Number.isFinite(number) ? number : fallback;
+};
+
+const parseOwnFlags = (argv) => {
+ const meta = {
+ checkItemId: process.env.AGENT_BROWSER_KLM_CHECK || process.env.KLM_CHECK_ITEM_ID,
+ label: process.env.AGENT_BROWSER_KLM_LABEL || process.env.KLM_LABEL,
+ phaseId: process.env.AGENT_BROWSER_KLM_PHASE || process.env.KLM_PHASE_ID,
+ surface: process.env.AGENT_BROWSER_KLM_SURFACE || process.env.KLM_SURFACE || 'web',
+ commandTimeoutMs: parseNumber(process.env.AGENT_BROWSER_KLM_COMMAND_TIMEOUT_MS, undefined),
+ trace:
+ process.env.AGENT_BROWSER_KLM_TRACE ||
+ process.env.INTERACTION_TRACE ||
+ path.resolve(process.cwd(), DEFAULT_TRACE),
+ };
+ let binary = process.env.AGENT_BROWSER_BIN || 'agent-browser';
+ const forwarded = [];
+
+ for (let index = 0; index < argv.length; index += 1) {
+ const arg = argv[index];
+ if (arg === '--') {
+ forwarded.push(...argv.slice(index + 1));
+ break;
+ }
+
+ if (arg === '--klm-help' || arg === '-h') {
+ usage();
+ process.exit(0);
+ }
+
+ if (arg === '--klm-trace') meta.trace = path.resolve(argv[++index] ?? DEFAULT_TRACE);
+ else if (arg === '--klm-phase') meta.phaseId = argv[++index];
+ else if (arg === '--klm-label') meta.label = argv[++index];
+ else if (arg === '--klm-check') meta.checkItemId = argv[++index];
+ else if (arg === '--klm-surface') meta.surface = argv[++index] ?? meta.surface;
+ else if (arg === '--klm-command-timeout-ms')
+ meta.commandTimeoutMs = parseNumber(argv[++index], meta.commandTimeoutMs);
+ else if (arg === '--klm-agent-browser') binary = argv[++index] ?? binary;
+ else forwarded.push(arg);
+ }
+
+ return { binary, forwarded, meta };
+};
+
+const appendEvent = async (trace, event) => {
+ await mkdir(path.dirname(path.resolve(trace)), { recursive: true });
+ await appendFile(trace, `${JSON.stringify(event)}\n`, 'utf8');
+};
+
+const findCommandIndex = (args) => {
+ for (let index = 0; index < args.length; index += 1) {
+ const arg = args[index];
+
+ if (arg === '--') continue;
+ if (optionValueFlags.has(arg)) {
+ index += 1;
+ continue;
+ }
+ if (arg.startsWith('--')) {
+ if (!forwardedBooleanGlobalFlags.has(arg) && arg.includes('=')) continue;
+ continue;
+ }
+ if (arg.startsWith('-')) continue;
+
+ return index;
+ }
+
+ return -1;
+};
+
+const normalizeCommand = (args) => {
+ const index = findCommandIndex(args);
+ if (index < 0) return { argsAfterCommand: [], command: null };
+ return {
+ argsAfterCommand: args.slice(index + 1),
+ command: args[index],
+ };
+};
+
+const textLength = (value) => (typeof value === 'string' ? [...value].length : 0);
+
+const lastNonFlag = (args) => {
+ for (let index = args.length - 1; index >= 0; index -= 1) {
+ const arg = args[index];
+ if (!arg.startsWith('-')) return arg;
+ }
+};
+
+const numericWaitMs = (args) => {
+ const direct = args.find((arg) => /^\d+(?:\.\d+)?$/.test(arg));
+ return direct ? Number(direct) : undefined;
+};
+
+const classifyFindCommand = (args) => {
+ const action = [...args]
+ .reverse()
+ .find((arg) => ['check', 'click', 'fill', 'press', 'select', 'type'].includes(arg));
+ if (!action)
+ return {
+ assumptions: ['Semantic lookup only; no user-equivalent action counted.'],
+ category: 'probe',
+ operators: defaultOperators(),
+ };
+
+ return classifyCommand(action, args.slice(args.indexOf(action) + 1), 0);
+};
+
+function classifyCommand(command, args, durationMs) {
+ const operators = defaultOperators();
+ const assumptions = [];
+ let category = 'probe';
+
+ switch (command) {
+ case 'check':
+ case 'click':
+ case 'download':
+ case 'select': {
+ operators.P = 1;
+ operators.K = 1;
+ category = 'interaction';
+ assumptions.push(`${command} maps to pointer acquisition plus one activation.`);
+ break;
+ }
+
+ case 'dblclick': {
+ operators.P = 1;
+ operators.K = 2;
+ category = 'interaction';
+ assumptions.push('dblclick maps to pointer acquisition plus two activations.');
+ break;
+ }
+
+ case 'fill':
+ case 'type': {
+ operators.P = 1;
+ operators.T_chars = textLength(lastNonFlag(args));
+ category = 'interaction';
+ assumptions.push(`${command} maps to pointer acquisition plus user-equivalent text entry.`);
+ break;
+ }
+
+ case 'keyboard': {
+ const subcommand = args[0];
+ if (subcommand === 'type' || subcommand === 'inserttext') {
+ operators.T_chars = textLength(args.at(-1));
+ category = 'interaction';
+ assumptions.push(`keyboard ${subcommand} maps to user-equivalent text entry.`);
+ } else if (subcommand === 'press') {
+ operators.K = 1;
+ category = 'interaction';
+ assumptions.push('keyboard press maps to one keystroke.');
+ }
+ break;
+ }
+
+ case 'press': {
+ operators.K = 1;
+ category = 'interaction';
+ assumptions.push('press maps to one keystroke.');
+ break;
+ }
+
+ case 'scroll': {
+ operators.P = 1;
+ operators.K = 1;
+ category = 'interaction';
+ assumptions.push('scroll maps to target acquisition plus one wheel/gesture action.');
+ break;
+ }
+
+ case 'open':
+ case 'goto':
+ case 'navigate': {
+ operators.R_ms = Math.max(0, Math.round(durationMs));
+ category = 'navigation';
+ assumptions.push('Direct navigation is counted as system response time, not URL typing.');
+ break;
+ }
+
+ case 'wait': {
+ operators.R_ms = Math.max(0, Math.round(numericWaitMs(args) ?? durationMs));
+ category = 'wait';
+ assumptions.push('wait maps to system response time.');
+ break;
+ }
+
+ case 'find': {
+ return classifyFindCommand(args);
+ }
+
+ case 'screenshot':
+ case 'pdf': {
+ category = 'evidence';
+ assumptions.push(
+ `${command} is evidence capture and is not counted as user-side interaction.`,
+ );
+ break;
+ }
+
+ case 'snapshot':
+ case 'eval':
+ case 'get':
+ case 'network':
+ case 'stream': {
+ category = 'probe';
+ assumptions.push(
+ `${command} is an agent probe and is not counted unless paired with a mental estimate.`,
+ );
+ break;
+ }
+
+ default: {
+ category = 'unknown';
+ assumptions.push('Unknown agent-browser command; no user-equivalent operators inferred.');
+ }
+ }
+
+ return { assumptions, category, operators };
+}
+
+const buildPhase = (meta) => {
+ if (!meta.phaseId && !meta.label && !meta.checkItemId) return undefined;
+ return {
+ checkItemId: meta.checkItemId,
+ id: meta.phaseId ?? meta.checkItemId ?? 'unscoped',
+ label: meta.label,
+ };
+};
+
+const runAgentBrowser = async (binary, args, meta) => {
+ if (args.length === 0) {
+ usage();
+ process.exit(1);
+ }
+
+ const startedAtMs = Date.now();
+ const startedAt = new Date(startedAtMs).toISOString();
+ const { argsAfterCommand, command } = normalizeCommand(args);
+
+ const result = spawnSync(binary, args, {
+ encoding: 'utf8',
+ killSignal: 'SIGKILL',
+ stdio: 'ignore',
+ timeout: meta.commandTimeoutMs && meta.commandTimeoutMs > 0 ? meta.commandTimeoutMs : undefined,
+ });
+
+ if (result.error && result.error.code !== 'ETIMEDOUT') {
+ console.error(`[agent-browser-klm] failed to start ${binary}:`, result.error.message);
+ }
+
+ const timedOut = result.error?.code === 'ETIMEDOUT';
+ const exitCode = timedOut ? 124 : (result.status ?? (result.error ? 127 : 1));
+
+ const completedAtMs = Date.now();
+ const durationMs = completedAtMs - startedAtMs;
+ const klm = classifyCommand(command, argsAfterCommand, durationMs);
+ if (timedOut) {
+ klm.category = 'blocked';
+ klm.operators = defaultOperators();
+ klm.assumptions.push('agent-browser command timed out; no user-equivalent cost counted.');
+ }
+ const event = {
+ agentBrowser: { args, command },
+ completedAt: new Date(completedAtMs).toISOString(),
+ durationMs,
+ exitCode,
+ id: randomUUID(),
+ klm,
+ phase: buildPhase(meta),
+ schema: SCHEMA,
+ source: 'agent-browser',
+ startedAt,
+ surface: meta.surface,
+ timedOut,
+ type: 'agent_browser_action',
+ };
+
+ await appendEvent(meta.trace, event);
+ process.exit(exitCode);
+};
+
+const recordMentalEstimate = async (argv, baseMeta) => {
+ const mental = {
+ confidence: undefined,
+ mOperators: 1,
+ reason: undefined,
+ score: undefined,
+ };
+
+ const { meta } = parseOwnFlags(argv);
+ const mergedMeta = { ...baseMeta, ...meta };
+
+ for (let index = 0; index < argv.length; index += 1) {
+ const arg = argv[index];
+ if (arg === '--m') mental.mOperators = parseNumber(argv[++index], mental.mOperators);
+ else if (arg === '--reason') mental.reason = argv[++index];
+ else if (arg === '--confidence') mental.confidence = parseNumber(argv[++index], undefined);
+ else if (arg === '--score') mental.score = parseNumber(argv[++index], undefined);
+ }
+
+ const operators = defaultOperators();
+ operators.M = mental.mOperators;
+ await appendEvent(mergedMeta.trace, {
+ id: randomUUID(),
+ klm: {
+ assumptions: ['Mental operators are estimated by the agent from the observed page/context.'],
+ category: 'mental',
+ operators,
+ },
+ mentalEstimate: mental,
+ phase: buildPhase(mergedMeta),
+ recordedAt: new Date().toISOString(),
+ schema: SCHEMA,
+ source: 'agent',
+ surface: mergedMeta.surface,
+ type: 'mental_estimate',
+ });
+};
+
+const main = async () => {
+ const argv = process.argv.slice(2);
+ if (argv[0] === '--klm-help' || argv[0] === '-h') {
+ usage();
+ return;
+ }
+
+ if (argv[0] === 'mental') {
+ const { meta } = parseOwnFlags(argv.slice(1));
+ await recordMentalEstimate(argv.slice(1), meta);
+ return;
+ }
+
+ const { binary, forwarded, meta } = parseOwnFlags(argv);
+ await runAgentBrowser(binary, forwarded, meta);
+};
+
+if (process.argv[1] === fileURLToPath(import.meta.url)) {
+ main().catch((error) => {
+ console.error('[agent-browser-klm]', error);
+ process.exit(1);
+ });
+}
diff --git a/.agents/skills/agent-testing/scripts/agent-browser-klm.test.sh b/.agents/skills/agent-testing/scripts/agent-browser-klm.test.sh
new file mode 100755
index 00000000000..3ce75ea2b0c
--- /dev/null
+++ b/.agents/skills/agent-testing/scripts/agent-browser-klm.test.sh
@@ -0,0 +1,97 @@
+#!/usr/bin/env bash
+# Smoke tests for agent-browser KLM wrapper + analyzer. Uses a stub
+# agent-browser, so no real browser is required.
+
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+WRAPPER="$SCRIPT_DIR/agent-browser-klm.mjs"
+ANALYZER="$SCRIPT_DIR/agent-browser-klm-analyze.mjs"
+
+fail() {
+ echo "FAIL: $*" >&2
+ exit 1
+}
+
+tmp_dir="$(mktemp -d)"
+trap 'rm -rf "$tmp_dir"' EXIT
+
+mkdir -p "$tmp_dir/bin"
+cat > "$tmp_dir/bin/agent-browser" << 'SH'
+#!/usr/bin/env bash
+set -euo pipefail
+printf '%s\n' "$*" >> "${AGENT_BROWSER_STUB_LOG:?}"
+SH
+chmod +x "$tmp_dir/bin/agent-browser"
+
+export PATH="$tmp_dir/bin:$PATH"
+export AGENT_BROWSER_STUB_LOG="$tmp_dir/agent-browser.log"
+
+trace="$tmp_dir/interaction-trace.jsonl"
+trace_flags="$tmp_dir/flags-trace.jsonl"
+result="$tmp_dir/result.json"
+
+node "$WRAPPER" --klm-trace "$trace" --klm-phase first --klm-check case-1 --session app click @e1
+node "$WRAPPER" --klm-trace "$trace" --klm-phase form --klm-check case-1 fill @e2 hello
+node "$WRAPPER" --klm-trace "$trace" --klm-phase wait --session app wait 2000
+node "$WRAPPER" mental --klm-trace "$trace" --klm-phase first --m 2 --score 3 --confidence 0.75 --reason "first view"
+node "$WRAPPER" --klm-trace "$trace_flags" --klm-phase nav --engine chrome --args --no-proxy-server open about:blank
+
+node "$ANALYZER" --trace "$trace" > "$tmp_dir/summary.json"
+
+node - "$tmp_dir/summary.json" << 'JS'
+const fs = require('fs');
+const summary = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
+
+function eq(actual, expected, label) {
+ if (actual !== expected) {
+ throw new Error(`${label}: expected ${expected}, got ${actual}`);
+ }
+}
+
+eq(summary.operators.P, 2, 'P');
+eq(summary.operators.K, 1, 'K');
+eq(summary.operators.M, 2, 'M');
+eq(summary.operators.T_chars, 5, 'T_chars');
+eq(summary.operators.R_ms, 2000, 'R_ms');
+eq(summary.totalSeconds, 8.1, 'totalSeconds');
+eq(summary.activeSeconds, 6.1, 'activeSeconds');
+eq(summary.waitSeconds, 2, 'waitSeconds');
+eq(summary.phases[0].id, 'first', 'top phase');
+JS
+
+cat > "$result" << 'JSON'
+{
+ "title": "KLM smoke",
+ "cases": [],
+ "summary": { "total": 0, "passed": 0, "failed": 0, "blocked": 0, "verdict": "pending" }
+}
+JSON
+
+node "$ANALYZER" --trace "$trace" --result "$result" --write > /dev/null
+
+node - "$result" << 'JS'
+const fs = require('fs');
+const result = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
+if (!result.interactionCost) throw new Error('interactionCost missing');
+if (result.interactionCost.totalSeconds !== 8.1) {
+ throw new Error(`unexpected patched total: ${result.interactionCost.totalSeconds}`);
+}
+JS
+
+grep -Fq -- "--session app click @e1" "$AGENT_BROWSER_STUB_LOG" || fail "wrapper did not forward click"
+grep -Fq -- "--engine chrome --args --no-proxy-server open about:blank" "$AGENT_BROWSER_STUB_LOG" ||
+ fail "wrapper did not forward global flags"
+
+node - "$trace_flags" << 'JS'
+const fs = require('fs');
+const event = JSON.parse(fs.readFileSync(process.argv[2], 'utf8').trim());
+if (event.agentBrowser.command !== 'open') {
+ throw new Error(`expected open command, got ${event.agentBrowser.command}`);
+}
+if (event.klm.category !== 'navigation') {
+ throw new Error(`expected navigation category, got ${event.klm.category}`);
+}
+JS
+
+echo "agent-browser KLM tests passed"
diff --git a/.agents/skills/agent-testing/scripts/report-init.sh b/.agents/skills/agent-testing/scripts/report-init.sh
index 6bacd36dcfd..2d884fdc634 100755
--- a/.agents/skills/agent-testing/scripts/report-init.sh
+++ b/.agents/skills/agent-testing/scripts/report-init.sh
@@ -54,6 +54,7 @@ cat > "$DIR/result.json" << EOF
"entry": "",
"focus": "",
"cases": [],
+ "interactionCost": null,
"summary": { "total": 0, "passed": 0, "failed": 0, "blocked": 0, "verdict": "pending", "conclusion": "", "score": null }
}
EOF
diff --git a/apps/cli/src/commands/verify.ts b/apps/cli/src/commands/verify.ts
index f0b0c33545f..d772cbf251c 100644
--- a/apps/cli/src/commands/verify.ts
+++ b/apps/cli/src/commands/verify.ts
@@ -130,6 +130,24 @@ function pullRequestFromResult(result: Record<string, unknown>) {
return entries.length > 0 ? Object.fromEntries(entries) : undefined;
}
+function metadataForReport(
+ result: Record<string, unknown>,
+ existingMetadata?: unknown,
+): Record<string, unknown> | undefined {
+ if (!Object.prototype.hasOwnProperty.call(result, 'interactionCost')) return undefined;
+
+ const metadata = { ...objectValue(existingMetadata) };
+ const interactionCost = objectValue(result.interactionCost);
+
+ if (interactionCost) {
+ metadata.interactionCost = interactionCost;
+ } else {
+ delete metadata.interactionCost;
+ }
+
+ return metadata;
+}
+
/**
* The report dir remembers which verification session it created, so
* re-verifying the same case updates one evolving `/verify/<id>` in place
@@ -1084,6 +1102,7 @@ export function registerVerifyCommand(program: Command) {
const client = await getTrpcClient();
const goal = options.goal ?? (typeof result.focus === 'string' ? result.focus : undefined);
const title = options.title ?? result.title;
+ const newRunMetadata = metadataForReport(result);
// Resolve the target session. Reuse the one this report dir already
// created (recorded in the sidecar) so re-verifying the same case
@@ -1098,9 +1117,10 @@ export function registerVerifyCommand(program: Command) {
if (existing) {
reused = true;
runId = existing.id;
+ const metadata = metadataForReport(result, existing.metadata);
// 1a. Refresh the scope header / title / goal in place.
await client.verify.updateRun.mutate({
- value: { context, goal, scenario, title },
+ value: { context, goal, metadata, scenario, title },
verifyRunId: runId,
});
} else if (options.run) {
@@ -1120,6 +1140,7 @@ export function registerVerifyCommand(program: Command) {
const run = await client.verify.createRun.mutate({
context,
goal,
+ metadata: newRunMetadata,
operationId: options.operation,
scenario,
source: options.source as any,
diff --git a/apps/server/src/routers/lambda/verify.ts b/apps/server/src/routers/lambda/verify.ts
index a170e03dedc..89c0ceb4b70 100644
--- a/apps/server/src/routers/lambda/verify.ts
+++ b/apps/server/src/routers/lambda/verify.ts
@@ -95,6 +95,10 @@ const checkItemSchema = z.object({
});
const verifyRunIdInputSchema = z.object({ verifyRunId: z.string() });
+const omitUndefined = <T extends Record<string, unknown>>(value: T): Partial<T> =>
+ Object.fromEntries(
+ Object.entries(value).filter(([, field]) => field !== undefined),
+ ) as Partial<T>;
// The scenario's context (coding scope), rendered as the report's scope header.
// Shared by createRun and updateRun so a re-ingest can refresh the scope in place.
@@ -122,12 +126,15 @@ const runContextSchema = z.object({
testedAt: z.string().optional(),
});
+const runMetadataSchema = z.record(z.unknown());
+
const updateRunInputSchema = verifyRunIdInputSchema.extend({
// Every field optional — a re-ingest may refresh only the context/goal while
// keeping the original title, so nothing here is required.
value: z.object({
context: runContextSchema.optional(),
goal: z.string().optional(),
+ metadata: runMetadataSchema.optional(),
scenario: z.enum(['coding']).optional(),
title: z.string().trim().min(1).max(200).optional(),
}),
@@ -490,6 +497,7 @@ export const verifyRouter = router({
// The active scenario's context, rendered as the report's scope header.
context: runContextSchema.optional(),
goal: z.string().optional(),
+ metadata: runMetadataSchema.optional(),
operationId: z.string().optional(),
scenario: z.enum(['coding']).optional(),
source: runSourceSchema.optional(),
@@ -500,6 +508,7 @@ export const verifyRouter = router({
ctx.runModel.create({
context: input.context,
goal: input.goal,
+ metadata: input.metadata,
operationId: input.operationId,
scenario: input.scenario,
source: input.source ?? 'agent-testing',
@@ -569,12 +578,16 @@ export const verifyRouter = router({
updateRun: verifyProcedure.input(updateRunInputSchema).mutation(async ({ ctx, input }) => {
const run = await resolveVerifyRun(ctx, input.verifyRunId);
- const updated = await ctx.runModel.update(run.id, {
- context: input.value.context,
- goal: input.value.goal,
- scenario: input.value.scenario,
- title: input.value.title,
- });
+ const updated = await ctx.runModel.update(
+ run.id,
+ omitUndefined({
+ context: input.value.context,
+ goal: input.value.goal,
+ metadata: input.value.metadata,
+ scenario: input.value.scenario,
+ title: input.value.title,
+ }),
+ );
return { data: updated, success: true };
}),
diff --git a/locales/en-US/verify.json b/locales/en-US/verify.json
index e5357be09f4..9fa85e2d0f9 100644
--- a/locales/en-US/verify.json
+++ b/locales/en-US/verify.json
@@ -61,6 +61,16 @@
"report.filter.passed": "Passed",
"report.filter.uncertain": "Uncertain",
"report.filterEmpty": "No checks match this filter.",
+ "report.interaction.active": "Active",
+ "report.interaction.operator.H": "H",
+ "report.interaction.operator.K": "K",
+ "report.interaction.operator.M": "M",
+ "report.interaction.operator.P": "P",
+ "report.interaction.operator.R_ms": "R",
+ "report.interaction.operator.T_chars": "T",
+ "report.interaction.title": "Interaction cost",
+ "report.interaction.total": "Total",
+ "report.interaction.wait": "Wait",
"report.missing.description": "Open a verification report with a valid run id.",
"report.missing.title": "Missing report id",
"report.notFound.description": "This report may have been deleted, or the link is not available to you.",
diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.json
index fb7f88a3ceb..384a7c1a782 100644
--- a/locales/zh-CN/verify.json
+++ b/locales/zh-CN/verify.json
@@ -61,6 +61,16 @@
"report.filter.passed": "已通过",
"report.filter.uncertain": "不确定",
"report.filterEmpty": "没有符合该筛选的检查项。",
+ "report.interaction.active": "主动",
+ "report.interaction.operator.H": "H",
+ "report.interaction.operator.K": "K",
+ "report.interaction.operator.M": "M",
+ "report.interaction.operator.P": "P",
+ "report.interaction.operator.R_ms": "R",
+ "report.interaction.operator.T_chars": "T",
+ "report.interaction.title": "交互成本",
+ "report.interaction.total": "总成本",
+ "report.interaction.wait": "等待",
"report.missing.description": "请使用有效的运行 ID 打开验证报告。",
"report.missing.title": "缺少报告 ID",
"report.notFound.description": "该报告可能已被删除,或当前链接不可用。",
diff --git a/packages/database/src/models/verifyRun.ts b/packages/database/src/models/verifyRun.ts
index 9bd37da449d..1c2f79fa6a6 100644
--- a/packages/database/src/models/verifyRun.ts
+++ b/packages/database/src/models/verifyRun.ts
@@ -285,7 +285,7 @@ export class VerifyRunModel {
update = async (
runId: string,
- value: Partial<Pick<NewVerifyRun, 'context' | 'goal' | 'scenario' | 'title'>>,
+ value: Partial<Pick<NewVerifyRun, 'context' | 'goal' | 'metadata' | 'scenario' | 'title'>>,
): Promise<VerifyRunItem | undefined> => {
const [run] = await this.db
.update(verifyRuns)
diff --git a/packages/database/src/schemas/verify.ts b/packages/database/src/schemas/verify.ts
index 76a1b2cdbae..23e902f5b13 100644
--- a/packages/database/src/schemas/verify.ts
+++ b/packages/database/src/schemas/verify.ts
@@ -3,6 +3,7 @@ import type {
VerifyCheckItem,
VerifyRubricConfig,
VerifyRunContext,
+ VerifyRunMetadata,
VerifyRunScenario,
} from '@lobechat/types';
import {
@@ -455,7 +456,7 @@ export const verifyRuns = pgTable(
* metadata we don't model yet (the active scenario's input lives in
* `context`). Kept open so future needs don't require a migration.
*/
- metadata: jsonb('metadata').$type<Record<string, unknown>>(),
+ metadata: jsonb('metadata').$type<VerifyRunMetadata>(),
/**
* Immutable check-plan snapshot for this session (instantiated from rubrics /
diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.ts
index 32b35b43d70..930d9f8b25d 100644
--- a/packages/locales/src/default/verify.ts
+++ b/packages/locales/src/default/verify.ts
@@ -71,6 +71,16 @@ export default {
'report.filter.passed': 'Passed',
'report.filter.uncertain': 'Uncertain',
'report.filterEmpty': 'No checks match this filter.',
+ 'report.interaction.active': 'Active',
+ 'report.interaction.operator.H': 'H',
+ 'report.interaction.operator.K': 'K',
+ 'report.interaction.operator.M': 'M',
+ 'report.interaction.operator.P': 'P',
+ 'report.interaction.operator.R_ms': 'R',
+ 'report.interaction.operator.T_chars': 'T',
+ 'report.interaction.title': 'Interaction cost',
+ 'report.interaction.total': 'Total',
+ 'report.interaction.wait': 'Wait',
'report.missing.description': 'Open a verification report with a valid run id.',
'report.missing.title': 'Missing report id',
'report.notFound.description':
diff --git a/packages/types/src/verify.ts b/packages/types/src/verify.ts
index dd4159b1f61..97d75149d9b 100644
--- a/packages/types/src/verify.ts
+++ b/packages/types/src/verify.ts
@@ -122,6 +122,43 @@ export interface VerifyCodingScope {
*/
export type VerifyRunContext = VerifyCodingScope;
+export interface VerifyInteractionCostOperators {
+ H?: number;
+ K?: number;
+ M?: number;
+ P?: number;
+ R_ms?: number;
+ T_chars?: number;
+}
+
+export interface VerifyInteractionCostPhase {
+ actionCount?: number;
+ activeSeconds?: number;
+ checkItemId?: string;
+ id: string;
+ label?: string;
+ operators?: VerifyInteractionCostOperators;
+ seconds?: number;
+ waitSeconds?: number;
+}
+
+export interface VerifyInteractionCost {
+ actionCount?: number;
+ activeSeconds: number;
+ actualAgentSeconds?: number;
+ categoryCounts?: Record<string, number>;
+ generatedAt?: string;
+ mentalEstimates?: Record<string, unknown>[];
+ model: string;
+ operators: VerifyInteractionCostOperators;
+ phases?: VerifyInteractionCostPhase[];
+ scope?: string;
+ sourceTrace?: string;
+ timingSeconds?: Record<string, number>;
+ totalSeconds: number;
+ waitSeconds: number;
+}
+
/** Default cap on automatic repair rounds when a rubric doesn't override it. */
export const DEFAULT_MAX_REPAIR_ROUNDS = 3;
@@ -144,6 +181,8 @@ export interface VerifyRubricConfig {
* migration; the active scenario's input lives in `context`, not here.
*/
export interface VerifyRunMetadata {
+ [key: string]: unknown;
+ interactionCost?: VerifyInteractionCost;
/**
* Per-run override for the repair-round cap, taking precedence over the
* rubric's {@link VerifyRubricConfig.maxRepairRounds}. Set from a task's
diff --git a/src/features/Verify/ReportViewer.tsx b/src/features/Verify/ReportViewer.tsx
index b2d38fdccf2..f2e01dee9fb 100644
--- a/src/features/Verify/ReportViewer.tsx
+++ b/src/features/Verify/ReportViewer.tsx
@@ -1,6 +1,13 @@
'use client';
-import type { VerifyCodingScope, VerifyEvidenceType } from '@lobechat/types';
+import type {
+ VerifyCodingScope,
+ VerifyEvidenceType,
+ VerifyInteractionCost,
+ VerifyInteractionCostOperators,
+ VerifyInteractionCostPhase,
+} from '@lobechat/types';
+import { toRecord } from '@lobechat/utils/object';
import {
Block,
Center,
@@ -134,6 +141,189 @@ const styles = createStaticStyles(({ css }) => ({
background: ${cssVar.colorInfoBg};
`,
+ interactionCost: css`
+ --klm-blue-1: color-mix(in srgb, ${cssVar.colorInfo} 70%, ${cssVar.colorBgContainer});
+ --klm-blue-2: ${cssVar.colorInfo};
+ --klm-blue-3: color-mix(in srgb, ${cssVar.colorInfo} 84%, ${cssVar.colorText});
+ --klm-blue-4: color-mix(in srgb, ${cssVar.colorInfo} 68%, ${cssVar.colorText});
+ --klm-blue-5: color-mix(in srgb, ${cssVar.colorInfo} 54%, ${cssVar.colorText});
+ --klm-blue-6: color-mix(in srgb, ${cssVar.colorInfo} 42%, ${cssVar.colorText});
+
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ width: 100%;
+ `,
+ interactionCostHeader: css`
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px 12px;
+ align-items: center;
+ justify-content: flex-end;
+ `,
+ interactionCostModel: css`
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ interactionMetrics: css`
+ display: grid;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ gap: 8px;
+
+ @media (width <= 520px) {
+ grid-template-columns: 1fr;
+ }
+ `,
+ interactionMetric: css`
+ min-width: 0;
+ padding-block: 9px;
+ padding-inline: 10px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusSM};
+ `,
+ interactionMetricLabel: css`
+ display: block;
+ margin-block-end: 4px;
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ interactionMetricValue: css`
+ font-size: 18px;
+ font-weight: 650;
+ font-variant-numeric: tabular-nums;
+ line-height: 1.2;
+ color: ${cssVar.colorText};
+ `,
+ operatorList: css`
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px 14px;
+ `,
+ operatorChip: css`
+ --operator-color: ${cssVar.colorTextSecondary};
+
+ display: inline-flex;
+ gap: 5px;
+ align-items: baseline;
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 12px;
+ color: color-mix(in srgb, var(--operator-color) 72%, ${cssVar.colorTextSecondary});
+
+ &::before {
+ content: '';
+
+ flex: 0 0 auto;
+
+ width: 6px;
+ height: 6px;
+ margin-block-start: 0.5em;
+ border-radius: 50%;
+
+ background: var(--operator-color);
+ }
+
+ b {
+ font-weight: 650;
+ color: var(--operator-color);
+ }
+
+ &[data-operator='K'] {
+ --operator-color: var(--klm-blue-1);
+ }
+
+ &[data-operator='P'] {
+ --operator-color: var(--klm-blue-2);
+ }
+
+ &[data-operator='M'] {
+ --operator-color: var(--klm-blue-3);
+ }
+
+ &[data-operator='H'] {
+ --operator-color: var(--klm-blue-4);
+ }
+
+ &[data-operator='T_chars'] {
+ --operator-color: var(--klm-blue-5);
+ }
+
+ &[data-operator='R_ms'] {
+ --operator-color: var(--klm-blue-6);
+ }
+ `,
+ phaseList: css`
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ `,
+ phaseRow: css`
+ display: grid;
+ grid-template-columns: minmax(120px, 1fr) minmax(140px, 1.6fr) auto;
+ gap: 10px;
+ align-items: center;
+
+ @media (width <= 640px) {
+ grid-template-columns: 1fr;
+ gap: 5px;
+ }
+ `,
+ phaseName: css`
+ overflow: hidden;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ phaseTrack: css`
+ overflow: hidden;
+ display: flex;
+
+ height: 8px;
+ border-radius: 999px;
+
+ background: transparent;
+ box-shadow: inset 0 0 0 1px ${cssVar.colorBorderSecondary};
+ `,
+ phaseSegment: css`
+ --operator-color: ${cssVar.colorTextSecondary};
+
+ flex: 0 0 auto;
+ min-width: 2px;
+ height: 100%;
+ background: var(--operator-color);
+
+ &[data-operator='K'] {
+ --operator-color: var(--klm-blue-1);
+ }
+
+ &[data-operator='P'] {
+ --operator-color: var(--klm-blue-2);
+ }
+
+ &[data-operator='M'] {
+ --operator-color: var(--klm-blue-3);
+ }
+
+ &[data-operator='H'] {
+ --operator-color: var(--klm-blue-4);
+ }
+
+ &[data-operator='T_chars'] {
+ --operator-color: var(--klm-blue-5);
+ }
+
+ &[data-operator='R_ms'] {
+ --operator-color: var(--klm-blue-6);
+ }
+ `,
+ phaseValue: css`
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+ color: ${cssVar.colorTextTertiary};
+ `,
codingScope: css`
display: flex;
flex-direction: column;
@@ -463,6 +653,10 @@ const styles = createStaticStyles(({ css }) => ({
/* narrative */
narrative: css`
margin-block-start: 24px;
+
+ &:not([open]) > :not(summary) {
+ display: none;
+ }
`,
narrativeSummary: css`
cursor: pointer;
@@ -492,6 +686,9 @@ const styles = createStaticStyles(({ css }) => ({
background: ${cssVar.colorBgContainer};
`,
+ interactionCostBody: css`
+ margin-block-start: 12px;
+ `,
/* evidence */
evidenceList: css`
@@ -666,6 +863,137 @@ const liveStatusLabelKey = {
verifying: 'report.status.verifying',
} as const;
+const OPERATOR_KEYS = ['K', 'P', 'M', 'H', 'T_chars', 'R_ms'] as const;
+type OperatorKey = (typeof OPERATOR_KEYS)[number];
+
+const OPERATOR_DEFAULT_SECONDS: Record<OperatorKey, number> = {
+ H: 0.4,
+ K: 0.2,
+ M: 1.35,
+ P: 1.1,
+ R_ms: 0.001,
+ T_chars: 0.2,
+};
+
+const finiteNumber = (value: unknown): number | undefined =>
+ typeof value === 'number' && Number.isFinite(value) ? value : undefined;
+
+const finiteString = (value: unknown): string | undefined =>
+ typeof value === 'string' && value.length > 0 ? value : undefined;
+
+const readOperators = (value: unknown): VerifyInteractionCostOperators => {
+ const record = toRecord(value);
+ if (!record) return {};
+
+ return {
+ H: finiteNumber(record.H),
+ K: finiteNumber(record.K),
+ M: finiteNumber(record.M),
+ P: finiteNumber(record.P),
+ R_ms: finiteNumber(record.R_ms),
+ T_chars: finiteNumber(record.T_chars),
+ };
+};
+
+const readTimingSeconds = (value: unknown): Record<string, number> | undefined => {
+ const record = toRecord(value);
+ if (!record) return undefined;
+
+ const entries = Object.entries(record).flatMap(([key, field]) => {
+ const seconds = finiteNumber(field);
+ return seconds === undefined ? [] : [[key, seconds] as const];
+ });
+
+ return entries.length > 0 ? Object.fromEntries(entries) : undefined;
+};
+
+const readPhase = (value: unknown, index: number): VerifyInteractionCostPhase | null => {
+ const record = toRecord(value);
+ if (!record) return null;
+
+ const seconds = finiteNumber(record.seconds);
+ const activeSeconds = finiteNumber(record.activeSeconds);
+ const waitSeconds = finiteNumber(record.waitSeconds);
+ const hasTiming =
+ seconds !== undefined || activeSeconds !== undefined || waitSeconds !== undefined;
+ if (!hasTiming) return null;
+
+ return {
+ actionCount: finiteNumber(record.actionCount),
+ activeSeconds,
+ checkItemId: finiteString(record.checkItemId),
+ id: finiteString(record.id) ?? `phase-${index + 1}`,
+ label: finiteString(record.label),
+ operators: readOperators(record.operators),
+ seconds,
+ waitSeconds,
+ };
+};
+
+const readInteractionCost = (metadata: unknown): VerifyInteractionCost | null => {
+ const cost = toRecord(toRecord(metadata)?.interactionCost);
+ if (!cost) return null;
+
+ const totalSeconds = finiteNumber(cost.totalSeconds);
+ if (totalSeconds === undefined) return null;
+
+ return {
+ actionCount: finiteNumber(cost.actionCount),
+ activeSeconds: finiteNumber(cost.activeSeconds) ?? 0,
+ model: finiteString(cost.model) ?? 'goms-klm',
+ operators: readOperators(cost.operators),
+ phases: Array.isArray(cost.phases)
+ ? cost.phases
+ .map((phase, index) => readPhase(phase, index))
+ .filter((phase): phase is VerifyInteractionCostPhase => Boolean(phase))
+ : [],
+ scope: finiteString(cost.scope),
+ sourceTrace: finiteString(cost.sourceTrace),
+ timingSeconds: readTimingSeconds(cost.timingSeconds),
+ totalSeconds,
+ waitSeconds: finiteNumber(cost.waitSeconds) ?? 0,
+ };
+};
+
+const formatSeconds = (seconds: number): string =>
+ `${seconds >= 10 ? seconds.toFixed(1) : seconds.toFixed(2)}s`;
+
+const phaseSeconds = (phase: VerifyInteractionCostPhase): number =>
+ phase.seconds ?? (phase.activeSeconds ?? 0) + (phase.waitSeconds ?? 0);
+
+const operatorSeconds = (
+ key: OperatorKey,
+ value: number,
+ timingSeconds?: Record<string, number>,
+): number => {
+ if (key === 'R_ms') return value / 1000;
+ if (key === 'T_chars') {
+ return (
+ value * (timingSeconds?.T_chars ?? timingSeconds?.T_char ?? OPERATOR_DEFAULT_SECONDS[key])
+ );
+ }
+
+ return value * (timingSeconds?.[key] ?? OPERATOR_DEFAULT_SECONDS[key]);
+};
+
+const operatorValue = (key: OperatorKey, value: number): string => {
+ if (key === 'R_ms') return formatSeconds(value / 1000);
+ if (key === 'T_chars') return `${Math.round(value)} chars`;
+ return Number.isInteger(value) ? String(value) : value.toFixed(2);
+};
+
+const phaseOperatorSegments = (
+ phase: VerifyInteractionCostPhase,
+ timingSeconds?: Record<string, number>,
+): { key: OperatorKey; seconds: number; value: number }[] =>
+ OPERATOR_KEYS.flatMap((key) => {
+ const value = phase.operators?.[key];
+ if (value === undefined || value <= 0) return [];
+
+ const seconds = operatorSeconds(key, value, timingSeconds);
+ return seconds > 0 ? [{ key, seconds, value }] : [];
+ });
+
/** Severity-first sort: failed → uncertain → passed. */
const SEVERITY_RANK: Record<Verdict, number> = { failed: 0, passed: 2, uncertain: 1 };
@@ -721,6 +1049,109 @@ const DocumentViewer = memo<{ fileName?: string | null; url: string }>(({ fileNa
);
});
+const InteractionCostPanel = memo<{ cost: VerifyInteractionCost }>(({ cost }) => {
+ const { t } = useTranslation('verify');
+ const phases = cost.phases ?? [];
+ const maxPhaseSeconds = Math.max(...phases.map(phaseSeconds), 0);
+ const metrics = [
+ {
+ label: t('report.interaction.total'),
+ value: formatSeconds(cost.totalSeconds),
+ },
+ {
+ label: t('report.interaction.active'),
+ value: formatSeconds(cost.activeSeconds),
+ },
+ {
+ label: t('report.interaction.wait'),
+ value: formatSeconds(cost.waitSeconds),
+ },
+ ];
+
+ return (
+ <section className={styles.interactionCost}>
+ <div className={styles.interactionCostHeader}>
+ <span className={styles.interactionCostModel}>{cost.model}</span>
+ </div>
+
+ <div className={styles.interactionMetrics}>
+ {metrics.map((metric) => (
+ <div className={styles.interactionMetric} key={metric.label}>
+ <span className={styles.interactionMetricLabel}>{metric.label}</span>
+ <span className={styles.interactionMetricValue}>{metric.value}</span>
+ </div>
+ ))}
+ </div>
+
+ <div className={styles.operatorList}>
+ {OPERATOR_KEYS.map((key) => {
+ const value = cost.operators[key];
+ if (value === undefined) return null;
+
+ return (
+ <span className={styles.operatorChip} data-operator={key} key={key}>
+ <span>{t(`report.interaction.operator.${key}`)}</span>
+ <b>{operatorValue(key, value)}</b>
+ </span>
+ );
+ })}
+ </div>
+
+ {phases.length > 0 && (
+ <div className={styles.phaseList}>
+ {phases.map((phase) => {
+ const seconds = phaseSeconds(phase);
+ const activeSeconds = phase.activeSeconds ?? 0;
+ const waitSeconds = phase.waitSeconds ?? 0;
+ const activeWidth = maxPhaseSeconds > 0 ? (activeSeconds / maxPhaseSeconds) * 100 : 0;
+ const waitWidth = maxPhaseSeconds > 0 ? (waitSeconds / maxPhaseSeconds) * 100 : 0;
+ const segments = phaseOperatorSegments(phase, cost.timingSeconds);
+
+ return (
+ <div className={styles.phaseRow} key={phase.id}>
+ <span className={styles.phaseName} title={phase.label ?? phase.id}>
+ {phase.label ?? phase.id}
+ </span>
+ <span className={styles.phaseTrack}>
+ {segments.length > 0 ? (
+ segments.map((segment) => (
+ <span
+ className={styles.phaseSegment}
+ data-operator={segment.key}
+ key={segment.key}
+ style={{
+ width: `${
+ maxPhaseSeconds > 0 ? (segment.seconds / maxPhaseSeconds) * 100 : 0
+ }%`,
+ }}
+ title={`${t(`report.interaction.operator.${segment.key}`)} ${formatSeconds(
+ segment.seconds,
+ )}`}
+ />
+ ))
+ ) : (
+ <>
+ <span className={styles.phaseSegment} style={{ width: `${activeWidth}%` }} />
+ <span
+ className={styles.phaseSegment}
+ data-operator={'R_ms'}
+ style={{ width: `${waitWidth}%` }}
+ />
+ </>
+ )}
+ </span>
+ <span className={styles.phaseValue}>{formatSeconds(seconds)}</span>
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </section>
+ );
+});
+
+InteractionCostPanel.displayName = 'InteractionCostPanel';
+
/** One evidence artifact rendered by its type: zoomable image/gif, video, doc, text. */
const EvidenceItem = memo<{ evidence: VerifyEvidenceWithUrl; index: number }>(
({ evidence: e, index }) => {
@@ -1155,6 +1586,7 @@ const ReportViewer = memo(() => {
const verdict = (report?.verdict as Verdict | null) ?? null;
const visible = filter === 'all' ? ordered : ordered.filter((r) => checkVerdict(r) === filter);
const isCodingReport = run.scenario === 'coding';
+ const interactionCost = readInteractionCost(run.metadata);
const chips: { count: number; dot?: string; key: Filter; label: string }[] = [
{ count: total, key: 'all', label: t('report.filter.all') },
@@ -1249,6 +1681,18 @@ const ReportViewer = memo(() => {
</div>
</details>
)}
+
+ {interactionCost && (
+ <details className={styles.narrative}>
+ <summary className={styles.narrativeSummary}>
+ <Icon icon={ChevronRight} size={13} />
+ {t('report.interaction.title')}
+ </summary>
+ <div className={styles.interactionCostBody}>
+ <InteractionCostPanel cost={interactionCost} />
+ </div>
+ </details>
+ )}
</div>
</div>
);