🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(verify): bind reports to their PR, plan and origin conversation (#17166)
Arvin Xu9491f6e04ce5
diff --git a/.agents/skills/agent-testing/SKILL.md b/.agents/skills/agent-testing/SKILL.mdindex 90ac283e4ab..bd2fff43b1e 100644--- a/.agents/skills/agent-testing/SKILL.md+++ b/.agents/skills/agent-testing/SKILL.md@@ -592,10 +592,20 @@ env -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME`verify ingest-report` reads `$DIR` and, in one call, creates a standaloneverification session and uploads everything:-- `result.json.cases[]` → one check result each (verdict + key observation)+- `result.json.plan[]` → the frozen check plan (what this round set out to verify)+- `result.json.cases[]` → one check result each (verdict + key observation),+ paired back to its plan item by `id`; a planned item with no case renders as+ **未执行** instead of silently disappearing- each case's `evidence` file(s) → uploaded to storage and attached to that result- `report.md` → the session's full report body, plus the `summary` stats+Two links are attached for you, no flags needed: the branch's **pull request**+(asked of `gh`) and — when the harness is running inside a LobeHub-spawned agent+— the **conversation that produced the report**, read from the `LOBEHUB_TOPIC_ID`+/ `LOBEHUB_AGENT_ID` / `LOBEHUB_OPERATION_ID` the runtime echoes into the child+env. The origin conversation is shown to the report's author only, never to+someone holding the shared link.+It prints the `verifyRunId` and, with `--open`, the in-app path`/verify/<verifyRunId>` — the report viewer (verdict, stats, every check, and theinline screenshot/text evidence). On production that resolves todiff --git a/.agents/skills/agent-testing/references/probe-mock-patterns.md b/.agents/skills/agent-testing/references/probe-mock-patterns.mdindex c1e75ea2ff8..23cc1a84492 100644--- a/.agents/skills/agent-testing/references/probe-mock-patterns.md+++ b/.agents/skills/agent-testing/references/probe-mock-patterns.md@@ -1237,3 +1237,33 @@ nodeintegration, plugins, disablewebsecurity, allowpopups, preload, …`). The h```Tag the resolved element with a `data-probe` attribute and drive it with `agent-browser click '[data-probe=...]'` (trusted CDP input, D18).- **Corollary**: the phantom also owns the tooltip text of whatever component it duplicates, so an `innerText`/aria grep can "find" a control that the user cannot see. Assert on `getBoundingClientRect()` before believing a control is present.+### C8. ✅ An agent-browser session can silently LOSE its seeded cookies — a 401, not `document.cookie`, is the signal++- **Situation**: verifying an owner-only affordance (a link the server renders only for the+ report's author). The page rendered without it, and the bundle came back `isOwner: false`+ even though the row's `userId` matched the seeded user — which reads exactly like a bug in+ the ownership check.+- **Doesn't work**: `document.cookie` as the auth probe. Better Auth's session cookie is+ **httpOnly**, so `document.cookie` is legitimately `[]` on a fully authenticated page —+ `cookieCount: 0` proves nothing either way.+- **Doesn't work**: trusting `setup-auth.sh web-seed`'s success line for the rest of the run.+ It verified the session at `/`; the session can still be empty later (this run's page had+ also drifted to `about:blank` at one point — see D14).+- **Works**: probe the SERVER, not the document — call any authed procedure from the page and+ read the status. `401` = no session reached the server; `200` = you are really signed in.+ ```js+ const r = await fetch(+ base ++ '/trpc/lambda/user.getUserState?input=' ++ encodeURIComponent(JSON.stringify({ json: {} })),+ { credentials: 'include' },+ );+ r.status; // 401 → re-seed; 200 → the session is live+ ```+ Recover with `agent-browser close --all` + `setup-auth.sh web-seed`, then re-open the route.+ After re-seeding, the same bundle returned `isOwner: true` with the owner-only link rendered —+ the code was correct all along.+- **Why it matters**: an auth-scoped assertion (owner-only / permission-gated UI) fails+ IDENTICALLY whether the gate is broken or the session is missing. Always establish that the+ session is live (a 200 from an authed procedure) BEFORE concluding the gate is wrong —+ otherwise you publish a false bug against your own change.diff --git a/.agents/skills/agent-testing/references/report.md b/.agents/skills/agent-testing/references/report.mdindex 0c153e38acb..39ddd0d7f03 100644--- a/.agents/skills/agent-testing/references/report.md+++ b/.agents/skills/agent-testing/references/report.md@@ -17,13 +17,12 @@ output):```**`result.json` is the report — `report.md` is just its tail.** The published-verify page (`/verify/<id>`) renders itself from `result.json`: the scope header-from `scenario` + `context` (branch / commit / surfaces / entry / focus), the-per-check table from `cases[]`, the overall conclusion from `summary.conclusion`-(shown at the top under the scope block), and the stats from `summary`. So-`report.md` must NOT repeat the scope block or a 用例 table — those double up on-the page. It carries only the non-duplicate narrative (仍需跟进 / 本轮验证 /-评分), rendered as the page's collapsible "Details".+verify page (`/verify/<id>`) renders itself from `result.json`: one line of+provenance (PR / branch / commit / date / surfaces), the overall conclusion from+`summary.conclusion` directly under the title, and the check list from `plan[]`+paired with `cases[]`. So `report.md` must NOT repeat the scope block or a 用例+table — those double up on the page. It carries only the non-duplicate narrative+(仍需跟进 / 本轮验证 / 评分), rendered as the page's collapsible "Details".## Workflow@@ -110,21 +109,32 @@ the page. It carries only the non-duplicate narrative (仍需跟进 / 本轮验- Network: `agent-browser network requests` dumps or HAR files.-3. **Fill `result.json` as you go** — it is the report. Each tested behavior is+3. **Write `plan[]` BEFORE you run anything.** The approved plan from Step 1 is+ part of the report, not scaffolding you throw away: each item is+ `{ id, title, verifier, method, expected, requiredEvidence }` — what you will+ check, how it is judged, how you will exercise it, what would make it pass,+ and the artifact it must produce. `verifier` and `requiredEvidence` are closed+ sets the pipeline acts on (see the schema below); `method` / `expected` are+ prose. `cases[]` later reuses the same `id`s, which is what lets the report+ pair intent against outcome. A planned item that never produces a case renders+ as **未执行** rather than vanishing, so cut coverage in the open — silently+ dropping a check now shows up as a hole in the report.++4. **Fill `result.json` as you go** — it is the report. Each tested behavior isone entry in `cases[]` (`{ id, name, result, observation, evidence }`), where`evidence` is a path under `assets/` (screenshot / GIF / transcript). Set the- scope fields (`scenario: "coding"`, `branch`, `commit`, `surfaces`, `entry`,- `focus`) and write the one-paragraph verdict into `summary.conclusion`. The- page pairs each check with its evidence inline, so you don't hand-build a- table. `report.md` holds only the narrative tail (跟进 / 本轮验证 / 评分).+ scope fields (`scenario: "coding"`, `branch`, `commit`, `surfaces`, `entry`)+ and write the one-paragraph verdict into `summary.conclusion`. The page pairs+ each check with its evidence inline, so you don't hand-build a table.+ `report.md` holds only the narrative tail (跟进 / 本轮验证 / 评分).-4. **Set the verdict** in both `report.md` and `result.json`, then link the+5. **Set the verdict** in both `report.md` and `result.json`, then link thereport directory in your final answer to the user. If UI evidence exists,list the key screenshot/GIF links in the final chat response. Use Markdownlink text as the evidence caption, for example:`[Image #1 - observed outcome](<report-dir>/assets/case1.png)`.-5. **Publish to LobeHub** (Step 4 of the skill) — upload the finished session so+6. **Publish to LobeHub** (Step 4 of the skill) — upload the finished session soit's viewable in-app, not just on disk. **Publish to PRODUCTION(`app.lobehub.com`) with the user's real login, NOT the local dev CLI** —strip the local dev overrides so `lh` uses its production defaults:@@ -239,6 +249,21 @@ missing; a blocked case is not a pass)."operators": { "K": 1, "P": 2, "H": 0, "M": 2, "T_chars": 5, "R_ms": 2000 },"phases": []},+ "plan": [+ {+ "id": "1",+ "title": "task tree returns nested children",+ "verifier": "program",+ "method": "lh task list --tree against a 3-level fixture",+ "expected": "root shows 3 nested children at depth 2",+ "requiredEvidence": ["text"]+ }+ ],+ "pullRequest": {+ "number": 17152,+ "title": "feat(task): nested task tree",+ "url": "https://github.com/lobehub/lobe-chat/pull/17152"+ },"summary": {"total": 1,"passed": 1,@@ -252,6 +277,43 @@ missing; a blocked case is not a pass).}```+`plan[]` is the checks you committed to **before running them**, and it shares+`id`s with `cases[]`. Only `id` and `title` are required. A plan item with no+matching case renders as **未执行**: cutting coverage is allowed, hiding that you+cut it is not.++Two of its fields are a **closed vocabulary**, because the pipeline acts on them+— they are not labels:++| field | values | what it does |+| ------------------ | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |+| `verifier` | `program` \| `agent` \| `llm` (default `agent`) | How the verdict is reached. A command-asserted check is `program`; calling it `agent` hides what actually judged it. |+| `requiredEvidence` | `screenshot` \| `gif` \| `video` \| `text` \| `dom_snapshot` \| `transcript` | The artifact this check **must** produce. The executor's coverage gate **fails** an item whose required medium is missing. |++An out-of-vocabulary value in either fails the ingest — an unrecognized medium+would silently gate on nothing, which is worse than no gate at all.++`method` (how you would exercise it) and `expected` (what would make it pass)+stay **free prose** — they carry intent no enum can, and both render under the+check on the page next to the outcome.++`surfaces` is a **closed set** — `web` | `desktop` | `cli` | `mobile` | `bot` —+and names the product surface a check ran **on**. `electron` is accepted and+normalized to `desktop`. Anything else fails the ingest, so don't reach for it:++- A **test kind** is not a surface. `unit`, `backend`, `database`, `type-check`+ do not belong here; a backend change verified through the CLI has surface+ `cli`.+- A **runtime mode** is not a surface. "packaged build (app.isPackaged=true)",+ "CDP dev instance" — that detail belongs on the plan item's `method`.++`entry` is the command or URL exercised (`lh task list --tree`,+`/chat/settings`) — **not** a PR title and not a description of the change.++`pullRequest` is optional: when it is absent, the ingest asks `gh` for the PR of+`branch` and fills it in. Write it explicitly only when the report verifies a PR+that isn't the branch's own.+`score` is optional — use it when the verdict has a subjective component (UIpolish, copy quality); omit it for purely binary runs. `verdict` is the singleword the user reads first: `pass`, `fail`, or `partial`.diff --git a/.agents/skills/agent-testing/scripts/report-init.sh b/.agents/skills/agent-testing/scripts/report-init.shindex 2d884fdc634..e64eba26dad 100755--- a/.agents/skills/agent-testing/scripts/report-init.sh+++ b/.agents/skills/agent-testing/scripts/report-init.sh@@ -40,9 +40,16 @@ cat > "$DIR/report.md" << EOFEOF# result.json drives the structured page. \`summary.conclusion\` is the overall-# conclusion shown at the top (under the scope block); \`summary.score\` (0-100)-# becomes the \`score\` stat; \`scenario\`/\`context\` fields-# (branch/commit/surfaces/entry/focus) render the scope header.+# conclusion shown at the top (under the title); \`summary.score\` (0-100) becomes+# the \`score\` stat; branch/commit/surfaces/entry render the one-line provenance.+#+# \`plan\` is filled BEFORE the run: {id, title, method, expected} per check. It+# shares ids with \`cases\`, so the page pairs intent against outcome and shows a+# planned item that never ran as 未执行 rather than dropping it.+#+# \`surfaces\` is a closed set: web | desktop | cli | mobile | bot. It is where a+# check RAN — not a test kind (unit/backend) and not a runtime mode (packaged+# build / CDP dev instance; that goes on the plan item's \`method\`).cat > "$DIR/result.json" << EOF{"title": "$TITLE",@@ -52,7 +59,7 @@ cat > "$DIR/result.json" << EOF"commit": "$COMMIT","surfaces": [],"entry": "",- "focus": "",+ "plan": [],"cases": [],"interactionCost": null,"summary": { "total": 0, "passed": 0, "failed": 0, "blocked": 0, "verdict": "pending", "conclusion": "", "score": null }diff --git a/apps/cli/src/commands/verify.test.ts b/apps/cli/src/commands/verify.test.tsindex 7ebfb08bb81..9f03a29f594 100644--- a/apps/cli/src/commands/verify.test.ts+++ b/apps/cli/src/commands/verify.test.ts@@ -5,7 +5,13 @@ import path from 'node:path';import { Command } from 'commander';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { registerVerifyCommand, reportEvidence } from './verify';+import {+ originFromEnv,+ planFromResult,+ registerVerifyCommand,+ reportEvidence,+ surfacesFromResult,+} from './verify';const { mockTrpcClient } = vi.hoisted(() => ({mockTrpcClient: {@@ -295,3 +301,173 @@ describe('reportEvidence — comparison normalization', () => {).toEqual([{ comparison: undefined, description: 'a shot', path: 'a.png' }]);});});++describe('surfacesFromResult — surface normalization', () => {+ let exitSpy: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {+ throw new Error('process.exit');+ }) as never);+ });++ afterEach(() => {+ exitSpy.mockRestore();+ });++ it('canonicalizes known aliases and dedupes', () => {+ expect(surfacesFromResult({ surfaces: ['electron', 'cli', 'desktop'] })).toEqual([+ 'desktop',+ 'cli',+ ]);+ });++ it('rejects a value that names no surface instead of silently dropping it', () => {+ // Free-form surfaces are how the field rotted: prose, runtime modes and test+ // kinds all ended up in it. Failing here puts the fix in the author's hands+ // while they still have the context to make it.+ expect(() =>+ surfacesFromResult({ surfaces: ['Electron 打包版(app.isPackaged=true)'] }),+ ).toThrow('process.exit');+ expect(() => surfacesFromResult({ surfaces: ['unit'] })).toThrow('process.exit');+ });++ it('returns undefined when the report names no surfaces at all', () => {+ expect(surfacesFromResult({})).toBeUndefined();+ expect(surfacesFromResult({ surfaces: [] })).toBeUndefined();+ });+});++describe('planFromResult — plan item normalization', () => {+ let exitSpy: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {+ throw new Error('process.exit');+ }) as never);+ });++ afterEach(() => {+ exitSpy.mockRestore();+ });++ it('fills every frozen-item field the author does not write', () => {+ expect(planFromResult({ plan: [{ id: '1', title: 'logs are persisted' }] })).toEqual([+ {+ description: undefined,+ id: '1',+ index: 0,+ onFail: 'manual',+ required: true,+ title: 'logs are persisted',+ verifierConfig: {},+ verifierType: 'agent',+ },+ ]);+ });++ it('honors the declared verifier instead of assuming every check is agent-judged', () => {+ const [item] = planFromResult({+ plan: [{ id: '1', title: 'cli returns a tree', verifier: 'program' }],+ })!;++ expect(item.verifierType).toBe('program');+ });++ it('carries requiredEvidence, which the executor coverage gate actually enforces', () => {+ const [item] = planFromResult({+ plan: [+ {+ id: '1',+ requiredEvidence: ['screenshot', { hint: 'the raw command output', type: 'text' }],+ title: 'ui renders',+ },+ ],+ })!;++ expect(item.verifierConfig).toEqual({+ requiredEvidence: [+ { hint: undefined, type: 'screenshot' },+ { hint: 'the raw command output', type: 'text' },+ ],+ });+ });++ it('rejects an out-of-vocabulary verifier or evidence medium', () => {+ // An unrecognized medium would gate on nothing — silently weaker than no gate.+ expect(() => planFromResult({ plan: [{ id: '1', title: 't', verifier: 'eyeball' }] })).toThrow(+ 'process.exit',+ );+ expect(() =>+ planFromResult({ plan: [{ id: '1', requiredEvidence: ['vibes'], title: 't' }] }),+ ).toThrow('process.exit');+ });++ it('carries how the check would be made and what it expected', () => {+ const [item] = planFromResult({+ plan: [{ expected: 'the file exists', id: '1', method: 'tail the log', title: 'logs' }],+ })!;++ expect(item.verifierConfig).toEqual({ expected: 'the file exists', method: 'tail the log' });+ });++ it('keys items by the same id the cases use, so results pair back to them', () => {+ const items = planFromResult({ plan: [{ id: 'case-a', title: 'a' }, { title: 'b' }] })!;++ expect(items.map((i) => i.id)).toEqual(['case-a', 'case-2']);+ });++ it('drops an item that names no check', () => {+ expect(planFromResult({ plan: [{ id: '1' }] })).toEqual([]);+ });++ it('distinguishes "no plan field" from "an empty plan", so a re-ingest can CLEAR a stale one', () => {+ // Absent → undefined → `updateRun` omits it → whatever is stored stays.+ expect(planFromResult({})).toBeUndefined();++ // Present but empty → `[]` → the stored plan is overwritten with nothing.+ // Without this, re-ingesting a reused report dir whose plan was emptied+ // would leave the PREVIOUS round's plan attached, and every one of its items+ // would render as "not run" against a report that never planned them.+ expect(planFromResult({ plan: [] })).toEqual([]);+ });+});++describe('originFromEnv — in-app provenance', () => {+ const saved = { ...process.env };++ afterEach(() => {+ process.env = { ...saved };+ });++ it('reads the conversation the agent runtime echoed into the child env', () => {+ process.env.LOBEHUB_AGENT_ID = 'agt_1';+ process.env.LOBEHUB_TOPIC_ID = 'tpc_1';+ process.env.LOBEHUB_OPERATION_ID = 'op_1';++ expect(originFromEnv()).toEqual({+ agentId: 'agt_1',+ operationId: 'op_1',+ topicId: 'tpc_1',+ });+ });++ it('never takes its operationId from --operation, which names the run under TEST', () => {+ // `--operation` links the session to the Agent Run being verified; origin is+ // the run that AUTHORED the report. Conflating them attributes the report to+ // its own subject — exactly the provenance this is meant to preserve.+ process.env.LOBEHUB_OPERATION_ID = 'op_authoring_run';++ expect(originFromEnv()?.operationId).toBe('op_authoring_run');+ // The flag is passed to `createRun` separately; it must not reach here at all.+ expect(originFromEnv).toHaveLength(0);+ });++ it('is undefined outside a LobeHub-spawned agent — a plain terminal is not an error', () => {+ delete process.env.LOBEHUB_AGENT_ID;+ delete process.env.LOBEHUB_TOPIC_ID;+ delete process.env.LOBEHUB_OPERATION_ID;++ expect(originFromEnv()).toBeUndefined();+ });+});diff --git a/apps/cli/src/commands/verify.ts b/apps/cli/src/commands/verify.tsindex ec80574dd65..26b2334b256 100644--- a/apps/cli/src/commands/verify.ts+++ b/apps/cli/src/commands/verify.ts@@ -1,6 +1,9 @@+import { execFileSync } from 'node:child_process';import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';import path from 'node:path';+import type { VerifyRunOrigin, VerifySurface } from '@lobechat/types';+import { normalizeVerifySurface, verifyEvidenceTypes, verifySurfaces } from '@lobechat/types';import type { Command } from 'commander';import pc from 'picocolors';@@ -18,6 +21,8 @@ type Decision = 'accepted' | 'overridden' | 'rejected';const VERIFIER_TYPES: VerifierType[] = ['program', 'agent', 'llm'];const ON_FAIL: OnFail[] = ['manual', 'auto_repair'];const DECISIONS: Decision[] = ['accepted', 'rejected', 'overridden'];+/** The evidence media a plan item may require — the same closed set the executor gates on. */+const EVIDENCE_TYPES = verifyEvidenceTypes;function parseConfig(raw?: string): Record<string, unknown> | undefined {if (!raw) return undefined;@@ -166,21 +171,219 @@ function pullRequestFromResult(result: Record<string, unknown>) {return entries.length > 0 ? Object.fromEntries(entries) : undefined;}+/**+ * The PR for a branch, asked of `gh`. A report almost always verifies a branch+ * that already has one, but the author has to remember to write it down — and+ * mostly doesn't, so the report loses its single most useful outbound link.+ * Best-effort by design: no `gh`, not a repo, not authenticated, or no PR for+ * the branch all mean "no PR", never a failed publish.+ */+function pullRequestFromBranch(branch: string | undefined) {+ if (!branch) return undefined;++ try {+ const raw = execFileSync(+ 'gh',+ ['pr', 'view', branch, '--json', 'number,title,url'],+ // `gh` writes its "no pull requests found" diagnostics to stderr; keep them+ // off the CLI's own output.+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000 },+ );+ const parsed = objectValue(JSON.parse(raw));+ const url = safeWebUrl(firstString(parsed?.url));+ const number = firstStringOrNumber(parsed?.number);+ const title = firstString(parsed?.title);+ const entries = Object.entries({ number, title, url }).filter(([, v]) => v !== undefined);++ return entries.length > 0 ? Object.fromEntries(entries) : undefined;+ } catch {+ return undefined;+ }+}++/**+ * The surfaces the report says it exercised, as canonical values.+ *+ * Strict on purpose: an unrecognized surface is a hard error, not a silently+ * dropped value. Free-form surfaces are how the field rotted — prose, runtime+ * modes ("packaged build") and test kinds ("unit", "type-check") all ended up in+ * it, and none of them render. Failing here puts the fix in the author's hands+ * while they still have the context to make it.+ */+export function surfacesFromResult(result: Record<string, unknown>): VerifySurface[] | undefined {+ if (!Array.isArray(result.surfaces)) return undefined;++ const raw = result.surfaces.filter((s: unknown): s is string => typeof s === 'string');+ const canonical: VerifySurface[] = [];+ const rejected: string[] = [];++ for (const value of raw) {+ const surface = normalizeVerifySurface(value);+ if (surface) {+ if (!canonical.includes(surface)) canonical.push(surface);+ } else {+ rejected.push(value);+ }+ }++ if (rejected.length > 0) {+ log.error(+ `result.json "surfaces" must name the product surface a check ran on, one of: ${verifySurfaces.join(', ')}`,+ );+ log.error(` rejected: ${rejected.map((v) => JSON.stringify(v)).join(', ')}`);+ log.error(+ ' Runtime detail ("packaged build", "CDP dev instance") belongs on a plan item\'s "method"; a test kind ("unit", "backend") is not a surface — a backend change verified through the CLI has surface "cli".',+ );+ process.exit(1);+ }++ return canonical.length > 0 ? canonical : undefined;+}++/** Reject an out-of-vocabulary plan value rather than storing a word nothing reads. */+function assertPlanEnum<T extends string>(+ value: string,+ allowed: readonly T[],+ field: string,+ itemId: string,+): T {+ if ((allowed as readonly string[]).includes(value)) return value as T;++ log.error(`result.json plan item "${itemId}": "${field}" must be one of: ${allowed.join(', ')}`);+ log.error(` rejected: ${JSON.stringify(value)}`);+ process.exit(1);+}++/**+ * The checks the run set out to make, as frozen plan items.+ *+ * Two of the fields are a closed vocabulary, not free text, because the pipeline+ * actually acts on them:+ *+ * - `verifier` → {@link VerifyCheckItem.verifierType} (`program | agent | llm`):+ * how the item is judged. Defaults to `agent`, but a command-asserted check is+ * `program` and mislabelling it hides what actually produced the verdict.+ * - `requiredEvidence` → `verifierConfig.requiredEvidence`+ * ({@link RequiredEvidenceSpec}, medium from {@link verifyEvidenceTypes}):+ * the artifact the item MUST produce. The executor's coverage gate fails an+ * item whose required medium is missing, so this is enforcement, not a label —+ * an unknown medium would silently gate on nothing.+ *+ * `method` / `expected` stay prose: they are the author's intent in words, which+ * no enum can carry. Everything else the frozen {@link VerifyCheckItem} needs is+ * filled in here, so an author writes only `{ id, title }` plus what they mean.+ *+ * Returns `undefined` only when the report declares no `plan` field at all —+ * "leave whatever is stored alone". A `plan` that IS present but empty returns+ * `[]`, which CLEARS the stored one. The distinction matters on a re-ingest of a+ * reused report dir: a previous round's plan would otherwise stay attached, and+ * every one of its items would render as "not run" against a report that never+ * planned them.+ */+export function planFromResult(result: Record<string, unknown>) {+ if (!Array.isArray(result.plan)) return undefined;++ const items = result.plan.flatMap((entry: unknown, index: number) => {+ const item = objectValue(entry);+ const title = firstString(item?.title, item?.name);+ // An item with no title names no check — it can't be rendered or paired.+ if (!item || !title) return [];++ const id = String(item.id ?? `case-${index + 1}`);+ const method = firstString(item.method, item.how);+ const expected = firstString(item.expected, item.expectation);++ const verifierRaw = firstString(item.verifier, item.verifierType);+ const verifierType = verifierRaw+ ? assertPlanEnum(verifierRaw, VERIFIER_TYPES, 'verifier', id)+ : ('agent' as const);++ const requiredEvidence = Array.isArray(item.requiredEvidence)+ ? item.requiredEvidence.flatMap((spec: unknown) => {+ // Accept the bare medium (`"screenshot"`) or the full spec object.+ const record = objectValue(spec);+ const raw = typeof spec === 'string' ? spec : firstString(record?.type);+ if (!raw) return [];++ return [+ {+ hint: firstString(record?.hint),+ type: assertPlanEnum(raw, EVIDENCE_TYPES, 'requiredEvidence', id),+ },+ ];+ })+ : [];++ return [+ {+ description: firstString(item.description),+ id,+ index,+ onFail: 'manual' as const,+ required: typeof item.required === 'boolean' ? item.required : true,+ title,+ verifierConfig: {+ ...(method === undefined ? {} : { method }),+ ...(expected === undefined ? {} : { expected }),+ ...(requiredEvidence.length > 0 ? { requiredEvidence } : {}),+ },+ verifierType,+ },+ ];+ });++ // `[]` is meaningful — it clears a stale plan. Only an absent `plan` field+ // (handled above) means "don't touch what's stored".+ return items;+}++/**+ * The LobeHub conversation this harness is running inside, read off the env the+ * agent runtime echoes into the child process. Lets a report published from an+ * in-app agent link back to the session that produced it with no flags to+ * remember. Absent (a plain terminal) → no origin, which is not an error.+ *+ * Reads the env and ONLY the env. `--operation` is the opposite relation — the+ * Agent Run this session *verifies* — so letting it fall through to here would+ * attribute the report to the run under test instead of the run that wrote it,+ * corrupting the very provenance this records. The two ids are independent and+ * may legitimately differ in the same publish.+ */+export function originFromEnv(): VerifyRunOrigin | undefined {+ const origin: VerifyRunOrigin = {+ agentId: firstString(process.env.LOBEHUB_AGENT_ID),+ operationId: firstString(process.env.LOBEHUB_OPERATION_ID),+ topicId: firstString(process.env.LOBEHUB_TOPIC_ID),+ };++ return Object.values(origin).some(Boolean) ? origin : undefined;+}+function metadataForReport(result: Record<string, unknown>,existingMetadata?: unknown,+ origin?: VerifyRunOrigin,): Record<string, unknown> | undefined {- if (!Object.prototype.hasOwnProperty.call(result, 'interactionCost')) return undefined;+ const hasInteractionCost = Object.prototype.hasOwnProperty.call(result, 'interactionCost');+ // Nothing to write is not the same as writing an empty bag — leave the run's+ // metadata untouched so a re-ingest from a plain terminal can't wipe the+ // origin a previous in-app round recorded.+ if (!hasInteractionCost && !origin) return undefined;const metadata = { ...objectValue(existingMetadata) };- const interactionCost = objectValue(result.interactionCost);- if (interactionCost) {- metadata.interactionCost = interactionCost;- } else {- delete metadata.interactionCost;+ if (hasInteractionCost) {+ const interactionCost = objectValue(result.interactionCost);++ if (interactionCost) {+ metadata.interactionCost = interactionCost;+ } else {+ delete metadata.interactionCost;+ }}+ if (origin) metadata.origin = origin;+return metadata;}@@ -1116,21 +1319,25 @@ export function registerVerifyCommand(program: Command) {// The scenario's context for the report's scope header, lifted from// result.json's top-level fields. Drop empty keys so the bag stays clean.- const surfaces = Array.isArray(result.surfaces)- ? result.surfaces.filter((s: unknown) => typeof s === 'string')- : undefined;- const pullRequest = pullRequestFromResult(result);+ const branch = typeof result.branch === 'string' ? result.branch : undefined;+ const surfaces = surfacesFromResult(result);+ // An authored PR wins; otherwise ask `gh` what the branch's PR is, so the+ // report links to it without the author having to remember the field.+ const pullRequest = pullRequestFromResult(result) ?? pullRequestFromBranch(branch);const contextEntries = Object.entries({- branch: typeof result.branch === 'string' ? result.branch : undefined,+ branch,commit: typeof result.commit === 'string' ? result.commit : undefined,entry: typeof result.entry === 'string' ? result.entry : undefined,- focus: typeof result.focus === 'string' ? result.focus : options.goal,pullRequest,- surfaces: surfaces && surfaces.length > 0 ? surfaces : undefined,+ surfaces,testedAt: typeof result.createdAt === 'string' ? result.createdAt : undefined,}).filter(([, v]) => v !== undefined);const context = contextEntries.length > 0 ? Object.fromEntries(contextEntries) : undefined;+ // What the run set out to check, written before it ran. Paired with the+ // results by `id`, so the report can show a planned item that never ran.+ const plan = planFromResult(result);+// The harness verifies software changes; tag the run so the viewer renders// the coding scope header. Overridable via result.json `scenario`.const scenario = result.scenario === 'coding' ? 'coding' : ('coding' as const);@@ -1138,7 +1345,11 @@ 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);+ // The in-app conversation that ran this harness, if any (env-supplied).+ // Strictly the authoring conversation. `--operation` names the Agent Run+ // under test and is passed to `createRun` below — a different relation.+ const origin = originFromEnv();+ const newRunMetadata = metadataForReport(result, undefined, origin);// Resolve the target session. Reuse the one this report dir already// created (recorded in the sidecar) so re-verifying the same case@@ -1153,10 +1364,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.+ const metadata = metadataForReport(result, existing.metadata, origin);+ // 1a. Refresh the scope header / plan / title / goal in place.await client.verify.updateRun.mutate({- value: { context, goal, metadata, scenario, title },+ value: { context, goal, metadata, plan, scenario, title },verifyRunId: runId,});} else if (options.run) {@@ -1178,6 +1389,7 @@ export function registerVerifyCommand(program: Command) {goal,metadata: newRunMetadata,operationId: options.operation,+ plan,scenario,source: options.source as any,title,@@ -1307,14 +1519,26 @@ export function registerVerifyCommand(program: Command) {// same dir updates it in place instead of creating a new one.writeSidecarRunId(dir, runId);+ // A case with no matching plan item means the run checked something it+ // never planned — worth saying out loud, but not a failure. Only+ // meaningful against a plan that actually names something: with no plan+ // (or a cleared one) every case is trivially "unplanned", which is noise.+ const unplanned = plan?.length+ ? [...seenCheckItemIds].filter((id) => !plan.some((item) => item.id === id))+ : [];+if (options.json !== undefined) {outputJson({cases: cases.length,evidence: evidenceCount,inlined,+ origin,+ planItems: plan?.length ?? 0,pruned,+ pullRequest,reused,+ unplanned,verifyRunId: runId,},typeof options.json === 'string' ? options.json : undefined,@@ -1328,6 +1552,20 @@ export function registerVerifyCommand(program: Command) {`${inlined > 0 ? `, ${pc.bold(String(inlined))} inline` : ''}` +`${pruned > 0 ? `, pruned ${pc.bold(String(pruned))} stale case(s)` : ''}`,);+ if (plan?.length) {+ const unexecuted = plan.filter((item) => !seenCheckItemIds.has(item.id));+ console.log(+ `${pc.bold('plan')}: ${plan.length} item(s)` ++ `${unexecuted.length > 0 ? pc.yellow(` — ${unexecuted.length} planned but not executed`) : ''}` ++ `${unplanned.length > 0 ? pc.dim(` — ${unplanned.length} unplanned case(s)`) : ''}`,+ );+ } else if (plan && reused) {+ // The report dropped its plan this round; say that the stored one went+ // with it, rather than leaving the user to wonder where it went.+ console.log(`${pc.bold('plan')}: ${pc.dim('none — cleared the previously stored plan')}`);+ }+ if (pullRequest?.url) console.log(`${pc.bold('pr')}: ${pullRequest.url}`);+ if (origin?.topicId) console.log(`${pc.bold('origin topic')}: ${origin.topicId}`);console.log(`${pc.bold('verifyRunId')}: ${runId}${reused ? pc.dim(' (updated in place)') : ''}`,);diff --git a/apps/server/src/routers/lambda/verify.ts b/apps/server/src/routers/lambda/verify.tsindex dd90f6480c1..2bb92115933 100644--- a/apps/server/src/routers/lambda/verify.ts+++ b/apps/server/src/routers/lambda/verify.ts@@ -1,5 +1,6 @@import { VerifySkill } from '@lobechat/builtin-skills';import type { VerifyCheckItem } from '@lobechat/types';+import { normalizeVerifySurface, verifySurfaces } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { asc, eq } from 'drizzle-orm';import { z } from 'zod';@@ -88,6 +89,7 @@ const rubricConfigSchema = z.object({});const checkItemSchema = z.object({+ description: z.string().optional(),id: z.string(),index: z.number(),onFail: onFailSchema,@@ -121,13 +123,34 @@ const pullRequestContextSchema = z.object({url: webUrlSchema.optional(),});+/**+ * A surface, canonicalized at the door.+ *+ * Not a bare `z.enum`: `lh` is installed independently of this server, so an+ * older CLI still posts the historical spellings — `electron` alone accounts for+ * most of the surfaces ever written. Rejecting those would break ingest for+ * every client that hasn't upgraded, to no benefit, since they name a surface we+ * can resolve. So known spellings are normalized (`electron` → `desktop`) and+ * only a value that names no surface at all is rejected — the column still ends+ * up with nothing but the closed set.+ */+const surfaceSchema = z.string().transform((value, ctx) => {+ const surface = normalizeVerifySurface(value);+ if (surface) return surface;++ ctx.addIssue({+ code: 'custom',+ message: `"${value}" is not a product surface. Expected one of: ${verifySurfaces.join(', ')}. A test kind ("unit", "backend") or a runtime mode ("packaged build") is not a surface.`,+ });+ return z.NEVER;+});+const runContextSchema = z.object({branch: z.string().optional(),commit: z.string().optional(),entry: z.string().optional(),- focus: z.string().optional(),pullRequest: pullRequestContextSchema.optional(),- surfaces: z.array(z.string()).optional(),+ surfaces: z.array(surfaceSchema).optional(),testedAt: z.string().optional(),});@@ -140,6 +163,7 @@ const updateRunInputSchema = verifyRunIdInputSchema.extend({context: runContextSchema.optional(),goal: z.string().optional(),metadata: runMetadataSchema.optional(),+ plan: z.array(checkItemSchema).optional(),scenario: z.enum(['coding']).optional(),title: z.string().trim().min(1).max(200).optional(),}),@@ -557,6 +581,9 @@ export const verifyRouter = router({goal: z.string().optional(),metadata: runMetadataSchema.optional(),operationId: z.string().optional(),+ // The checks the run set out to make, authored before it ran. Kept next+ // to the results so a planned-but-never-executed item stays visible.+ plan: z.array(checkItemSchema).optional(),scenario: z.enum(['coding']).optional(),source: runSourceSchema.optional(),title: z.string().optional(),@@ -568,6 +595,7 @@ export const verifyRouter = router({goal: input.goal,metadata: input.metadata,operationId: input.operationId,+ plan: input.plan,scenario: input.scenario,source: input.source ?? 'agent-testing',title: input.title,@@ -644,6 +672,7 @@ export const verifyRouter = router({context: input.value.context,goal: input.value.goal,metadata: input.value.metadata,+ plan: input.value.plan,scenario: input.value.scenario,title: input.value.title,}),@@ -923,14 +952,25 @@ export const verifyRouter = router({* One-shot payload for the standalone report viewer: the session, its report,* and every check result with its evidence — addressed purely by verifyRunId* (no operation / chat context required).+ *+ * Public: a report URL is shareable, so anyone with the id gets the checks and+ * evidence. `isOwner` gates what only the author may see — today the origin+ * conversation, which is redacted for everyone else.*/getReportBundle: publicVerifyReportProcedure.input(verifyRunIdInputSchema).query(async ({ ctx, input }) => {- const run = await ctx.serverDB.query.verifyRuns.findFirst({+ const found = await ctx.serverDB.query.verifyRuns.findFirst({where: eq(verifyRuns.id, input.verifyRunId),});- if (!run) return null;+ if (!found) return null;++ const isOwner = Boolean(ctx.userId) && ctx.userId === found.userId;+ // `origin` points at the author's private topic/agent — never hand it to a+ // visitor holding nothing but the shared link.+ const { origin: _origin, ...publicMetadata } = found.metadata ?? {};+ const run =+ isOwner || !found.metadata?.origin ? found : { ...found, metadata: publicMetadata };const [report, results] = await Promise.all([ctx.serverDB.query.verifyReports.findFirst({where: eq(verifyReports.verifyRunId, input.verifyRunId),@@ -1000,6 +1040,6 @@ export const verifyRouter = router({};}),);- return { report: report ?? null, results: resultsWithEvidence, run };+ return { isOwner, report: report ?? null, results: resultsWithEvidence, run };}),});diff --git a/locales/en-US/verify.json b/locales/en-US/verify.jsonindex f18b562ba4e..b5db7325f4a 100644--- a/locales/en-US/verify.json+++ b/locales/en-US/verify.json@@ -59,10 +59,17 @@"report.evidence.comparison.before": "Before","report.evidence.count": "{{count}} evidence","report.evidence.inlineFallback": "Inline evidence {{index}}",+ "report.evidence.medium.dom_snapshot": "DOM snapshot",+ "report.evidence.medium.gif": "GIF",+ "report.evidence.medium.screenshot": "Screenshot",+ "report.evidence.medium.text": "Text",+ "report.evidence.medium.transcript": "Transcript",+ "report.evidence.medium.video": "Video","report.evidence.openDetail": "Open {{name}}","report.evidence.view": "View evidence ({{count}})","report.filter.all": "All","report.filter.failed": "Failed",+ "report.filter.notExecuted": "Not run","report.filter.passed": "Passed","report.filter.uncertain": "Uncertain","report.filterEmpty": "No checks match this filter.",@@ -89,11 +96,15 @@"report.overview.title": "Check overview","report.overview.total": "All","report.overview.uncertain": "Uncertain",+ "report.plan.expected": "Expected",+ "report.plan.method": "How",+ "report.plan.notExecutedHint": "This check was planned but never ran, so nothing was verified.",+ "report.plan.requiredEvidence": "Must produce","report.scope.branch": "Branch","report.scope.commit": "Commit","report.scope.date": "Date","report.scope.entry": "Entry",- "report.scope.focus": "Focus",+ "report.scope.origin": "Open the conversation that produced this report","report.scope.pullRequest": "Pull request","report.scope.pullRequestNumber": "PR #{{number}}","report.scope.surface": "Surface",@@ -109,8 +120,14 @@"report.status.repairing": "A repair round is running. This report refreshes automatically.","report.status.unverified": "Verification has not started yet.","report.status.verifying": "Verification is running. This report refreshes automatically.",+ "report.surface.bot": "Bot",+ "report.surface.cli": "CLI",+ "report.surface.desktop": "Desktop",+ "report.surface.mobile": "Mobile",+ "report.surface.web": "Web","report.titleFallback": "Verification report","report.verdict.failed": "Failed",+ "report.verdict.notExecuted": "Not run","report.verdict.passed": "Passed","report.verdict.uncertain": "Uncertain","reports.actions.refresh": "Refresh",diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.jsonindex d5d317b51ba..fb6d8f40ed9 100644--- a/locales/zh-CN/verify.json+++ b/locales/zh-CN/verify.json@@ -59,10 +59,17 @@"report.evidence.comparison.before": "优化前","report.evidence.count": "{{count}} 条证据","report.evidence.inlineFallback": "内联证据 {{index}}",+ "report.evidence.medium.dom_snapshot": "DOM 快照",+ "report.evidence.medium.gif": "GIF",+ "report.evidence.medium.screenshot": "截图",+ "report.evidence.medium.text": "文本",+ "report.evidence.medium.transcript": "会话记录",+ "report.evidence.medium.video": "视频","report.evidence.openDetail": "打开 {{name}}","report.evidence.view": "查看证据({{count}})","report.filter.all": "全部","report.filter.failed": "未通过",+ "report.filter.notExecuted": "未执行","report.filter.passed": "已通过","report.filter.uncertain": "不确定","report.filterEmpty": "没有符合该筛选的检查项。",@@ -89,11 +96,15 @@"report.overview.title": "检查概览","report.overview.total": "全部","report.overview.uncertain": "不确定",+ "report.plan.expected": "预期",+ "report.plan.method": "验法",+ "report.plan.notExecutedHint": "这项检查计划中有,但本轮没有执行,因此未被验证。",+ "report.plan.requiredEvidence": "须产出","report.scope.branch": "分支","report.scope.commit": "提交","report.scope.date": "日期","report.scope.entry": "入口",- "report.scope.focus": "重点",+ "report.scope.origin": "打开产出这份报告的对话","report.scope.pullRequest": "关联 PR","report.scope.pullRequestNumber": "PR #{{number}}","report.scope.surface": "范围",@@ -109,8 +120,14 @@"report.status.repairing": "修复轮次正在运行,本报告会自动刷新。","report.status.unverified": "验证尚未开始。","report.status.verifying": "验证正在运行,本报告会自动刷新。",+ "report.surface.bot": "机器人",+ "report.surface.cli": "命令行",+ "report.surface.desktop": "桌面端",+ "report.surface.mobile": "移动端",+ "report.surface.web": "网页端","report.titleFallback": "验证报告","report.verdict.failed": "未通过",+ "report.verdict.notExecuted": "未执行","report.verdict.passed": "已通过","report.verdict.uncertain": "不确定","reports.actions.refresh": "刷新",diff --git a/packages/database/src/models/verifyRun.ts b/packages/database/src/models/verifyRun.tsindex 2487d12c7be..e819f7ac4a7 100644--- a/packages/database/src/models/verifyRun.ts+++ b/packages/database/src/models/verifyRun.ts@@ -293,7 +293,9 @@ export class VerifyRunModel {update = async (runId: string,- value: Partial<Pick<NewVerifyRun, 'context' | 'goal' | 'metadata' | 'scenario' | 'title'>>,+ value: Partial<+ Pick<NewVerifyRun, 'context' | 'goal' | 'metadata' | 'plan' | 'scenario' | 'title'>+ >,): Promise<VerifyRunItem | undefined> => {const [run] = await this.db.update(verifyRuns)diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.tsindex e8e7f5e05f5..6d1336ad569 100644--- a/packages/locales/src/default/verify.ts+++ b/packages/locales/src/default/verify.ts@@ -73,6 +73,7 @@ export default {'report.evidence.view': 'View evidence ({{count}})','report.filter.all': 'All','report.filter.failed': 'Failed',+ 'report.filter.notExecuted': 'Not run','report.filter.passed': 'Passed','report.filter.uncertain': 'Uncertain','report.filterEmpty': 'No checks match this filter.',@@ -102,11 +103,21 @@ export default {'report.overview.title': 'Check overview','report.overview.total': 'All','report.overview.uncertain': 'Uncertain',+ 'report.evidence.medium.dom_snapshot': 'DOM snapshot',+ 'report.evidence.medium.gif': 'GIF',+ 'report.evidence.medium.screenshot': 'Screenshot',+ 'report.evidence.medium.text': 'Text',+ 'report.evidence.medium.transcript': 'Transcript',+ 'report.evidence.medium.video': 'Video',+ 'report.plan.expected': 'Expected',+ 'report.plan.method': 'How',+ 'report.plan.notExecutedHint': 'This check was planned but never ran, so nothing was verified.',+ 'report.plan.requiredEvidence': 'Must produce','report.scope.branch': 'Branch','report.scope.commit': 'Commit','report.scope.date': 'Date','report.scope.entry': 'Entry',- 'report.scope.focus': 'Focus',+ 'report.scope.origin': 'Open the conversation that produced this report','report.scope.pullRequest': 'Pull request','report.scope.pullRequestNumber': 'PR #{{number}}','report.scope.surface': 'Surface',@@ -122,8 +133,14 @@ export default {'report.status.repairing': 'A repair round is running. This report refreshes automatically.','report.status.unverified': 'Verification has not started yet.','report.status.verifying': 'Verification is running. This report refreshes automatically.',+ 'report.surface.bot': 'Bot',+ 'report.surface.cli': 'CLI',+ 'report.surface.desktop': 'Desktop',+ 'report.surface.mobile': 'Mobile',+ 'report.surface.web': 'Web','report.titleFallback': 'Verification report','report.verdict.failed': 'Failed',+ 'report.verdict.notExecuted': 'Not run','report.verdict.passed': 'Passed','report.verdict.uncertain': 'Uncertain',diff --git a/packages/types/src/verify.ts b/packages/types/src/verify.tsindex 8af9307c073..69214a0ad43 100644--- a/packages/types/src/verify.ts+++ b/packages/types/src/verify.ts@@ -80,6 +80,38 @@ export type VerifyRunSource = (typeof verifyRunSources)[number];export const verifyRunScenarios = ['coding'] as const;export type VerifyRunScenario = (typeof verifyRunScenarios)[number];+/**+ * The product surface a check was exercised on — *where* it ran, never *what+ * kind* of test it was. `unit` / `backend` / `type-check` are test kinds and do+ * not belong here; a backend change verified through the CLI has surface `cli`.+ *+ * A closed set on purpose: free-form surfaces drifted into 76 distinct values+ * (long prose, runtime modes, tool names), which no viewer can render as a+ * legible badge. Runtime detail ("packaged build", "CDP dev instance") belongs+ * on the plan item's `method`, not here.+ */+export const verifySurfaces = ['web', 'desktop', 'cli', 'mobile', 'bot'] as const;+export type VerifySurface = (typeof verifySurfaces)[number];++/**+ * Historical spellings that name a surface in this set. Only unambiguous+ * synonyms — anything else is a rejected value, not a guess.+ */+const VERIFY_SURFACE_ALIASES: Record<string, VerifySurface> = {+ android: 'mobile',+ browser: 'web',+ electron: 'desktop',+ ios: 'mobile',+ terminal: 'cli',+};++/** Canonical surface for a raw value, or null when it names no known surface. */+export const normalizeVerifySurface = (value: string): VerifySurface | null => {+ const key = value.trim().toLowerCase();+ if ((verifySurfaces as readonly string[]).includes(key)) return key as VerifySurface;+ return VERIFY_SURFACE_ALIASES[key] ?? null;+};+/*** Coding-scenario scope: where the code under test came from and how it ran.* Rendered as the report's scope header so the verify page reads as the final@@ -101,12 +133,10 @@ export interface VerifyCodingScope {commit?: string;/** Entry point / command exercised, e.g. "lh verify ingest-report". */entry?: string;- /** The focus / key risk of this round (free text). */- focus?: string;/** Associated pull request, when the verification run has one. */pullRequest?: VerifyCodingPullRequest;- /** Test surfaces exercised, e.g. ["cli", "web"]. */- surfaces?: string[];+ /** Product surfaces the checks ran on. */+ surfaces?: VerifySurface[];/** When the report was authored (ISO 8601) — distinct from the row's createdAt (ingest time). */testedAt?: string;}@@ -175,6 +205,19 @@ export interface VerifyRubricConfig {maxRepairRounds?: number;}+/**+ * The LobeHub conversation an ingested report was authored in. Lets the report+ * link back to (and later resume) the agent session that produced it.+ */+export interface VerifyRunOrigin {+ /** The agent that ran the verification. */+ agentId?: string;+ /** The agent operation (one execution) that produced the report. */+ operationId?: string;+ /** The topic to reopen to continue from this report. */+ topicId?: string;+}+/*** Generic per-run extension bag (`verify_runs.metadata`) — cross-scenario knobs* we don't model as columns. Kept open so new policy switches don't require a@@ -191,6 +234,17 @@ export interface VerifyRunMetadata {* time via {@link DEFAULT_MAX_REPAIR_ROUNDS} fallback.*/maxRepairRounds?: number;+ /**+ * Where this report came from — the LobeHub conversation whose agent produced+ * it. Set when the harness runs inside a LobeHub-spawned agent (the runtime+ * echoes the ids into the child env; see {@link VerifyRunOrigin}).+ *+ * Deliberately *not* `verify_runs.operation_id`: that column means "this+ * session verifies that Agent Run" and is uniquely indexed, so one agent+ * publishing two reports would collide. Origin is the inverse relation — the+ * run that *authored* the report — and is many-to-one.+ */+ origin?: VerifyRunOrigin;}/**@@ -222,6 +276,27 @@ export interface VerifyCheckItem {verifierType: VerifierType;}+/**+ * `verifierConfig` of a plan item authored by a harness before its run.+ *+ * Note what is NOT here: *how the item is judged* is `verifierType`+ * (program / agent / llm), and *what artifact it must produce* is+ * {@link RequiredEvidenceSpec} under `requiredEvidence` — both closed sets, and+ * the latter is enforced (a missing required artifact fails the item through the+ * executor's coverage gate). `method` and `expected` are the human-readable+ * complement to those two, not a replacement: prose the author writes down+ * *before* the run so a reader can weigh intent against outcome, and so a+ * planned-but-never-executed item stays legible instead of vanishing.+ */+export interface VerifyAgentPlanConfig {+ /** The observable outcome that would make this item pass. Prose. */+ expected?: string;+ /** How the item would be exercised (steps / command / probe). Prose. */+ method?: string;+ /** Evidence media this item must produce — gated, not decorative. */+ requiredEvidence?: RequiredEvidenceSpec[];+}+/*** Strongly-typed Toulmin narrative for a verdict. Only ever read as a whole, so* the narrative elements live in one bag instead of 4-5 half-empty columns.diff --git a/src/features/Verify/ReportViewer.tsx b/src/features/Verify/ReportViewer.tsxindex 8e9b5fe4058..67b028157ca 100644--- a/src/features/Verify/ReportViewer.tsx+++ b/src/features/Verify/ReportViewer.tsx@@ -1,11 +1,16 @@'use client';import type {+ VerifyAgentPlanConfig,+ VerifyCheckItem,VerifyCodingScope,VerifyEvidenceType,VerifyInteractionCost,VerifyInteractionCostOperators,VerifyInteractionCostPhase,+ VerifyRunOrigin,+ VerifySurface,+ VerifyVerdict,} from '@lobechat/types';import { toRecord } from '@lobechat/utils/object';import {@@ -25,9 +30,11 @@ import { createStaticStyles, cssVar, cx } from 'antd-style';import type { TFunction } from 'i18next';import {AlertTriangle,+ Bot,CalendarClock,Check,ChevronRight,+ CircleDashed,CircleHelp,Clock3,ExternalLink,@@ -35,10 +42,12 @@ import {GitBranch,GitCommit,GitPullRequest,+ Globe,Image as ImageIcon,- Layers,+ MessagesSquare,+ Monitor,RefreshCw,- Target,+ Smartphone,Terminal,Video,X,@@ -49,13 +58,13 @@ import { useParams } from 'react-router';import Loading from '@/components/Loading/BrandTextLoading';import { useTextFileLoader } from '@/features/FileViewer/hooks/useTextFileLoader';-import type { VerifyEvidenceWithUrl, VerifyResultWithEvidence } from '@/services/verify';+import type { VerifyEvidenceWithUrl } from '@/services/verify';import { getLanguageFromFilename } from '@/utils/fileLanguage';import { useVerifyReportBundle } from './hooks';+import { buildCheckRows, type CheckRowData, type CheckState, renderableSurfaces } from './utils';-type Verdict = 'passed' | 'failed' | 'uncertain';-type Filter = 'all' | Verdict;+type Filter = 'all' | CheckState;/** Best-effort filename from a (possibly signed) file URL, for syntax highlighting. */const filenameFromUrl = (url: string): string => {@@ -77,7 +86,10 @@ const styles = createStaticStyles(({ css }) => ({max-width: 880px;margin-inline: auto;padding-block: 32px 64px;- padding-inline: 32px;++ /* Start-aligned with the 46px gutter a check row's body sits at, so the hero+ prose and the expanded check prose share one text edge. */+ padding-inline: 46px 32px;`,/* hero */@@ -325,21 +337,34 @@ const styles = createStaticStyles(({ css }) => ({font-variant-numeric: tabular-nums;color: ${cssVar.colorTextTertiary};`,+ /* Provenance: where the code came from. Reference material the reader scans,+ so it stays visually subordinate to the verdict + summary above it. */codingScope: css`display: flex;flex-direction: column;gap: 6px;+ min-width: 0;+ max-width: 100%;+ margin-block-start: 4px;+ `,+ /* The PR gets its own line. It is the one outbound link a reader actually+ follows, and its title is long enough that sharing a row with branch/commit+ would either push them onto a second line anyway or truncate the title to+ nothing. */+ scopePullRequestLine: css`+ display: flex;+ min-width: 0;max-width: 100%;- margin-block-start: 8px;`,- codingScopeMain: css`+ scopeMetaLine: css`display: flex;flex-wrap: wrap;gap: 6px 14px;align-items: center;min-width: 0;+ max-width: 100%;`,branchChip: css`display: inline-flex;@@ -396,8 +421,9 @@ const styles = createStaticStyles(({ css }) => ({gap: 6px;align-items: center;+ /* Owns its own line, so the title gets the full column before ellipsizing. */min-width: 0;- max-width: 420px;+ max-width: 100%;font-size: 12px;color: ${cssVar.colorTextSecondary};@@ -430,14 +456,6 @@ const styles = createStaticStyles(({ css }) => ({text-overflow: ellipsis;white-space: nowrap;`,- scopeMetaRow: css`- display: flex;- flex-wrap: wrap;- gap: 8px 14px;- align-items: center;-- min-width: 0;- `,scopeMetaItem: css`display: inline-flex;gap: 6px;@@ -461,17 +479,29 @@ const styles = createStaticStyles(({ css }) => ({text-overflow: ellipsis;white-space: nowrap;}++ svg {+ flex: 0 0 auto;+ color: ${cssVar.colorTextQuaternary};+ }`,- scopeFocus: css`- display: inline-flex;- gap: 6px;- align-items: flex-start;+ /* The command / URL under test. Can be long; it must never push the rest of+ the provenance line onto a second row. */+ scopeEntry: css`+ max-width: 260px;+ `,+ originLink: css`+ cursor: pointer;+ color: ${cssVar.colorTextTertiary};+ text-decoration: none;- max-width: 72ch;+ &:hover {+ color: ${cssVar.colorLink};+ }- font-size: 13px;- line-height: 1.45;- color: ${cssVar.colorTextSecondary};+ &:hover svg {+ color: ${cssVar.colorLink};+ }`,surfaceList: css`display: flex;@@ -479,6 +509,10 @@ const styles = createStaticStyles(({ css }) => ({gap: 4px;`,surfaceChip: css`+ display: inline-flex;+ gap: 4px;+ align-items: center;+padding-block: 1px;padding-inline: 6px;border-radius: ${cssVar.borderRadiusSM};@@ -487,6 +521,10 @@ const styles = createStaticStyles(({ css }) => ({color: ${cssVar.colorTextSecondary};background: ${cssVar.colorFillTertiary};++ svg {+ color: ${cssVar.colorTextTertiary};+ }`,/* sticky filter chips */@@ -636,13 +674,11 @@ const styles = createStaticStyles(({ css }) => ({padding-inline: 46px 16px;`,reasoning: css`- max-width: 70ch;font-size: 13px;line-height: 1.6;color: ${cssVar.colorTextSecondary};`,suggestion: css`- max-width: 70ch;padding-inline-start: 10px;border-inline-start: 2px solid ${cssVar.colorBorder};@@ -650,6 +686,26 @@ const styles = createStaticStyles(({ css }) => ({line-height: 1.6;color: ${cssVar.colorTextSecondary};`,+ /* What the run said it would do, before it did it — read above the outcome so+ intent and result sit together and a gap between them is visible. */+ planDetail: css`+ display: grid;+ grid-template-columns: auto minmax(0, 1fr);+ gap: 4px 8px;++ font-size: 13px;+ line-height: 1.6;+ color: ${cssVar.colorTextTertiary};+ `,+ planDetailLabel: css`+ color: ${cssVar.colorTextQuaternary};+ white-space: nowrap;+ `,+ notExecutedHint: css`+ font-size: 13px;+ line-height: 1.6;+ color: ${cssVar.colorTextTertiary};+ `,/* narrative */narrative: css`@@ -698,7 +754,7 @@ const styles = createStaticStyles(({ css }) => ({gap: 6px;align-items: flex-start;- max-width: 70ch;+ width: 100%;`,comparison: css`display: grid;@@ -866,7 +922,7 @@ const styles = createStaticStyles(({ css }) => ({}));const VERDICT_META: Record<- Verdict,+ CheckState,{ bg: string; color: string; dot: string; icon: typeof Check; labelKey: string }> = {failed: {@@ -876,6 +932,13 @@ const VERDICT_META: Record<icon: X,labelKey: 'report.verdict.failed',},+ not_executed: {+ bg: cssVar.colorFillTertiary,+ color: cssVar.colorTextTertiary,+ dot: cssVar.colorTextQuaternary,+ icon: CircleDashed,+ labelKey: 'report.verdict.notExecuted',+ },passed: {bg: cssVar.colorSuccessBg,color: cssVar.colorSuccessText,@@ -892,6 +955,15 @@ const VERDICT_META: Record<},};+/** Each surface reads as a badge, so it needs a mark, not just a word. */+const SURFACE_ICON: Record<VerifySurface, typeof Check> = {+ bot: Bot,+ cli: Terminal,+ desktop: Monitor,+ mobile: Smartphone,+ web: Globe,+};+const imageEvidenceTypes = new Set(['gif', 'screenshot']);/** Visual media that renders/plays inline in the check body, no click-to-open. */const isInlineVisualEvidence = (evidence: VerifyEvidenceWithUrl) =>@@ -1052,15 +1124,6 @@ const phaseOperatorSegments = (return seconds > 0 ? [{ key, seconds, value }] : [];});-/** Severity-first sort: failed → uncertain → passed. */-const SEVERITY_RANK: Record<Verdict, number> = { failed: 0, passed: 2, uncertain: 1 };--const checkVerdict = (result: VerifyResultWithEvidence): Verdict => {- const v = result.verdict ?? result.status;- if (v === 'passed' || v === 'failed' || v === 'uncertain') return v;- return 'uncertain';-};-const evidenceDisplayName = (evidence: VerifyEvidenceWithUrl,t: TFunction<'verify'>,@@ -1410,122 +1473,172 @@ EvidenceComparisonView.displayName = 'EvidenceComparisonView';EvidenceDrawer.displayName = 'EvidenceDrawer';/** One check — an expandable row; evidence opens one artifact at a time. */-const CheckRow = memo<{ defaultOpen: boolean; result: VerifyResultWithEvidence }>(- ({ defaultOpen, result }) => {- const { t } = useTranslation('verify');- const [open, setOpen] = useState(defaultOpen);- const [selectedEvidenceId, setSelectedEvidenceId] = useState<string | null>(null);- const verdict = checkVerdict(result);- const meta = VERDICT_META[verdict];- const evidenceCount = result.evidence.length;- const categoryCounts = result.evidence.reduce(- (acc, e) => {- acc[evidenceCategory(e.type)] += 1;- return acc;- },- { file: 0, image: 0, video: 0 } as Record<EvidenceCategory, number>,- );- const hasBody =- Boolean(result.toulmin?.evidence) || Boolean(result.suggestion) || evidenceCount > 0;- const selectedEvidenceIndex = selectedEvidenceId- ? result.evidence.findIndex((e) => e.id === selectedEvidenceId)- : -1;- const selectedEvidence =- selectedEvidenceIndex >= 0 ? result.evidence[selectedEvidenceIndex] : null;- const comparisonGroups = new Map<- string,- Partial<Record<'after' | 'before', VerifyEvidenceWithUrl>>- >();- for (const evidence of result.evidence) {- const comparison = evidenceComparison(evidence);- if (!comparison) continue;- const group = comparisonGroups.get(comparison.id) ?? {};- group[comparison.role] = evidence;- comparisonGroups.set(comparison.id, group);- }- const pairedEvidenceIds = new Set(- [...comparisonGroups.values()]- .filter((group) => group.before && group.after)- .flatMap((group) => [group.before!.id, group.after!.id]),- );+const CheckRow = memo<{ defaultOpen: boolean; row: CheckRowData }>(({ defaultOpen, row }) => {+ const { t } = useTranslation('verify');+ const { planItem, result, state } = row;+ const [open, setOpen] = useState(defaultOpen);+ const [selectedEvidenceId, setSelectedEvidenceId] = useState<string | null>(null);+ const meta = VERDICT_META[state];+ const evidence = result?.evidence ?? [];+ const evidenceCount = evidence.length;+ // An agent-authored plan item records how it meant to check this and what it+ // expected to see (prose), plus the evidence media it is required to produce+ // (a closed set the executor's coverage gate enforces).+ const planConfig = (planItem?.verifierConfig ?? {}) as VerifyAgentPlanConfig;+ const requiredEvidence = planConfig.requiredEvidence ?? [];+ const categoryCounts = evidence.reduce(+ (acc, e) => {+ acc[evidenceCategory(e.type)] += 1;+ return acc;+ },+ { file: 0, image: 0, video: 0 } as Record<EvidenceCategory, number>,+ );+ // `required` lives on the result when there is one, on the plan item otherwise+ // — a check that never ran still knows whether it was optional.+ const required = result?.required ?? planItem?.required ?? true;+ const hasBody =+ Boolean(result?.toulmin?.evidence) ||+ Boolean(result?.suggestion) ||+ Boolean(planConfig.method) ||+ Boolean(planConfig.expected) ||+ requiredEvidence.length > 0 ||+ state === 'not_executed' ||+ evidenceCount > 0;+ const selectedEvidenceIndex = selectedEvidenceId+ ? evidence.findIndex((e) => e.id === selectedEvidenceId)+ : -1;+ const selectedEvidence = selectedEvidenceIndex >= 0 ? evidence[selectedEvidenceIndex] : null;+ const comparisonGroups = new Map<+ string,+ Partial<Record<'after' | 'before', VerifyEvidenceWithUrl>>+ >();+ for (const item of evidence) {+ const comparison = evidenceComparison(item);+ if (!comparison) continue;+ const group = comparisonGroups.get(comparison.id) ?? {};+ group[comparison.role] = item;+ comparisonGroups.set(comparison.id, group);+ }+ const pairedEvidenceIds = new Set(+ [...comparisonGroups.values()]+ .filter((group) => group.before && group.after)+ .flatMap((group) => [group.before!.id, group.after!.id]),+ );- return (- <div className={styles.row}>- <button- className={styles.rowHead}- type={'button'}- onClick={() => hasBody && setOpen((o) => !o)}- >- <span style={{ color: meta.dot, display: 'flex' }}>- <Icon icon={meta.icon} size={16} />- </span>- <span className={styles.rowTitle} data-failed={verdict === 'failed'}>- {result.checkItemTitle || result.checkItemId}- </span>- <span className={styles.rowSide}>- {CATEGORY_ORDER.map((cat) =>- categoryCounts[cat] > 0 ? (- <span- className={styles.evChip}- key={cat}- title={`${t(`report.evidence.category.${cat}`)} × ${categoryCounts[cat]}`}- >- <Icon icon={CATEGORY_ICON[cat]} size={12} />- {categoryCounts[cat]}- </span>- ) : null,- )}- {!result.required && (- <span className={styles.softTag}>{t('report.check.optional')}</span>- )}- {hasBody && (- <Icon className={styles.chev} data-open={open} icon={ChevronRight} size={14} />- )}- </span>- </button>- {open && hasBody && (- <div className={styles.rowBody}>- {result.toulmin?.evidence && (- <p className={styles.reasoning}>{result.toulmin.evidence}</p>- )}- {result.suggestion && <p className={styles.suggestion}>{result.suggestion}</p>}- {evidenceCount > 0 && (- <>- <div className={styles.evidenceList}>- {[...comparisonGroups.entries()].map(([id, group]) =>- group.before && group.after ? (- <EvidenceComparisonView after={group.after} before={group.before} key={id} />- ) : null,- )}- {result.evidence.map((e, index) =>- pairedEvidenceIds.has(e.id) ? null : isInlineEvidence(e) ? (- <EvidenceItem evidence={e} index={index + 1} key={e.id} />- ) : (- <EvidenceFileButton- evidence={e}- index={index + 1}- key={e.id}- onClick={() => setSelectedEvidenceId(e.id)}- />- ),- )}- </div>- {selectedEvidence && (- <EvidenceDrawer- evidence={[selectedEvidence]}- open={Boolean(selectedEvidence)}- title={evidenceDisplayName(selectedEvidence, t, selectedEvidenceIndex + 1)}- onClose={() => setSelectedEvidenceId(null)}- />+ return (+ <div className={styles.row}>+ <button+ className={styles.rowHead}+ type={'button'}+ onClick={() => hasBody && setOpen((o) => !o)}+ >+ <span style={{ color: meta.dot, display: 'flex' }}>+ <Icon icon={meta.icon} size={16} />+ </span>+ <span className={styles.rowTitle} data-failed={state === 'failed'}>+ {result?.checkItemTitle || planItem?.title || row.id}+ </span>+ <span className={styles.rowSide}>+ {CATEGORY_ORDER.map((cat) =>+ categoryCounts[cat] > 0 ? (+ <span+ className={styles.evChip}+ key={cat}+ title={`${t(`report.evidence.category.${cat}`)} × ${categoryCounts[cat]}`}+ >+ <Icon icon={CATEGORY_ICON[cat]} size={12} />+ {categoryCounts[cat]}+ </span>+ ) : null,+ )}+ {state === 'not_executed' && (+ <span className={styles.softTag}>{t('report.verdict.notExecuted')}</span>+ )}+ {!required && <span className={styles.softTag}>{t('report.check.optional')}</span>}+ {hasBody && (+ <Icon className={styles.chev} data-open={open} icon={ChevronRight} size={14} />+ )}+ </span>+ </button>+ {open && hasBody && (+ <div className={styles.rowBody}>+ {(planConfig.method || planConfig.expected || requiredEvidence.length > 0) && (+ <div className={styles.planDetail}>+ {planConfig.method && (+ <>+ <span className={styles.planDetailLabel}>{t('report.plan.method')}</span>+ <span>{planConfig.method}</span>+ </>+ )}+ {planConfig.expected && (+ <>+ <span className={styles.planDetailLabel}>{t('report.plan.expected')}</span>+ <span>{planConfig.expected}</span>+ </>+ )}+ {/* The media this item is *required* to produce. Not decoration: a+ missing one fails the item through the executor's coverage gate,+ so a reader can see what the check was contractually owed. */}+ {requiredEvidence.length > 0 && (+ <>+ <span className={styles.planDetailLabel}>+ {t('report.plan.requiredEvidence')}+ </span>+ <span className={styles.surfaceList}>+ {requiredEvidence.map((spec) => (+ <span className={styles.surfaceChip} key={spec.type} title={spec.hint}>+ <Icon icon={CATEGORY_ICON[evidenceCategory(spec.type)]} size={12} />+ {t(`report.evidence.medium.${spec.type}`)}+ </span>+ ))}+ </span>+ </>+ )}+ </div>+ )}+ {state === 'not_executed' && (+ <p className={styles.notExecutedHint}>{t('report.plan.notExecutedHint')}</p>+ )}+ {result?.toulmin?.evidence && (+ <p className={styles.reasoning}>{result.toulmin.evidence}</p>+ )}+ {result?.suggestion && <p className={styles.suggestion}>{result.suggestion}</p>}+ {evidenceCount > 0 && (+ <>+ <div className={styles.evidenceList}>+ {[...comparisonGroups.entries()].map(([id, group]) =>+ group.before && group.after ? (+ <EvidenceComparisonView after={group.after} before={group.before} key={id} />+ ) : null,)}- </>- )}- </div>- )}- </div>- );- },-);+ {evidence.map((e, index) =>+ pairedEvidenceIds.has(e.id) ? null : isInlineEvidence(e) ? (+ <EvidenceItem evidence={e} index={index + 1} key={e.id} />+ ) : (+ <EvidenceFileButton+ evidence={e}+ index={index + 1}+ key={e.id}+ onClick={() => setSelectedEvidenceId(e.id)}+ />+ ),+ )}+ </div>+ {selectedEvidence && (+ <EvidenceDrawer+ evidence={[selectedEvidence]}+ open={Boolean(selectedEvidence)}+ title={evidenceDisplayName(selectedEvidence, t, selectedEvidenceIndex + 1)}+ onClose={() => setSelectedEvidenceId(null)}+ />+ )}+ </>+ )}+ </div>+ )}+ </div>+ );+});CheckRow.displayName = 'CheckRow';@@ -1570,23 +1683,34 @@ const pullRequestLabel = (});};-const CodingScopeCard = memo<{ context: VerifyCodingScope | null | undefined }>(({ context }) => {+/**+ * One line of provenance: the PR, the code, when, and where it ran. Reference+ * material — the reader scans it to place the report, then moves on — so it+ * stays subordinate to the verdict and the summary above it, and never grows+ * into a stack of labelled rows.+ */+const CodingScopeCard = memo<{+ context: VerifyCodingScope | null | undefined;+ origin?: VerifyRunOrigin;+}>(({ context, origin }) => {const { t } = useTranslation('verify');if (!context) return null;- const { branch, commit, entry, focus, pullRequest, surfaces, testedAt } = context;+ const { branch, commit, entry, pullRequest, testedAt } = context;const hasPullRequest = Boolean(pullRequest && (pullRequest.number !== undefined || pullRequest.title || pullRequest.url),);const date = formatScopeDate(testedAt);+ const surfaces = renderableSurfaces(context.surfaces);+ const originTopicId = origin?.topicId;const hasScope =Boolean(branch) ||Boolean(commit) ||Boolean(entry) ||- Boolean(focus) ||hasPullRequest ||- Boolean(surfaces?.length) ||- Boolean(date);+ surfaces.length > 0 ||+ Boolean(date) ||+ Boolean(originTopicId);if (!hasScope) return null;@@ -1604,75 +1728,77 @@ const CodingScopeCard = memo<{ context: VerifyCodingScope | null | undefined }>(return (<div className={styles.codingScope}>- {(hasPullRequest || branch || commit || date) && (- <div className={styles.codingScopeMain}>- {pullRequestContent &&- (pullRequestUrl ? (- <a- className={styles.prChip}- data-link={true}- href={pullRequestUrl}- rel="noreferrer"- target="_blank"- title={pullRequest?.title ?? pullRequestUrl}- >- {pullRequestContent}- </a>- ) : (- <span className={styles.prChip} title={pullRequest?.title}>- {pullRequestContent}- </span>- ))}- {branch && (- <span className={styles.branchChip} title={branch}>- <Icon icon={GitBranch} size={15} />- <code>{branch}</code>- </span>- )}- {commit && (- <span className={styles.commitChip} title={commit}>- <Icon icon={GitCommit} size={14} />- <code>{shortCommit}</code>- </span>- )}- {date && (- <span className={styles.scopeMetaItem}>- <Icon icon={CalendarClock} size={13} />- <span>{date}</span>+ {pullRequestContent && (+ <div className={styles.scopePullRequestLine}>+ {pullRequestUrl ? (+ <a+ className={styles.prChip}+ data-link={true}+ href={pullRequestUrl}+ rel="noreferrer"+ target="_blank"+ title={pullRequest?.title ?? pullRequestUrl}+ >+ {pullRequestContent}+ </a>+ ) : (+ <span className={styles.prChip} title={pullRequest?.title}>+ {pullRequestContent}</span>)}</div>)}- {(surfaces?.length || entry) && (- <div className={styles.scopeMetaRow}>- {surfaces && surfaces.length > 0 && (- <span className={styles.scopeMetaItem}>- <Icon icon={Layers} size={13} />- <span className={styles.surfaceList}>- {surfaces.map((surface) => (- <span className={styles.surfaceChip} key={surface}>- {surface}- </span>- ))}+ <div className={styles.scopeMetaLine}>+ {branch && (+ <span className={styles.branchChip} title={branch}>+ <Icon icon={GitBranch} size={15} />+ <code>{branch}</code>+ </span>+ )}+ {commit && (+ <span className={styles.commitChip} title={commit}>+ <Icon icon={GitCommit} size={14} />+ <code>{shortCommit}</code>+ </span>+ )}+ {date && (+ <span className={styles.scopeMetaItem}>+ <Icon icon={CalendarClock} size={13} />+ <span>{date}</span>+ </span>+ )}+ {surfaces.length > 0 && (+ <span className={styles.surfaceList}>+ {surfaces.map((surface) => (+ <span className={styles.surfaceChip} key={surface}>+ <Icon icon={SURFACE_ICON[surface]} size={12} />+ {t(`report.surface.${surface}`)}</span>- </span>- )}- {entry && (- <span className={styles.scopeMetaItem} title={entry}>- <Icon icon={Terminal} size={13} />- <code>{entry}</code>- </span>- )}- </div>- )}-- {focus && (- <div className={styles.scopeFocus}>- <Icon icon={Target} size={13} />- <span>{focus}</span>- </div>- )}+ ))}+ </span>+ )}+ {entry && (+ <span className={cx(styles.scopeMetaItem, styles.scopeEntry)} title={entry}>+ <Icon icon={Terminal} size={13} />+ <code>{entry}</code>+ </span>+ )}+ {/* Only ever rendered for the report's author — the server redacts `origin`+ from a bundle fetched by anyone else holding the shared link. */}+ {originTopicId && (+ <a+ className={cx(styles.scopeMetaItem, styles.originLink)}+ href={`/chat?topic=${originTopicId}`}+ rel="noreferrer"+ target="_blank"+ title={t('report.scope.origin')}+ >+ <Icon icon={MessagesSquare} size={13} />+ <Icon icon={ExternalLink} size={11} />+ </a>+ )}+ </div></div>);});@@ -1705,9 +1831,7 @@ const ReportViewer = memo<ReportViewerProps>(({ runId: explicitRunId }) => {const ordered = useMemo(() => {if (!data) return [];- return [...data.results].sort(- (a, b) => SEVERITY_RANK[checkVerdict(a)] - SEVERITY_RANK[checkVerdict(b)],- );+ return buildCheckRows((data.run.plan as VerifyCheckItem[] | null) ?? null, data.results);}, [data]);if (!verifyRunId) {@@ -1751,20 +1875,28 @@ const ReportViewer = memo<ReportViewerProps>(({ runId: explicitRunId }) => {: null;const counts = ordered.reduce(- (acc, r) => {- acc[checkVerdict(r)] += 1;+ (acc, row) => {+ acc[row.state] += 1;return acc;},- { failed: 0, passed: 0, uncertain: 0 } as Record<Verdict, number>,+ { failed: 0, not_executed: 0, passed: 0, uncertain: 0 } as Record<CheckState, number>,);- const total = report?.totalChecks ?? ordered.length;- const passed = report?.passedChecks ?? counts.passed;- const failed = report?.failedChecks ?? counts.failed;- const uncertain = report?.uncertainChecks ?? counts.uncertain;- const verdict = (report?.verdict as Verdict | null) ?? null;- const visible = filter === 'all' ? ordered : ordered.filter((r) => checkVerdict(r) === filter);+ // A chip's count is a promise about the rows behind it, so whenever there are+ // rows they are the truth — the report's own stats count the cases it ingested+ // and know nothing about a planned check that never produced one. Only an+ // empty list falls back to them (a report can exist before any result does).+ const hasRows = ordered.length > 0;+ const total = hasRows ? ordered.length : (report?.totalChecks ?? 0);+ const passed = hasRows ? counts.passed : (report?.passedChecks ?? 0);+ const failed = hasRows ? counts.failed : (report?.failedChecks ?? 0);+ const uncertain = hasRows ? counts.uncertain : (report?.uncertainChecks ?? 0);+ const verdict = (report?.verdict as VerifyVerdict | null) ?? null;+ const visible = filter === 'all' ? ordered : ordered.filter((row) => row.state === filter);const isCodingReport = run.scenario === 'coding';const interactionCost = readInteractionCost(run.metadata);+ // The server strips `origin` for anyone but the author; `isOwner` keeps the+ // affordance off the page for a visitor even if that ever regressed.+ const origin = data.isOwner ? run.metadata?.origin : undefined;const chips: { count: number; dot?: string; key: Filter; label: string }[] = [{ count: total, key: 'all', label: t('report.filter.all') },@@ -1775,6 +1907,18 @@ const ReportViewer = memo<ReportViewerProps>(({ runId: explicitRunId }) => {key: 'uncertain',label: t('report.filter.uncertain'),},+ // Only a report with a stored plan can have these, so the chip appears only+ // when there is something to filter to.+ ...(counts.not_executed > 0+ ? [+ {+ count: counts.not_executed,+ dot: cssVar.colorTextQuaternary,+ key: 'not_executed' as const,+ label: t('report.filter.notExecuted'),+ },+ ]+ : []),{ count: passed, dot: cssVar.colorSuccess, key: 'passed', label: t('report.filter.passed') },];@@ -1804,7 +1948,7 @@ const ReportViewer = memo<ReportViewerProps>(({ runId: explicitRunId }) => {{!isCodingReport && run.goal && <Text className={styles.summary}>{run.goal}</Text>}{report?.summary && <Text className={styles.summary}>{report.summary}</Text>}- {isCodingReport && <CodingScopeCard context={run.context} />}+ {isCodingReport && <CodingScopeCard context={run.context} origin={origin} />}{liveStatus && (<div className={styles.liveBanner}>@@ -1836,12 +1980,14 @@ const ReportViewer = memo<ReportViewerProps>(({ runId: explicitRunId }) => {{visible.length > 0 ? (<div className={styles.checks}>- {visible.map((r) => (+ {visible.map((row) => (<CheckRow- key={r.id}- result={r}+ key={row.id}+ row={row}defaultOpen={- checkVerdict(r) === 'failed' || r.evidence.some(isInlineVisualEvidence)+ row.state === 'failed' ||+ row.state === 'not_executed' ||+ (row.result?.evidence ?? []).some(isInlineVisualEvidence)}/>))}diff --git a/src/features/Verify/utils.test.ts b/src/features/Verify/utils.test.tsindex 02b7a2c1404..27d8025c11e 100644--- a/src/features/Verify/utils.test.ts+++ b/src/features/Verify/utils.test.ts@@ -1,6 +1,38 @@+import type { VerifyCheckItem } from '@lobechat/types';import { describe, expect, it } from 'vitest';-import { countResults, isDraftUnconfirmed, itemBehavior, phaseFromStatus } from './utils';+import type { VerifyResultWithEvidence } from '@/services/verify';++import {+ buildCheckRows,+ countResults,+ isDraftUnconfirmed,+ itemBehavior,+ phaseFromStatus,+ renderableSurfaces,+} from './utils';++const planItem = (id: string, overrides: Partial<VerifyCheckItem> = {}): VerifyCheckItem => ({+ id,+ index: 0,+ onFail: 'manual',+ required: true,+ title: `plan ${id}`,+ verifierConfig: {},+ verifierType: 'agent',+ ...overrides,+});++const result = (+ checkItemId: string,+ verdict: 'passed' | 'failed' | 'uncertain',+): VerifyResultWithEvidence =>+ ({+ checkItemId,+ evidence: [],+ id: `result-${checkItemId}`,+ verdict,+ }) as unknown as VerifyResultWithEvidence;describe('phaseFromStatus', () => {it('maps rollup statuses to dock phases', () => {@@ -44,3 +76,69 @@ describe('countResults', () => {).toEqual({ failed: 1, passed: 1, total: 3 });});});++describe('buildCheckRows', () => {+ it('keeps a planned check that never produced a result', () => {+ const rows = buildCheckRows(+ [planItem('a'), planItem('b'), planItem('c')],+ [result('a', 'passed'), result('c', 'passed')],+ );++ // The whole reason the plan is stored: `b` was promised and silently never+ // ran. Without the plan it would simply be absent, and a reader would see+ // "2/2 passed" with no way to know a third of the coverage vanished.+ const notExecuted = rows.filter((row) => row.state === 'not_executed');+ expect(notExecuted.map((row) => row.id)).toEqual(['b']);+ expect(rows).toHaveLength(3);+ });++ it('sorts unresolved first: failed → uncertain → never ran → passed', () => {+ const rows = buildCheckRows(+ [planItem('pass'), planItem('skip'), planItem('fail'), planItem('unsure')],+ [result('pass', 'passed'), result('fail', 'failed'), result('unsure', 'uncertain')],+ );++ expect(rows.map((row) => row.id)).toEqual(['fail', 'unsure', 'skip', 'pass']);+ });++ it('appends a result the plan never named rather than dropping it', () => {+ const rows = buildCheckRows(+ [planItem('planned')],+ [result('planned', 'passed'), result('discovered', 'failed')],+ );++ const discovered = rows.find((row) => row.id === 'discovered');+ expect(discovered?.state).toBe('failed');+ expect(discovered?.planItem).toBeUndefined();+ });++ it('degrades to results-only when the run has no plan', () => {+ const rows = buildCheckRows(null, [result('a', 'passed'), result('b', 'failed')]);++ expect(rows.map((row) => row.id)).toEqual(['b', 'a']);+ expect(rows.every((row) => row.state !== 'not_executed')).toBe(true);+ });+});++describe('renderableSurfaces', () => {+ it('resolves known aliases and drops values that name no surface', () => {+ expect(+ renderableSurfaces([+ 'electron',+ 'cli',+ // The long tail history left behind: prose, runtime modes, test kinds.+ 'Electron 打包版(app.isPackaged=true)',+ 'unit',+ ] as any),+ ).toEqual(['desktop', 'cli']);+ });++ it('dedupes surfaces that collapse onto the same canonical value', () => {+ expect(renderableSurfaces(['electron', 'desktop'] as any)).toEqual(['desktop']);+ });++ it('returns nothing for an empty or missing list', () => {+ expect(renderableSurfaces([])).toEqual([]);+ expect(renderableSurfaces(undefined)).toEqual([]);+ });+});diff --git a/src/features/Verify/utils.ts b/src/features/Verify/utils.tsindex fdc825ee75c..13576594de9 100644--- a/src/features/Verify/utils.ts+++ b/src/features/Verify/utils.ts@@ -1,7 +1,9 @@-import type { VerifyCheckItem } from '@lobechat/types';+import type { VerifyCheckItem, VerifyCodingScope, VerifySurface } from '@lobechat/types';+import { normalizeVerifySurface } from '@lobechat/types';import type { VerifyStatus } from '@/database/models/agentOperation';import type { VerifyCheckResultItem } from '@/database/schemas/verify';+import type { VerifyResultWithEvidence } from '@/services/verify';export type DockPhase =| 'idle'@@ -52,6 +54,97 @@ export const isDraftUnconfirmed = (export const itemBehavior = (item: Pick<VerifyCheckItem, 'required'>): 'gate' | 'auto_improve' =>item.required ? 'gate' : 'auto_improve';+type Verdict = 'passed' | 'failed' | 'uncertain';++/**+ * What a row of the report's check list can be. `not_executed` is not a verdict+ * the verifier can reach — it's a planned item that produced no result at all,+ * which only became visible once the plan started being stored next to the+ * results. Rendering it is the point: a check that quietly never ran is+ * otherwise indistinguishable from one that was never planned.+ */+export type CheckState = Verdict | 'not_executed';++/**+ * Unresolved-first sort: failed → uncertain → never ran → passed. A planned+ * check that never ran is a hole in the verification, not a mild pass — it+ * belongs with the things still owed the reader, above everything settled.+ */+export const SEVERITY_RANK: Record<CheckState, number> = {+ failed: 0,+ not_executed: 2,+ passed: 3,+ uncertain: 1,+};++export const checkVerdict = (result: VerifyResultWithEvidence): Verdict => {+ const v = result.verdict ?? result.status;+ if (v === 'passed' || v === 'failed' || v === 'uncertain') return v;+ return 'uncertain';+};++/** One row of the report's check list: a planned check, its result, or both. */+export interface CheckRowData {+ /** `checkItemId` — the key the plan and the results agree on. */+ id: string;+ planItem?: VerifyCheckItem;+ result?: VerifyResultWithEvidence;+ state: CheckState;+}++/**+ * The check list, built from the plan and the results together.+ *+ * The plan is the skeleton when there is one: every item it named gets a row,+ * even the ones that produced no result, so a check that was promised and then+ * quietly skipped stays visible instead of disappearing from the report. Cases+ * the run produced without ever planning them are appended — a run may+ * legitimately discover a check midway, and dropping it would hide real+ * findings. With no plan (every report ingested before plans were stored), this+ * degrades to exactly the old behavior: the results, severity-first.+ */+export const buildCheckRows = (+ plan: VerifyCheckItem[] | null,+ results: VerifyResultWithEvidence[],+): CheckRowData[] => {+ const resultsByCheckItem = new Map(results.map((result) => [result.checkItemId, result]));++ const planned: CheckRowData[] = (plan ?? []).map((planItem) => {+ const result = resultsByCheckItem.get(planItem.id);+ return {+ id: planItem.id,+ planItem,+ result,+ state: result ? checkVerdict(result) : ('not_executed' as const),+ };+ });++ const plannedIds = new Set(planned.map((row) => row.id));+ const unplanned: CheckRowData[] = results+ .filter((result) => !plannedIds.has(result.checkItemId))+ .map((result) => ({ id: result.checkItemId, result, state: checkVerdict(result) }));++ return [...planned, ...unplanned].sort((a, b) => SEVERITY_RANK[a.state] - SEVERITY_RANK[b.state]);+};++/**+ * Surfaces worth rendering, as canonical values. History holds 76 distinct+ * free-form strings — prose, runtime modes, tool and test-kind names — none of+ * which read as a badge. Anything that doesn't name a real surface is dropped+ * rather than shown as a mystery chip; known spellings (`electron`) still+ * resolve.+ */+export const renderableSurfaces = (surfaces: VerifyCodingScope['surfaces']): VerifySurface[] => {+ if (!surfaces?.length) return [];++ const seen: VerifySurface[] = [];+ for (const value of surfaces) {+ const surface = normalizeVerifySurface(value);+ if (surface && !seen.includes(surface)) seen.push(surface);+ }+ return seen;+};+export interface CheckCounts {failed: number;passed: number;diff --git a/src/services/verify.ts b/src/services/verify.tsindex 9ff0e7000ad..b758c575940 100644--- a/src/services/verify.ts+++ b/src/services/verify.ts@@ -80,6 +80,12 @@ export type VerifyResultWithEvidence = VerifyCheckResultItem & {/** Everything the standalone report viewer needs for one verification session. */export interface VerifyReportBundle {+ /**+ * Whether the viewer authored this run. Report URLs are public, so+ * author-only affordances (the origin conversation) gate on this — the server+ * redacts `run.metadata.origin` for everyone else.+ */+ isOwner: boolean;report: VerifyReport | null;results: VerifyResultWithEvidence[];run: VerifyRunItem;diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex 3e802b3aa75..66ed24a0ec1 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -72,6 +72,7 @@ import type { RunScope } from '../../lifecycle/types';import { createGatewayEventHandler, isCompletedRuntimeEnd } from '../gateway/gatewayEventHandler';import { createMessageWriteBatcher, type ToolMessageUpdateOperation } from './messageWriteBatcher';import { createPendingCreateLedger } from './pendingCreateLedger';+import { buildLobeHubSessionEnv } from './sessionEnv';/** Mirrors `idGenerator('threads', 16)` on the server so sync-allocated ids have the same shape. */const generateThreadId = () => `thd_${createNanoId(16)()}`;@@ -1676,7 +1677,19 @@ export const executeHeterogeneousAgent = async (args: buildHeteroSpawnArgs(heterogeneousProvider),command: heterogeneousProvider.command || (adapterType === 'codex' ? 'codex' : 'claude'),cwd: workingDirectory,- env: heterogeneousProvider.env,+ env: {+ // Tell the CLI which LobeHub conversation it is running inside. The child+ // (and every subprocess it spawns, e.g. `lh`) inherits these, so a tool+ // running under the agent can attribute its output back to this topic+ // without the agent having to pass ids it can't see. User-configured env+ // wins — this is provenance, never an override the user can't escape.+ ...buildLobeHubSessionEnv({+ agentId: context.agentId,+ operationId,+ topicId: context.topicId,+ }),+ ...heterogeneousProvider.env,+ },resumeSessionId,useClaudeCodeSdk: labPreferSelectors.enableClaudeCodeSdk(useUserStore.getState()),});diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/sessionEnv.test.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/sessionEnv.test.tsnew file mode 100644index 00000000000..035d72eea7d--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/sessionEnv.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it } from 'vitest';++import { buildLobeHubSessionEnv } from './sessionEnv';++describe('buildLobeHubSessionEnv', () => {+ it('echoes the conversation ids the child process can attribute its output to', () => {+ expect(+ buildLobeHubSessionEnv({ agentId: 'agt_1', operationId: 'op_1', topicId: 'tpc_1' }),+ ).toEqual({+ LOBEHUB_AGENT_ID: 'agt_1',+ LOBEHUB_OPERATION_ID: 'op_1',+ LOBEHUB_TOPIC_ID: 'tpc_1',+ });+ });++ it('omits an id that did not resolve rather than exporting an empty var', () => {+ // A var set to '' or 'undefined' reads as present to every consumer down the+ // chain — `lh` would stamp a report with a topic id that resolves to nothing.+ expect(+ buildLobeHubSessionEnv({ agentId: 'agt_1', operationId: null, topicId: undefined }),+ ).toEqual({ LOBEHUB_AGENT_ID: 'agt_1' });+ });++ it('is empty when the run carries no conversation at all', () => {+ expect(buildLobeHubSessionEnv({})).toEqual({});+ });+});diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/sessionEnv.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/sessionEnv.tsnew file mode 100644index 00000000000..3ad337b6958--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/sessionEnv.ts@@ -0,0 +1,34 @@+/**+ * Provenance env for a heterogeneous agent's child process.+ *+ * An external CLI agent (Claude Code / Codex) runs blind to the LobeHub session+ * it was launched from: it has no way to name the topic it lives in, so anything+ * it publishes — a verification report, an artifact, a trace — lands detached+ * from the conversation that asked for it. Echoing the ids into the child env+ * closes that loop for free: the CLI inherits them, so does every subprocess it+ * spawns (`lh`, a script, a test harness), and each one can attribute its output+ * back to this topic without the agent having to pass ids it cannot see.+ *+ * Read by `lh verify ingest-report`, which stamps them onto the report's+ * `metadata.origin`.+ */+export interface LobeHubSessionEnvIds {+ agentId?: string | null;+ operationId?: string | null;+ topicId?: string | null;+}++/** Only the ids that actually resolved — never an env var set to "undefined". */+export const buildLobeHubSessionEnv = ({+ agentId,+ operationId,+ topicId,+}: LobeHubSessionEnvIds): Record<string, string> => {+ const env: Record<string, string> = {};++ if (agentId) env.LOBEHUB_AGENT_ID = agentId;+ if (operationId) env.LOBEHUB_OPERATION_ID = operationId;+ if (topicId) env.LOBEHUB_TOPIC_ID = topicId;++ return env;+};