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(verify): subject-level acceptance aggregate with cross-round check union (#17229)

Arvin Xuf8ff7ff8bad2
diff --git a/.agents/skills/agent-testing/SKILL.md b/.agents/skills/agent-testing/SKILL.md
index 7ec916958a1..fb1be32959a 100644
--- a/.agents/skills/agent-testing/SKILL.md
+++ b/.agents/skills/agent-testing/SKILL.md
@@ -635,6 +635,26 @@ inline screenshot/text evidence). On production that resolves to
`https://app.lobehub.com/verify/<verifyRunId>`. **Include that full production
link in the final chat reply** alongside the local report dir.
+#### Chaining rounds onto a subject's acceptance (optional)
+
+When the verification belongs to a business subject — a task, a topic, or a
+document — chain the session onto that subject's **acceptance aggregate** so
+every round lands on ONE decision page instead of scattered report entries:
+
+```bash
+# SUBJECT is task:$TASK_ID, topic:$TOPIC_ID, or document:$DOC_ID
+env -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME \
+ lh verify ingest-report "$DIR" --source agent-testing --subject "$SUBJECT" --open --json
+```
+
+`--subject` accepts `task:<id> | topic:<id> | document:<id>` (or put
+`"subject": "task:<id>"` / `{ "type", "id", "requirement" }` in `result.json`).
+The first ingest creates the acceptance; each **new session** (`--new` or a fresh
+`$DIR`) becomes the next round; re-ingesting a remembered dir updates its round
+in place. The user closes the loop on `/acceptance/<acceptanceId>` (also
+printed by `--open`) — accept / reject with a comment; inspect or decide from the
+terminal via `lh verify acceptance view|accept|reject <id | type:id>`.
+
#### Re-verifying the same case updates the report in place (don't spawn a new one)
When you iterate on one change — fix → re-verify → fix again — **keep reusing the
diff --git a/.agents/skills/agent-testing/references/report.md b/.agents/skills/agent-testing/references/report.md
index 39ddd0d7f03..74c380403b9 100644
--- a/.agents/skills/agent-testing/references/report.md
+++ b/.agents/skills/agent-testing/references/report.md
@@ -297,6 +297,12 @@ would silently gate on nothing, which is worse than no gate at all.
stay **free prose** — they carry intent no enum can, and both render under the
check on the page next to the outcome.
+A plan item may also carry a per-item `surface` (same closed set as the run-level
+`surfaces` below; `electron` normalizes to `desktop`). It says which product
+surface THIS check ran on — the acceptance union view groups checks by it, so a
+mixed web+cli round stays legible. An unknown value is warned about and dropped,
+never stored.
+
`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:
@@ -318,6 +324,12 @@ that isn't the branch's own.
polish, copy quality); omit it for purely binary runs. `verdict` is the single
word the user reads first: `pass`, `fail`, or `partial`.
+`subject` is optional and chains the session onto a business subject's
+**acceptance aggregate** (one decision page across repair rounds): either
+`"subject": "task:<id>"` (`task` | `topic` | `document`) or
+`{ "type": "task", "id": "task_…", "requirement": "one-sentence acceptance bar" }`.
+The `--subject` flag on `ingest-report` overrides this field.
+
`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
diff --git a/apps/cli/package.json b/apps/cli/package.json
index f7db4d7fedc..499f1db4798 100644
--- a/apps/cli/package.json
+++ b/apps/cli/package.json
@@ -58,5 +58,11 @@
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org"
+ },
+ "pnpm": {
+ "overrides": {
+ "@types/react": "19.2.13",
+ "antd": "6.3.5"
+ }
}
}
diff --git a/apps/cli/src/commands/verify.test.ts b/apps/cli/src/commands/verify.test.ts
index 9f03a29f594..1c1cdee4873 100644
--- a/apps/cli/src/commands/verify.test.ts
+++ b/apps/cli/src/commands/verify.test.ts
@@ -1,4 +1,4 @@
-import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
@@ -7,9 +7,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
originFromEnv,
+ parseSubjectRef,
planFromResult,
registerVerifyCommand,
reportEvidence,
+ subjectFromResult,
surfacesFromResult,
} from './verify';
@@ -411,6 +413,20 @@ describe('planFromResult — plan item normalization', () => {
expect(item.verifierConfig).toEqual({ expected: 'the file exists', method: 'tail the log' });
});
+ it('normalizes a per-item surface and drops one that names no surface', () => {
+ const items = planFromResult({
+ plan: [
+ { id: '1', surface: 'electron', title: 'tray dedupe' },
+ { id: '2', surface: 'unit', title: 'model test' },
+ { id: '3', title: 'no surface' },
+ ],
+ })!;
+
+ expect(items[0].verifierConfig).toEqual({ surface: 'desktop' });
+ expect(items[1].verifierConfig).toEqual({});
+ expect(items[2].verifierConfig).toEqual({});
+ });
+
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' }] })!;
@@ -433,6 +449,115 @@ describe('planFromResult — plan item normalization', () => {
});
});
+describe('verify ingest-report — decided rounds are immutable', () => {
+ let consoleSpy: ReturnType<typeof vi.spyOn>;
+ let dir: string;
+
+ beforeEach(() => {
+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ mockGetTrpcClient.mockResolvedValue(mockTrpcClient);
+ const verify = mockTrpcClient.verify as Record<string, any>;
+ verify.getRun = { query: vi.fn() };
+ verify.createRun = { mutate: vi.fn().mockResolvedValue({ id: 'run-new' }) };
+ verify.updateRun = { mutate: vi.fn() };
+ verify.upsertReport = { mutate: vi.fn().mockResolvedValue({}) };
+
+ dir = mkdtempSync(path.join(tmpdir(), 'lh-ingest-'));
+ writeFileSync(path.join(dir, 'result.json'), JSON.stringify({ cases: [] }));
+ // The sidecar remembers the previous round's session.
+ writeFileSync(path.join(dir, '.verify-run.json'), JSON.stringify({ verifyRunId: 'run-old' }));
+ });
+
+ afterEach(() => {
+ consoleSpy.mockRestore();
+ rmSync(dir, { force: true, recursive: true });
+ });
+
+ const run = async (args: string[]) => {
+ const program = new Command();
+ program.exitOverride();
+ registerVerifyCommand(program);
+ await program.parseAsync(['node', 'lh', 'verify', ...args]);
+ };
+
+ it('starts a fresh round instead of updating a decided session in place', async () => {
+ const verify = mockTrpcClient.verify as Record<string, any>;
+ verify.getRun.query.mockResolvedValue({
+ id: 'run-old',
+ metadata: null,
+ userDecision: 'reject',
+ });
+
+ await run(['ingest-report', dir, '--json']);
+
+ // The rejected round is history: no in-place update, a new session instead.
+ expect(verify.updateRun.mutate).not.toHaveBeenCalled();
+ expect(verify.createRun.mutate).toHaveBeenCalled();
+ });
+
+ it('still updates an undecided remembered session in place', async () => {
+ const verify = mockTrpcClient.verify as Record<string, any>;
+ verify.getRun.query.mockResolvedValue({ id: 'run-old', metadata: null, userDecision: null });
+ verify.listResultsByRun = { query: vi.fn().mockResolvedValue([]) };
+
+ await run(['ingest-report', dir, '--json']);
+
+ expect(verify.updateRun.mutate).toHaveBeenCalled();
+ expect(verify.createRun.mutate).not.toHaveBeenCalled();
+ });
+});
+
+describe('parseSubjectRef / subjectFromResult — acceptance subject', () => {
+ it('parses the closed set of type:id references', () => {
+ expect(parseSubjectRef('task:task_123')).toEqual({
+ subjectId: 'task_123',
+ subjectType: 'task',
+ });
+ expect(parseSubjectRef('topic:tpc_abc')).toEqual({
+ subjectId: 'tpc_abc',
+ subjectType: 'topic',
+ });
+ expect(parseSubjectRef('document:doc_1')).toEqual({
+ subjectId: 'doc_1',
+ subjectType: 'document',
+ });
+ });
+
+ it('rejects unknown types and malformed references', () => {
+ expect(parseSubjectRef('release:rel_1')).toBeNull();
+ expect(parseSubjectRef('task:')).toBeNull();
+ expect(parseSubjectRef('task_123')).toBeNull();
+ expect(parseSubjectRef(undefined)).toBeNull();
+ });
+
+ it('keeps an id containing colons intact (splits on the FIRST colon only)', () => {
+ expect(parseSubjectRef('topic:tpc:odd:id')).toEqual({
+ subjectId: 'tpc:odd:id',
+ subjectType: 'topic',
+ });
+ });
+
+ it('reads result.json subject in both string and object shapes', () => {
+ expect(subjectFromResult({ subject: 'task:task_9' })).toEqual({
+ ref: { subjectId: 'task_9', subjectType: 'task' },
+ });
+ expect(
+ subjectFromResult({
+ subject: { id: 'tpc_1', requirement: 'no regressions', type: 'topic' },
+ }),
+ ).toEqual({
+ ref: { subjectId: 'tpc_1', subjectType: 'topic' },
+ requirement: 'no regressions',
+ });
+ });
+
+ it('returns null on a malformed subject field instead of guessing', () => {
+ expect(subjectFromResult({})).toBeNull();
+ expect(subjectFromResult({ subject: 'nonsense' })).toBeNull();
+ expect(subjectFromResult({ subject: { id: 'x' } })).toBeNull();
+ });
+});
+
describe('originFromEnv — in-app provenance', () => {
const saved = { ...process.env };
diff --git a/apps/cli/src/commands/verify.ts b/apps/cli/src/commands/verify.ts
index b70f0f5d628..f176e1981a1 100644
--- a/apps/cli/src/commands/verify.ts
+++ b/apps/cli/src/commands/verify.ts
@@ -2,8 +2,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/const/verify';
+import type { AcceptanceSubjectType, VerifyRunOrigin, VerifySurface } from '@lobechat/const/verify';
import {
+ acceptanceSubjectTypes,
normalizeVerifySurface,
verifyEvidenceTypes,
verifySurfaces,
@@ -15,6 +16,7 @@ import { getTrpcClient } from '../api/client';
import { confirm, outputJson, printTable, timeAgo, truncate } from '../utils/format';
import { log } from '../utils/logger';
import { uploadLocalFile } from '../utils/uploadLocalFile';
+import { registerAcceptanceCommands } from './verifyAcceptance';
// ── Helpers ────────────────────────────────────────────────
@@ -318,18 +320,39 @@ export function planFromResult(result: Record<string, unknown>) {
})
: [];
+ // Per-item surface: the acceptance union groups checks by it. Normalized to
+ // the closed set (electron → desktop); an unknown value is dropped loudly
+ // rather than stored as a mystery chip.
+ const surfaceRaw = firstString(item.surface);
+ const surface = surfaceRaw ? normalizeVerifySurface(surfaceRaw) : null;
+ if (surfaceRaw && !surface) {
+ log.warn(
+ `plan item "${id}": surface "${surfaceRaw}" names no product surface (expected ${verifySurfaces.join('/')}) — dropping it`,
+ );
+ }
+
+ // The acceptance union groups by category and folds superseded ids into
+ // the new item's iteration timeline — both authored by the harness.
+ const category = firstString(item.category, item.group);
+ const supersedes = Array.isArray(item.supersedes)
+ ? item.supersedes.filter((value: unknown): value is string => typeof value === 'string')
+ : [];
+
return [
{
+ ...(category === undefined ? {} : { category }),
description: firstString(item.description),
id,
index,
onFail: 'manual' as const,
required: typeof item.required === 'boolean' ? item.required : true,
+ ...(supersedes.length > 0 ? { supersedes } : {}),
title,
verifierConfig: {
...(method === undefined ? {} : { method }),
...(expected === undefined ? {} : { expected }),
...(requiredEvidence.length > 0 ? { requiredEvidence } : {}),
+ ...(surface ? { surface } : {}),
},
verifierType,
},
@@ -391,6 +414,47 @@ function metadataForReport(
return metadata;
}
+/** A parsed acceptance subject reference (`task:<id>` / `topic:<id>` / `document:<id>`). */
+export interface AcceptanceSubjectRef {
+ subjectId: string;
+ subjectType: AcceptanceSubjectType;
+}
+
+/**
+ * Parse a `type:id` subject reference. Returns null on anything malformed —
+ * callers decide whether that is an error (an explicit `--subject`) or a
+ * silently absent field (result.json).
+ */
+export function parseSubjectRef(raw: unknown): AcceptanceSubjectRef | null {
+ if (typeof raw !== 'string') return null;
+ const idx = raw.indexOf(':');
+ if (idx <= 0) return null;
+ const type = raw.slice(0, idx).trim().toLowerCase();
+ const id = raw.slice(idx + 1).trim();
+ if (!id || !(acceptanceSubjectTypes as readonly string[]).includes(type)) return null;
+ return { subjectId: id, subjectType: type as AcceptanceSubjectType };
+}
+
+/**
+ * The acceptance subject a report attributes itself to, from result.json's
+ * `subject` field — either `"task:<id>"` or `{ type, id, requirement? }`. An
+ * explicit `--subject` flag wins over this.
+ */
+export function subjectFromResult(result: Record<string, unknown>): {
+ ref: AcceptanceSubjectRef;
+ requirement?: string;
+} | null {
+ const raw = result.subject;
+ if (typeof raw === 'string') {
+ const ref = parseSubjectRef(raw);
+ return ref ? { ref } : null;
+ }
+ const value = objectValue(raw);
+ if (!value) return null;
+ const ref = parseSubjectRef(`${firstString(value.type) ?? ''}:${firstString(value.id) ?? ''}`);
+ return ref ? { ref, requirement: firstString(value.requirement) } : null;
+}
+
/**
* The report dir remembers which verification session it created, so
* re-verifying the same case updates one evolving `/verify/<id>` in place
@@ -426,6 +490,9 @@ export function registerVerifyCommand(program: Command) {
.command('verify')
.description('Manage the Agent Run delivery checker (criteria, rubrics, plans, results)');
+ // `verify acceptance …` — subject-level acceptance aggregates.
+ registerAcceptanceCommands(verify);
+
// ════════════ init (materialize the portable verify skill) ════════════
verify
.command('init')
@@ -1285,6 +1352,14 @@ export function registerVerifyCommand(program: Command) {
.option('--goal <goal>', 'The goal/task being verified')
.option('--run <verifyRunId>', 'Update an existing session in place instead of creating one')
.option('--new', 'Force a fresh session even if this report dir already created one')
+ .option(
+ '--subject <type:id>',
+ "Chain this session onto the subject's acceptance as its next round (task:<id> | topic:<id> | document:<id>)",
+ )
+ .option(
+ '--requirement <text>',
+ 'Acceptance requirement recorded when the aggregate is first created',
+ )
.option('--open', 'Print the in-app URL to open the report')
.option('--json [fields]', 'Output JSON')
.action(
@@ -1296,8 +1371,10 @@ export function registerVerifyCommand(program: Command) {
new?: boolean;
open?: boolean;
operation?: string;
+ requirement?: string;
run?: string;
source?: string;
+ subject?: string;
title?: string;
},
) => {
@@ -1346,6 +1423,26 @@ export function registerVerifyCommand(program: Command) {
// the coding scope header. Overridable via result.json `scenario`.
const scenario = result.scenario === 'coding' ? 'coding' : ('coding' as const);
+ // The acceptance subject this report belongs to: an explicit --subject
+ // wins; otherwise result.json's `subject` field. Malformed explicit input
+ // is a user error; a malformed result field is reported and skipped.
+ let subject = subjectFromResult(result);
+ if (options.subject) {
+ const ref = parseSubjectRef(options.subject);
+ if (!ref) {
+ log.error(
+ `--subject must be one of ${acceptanceSubjectTypes.map((t) => `${t}:<id>`).join(' | ')}`,
+ );
+ process.exit(1);
+ }
+ subject = { ref, requirement: subject?.requirement };
+ } else if (result.subject && !subject) {
+ log.warn(
+ 'result.json `subject` is malformed — ignoring it (expected "type:id" or {type,id})',
+ );
+ }
+ const requirement = options.requirement ?? subject?.requirement;
+
const client = await getTrpcClient();
const goal = options.goal ?? (typeof result.focus === 'string' ? result.focus : undefined);
const title = options.title ?? result.title;
@@ -1365,7 +1462,22 @@ export function registerVerifyCommand(program: Command) {
let reused = false;
if (rememberedRunId) {
const existing = await client.verify.getRun.query({ verifyRunId: rememberedRunId });
- if (existing) {
+ if (existing && existing.userDecision) {
+ // The remembered round has already been judged (e.g. rejected on the
+ // acceptance page). A decided round is immutable history — updating
+ // it in place would leave the aggregate stuck on the old decision.
+ // Fall through to a fresh session, which chains as the NEXT round
+ // and re-opens the acceptance.
+ if (options.run) {
+ log.error(
+ `Session ${options.run} already carries a user decision (${existing.userDecision}) — drop --run so a new round is created`,
+ );
+ process.exit(1);
+ }
+ log.info(
+ `Recorded session was already decided (${existing.userDecision}) — starting a new round`,
+ );
+ } else if (existing) {
reused = true;
runId = existing.id;
const metadata = metadataForReport(result, existing.metadata, origin);
@@ -1401,6 +1513,23 @@ export function registerVerifyCommand(program: Command) {
runId = run.id;
}
+ // 1c. Chain the session onto its subject's acceptance as the next round
+ // BEFORE the report lands, so the report-time status rollup already
+ // sees the aggregate. Idempotent: a reused session keeps its round.
+ let acceptanceId: string | undefined;
+ if (subject) {
+ const acceptance = await client.acceptance.ensure.mutate({
+ requirement,
+ subjectId: subject.ref.subjectId,
+ subjectType: subject.ref.subjectType,
+ });
+ acceptanceId = acceptance.id;
+ await client.acceptance.attachRun.mutate({
+ acceptanceId: acceptance.id,
+ verifyRunId: runId,
+ });
+ }
+
// 2. Ingest each case as a check result + its evidence. `checkItemId` is
// the stable upsert key, so a re-ingest overwrites the matching case
// rather than duplicating it. Track the ids we touch to prune dropped
@@ -1534,6 +1663,7 @@ export function registerVerifyCommand(program: Command) {
if (options.json !== undefined) {
outputJson(
{
+ acceptanceId,
cases: cases.length,
evidence: evidenceCount,
inlined,
@@ -1542,6 +1672,7 @@ export function registerVerifyCommand(program: Command) {
pruned,
pullRequest,
reused,
+ subject: subject?.ref,
unplanned,
verifyRunId: runId,
},
@@ -1573,8 +1704,15 @@ export function registerVerifyCommand(program: Command) {
console.log(
`${pc.bold('verifyRunId')}: ${runId}${reused ? pc.dim(' (updated in place)') : ''}`,
);
+ if (acceptanceId) {
+ console.log(
+ `${pc.bold('acceptance')}: ${acceptanceId} ${pc.dim(`(${subject!.ref.subjectType}:${subject!.ref.subjectId})`)}`,
+ );
+ }
if (options.open) {
console.log(`${pc.bold('open')}: /verify/${runId}`);
+ if (acceptanceId)
+ console.log(`${pc.bold('open acceptance')}: /acceptance/${acceptanceId}`);
}
},
);
diff --git a/apps/cli/src/commands/verifyAcceptance.ts b/apps/cli/src/commands/verifyAcceptance.ts
new file mode 100644
index 00000000000..bae73ed86f0
--- /dev/null
+++ b/apps/cli/src/commands/verifyAcceptance.ts
@@ -0,0 +1,167 @@
+import type { Command } from 'commander';
+import pc from 'picocolors';
+
+import { getTrpcClient } from '../api/client';
+import { outputJson, printTable, timeAgo, truncate } from '../utils/format';
+import { log } from '../utils/logger';
+import { parseSubjectRef } from './verify';
+
+/**
+ * Resolve an acceptance from either its uuid or a `type:id` subject reference —
+ * the subject form is what a harness naturally holds (it knows what it tested,
+ * not the aggregate's id).
+ */
+async function resolveAcceptanceId(ref: string): Promise<string> {
+ const subject = parseSubjectRef(ref);
+ if (!subject) return ref;
+
+ const client = await getTrpcClient();
+ const acceptance = await client.acceptance.getBySubject.query({
+ subjectId: subject.subjectId,
+ subjectType: subject.subjectType,
+ });
+ if (!acceptance) {
+ log.error(`No acceptance found for ${ref}`);
+ process.exit(1);
+ }
+ return acceptance.id;
+}
+
+const stateGlyph = (state: string): string => {
+ if (state === 'passed') return pc.green('✓ passed');
+ if (state === 'failed') return pc.red('✗ failed');
+ if (state === 'uncertain') return pc.yellow('? uncertain');
+ return pc.dim('· not executed');
+};
+
+const statusColor = (status: string): string => {
+ if (status === 'accepted') return pc.green(status);
+ if (status === 'rejected') return pc.red(status);
+ if (status === 'delivered') return pc.yellow(status);
+ return pc.dim(status);
+};
+
+export function registerAcceptanceCommands(verify: Command) {
+ const acceptance = verify
+ .command('acceptance')
+ .description(
+ 'Manage subject-level delivery acceptances (the cross-round union of verify sessions)',
+ );
+
+ acceptance
+ .command('list')
+ .description('List acceptances, newest first')
+ .option('--json [fields]', 'Output JSON')
+ .action(async (options: { json?: boolean | string }) => {
+ const client = await getTrpcClient();
+ const items = await client.acceptance.list.query();
+
+ if (options.json !== undefined) {
+ outputJson(items, typeof options.json === 'string' ? options.json : undefined);
+ return;
+ }
+ if (items.length === 0) {
+ console.log(pc.dim('No acceptances yet.'));
+ return;
+ }
+ printTable(
+ items.map((a) => [
+ a.id,
+ `${a.subjectType}:${truncate(a.subjectId, 24)}`,
+ statusColor(a.status),
+ truncate(a.requirement ?? '', 40),
+ timeAgo(a.createdAt),
+ ]),
+ ['ID', 'SUBJECT', 'STATUS', 'REQUIREMENT', 'CREATED'],
+ );
+ });
+
+ acceptance
+ .command('view <idOrSubject>')
+ .description('Show the acceptance decision bundle (union checks + round ledger)')
+ .option('--json [fields]', 'Output JSON')
+ .action(async (idOrSubject: string, options: { json?: boolean | string }) => {
+ const id = await resolveAcceptanceId(idOrSubject);
+ const client = await getTrpcClient();
+ const bundle = await client.acceptance.getBundle.query({ id });
+
+ if (options.json !== undefined) {
+ outputJson(bundle, typeof options.json === 'string' ? options.json : undefined);
+ return;
+ }
+
+ const { acceptance: agg, checks, latestReport, rounds, subject } = bundle;
+ console.log(
+ `${pc.bold(subject.title ?? subject.id)} ${pc.dim(`(${subject.type}:${subject.id})`)}`,
+ );
+ console.log(
+ `${pc.bold('status')}: ${statusColor(agg.status)} ${pc.bold('rounds')}: ${rounds.length}`,
+ );
+ if (agg.requirement) console.log(`${pc.bold('requirement')}: ${agg.requirement}`);
+ if (latestReport?.summary) console.log(`${pc.bold('summary')}: ${latestReport.summary}`);
+
+ console.log();
+ printTable(
+ checks.map((c) => [
+ truncate(c.title, 46),
+ stateGlyph(c.state),
+ c.required ? 'gate' : 'soft',
+ c.surface ?? '',
+ c.fixed
+ ? 'fixed'
+ : c.carriedFromRound !== undefined
+ ? `carried r${c.carriedFromRound}`
+ : '',
+ c.history.map((h) => `r${h.roundIndex}:${h.state}`).join(' → '),
+ ]),
+ ['CHECK', 'FINAL', 'BLOCK', 'SURFACE', 'NOTE', 'HISTORY'],
+ );
+
+ console.log();
+ printTable(
+ rounds.map((r) => [
+ `r${r.run.roundIndex}`,
+ r.run.status ?? (r.report ? 'settled' : 'open'),
+ r.report?.verdict ?? '',
+ `${r.report?.passedChecks ?? '-'}/${r.report?.totalChecks ?? '-'}`,
+ r.run.userDecision ?? '',
+ timeAgo(r.run.createdAt),
+ ]),
+ ['ROUND', 'STATUS', 'VERDICT', 'PASSED', 'DECISION', 'CREATED'],
+ );
+ });
+
+ acceptance
+ .command('accept <idOrSubject>')
+ .description('Accept the delivery — the terminal user decision that closes the acceptance')
+ .option('--comment <text>', 'Optional note recorded with the decision')
+ .option('--json [fields]', 'Output JSON')
+ .action(async (idOrSubject: string, options: { comment?: string; json?: boolean | string }) => {
+ const id = await resolveAcceptanceId(idOrSubject);
+ const client = await getTrpcClient();
+ const result = await client.acceptance.accept.mutate({ comment: options.comment, id });
+
+ if (options.json !== undefined) {
+ outputJson(result, typeof options.json === 'string' ? options.json : undefined);
+ return;
+ }
+ console.log(`${pc.green('✓')} Delivery accepted (${result.id})`);
+ });
+
+ acceptance
+ .command('reject <idOrSubject>')
+ .description('Reject the delivery — the comment seeds the next repair round')
+ .requiredOption('--comment <text>', 'Why the delivery is rejected (the re-tasking input)')
+ .option('--json [fields]', 'Output JSON')
+ .action(async (idOrSubject: string, options: { comment: string; json?: boolean | string }) => {
+ const id = await resolveAcceptanceId(idOrSubject);
+ const client = await getTrpcClient();
+ const result = await client.acceptance.reject.mutate({ comment: options.comment, id });
+
+ if (options.json !== undefined) {
+ outputJson(result, typeof options.json === 'string' ? options.json : undefined);
+ return;
+ }
+ console.log(`${pc.red('✗')} Delivery rejected (${result.id}) — next round re-opens it`);
+ });
+}
diff --git a/apps/server/src/routers/lambda/__tests__/verify.test.ts b/apps/server/src/routers/lambda/__tests__/verify.test.ts
index a00551a717e..b53582e244a 100644
--- a/apps/server/src/routers/lambda/__tests__/verify.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/verify.test.ts
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { verifyRouter } from '@/server/routers/lambda/verify';
import { FileService } from '@/server/services/file';
+import type * as VerifyServiceModule from '@/server/services/verify';
const modelMocks = vi.hoisted(() => ({
createEvidence: vi.fn(),
@@ -43,7 +44,8 @@ vi.mock('@/database/models/verifyEvidence', () => ({
})),
}));
-vi.mock('@/server/services/verify', () => ({
+vi.mock('@/server/services/verify', async (importOriginal) => ({
+ ...(await importOriginal<typeof VerifyServiceModule>()),
VerifyExecutorService: class VerifyExecutorService {},
VerifyFeedbackService: class VerifyFeedbackService {},
VerifyPlanGeneratorService: class VerifyPlanGeneratorService {},
diff --git a/apps/server/src/routers/lambda/acceptance.ts b/apps/server/src/routers/lambda/acceptance.ts
new file mode 100644
index 00000000000..0c8b9d5f9ec
--- /dev/null
+++ b/apps/server/src/routers/lambda/acceptance.ts
@@ -0,0 +1,228 @@
+import { acceptanceSubjectTypes } from '@lobechat/const/verify';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import {
+ requireWorkspaceRoleWhenScoped,
+ wsCompatProcedure,
+} from '@/business/server/trpc-middlewares/workspaceAuth';
+import { VerifyRunModel } from '@/database/models/verifyRun';
+import type { AcceptanceItem } from '@/database/schemas/verify';
+import { router } from '@/libs/trpc/lambda';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import {
+ AcceptanceService,
+ buildAcceptanceCheckUnion,
+ createEvidenceFileResolver,
+} from '@/server/services/verify';
+
+import { assertWorkspaceRowManageable } from './_helpers/assertWorkspaceRowManageable';
+
+const subjectTypeSchema = z.enum(acceptanceSubjectTypes);
+
+const acceptanceProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
+ return opts.next({
+ ctx: {
+ acceptanceService: new AcceptanceService(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ ),
+ },
+ });
+});
+
+// Writes: workspace mode requires at least the member role (viewers are
+// read-only); personal mode passes through unrestricted.
+const acceptanceWriteProcedure = acceptanceProcedure.use(requireWorkspaceRoleWhenScoped('member'));
+
+const resolveAcceptance = async (
+ ctx: { acceptanceService: AcceptanceService },
+ id: string,
+): Promise<AcceptanceItem> => {
+ const acceptance = await ctx.acceptanceService.acceptanceModel.findById(id);
+
+ if (!acceptance) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Acceptance not found' });
+ }
+
+ return acceptance;
+};
+
+export const acceptanceRouter = router({
+ /**
+ * The user accepts the delivery — the terminal business event that closes
+ * the acceptance lifecycle. The verifier's verdict is a recommendation; this
+ * click is the event (a failed/uncertain round can still be accepted, which
+ * means the user knowingly takes it with its exceptions).
+ */
+ accept: acceptanceWriteProcedure
+ .input(z.object({ comment: z.string().max(2000).optional(), id: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ const acceptance = await resolveAcceptance(ctx, input.id);
+ assertWorkspaceRowManageable(ctx, acceptance.userId, 'acceptance');
+
+ return ctx.acceptanceService.accept(acceptance.id, input.comment);
+ }),
+
+ /**
+ * Chain an existing verify run onto an acceptance as its next round.
+ * Idempotent when the run is already chained to the same acceptance (the
+ * ingest CLI re-runs against a remembered session).
+ */
+ attachRun: acceptanceWriteProcedure
+ .input(z.object({ acceptanceId: z.string(), verifyRunId: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ const acceptance = await resolveAcceptance(ctx, input.acceptanceId);
+ assertWorkspaceRowManageable(ctx, acceptance.userId, 'acceptance');
+
+ // The attach rewrites the RUN's acceptance_id/round_index too — and a
+ // workspace-visible run is not necessarily the caller's. Creator-scope it
+ // like every other verify write, or a member could chain another
+ // member's report onto their aggregate.
+ const run = await new VerifyRunModel(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ ).findById(input.verifyRunId);
+ if (!run) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Verification run not found' });
+ }
+ assertWorkspaceRowManageable(ctx, run.userId, 'verify run');
+
+ try {
+ return await ctx.acceptanceService.attachRun(run.id, acceptance.id);
+ } catch (error) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: error instanceof Error ? error.message : 'Failed to attach run',
+ });
+ }
+ }),
+
+ /** Get (or lazily create) the aggregate for a subject — the ingest entry point. */
+ ensure: acceptanceWriteProcedure
+ .input(
+ z.object({
+ requirement: z.string().max(2000).optional(),
+ subjectId: z.string(),
+ subjectType: subjectTypeSchema,
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ try {
+ return await ctx.acceptanceService.ensureForSubject(input.subjectType, input.subjectId, {
+ requirement: input.requirement,
+ });
+ } catch (error) {
+ throw new TRPCError({
+ code: 'NOT_FOUND',
+ message: error instanceof Error ? error.message : 'Acceptance subject not found',
+ });
+ }
+ }),
+
+ /** The acceptance row for a subject, or null when none exists yet. */
+ getBySubject: acceptanceProcedure
+ .input(z.object({ subjectId: z.string(), subjectType: subjectTypeSchema }))
+ .query(async ({ ctx, input }) => {
+ const acceptance = await ctx.acceptanceService.acceptanceModel.findBySubject(
+ input.subjectType,
+ input.subjectId,
+ );
+ return acceptance ?? null;
+ }),
+
+ /**
+ * One-shot payload for the acceptance decision workspace: the aggregate, its
+ * subject header, the round ledger (each round's run + report), and the
+ * cross-round check union — every check ever planned, with its final verdict,
+ * final evidence (file-URL enriched) and round provenance.
+ */
+ getBundle: acceptanceProcedure
+ .input(z.object({ id: z.string() }))
+ .query(async ({ ctx, input }) => {
+ const acceptance = await resolveAcceptance(ctx, input.id);
+
+ const [subject, { evidence, reports, results, runs }] = await Promise.all([
+ ctx.acceptanceService.resolveSubject(acceptance),
+ ctx.acceptanceService.loadRounds(acceptance.id),
+ ]);
+
+ const resultsByRun = new Map<string, typeof results>();
+ for (const result of results) {
+ const key = result.verifyRunId!;
+ const bucket = resultsByRun.get(key) ?? [];
+ bucket.push(result);
+ resultsByRun.set(key, bucket);
+ }
+
+ const checks = buildAcceptanceCheckUnion(
+ runs.map((run) => ({ results: resultsByRun.get(run.id) ?? [], run })),
+ );
+
+ // Enrich the evidence backing every executed timeline step — the final
+ // round's artifacts render inline on the row; earlier steps' artifacts
+ // render inside the check's iteration-history timeline.
+ const resolveFileMeta = createEvidenceFileResolver(
+ ctx.serverDB,
+ acceptance.userId,
+ acceptance.workspaceId ?? undefined,
+ );
+ const timelineResultIds = new Set(
+ checks.flatMap((check) => check.timeline.map((entry) => entry.resultId)),
+ );
+ const enriched = await Promise.all(
+ evidence
+ .filter((e) => timelineResultIds.has(e.checkResultId))
+ .map(async (e) => ({ ...e, ...(await resolveFileMeta(e.fileId ?? null)) })),
+ );
+ const evidenceByResult = new Map<string, typeof enriched>();
+ for (const e of enriched) {
+ const bucket = evidenceByResult.get(e.checkResultId) ?? [];
+ bucket.push(e);
+ evidenceByResult.set(e.checkResultId, bucket);
+ }
+
+ const reportsByRun = new Map(reports.map((r) => [r.verifyRunId!, r]));
+ const rounds = runs.map((run) => ({
+ report: reportsByRun.get(run.id) ?? null,
+ run,
+ }));
+ const latestReport = [...rounds].reverse().find((r) => r.report)?.report ?? null;
+
+ return {
+ acceptance,
+ checks: checks.map((check) => ({
+ ...check,
+ evidence: check.result ? (evidenceByResult.get(check.result.id) ?? []) : [],
+ timeline: check.timeline.map((entry) => ({
+ ...entry,
+ evidence: evidenceByResult.get(entry.resultId) ?? [],
+ })),
+ })),
+ latestReport,
+ rounds,
+ subject,
+ };
+ }),
+
+ /** Recent acceptances, newest first — the CLI list surface. */
+ list: acceptanceProcedure.query(async ({ ctx }) => ctx.acceptanceService.acceptanceModel.query()),
+
+ /**
+ * The user rejects the delivery. The comment is a re-tasking input: it is
+ * recorded on the current round's decision and seeds the next repair/verify
+ * round (spawned by the runtime for agent rounds, or by the next
+ * `lh verify ingest-report` for harness rounds).
+ */
+ reject: acceptanceWriteProcedure
+ .input(z.object({ comment: z.string().min(1).max(2000), id: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ const acceptance = await resolveAcceptance(ctx, input.id);
+ assertWorkspaceRowManageable(ctx, acceptance.userId, 'acceptance');
+
+ return ctx.acceptanceService.reject(acceptance.id, input.comment);
+ }),
+});
diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.ts
index f316039f4fe..336860de981 100644
--- a/apps/server/src/routers/lambda/index.ts
+++ b/apps/server/src/routers/lambda/index.ts
@@ -18,6 +18,7 @@ import { workspaceMemberRouter } from '@/business/server/lambda-routers/workspac
import { workspaceUsageRouter } from '@/business/server/lambda-routers/workspaceUsage';
import { publicProcedure, router } from '@/libs/trpc/lambda';
+import { acceptanceRouter } from './acceptance';
import { agentRouter } from './agent';
import { agentBotProviderRouter } from './agentBotProvider';
import { agentDocumentRouter } from './agentDocument';
@@ -84,6 +85,7 @@ import { webBrowsingRouter } from './webBrowsing';
import { workspaceUserSettingsRouter } from './workspaceUserSettings';
export const lambdaRouter = router({
+ acceptance: acceptanceRouter,
agent: agentRouter,
agentBotProvider: agentBotProviderRouter,
agentNotify: agentNotifyRouter,
diff --git a/apps/server/src/routers/lambda/verify.ts b/apps/server/src/routers/lambda/verify.ts
index a3f0f87daea..9596f862d0e 100644
--- a/apps/server/src/routers/lambda/verify.ts
+++ b/apps/server/src/routers/lambda/verify.ts
@@ -10,7 +10,6 @@ import {
wsCompatProcedure,
} from '@/business/server/trpc-middlewares/workspaceAuth';
import { AgentOperationModel } from '@/database/models/agentOperation';
-import { FileModel } from '@/database/models/file';
import { LlmGenerationTracingModel } from '@/database/models/llmGenerationTracing';
import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';
import { VerifyCriterionModel } from '@/database/models/verifyCriterion';
@@ -26,8 +25,9 @@ import {
} from '@/database/schemas/verify';
import { publicProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
-import { FileService } from '@/server/services/file';
import {
+ AcceptanceService,
+ createEvidenceFileResolver,
finalizeVerifyRun,
VerifyExecutorService,
VerifyFeedbackService,
@@ -89,6 +89,7 @@ const rubricConfigSchema = z.object({
});
const checkItemSchema = z.object({
+ category: z.string().optional(),
description: z.string().optional(),
id: z.string(),
index: z.number(),
@@ -96,6 +97,7 @@ const checkItemSchema = z.object({
required: z.boolean(),
sourceCriterionId: z.string().nullish(),
sourceRubricId: z.string().nullish(),
+ supersedes: z.array(z.string()).optional(),
title: z.string(),
verifierConfig: z.record(z.string(), z.unknown()),
verifierType: verifierTypeSchema,
@@ -904,7 +906,7 @@ export const verifyRouter = router({
// The upsert overwrites the run's existing report row.
assertWorkspaceRowManageable(ctx, run.userId, 'verify run');
- return ctx.reportModel.upsertByRun({
+ const report = await ctx.reportModel.upsertByRun({
content: input.content ?? null,
failedChecks: input.failedChecks ?? null,
generatedBy: input.generatedBy ?? 'agent-testing',
@@ -916,6 +918,23 @@ export const verifyRouter = router({
verdict: input.verdict ?? null,
verifyRunId: run.id,
});
+
+ // A published report settles an ingested round — re-derive the aggregate
+ // it chains onto (→ `delivered`, awaiting the user's decision). Best-effort:
+ // the report write must not fail on a rollup hiccup.
+ if (run.acceptanceId) {
+ try {
+ await new AcceptanceService(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ ).recomputeStatus(run.acceptanceId);
+ } catch (error) {
+ console.error('[verify:upsertReport:recomputeAcceptance]', error);
+ }
+ }
+
+ return report;
}),
getReport: verifyProcedure.input(verifyRunIdInputSchema).query(async ({ ctx, input }) => {
@@ -983,47 +1002,11 @@ export const verifyRouter = router({
]);
// Resolve display metadata for each file-backed evidence artifact.
- let fileService: FileService | null | undefined;
- const getFileService = () => {
- if (fileService !== undefined) return fileService;
-
- try {
- fileService = new FileService(ctx.serverDB, run.userId, run.workspaceId ?? undefined);
- } catch (error) {
- console.error('[verify:getReportBundle:resolveFileMeta]', error);
- fileService = null;
- }
-
- return fileService;
- };
- const resolveFileMeta = async (fileId: string | null) => {
- if (!fileId) return { fileName: null, fileUrl: null };
-
- try {
- const file = await FileModel.getFileById(ctx.serverDB, fileId);
- if (!file) return { fileName: null, fileUrl: null };
- if (!file.url) return { fileName: file.name ?? null, fileUrl: null };
-
- const service = getFileService();
- if (!service) return { fileName: file.name ?? null, fileUrl: null };
-
- try {
- return {
- fileName: file.name ?? null,
- fileUrl: await service.getFullFileUrl(file.url),
- };
- } catch (error) {
- console.error('[verify:getReportBundle:resolveFileMeta]', error);
- return { fileName: file.name ?? null, fileUrl: null };
- }
- } catch (error) {
- console.error('[verify:getReportBundle:resolveFileMeta]', error);
- return {
- fileName: null,
- fileUrl: null,
- };
- }
- };
+ const resolveFileMeta = createEvidenceFileResolver(
+ ctx.serverDB,
+ run.userId,
+ run.workspaceId ?? undefined,
+ );
const resultsWithEvidence = await Promise.all(
results.map(async (r) => {
diff --git a/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts b/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts
new file mode 100644
index 00000000000..740156aac11
--- /dev/null
+++ b/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts
@@ -0,0 +1,96 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AcceptanceService } from '../acceptanceService';
+
+const mocks = vi.hoisted(() => ({
+ findById: vi.fn(),
+ listByAcceptance: vi.fn(),
+ setDecision: vi.fn(),
+ taskResolve: vi.fn(),
+ updateStatus: vi.fn(),
+}));
+
+vi.mock('@/database/models/acceptance', () => ({
+ AcceptanceModel: vi.fn(() => ({
+ findById: mocks.findById,
+ updateStatus: mocks.updateStatus,
+ })),
+}));
+vi.mock('@/database/models/verifyRun', () => ({
+ VerifyRunModel: vi.fn(() => ({
+ listByAcceptance: mocks.listByAcceptance,
+ setDecision: mocks.setDecision,
+ })),
+}));
+vi.mock('@/database/models/verifyCheckResult', () => ({ VerifyCheckResultModel: vi.fn() }));
+vi.mock('@/database/models/verifyEvidence', () => ({ VerifyEvidenceModel: vi.fn() }));
+vi.mock('@/database/models/verifyReport', () => ({ VerifyReportModel: vi.fn() }));
+vi.mock('@/database/models/task', () => ({
+ TaskModel: vi.fn(() => ({ resolve: mocks.taskResolve })),
+}));
+vi.mock('@/database/models/topic', () => ({ TopicModel: vi.fn() }));
+vi.mock('@/database/models/document', () => ({ DocumentModel: vi.fn() }));
+vi.mock('@/server/services/task', () => ({ TaskService: vi.fn() }));
+
+const service = () => new AcceptanceService({} as any, 'user-1');
+
+const acceptance = (status: string) => ({
+ id: 'acc-1',
+ status,
+ subjectId: 'tpc-1',
+ subjectType: 'topic',
+});
+
+describe('AcceptanceService decision gating', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.listByAcceptance.mockResolvedValue([{ id: 'run-1', roundIndex: 1 }]);
+ });
+
+ it.each(['pending', 'planned', 'verifying', 'repairing'])(
+ 'refuses to accept while the round chain is still %s',
+ async (status) => {
+ mocks.findById.mockResolvedValue(acceptance(status));
+
+ await expect(service().accept('acc-1')).rejects.toThrow('still in progress');
+ expect(mocks.setDecision).not.toHaveBeenCalled();
+ expect(mocks.updateStatus).not.toHaveBeenCalled();
+ },
+ );
+
+ it('refuses to decide twice', async () => {
+ mocks.findById.mockResolvedValue(acceptance('accepted'));
+ await expect(service().accept('acc-1')).rejects.toThrow('already been accepted');
+
+ mocks.findById.mockResolvedValue(acceptance('rejected'));
+ await expect(service().reject('acc-1', 'again')).rejects.toThrow('re-opens it');
+ expect(mocks.setDecision).not.toHaveBeenCalled();
+ });
+
+ it.each(['delivered', 'errored'])('accepts a settled (%s) delivery', async (status) => {
+ mocks.findById.mockResolvedValue(acceptance(status));
+
+ await service().accept('acc-1', 'looks good');
+
+ expect(mocks.setDecision).toHaveBeenCalledWith(
+ 'run-1',
+ 'accept',
+ expect.objectContaining({ comment: 'looks good', decidedBy: 'user-1' }),
+ );
+ expect(mocks.updateStatus).toHaveBeenCalledWith('acc-1', 'accepted');
+ });
+
+ it('rejects a settled delivery with the re-tasking comment', async () => {
+ mocks.findById.mockResolvedValue(acceptance('delivered'));
+
+ await service().reject('acc-1', 'dark mode needs a screenshot');
+
+ expect(mocks.setDecision).toHaveBeenCalledWith(
+ 'run-1',
+ 'reject',
+ expect.objectContaining({ comment: 'dark mode needs a screenshot' }),
+ );
+ expect(mocks.updateStatus).toHaveBeenCalledWith('acc-1', 'rejected');
+ });
+});
diff --git a/apps/server/src/services/verify/__tests__/acceptanceUnion.test.ts b/apps/server/src/services/verify/__tests__/acceptanceUnion.test.ts
new file mode 100644
index 00000000000..a9b435e138b
--- /dev/null
+++ b/apps/server/src/services/verify/__tests__/acceptanceUnion.test.ts
@@ -0,0 +1,230 @@
+// @vitest-environment node
+import type { VerifyCheckItem } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import type { VerifyCheckResultItem, VerifyRunItem } from '@/database/schemas/verify';
+
+import { buildAcceptanceCheckUnion } from '../acceptanceService';
+
+const planItem = (id: string, overrides: Partial<VerifyCheckItem> = {}): VerifyCheckItem => ({
+ id,
+ index: 0,
+ onFail: 'manual',
+ required: true,
+ title: `check ${id}`,
+ verifierConfig: {},
+ verifierType: 'agent',
+ ...overrides,
+});
+
+const run = (id: string, roundIndex: number, plan: VerifyCheckItem[]): VerifyRunItem =>
+ ({ id, plan, roundIndex }) as VerifyRunItem;
+
+const result = (
+ checkItemId: string,
+ verdict: 'passed' | 'failed' | 'uncertain',
+ overrides: Partial<VerifyCheckResultItem> = {},
+): VerifyCheckResultItem =>
+ ({
+ checkItemId,
+ id: `res-${checkItemId}-${verdict}`,
+ required: true,
+ status: verdict,
+ verdict,
+ ...overrides,
+ }) as VerifyCheckResultItem;
+
+describe('buildAcceptanceCheckUnion', () => {
+ it('takes each item final verdict from its latest round and keeps the trail', () => {
+ const plan = [planItem('badge')];
+ const rows = buildAcceptanceCheckUnion([
+ { results: [result('badge', 'failed')], run: run('r1', 1, plan) },
+ { results: [result('badge', 'failed')], run: run('r2', 2, plan) },
+ { results: [result('badge', 'passed')], run: run('r3', 3, plan) },
+ ]);
+
+ expect(rows).toHaveLength(1);
+ const row = rows[0];
+ expect(row.state).toBe('passed');
+ expect(row.fixed).toBe(true);
+ expect(row.resultRound).toBe(3);
+ expect(row.introducedAtRound).toBe(1);
+ expect(row.history.map((h) => `${h.roundIndex}:${h.state}`)).toEqual([
+ '1:failed',
+ '2:failed',
+ '3:passed',
+ ]);
+ });
+
+ it('marks an item planned later but never re-run as carried forward', () => {
+ const plan = [planItem('prefs')];
+ const rows = buildAcceptanceCheckUnion([
+ { results: [result('prefs', 'passed')], run: run('r1', 1, plan) },
+ { results: [], run: run('r2', 2, plan) },
+ ]);
+
+ expect(rows[0].state).toBe('passed');
+ expect(rows[0].carriedFromRound).toBe(1);
+ expect(rows[0].fixed).toBe(false);
+ });
+
+ it('keeps a planned-but-never-executed item visible as not_executed', () => {
+ const rows = buildAcceptanceCheckUnion([
+ { results: [], run: run('r1', 1, [planItem('dark-contrast')]) },
+ ]);
+
+ expect(rows[0].state).toBe('not_executed');
+ expect(rows[0].history).toEqual([]);
+ expect(rows[0].carriedFromRound).toBeUndefined();
+ });
+
+ it('records an item introduced by a later round', () => {
+ const first = [planItem('a')];
+ const second = [planItem('a'), planItem('empty-state')];
+ const rows = buildAcceptanceCheckUnion([
+ { results: [result('a', 'passed')], run: run('r1', 1, first) },
+ {
+ results: [result('a', 'passed'), result('empty-state', 'passed')],
+ run: run('r2', 2, second),
+ },
+ ]);
+
+ const introduced = rows.find((r) => r.id === 'empty-state')!;
+ expect(introduced.introducedAtRound).toBe(2);
+ expect(introduced.state).toBe('passed');
+ });
+
+ it('includes unplanned results and reads their snapshot title/required', () => {
+ const rows = buildAcceptanceCheckUnion([
+ {
+ results: [
+ result('surprise', 'failed', { checkItemTitle: 'Surprise finding', required: false }),
+ ],
+ run: run('r1', 1, []),
+ },
+ ]);
+
+ expect(rows[0].title).toBe('Surprise finding');
+ expect(rows[0].required).toBe(false);
+ expect(rows[0].state).toBe('failed');
+ });
+
+ it('resolves the per-item surface from the plan verifierConfig, normalized', () => {
+ const rows = buildAcceptanceCheckUnion([
+ {
+ results: [],
+ run: run('r1', 1, [
+ planItem('web-check', { verifierConfig: { surface: 'web' } }),
+ planItem('desktop-check', { verifierConfig: { surface: 'electron' } }),
+ planItem('bare-check'),
+ ]),
+ },
+ ]);
+
+ const byId = new Map(rows.map((r) => [r.id, r]));
+ expect(byId.get('web-check')?.surface).toBe('web');
+ expect(byId.get('desktop-check')?.surface).toBe('desktop');
+ expect(byId.get('bare-check')?.surface).toBeNull();
+ });
+
+ it('prefers the latest plan snapshot for title/required', () => {
+ const rows = buildAcceptanceCheckUnion([
+ { results: [], run: run('r1', 1, [planItem('x', { title: 'old title' })]) },
+ {
+ results: [],
+ run: run('r2', 2, [planItem('x', { required: false, title: 'new title' })]),
+ },
+ ]);
+
+ expect(rows[0].title).toBe('new title');
+ expect(rows[0].required).toBe(false);
+ });
+
+ it('builds the timeline with each round own wording', () => {
+ const rows = buildAcceptanceCheckUnion([
+ {
+ results: [result('x', 'failed')],
+ run: run('r1', 1, [planItem('x', { title: 'first wording' })]),
+ },
+ {
+ results: [result('x', 'passed')],
+ run: run('r2', 2, [planItem('x', { title: 'refined wording' })]),
+ },
+ ]);
+
+ const row = rows[0];
+ expect(row.revisions).toBe(2);
+ expect(row.titleChanged).toBe(true);
+ expect(row.timeline.map((entry) => `${entry.roundIndex}:${entry.title}`)).toEqual([
+ '1:first wording',
+ '2:refined wording',
+ ]);
+ // Re-runs with a stable wording are NOT an iteration.
+ const stable = buildAcceptanceCheckUnion([
+ { results: [result('y', 'passed')], run: run('r1', 1, [planItem('y')]) },
+ { results: [result('y', 'passed')], run: run('r2', 2, [planItem('y')]) },
+ ])[0];
+ expect(stable.revisions).toBe(2);
+ expect(stable.titleChanged).toBe(false);
+ });
+
+ it('folds superseded generations into the successor timeline', () => {
+ const rows = buildAcceptanceCheckUnion([
+ {
+ results: [result('single-section', 'passed')],
+ run: run('r1', 1, [planItem('single-section', { title: '仅未读时无分区标题' })]),
+ },
+ {
+ results: [result('single-section-removed', 'passed')],
+ run: run('r2', 2, [
+ planItem('single-section-removed', {
+ supersedes: ['single-section'],
+ title: '单区标题规则已移除',
+ }),
+ ]),
+ },
+ ]);
+
+ expect(rows).toHaveLength(1);
+ const row = rows[0];
+ expect(row.id).toBe('single-section-removed');
+ expect(row.supersededIds).toEqual(['single-section']);
+ expect(row.introducedAtRound).toBe(1);
+ expect(row.revisions).toBe(2);
+ expect(row.titleChanged).toBe(true);
+ expect(row.timeline.map((entry) => entry.title)).toEqual([
+ '仅未读时无分区标题',
+ '单区标题规则已移除',
+ ]);
+ expect(row.state).toBe('passed');
+ });
+
+ it('collapses a supersedes chain fully into the newest generation', () => {
+ const rows = buildAcceptanceCheckUnion([
+ { results: [result('a', 'failed')], run: run('r1', 1, [planItem('a')]) },
+ {
+ results: [result('b', 'failed')],
+ run: run('r2', 2, [planItem('b', { supersedes: ['a'] })]),
+ },
+ {
+ results: [result('c', 'passed')],
+ run: run('r3', 3, [planItem('c', { supersedes: ['b'] })]),
+ },
+ ]);
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0].id).toBe('c');
+ expect(rows[0].supersededIds.sort()).toEqual(['a', 'b']);
+ expect(rows[0].revisions).toBe(3);
+ expect(rows[0].fixed).toBe(true);
+ });
+
+ it('reads the grouping category from the latest plan snapshot', () => {
+ const rows = buildAcceptanceCheckUnion([
+ { results: [], run: run('r1', 1, [planItem('x', { category: '未读区' })]) },
+ { results: [], run: run('r2', 2, [planItem('x')]) },
+ ]);
+
+ expect(rows[0].category).toBe('未读区');
+ });
+});
diff --git a/apps/server/src/services/verify/acceptanceService.ts b/apps/server/src/services/verify/acceptanceService.ts
new file mode 100644
index 00000000000..c6dd85f0de1
--- /dev/null
+++ b/apps/server/src/services/verify/acceptanceService.ts
@@ -0,0 +1,519 @@
+import { normalizeVerifySurface } from '@lobechat/const/verify';
+import type {
+ AcceptanceStatus,
+ AcceptanceSubjectType,
+ VerifyAgentPlanConfig,
+ VerifyCheckItem,
+ VerifyRunDecisionDetail,
+ VerifySurface,
+} from '@lobechat/types';
+import debug from 'debug';
+
+import { AcceptanceModel } from '@/database/models/acceptance';
+import { DocumentModel } from '@/database/models/document';
+import { TaskModel } from '@/database/models/task';
+import { TopicModel } from '@/database/models/topic';
+import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';
+import { VerifyEvidenceModel } from '@/database/models/verifyEvidence';
+import { VerifyReportModel } from '@/database/models/verifyReport';
+import { VerifyRunModel } from '@/database/models/verifyRun';
+import type {
+ AcceptanceItem,
+ VerifyCheckResultItem,
+ VerifyRunItem,
+} from '@/database/schemas/verify';
+import type { LobeChatDatabase } from '@/database/type';
+import { TaskService } from '@/server/services/task';
+
+const log = debug('lobe-server:verify-acceptance');
+
+// ============================================
+// Union view — the cross-round check merge (P-14: the complete inventory of
+// acceptance checks, each with its final verdict + evidence; rounds demoted to
+// provenance). Deterministically computed at read time — never stored, so it
+// can't go stale.
+// ============================================
+
+type CheckState = 'passed' | 'failed' | 'uncertain' | 'not_executed';
+
+const resultState = (result: VerifyCheckResultItem): CheckState => {
+ const v = result.verdict ?? result.status;
+ if (v === 'passed' || v === 'failed' || v === 'uncertain') return v;
+ return 'uncertain';
+};
+
+export interface AcceptanceCheckHistoryEntry {
+ roundIndex: number;
+ state: CheckState;
+ verifyRunId: string;
+}
+
+/**
+ * One executed step of a check's iteration timeline. Carries the title THAT
+ * round used (a superseded item keeps its own wording) so the evolution reads
+ * as written, newest rendered first by the viewer.
+ */
+export interface AcceptanceTimelineEntry {
+ /** The result row backing this step — the key its evidence attaches by. */
+ resultId: string;
+ roundIndex: number;
+ state: CheckState;
+ title: string;
+ verifyRunId: string;
+}
+
+/** One row of the acceptance union: a check item merged across every round. */
+export interface AcceptanceCheckRow {
+ /**
+ * Set when the item was planned in rounds AFTER the one that produced its
+ * final result (it was carried forward without a re-run): the round the
+ * evidence actually comes from.
+ */
+ carriedFromRound?: number;
+ /** Grouping key for the union view (harness-authored page section / domain). */
+ category: string | null;
+ /** Passed now, but failed in at least one earlier round — a repaired check. */
+ fixed: boolean;
+ /** Verdict trail across rounds, oldest first — only rounds that produced a result. */
+ history: AcceptanceCheckHistoryEntry[];
+ /** The `checkItemId` every round agrees on (the successor id after folding). */
+ id: string;
+ /** First round whose plan (or results) named this check (or one it supersedes). */
+ introducedAtRound: number;
+ /** The latest plan snapshot of this item (carries method/expected/requiredEvidence). */
+ planItem?: VerifyCheckItem;
+ required: boolean;
+ /** The final (latest-round) result row, or undefined when the item never ran. */
+ result?: VerifyCheckResultItem;
+ /** Round the final result came from. */
+ resultRound?: number;
+ /** How many executed steps the timeline holds (re-runs + folded generations). */
+ revisions: number;
+ /** Final cross-round state — what the decision is made on. */
+ state: CheckState;
+ /** Ids folded into this row via `supersedes` declarations. */
+ supersededIds: string[];
+ /** Per-item product surface (from the plan item's `verifierConfig.surface`). */
+ surface: VerifySurface | null;
+ /** The executed steps, oldest first — drives the iteration-history timeline. */
+ timeline: AcceptanceTimelineEntry[];
+ title: string;
+ /** The wording evolved across the timeline (a real iteration, not a re-run). */
+ titleChanged: boolean;
+}
+
+interface RoundInput {
+ results: VerifyCheckResultItem[];
+ run: VerifyRunItem;
+}
+
+const itemSurface = (item: VerifyCheckItem | undefined): VerifySurface | null => {
+ const raw = (item?.verifierConfig as VerifyAgentPlanConfig | undefined)?.surface;
+ return typeof raw === 'string' ? normalizeVerifySurface(raw) : null;
+};
+
+/**
+ * Merge a whole round chain into the union check list.
+ *
+ * Alignment is two-layered, both harness-authored (no fuzzy matching):
+ * - the stable `checkItemId` aligns re-runs of the same check across rounds;
+ * - a plan item's `supersedes` folds the ids of checks it REPLACES into this
+ * item's iteration timeline, so a semantically-dead older wording stops
+ * showing up as its own row.
+ */
+export const buildAcceptanceCheckUnion = (rounds: RoundInput[]): AcceptanceCheckRow[] => {
+ const ordered = [...rounds].sort((a, b) => (a.run.roundIndex ?? 0) - (b.run.roundIndex ?? 0));
+
+ const rows = new Map<string, AcceptanceCheckRow>();
+ // Last round whose PLAN named each item — drives the carried-forward flag.
+ const lastPlannedRound = new Map<string, number>();
+
+ const ensureRow = (id: string, roundIndex: number): AcceptanceCheckRow => {
+ const existing = rows.get(id);
+ if (existing) return existing;
+ const row: AcceptanceCheckRow = {
+ category: null,
+ fixed: false,
+ history: [],
+ id,
+ introducedAtRound: roundIndex,
+ required: true,
+ revisions: 0,
+ state: 'not_executed',
+ supersededIds: [],
+ surface: null,
+ timeline: [],
+ title: id,
+ titleChanged: false,
+ };
+ rows.set(id, row);
+ return row;
+ };
+
+ for (const { results, run } of ordered) {
+ const roundIndex = run.roundIndex ?? 0;
+ const plan = (run.plan ?? []) as VerifyCheckItem[];
+ const planById = new Map(plan.map((item) => [item.id, item]));
+
+ for (const item of plan) {
+ const row = ensureRow(item.id, roundIndex);
+ // The latest snapshot wins: repair rounds may refine method/expected.
+ row.planItem = item;
+ row.title = item.title;
+ row.required = item.required;
+ row.category = item.category ?? row.category;
+ row.surface = itemSurface(item) ?? row.surface;
+ lastPlannedRound.set(item.id, roundIndex);
+ }
+
+ for (const result of results) {
+ const row = ensureRow(result.checkItemId, roundIndex);
+ const state = resultState(result);
+ // The title THIS round used — the current round's snapshot, not the final one.
+ const roundTitle =
+ planById.get(result.checkItemId)?.title ?? result.checkItemTitle ?? row.title;
+ row.history.push({ roundIndex, state, verifyRunId: run.id });
+ row.timeline.push({
+ resultId: result.id,
+ roundIndex,
+ state,
+ title: roundTitle,
+ verifyRunId: run.id,
+ });
+ row.result = result;
+ row.resultRound = roundIndex;
+ if (!row.planItem && result.checkItemTitle) row.title = result.checkItemTitle;
+ if (!row.planItem) row.required = result.required;
+ }
+ }
+
+ // Fold superseded generations into their successor's timeline, in round
+ // order so a chain (C replaced by B replaced by A) collapses fully into A.
+ const foldOrder = [...rows.values()].sort((a, b) => a.introducedAtRound - b.introducedAtRound);
+ for (const row of foldOrder) {
+ const supersedes = row.planItem?.supersedes ?? [];
+ for (const oldId of supersedes) {
+ const old = rows.get(oldId);
+ if (!old || old === row) continue;
+ row.timeline = [...old.timeline, ...row.timeline].sort((a, b) => a.roundIndex - b.roundIndex);
+ row.history = [...old.history, ...row.history].sort((a, b) => a.roundIndex - b.roundIndex);
+ row.introducedAtRound = Math.min(row.introducedAtRound, old.introducedAtRound);
+ row.supersededIds = [...row.supersededIds, ...old.supersededIds, old.id];
+ // The successor's own state stands; a never-run successor inherits the
+ // superseded item's final result so the row still shows evidence.
+ if (!row.result && old.result) {
+ row.result = old.result;
+ row.resultRound = old.resultRound;
+ }
+ rows.delete(oldId);
+ }
+ }
+
+ for (const row of rows.values()) {
+ row.state = row.result ? resultState(row.result) : 'not_executed';
+ row.fixed = row.state === 'passed' && row.history.some((entry) => entry.state === 'failed');
+ row.revisions = row.timeline.length;
+ row.titleChanged = row.timeline.some((entry) => entry.title !== row.title);
+ // Carried forward: a later round still planned the item but never re-ran it,
+ // so the final evidence predates the current round.
+ const planned = lastPlannedRound.get(row.id);
+ if (row.resultRound !== undefined && planned !== undefined && planned > row.resultRound) {
+ row.carriedFromRound = row.resultRound;
+ }
+ }
+
+ return [...rows.values()];
+};
+
+// ============================================
+// Status rollup — the aggregate's user-facing lifecycle state, derived from the
+// current (highest) round. `accepted` is terminal and user-owned: recompute
+// never overwrites it. `rejected` holds until a newer round re-opens the loop.
+// ============================================
+
+/** Derive the aggregate status from the current round's pipeline state. */
+const statusFromRound = (run: VerifyRunItem, hasReport: boolean): AcceptanceStatus => {
+ switch (run.status) {
+ case 'planned': {
+ return 'planned';
+ }
+ case 'verifying': {
+ return 'verifying';
+ }
+ case 'repairing': {
+ return 'repairing';
+ }
+ case 'errored': {
+ return 'errored';
+ }
+ // Both settled outcomes await the same human decision — the verdict is
+ // advice, acceptance is the user's event (P-12).
+ case 'passed':
+ case 'failed':
+ case 'delivered': {
+ return 'delivered';
+ }
+ default: {
+ // Ingested rounds carry no rollup status: a published report means the
+ // round has settled and awaits the decision; otherwise it is still open.
+ return hasReport ? 'delivered' : 'verifying';
+ }
+ }
+};
+
+export interface AcceptanceSubjectSummary {
+ id: string;
+ title: string | null;
+ type: AcceptanceSubjectType;
+}
+
+export class AcceptanceService {
+ private readonly db: LobeChatDatabase;
+ private readonly userId: string;
+ private readonly workspaceId?: string;
+
+ readonly acceptanceModel: AcceptanceModel;
+ private readonly runModel: VerifyRunModel;
+ private readonly resultModel: VerifyCheckResultModel;
+ private readonly evidenceModel: VerifyEvidenceModel;
+ private readonly reportModel: VerifyReportModel;
+
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ this.db = db;
+ this.userId = userId;
+ this.workspaceId = workspaceId;
+ this.acceptanceModel = new AcceptanceModel(db, userId, workspaceId);
+ this.runModel = new VerifyRunModel(db, userId, workspaceId);
+ this.resultModel = new VerifyCheckResultModel(db, userId, workspaceId);
+ this.evidenceModel = new VerifyEvidenceModel(db, userId, workspaceId);
+ this.reportModel = new VerifyReportModel(db, userId, workspaceId);
+ }
+
+ /**
+ * Validate the subject exists in the caller's scope before creating an
+ * aggregate for it — the table deliberately has no FK (polymorphic subject),
+ * so this is where dangling aggregates are prevented.
+ */
+ private assertSubjectExists = async (
+ subjectType: AcceptanceSubjectType,
+ subjectId: string,
+ ): Promise<void> => {
+ const found = await this.findSubject(subjectType, subjectId);
+ if (!found) {
+ throw new Error(`${subjectType} "${subjectId}" not found in the current workspace`);
+ }
+ };
+
+ private findSubject = async (
+ subjectType: AcceptanceSubjectType,
+ subjectId: string,
+ ): Promise<{ title: string | null } | null> => {
+ switch (subjectType) {
+ case 'task': {
+ const task = await new TaskModel(this.db, this.userId, this.workspaceId).resolve(subjectId);
+ return task ? { title: task.name ?? task.identifier } : null;
+ }
+ case 'topic': {
+ const topic = await new TopicModel(this.db, this.userId, this.workspaceId).findById(
+ subjectId,
+ );
+ return topic ? { title: topic.title ?? null } : null;
+ }
+ case 'document': {
+ const doc = await new DocumentModel(this.db, this.userId, this.workspaceId).findById(
+ subjectId,
+ );
+ return doc ? { title: doc.title ?? null } : null;
+ }
+ }
+ };
+
+ /** Get (or create) the aggregate for a subject, validating the subject first. */
+ ensureForSubject = async (
+ subjectType: AcceptanceSubjectType,
+ subjectId: string,
+ defaults?: { requirement?: string },
+ ): Promise<AcceptanceItem> => {
+ await this.assertSubjectExists(subjectType, subjectId);
+ return this.acceptanceModel.ensureForSubject(subjectType, subjectId, defaults);
+ };
+
+ /**
+ * Chain a run onto an acceptance as its next round, then re-derive the
+ * aggregate status (a new round re-opens a rejected loop).
+ */
+ attachRun = async (runId: string, acceptanceId: string): Promise<VerifyRunItem> => {
+ const acceptance = await this.acceptanceModel.findById(acceptanceId);
+ if (!acceptance) throw new Error(`Acceptance "${acceptanceId}" not found`);
+
+ // Idempotent for the re-ingest path (the CLI sidecar remembers the run):
+ // an already-chained round keeps its index instead of being re-appended.
+ const existing = await this.runModel.findById(runId);
+ if (!existing) throw new Error(`Verify run "${runId}" not found in the current workspace`);
+ if (existing.acceptanceId === acceptanceId) return existing;
+ if (existing.acceptanceId) {
+ throw new Error('This verify run already belongs to another acceptance');
+ }
+
+ const run = await this.runModel.attachToAcceptance(runId, acceptanceId);
+ await this.recomputeStatus(acceptanceId);
+ log('run %s attached to acceptance %s as round %d', runId, acceptanceId, run.roundIndex);
+ return run;
+ };
+
+ /**
+ * Re-derive the aggregate's lifecycle state from its current round. The
+ * user's `accepted` is terminal; `rejected` is sticky until a round newer
+ * than the decision arrives.
+ */
+ recomputeStatus = async (acceptanceId: string): Promise<AcceptanceStatus | null> => {
+ const acceptance = await this.acceptanceModel.findById(acceptanceId);
+ if (!acceptance) return null;
+ if (acceptance.status === 'accepted') return 'accepted';
+
+ const runs = await this.runModel.listByAcceptance(acceptanceId);
+ const current = runs.at(-1);
+ if (!current) return acceptance.status as AcceptanceStatus;
+
+ // The rejected round stays rejected; only a NEWER round re-opens the loop.
+ if (acceptance.status === 'rejected' && current.userDecision === 'reject') return 'rejected';
+
+ const report = await this.reportModel.findByRun(current.id);
+ const status = statusFromRound(current, Boolean(report));
+ if (status !== acceptance.status) {
+ await this.acceptanceModel.updateStatus(acceptanceId, status);
+ log('acceptance %s → %s (from round %d)', acceptanceId, status, current.roundIndex);
+ }
+ return status;
+ };
+
+ /**
+ * The user accepts the delivery — the terminal business event (P-12). Stamps
+ * the decision on the current round, closes the aggregate, and best-effort
+ * completes a task subject that verification alone didn't settle.
+ */
+ accept = async (acceptanceId: string, comment?: string): Promise<AcceptanceItem> => {
+ const acceptance = await this.requireDecidableAcceptance(acceptanceId);
+
+ await this.stampDecision(acceptanceId, 'accept', comment);
+ await this.acceptanceModel.updateStatus(acceptanceId, 'accepted');
+
+ if (acceptance.subjectType === 'task') await this.completeTaskSubject(acceptance.subjectId);
+
+ return (await this.acceptanceModel.findById(acceptanceId))!;
+ };
+
+ /**
+ * The user rejects the delivery. The comment is the re-tasking input: it is
+ * recorded on the round's decision detail, where the next repair/verify round
+ * picks it up. (Spawning the repair run itself is the runtime's job — for
+ * agent-bound rounds via the repair pipeline, for ingested rounds via the
+ * next `lh verify ingest-report`.)
+ */
+ reject = async (acceptanceId: string, comment: string): Promise<AcceptanceItem> => {
+ await this.requireDecidableAcceptance(acceptanceId);
+
+ await this.stampDecision(acceptanceId, 'reject', comment);
+ await this.acceptanceModel.updateStatus(acceptanceId, 'rejected');
+
+ return (await this.acceptanceModel.findById(acceptanceId))!;
+ };
+
+ /**
+ * A user decision needs a SETTLED round to judge (`delivered`, or `errored`
+ * — the verifier could not run, the user may still take or refuse the
+ * delivery). Deciding mid-flight would stamp a terminal state (and possibly
+ * complete a task) before any report/verdict exists, and `recomputeStatus`
+ * treats `accepted` as sticky, so a premature accept could never be
+ * corrected by the pipeline.
+ */
+ private requireDecidableAcceptance = async (acceptanceId: string): Promise<AcceptanceItem> => {
+ const acceptance = await this.acceptanceModel.findById(acceptanceId);
+ if (!acceptance) throw new Error(`Acceptance "${acceptanceId}" not found`);
+ if (acceptance.status === 'accepted') {
+ throw new Error('This delivery has already been accepted');
+ }
+ if (acceptance.status === 'rejected') {
+ throw new Error('This delivery was rejected — the next verification round re-opens it');
+ }
+ if (acceptance.status !== 'delivered' && acceptance.status !== 'errored') {
+ throw new Error(
+ `Verification is still in progress (${acceptance.status}) — the decision comes once the round settles`,
+ );
+ }
+ return acceptance;
+ };
+
+ private stampDecision = async (
+ acceptanceId: string,
+ decision: 'accept' | 'reject',
+ comment?: string,
+ ): Promise<void> => {
+ const runs = await this.runModel.listByAcceptance(acceptanceId);
+ const current = runs.at(-1);
+ if (!current) throw new Error('This acceptance has no verification round to decide on');
+
+ const detail: VerifyRunDecisionDetail = {
+ decidedAt: new Date().toISOString(),
+ decidedBy: this.userId,
+ ...(comment ? { comment } : {}),
+ };
+ await this.runModel.setDecision(current.id, decision, detail);
+ };
+
+ /**
+ * Accepting a task subject completes the task when verification didn't
+ * already (e.g. the round failed but the user accepted anyway). Best-effort:
+ * a task error must not undo the recorded acceptance.
+ */
+ private completeTaskSubject = async (subjectId: string): Promise<void> => {
+ try {
+ const taskModel = new TaskModel(this.db, this.userId, this.workspaceId);
+ const task = await taskModel.resolve(subjectId);
+ if (!task || ['canceled', 'completed', 'failed'].includes(task.status)) return;
+
+ // TaskService cascades checkpoint / sibling rollup / downstream unlock —
+ // the same completion path settle.ts drives on a passed verify.
+ await new TaskService(this.db, this.userId, this.workspaceId).updateStatus({
+ id: task.id,
+ status: 'completed',
+ });
+ log('acceptance accepted → task %s completed', task.id);
+ } catch (error) {
+ log('completeTaskSubject failed (non-fatal): %O', error);
+ }
+ };
+
+ /** Best-effort subject header info for the bundle (title may be gone). */
+ resolveSubject = async (acceptance: AcceptanceItem): Promise<AcceptanceSubjectSummary> => {
+ let title: string | null = null;
+ try {
+ title =
+ (
+ await this.findSubject(
+ acceptance.subjectType as AcceptanceSubjectType,
+ acceptance.subjectId,
+ )
+ )?.title ?? null;
+ } catch (error) {
+ log('resolveSubject failed (non-fatal): %O', error);
+ }
+ return {
+ id: acceptance.subjectId,
+ title,
+ type: acceptance.subjectType as AcceptanceSubjectType,
+ };
+ };
+
+ /** The rounds + their per-round data the bundle and the union both read. */
+ loadRounds = async (acceptanceId: string) => {
+ const runs = await this.runModel.listByAcceptance(acceptanceId);
+ const runIds = runs.map((r) => r.id);
+ const [results, evidence, reports] = await Promise.all([
+ this.resultModel.listByRuns(runIds),
+ this.evidenceModel.listByRuns(runIds),
+ this.reportModel.findByRuns(runIds),
+ ]);
+ return { evidence, reports, results, runs };
+ };
+}
diff --git a/apps/server/src/services/verify/evidenceFiles.ts b/apps/server/src/services/verify/evidenceFiles.ts
new file mode 100644
index 00000000000..f34c4ed737a
--- /dev/null
+++ b/apps/server/src/services/verify/evidenceFiles.ts
@@ -0,0 +1,59 @@
+import { FileModel } from '@/database/models/file';
+import type { LobeChatDatabase } from '@/database/type';
+import { FileService } from '@/server/services/file';
+
+export interface EvidenceFileMeta {
+ fileName: string | null;
+ fileUrl: string | null;
+}
+
+/**
+ * Display metadata for file-backed evidence artifacts (name + full/signed URL).
+ *
+ * Every failure degrades to nulls instead of throwing: a report/bundle must
+ * still render when one screenshot's storage row is gone. The `FileService` is
+ * built lazily and once — constructing it can itself throw (storage env), and a
+ * bundle resolves dozens of artifacts.
+ */
+export const createEvidenceFileResolver = (
+ db: LobeChatDatabase,
+ userId: string,
+ workspaceId?: string,
+) => {
+ let fileService: FileService | null | undefined;
+ const getFileService = () => {
+ if (fileService !== undefined) return fileService;
+
+ try {
+ fileService = new FileService(db, userId, workspaceId);
+ } catch (error) {
+ console.error('[verify:getReportBundle:resolveFileMeta]', error);
+ fileService = null;
+ }
+
+ return fileService;
+ };
+
+ return async (fileId: string | null): Promise<EvidenceFileMeta> => {
+ if (!fileId) return { fileName: null, fileUrl: null };
+
+ try {
+ const file = await FileModel.getFileById(db, fileId);
+ if (!file) return { fileName: null, fileUrl: null };
+ if (!file.url) return { fileName: file.name ?? null, fileUrl: null };
+
+ const service = getFileService();
+ if (!service) return { fileName: file.name ?? null, fileUrl: null };
+
+ try {
+ return { fileName: file.name ?? null, fileUrl: await service.getFullFileUrl(file.url) };
+ } catch (error) {
+ console.error('[verify:getReportBundle:resolveFileMeta]', error);
+ return { fileName: file.name ?? null, fileUrl: null };
+ }
+ } catch (error) {
+ console.error('[verify:getReportBundle:resolveFileMeta]', error);
+ return { fileName: null, fileUrl: null };
+ }
+ };
+};
diff --git a/apps/server/src/services/verify/index.ts b/apps/server/src/services/verify/index.ts
index d80f1be9e1a..3111a79b2c9 100644
--- a/apps/server/src/services/verify/index.ts
+++ b/apps/server/src/services/verify/index.ts
@@ -1,5 +1,13 @@
+export {
+ type AcceptanceCheckHistoryEntry,
+ type AcceptanceCheckRow,
+ AcceptanceService,
+ type AcceptanceSubjectSummary,
+ buildAcceptanceCheckUnion,
+} from './acceptanceService';
export { createVerifierAgentRunner } from './agentVerifier';
export { coverageGaps, readRequiredEvidence } from './evidenceCoverage';
+export { createEvidenceFileResolver, type EvidenceFileMeta } from './evidenceFiles';
export {
type ExecuteVerifyParams,
type VerifierAgentRunner,
diff --git a/locales/en-US/verify.json b/locales/en-US/verify.json
index b5db7325f4a..d01a75c905e 100644
--- a/locales/en-US/verify.json
+++ b/locales/en-US/verify.json
@@ -1,4 +1,91 @@
{
+ "acceptance.accept.exceptionsHint": "Accepting means you have seen these exceptions and take the delivery with them.",
+ "acceptance.accept.exceptionsTitle": "{{count}} exception(s) still unresolved:",
+ "acceptance.accept.summary": "Mark \"{{title}}\" as accepted: every verification round and its evidence is archived as the acceptance record.",
+ "acceptance.actionError": "The acceptance could not be updated. Try again.",
+ "acceptance.actions.accept": "Accept delivery",
+ "acceptance.actions.cancel": "Cancel",
+ "acceptance.actions.confirmAccept": "Confirm acceptance",
+ "acceptance.actions.confirmReject": "Reject and start the next round",
+ "acceptance.actions.reject": "Reject delivery",
+ "acceptance.banner.accepted": "Accepted · confirmed by you at {{time}}",
+ "acceptance.banner.acceptedHint": "{{count}} verification round(s) archived as the acceptance record",
+ "acceptance.banner.clean": "All {{count}} round(s) passed — awaiting your acceptance",
+ "acceptance.banner.decisionHint": "The verdict is a recommendation; the acceptance decision is yours.",
+ "acceptance.banner.exceptions": "Verification settled with {{count}} exception(s) for you to judge",
+ "acceptance.banner.liveHint": "You can inspect finished checks now; the decision comes once the round settles.",
+ "acceptance.banner.rejected": "Rejected",
+ "acceptance.banner.rejectedHint": "The next verification round re-opens this acceptance when it lands.",
+ "acceptance.banner.rejectedReason": "Reason: {{reason}}",
+ "acceptance.checks.finalRoundHint": "The final result and evidence come from this round — click to locate it.",
+ "acceptance.checks.fixed": "Fixed",
+ "acceptance.checks.fixedHint": "Failed in round {{round}} → fixed in round {{fixedRound}}.",
+ "acceptance.checks.introduced": "Added in round {{round}}",
+ "acceptance.checks.introducedHint": "This check first appeared in that round — click to locate it.",
+ "acceptance.checks.iterated": "Iterated {{count}}×",
+ "acceptance.checks.iteratedHint": "The same acceptance concern evolved across {{count}} rounds; the last round stands. See the iteration history for the evolution.",
+ "acceptance.checks.iterationHistory": "Iteration history ({{count}} rounds)",
+ "acceptance.checks.notRequired": "Non-blocking",
+ "acceptance.checks.notRequiredHint": "required = false: failing this does not block acceptance.",
+ "acceptance.checks.rerun": "Verified {{count}} rounds",
+ "acceptance.checks.rerunHint": "The same check ran in {{count}} rounds; the last round stands.",
+ "acceptance.checks.subtitle": "{{count}} check(s) merged across {{rounds}} round(s)",
+ "acceptance.checks.title": "Acceptance checks",
+ "acceptance.detail.suggestion": "Suggestion",
+ "acceptance.error.description": "Check your connection and try loading this acceptance again.",
+ "acceptance.error.title": "Unable to load acceptance",
+ "acceptance.evidence.file": "{{count}} text evidence item(s)",
+ "acceptance.evidence.image": "{{count}} image evidence item(s)",
+ "acceptance.evidence.video": "{{count}} video evidence item(s)",
+ "acceptance.filter.all": "All {{count}}",
+ "acceptance.filter.exception": "Exceptions {{count}}",
+ "acceptance.filter.fixed": "Fixed {{count}}",
+ "acceptance.group.collapseAll": "Collapse groups",
+ "acceptance.group.collapseItems": "Collapse checks in this group",
+ "acceptance.group.expandAll": "Expand groups",
+ "acceptance.group.expandItems": "Expand checks in this group",
+ "acceptance.group.passRatio": "{{passed}}/{{total}} passed",
+ "acceptance.history.jump": "Round {{round}} — click to locate it in the ledger",
+ "acceptance.latestSummary": "Latest report summary",
+ "acceptance.ledger.collapse": "Collapse the round ledger",
+ "acceptance.ledger.count": "{{count}} round(s)",
+ "acceptance.ledger.description": "Each round is one full verification run; the main list is the cross-round merge. Trace the full history here.",
+ "acceptance.ledger.expand": "Expand the round ledger",
+ "acceptance.ledger.latest": "Latest",
+ "acceptance.ledger.stats": "{{passed}}/{{total}} passed",
+ "acceptance.ledger.title": "Round ledger",
+ "acceptance.ledger.viewReport": "View round report",
+ "acceptance.reject.description": "Your reason becomes input for the next repair round; this is not a passive comment.",
+ "acceptance.reject.placeholder": "Describe what must change before this delivery can be accepted.",
+ "acceptance.reportDrawer.title": "Round {{round}} · verification report",
+ "acceptance.requirementLabel": "Acceptance bar",
+ "acceptance.round": "Round {{round}}",
+ "acceptance.roundCount": "{{count}} verification round(s)",
+ "acceptance.roundStatus.errored": "Errored",
+ "acceptance.roundStatus.failed": "Failed",
+ "acceptance.roundStatus.passed": "Passed",
+ "acceptance.roundStatus.repairing": "Repairing",
+ "acceptance.roundStatus.uncertain": "Uncertain",
+ "acceptance.roundStatus.verifying": "In progress",
+ "acceptance.stats.failed": "{{count}} failed",
+ "acceptance.stats.notExecuted": "{{count}} not executed",
+ "acceptance.stats.passed": "{{count}} passed",
+ "acceptance.stats.uncertain": "{{count}} uncertain",
+ "acceptance.status.accepted": "Delivery accepted",
+ "acceptance.status.delivered": "Ready for your decision",
+ "acceptance.status.errored": "Verification could not run",
+ "acceptance.status.failed": "Verification failed",
+ "acceptance.status.pending": "Waiting for verification",
+ "acceptance.status.planned": "Verification planned",
+ "acceptance.status.rejected": "Delivery rejected",
+ "acceptance.status.repairing": "Repair in progress",
+ "acceptance.status.verifying": "Verification in progress",
+ "acceptance.subject.document": "Document",
+ "acceptance.subject.task": "Task",
+ "acceptance.subject.topic": "Topic",
+ "acceptance.surface.other": "Other",
+ "acceptance.titleFallback": "Delivery acceptance",
+ "acceptance.viewFullReport": "View full report",
"badge.errored": "Check could not run",
"badge.failed": "Check failed",
"badge.passed": "Check passed",
diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.json
index fb6d8f40ed9..c48a77a8ff4 100644
--- a/locales/zh-CN/verify.json
+++ b/locales/zh-CN/verify.json
@@ -1,4 +1,91 @@
{
+ "acceptance.accept.exceptionsHint": "接受即表示你已知悉这些例外并愿意带着它们验收。",
+ "acceptance.accept.exceptionsTitle": "仍有 {{count}} 项例外未处理:",
+ "acceptance.accept.summary": "将「{{title}}」标记为已验收:全部验证轮次与证据将归档为验收依据。",
+ "acceptance.actionError": "验收状态更新失败,请重试。",
+ "acceptance.actions.accept": "接受交付",
+ "acceptance.actions.cancel": "取消",
+ "acceptance.actions.confirmAccept": "确认接受交付",
+ "acceptance.actions.confirmReject": "打回并发起下一轮",
+ "acceptance.actions.reject": "打回交付",
+ "acceptance.banner.accepted": "已验收 · {{time}} 由你确认接受交付",
+ "acceptance.banner.acceptedHint": "{{count}} 轮验证记录已归档为验收依据",
+ "acceptance.banner.clean": "{{count}} 轮验证全部通过,等待你的验收",
+ "acceptance.banner.decisionHint": "验证结论是建议,验收由你决定",
+ "acceptance.banner.exceptions": "验证完成,有 {{count}} 项例外等待你的判断",
+ "acceptance.banner.liveHint": "已完成项的证据可先行查看;验证结束后由你决定是否接受交付",
+ "acceptance.banner.rejected": "已打回",
+ "acceptance.banner.rejectedHint": "下一轮验证完成后将重新回到待验收",
+ "acceptance.banner.rejectedReason": "打回意见:{{reason}}",
+ "acceptance.checks.finalRoundHint": "最终结果与证据来自该轮,点击查看",
+ "acceptance.checks.fixed": "已修复",
+ "acceptance.checks.fixedHint": "第 {{round}} 轮失败 → 第 {{fixedRound}} 轮修复",
+ "acceptance.checks.introduced": "第 {{round}} 轮引入",
+ "acceptance.checks.introducedHint": "该检查在此轮首次出现,点击查看",
+ "acceptance.checks.iterated": "迭代 {{count}} 次",
+ "acceptance.checks.iteratedHint": "同一验收对象跨 {{count}} 轮迭代,以最后一轮为准;演进过程见「迭代历史」",
+ "acceptance.checks.iterationHistory": "迭代历史({{count}} 轮)",
+ "acceptance.checks.notRequired": "非阻断",
+ "acceptance.checks.notRequiredHint": "required = false:失败不阻止验收",
+ "acceptance.checks.rerun": "验证 {{count}} 轮",
+ "acceptance.checks.rerunHint": "同一检查项在 {{count}} 轮各验证一次,以最后一轮为准",
+ "acceptance.checks.subtitle": "{{count}} 项(跨 {{rounds}} 轮归并,每项展示最终结果与证据)",
+ "acceptance.checks.title": "验收检查清单",
+ "acceptance.detail.suggestion": "建议",
+ "acceptance.error.description": "请检查网络连接后重试。",
+ "acceptance.error.title": "无法加载验收信息",
+ "acceptance.evidence.file": "{{count}} 份文本证据",
+ "acceptance.evidence.image": "{{count}} 份图片证据",
+ "acceptance.evidence.video": "{{count}} 份视频证据",
+ "acceptance.filter.all": "全部 {{count}}",
+ "acceptance.filter.exception": "例外 {{count}}",
+ "acceptance.filter.fixed": "已修复 {{count}}",
+ "acceptance.group.collapseAll": "收起分组",
+ "acceptance.group.collapseItems": "收起本组检查项",
+ "acceptance.group.expandAll": "展开分组",
+ "acceptance.group.expandItems": "展开本组检查项",
+ "acceptance.group.passRatio": "{{passed}}/{{total}} 通过",
+ "acceptance.history.jump": "第 {{round}} 轮——点击在轮次审计中定位",
+ "acceptance.latestSummary": "最新报告摘要",
+ "acceptance.ledger.collapse": "收起轮次审计",
+ "acceptance.ledger.count": "{{count}} 轮",
+ "acceptance.ledger.description": "每轮是一次完整验证(verify run),左侧清单是跨轮归并后的最终态;完整执行史在这里追查。",
+ "acceptance.ledger.expand": "展开轮次审计",
+ "acceptance.ledger.latest": "最新",
+ "acceptance.ledger.stats": "{{passed}}/{{total}} 通过",
+ "acceptance.ledger.title": "轮次审计",
+ "acceptance.ledger.viewReport": "查看该轮报告",
+ "acceptance.reject.description": "打回不是留言:你的意见将作为输入,发起新一轮修复,完成后回到「待验收」。",
+ "acceptance.reject.placeholder": "说明打回原因,例如:深色模式需补截图证据……",
+ "acceptance.reportDrawer.title": "第 {{round}} 轮 · 交付验证报告",
+ "acceptance.requirementLabel": "验收要求",
+ "acceptance.round": "第 {{round}} 轮",
+ "acceptance.roundCount": "{{count}} 轮验证",
+ "acceptance.roundStatus.errored": "异常",
+ "acceptance.roundStatus.failed": "失败",
+ "acceptance.roundStatus.passed": "通过",
+ "acceptance.roundStatus.repairing": "修复中",
+ "acceptance.roundStatus.uncertain": "不确定",
+ "acceptance.roundStatus.verifying": "进行中",
+ "acceptance.stats.failed": "{{count}} 失败",
+ "acceptance.stats.notExecuted": "{{count}} 未执行",
+ "acceptance.stats.passed": "{{count}} 通过",
+ "acceptance.stats.uncertain": "{{count}} 不确定",
+ "acceptance.status.accepted": "交付已接受",
+ "acceptance.status.delivered": "等待你的决定",
+ "acceptance.status.errored": "验证未能运行",
+ "acceptance.status.failed": "验证未通过",
+ "acceptance.status.pending": "等待验证",
+ "acceptance.status.planned": "验证已计划",
+ "acceptance.status.rejected": "交付已打回",
+ "acceptance.status.repairing": "修复进行中",
+ "acceptance.status.verifying": "验证进行中",
+ "acceptance.subject.document": "文档",
+ "acceptance.subject.task": "任务",
+ "acceptance.subject.topic": "话题",
+ "acceptance.surface.other": "其他",
+ "acceptance.titleFallback": "交付验收",
+ "acceptance.viewFullReport": "查看完整报告",
"badge.errored": "检查无法运行",
"badge.failed": "检查未通过",
"badge.passed": "检查通过",
diff --git a/packages/const/src/verify.ts b/packages/const/src/verify.ts
index c0d60689d01..8feea722559 100644
--- a/packages/const/src/verify.ts
+++ b/packages/const/src/verify.ts
@@ -139,8 +139,9 @@ export const acceptanceStatuses = [
'planned',
'verifying',
'repairing',
- // Verification settled positively; waiting for the user's accept/reject —
- // the human decision closes the lifecycle, the verdict is a recommendation.
+ // Verification settled (passed OR failed); waiting for the user's
+ // accept/reject — the human decision closes the lifecycle, the verdict is a
+ // recommendation either way.
'delivered',
'accepted',
'rejected',
diff --git a/packages/database/src/models/__tests__/acceptance.test.ts b/packages/database/src/models/__tests__/acceptance.test.ts
new file mode 100644
index 00000000000..5f869b5be82
--- /dev/null
+++ b/packages/database/src/models/__tests__/acceptance.test.ts
@@ -0,0 +1,120 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { acceptances, topics, users, verifyRuns } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { AcceptanceModel } from '../acceptance';
+import { VerifyRunModel } from '../verifyRun';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'acceptance-test-user';
+const otherUserId = 'acceptance-test-other';
+const topicId = 'acceptance-test-topic';
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await serverDB.insert(topics).values([{ id: topicId, userId }]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(verifyRuns);
+ await serverDB.delete(acceptances);
+ await serverDB.delete(topics);
+ await serverDB.delete(users);
+});
+
+describe('AcceptanceModel', () => {
+ it('ensureForSubject creates once and converges on the same row', async () => {
+ const model = new AcceptanceModel(serverDB, userId);
+
+ const first = await model.ensureForSubject('topic', topicId, {
+ requirement: 'All checks green',
+ });
+ expect(first.status).toBe('pending');
+ expect(first.requirement).toBe('All checks green');
+
+ // Second ensure returns the SAME aggregate and never overwrites defaults.
+ const second = await model.ensureForSubject('topic', topicId, {
+ requirement: 'Different text',
+ });
+ expect(second.id).toBe(first.id);
+ expect(second.requirement).toBe('All checks green');
+ });
+
+ it('scopes subject lookup per owner', async () => {
+ const model = new AcceptanceModel(serverDB, userId);
+ await model.ensureForSubject('topic', topicId);
+
+ const otherModel = new AcceptanceModel(serverDB, otherUserId);
+ expect(await otherModel.findBySubject('topic', topicId)).toBeUndefined();
+ });
+
+ it('updateStatus stamps completedAt only on user-terminal statuses', async () => {
+ const model = new AcceptanceModel(serverDB, userId);
+ const row = await model.ensureForSubject('topic', topicId);
+
+ await model.updateStatus(row.id, 'delivered');
+ expect((await model.findById(row.id))?.completedAt).toBeNull();
+
+ await model.updateStatus(row.id, 'accepted');
+ expect((await model.findById(row.id))?.completedAt).toBeInstanceOf(Date);
+
+ // A new round re-opening the loop clears the completion stamp.
+ await model.updateStatus(row.id, 'verifying');
+ expect((await model.findById(row.id))?.completedAt).toBeNull();
+ });
+});
+
+describe('VerifyRunModel acceptance chain', () => {
+ it('attachToAcceptance assigns sequential round indexes', async () => {
+ const acceptanceModel = new AcceptanceModel(serverDB, userId);
+ const acceptance = await acceptanceModel.ensureForSubject('topic', topicId);
+
+ const runModel = new VerifyRunModel(serverDB, userId);
+ const first = await runModel.create({ source: 'agent-testing', title: 'round 1' });
+ const second = await runModel.create({ source: 'agent-testing', title: 'round 2' });
+
+ const attached1 = await runModel.attachToAcceptance(first.id, acceptance.id);
+ const attached2 = await runModel.attachToAcceptance(second.id, acceptance.id);
+ expect(attached1.roundIndex).toBe(1);
+ expect(attached2.roundIndex).toBe(2);
+
+ const rounds = await runModel.listByAcceptance(acceptance.id);
+ expect(rounds.map((r) => r.title)).toEqual(['round 1', 'round 2']);
+ });
+
+ it('setDecision records the user verdict with its detail', async () => {
+ const acceptanceModel = new AcceptanceModel(serverDB, userId);
+ const acceptance = await acceptanceModel.ensureForSubject('topic', topicId);
+
+ const runModel = new VerifyRunModel(serverDB, userId);
+ const run = await runModel.create({ source: 'agent-testing' });
+ await runModel.attachToAcceptance(run.id, acceptance.id);
+
+ await runModel.setDecision(run.id, 'reject', {
+ comment: 'dark mode needs a screenshot',
+ decidedAt: new Date().toISOString(),
+ decidedBy: userId,
+ });
+
+ const found = await runModel.findById(run.id);
+ expect(found?.userDecision).toBe('reject');
+ expect(found?.decisionDetail?.comment).toBe('dark mode needs a screenshot');
+ });
+
+ it('rejects attaching a run that is not owned by the caller', async () => {
+ const acceptanceModel = new AcceptanceModel(serverDB, userId);
+ const acceptance = await acceptanceModel.ensureForSubject('topic', topicId);
+
+ const otherRun = await new VerifyRunModel(serverDB, otherUserId).create({
+ source: 'agent-testing',
+ });
+
+ await expect(
+ new VerifyRunModel(serverDB, userId).attachToAcceptance(otherRun.id, acceptance.id),
+ ).rejects.toThrow('not found');
+ });
+});
diff --git a/packages/database/src/models/acceptance.ts b/packages/database/src/models/acceptance.ts
new file mode 100644
index 00000000000..652f5e1e389
--- /dev/null
+++ b/packages/database/src/models/acceptance.ts
@@ -0,0 +1,128 @@
+import type { AcceptanceStatus, AcceptanceSubjectType } from '@lobechat/types';
+import { and, desc, eq } from 'drizzle-orm';
+
+import type { AcceptanceItem, NewAcceptance } from '../schemas/verify';
+import { acceptances } from '../schemas/verify';
+import type { LobeChatDatabase } from '../type';
+import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
+
+/** Statuses a user's decision produced — sticky until a new round re-opens the loop. */
+const TERMINAL_ACCEPTANCE_STATUSES = new Set<AcceptanceStatus>(['accepted', 'rejected']);
+
+/**
+ * Owns the business-level acceptance aggregate (`acceptances`): one row per
+ * subject (task / topic / document) carrying the user-facing lifecycle state.
+ * The verify rounds chain onto it through `verify_runs.acceptance_id` +
+ * `round_index`; this model deliberately holds no round pointers — root /
+ * current / latest-report are all derived from that chain at read time.
+ */
+export class AcceptanceModel {
+ private readonly db: LobeChatDatabase;
+ private readonly userId: string;
+ private readonly workspaceId?: string;
+
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ this.db = db;
+ this.userId = userId;
+ this.workspaceId = workspaceId;
+ }
+
+ private ownership = () =>
+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, acceptances);
+
+ create = async (
+ params: Omit<NewAcceptance, 'userId' | 'workspaceId'>,
+ ): Promise<AcceptanceItem> => {
+ const [row] = await this.db
+ .insert(acceptances)
+ .values(buildWorkspacePayload({ userId: this.userId, workspaceId: this.workspaceId }, params))
+ .returning();
+ return row;
+ };
+
+ findById = async (id: string) => {
+ return this.db.query.acceptances.findFirst({
+ where: and(eq(acceptances.id, id), this.ownership()),
+ });
+ };
+
+ /** The (unique per scope) acceptance for a subject, or undefined when none yet. */
+ findBySubject = async (subjectType: AcceptanceSubjectType, subjectId: string) => {
+ return this.db.query.acceptances.findFirst({
+ where: and(
+ eq(acceptances.subjectType, subjectType),
+ eq(acceptances.subjectId, subjectId),
+ this.ownership(),
+ ),
+ });
+ };
+
+ /**
+ * Get (or lazily create) the acceptance aggregate for a subject. Upserts on
+ * the per-scope subject unique index so concurrent callers converge on one
+ * row; `defaults` only apply on first creation and never overwrite an
+ * existing aggregate.
+ */
+ ensureForSubject = async (
+ subjectType: AcceptanceSubjectType,
+ subjectId: string,
+ defaults?: Partial<Pick<NewAcceptance, 'config' | 'requirement'>>,
+ ): Promise<AcceptanceItem> => {
+ const existing = await this.findBySubject(subjectType, subjectId);
+ if (existing) return existing;
+
+ await this.db
+ .insert(acceptances)
+ .values(
+ buildWorkspacePayload(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ { subjectId, subjectType, ...defaults },
+ ),
+ )
+ // Conflict = another caller won the per-scope subject unique index race.
+ .onConflictDoNothing();
+
+ // Re-read so concurrent winners and this caller both return the canonical row.
+ return (await this.findBySubject(subjectType, subjectId))!;
+ };
+
+ /** Recent acceptances for the current user/workspace, newest first. */
+ query = async (limit = 50) => {
+ return this.db.query.acceptances.findMany({
+ limit,
+ orderBy: [desc(acceptances.createdAt)],
+ where: this.ownership(),
+ });
+ };
+
+ update = async (
+ id: string,
+ value: Partial<Pick<NewAcceptance, 'config' | 'metadata' | 'requirement' | 'visualRender'>>,
+ ): Promise<AcceptanceItem | undefined> => {
+ const [row] = await this.db
+ .update(acceptances)
+ .set(value)
+ .where(and(eq(acceptances.id, id), this.ownership()))
+ .returning();
+ return row;
+ };
+
+ /**
+ * Move the user-facing lifecycle state. `completedAt` is stamped when the
+ * user's decision closes the loop (accepted / rejected) and cleared when a
+ * new round re-opens it.
+ */
+ updateStatus = async (id: string, status: AcceptanceStatus): Promise<void> => {
+ await this.db
+ .update(acceptances)
+ .set({
+ completedAt: TERMINAL_ACCEPTANCE_STATUSES.has(status) ? new Date() : null,
+ status,
+ })
+ .where(and(eq(acceptances.id, id), this.ownership()));
+ };
+
+ delete = async (id: string) => {
+ return this.db.delete(acceptances).where(and(eq(acceptances.id, id), this.ownership()));
+ };
+}
diff --git a/packages/database/src/models/verifyCheckResult.ts b/packages/database/src/models/verifyCheckResult.ts
index 68802be849a..6dff9f3a7fa 100644
--- a/packages/database/src/models/verifyCheckResult.ts
+++ b/packages/database/src/models/verifyCheckResult.ts
@@ -120,6 +120,20 @@ export class VerifyCheckResultModel {
.orderBy(asc(verifyCheckResults.checkItemIndex));
};
+ /**
+ * All results across several verification rounds in one query — the
+ * acceptance union reads a whole round chain, so it must not fan out into a
+ * per-run query. Ordered by display index for stable downstream grouping.
+ */
+ listByRuns = async (verifyRunIds: string[]): Promise<VerifyCheckResultItem[]> => {
+ if (verifyRunIds.length === 0) return [];
+ return this.db
+ .select()
+ .from(verifyCheckResults)
+ .where(and(inArray(verifyCheckResults.verifyRunId, verifyRunIds), this.ownership()))
+ .orderBy(asc(verifyCheckResults.checkItemIndex));
+ };
+
update = async (id: string, value: Partial<Omit<VerifyCheckResultItem, 'id' | 'userId'>>) => {
return this.db
.update(verifyCheckResults)
diff --git a/packages/database/src/models/verifyEvidence.ts b/packages/database/src/models/verifyEvidence.ts
index 90bea5b1759..376c9a97056 100644
--- a/packages/database/src/models/verifyEvidence.ts
+++ b/packages/database/src/models/verifyEvidence.ts
@@ -1,5 +1,5 @@
import type { VerifyEvidence } from '@lobechat/types';
-import { and, asc, eq } from 'drizzle-orm';
+import { and, asc, eq, inArray } from 'drizzle-orm';
import { verifyCheckResults, verifyEvidence } from '../schemas/verify';
import type { LobeChatDatabase } from '../type';
@@ -11,6 +11,9 @@ type CreateVerifyEvidence = Omit<VerifyEvidence, 'id' | 'createdAt'>;
/** An evidence row annotated with the run-stable `checkItemId` of its result. */
export type VerifyEvidenceForRun = VerifyEvidence & { checkItemId: string };
+/** An evidence row annotated with both its check item and the round it came from. */
+export type VerifyEvidenceForRuns = VerifyEvidenceForRun & { verifyRunId: string };
+
export class VerifyEvidenceModel {
private readonly db: LobeChatDatabase;
private readonly userId: string;
@@ -86,6 +89,33 @@ export class VerifyEvidenceModel {
return rows.map((r) => ({ ...r.evidence, checkItemId: r.checkItemId }));
};
+ /**
+ * All evidence across several verification rounds in one query, each row
+ * carrying its result's `checkItemId` and the round (`verifyRunId`) it was
+ * captured in — the acceptance union joins a whole round chain at once.
+ */
+ listByRuns = async (verifyRunIds: string[]): Promise<VerifyEvidenceForRuns[]> => {
+ if (verifyRunIds.length === 0) return [];
+
+ const rows = await this.db
+ .select({
+ checkItemId: verifyCheckResults.checkItemId,
+ evidence: verifyEvidence,
+ verifyRunId: verifyCheckResults.verifyRunId,
+ })
+ .from(verifyEvidence)
+ .innerJoin(verifyCheckResults, eq(verifyEvidence.checkResultId, verifyCheckResults.id))
+ .where(and(inArray(verifyCheckResults.verifyRunId, verifyRunIds), this.ownership()))
+ .orderBy(asc(verifyEvidence.createdAt));
+
+ return rows.map((r) => ({
+ ...r.evidence,
+ checkItemId: r.checkItemId,
+ // The join filter guarantees a run id; the column is only nullable for legacy rows.
+ verifyRunId: r.verifyRunId!,
+ }));
+ };
+
delete = async (id: string) => {
return this.db.delete(verifyEvidence).where(and(eq(verifyEvidence.id, id), this.ownership()));
};
diff --git a/packages/database/src/models/verifyReport.ts b/packages/database/src/models/verifyReport.ts
index efe85b84ec3..f5db19042eb 100644
--- a/packages/database/src/models/verifyReport.ts
+++ b/packages/database/src/models/verifyReport.ts
@@ -1,5 +1,5 @@
import type { VerifyReport } from '@lobechat/types';
-import { and, eq } from 'drizzle-orm';
+import { and, eq, inArray } from 'drizzle-orm';
import { verifyReports, verifyRuns } from '../schemas/verify';
import type { LobeChatDatabase } from '../type';
@@ -88,6 +88,17 @@ export class VerifyReportModel {
});
};
+ /**
+ * The reports of several verification rounds in one query (at most one per
+ * run) — the acceptance ledger renders a whole round chain at once.
+ */
+ findByRuns = async (verifyRunIds: string[]) => {
+ if (verifyRunIds.length === 0) return [];
+ return this.db.query.verifyReports.findMany({
+ where: and(inArray(verifyReports.verifyRunId, verifyRunIds), this.ownership()),
+ });
+ };
+
update = async (id: string, value: Partial<Omit<VerifyReport, 'id'>>) => {
return this.db
.update(verifyReports)
diff --git a/packages/database/src/models/verifyRun.ts b/packages/database/src/models/verifyRun.ts
index e819f7ac4a7..a375c3475cc 100644
--- a/packages/database/src/models/verifyRun.ts
+++ b/packages/database/src/models/verifyRun.ts
@@ -1,5 +1,10 @@
-import type { VerifyCheckItem, VerifyRunSource, VerifyRunStatus } from '@lobechat/types';
-import { and, desc, eq, ilike, isNull, lt, or, sql } from 'drizzle-orm';
+import type {
+ VerifyCheckItem,
+ VerifyRunDecisionDetail,
+ VerifyRunSource,
+ VerifyRunStatus,
+} from '@lobechat/types';
+import { and, asc, desc, eq, ilike, isNull, lt, or, sql } from 'drizzle-orm';
import { agentOperations } from '../schemas/agentOperations';
import type { NewVerifyRun, VerifyRunItem } from '../schemas/verify';
@@ -200,6 +205,54 @@ export class VerifyRunModel {
return { items, nextCursor };
};
+ /** Every round chained onto an acceptance aggregate, in round order. */
+ listByAcceptance = async (acceptanceId: string): Promise<VerifyRunItem[]> => {
+ return this.db.query.verifyRuns.findMany({
+ orderBy: [asc(verifyRuns.roundIndex)],
+ where: and(eq(verifyRuns.acceptanceId, acceptanceId), this.ownership()),
+ });
+ };
+
+ /**
+ * Chain a run onto an acceptance as its next round. The round index is
+ * assigned inside the UPDATE from the chain's current max, so two concurrent
+ * attaches cannot read the same max; if they still collide, the
+ * `(acceptance_id, round_index)` unique index rejects the loser.
+ */
+ attachToAcceptance = async (runId: string, acceptanceId: string): Promise<VerifyRunItem> => {
+ const [run] = await this.db
+ .update(verifyRuns)
+ .set({
+ acceptanceId,
+ roundIndex: sql`(
+ SELECT COALESCE(MAX(${verifyRuns.roundIndex}), 0) + 1
+ FROM ${verifyRuns}
+ WHERE ${verifyRuns.acceptanceId} = ${acceptanceId}
+ )`,
+ })
+ .where(and(eq(verifyRuns.id, runId), this.ownership()))
+ .returning();
+
+ if (!run) throw new Error(`Verify run "${runId}" not found in the current workspace`);
+ return run;
+ };
+
+ /**
+ * Record the user's acceptance decision on THIS round (the human verdict that
+ * closes or re-opens the acceptance loop). Free-form verb by design — see the
+ * `user_decision` column comment.
+ */
+ setDecision = async (
+ runId: string,
+ userDecision: string,
+ decisionDetail?: VerifyRunDecisionDetail,
+ ): Promise<void> => {
+ await this.db
+ .update(verifyRuns)
+ .set({ decisionDetail, userDecision })
+ .where(and(eq(verifyRuns.id, runId), this.ownership()));
+ };
+
/** The verification session bound to an Agent Run, or undefined when none yet. */
findByOperation = async (operationId: string) => {
return this.db.query.verifyRuns.findFirst({
diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.ts
index 6d1336ad569..bc72a1b7045 100644
--- a/packages/locales/src/default/verify.ts
+++ b/packages/locales/src/default/verify.ts
@@ -1,4 +1,104 @@
export default {
+ 'acceptance.accept.exceptionsHint':
+ 'Accepting means you have seen these exceptions and take the delivery with them.',
+ 'acceptance.accept.exceptionsTitle': '{{count}} exception(s) still unresolved:',
+ 'acceptance.accept.summary':
+ 'Mark "{{title}}" as accepted: every verification round and its evidence is archived as the acceptance record.',
+ 'acceptance.actionError': 'The acceptance could not be updated. Try again.',
+ 'acceptance.actions.accept': 'Accept delivery',
+ 'acceptance.actions.cancel': 'Cancel',
+ 'acceptance.actions.confirmAccept': 'Confirm acceptance',
+ 'acceptance.actions.confirmReject': 'Reject and start the next round',
+ 'acceptance.actions.reject': 'Reject delivery',
+ 'acceptance.banner.accepted': 'Accepted · confirmed by you at {{time}}',
+ 'acceptance.banner.acceptedHint':
+ '{{count}} verification round(s) archived as the acceptance record',
+ 'acceptance.banner.clean': 'All {{count}} round(s) passed — awaiting your acceptance',
+ 'acceptance.banner.decisionHint':
+ 'The verdict is a recommendation; the acceptance decision is yours.',
+ 'acceptance.banner.exceptions':
+ 'Verification settled with {{count}} exception(s) for you to judge',
+ 'acceptance.banner.liveHint':
+ 'You can inspect finished checks now; the decision comes once the round settles.',
+ 'acceptance.banner.rejected': 'Rejected',
+ 'acceptance.banner.rejectedHint':
+ 'The next verification round re-opens this acceptance when it lands.',
+ 'acceptance.banner.rejectedReason': 'Reason: {{reason}}',
+ 'acceptance.checks.finalRoundHint':
+ 'The final result and evidence come from this round — click to locate it.',
+ 'acceptance.checks.fixed': 'Fixed',
+ 'acceptance.checks.fixedHint': 'Failed in round {{round}} → fixed in round {{fixedRound}}.',
+ 'acceptance.checks.introduced': 'Added in round {{round}}',
+ 'acceptance.checks.introducedHint':
+ 'This check first appeared in that round — click to locate it.',
+ 'acceptance.checks.iterated': 'Iterated {{count}}×',
+ 'acceptance.checks.iteratedHint':
+ 'The same acceptance concern evolved across {{count}} rounds; the last round stands. See the iteration history for the evolution.',
+ 'acceptance.checks.iterationHistory': 'Iteration history ({{count}} rounds)',
+ 'acceptance.checks.notRequired': 'Non-blocking',
+ 'acceptance.checks.notRequiredHint': 'required = false: failing this does not block acceptance.',
+ 'acceptance.checks.rerun': 'Verified {{count}} rounds',
+ 'acceptance.checks.rerunHint': 'The same check ran in {{count}} rounds; the last round stands.',
+ 'acceptance.checks.subtitle': '{{count}} check(s) merged across {{rounds}} round(s)',
+ 'acceptance.checks.title': 'Acceptance checks',
+ 'acceptance.detail.suggestion': 'Suggestion',
+ 'acceptance.error.description': 'Check your connection and try loading this acceptance again.',
+ 'acceptance.error.title': 'Unable to load acceptance',
+ 'acceptance.evidence.file': '{{count}} text evidence item(s)',
+ 'acceptance.evidence.image': '{{count}} image evidence item(s)',
+ 'acceptance.evidence.video': '{{count}} video evidence item(s)',
+ 'acceptance.filter.all': 'All {{count}}',
+ 'acceptance.filter.exception': 'Exceptions {{count}}',
+ 'acceptance.filter.fixed': 'Fixed {{count}}',
+ 'acceptance.group.collapseAll': 'Collapse groups',
+ 'acceptance.group.collapseItems': 'Collapse checks in this group',
+ 'acceptance.group.expandAll': 'Expand groups',
+ 'acceptance.group.expandItems': 'Expand checks in this group',
+ 'acceptance.group.passRatio': '{{passed}}/{{total}} passed',
+ 'acceptance.history.jump': 'Round {{round}} — click to locate it in the ledger',
+ 'acceptance.latestSummary': 'Latest report summary',
+ 'acceptance.ledger.collapse': 'Collapse the round ledger',
+ 'acceptance.ledger.count': '{{count}} round(s)',
+ 'acceptance.ledger.description':
+ 'Each round is one full verification run; the main list is the cross-round merge. Trace the full history here.',
+ 'acceptance.ledger.expand': 'Expand the round ledger',
+ 'acceptance.ledger.latest': 'Latest',
+ 'acceptance.ledger.stats': '{{passed}}/{{total}} passed',
+ 'acceptance.ledger.title': 'Round ledger',
+ 'acceptance.ledger.viewReport': 'View round report',
+ 'acceptance.reject.description':
+ 'Your reason becomes input for the next repair round; this is not a passive comment.',
+ 'acceptance.reject.placeholder':
+ 'Describe what must change before this delivery can be accepted.',
+ 'acceptance.reportDrawer.title': 'Round {{round}} · verification report',
+ 'acceptance.requirementLabel': 'Acceptance bar',
+ 'acceptance.round': 'Round {{round}}',
+ 'acceptance.roundCount': '{{count}} verification round(s)',
+ 'acceptance.roundStatus.errored': 'Errored',
+ 'acceptance.roundStatus.failed': 'Failed',
+ 'acceptance.roundStatus.passed': 'Passed',
+ 'acceptance.roundStatus.repairing': 'Repairing',
+ 'acceptance.roundStatus.uncertain': 'Uncertain',
+ 'acceptance.roundStatus.verifying': 'In progress',
+ 'acceptance.stats.failed': '{{count}} failed',
+ 'acceptance.stats.notExecuted': '{{count}} not executed',
+ 'acceptance.stats.passed': '{{count}} passed',
+ 'acceptance.stats.uncertain': '{{count}} uncertain',
+ 'acceptance.status.accepted': 'Delivery accepted',
+ 'acceptance.status.delivered': 'Ready for your decision',
+ 'acceptance.status.errored': 'Verification could not run',
+ 'acceptance.status.failed': 'Verification failed',
+ 'acceptance.status.pending': 'Waiting for verification',
+ 'acceptance.status.planned': 'Verification planned',
+ 'acceptance.status.rejected': 'Delivery rejected',
+ 'acceptance.status.repairing': 'Repair in progress',
+ 'acceptance.status.verifying': 'Verification in progress',
+ 'acceptance.subject.document': 'Document',
+ 'acceptance.subject.task': 'Task',
+ 'acceptance.subject.topic': 'Topic',
+ 'acceptance.surface.other': 'Other',
+ 'acceptance.titleFallback': 'Delivery acceptance',
+ 'acceptance.viewFullReport': 'View full report',
'report.actions.copyLink': 'Copy link',
'report.actions.copyLinkSuccess': 'Link copied',
'report.actions.openInBrowser': 'Open in browser',
diff --git a/packages/types/src/verify.ts b/packages/types/src/verify.ts
index 80089a60626..84355ab37b8 100644
--- a/packages/types/src/verify.ts
+++ b/packages/types/src/verify.ts
@@ -56,9 +56,9 @@ export type AcceptanceSubjectType = 'task' | 'topic' | 'document';
* verify vocabulary (`passed` / `failed`); the aggregate exposes the user's
* outcome language (`accepted` / `rejected`).
*
- * `delivered`: verification settled positively and the aggregate now waits for
- * the user's accept/reject — the human decision closes the lifecycle, the
- * verifier's verdict is only a recommendation.
+ * `delivered`: verification settled (passed OR failed) and the aggregate now
+ * waits for the user's accept/reject — the human decision closes the lifecycle,
+ * the verifier's verdict is only a recommendation either way.
*/
export type AcceptanceStatus =
| 'pending'
@@ -315,6 +315,12 @@ export interface VerifyRunMetadata {
* `sourceRubricId` are provenance pointers only.
*/
export interface VerifyCheckItem {
+ /**
+ * Grouping key for the acceptance union view (a page section / feature
+ * domain, authored by the harness that writes the plan). Free-form label;
+ * checks without one fall back to surface grouping.
+ */
+ category?: string;
/** One-sentence summary of what this check verifies. */
description?: string;
/** The document holding the detailed judging instruction / rule body, if any. */
@@ -331,6 +337,12 @@ export interface VerifyCheckItem {
sourceCriterionId?: string | null;
/** Provenance: the rubric (group) this item came in through, or null. */
sourceRubricId?: string | null;
+ /**
+ * Generation declaration: the older check-item ids THIS item replaces. The
+ * acceptance union folds the superseded items into this item's iteration
+ * timeline instead of listing semantically-dead checks side by side.
+ */
+ supersedes?: string[];
title: string;
verifierConfig: Record<string, unknown>;
verifierType: VerifierType;
@@ -355,6 +367,14 @@ export interface VerifyAgentPlanConfig {
method?: string;
/** Evidence media this item must produce — gated, not decorative. */
requiredEvidence?: RequiredEvidenceSpec[];
+ /**
+ * The product surface THIS item was exercised on — the acceptance union view
+ * groups checks by it. Optional and per-item on purpose: the run-level
+ * `context.surfaces` records where the round ran as a whole, while one round
+ * routinely mixes web + cli + desktop checks. Same closed set as
+ * {@link VerifySurface}; a missing value renders ungrouped.
+ */
+ surface?: VerifySurface;
}
/**
diff --git a/src/features/Verify/Acceptance/CheckList.tsx b/src/features/Verify/Acceptance/CheckList.tsx
new file mode 100644
index 00000000000..667d05107fe
--- /dev/null
+++ b/src/features/Verify/Acceptance/CheckList.tsx
@@ -0,0 +1,630 @@
+'use client';
+
+import { ActionIcon, Flexbox, Icon, Image, Tag, Text, Tooltip } from '@lobehub/ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import {
+ CheckCircle2,
+ ChevronRight,
+ ChevronsDownUp,
+ ChevronsUpDown,
+ CircleDashed,
+ FileText,
+ Film,
+ HelpCircle,
+ Images,
+ Repeat,
+ Wrench,
+ XCircle,
+} from 'lucide-react';
+import { Fragment, memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { AcceptanceBundle } from '@/services/verify';
+
+export type AcceptanceCheck = AcceptanceBundle['checks'][number];
+export type AcceptanceCheckState = AcceptanceCheck['state'];
+type AcceptanceEvidence = AcceptanceCheck['evidence'][number];
+
+/** Unresolved-first ordering — exceptions are what the decision hinges on. */
+const SEVERITY: Record<AcceptanceCheckState, number> = {
+ failed: 0,
+ not_executed: 2,
+ passed: 3,
+ uncertain: 1,
+};
+
+const STATE_META: Record<AcceptanceCheckState, { color: string; icon: typeof CheckCircle2 }> = {
+ failed: { color: cssVar.colorError, icon: XCircle },
+ not_executed: { color: cssVar.colorTextQuaternary, icon: CircleDashed },
+ passed: { color: cssVar.colorSuccess, icon: CheckCircle2 },
+ uncertain: { color: cssVar.colorWarning, icon: HelpCircle },
+};
+
+export const isException = (check: AcceptanceCheck) =>
+ check.state === 'failed' || check.state === 'uncertain';
+
+const VISUAL_EVIDENCE = new Set(['gif', 'screenshot', 'video']);
+
+const isVisual = (item: AcceptanceEvidence) =>
+ Boolean(item.fileUrl) && VISUAL_EVIDENCE.has(item.type);
+
+export const hasVisualEvidence = (check: AcceptanceCheck) => check.evidence.some(isVisual);
+
+const styles = createStaticStyles(({ css }) => ({
+ caption: css`
+ align-self: center;
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ chip: css`
+ padding-inline: 6px;
+ border-radius: 4px;
+
+ font-size: 11px;
+ line-height: 18px;
+ color: ${cssVar.colorTextTertiary};
+ white-space: nowrap;
+
+ background: ${cssVar.colorFillTertiary};
+ `,
+ chipClickable: css`
+ cursor: pointer;
+
+ &:hover {
+ color: ${cssVar.colorText};
+ background: ${cssVar.colorFillSecondary};
+ }
+ `,
+ descClamp: css`
+ overflow: hidden;
+ display: -webkit-box;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 2;
+ `,
+ evidenceImage: css`
+ overflow: hidden;
+
+ width: fit-content;
+ max-width: 100%;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+ `,
+ evidenceText: css`
+ overflow: auto;
+
+ max-height: 200px;
+ padding-block: 8px;
+ padding-inline: 12px;
+ border-radius: ${cssVar.borderRadius};
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 12px;
+ white-space: pre-wrap;
+
+ background: ${cssVar.colorFillQuaternary};
+ `,
+ groupCard: css`
+ overflow: hidden;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+ background: ${cssVar.colorBgContainer};
+ `,
+ groupHeader: css`
+ cursor: pointer;
+ padding-block: 10px;
+ padding-inline: 16px;
+ background: ${cssVar.colorFillQuaternary};
+ `,
+ historyToggle: css`
+ cursor: pointer;
+
+ display: inline-flex;
+ gap: 4px;
+ align-items: center;
+
+ width: fit-content;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+
+ &:hover {
+ color: ${cssVar.colorText};
+ }
+ `,
+ row: css`
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+ rowHeader: css`
+ cursor: pointer;
+ padding-block: 12px;
+ padding-inline: 16px;
+
+ &:hover {
+ background: ${cssVar.colorFillQuaternary};
+ }
+ `,
+ stepDot: css`
+ flex: none;
+
+ width: 9px;
+ height: 9px;
+ margin-block-start: 5px;
+ border: 2px solid;
+ border-radius: 50%;
+
+ background: ${cssVar.colorBgContainer};
+ `,
+ stepRail: css`
+ flex: 1;
+ width: 1px;
+ margin-block-start: 6px;
+ background: ${cssVar.colorBorderSecondary};
+ `,
+ titleEllipsis: css`
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+}));
+
+/** Evidence media counts for the collapsed row's right-side badges. */
+const evidenceCounts = (evidence: AcceptanceEvidence[]) => {
+ const counts = { file: 0, image: 0, video: 0 };
+ for (const item of evidence) {
+ if (item.type === 'video' && item.fileUrl) counts.video += 1;
+ else if (isVisual(item)) counts.image += 1;
+ else counts.file += 1;
+ }
+ return counts;
+};
+
+const EVIDENCE_BADGES = [
+ { icon: Images, key: 'image', labelKey: 'acceptance.evidence.image' },
+ { icon: Film, key: 'video', labelKey: 'acceptance.evidence.video' },
+ { icon: FileText, key: 'file', labelKey: 'acceptance.evidence.file' },
+] as const;
+
+/** A filename is not a caption — only descriptive text renders under the artifact. */
+const isFilename = (value: string | null | undefined) =>
+ !value || /^[\w.-]+\.(?:gif|jpe?g|mp4|png|webm|webp)$/i.test(value);
+
+const EvidenceList = memo<{ evidence: AcceptanceEvidence[] }>(({ evidence }) => {
+ const sorted = [...evidence].sort((a, b) => (isVisual(b) ? 1 : 0) - (isVisual(a) ? 1 : 0));
+ if (sorted.length === 0) return null;
+
+ return (
+ <Flexbox gap={12}>
+ {sorted.map((item) => {
+ const caption = !isFilename(item.description) && (
+ <span className={styles.caption}>{item.description}</span>
+ );
+ if (item.fileUrl && item.type === 'video')
+ return (
+ <Flexbox gap={4} key={item.id} style={{ maxWidth: '100%', width: 'fit-content' }}>
+ <video
+ controls
+ src={item.fileUrl}
+ style={{ borderRadius: 8, maxHeight: 360, maxWidth: '100%', width: 'auto' }}
+ />
+ {caption}
+ </Flexbox>
+ );
+ if (item.fileUrl && VISUAL_EVIDENCE.has(item.type))
+ return (
+ <Flexbox gap={4} key={item.id} style={{ maxWidth: '100%', width: 'fit-content' }}>
+ <Flexbox className={styles.evidenceImage}>
+ <Image
+ alt={item.description ?? item.fileName ?? item.type}
+ loading={'lazy'}
+ src={item.fileUrl}
+ style={{ maxWidth: '100%' }}
+ />
+ </Flexbox>
+ {caption}
+ </Flexbox>
+ );
+ if (item.content)
+ return (
+ <Flexbox gap={4} key={item.id}>
+ <div className={styles.evidenceText}>{item.content}</div>
+ {caption}
+ </Flexbox>
+ );
+ return null;
+ })}
+ </Flexbox>
+ );
+});
+
+/**
+ * The iteration-history timeline (newest first): each executed step's round,
+ * the wording THAT round used, and its evidence — how the check evolved.
+ */
+const IterationTimeline = memo<{
+ check: AcceptanceCheck;
+ onRound: (round: number) => void;
+}>(({ check, onRound }) => {
+ const { t } = useTranslation('verify');
+ const steps = [...check.timeline].reverse();
+
+ return (
+ <Flexbox>
+ {steps.map((step, index) => {
+ const isCurrent = index === 0;
+ const isLast = index === steps.length - 1;
+ const stateColor =
+ {
+ failed: cssVar.colorError,
+ passed: cssVar.colorSuccess,
+ uncertain: cssVar.colorWarning,
+ }[step.state as string] ?? cssVar.colorTextQuaternary;
+
+ return (
+ <Flexbox horizontal gap={12} key={`${step.roundIndex}-${step.resultId}`}>
+ <Flexbox align={'center'} style={{ flex: 'none', width: 9 }}>
+ <span
+ className={styles.stepDot}
+ style={{
+ background: isCurrent ? stateColor : cssVar.colorBgContainer,
+ borderColor: isCurrent ? stateColor : cssVar.colorTextQuaternary,
+ }}
+ />
+ {!isLast && <div className={styles.stepRail} />}
+ </Flexbox>
+ <Flexbox flex={1} gap={6} style={{ minWidth: 0, paddingBlockEnd: isLast ? 0 : 20 }}>
+ <Tooltip title={t('acceptance.history.jump', { round: step.roundIndex })}>
+ <Text
+ strong
+ style={{ cursor: 'pointer', fontSize: 12, lineHeight: '19px' }}
+ onClick={() => onRound(step.roundIndex)}
+ >
+ {t('acceptance.round', { round: step.roundIndex })}
+ </Text>
+ </Tooltip>
+ <Text style={{ fontSize: 12 }}>{step.title}</Text>
+ {step.evidence.length > 0 && (
+ <Flexbox horizontal gap={8} wrap={'wrap'}>
+ {step.evidence.map((item) =>
+ item.fileUrl && VISUAL_EVIDENCE.has(item.type) ? (
+ <Flexbox className={styles.evidenceImage} key={item.id}>
+ <Image
+ alt={item.description ?? item.type}
+ loading={'lazy'}
+ src={item.fileUrl}
+ style={{ maxHeight: 160, maxWidth: 280, width: 'auto' }}
+ />
+ </Flexbox>
+ ) : item.content ? (
+ <div
+ className={styles.evidenceText}
+ key={item.id}
+ style={{ maxHeight: 120, maxWidth: 420 }}
+ >
+ {item.content}
+ </div>
+ ) : null,
+ )}
+ </Flexbox>
+ )}
+ </Flexbox>
+ </Flexbox>
+ );
+ })}
+ {check.result?.suggestion && (
+ <Flexbox horizontal gap={12} style={{ marginBlockStart: 12 }}>
+ <Text fontSize={12} style={{ flex: 'none', minWidth: 64 }} type={'secondary'}>
+ {t('acceptance.detail.suggestion')}
+ </Text>
+ <Text fontSize={12} type={'secondary'}>
+ {check.result.suggestion}
+ </Text>
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+});
+
+const CheckRow = memo<{
+ check: AcceptanceCheck;
+ expanded: boolean;
+ onRound: (round: number) => void;
+ onToggle: () => void;
+}>(({ check, expanded, onRound, onToggle }) => {
+ const { t } = useTranslation('verify');
+ // The judging narrative stays collapsed: level one is title + evidence.
+ const [historyOpen, setHistoryOpen] = useState(false);
+ const meta = STATE_META[check.state];
+ const counts = evidenceCounts(check.evidence);
+
+ return (
+ <Flexbox className={styles.row}>
+ <Flexbox horizontal align={'center'} className={styles.rowHeader} gap={10} onClick={onToggle}>
+ <Icon color={meta.color} icon={meta.icon} size={16} />
+ <Flexbox
+ horizontal
+ align={'center'}
+ flex={1}
+ gap={8}
+ style={{ minWidth: 0 }}
+ wrap={expanded ? 'wrap' : 'nowrap'}
+ >
+ <Text
+ className={expanded ? undefined : styles.titleEllipsis}
+ style={{ fontSize: 13, minWidth: 0 }}
+ >
+ {check.title}
+ </Text>
+ {!check.required && (
+ <Tooltip title={t('acceptance.checks.notRequiredHint')}>
+ <Tag size={'small'}>{t('acceptance.checks.notRequired')}</Tag>
+ </Tooltip>
+ )}
+ </Flexbox>
+ <Flexbox horizontal align={'center'} gap={6}>
+ {EVIDENCE_BADGES.map(({ icon, key, labelKey }) =>
+ counts[key] ? (
+ <Tooltip key={key} title={t(labelKey, { count: counts[key] })}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={3}
+ style={{ color: cssVar.colorTextTertiary, fontSize: 11 }}
+ >
+ <Icon icon={icon} size={13} />
+ {counts[key] > 1 ? counts[key] : null}
+ </Flexbox>
+ </Tooltip>
+ ) : null,
+ )}
+ {check.revisions > 1 && (
+ <Tooltip
+ title={
+ check.titleChanged
+ ? t('acceptance.checks.iteratedHint', { count: check.revisions })
+ : t('acceptance.checks.rerunHint', { count: check.revisions })
+ }
+ >
+ <span className={styles.chip}>
+ <Icon icon={Repeat} size={10} />{' '}
+ {check.titleChanged
+ ? t('acceptance.checks.iterated', { count: check.revisions })
+ : t('acceptance.checks.rerun', { count: check.revisions })}
+ </span>
+ </Tooltip>
+ )}
+ {check.fixed && (
+ <Tooltip
+ title={t('acceptance.checks.fixedHint', {
+ fixedRound: check.resultRound,
+ round: check.introducedAtRound,
+ })}
+ >
+ <span className={styles.chip}>
+ <Icon icon={Wrench} size={10} /> {t('acceptance.checks.fixed')}
+ </span>
+ </Tooltip>
+ )}
+ {check.resultRound !== undefined &&
+ check.resultRound !== null &&
+ check.introducedAtRound !== check.resultRound && (
+ <Tooltip title={t('acceptance.checks.introducedHint')}>
+ <span
+ className={cx(styles.chip, styles.chipClickable)}
+ onClick={(event) => {
+ event.stopPropagation();
+ onRound(check.introducedAtRound);
+ }}
+ >
+ {t('acceptance.checks.introduced', { round: check.introducedAtRound })}
+ </span>
+ </Tooltip>
+ )}
+ {check.resultRound !== undefined && check.resultRound !== null && (
+ <Tooltip title={t('acceptance.checks.finalRoundHint')}>
+ <span
+ className={cx(styles.chip, styles.chipClickable)}
+ onClick={(event) => {
+ event.stopPropagation();
+ onRound(check.resultRound!);
+ }}
+ >
+ {t('acceptance.round', { round: check.resultRound })}
+ </span>
+ </Tooltip>
+ )}
+ <Icon
+ color={cssVar.colorTextQuaternary}
+ icon={ChevronRight}
+ size={14}
+ style={{ transform: expanded ? 'rotate(90deg)' : 'none', transition: 'transform 0.2s' }}
+ />
+ </Flexbox>
+ </Flexbox>
+
+ {expanded && (
+ <Flexbox gap={10} paddingBlock={'0 14px'} paddingInline={16}>
+ {check.result?.toulmin?.evidence && (
+ <Text className={styles.descClamp} fontSize={12} type={'secondary'}>
+ {check.result.toulmin.evidence}
+ </Text>
+ )}
+ <EvidenceList evidence={check.evidence} />
+
+ {check.revisions > 1 && (
+ <span className={styles.historyToggle} onClick={() => setHistoryOpen((open) => !open)}>
+ <Icon
+ icon={ChevronRight}
+ size={12}
+ style={{
+ transform: historyOpen ? 'rotate(90deg)' : 'none',
+ transition: 'transform 0.2s',
+ }}
+ />
+ {t('acceptance.checks.iterationHistory', { count: check.revisions })}
+ </span>
+ )}
+ {historyOpen && check.revisions > 1 && (
+ <IterationTimeline check={check} onRound={onRound} />
+ )}
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+});
+
+export type CheckFilter = 'all' | 'exception' | 'fixed';
+
+interface CheckGroup {
+ checks: AcceptanceCheck[];
+ key: string;
+ label: string;
+}
+
+/**
+ * Group by the harness-authored `category`, falling back to the product
+ * surface, then a catch-all — familiar sections over storage taxonomy (P-14).
+ */
+export const groupChecks = (
+ checks: AcceptanceCheck[],
+ surfaceLabel: (surface: NonNullable<AcceptanceCheck['surface']>) => string,
+ otherLabel: string,
+): CheckGroup[] => {
+ const groups = new Map<string, CheckGroup>();
+ for (const check of checks) {
+ const key = check.category ?? (check.surface ? `surface:${check.surface}` : 'other');
+ const label = check.category ?? (check.surface ? surfaceLabel(check.surface) : otherLabel);
+ const group = groups.get(key) ?? { checks: [], key, label };
+ group.checks.push(check);
+ groups.set(key, group);
+ }
+ return [...groups.values()];
+};
+
+interface CheckListProps {
+ checks: AcceptanceCheck[];
+ collapsedGroups: Set<string>;
+ expanded: Set<string>;
+ filter: CheckFilter;
+ onRound: (round: number) => void;
+ onToggleGroup: (key: string) => void;
+ onToggleGroupItems: (ids: string[], open: boolean) => void;
+ onToggleItem: (id: string) => void;
+}
+
+/** The union check list: one joined card, collapsible business groups. */
+const CheckList = memo<CheckListProps>(
+ ({
+ checks,
+ collapsedGroups,
+ expanded,
+ filter,
+ onRound,
+ onToggleGroup,
+ onToggleGroupItems,
+ onToggleItem,
+ }) => {
+ const { t } = useTranslation('verify');
+
+ const visible = (check: AcceptanceCheck) => {
+ if (filter === 'exception') return isException(check);
+ if (filter === 'fixed') return check.fixed;
+ return true;
+ };
+
+ const groups = groupChecks(
+ checks,
+ (surface) => t(`report.surface.${surface}`),
+ t('acceptance.surface.other'),
+ )
+ .map((group) => ({
+ ...group,
+ rows: group.checks
+ .filter(visible)
+ .sort(
+ (a, b) =>
+ SEVERITY[a.state] - SEVERITY[b.state] ||
+ (hasVisualEvidence(b) ? 1 : 0) - (hasVisualEvidence(a) ? 1 : 0) ||
+ a.introducedAtRound - b.introducedAtRound,
+ ),
+ }))
+ .filter((group) => group.rows.length > 0);
+
+ return (
+ <Flexbox className={styles.groupCard}>
+ {groups.map(({ checks: groupChecks_, key, label, rows }, groupIndex) => {
+ const passed = groupChecks_.filter((check) => check.state === 'passed').length;
+ const collapsed = collapsedGroups.has(key);
+ const anyItemOpen = rows.some((check) => expanded.has(check.id));
+
+ return (
+ <Fragment key={key}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.groupHeader}
+ gap={8}
+ style={{
+ borderBlockStart:
+ groupIndex > 0 ? `1px solid ${cssVar.colorBorderSecondary}` : 'none',
+ }}
+ onClick={() => onToggleGroup(key)}
+ >
+ <Text strong style={{ fontSize: 13 }}>
+ {label}
+ </Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t('acceptance.group.passRatio', { passed, total: groupChecks_.length })}
+ </Text>
+ <Flexbox flex={1} />
+ {collapsed ? (
+ // Fixed-size placeholder keeps the header height stable across toggles.
+ <div style={{ height: 24, width: 24 }} />
+ ) : (
+ <ActionIcon
+ icon={anyItemOpen ? ChevronsDownUp : ChevronsUpDown}
+ size={'small'}
+ title={
+ anyItemOpen
+ ? t('acceptance.group.collapseItems')
+ : t('acceptance.group.expandItems')
+ }
+ onClick={(event) => {
+ event.stopPropagation();
+ onToggleGroupItems(
+ rows.map((check) => check.id),
+ !anyItemOpen,
+ );
+ }}
+ />
+ )}
+ <Icon
+ color={cssVar.colorTextQuaternary}
+ icon={ChevronRight}
+ size={14}
+ style={{
+ transform: collapsed ? 'none' : 'rotate(90deg)',
+ transition: 'transform 0.2s',
+ }}
+ />
+ </Flexbox>
+ {!collapsed &&
+ rows.map((check) => (
+ <CheckRow
+ check={check}
+ expanded={expanded.has(check.id)}
+ key={check.id}
+ onRound={onRound}
+ onToggle={() => onToggleItem(check.id)}
+ />
+ ))}
+ </Fragment>
+ );
+ })}
+ </Flexbox>
+ );
+ },
+);
+
+CheckList.displayName = 'AcceptanceCheckList';
+
+export default CheckList;
diff --git a/src/features/Verify/Acceptance/LedgerPanel.tsx b/src/features/Verify/Acceptance/LedgerPanel.tsx
new file mode 100644
index 00000000000..6a532c95fda
--- /dev/null
+++ b/src/features/Verify/Acceptance/LedgerPanel.tsx
@@ -0,0 +1,161 @@
+'use client';
+
+import { ActionIcon, Flexbox, Icon, Text } from '@lobehub/ui';
+import { Button } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import dayjs from 'dayjs';
+import {
+ CheckCircle2,
+ CircleAlert,
+ FileClock,
+ FileText,
+ HelpCircle,
+ Loader2,
+ PanelRightClose,
+ Wrench,
+ XCircle,
+} from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { AcceptanceBundle } from '@/services/verify';
+
+export type AcceptanceRound = AcceptanceBundle['rounds'][number];
+
+const styles = createStaticStyles(({ css }) => ({
+ round: css`
+ padding-block: 10px;
+ padding-inline: 12px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadius};
+
+ transition: box-shadow 0.2s ease;
+ `,
+ roundActive: css`
+ border-color: ${cssVar.colorPrimary};
+ box-shadow: 0 0 0 2px ${cssVar.colorPrimaryBg};
+ `,
+}));
+
+const STATUS_META: Record<string, { color: string; icon: typeof CheckCircle2 }> = {
+ errored: { color: cssVar.colorWarning, icon: CircleAlert },
+ failed: { color: cssVar.colorError, icon: XCircle },
+ passed: { color: cssVar.colorSuccess, icon: CheckCircle2 },
+ repairing: { color: cssVar.colorInfo, icon: Wrench },
+ uncertain: { color: cssVar.colorWarning, icon: HelpCircle },
+ verifying: { color: cssVar.colorInfo, icon: Loader2 },
+};
+
+/** The round's settled state for the ledger — report verdict beats a null rollup. */
+const roundStatus = (round: AcceptanceRound): string => {
+ const status = round.run.status;
+ if (status === 'passed' || status === 'failed' || status === 'errored') return status;
+ if (status === 'repairing' || status === 'verifying') return status;
+ return round.report?.verdict ?? (round.report ? 'passed' : 'verifying');
+};
+
+interface LedgerPanelProps {
+ highlight: number | null;
+ onCollapse: () => void;
+ onOpenReport: (round: AcceptanceRound) => void;
+ rounds: AcceptanceRound[];
+}
+
+/**
+ * The execution history, demoted to an audit side panel (P-13): each round is a
+ * full verify run; the main list is the cross-round merge. Newest round first —
+ * the latest attempt is the one under judgment.
+ */
+const LedgerPanel = memo<LedgerPanelProps>(({ highlight, onCollapse, onOpenReport, rounds }) => {
+ const { t } = useTranslation('verify');
+ const latestIndex = rounds.at(-1)?.run.roundIndex;
+
+ return (
+ <Flexbox gap={12} padding={16}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Icon color={cssVar.colorTextSecondary} icon={FileClock} size={16} />
+ <Text strong style={{ fontSize: 13 }}>
+ {t('acceptance.ledger.title')}
+ </Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t('acceptance.ledger.count', { count: rounds.length })}
+ </Text>
+ <Flexbox flex={1} />
+ <ActionIcon
+ icon={PanelRightClose}
+ size={'small'}
+ title={t('acceptance.ledger.collapse')}
+ onClick={onCollapse}
+ />
+ </Flexbox>
+ <Text fontSize={12} type={'secondary'}>
+ {t('acceptance.ledger.description')}
+ </Text>
+ {[...rounds].reverse().map((round) => {
+ const status = roundStatus(round);
+ const meta = STATUS_META[status] ?? STATUS_META.verifying;
+ const stats =
+ round.report?.totalChecks != null
+ ? t('acceptance.ledger.stats', {
+ passed: round.report.passedChecks ?? 0,
+ total: round.report.totalChecks,
+ })
+ : null;
+ const commit = (round.run.context as { commit?: string } | null)?.commit;
+
+ return (
+ <Flexbox
+ className={cx(styles.round, highlight === round.run.roundIndex && styles.roundActive)}
+ gap={6}
+ key={round.run.id}
+ >
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text strong style={{ fontSize: 13 }}>
+ {t('acceptance.round', { round: round.run.roundIndex })}
+ </Text>
+ {round.run.roundIndex === latestIndex && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('acceptance.ledger.latest')}
+ </Text>
+ )}
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={4}
+ style={{ color: meta.color, fontSize: 12 }}
+ >
+ <Icon icon={meta.icon} size={13} />
+ {t(`acceptance.roundStatus.${status}`, { defaultValue: status })}
+ </Flexbox>
+ <Flexbox flex={1} />
+ <Text fontSize={12} type={'secondary'}>
+ {dayjs(round.run.createdAt).format('MM-DD HH:mm')}
+ </Text>
+ </Flexbox>
+ {round.run.title && (
+ <Text fontSize={12} style={{ lineHeight: 1.5 }} type={'secondary'}>
+ {round.run.title}
+ </Text>
+ )}
+ {(stats || commit) && (
+ <Text fontSize={12} type={'secondary'}>
+ {[stats, commit?.slice(0, 10)].filter(Boolean).join(' · ')}
+ </Text>
+ )}
+ {round.report && (
+ <Flexbox horizontal>
+ <Button size={'small'} type={'text'} onClick={() => onOpenReport(round)}>
+ <Icon icon={FileText} size={13} /> {t('acceptance.ledger.viewReport')}
+ </Button>
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+ })}
+ </Flexbox>
+ );
+});
+
+LedgerPanel.displayName = 'AcceptanceLedgerPanel';
+
+export default LedgerPanel;
diff --git a/src/features/Verify/Acceptance/index.tsx b/src/features/Verify/Acceptance/index.tsx
new file mode 100644
index 00000000000..d800c4bfc1e
--- /dev/null
+++ b/src/features/Verify/Acceptance/index.tsx
@@ -0,0 +1,538 @@
+'use client';
+
+import {
+ ActionIcon,
+ Center,
+ DraggablePanel,
+ Drawer,
+ Empty,
+ Flexbox,
+ Icon,
+ Markdown,
+ ScrollShadow,
+ Tag,
+ Text,
+} from '@lobehub/ui';
+import { Button, Segmented } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import dayjs from 'dayjs';
+import {
+ BadgeCheck,
+ CheckCircle2,
+ ChevronsDownUp,
+ ChevronsUpDown,
+ FileClock,
+ FileText,
+ GitBranch,
+ GitCommitHorizontal,
+ GitPullRequest,
+ HelpCircle,
+ Loader2,
+ PanelRightOpen,
+ RotateCcw,
+} from 'lucide-react';
+import { memo, useEffect, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useParams } from 'react-router';
+
+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
+import { verifyService } from '@/services/verify';
+
+import { useAcceptanceBundle } from '../hooks';
+import CheckList, {
+ type CheckFilter,
+ groupChecks,
+ hasVisualEvidence,
+ isException,
+} from './CheckList';
+import LedgerPanel, { type AcceptanceRound } from './LedgerPanel';
+import { openAcceptModal, openRejectModal } from './modals';
+
+const styles = createStaticStyles(({ css }) => ({
+ banner: css`
+ padding-block: 12px;
+ padding-inline: 16px;
+ border-radius: ${cssVar.borderRadiusLG};
+ `,
+ card: css`
+ overflow: hidden;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+ background: ${cssVar.colorBgContainer};
+ `,
+ page: css`
+ overflow: hidden;
+ height: 100%;
+ background: ${cssVar.colorBgLayout};
+ `,
+ requirementLabel: css`
+ font-size: 12px;
+ font-weight: 500;
+ color: ${cssVar.colorTextTertiary};
+ letter-spacing: 0.04em;
+ `,
+ scopeChip: css`
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ summaryClamp: css`
+ overflow: hidden;
+ display: -webkit-box;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 5;
+ `,
+}));
+
+/** Aggregate states in which the round chain is still executing. */
+const LIVE_STATUSES = new Set(['pending', 'planned', 'verifying', 'repairing']);
+
+/**
+ * The user-closure decision bar (accept / reject) is NOT shipping in this
+ * release — kept behind this switch (with its modals) until the loop launches.
+ */
+const ENABLE_DECISION_BAR = false;
+
+const AcceptancePage = memo(() => {
+ const { acceptanceId } = useParams<{ acceptanceId: string }>();
+ const { t } = useTranslation('verify');
+ const { data, error, isLoading, mutate } = useAcceptanceBundle(acceptanceId ?? null);
+
+ const [filter, setFilter] = useState<CheckFilter>('all');
+ const [expanded, setExpanded] = useState<Set<string>>(() => new Set());
+ const [collapsedGroups, setCollapsedGroups] = useState<Set<string>>(() => new Set());
+ const [seeded, setSeeded] = useState(false);
+ const [highlightRound, setHighlightRound] = useState<number | null>(null);
+ const [ledgerExpand, setLedgerExpand] = useState(true);
+ const [reportRound, setReportRound] = useState<AcceptanceRound | null>(null);
+ const [pending, setPending] = useState(false);
+ const [actionError, setActionError] = useState<string>();
+
+ const status = data?.acceptance.status;
+
+ // A chain still executing refreshes itself — same cadence as the report page.
+ useEffect(() => {
+ if (!status || !LIVE_STATUSES.has(status)) return;
+ const timer = setInterval(() => void mutate(), 5000);
+ return () => clearInterval(timer);
+ }, [status, mutate]);
+
+ // Exceptions and visually-evidenced checks start expanded (P-08) — once,
+ // on first load, so the user's own toggling is never overwritten.
+ useEffect(() => {
+ if (seeded || !data) return;
+ setExpanded(
+ new Set(
+ data.checks
+ .filter((check) => isException(check) || hasVisualEvidence(check))
+ .map((check) => check.id),
+ ),
+ );
+ setSeeded(true);
+ }, [data, seeded]);
+
+ const counts = useMemo(() => {
+ const checks = data?.checks ?? [];
+ return {
+ exceptions: checks.filter((check) => isException(check)).length,
+ failed: checks.filter((check) => check.state === 'failed').length,
+ fixed: checks.filter((check) => check.fixed).length,
+ notExecuted: checks.filter((check) => check.state === 'not_executed').length,
+ passed: checks.filter((check) => check.state === 'passed').length,
+ total: checks.length,
+ uncertain: checks.filter((check) => check.state === 'uncertain').length,
+ };
+ }, [data]);
+
+ if (isLoading)
+ return (
+ <Center height={'100%'}>
+ <NeuralNetworkLoading size={48} />
+ </Center>
+ );
+
+ if (error || !data)
+ return (
+ <Center height={'100%'}>
+ <Empty description={t('acceptance.error.description')} title={t('acceptance.error.title')}>
+ <Button onClick={() => void mutate()}>{t('report.actions.retry')}</Button>
+ </Empty>
+ </Center>
+ );
+
+ const { acceptance, checks, latestReport, rounds, subject } = data;
+ const currentRound = rounds.at(-1);
+ // The scope header comes from the latest round that carries a coding context.
+ const scope = [...rounds].reverse().find((round) => round.run.context)?.run.context;
+
+ const groupKeys = groupChecks(
+ checks,
+ (surface) => t(`report.surface.${surface}`),
+ t('acceptance.surface.other'),
+ ).map((group) => group.key);
+ const allGroupsCollapsed =
+ groupKeys.length > 0 && groupKeys.every((key) => collapsedGroups.has(key));
+
+ const countsText = [
+ t('acceptance.stats.passed', { count: counts.passed }),
+ counts.uncertain > 0 ? t('acceptance.stats.uncertain', { count: counts.uncertain }) : null,
+ counts.failed > 0 ? t('acceptance.stats.failed', { count: counts.failed }) : null,
+ counts.notExecuted > 0
+ ? t('acceptance.stats.notExecuted', { count: counts.notExecuted })
+ : null,
+ ]
+ .filter(Boolean)
+ .join(' · ');
+
+ const runAction = async (action: () => Promise<unknown>) => {
+ try {
+ setPending(true);
+ setActionError(undefined);
+ await action();
+ await mutate();
+ return true;
+ } catch (cause) {
+ setActionError(cause instanceof Error ? cause.message : t('acceptance.actionError'));
+ return false;
+ } finally {
+ setPending(false);
+ }
+ };
+
+ const gotoRound = (round: number) => {
+ setHighlightRound(round);
+ setLedgerExpand(true);
+ };
+
+ const decisionBanner = () => {
+ if (LIVE_STATUSES.has(acceptance.status))
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.banner}
+ gap={10}
+ style={{ background: cssVar.colorInfoBg }}
+ >
+ <Icon spin color={cssVar.colorInfo} icon={Loader2} size={16} />
+ <Flexbox flex={1} gap={2}>
+ <Text strong style={{ fontSize: 13 }}>
+ {t(`acceptance.status.${acceptance.status}`)}
+ </Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t('acceptance.banner.liveHint')}
+ </Text>
+ </Flexbox>
+ </Flexbox>
+ );
+
+ if (acceptance.status === 'accepted')
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.banner}
+ gap={10}
+ style={{ background: cssVar.colorSuccessBg }}
+ >
+ <Icon color={cssVar.colorSuccess} icon={BadgeCheck} size={18} />
+ <Flexbox flex={1} gap={2}>
+ <Text strong style={{ fontSize: 13 }}>
+ {t('acceptance.banner.accepted', {
+ time: acceptance.completedAt
+ ? dayjs(acceptance.completedAt).format('YYYY-MM-DD HH:mm')
+ : '',
+ })}
+ </Text>
+ <Text fontSize={12} type={'secondary'}>
+ {countsText} · {t('acceptance.banner.acceptedHint', { count: rounds.length })}
+ </Text>
+ </Flexbox>
+ </Flexbox>
+ );
+
+ if (acceptance.status === 'rejected') {
+ const reason = currentRound?.run.decisionDetail?.comment;
+ return (
+ <Flexbox className={styles.banner} gap={6} style={{ background: cssVar.colorErrorBg }}>
+ <Flexbox horizontal align={'center'} gap={10}>
+ <Icon color={cssVar.colorError} icon={RotateCcw} size={16} />
+ <Text strong style={{ fontSize: 13 }}>
+ {t('acceptance.banner.rejected')}
+ </Text>
+ </Flexbox>
+ {reason && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('acceptance.banner.rejectedReason', { reason })}
+ </Text>
+ )}
+ <Text fontSize={12} type={'secondary'}>
+ {t('acceptance.banner.rejectedHint')}
+ </Text>
+ </Flexbox>
+ );
+ }
+
+ // delivered / errored — the round chain settled; the decision is the user's.
+ const hasException = counts.exceptions > 0;
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.banner}
+ gap={12}
+ style={{ background: hasException ? cssVar.colorWarningBg : cssVar.colorSuccessBg }}
+ >
+ <Icon
+ color={hasException ? cssVar.colorWarning : cssVar.colorSuccess}
+ icon={hasException ? HelpCircle : CheckCircle2}
+ size={18}
+ />
+ <Flexbox flex={1} gap={2}>
+ <Text strong style={{ fontSize: 13 }}>
+ {hasException
+ ? t('acceptance.banner.exceptions', { count: counts.exceptions })
+ : t('acceptance.banner.clean', { count: rounds.length })}
+ </Text>
+ <Text fontSize={12} type={'secondary'}>
+ {countsText} · {t('acceptance.banner.decisionHint')}
+ </Text>
+ </Flexbox>
+ <Button
+ disabled={pending}
+ onClick={() =>
+ openRejectModal({
+ onConfirm: (comment) =>
+ runAction(() => verifyService.rejectDelivery(acceptance.id, comment)),
+ })
+ }
+ >
+ {t('acceptance.actions.reject')}
+ </Button>
+ <Button
+ disabled={pending}
+ type={'primary'}
+ onClick={() =>
+ openAcceptModal({
+ exceptions: checks.filter((check) => isException(check)).map((check) => check.title),
+ onConfirm: () => runAction(() => verifyService.acceptDelivery(acceptance.id)),
+ subjectTitle: subject.title ?? subject.id,
+ })
+ }
+ >
+ {t('acceptance.actions.accept')}
+ </Button>
+ </Flexbox>
+ );
+ };
+
+ return (
+ <Flexbox horizontal className={styles.page}>
+ <Flexbox flex={1} style={{ minWidth: 0 }}>
+ <ScrollShadow style={{ height: '100%' }}>
+ <Flexbox
+ gap={16}
+ paddingBlock={20}
+ paddingInline={24}
+ style={{ margin: '0 auto', maxWidth: 920, width: '100%' }}
+ >
+ {/* Header — the accepted object and its scope */}
+ <Flexbox gap={8}>
+ <Flexbox horizontal align={'center'} gap={10}>
+ <Text as={'h1'} style={{ fontSize: 18, margin: 0 }}>
+ {subject.title ?? subject.id}
+ </Text>
+ <Tag size={'small'}>{t(`acceptance.subject.${subject.type}`)}</Tag>
+ <Flexbox flex={1} />
+ {!ledgerExpand && (
+ <ActionIcon
+ icon={PanelRightOpen}
+ size={'small'}
+ title={t('acceptance.ledger.expand')}
+ onClick={() => setLedgerExpand(true)}
+ />
+ )}
+ </Flexbox>
+ <Flexbox horizontal align={'center'} gap={16} wrap={'wrap'}>
+ {scope?.branch && (
+ <Flexbox horizontal align={'center'} className={styles.scopeChip} gap={4}>
+ <Icon icon={GitBranch} size={13} /> {scope.branch}
+ </Flexbox>
+ )}
+ {scope?.commit && (
+ <Flexbox horizontal align={'center'} className={styles.scopeChip} gap={4}>
+ <Icon icon={GitCommitHorizontal} size={13} /> {scope.commit.slice(0, 10)}
+ </Flexbox>
+ )}
+ {scope?.pullRequest?.number && (
+ <Flexbox horizontal align={'center'} className={styles.scopeChip} gap={4}>
+ <Icon icon={GitPullRequest} size={13} /> #{scope.pullRequest.number}
+ </Flexbox>
+ )}
+ <Flexbox horizontal align={'center'} className={styles.scopeChip} gap={4}>
+ <Icon icon={FileClock} size={13} />{' '}
+ {t('acceptance.roundCount', { count: rounds.length })}
+ </Flexbox>
+ </Flexbox>
+ </Flexbox>
+
+ {/* The acceptance bar — what this delivery is judged against.
+ Prominence through typography (a lede under the heading), not
+ chrome: no card, no border. */}
+ {acceptance.requirement && (
+ <Flexbox gap={4} style={{ maxWidth: 760 }}>
+ <Text className={styles.requirementLabel}>{t('acceptance.requirementLabel')}</Text>
+ <Text style={{ fontSize: 15, lineHeight: 1.7 }}>{acceptance.requirement}</Text>
+ </Flexbox>
+ )}
+
+ {/* Decision bar — the user closes the lifecycle (P-12). Hidden
+ until the accept/reject loop ships. */}
+ {ENABLE_DECISION_BAR && decisionBanner()}
+ {ENABLE_DECISION_BAR && actionError && <Text type={'danger'}>{actionError}</Text>}
+
+ {/* Latest report narrative — an entry point, not the page's spine */}
+ {latestReport?.summary && (
+ <Flexbox className={styles.card} gap={8} padding={16}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Icon color={cssVar.colorTextSecondary} icon={FileText} size={15} />
+ <Text strong style={{ fontSize: 13 }}>
+ {t('acceptance.latestSummary')}
+ {currentRound
+ ? ` · ${t('acceptance.round', { round: currentRound.run.roundIndex })}`
+ : ''}
+ </Text>
+ <Flexbox flex={1} />
+ <Button
+ size={'small'}
+ type={'text'}
+ onClick={() =>
+ setReportRound([...rounds].reverse().find((r) => r.report) ?? null)
+ }
+ >
+ {t('acceptance.viewFullReport')}
+ </Button>
+ </Flexbox>
+ <Text className={styles.summaryClamp} fontSize={13} type={'secondary'}>
+ {latestReport.summary}
+ </Text>
+ </Flexbox>
+ )}
+
+ {/* Check union — the complete inventory, familiar sections (P-14) */}
+ <Flexbox horizontal align={'center'} gap={12}>
+ <Text strong style={{ fontSize: 14 }}>
+ {t('acceptance.checks.title')}
+ </Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t('acceptance.checks.subtitle', { count: counts.total, rounds: rounds.length })}
+ </Text>
+ <Flexbox flex={1} />
+ <Segmented
+ size={'small'}
+ value={filter}
+ options={[
+ { label: t('acceptance.filter.all', { count: counts.total }), value: 'all' },
+ {
+ label: t('acceptance.filter.exception', { count: counts.exceptions }),
+ value: 'exception',
+ },
+ { label: t('acceptance.filter.fixed', { count: counts.fixed }), value: 'fixed' },
+ ]}
+ onChange={(value) => setFilter(value as CheckFilter)}
+ />
+ <Button
+ icon={<Icon icon={allGroupsCollapsed ? ChevronsUpDown : ChevronsDownUp} />}
+ size={'small'}
+ onClick={() =>
+ setCollapsedGroups(allGroupsCollapsed ? new Set() : new Set(groupKeys))
+ }
+ >
+ {allGroupsCollapsed
+ ? t('acceptance.group.expandAll')
+ : t('acceptance.group.collapseAll')}
+ </Button>
+ </Flexbox>
+
+ <CheckList
+ checks={checks}
+ collapsedGroups={collapsedGroups}
+ expanded={expanded}
+ filter={filter}
+ onRound={gotoRound}
+ onToggleGroup={(key) =>
+ setCollapsedGroups((previous) => {
+ const next = new Set(previous);
+ if (next.has(key)) next.delete(key);
+ else next.add(key);
+ return next;
+ })
+ }
+ onToggleGroupItems={(ids, open) =>
+ setExpanded((previous) => {
+ const next = new Set(previous);
+ for (const id of ids) {
+ if (open) next.add(id);
+ else next.delete(id);
+ }
+ return next;
+ })
+ }
+ onToggleItem={(id) =>
+ setExpanded((previous) => {
+ const next = new Set(previous);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ return next;
+ })
+ }
+ />
+ <Flexbox style={{ height: 24 }} />
+ </Flexbox>
+ </ScrollShadow>
+ </Flexbox>
+
+ {/* Round ledger — audit detail, off the decision path (P-13) */}
+ <DraggablePanel
+ expandable
+ showHandleWhenCollapsed
+ defaultSize={{ width: 340 }}
+ expand={ledgerExpand}
+ minWidth={300}
+ placement={'right'}
+ onExpandChange={setLedgerExpand}
+ >
+ <ScrollShadow style={{ height: '100%' }}>
+ <LedgerPanel
+ highlight={highlightRound}
+ rounds={rounds}
+ onCollapse={() => setLedgerExpand(false)}
+ onOpenReport={setReportRound}
+ />
+ </ScrollShadow>
+ </DraggablePanel>
+
+ {/* Per-round report drill-down */}
+ <Drawer
+ open={reportRound !== null}
+ placement={'right'}
+ width={640}
+ title={
+ reportRound
+ ? t('acceptance.reportDrawer.title', { round: reportRound.run.roundIndex })
+ : ''
+ }
+ onClose={() => setReportRound(null)}
+ >
+ {reportRound?.report?.content ? (
+ <Markdown>{reportRound.report.content}</Markdown>
+ ) : (
+ <Text type={'secondary'}>{reportRound?.report?.summary}</Text>
+ )}
+ </Drawer>
+ </Flexbox>
+ );
+});
+
+AcceptancePage.displayName = 'AcceptancePage';
+
+export default AcceptancePage;
diff --git a/src/features/Verify/Acceptance/modals.tsx b/src/features/Verify/Acceptance/modals.tsx
new file mode 100644
index 00000000000..796b108fe2f
--- /dev/null
+++ b/src/features/Verify/Acceptance/modals.tsx
@@ -0,0 +1,143 @@
+'use client';
+
+import { Flexbox, Text, TextArea } from '@lobehub/ui';
+import { Button, createModal, type ModalInstance, useModalContext } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { t } from 'i18next';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const styles = createStaticStyles(({ css }) => ({
+ warning: css`
+ padding-block: 10px;
+ padding-inline: 14px;
+ border-radius: ${cssVar.borderRadiusLG};
+ background: ${cssVar.colorWarningBg};
+ `,
+}));
+
+interface AcceptContentProps {
+ /** Titles of the exceptions the user is knowingly accepting with. */
+ exceptions: string[];
+ /** Perform the accept; resolve true to close, false to stay open (error shown by the page). */
+ onConfirm: () => Promise<boolean>;
+ subjectTitle: string;
+}
+
+const AcceptContent = memo<AcceptContentProps>(({ exceptions, onConfirm, subjectTitle }) => {
+ const { t: translate } = useTranslation('verify');
+ const { close } = useModalContext();
+ const [loading, setLoading] = useState(false);
+
+ const handleConfirm = async () => {
+ setLoading(true);
+ try {
+ if (await onConfirm()) close();
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return (
+ <Flexbox gap={16}>
+ <Text>{translate('acceptance.accept.summary', { title: subjectTitle })}</Text>
+ {exceptions.length > 0 && (
+ <Flexbox className={styles.warning} gap={4}>
+ <Text strong fontSize={13}>
+ {translate('acceptance.accept.exceptionsTitle', { count: exceptions.length })}
+ </Text>
+ {exceptions.map((title) => (
+ <Text fontSize={12} key={title} type={'secondary'}>
+ · {title}
+ </Text>
+ ))}
+ <Text fontSize={12} type={'secondary'}>
+ {translate('acceptance.accept.exceptionsHint')}
+ </Text>
+ </Flexbox>
+ )}
+ <Flexbox horizontal gap={8} justify={'flex-end'}>
+ <Button disabled={loading} onClick={close}>
+ {translate('acceptance.actions.cancel')}
+ </Button>
+ <Button loading={loading} type={'primary'} onClick={handleConfirm}>
+ {translate('acceptance.actions.confirmAccept')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+AcceptContent.displayName = 'AcceptanceAcceptContent';
+
+/** Accept confirmation — spells out the terminal event and the exceptions taken with it. */
+export const openAcceptModal = (options: AcceptContentProps): ModalInstance =>
+ createModal({
+ content: <AcceptContent {...options} />,
+ footer: null,
+ maskClosable: true,
+ title: t('acceptance.actions.accept', { ns: 'verify' }),
+ width: 'min(90vw, 480px)',
+ });
+
+interface RejectContentProps {
+ /** Perform the reject with the reason; resolve true to close. */
+ onConfirm: (comment: string) => Promise<boolean>;
+}
+
+const RejectContent = memo<RejectContentProps>(({ onConfirm }) => {
+ const { t: translate } = useTranslation('verify');
+ const { close } = useModalContext();
+ const [comment, setComment] = useState('');
+ const [loading, setLoading] = useState(false);
+
+ const handleConfirm = async () => {
+ const trimmed = comment.trim();
+ if (!trimmed) return;
+ setLoading(true);
+ try {
+ if (await onConfirm(trimmed)) close();
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return (
+ <Flexbox gap={16}>
+ <Text fontSize={13} type={'secondary'}>
+ {translate('acceptance.reject.description')}
+ </Text>
+ <TextArea
+ autoSize={{ maxRows: 6, minRows: 3 }}
+ placeholder={translate('acceptance.reject.placeholder')}
+ value={comment}
+ onChange={(event) => setComment(event.target.value)}
+ />
+ <Flexbox horizontal gap={8} justify={'flex-end'}>
+ <Button disabled={loading} onClick={close}>
+ {translate('acceptance.actions.cancel')}
+ </Button>
+ <Button
+ disabled={!comment.trim()}
+ loading={loading}
+ type={'primary'}
+ onClick={handleConfirm}
+ >
+ {translate('acceptance.actions.confirmReject')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+RejectContent.displayName = 'AcceptanceRejectContent';
+
+/** Reject dialog — the reason is required: it is the next round's input, not a note. */
+export const openRejectModal = (options: RejectContentProps): ModalInstance =>
+ createModal({
+ content: <RejectContent {...options} />,
+ footer: null,
+ maskClosable: true,
+ title: t('acceptance.actions.reject', { ns: 'verify' }),
+ width: 'min(90vw, 480px)',
+ });
diff --git a/src/features/Verify/hooks.ts b/src/features/Verify/hooks.ts
index 4f6f66d0191..532d1e8daeb 100644
--- a/src/features/Verify/hooks.ts
+++ b/src/features/Verify/hooks.ts
@@ -35,6 +35,14 @@ export const useVerifyReportBundle = (verifyRunId: string | null) =>
VERIFY_REPORT_SWR_CONFIG,
);
+/** Cross-round acceptance decision bundle by acceptance id. */
+export const useAcceptanceBundle = (acceptanceId: string | null) =>
+ useClientDataSWR(
+ acceptanceId ? verifyKeys.acceptanceBundle(acceptanceId) : null,
+ () => verifyService.getAcceptanceBundle(acceptanceId!),
+ VERIFY_REPORT_SWR_CONFIG,
+ );
+
/**
* Cursor-paginated, infinite-scrolling report summaries. `q` drives a
* server-side title search (spanning the whole history, not just loaded pages);
diff --git a/src/features/Verify/index.ts b/src/features/Verify/index.ts
index 9baa705a3de..d81fab65201 100644
--- a/src/features/Verify/index.ts
+++ b/src/features/Verify/index.ts
@@ -1,5 +1,11 @@
+export { default as AcceptanceViewer } from './Acceptance';
export { default as CheckerDock } from './CheckerDock';
-export { useVerifyReportSummariesInfinite, useVerifyResults, useVerifyState } from './hooks';
+export {
+ useAcceptanceBundle,
+ useVerifyReportSummariesInfinite,
+ useVerifyResults,
+ useVerifyState,
+} from './hooks';
export { default as ReportViewer } from './ReportViewer';
export { default as RunResult } from './RunResult';
export { countResults, isDraftUnconfirmed, phaseFromStatus } from './utils';
diff --git a/src/features/Verify/routeMeta.ts b/src/features/Verify/routeMeta.ts
index 884f1fc618e..36cf5a29e49 100644
--- a/src/features/Verify/routeMeta.ts
+++ b/src/features/Verify/routeMeta.ts
@@ -5,7 +5,24 @@ import { usePublishDynamicRouteMeta } from '@/features/RouteMeta/usePublishDynam
import type { DynamicRouteMetaProps } from '@/spa/router/routeMeta';
import { routeMeta } from '@/spa/router/routeMeta';
-import { useVerifyReportBundle } from './hooks';
+import { useAcceptanceBundle, useVerifyReportBundle } from './hooks';
+
+const AcceptanceDynamicMeta = ({ onResolve, params }: DynamicRouteMetaProps) => {
+ const { t } = useTranslation('verify');
+ const { data } = useAcceptanceBundle(params.acceptanceId ?? null);
+
+ usePublishDynamicRouteMeta(
+ { title: data?.subject.title || t('acceptance.titleFallback') },
+ onResolve,
+ );
+
+ return null;
+};
+
+export const acceptanceRouteMeta = routeMeta({
+ DynamicMeta: AcceptanceDynamicMeta,
+ icon: ClipboardCheckIcon,
+});
const VerifyDynamicMeta = ({ onResolve, params }: DynamicRouteMetaProps) => {
const { t } = useTranslation('verify');
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 1e685547ce0..5cbe73659ff 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -711,6 +711,10 @@ export const messengerKeys = {
// ---- verify (deliverable judging) ---------------------------------------
export const verifyKeys = {
+ acceptanceBundle: def('verify:acceptanceBundle', (acceptanceId: string) => [
+ 'verify:acceptanceBundle',
+ acceptanceId,
+ ]),
criteria: def('verify:criteria', () => ['verify:criteria']),
instruction: def('verify:instruction', (documentId: string) => [
'verify:instruction',
diff --git a/src/proxy.ts b/src/proxy.ts
index 09e9c0041fe..445b6b32d15 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -15,6 +15,8 @@ export const config = {
// /oauth stay matched below — their middleware pass is still load-bearing.)
// include the /
'/',
+ '/acceptance',
+ '/acceptance(.*)',
'/community',
'/community(.*)',
'/labs',
diff --git a/src/routes/acceptance/[acceptanceId]/index.tsx b/src/routes/acceptance/[acceptanceId]/index.tsx
new file mode 100644
index 00000000000..4078ac686cd
--- /dev/null
+++ b/src/routes/acceptance/[acceptanceId]/index.tsx
@@ -0,0 +1,3 @@
+'use client';
+
+export { AcceptanceViewer as default } from '@/features/Verify';
diff --git a/src/services/verify.ts b/src/services/verify.ts
index b758c575940..1acf991891b 100644
--- a/src/services/verify.ts
+++ b/src/services/verify.ts
@@ -17,6 +17,8 @@ import type {
} from '@/database/schemas/verify';
import { lambdaClient } from '@/libs/trpc/client';
+export type AcceptanceBundle = Awaited<ReturnType<typeof lambdaClient.acceptance.getBundle.query>>;
+
/** Editable fields of a single delivery-check criterion. */
export interface UpdateCriterionValue {
description?: string | null;
@@ -130,6 +132,16 @@ export interface GenerateDraftPlanInput {
/** Client wrapper around the `verify` lambda router. */
export class VerifyService {
+ // ---- subject-level acceptance ----
+ getAcceptanceBundle = (id: string): Promise<AcceptanceBundle> =>
+ lambdaClient.acceptance.getBundle.query({ id });
+
+ acceptDelivery = (id: string, comment?: string) =>
+ lambdaClient.acceptance.accept.mutate({ comment, id });
+
+ rejectDelivery = (id: string, comment: string) =>
+ lambdaClient.acceptance.reject.mutate({ comment, id });
+
// ---- per-run plan ----
getVerifyState = (operationId: string): Promise<VerifyStateResponse | null> =>
lambdaClient.verify.getVerifyState.query({
diff --git a/src/spa/router/desktopRouter.config.desktop.tsx b/src/spa/router/desktopRouter.config.desktop.tsx
index 43a0167f48a..20552561361 100644
--- a/src/spa/router/desktopRouter.config.desktop.tsx
+++ b/src/spa/router/desktopRouter.config.desktop.tsx
@@ -21,6 +21,11 @@ import { agentDocumentRouteMeta } from '@/features/AgentDocumentPage/routeMeta';
import { taskRouteMeta, tasksRouteMeta } from '@/features/AgentTasks/routeMeta';
import { fleetRouteMeta } from '@/features/Fleet/routeMeta';
import { pageRouteMeta } from '@/features/Pages/routeMeta';
+import {
+ acceptanceRouteMeta,
+ verifyReportsRouteMeta,
+ verifyRouteMeta,
+} from '@/features/Verify/routeMeta';
import { workspaceHomeRouteMeta } from '@/features/Workspace/routeMeta';
import DesktopOnboarding from '@/routes/(desktop)/desktop-onboarding';
// Layouts — sync import (Electron local, no network overhead)
@@ -127,11 +132,15 @@ import { settingsRouteMeta } from '@/routes/(main)/settings/features/routeMeta';
import { ProviderDetailPage, ProviderLayout } from '@/routes/(main)/settings/provider';
import TaskDetailRoute from '@/routes/(main)/task/[taskId]';
import AllTasksPage from '@/routes/(main)/tasks';
+import VerifyWorkspace from '@/routes/(main)/verify';
+import VerifyEmptyPage from '@/routes/(main)/verify/empty';
+import AcceptanceReportPage from '@/routes/acceptance/[acceptanceId]';
import SharePagePage from '@/routes/share/page/[id]';
import { sharePageRouteMeta } from '@/routes/share/page/[id]/routeMeta';
import ShareTopicPage from '@/routes/share/t/[id]';
import ShareTopicLayout from '@/routes/share/t/[id]/_layout';
import { shareTopicRouteMeta } from '@/routes/share/t/[id]/routeMeta';
+import VerifyReportPage from '@/routes/verify/[runId]';
import { routeMeta } from '@/spa/router/routeMeta';
import { SettingsTabs } from '@/store/global/initialState';
import { ErrorBoundary, redirectElement } from '@/utils/router';
@@ -785,6 +794,30 @@ export const desktopRoutes: RouteObject[] = [
path: '/share/page',
},
+ // Verify report workspace — standalone master-detail (outside main layout)
+ {
+ children: [
+ { element: <VerifyEmptyPage />, index: true },
+ {
+ element: <VerifyReportPage />,
+ handle: { meta: verifyRouteMeta },
+ path: ':runId',
+ },
+ ],
+ element: <VerifyWorkspace />,
+ errorElement: <ErrorBoundary />,
+ handle: { meta: verifyReportsRouteMeta },
+ path: '/verify',
+ },
+
+ // Subject-level delivery acceptance — separate from single-run verify reports.
+ {
+ element: <AcceptanceReportPage />,
+ errorElement: <ErrorBoundary />,
+ handle: { meta: acceptanceRouteMeta },
+ path: '/acceptance/:acceptanceId',
+ },
+
// Devtools route (outside main layout, dev-only)
...(__DEV__
? [
diff --git a/src/spa/router/desktopRouter.config.tsx b/src/spa/router/desktopRouter.config.tsx
index c3dd54e2fae..792ce826afc 100644
--- a/src/spa/router/desktopRouter.config.tsx
+++ b/src/spa/router/desktopRouter.config.tsx
@@ -21,7 +21,11 @@ import { agentDocumentRouteMeta } from '@/features/AgentDocumentPage/routeMeta';
import { taskRouteMeta, tasksRouteMeta } from '@/features/AgentTasks/routeMeta';
import { fleetRouteMeta } from '@/features/Fleet/routeMeta';
import { pageRouteMeta } from '@/features/Pages/routeMeta';
-import { verifyReportsRouteMeta, verifyRouteMeta } from '@/features/Verify/routeMeta';
+import {
+ acceptanceRouteMeta,
+ verifyReportsRouteMeta,
+ verifyRouteMeta,
+} from '@/features/Verify/routeMeta';
import { workspaceHomeRouteMeta } from '@/features/Workspace/routeMeta';
import { agentRouteMeta, topicsRouteMeta } from '@/routes/(main)/agent/features/routeMeta';
import { groupRouteMeta } from '@/routes/(main)/group/features/routeMeta';
@@ -1046,6 +1050,17 @@ export const desktopRoutes: RouteObject[] = [
path: '/verify',
},
+ // Subject-level delivery acceptance — separate from single-run verify reports.
+ {
+ element: dynamicElement(
+ () => import('@/routes/acceptance/[acceptanceId]'),
+ 'Desktop > AcceptanceReport',
+ ),
+ errorElement: <ErrorBoundary />,
+ handle: { meta: acceptanceRouteMeta },
+ path: '/acceptance/:acceptanceId',
+ },
+
// Devtools route (outside main layout, dev-only)
...(__DEV__
? [
diff --git a/src/spa/router/desktopRouter.sync.test.tsx b/src/spa/router/desktopRouter.sync.test.tsx
index a3e4acf9281..76a23e2fc07 100644
--- a/src/spa/router/desktopRouter.sync.test.tsx
+++ b/src/spa/router/desktopRouter.sync.test.tsx
@@ -25,20 +25,16 @@ const WEB_ONLY_PATHS = new Set([
'/onboarding',
'/onboarding/agent',
'/onboarding/classic',
- // Verify report workspace + messenger link flow — web/CLI only
- '/verify',
+ // Messenger link flow — web/CLI only (the verify workspace + acceptance
+ // pages ship on Electron too, so they are synced, not listed here)
'/verify-im',
- ':runId',
]);
-/** Extra `index: true` routes present only on web (verify empty detail). */
-const WEB_ONLY_INDEX_DELTA = 1;
+/** Extra `index: true` routes present only on web. */
+const WEB_ONLY_INDEX_DELTA = 0;
/** handle.meta blobs present only on web. */
-const WEB_ONLY_HANDLE_METAS = new Set([
- '{ meta: verifyRouteMeta }',
- '{ meta: verifyReportsRouteMeta }',
-]);
+const WEB_ONLY_HANDLE_METAS = new Set<string>([]);
function extractIndexCount(source: string) {
return [...source.matchAll(/index:\s*true/g)].length;
diff --git a/src/spa/router/mobileRouter.config.tsx b/src/spa/router/mobileRouter.config.tsx
index 9a38a7d91d0..f848efe081c 100644
--- a/src/spa/router/mobileRouter.config.tsx
+++ b/src/spa/router/mobileRouter.config.tsx
@@ -7,7 +7,11 @@ import {
BusinessMobileRoutesWithoutMainLayout,
} from '@/business/client/BusinessMobileRoutes';
import { mobileAgentSettingsRouteMeta } from '@/features/RouteMeta/mobileRouteMeta';
-import { verifyReportsRouteMeta, verifyRouteMeta } from '@/features/Verify/routeMeta';
+import {
+ acceptanceRouteMeta,
+ verifyReportsRouteMeta,
+ verifyRouteMeta,
+} from '@/features/Verify/routeMeta';
import { agentRouteMeta } from '@/routes/(main)/agent/features/routeMeta';
import { sharePageRouteMeta } from '@/routes/share/page/[id]/routeMeta';
import { shareTopicRouteMeta } from '@/routes/share/t/[id]/routeMeta';
@@ -570,4 +574,13 @@ export const mobileRoutes: RouteObject[] = [
handle: { meta: verifyReportsRouteMeta },
path: '/verify',
},
+ {
+ element: dynamicElement(
+ () => import('@/routes/acceptance/[acceptanceId]'),
+ 'Mobile > AcceptanceReport',
+ ),
+ errorElement: <ErrorBoundary />,
+ handle: { meta: acceptanceRouteMeta },
+ path: '/acceptance/:acceptanceId',
+ },
];