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(acceptance): render local acceptance reports without a LobeHub account (#21631)

AmAzing-a2b8c8c68405
diff --git a/apps/cli/README.md b/apps/cli/README.md
index 844f05e14f6..54c4815d900 100644
--- a/apps/cli/README.md
+++ b/apps/cli/README.md
@@ -61,8 +61,8 @@ Update the installed skill:
lh acceptance update
```
-Creating acceptances and publishing reports require authentication. Run `lh login`
-before using those commands.
+Publishing reports to LobeHub requires authentication (`lh login`). Without a
+login, acceptance runs locally — see [Local reports](#local-reports).
This selects the same source as `npx skills add lobehub/acceptance --skill acceptance`.
Changes merged into the default branch are available on the next install or
@@ -84,6 +84,31 @@ To select an existing version tag explicitly, use `lh acceptance update --skill-
with `npx skills add`. A later `lh acceptance update` without `--skill-version`
returns to the current default-branch source.
+## Local reports
+
+A machine that has never signed in renders acceptance reports locally instead
+of publishing them; `lh acceptance preflight --json` reports `"mode": "local"`.
+
+```bash
+lh acceptance run render .acceptances/<subject>/<round> --requirement "<business goal>"
+```
+
+This writes `report.html` beside the rounds: the acceptance page, offline — the
+checklist, evidence, before/after pairs, video chapters and round history,
+rendered from every round of that acceptance. Nothing is uploaded. The reader
+can accept or reject checks and circle regions on screenshots there; **Save
+reviews** downloads the decisions, and the next
+`lh acceptance feedback .acceptances/<subject>` (or `view`) files them as
+`reviews.json` and reports them like hosted feedback.
+
+Comments, mentions and shared links need LobeHub. After `lh login`,
+`lh acceptance publish .acceptances/<subject>` publishes the unpublished rounds
+in order into one acceptance and carries the standing review decisions over;
+running it again publishes only newer rounds.
+
+The page is built by `apps/workbench` (`bun run --cwd ../workbench build:report`);
+`bun run build` copies it to `dist/acceptance-report.html` when it exists.
+
## Local Development
| Task | Command |
@@ -93,7 +118,7 @@ returns to the current default-branch source.
| Link `lh`/`lobe`/`lobehub` into your shell | `bun run cli:link` |
| Remove the global link | `bun run cli:unlink` |
-- `bun run build` only generates `dist/index.js`.
+- `bun run build` generates `dist/index.js`, plus `dist/acceptance-report.html` when the local report page is built.
- To make `lh` available in your shell, run `bun run cli:link`.
- After linking, if your shell still cannot find `lh`, run `rehash` in `zsh`.
diff --git a/apps/cli/package.json b/apps/cli/package.json
index 36705cd4654..e0e4d0686ca 100644
--- a/apps/cli/package.json
+++ b/apps/cli/package.json
@@ -17,12 +17,12 @@
"man"
],
"scripts": {
- "build": "bun scripts/ensureWorkspaceLinks.ts && tsdown && tsdown src/daemon/maintenanceWorker.ts --no-config --no-clean --format esm --target node22",
+ "build": "bun scripts/ensureWorkspaceLinks.ts && tsdown && tsdown src/daemon/maintenanceWorker.ts --no-config --no-clean --format esm --target node22 && bun scripts/copyReportTemplate.ts",
"cli:link": "bun link",
"cli:unlink": "bun unlink",
"dev": "LOBEHUB_CLI_HOME=.lobehub-dev bun src/index.ts",
"man:generate": "bun src/man/generate.ts",
- "prepublishOnly": "npm run build && npm run man:generate",
+ "prepublishOnly": "bun run --cwd ../workbench build:report && npm run build && bun scripts/copyReportTemplate.ts --require && npm run man:generate",
"test": "bunx vitest run --config vitest.config.mts --silent='passed-only'",
"test:coverage": "bunx vitest run --config vitest.config.mts --coverage",
"test:e2e": "bunx vitest run --config vitest.e2e.config.mts --silent='passed-only'",
diff --git a/apps/cli/scripts/copyReportTemplate.ts b/apps/cli/scripts/copyReportTemplate.ts
new file mode 100644
index 00000000000..9febba8a6c0
--- /dev/null
+++ b/apps/cli/scripts/copyReportTemplate.ts
@@ -0,0 +1,26 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+/**
+ * Ship the offline acceptance page next to the bundle: `lh acceptance run
+ * render` reads `dist/acceptance-report.html` at runtime. The page is built by
+ * apps/workbench (`build:report`). A local build without it still produces a
+ * working CLI — only `run render` reports the page missing — but a release
+ * passes `--require`, so a published CLI always carries it.
+ */
+const cliDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const source = path.resolve(cliDir, '../workbench/dist-report/acceptance-report.html');
+const target = path.join(cliDir, 'dist/acceptance-report.html');
+
+if (fs.existsSync(source)) {
+ fs.copyFileSync(source, target);
+ console.info(`copied ${path.relative(cliDir, source)} → ${path.relative(cliDir, target)}`);
+} else if (process.argv.includes('--require')) {
+ console.error(`Missing ${source}. Build it first: bun run --cwd ../workbench build:report`);
+ process.exit(1);
+} else {
+ console.warn(
+ `Skipping the local report page (${path.relative(cliDir, source)} not built); \`lh acceptance run render\` will report it missing.`,
+ );
+}
diff --git a/apps/cli/src/commands/acceptance/index.preflight.test.ts b/apps/cli/src/commands/acceptance/index.preflight.test.ts
new file mode 100644
index 00000000000..719549a0f5d
--- /dev/null
+++ b/apps/cli/src/commands/acceptance/index.preflight.test.ts
@@ -0,0 +1,113 @@
+import fs from 'node:fs';
+
+import { Command } from 'commander';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { clearCredentials, saveCredentials } from '../../auth/credentials';
+import { credentialsPath } from '../../auth/source';
+
+vi.mock('../../settings', () => ({
+ loadActiveWorkspace: () => undefined,
+ resolveServerUrl: () => 'https://acceptance.example.test',
+}));
+vi.unmock('../../utils/logger');
+
+let output: ReturnType<typeof vi.spyOn>;
+let errors: ReturnType<typeof vi.spyOn>;
+
+const run = async () => {
+ const { registerAcceptanceCommands } = await import('.');
+ const program = new Command().exitOverride();
+ registerAcceptanceCommands(program);
+ await program.parseAsync(['node', 'lh', 'acceptance', 'preflight', '--json']);
+ return JSON.parse(String(output.mock.calls.at(-1)?.[0]));
+};
+
+beforeEach(() => {
+ vi.resetModules();
+ clearCredentials();
+ vi.stubEnv('LOBEHUB_JWT', '');
+ vi.stubEnv('LOBEHUB_CLI_API_KEY', '');
+ vi.stubEnv('LOBEHUB_WORKSPACE_ID', 'personal');
+ output = vi.spyOn(console, 'log').mockImplementation(() => {});
+ errors = vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.spyOn(process, 'exit').mockImplementation((code) => {
+ throw new Error(`process.exit(${code})`);
+ });
+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('Network unavailable')));
+});
+
+afterEach(() => {
+ clearCredentials();
+ vi.unstubAllEnvs();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+describe('acceptance preflight', () => {
+ it('selects offline reports when no credentials exist', async () => {
+ expect(await run()).toMatchObject({
+ authenticated: false,
+ language: { status: 'unset' },
+ mode: 'local',
+ });
+ });
+
+ it.each(['expired', 'undated', 'corrupt'])(
+ 'stops with a login remedy instead of silently selecting local mode for %s credentials',
+ async (state) => {
+ saveCredentials({
+ accessToken: 'fixture-access-token',
+ expiresAt: state === 'expired' ? 1 : undefined,
+ });
+ if (state === 'corrupt') fs.writeFileSync(credentialsPath(), 'unreadable-credentials');
+
+ await expect(run()).rejects.toThrow('process.exit(1)');
+ expect(output.mock.calls).toEqual([]);
+ expect(errors.mock.calls.flat().join(' ')).toContain('lh login');
+ expect(fs.existsSync(credentialsPath())).toBe(true);
+ },
+ );
+
+ it.each(['stored', 'jwt', 'apiKey'])(
+ 'keeps publishing with valid %s credentials and the account language',
+ async (source) => {
+ if (source === 'stored') {
+ saveCredentials({
+ accessToken: 'fixture-access-token',
+ expiresAt: Math.floor(Date.now() / 1000) + 3600,
+ });
+ } else {
+ vi.stubEnv(source === 'jwt' ? 'LOBEHUB_JWT' : 'LOBEHUB_CLI_API_KEY', 'fixture-token');
+ }
+ vi.mocked(fetch).mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ result: { data: { json: { settings: { general: { responseLanguage: 'zh-CN' } } } } },
+ }),
+ { headers: { 'Content-Type': 'application/json' } },
+ ),
+ );
+
+ expect(await run()).toMatchObject({
+ authenticated: true,
+ language: { locale: 'zh-CN', status: 'enforced' },
+ mode: 'publish',
+ });
+ },
+ );
+
+ it('surfaces an unavailable refresh without changing mode or removing the stored login', async () => {
+ saveCredentials({
+ accessToken: 'expired-token',
+ expiresAt: 1,
+ refreshToken: 'fixture-refresh',
+ });
+ const stored = fs.readFileSync(credentialsPath(), 'utf8');
+
+ await expect(run()).rejects.toThrow('process.exit(1)');
+ expect(output.mock.calls).toEqual([]);
+ expect(errors.mock.calls.flat().join(' ')).toContain('Retry in a moment');
+ expect(fs.readFileSync(credentialsPath(), 'utf8')).toBe(stored);
+ });
+});
diff --git a/apps/cli/src/commands/acceptance/index.ts b/apps/cli/src/commands/acceptance/index.ts
index d1479603ba2..3c024610087 100644
--- a/apps/cli/src/commands/acceptance/index.ts
+++ b/apps/cli/src/commands/acceptance/index.ts
@@ -2,12 +2,16 @@ import { randomUUID } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { acceptanceSubjectTypes } from '@lobechat/const/verify';
-import type { AcceptanceAttachment, AcceptanceCheckGroup } from '@lobechat/types';
+import type {
+ AcceptanceAttachment,
+ AcceptanceCheckGroup,
+ AcceptanceCommentList,
+} from '@lobechat/types';
import type { Command } from 'commander';
import { InvalidArgumentError } from 'commander';
import pc from 'picocolors';
-import { getTrpcClient } from '../../api/client';
+import { getTrpcClient, type TrpcClient } from '../../api/client';
import { resolveServerUrl } from '../../settings';
import { outputJson, printTable, timeAgo, truncate } from '../../utils/format';
import { log } from '../../utils/logger';
@@ -22,6 +26,9 @@ import {
responseLanguageSettingsUrl,
unsetLanguageWarning,
} from './language';
+import { localAcceptanceTarget, readLocalBundle } from './local/localBundle';
+import { isSignedOut, LOCAL_MODE_INSTRUCTION } from './local/mode';
+import { publishAction, withPublishOptions } from './local/publish';
import { attachPlanCommands } from './plan';
import { projectEnsureInput, resolveAcceptanceProject, warnIfFiledElsewhere } from './project';
import { attachRubricCommands } from './rubric';
@@ -29,6 +36,9 @@ import { attachAcceptanceRunCommands } from './run';
import type { ReviewAnnotationRegion } from './utils';
import { formatAnnotationRegion, formatDisputedChapter, parseSubjectRef } from './utils';
+/** What `acceptance.getBundle` answers; a local acceptance is assembled into the same shape. */
+type RemoteBundle = Awaited<ReturnType<TrpcClient['acceptance']['getBundle']['query']>>;
+
/**
* 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,
@@ -89,14 +99,37 @@ export function registerAcceptanceCommands(parent: Command, options?: { deprecat
attachAcceptanceFlowCommands(acceptance);
+ withPublishOptions(
+ acceptance
+ .command('publish <acceptanceDir>')
+ .description(
+ 'Publish a local acceptance to LobeHub for team review: its unpublished rounds in order, then the local review decisions',
+ ),
+ ).action(publishAction);
+
acceptance
.command('preflight')
.description(
- 'Check that the CLI is authenticated and print the language every acceptance text must be written in. ' +
+ 'Say whether acceptance publishes to LobeHub (signed in) or renders locally (never signed in), and print the language every acceptance text must be written in. ' +
'Run it before authoring anything, and pass the language to any subagent you delegate to.',
)
.option('--json [fields]', 'Output JSON')
.action(async (options: { json?: boolean | string }) => {
+ // Never signed in: nothing to stop on — acceptance runs locally and the
+ // report is an offline page. A sign-in that exists but fails still stops.
+ if (isSignedOut()) {
+ const instruction = LOCAL_MODE_INSTRUCTION;
+ if (options.json !== undefined) {
+ outputJson(
+ { authenticated: false, instruction, language: { status: 'unset' }, mode: 'local' },
+ typeof options.json === 'string' ? options.json : undefined,
+ );
+ return;
+ }
+ console.log(`${pc.yellow('○')} Not signed in to LobeHub — reports are rendered locally`);
+ console.log(instruction);
+ return;
+ }
const client = await getTrpcClient();
// An auth failure throws here, which is the signal to stop before authoring.
const language = await resolveReportLanguage(client);
@@ -110,6 +143,7 @@ export function registerAcceptanceCommands(parent: Command, options?: { deprecat
authenticated: true,
instruction,
language: languageSummary(language),
+ mode: 'publish',
settingsUrl: responseLanguageSettingsUrl(),
},
typeof options.json === 'string' ? options.json : undefined,
@@ -273,18 +307,28 @@ export function registerAcceptanceCommands(parent: Command, options?: { deprecat
acceptance
.command('view <idOrSubject>')
- .description('Show the acceptance decision bundle (union checks + round ledger)')
+ .description(
+ 'Show the acceptance decision bundle (union checks + round ledger); a local acceptance directory reads it offline',
+ )
+ .option('--reviews <file>', 'Local only: the review log the report page saved')
.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 });
+ .action(async (idOrSubject: string, options: { json?: boolean | string; reviews?: string }) => {
+ const local = localAcceptanceTarget(idOrSubject);
+ let bundle: RemoteBundle;
+ if (local) {
+ bundle = readLocalBundle(local, { reviewsFile: options.reviews })
+ .bundle as unknown as RemoteBundle;
+ } else {
+ const id = await resolveAcceptanceId(idOrSubject);
+ const client = await getTrpcClient();
+ bundle = await client.acceptance.getBundle.query({ id });
+ if (options.json !== undefined) {
+ bundle = withUrl(bundle, await resolveUrlBuilder(client), resourcePath.acceptance(id));
+ }
+ }
if (options.json !== undefined) {
- outputJson(
- withUrl(bundle, await resolveUrlBuilder(client), resourcePath.acceptance(id)),
- typeof options.json === 'string' ? options.json : undefined,
- );
+ outputJson(bundle, typeof options.json === 'string' ? options.json : undefined);
return;
}
@@ -361,15 +405,35 @@ export function registerAcceptanceCommands(parent: Command, options?: { deprecat
"The user's review feedback — unresolved comments, region notes, attachments and rejection decisions",
)
.option('--actionable', 'Only standing feedback the next repair round must act on')
+ .option('--reviews <file>', 'Local only: the review log the report page saved')
.option('--json [fields]', 'Output JSON')
.action(
- async (idOrSubject: string, options: { actionable?: boolean; json?: boolean | string }) => {
- const id = await resolveAcceptanceId(idOrSubject);
- const client = await getTrpcClient();
- const [bundle, comments] = await Promise.all([
- client.acceptance.getBundle.query({ id }),
- client.acceptanceComment.list.query({ acceptanceId: id }),
- ]);
+ async (
+ idOrSubject: string,
+ options: { actionable?: boolean; json?: boolean | string; reviews?: string },
+ ) => {
+ const local = localAcceptanceTarget(idOrSubject);
+ let id: string;
+ let bundle: RemoteBundle;
+ let comments: Pick<AcceptanceCommentList, 'items'>;
+ if (local) {
+ // The reviewer decided in the offline report; its saved log is read here.
+ const read = readLocalBundle(local, { reviewsFile: options.reviews });
+ if (read.read.source.reviews.length === 0)
+ log.warn(
+ 'No saved review found. The reviewer saves decisions with "Save reviews" in report.html; the file lands in their Downloads folder (or pass --reviews <file>).',
+ );
+ id = read.read.info.id;
+ bundle = read.bundle as unknown as RemoteBundle;
+ comments = read.comments;
+ } else {
+ id = await resolveAcceptanceId(idOrSubject);
+ const client = await getTrpcClient();
+ [bundle, comments] = await Promise.all([
+ client.acceptance.getBundle.query({ id }),
+ client.acceptanceComment.list.query({ acceptanceId: id }),
+ ]);
+ }
const currentRoundIndex = bundle.rounds.at(-1)?.run.roundIndex ?? 0;
diff --git a/apps/cli/src/commands/acceptance/index.view.test.ts b/apps/cli/src/commands/acceptance/index.view.test.ts
new file mode 100644
index 00000000000..a964649f6d7
--- /dev/null
+++ b/apps/cli/src/commands/acceptance/index.view.test.ts
@@ -0,0 +1,103 @@
+import path from 'node:path';
+
+import { Command } from 'commander';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getTrpcClient } from '../../api/client';
+import { resolveWorkspaceId } from '../../api/workspace';
+import { registerAcceptanceCommands } from '.';
+import { ensureAcceptanceInfo } from './local/acceptanceDir';
+import { createLocalAcceptance, firstRound } from './local/testUtils';
+
+vi.mock('../../api/client', () => ({ getTrpcClient: vi.fn() }));
+vi.mock('../../api/workspace', () => ({ resolveWorkspaceId: vi.fn() }));
+vi.mock('../../settings', () => ({ resolveServerUrl: () => 'https://app.lobehub.com' }));
+
+const getBundle = vi.fn();
+const getBySubject = vi.fn();
+const getWorkspace = vi.fn();
+let output: ReturnType<typeof vi.spyOn>;
+let fixture: ReturnType<typeof createLocalAcceptance> | undefined;
+
+const run = async (args: string[]) => {
+ const program = new Command().exitOverride();
+ registerAcceptanceCommands(program);
+ await program.parseAsync(['node', 'lh', 'acceptance', 'view', ...args]);
+ return JSON.parse(String(output.mock.calls.at(-1)?.[0]));
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ output = vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.mocked(resolveWorkspaceId).mockReturnValue(undefined);
+ vi.mocked(getTrpcClient).mockResolvedValue({
+ acceptance: { getBundle: { query: getBundle }, getBySubject: { query: getBySubject } },
+ workspace: { getById: { query: getWorkspace } },
+ } as unknown as Awaited<ReturnType<typeof getTrpcClient>>);
+});
+
+afterEach(() => {
+ fixture?.cleanup();
+ fixture = undefined;
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+});
+
+describe('acceptance view', () => {
+ it('reads a local bundle as JSON without authentication or a remote URL', async () => {
+ fixture = createLocalAcceptance([firstRound()]);
+ vi.stubEnv('HOME', fixture.root);
+ vi.stubEnv('LOBEHUB_ACCEPTANCE_DOWNLOADS', path.join(fixture.root, 'Downloads'));
+ vi.stubEnv('XDG_DOWNLOAD_DIR', path.join(fixture.root, 'Downloads'));
+ vi.mocked(getTrpcClient).mockRejectedValue(new Error('Not authenticated'));
+ const { info } = ensureAcceptanceInfo(fixture.acceptanceDir, 'Users can rename a topic');
+
+ const bundle = await run([fixture.acceptanceDir, '--json']);
+
+ expect(bundle.acceptance).toMatchObject({ id: info.id, requirement: info.requirement });
+ expect(bundle.checks).toEqual([
+ expect.objectContaining({
+ id: 'rename',
+ state: 'passed',
+ title: 'Rename keeps the new title',
+ }),
+ expect.objectContaining({ id: 'enter', state: 'not_executed', title: 'Enter saves' }),
+ ]);
+ expect(bundle.rounds).toHaveLength(1);
+ expect(bundle).not.toHaveProperty('url');
+ expect(await run([fixture.acceptanceDir, '--json', 'acceptance,checks'])).toEqual({
+ acceptance: bundle.acceptance,
+ checks: bundle.checks,
+ });
+ expect(getTrpcClient).not.toHaveBeenCalled();
+ expect(resolveWorkspaceId).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { ref: 'acc_1', workspaceSlug: undefined },
+ { ref: 'task:task-1', workspaceSlug: 'acme' },
+ ])(
+ 'keeps the resolved acceptance URL when reading $ref remotely',
+ async ({ ref, workspaceSlug }) => {
+ const bundle = {
+ acceptance: { id: 'acc_1', requirement: 'Ship it', status: 'pending' },
+ checks: [],
+ rounds: [],
+ subject: { id: 'task-1', title: 'Ship it', type: 'task' },
+ };
+ getBundle.mockResolvedValue(bundle);
+ getBySubject.mockResolvedValue({ id: 'acc_1' });
+ if (workspaceSlug) {
+ vi.mocked(resolveWorkspaceId).mockReturnValue('ws-1');
+ getWorkspace.mockResolvedValue({ slug: workspaceSlug });
+ }
+ const url = `https://app.lobehub.com${workspaceSlug ? `/${workspaceSlug}` : ''}/acceptance/acc_1`;
+
+ expect(await run([ref, '--json'])).toEqual({ ...bundle, url });
+ expect(await run([ref, '--json', 'acceptance,url'])).toEqual({
+ acceptance: bundle.acceptance,
+ url,
+ });
+ },
+ );
+});
diff --git a/apps/cli/src/commands/acceptance/local/acceptanceDir.ts b/apps/cli/src/commands/acceptance/local/acceptanceDir.ts
new file mode 100644
index 00000000000..911967fffba
--- /dev/null
+++ b/apps/cli/src/commands/acceptance/local/acceptanceDir.ts
@@ -0,0 +1,138 @@
+import { createHash, randomUUID } from 'node:crypto';
+import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+
+import type { LocalAcceptanceInfo } from '@lobechat/utils/verify/localAcceptance';
+import { LOCAL_ACCEPTANCE_FORMAT } from '@lobechat/utils/verify/localAcceptance';
+
+// ============================================
+// A local acceptance is a directory under `.acceptances/`: one subdirectory
+// per immutable round, plus `acceptance.json` (its identity), `reviews.json`
+// (the reviewer's decisions) and `report.html` (the rendered page).
+// ============================================
+
+export const ACCEPTANCE_FILE = 'acceptance.json';
+export const REVIEWS_FILE = 'reviews.json';
+export const REPORT_FILE = 'report.html';
+
+const ROUND_FILE = 'result.json';
+
+/** `20260101-093000-<slug>` — the timestamp `new_round` names a round with. */
+const ROUND_TIMESTAMP = /^(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})(\d{2})(?:-|$)/;
+
+const isRoundDir = (dir: string) => existsSync(path.join(dir, ROUND_FILE));
+
+/**
+ * The acceptance directory a path names: a round directory resolves to the
+ * acceptance it belongs to; an acceptance directory is itself. `undefined`
+ * when the path holds neither.
+ */
+export const resolveAcceptanceDir = (target: string): string | undefined => {
+ const dir = path.resolve(target);
+ if (!existsSync(dir) || !statSync(dir).isDirectory()) return undefined;
+ if (isRoundDir(dir)) return path.dirname(dir);
+ if (existsSync(path.join(dir, ACCEPTANCE_FILE)) || listRoundDirs(dir).length > 0) return dir;
+ return undefined;
+};
+
+/** Round directory names, oldest first — the order `new_round`'s timestamps sort in. */
+export const listRoundDirs = (acceptanceDir: string): string[] =>
+ readdirSync(acceptanceDir, { withFileTypes: true })
+ .filter((entry) => entry.isDirectory() && isRoundDir(path.join(acceptanceDir, entry.name)))
+ .map((entry) => entry.name)
+ .sort((a, b) => a.localeCompare(b));
+
+/** When a round was made: its `new_round` timestamp, else the directory's mtime. */
+export const roundCreatedAt = (acceptanceDir: string, roundDir: string): string => {
+ const match = roundDir.match(ROUND_TIMESTAMP);
+ if (match) {
+ const [, y, mo, d, h, mi, s] = match;
+ const local = new Date(Number(y), Number(mo) - 1, Number(d), Number(h), Number(mi), Number(s));
+ if (!Number.isNaN(local.getTime())) return local.toISOString();
+ }
+ return statSync(path.join(acceptanceDir, roundDir)).mtime.toISOString();
+};
+
+/**
+ * A stable UUID-shaped id derived from its parts, so the same round, result
+ * and evidence keep the same ids every time the report is rendered — the ids
+ * a review decision and a circled region point at.
+ */
+export const localId = (...parts: string[]) => {
+ const hex = createHash('sha256').update(parts.join('\0')).digest('hex');
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-a${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
+};
+
+/**
+ * A local artifact's id: its round, its check, its place in the authored
+ * `evidence` list — the coordinates `ingest` reports each upload by.
+ */
+export const localEvidenceId = (
+ acceptanceId: string,
+ dir: string,
+ checkItemId: string,
+ position: number,
+) => localId(acceptanceId, 'evidence', dir, checkItemId, String(position));
+
+const readJson = (file: string): unknown => {
+ try {
+ return JSON.parse(readFileSync(file, 'utf8'));
+ } catch {
+ return undefined;
+ }
+};
+
+export const readAcceptanceInfo = (acceptanceDir: string): LocalAcceptanceInfo | undefined => {
+ const raw = readJson(path.join(acceptanceDir, ACCEPTANCE_FILE)) as
+ Partial<LocalAcceptanceInfo> | undefined;
+ if (!raw || typeof raw.id !== 'string') return undefined;
+ return {
+ createdAt: typeof raw.createdAt === 'string' ? raw.createdAt : new Date().toISOString(),
+ id: raw.id,
+ ...(raw.remote ? { remote: raw.remote } : {}),
+ requirement: typeof raw.requirement === 'string' ? raw.requirement : null,
+ subjectKey: path.basename(acceptanceDir),
+ };
+};
+
+export const writeAcceptanceInfo = (acceptanceDir: string, info: LocalAcceptanceInfo) => {
+ const { subjectKey: _subjectKey, ...stored } = info;
+ writeFileSync(
+ path.join(acceptanceDir, ACCEPTANCE_FILE),
+ `${JSON.stringify({ format: LOCAL_ACCEPTANCE_FORMAT, ...stored }, null, 2)}\n`,
+ );
+};
+
+/**
+ * The acceptance's identity, minted on first use. The requirement is the
+ * durable goal of the whole acceptance and, as on LobeHub, is recorded once:
+ * a later, different one is reported back instead of overwriting it.
+ */
+export const ensureAcceptanceInfo = (
+ acceptanceDir: string,
+ requirement?: string,
+): { info: LocalAcceptanceInfo; keptRequirement?: string } => {
+ const existing = readAcceptanceInfo(acceptanceDir);
+ const wanted = requirement?.trim() || undefined;
+ if (existing) {
+ if (!existing.requirement && wanted) {
+ const info = { ...existing, requirement: wanted };
+ writeAcceptanceInfo(acceptanceDir, info);
+ return { info };
+ }
+ const keptRequirement =
+ wanted && existing.requirement && wanted !== existing.requirement
+ ? existing.requirement
+ : undefined;
+ return { info: existing, keptRequirement };
+ }
+
+ const info: LocalAcceptanceInfo = {
+ createdAt: new Date().toISOString(),
+ id: randomUUID(),
+ requirement: wanted ?? null,
+ subjectKey: path.basename(acceptanceDir),
+ };
+ writeAcceptanceInfo(acceptanceDir, info);
+ return { info };
+};
diff --git a/apps/cli/src/commands/acceptance/local/imageSize.test.ts b/apps/cli/src/commands/acceptance/local/imageSize.test.ts
new file mode 100644
index 00000000000..8c16a291a72
--- /dev/null
+++ b/apps/cli/src/commands/acceptance/local/imageSize.test.ts
@@ -0,0 +1,50 @@
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { readImageSize } from './imageSize';
+import { pngHeader } from './testUtils';
+
+let dir: string;
+const file = (name: string, content: Buffer) => {
+ const target = path.join(dir, name);
+ writeFileSync(target, content);
+ return target;
+};
+
+describe('readImageSize', () => {
+ beforeEach(() => {
+ dir = mkdtempSync(path.join(tmpdir(), 'lh-image-size-'));
+ });
+
+ afterEach(() => {
+ rmSync(dir, { force: true, recursive: true });
+ });
+
+ it('reads PNG, GIF and JPEG headers', () => {
+ expect(readImageSize(file('a.png', pngHeader(1280, 720)))).toEqual({
+ height: 720,
+ width: 1280,
+ });
+
+ const gif = Buffer.alloc(13);
+ gif.write('GIF89a', 0, 'ascii');
+ gif.writeUInt16LE(320, 6);
+ gif.writeUInt16LE(240, 8);
+ expect(readImageSize(file('b.gif', gif))).toEqual({ height: 240, width: 320 });
+
+ // SOI, an APP0 segment, then a baseline frame header.
+ const jpeg = Buffer.from([
+ 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x04, 0x00, 0x00, 0xff, 0xc0, 0x00, 0x11, 0x08, 0x01, 0x90,
+ 0x02, 0x58, 0x03, 0x01, 0x22, 0x00,
+ ]);
+ expect(readImageSize(file('c.jpg', jpeg))).toEqual({ height: 400, width: 600 });
+ });
+
+ it('answers null for anything it cannot read', () => {
+ expect(readImageSize(file('d.png', Buffer.from('not an image')))).toBeNull();
+ expect(readImageSize(path.join(dir, 'missing.png'))).toBeNull();
+ });
+});
diff --git a/apps/cli/src/commands/acceptance/local/imageSize.ts b/apps/cli/src/commands/acceptance/local/imageSize.ts
new file mode 100644
index 00000000000..4ae2846320f
--- /dev/null
+++ b/apps/cli/src/commands/acceptance/local/imageSize.ts
@@ -0,0 +1,68 @@
+import { closeSync, openSync, readSync } from 'node:fs';
+
+/**
+ * Intrinsic pixel size of a PNG, JPEG, GIF or WebP, read from its header.
+ * The page reserves each screenshot's aspect ratio before it loads (as the
+ * hosted page does from the upload's metadata), so an expanding check never
+ * jumps. Anything unrecognized is `null` — the image still renders.
+ */
+export const readImageSize = (file: string): { height: number; width: number } | null => {
+ let fd: number | undefined;
+ try {
+ fd = openSync(file, 'r');
+ const head = Buffer.alloc(64 * 1024);
+ const length = readSync(fd, head, 0, head.length, 0);
+ return parse(head.subarray(0, length));
+ } catch {
+ return null;
+ } finally {
+ if (fd !== undefined) closeSync(fd);
+ }
+};
+
+const valid = (width: number, height: number) =>
+ width > 0 && height > 0 ? { height, width } : null;
+
+const parse = (buf: Buffer) => {
+ // PNG: signature, then the IHDR chunk.
+ if (
+ buf.length >= 24 &&
+ buf.readUInt32BE(0) === 0x89_50_4e_47 &&
+ buf.toString('ascii', 12, 16) === 'IHDR'
+ )
+ return valid(buf.readUInt32BE(16), buf.readUInt32BE(20));
+
+ // GIF: logical screen descriptor.
+ if (buf.length >= 10 && buf.toString('ascii', 0, 3) === 'GIF')
+ return valid(buf.readUInt16LE(6), buf.readUInt16LE(8));
+
+ // WebP: RIFF container with a VP8 / VP8L / VP8X chunk.
+ if (
+ buf.length >= 30 &&
+ buf.toString('ascii', 0, 4) === 'RIFF' &&
+ buf.toString('ascii', 8, 12) === 'WEBP'
+ ) {
+ const chunk = buf.toString('ascii', 12, 16);
+ if (chunk === 'VP8 ')
+ return valid(buf.readUInt16LE(26) & 0x3f_ff, buf.readUInt16LE(28) & 0x3f_ff);
+ if (chunk === 'VP8L') {
+ const bits = buf.readUInt32LE(21);
+ return valid((bits & 0x3f_ff) + 1, ((bits >> 14) & 0x3f_ff) + 1);
+ }
+ if (chunk === 'VP8X') return valid(buf.readUIntLE(24, 3) + 1, buf.readUIntLE(27, 3) + 1);
+ }
+
+ // JPEG: walk the markers to the first start-of-frame.
+ if (buf.length >= 4 && buf[0] === 0xff && buf[1] === 0xd8) {
+ let offset = 2;
+ while (offset + 9 < buf.length) {
+ if (buf[offset] !== 0xff) return null;
+ const marker = buf[offset + 1]!;
+ const size = buf.readUInt16BE(offset + 2);
+ const isFrame = marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker);
+ if (isFrame) return valid(buf.readUInt16BE(offset + 7), buf.readUInt16BE(offset + 5));
+ offset += 2 + size;
+ }
+ }
+ return null;
+};
diff --git a/apps/cli/src/commands/acceptance/local/localAcceptance.test.ts b/apps/cli/src/commands/acceptance/local/localAcceptance.test.ts
new file mode 100644
index 00000000000..cc9a51791d9
--- /dev/null
+++ b/apps/cli/src/commands/acceptance/local/localAcceptance.test.ts
@@ -0,0 +1,187 @@
+import { mkdirSync, readFileSync, utimesSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+
+import { assembleLocalAcceptance } from '@lobechat/utils/verify/localAcceptance';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { log } from '../../../utils/logger';
+import { ReportRoundError } from '../run/reportRound';
+import { ACCEPTANCE_FILE, REVIEWS_FILE } from './acceptanceDir';
+import { findSavedReviewLog, loadLocalAcceptance, reviewExportPrefix } from './localAcceptance';
+import { createLocalAcceptance, firstRound } from './testUtils';
+
+describe('loadLocalAcceptance', () => {
+ let fixture: ReturnType<typeof createLocalAcceptance>;
+
+ beforeEach(() => {
+ vi.spyOn(log, 'warn').mockImplementation(() => {});
+ fixture = createLocalAcceptance([firstRound()]);
+ vi.stubEnv('LOBEHUB_ACCEPTANCE_DOWNLOADS', path.join(fixture.root, 'Downloads'));
+ vi.stubEnv('XDG_DOWNLOAD_DIR', path.join(fixture.root, 'Downloads'));
+ vi.stubEnv('HOME', fixture.root);
+ });
+
+ afterEach(() => {
+ fixture.cleanup();
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ });
+
+ it('reads a round the way ingest publishes it', () => {
+ const roundDir = path.join(fixture.acceptanceDir, '20260101-090000-first');
+ const { info, rounds, source } = loadLocalAcceptance(roundDir, {
+ create: true,
+ requirement: 'Users can rename a topic',
+ });
+
+ expect(info.requirement).toBe('Users can rename a topic');
+ expect(info.subjectKey).toBe('standalone-demo');
+ const [round] = rounds;
+ // The test gate is screened out exactly as on ingest.
+ expect(round!.droppedLabels).toEqual(['unit — Unit tests pass']);
+ expect(round!.source.results.map((result) => result.checkItemId)).toEqual(['rename']);
+ expect(round!.source.results[0]).toMatchObject({
+ toulmin: { evidence: 'The list shows the new title.' },
+ verdict: 'passed',
+ });
+ // The never-run video check is an open gap, not a pass.
+ expect(round!.unexecuted).toEqual(['enter']);
+ expect(round!.missingEvidence).toEqual([{ checkItemId: 'enter', types: ['video'] }]);
+ expect(round!.source.report).toMatchObject({
+ totalChecks: 2,
+ passedChecks: 1,
+ verdict: 'uncertain',
+ });
+
+ const [screenshot, text] = round!.source.evidence;
+ // Relative to the acceptance directory, where report.html lives; spaces encoded.
+ expect(screenshot).toMatchObject({
+ content: null,
+ fileHeight: 600,
+ fileUrl: '20260101-090000-first/assets/after%20shot.png',
+ fileWidth: 800,
+ type: 'screenshot',
+ });
+ // A page opened from disk cannot fetch siblings: text travels inline.
+ expect(text).toMatchObject({
+ content: expect.stringContaining('Weekly sync'),
+ fileUrl: null,
+ type: 'text',
+ });
+ expect(source.rounds[0]!.proposal).toBe('Rename keeps the new title.');
+ expect(source.rounds[0]!.run.createdAt).toBe(new Date(2026, 0, 1, 9, 0, 0).toISOString());
+ });
+
+ it('keeps ids stable across reads, so decisions stay on their evidence', () => {
+ const first = loadLocalAcceptance(fixture.acceptanceDir, { create: true });
+ const second = loadLocalAcceptance(fixture.acceptanceDir);
+ expect(second.info.id).toBe(first.info.id);
+ expect(second.source.rounds[0]!.results[0]!.id).toBe(first.source.rounds[0]!.results[0]!.id);
+ expect(second.source.rounds[0]!.evidence.map((item) => item.id)).toEqual(
+ first.source.rounds[0]!.evidence.map((item) => item.id),
+ );
+ });
+
+ it('records the requirement once', () => {
+ loadLocalAcceptance(fixture.acceptanceDir, { create: true, requirement: 'First goal' });
+ const again = loadLocalAcceptance(fixture.acceptanceDir, {
+ create: true,
+ requirement: 'Another goal',
+ });
+ expect(again.info.requirement).toBe('First goal');
+ expect(again.keptRequirement).toBe('First goal');
+ const stored = JSON.parse(
+ readFileSync(path.join(fixture.acceptanceDir, ACCEPTANCE_FILE), 'utf8'),
+ );
+ expect(stored).toMatchObject({ format: 1, requirement: 'First goal' });
+ expect(stored.subjectKey).toBeUndefined();
+ });
+
+ it('downgrades a pass whose required evidence is missing', () => {
+ const round = firstRound();
+ round.dir = '20260102-090000-second';
+ round.assets = {};
+ fixture.addRound(round);
+ const { rounds } = loadLocalAcceptance(fixture.acceptanceDir, { create: true });
+ const second = rounds[1]!;
+ expect(second.failedEvidence.map((item) => path.basename(item.path))).toEqual([
+ 'after shot.png',
+ 'api.txt',
+ ]);
+ expect(second.source.results[0]).toMatchObject({
+ toulmin: { limitation: 'Required evidence not published: screenshot, text.' },
+ verdict: 'uncertain',
+ });
+ });
+
+ it('refuses a round of nothing but programmatic gates', () => {
+ const round = firstRound();
+ round.dir = '20260103-090000-gates';
+ round.result = { cases: [{ id: 'unit', name: 'Unit tests pass', status: 'pass' }] };
+ fixture.addRound(round);
+ expect(() => loadLocalAcceptance(fixture.acceptanceDir, { create: true })).toThrow(
+ ReportRoundError,
+ );
+ });
+
+ it('reads the review log the page saved to the downloads folder', () => {
+ const { info, source } = loadLocalAcceptance(fixture.acceptanceDir, { create: true });
+ const bundle = assembleLocalAcceptance(source);
+ const reviewLog = {
+ acceptanceId: info.id,
+ events: [
+ {
+ action: 'reject',
+ comment: 'Title is cut off',
+ createdAt: '2026-01-01T10:00:00.000Z',
+ id: 'event-1',
+ kind: 'checks',
+ roundIndex: 1,
+ targets: [{ checkId: 'rename', resultId: bundle.checks[0]!.result!.id }],
+ },
+ ],
+ format: 1,
+ };
+ const downloads = path.join(fixture.root, 'Downloads');
+ mkdirSync(downloads);
+ // A second save of the same name gets a browser suffix; the newest one wins.
+ writeFileSync(
+ path.join(downloads, `${reviewExportPrefix(info.id)}.json`),
+ JSON.stringify({ ...reviewLog, events: [] }),
+ );
+ const newest = path.join(downloads, `${reviewExportPrefix(info.id)} (1).json`);
+ writeFileSync(newest, JSON.stringify(reviewLog));
+ const later = new Date(Date.now() + 1000);
+ utimesSync(newest, later, later);
+
+ expect(findSavedReviewLog(info.id)).toBe(newest);
+ const read = loadLocalAcceptance(fixture.acceptanceDir);
+ expect(read.reviewsImported).toEqual({ added: 1, file: newest });
+ expect(assembleLocalAcceptance(read.source).checks[0]!.userReview).toMatchObject({
+ action: 'reject',
+ comment: 'Title is cut off',
+ stale: false,
+ });
+ // Filed beside the rounds; reading the same download again adds nothing.
+ expect(
+ JSON.parse(readFileSync(path.join(fixture.acceptanceDir, REVIEWS_FILE), 'utf8')).events,
+ ).toHaveLength(1);
+ expect(loadLocalAcceptance(fixture.acceptanceDir).reviewsImported).toEqual({
+ added: 0,
+ file: newest,
+ });
+ });
+
+ it('rejects a saved review log of another acceptance', () => {
+ loadLocalAcceptance(fixture.acceptanceDir, { create: true });
+ const file = path.join(fixture.root, 'other.json');
+ writeFileSync(file, JSON.stringify({ acceptanceId: 'someone-else', events: [], format: 1 }));
+ expect(() => loadLocalAcceptance(fixture.acceptanceDir, { reviewsFile: file })).toThrow(
+ 'reviews of another acceptance',
+ );
+ });
+
+ it('needs a render before read-only commands', () => {
+ expect(() => loadLocalAcceptance(fixture.acceptanceDir)).toThrow('no acceptance.json yet');
+ });
+});
diff --git a/apps/cli/src/commands/acceptance/local/localAcceptance.ts b/apps/cli/src/commands/acceptance/local/localAcceptance.ts
new file mode 100644
index 00000000000..168f6791bd9
--- /dev/null
+++ b/apps/cli/src/commands/acceptance/local/localAcceptance.ts
@@ -0,0 +1,182 @@
+import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
+import { homedir } from 'node:os';
+import path from 'node:path';
+
+import type {
+ LocalAcceptanceInfo,
+ LocalAcceptanceSource,
+ LocalReviewEvent,
+ LocalReviewLog,
+} from '@lobechat/utils/verify/localAcceptance';
+import {
+ LOCAL_ACCEPTANCE_FORMAT,
+ mergeLocalReviewEvents,
+} from '@lobechat/utils/verify/localAcceptance';
+
+import {
+ ensureAcceptanceInfo,
+ listRoundDirs,
+ readAcceptanceInfo,
+ resolveAcceptanceDir,
+ REVIEWS_FILE,
+} from './acceptanceDir';
+import { type LocalRoundRead, readLocalRound } from './localRound';
+
+/** The file name the report page saves its review log as (see `LocalReviewBar`). */
+export const reviewExportPrefix = (acceptanceId: string) => `acceptance-reviews-${acceptanceId}`;
+
+const readReviewLog = (file: string): LocalReviewLog | undefined => {
+ try {
+ const raw = JSON.parse(readFileSync(file, 'utf8')) as Partial<LocalReviewLog>;
+ if (raw.format !== LOCAL_ACCEPTANCE_FORMAT || !Array.isArray(raw.events)) return undefined;
+ return { acceptanceId: String(raw.acceptanceId ?? ''), events: raw.events, format: raw.format };
+ } catch {
+ return undefined;
+ }
+};
+
+/** Where a browser saves the page's review log: `$XDG_DOWNLOAD_DIR`, else `~/Downloads`. */
+const downloadDirs = () => {
+ const dirs = [process.env.LOBEHUB_ACCEPTANCE_DOWNLOADS, process.env.XDG_DOWNLOAD_DIR];
+ try {
+ const userDirs = readFileSync(path.join(homedir(), '.config/user-dirs.dirs'), 'utf8');
+ const match = userDirs.match(/^XDG_DOWNLOAD_DIR="?([^"\n]+)"?/m);
+ if (match) dirs.push(match[1]!.replace('$HOME', homedir()));
+ } catch {
+ // Not a freedesktop system.
+ }
+ dirs.push(path.join(homedir(), 'Downloads'));
+ return [...new Set(dirs.filter((dir): dir is string => Boolean(dir)))];
+};
+
+/** The newest review log the page saved for this acceptance (`… (1).json` included). */
+export const findSavedReviewLog = (acceptanceId: string): string | undefined => {
+ const prefix = reviewExportPrefix(acceptanceId);
+ let newest: { file: string; mtime: number } | undefined;
+ for (const dir of downloadDirs()) {
+ let names: string[];
+ try {
+ names = readdirSync(dir);
+ } catch {
+ continue;
+ }
+ for (const name of names) {
+ if (!name.startsWith(prefix) || !name.endsWith('.json')) continue;
+ const file = path.join(dir, name);
+ const mtime = statSync(file).mtimeMs;
+ if (!newest || mtime > newest.mtime) newest = { file, mtime };
+ }
+ }
+ return newest?.file;
+};
+
+/**
+ * Fold a saved review log into the acceptance's `reviews.json`. Merging is by
+ * event id, so reading the same download twice changes nothing.
+ */
+export const importReviewLog = (
+ acceptanceDir: string,
+ acceptanceId: string,
+ file: string,
+): { added: number; events: LocalReviewEvent[] } => {
+ const incoming = readReviewLog(file);
+ if (!incoming) throw new Error(`${file} is not an acceptance review log`);
+ if (incoming.acceptanceId !== acceptanceId)
+ throw new Error(`${file} holds reviews of another acceptance (${incoming.acceptanceId})`);
+ const current = readReviewLog(path.join(acceptanceDir, REVIEWS_FILE))?.events ?? [];
+ const events = mergeLocalReviewEvents(current, incoming.events);
+ const added = events.length - current.length;
+ if (added > 0) writeReviewLog(acceptanceDir, acceptanceId, events);
+ return { added, events };
+};
+
+export const writeReviewLog = (
+ acceptanceDir: string,
+ acceptanceId: string,
+ events: LocalReviewEvent[],
+) => {
+ const log: LocalReviewLog = { acceptanceId, events, format: LOCAL_ACCEPTANCE_FORMAT };
+ writeFileSync(path.join(acceptanceDir, REVIEWS_FILE), `${JSON.stringify(log, null, 2)}\n`);
+};
+
+export interface LocalAcceptanceRead {
+ acceptanceDir: string;
+ info: LocalAcceptanceInfo;
+ /** A requirement passed now that differs from the one recorded first. */
+ keptRequirement?: string;
+ /** The saved review log read in this call, with how many decisions were new. */
+ reviewsImported?: { added: number; file: string };
+ rounds: LocalRoundRead[];
+ source: LocalAcceptanceSource;
+}
+
+/**
+ * Read a local acceptance — every round, plus the reviewer's decisions —
+ * into the source its page renders from. `target` is the acceptance directory
+ * or any of its round directories.
+ */
+export function loadLocalAcceptance(
+ target: string,
+ options: {
+ /** Create `acceptance.json` when missing (render does; read-only commands do not). */
+ create?: boolean;
+ requirement?: string;
+ /** A review log to read instead of looking in the downloads folder. */
+ reviewsFile?: string;
+ /** Warn about authoring gaps of the newest round. */
+ warnLatest?: boolean;
+ } = {},
+): LocalAcceptanceRead {
+ const acceptanceDir = resolveAcceptanceDir(target);
+ if (!acceptanceDir) throw new Error(`${target} is not a local acceptance or round directory`);
+
+ let info: LocalAcceptanceInfo;
+ let keptRequirement: string | undefined;
+ if (options.create) {
+ ({ info, keptRequirement } = ensureAcceptanceInfo(acceptanceDir, options.requirement));
+ } else {
+ const existing = readAcceptanceInfo(acceptanceDir);
+ if (!existing)
+ throw new Error(
+ `${acceptanceDir} has no acceptance.json yet — render it first with \`lh acceptance run render\``,
+ );
+ info = existing;
+ }
+
+ const dirs = listRoundDirs(acceptanceDir);
+ const rounds = dirs.map((dir, index) =>
+ readLocalRound({
+ acceptanceDir,
+ acceptanceId: info.id,
+ dir,
+ roundIndex: index + 1,
+ warn: options.warnLatest && index === dirs.length - 1,
+ }),
+ );
+
+ const savedLog = options.reviewsFile ?? findSavedReviewLog(info.id);
+ let reviewsImported: LocalAcceptanceRead['reviewsImported'];
+ let events = readReviewLog(path.join(acceptanceDir, REVIEWS_FILE))?.events ?? [];
+ if (savedLog && existsSync(savedLog)) {
+ const imported = importReviewLog(acceptanceDir, info.id, savedLog);
+ events = imported.events;
+ reviewsImported = { added: imported.added, file: savedLog };
+ } else if (options.reviewsFile) {
+ throw new Error(`${options.reviewsFile} does not exist`);
+ }
+
+ return {
+ acceptanceDir,
+ info,
+ keptRequirement,
+ reviewsImported,
+ rounds,
+ source: {
+ acceptance: info,
+ format: LOCAL_ACCEPTANCE_FORMAT,
+ generatedAt: new Date().toISOString(),
+ reviews: events,
+ rounds: rounds.map((round) => round.source),
+ },
+ };
+}
diff --git a/apps/cli/src/commands/acceptance/local/localBundle.ts b/apps/cli/src/commands/acceptance/local/localBundle.ts
new file mode 100644
index 00000000000..f55f6eb5d6d
--- /dev/null
+++ b/apps/cli/src/commands/acceptance/local/localBundle.ts
@@ -0,0 +1,28 @@
+import {
+ assembleLocalAcceptance,
+ localAcceptanceComments,
+} from '@lobechat/utils/verify/localAcceptance';
+
+import { resolveAcceptanceDir } from './acceptanceDir';
+import { loadLocalAcceptance } from './localAcceptance';
+
+/**
+ * Whether a `view` / `feedback` argument names a local acceptance (or one of
+ * its rounds) rather than a LobeHub acceptance id or `type:id` subject.
+ */
+export const localAcceptanceTarget = (ref: string): string | undefined =>
+ /[\\/]/.test(ref) || ref.startsWith('.') ? resolveAcceptanceDir(ref) : undefined;
+
+/**
+ * A local acceptance read the way `acceptance.getBundle` and
+ * `acceptanceComment.list` answer for a published one — same union, same
+ * review overlay — so the commands that read feedback need no second code path.
+ */
+export const readLocalBundle = (target: string, options: { reviewsFile?: string } = {}) => {
+ const read = loadLocalAcceptance(target, { reviewsFile: options.reviewsFile });
+ return {
+ bundle: assembleLocalAcceptance(read.source),
+ comments: localAcceptanceComments(read.source),
+ read,
+ };
+};
diff --git a/apps/cli/src/commands/acceptance/local/localRound.ts b/apps/cli/src/commands/acceptance/local/localRound.ts
new file mode 100644
index 00000000000..cda37ae6c03
--- /dev/null
+++ b/apps/cli/src/commands/acceptance/local/localRound.ts
@@ -0,0 +1,220 @@
+import { existsSync, readFileSync, statSync } from 'node:fs';
+import path from 'node:path';
+
+import { normalizeEvidenceMetadata } from '@lobechat/const/verify';
+import type { VerifyRunContext, VerifyRunMetadata } from '@lobechat/types';
+import type {
+ LocalEvidenceSource,
+ LocalResultSource,
+ LocalRoundSource,
+} from '@lobechat/utils/verify/localAcceptance';
+
+import { log } from '../../../utils/logger';
+import {
+ caseResult,
+ missingEvidenceLimitation,
+ publishedVerdictFor,
+ readReportRound,
+ requiredEvidenceGaps,
+ settleReport,
+ unexecutedEvidenceGaps,
+} from '../run/reportRound';
+import {
+ evidenceDescriptionForFile,
+ type EvidenceType,
+ evidenceTypeForFile,
+ INLINE_TEXT_EVIDENCE_TYPES,
+ interactionCostFromReportDir,
+ metadataForReport,
+ reportEvidence,
+ type Verdict,
+} from '../utils';
+import { localEvidenceId, localId, roundCreatedAt } from './acceptanceDir';
+import { readImageSize } from './imageSize';
+
+/**
+ * A page opened from disk cannot fetch a sibling file, so text evidence is
+ * carried in the page itself — up to this size. Bigger logs stay files the
+ * reader opens directly.
+ */
+const LOCAL_INLINE_TEXT_LIMIT = 256 * 1024;
+
+const inlineText = (file: string, type: EvidenceType): string | null => {
+ if (!INLINE_TEXT_EVIDENCE_TYPES.has(type)) return null;
+ try {
+ if (statSync(file).size > LOCAL_INLINE_TEXT_LIMIT) return null;
+ const buffer = readFileSync(file);
+ if (buffer.includes(0)) return null;
+ const content = buffer.toString('utf8');
+ return content.length > 0 ? content : null;
+ } catch {
+ return null;
+ }
+};
+
+/** A path the page can load: relative to the acceptance directory, URL-encoded. */
+const pageUrl = (acceptanceDir: string, file: string) =>
+ path.relative(acceptanceDir, file).split(path.sep).map(encodeURIComponent).join('/');
+
+export interface LocalRoundRead {
+ droppedLabels: string[];
+ failedEvidence: { checkItemId: string; path: string; reason: 'file_missing' }[];
+ missingEvidence: { checkItemId: string; types: EvidenceType[] }[];
+ source: LocalRoundSource;
+ unexecuted: string[];
+}
+
+/**
+ * Read one round directory into the rows `ingest` would publish for it —
+ * through the same reader, so the local page shows exactly the checks,
+ * verdicts and evidence gaps the hosted one would.
+ */
+export function readLocalRound(params: {
+ acceptanceDir: string;
+ acceptanceId: string;
+ dir: string;
+ roundIndex: number;
+ /** Only the round being rendered now warns about its own authoring gaps. */
+ warn?: boolean;
+}): LocalRoundRead {
+ const { acceptanceDir, acceptanceId, dir, roundIndex } = params;
+ const roundPath = path.join(acceptanceDir, dir);
+ const round = readReportRound(roundPath, { inferPullRequest: false, quiet: !params.warn });
+ const createdAt =
+ typeof round.result.createdAt === 'string' &&
+ !Number.isNaN(new Date(round.result.createdAt).getTime())
+ ? new Date(round.result.createdAt).toISOString()
+ : roundCreatedAt(acceptanceDir, dir);
+ const runId = localId(acceptanceId, 'run', dir);
+
+ const results: LocalResultSource[] = [];
+ const evidence: LocalEvidenceSource[] = [];
+ const missingEvidence: LocalRoundRead['missingEvidence'] = [];
+ const failedEvidence: LocalRoundRead['failedEvidence'] = [];
+ const publishedVerdicts: Verdict[] = [];
+ const executed = new Set<string>();
+
+ for (const [index, { case: c, checkItemId }] of round.cases.entries()) {
+ executed.add(checkItemId);
+ const result = caseResult(c, checkItemId, index, round.caseMetadata[index]);
+ const resultId = localId(acceptanceId, 'result', dir, checkItemId);
+
+ const present = new Set<EvidenceType>();
+ for (const [position, input] of reportEvidence(c.evidence).entries()) {
+ const file = path.resolve(roundPath, input.path);
+ if (!existsSync(file)) {
+ failedEvidence.push({ checkItemId, path: file, reason: 'file_missing' });
+ if (params.warn) log.warn(`evidence not found: ${input.path}`);
+ continue;
+ }
+ const type = evidenceTypeForFile(file);
+ // The metadata the server stores for an upload: chapters only on video.
+ const metadata =
+ input.comparison || input.chapters
+ ? normalizeEvidenceMetadata(
+ {
+ ...(input.chapters ? { chapters: input.chapters } : {}),
+ ...(input.comparison ? { comparison: input.comparison } : {}),
+ },
+ type,
+ )
+ : null;
+ const content = inlineText(file, type);
+ const size = type === 'screenshot' || type === 'gif' ? readImageSize(file) : null;
+ present.add(type);
+ evidence.push({
+ checkResultId: resultId,
+ content,
+ createdAt,
+ description: evidenceDescriptionForFile(input.description, file) ?? null,
+ fileHeight: size?.height ?? null,
+ fileName: path.basename(file),
+ fileUrl: content === null ? pageUrl(acceptanceDir, file) : null,
+ fileWidth: size?.width ?? null,
+ id: localEvidenceId(acceptanceId, dir, checkItemId, position),
+ metadata: metadata ?? null,
+ type,
+ });
+ }
+
+ const gaps = requiredEvidenceGaps(round.plan, checkItemId, present);
+ const verdict = publishedVerdictFor(result.verdict, gaps);
+ publishedVerdicts.push(verdict);
+ if (gaps.length > 0) {
+ missingEvidence.push({ checkItemId, types: gaps });
+ if (params.warn) log.warn(`${checkItemId}: ${missingEvidenceLimitation(gaps)}`);
+ }
+ results.push({
+ checkItemId,
+ checkItemIndex: index,
+ checkItemTitle: String(result.checkItemTitle),
+ createdAt,
+ id: resultId,
+ metadata: (result.metadata as LocalResultSource['metadata']) ?? null,
+ required: Boolean(result.required),
+ suggestion: result.suggestion,
+ toulmin:
+ gaps.length > 0
+ ? { ...result.toulmin, limitation: missingEvidenceLimitation(gaps) }
+ : result.toulmin,
+ verdict,
+ });
+ }
+
+ const unexecuted = round.plan?.filter((item) => !executed.has(item.id)) ?? [];
+ for (const { item, types } of unexecutedEvidenceGaps(round.plan, executed)) {
+ missingEvidence.push({ checkItemId: item.id, types });
+ publishedVerdicts.push('uncertain');
+ if (params.warn)
+ log.warn(`${item.id}: not executed; required evidence not published: ${types.join(', ')}.`);
+ }
+
+ const result = round.result;
+ const tracedCost = interactionCostFromReportDir(roundPath, result);
+ const metadata = metadataForReport(
+ tracedCost ? { ...result, interactionCost: tracedCost } : result,
+ );
+ const report = settleReport({
+ allCasesCount: round.allCases.length,
+ casesCount: round.cases.length,
+ conclusion: round.conclusion,
+ content: round.content,
+ missingEvidenceCount: missingEvidence.length,
+ publishedVerdicts,
+ summary: round.summary,
+ });
+
+ return {
+ droppedLabels: round.droppedLabels,
+ failedEvidence,
+ missingEvidence,
+ source: {
+ dir,
+ evidence,
+ proposal: round.proposal || null,
+ report: {
+ content: report.content ?? null,
+ failedChecks: report.failedChecks ?? null,
+ overallConfidence: report.overallConfidence ?? null,
+ passedChecks: report.passedChecks ?? null,
+ summary: report.summary ?? null,
+ totalChecks: report.totalChecks ?? null,
+ uncertainChecks: report.uncertainChecks ?? null,
+ verdict: report.verdict ?? null,
+ },
+ results,
+ run: {
+ context: (round.context as VerifyRunContext | undefined) ?? null,
+ createdAt,
+ goal: round.goal ?? null,
+ id: runId,
+ metadata: (metadata as VerifyRunMetadata | undefined) ?? null,
+ plan: round.plan ?? null,
+ roundIndex,
+ scenario: round.scenario,
+ title: round.title ?? null,
+ },
+ },
+ unexecuted: unexecuted.map((item) => item.id),
+ };
+}
diff --git a/apps/cli/src/commands/acceptance/local/mode.ts b/apps/cli/src/commands/acceptance/local/mode.ts
new file mode 100644
index 00000000000..e8f3f212ea5
--- /dev/null
+++ b/apps/cli/src/commands/acceptance/local/mode.ts
@@ -0,0 +1,20 @@
+import { existsSync } from 'node:fs';
+
+import { credentialsPath, pickAuthSource } from '../../../auth/source';
+
+/**
+ * Whether this machine has no credential in the environment and no stored
+ * login file. Such a user gets local reports. A login
+ * that exists but no longer works is NOT signed out — they expect their
+ * acceptance to publish, so the failure must surface instead.
+ */
+export const isSignedOut = (): boolean => {
+ if (pickAuthSource().kind !== 'stored') return false;
+ // Token lookup also reports `no-login` for expired credentials without a
+ // refresh token, and unreadable files cannot be distinguished by loading.
+ // Leave validation and refresh to the authenticated path, not mode selection.
+ return !existsSync(credentialsPath());
+};
+
+export const LOCAL_MODE_INSTRUCTION =
+ 'Not signed in to LobeHub, so acceptance runs locally: write each round as usual and render it with `lh acceptance run render <roundDir>`; nothing is uploaded. No account language is set — write every human-readable acceptance field in the language the user converses in, and pass it to any subagent you delegate to. To share the acceptance for team review later, the user signs in and runs `lh acceptance publish <acceptanceDir>`.';
diff --git a/apps/cli/src/commands/acceptance/local/publish.test.ts b/apps/cli/src/commands/acceptance/local/publish.test.ts
new file mode 100644
index 00000000000..3f448cd7526
--- /dev/null
+++ b/apps/cli/src/commands/acceptance/local/publish.test.ts
@@ -0,0 +1,317 @@
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+
+import { assembleLocalAcceptance } from '@lobechat/utils/verify/localAcceptance';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as Format from '../../../utils/format';
+import { log } from '../../../utils/logger';
+import { ACCEPTANCE_FILE } from './acceptanceDir';
+import { loadLocalAcceptance, writeReviewLog } from './localAcceptance';
+import { publishAction } from './publish';
+import { createLocalAcceptance, firstRound } from './testUtils';
+
+const { client, ingestReportAction, outputJson } = vi.hoisted(() => ({
+ client: {
+ acceptance: {
+ addGroupFeedback: { mutate: vi.fn() },
+ getBundle: { query: vi.fn() },
+ reviewChecks: { mutate: vi.fn() },
+ },
+ },
+ ingestReportAction: vi.fn(),
+ outputJson: vi.fn(),
+}));
+vi.mock('../../../api/client', () => ({ getTrpcClient: async () => client }));
+vi.mock('../run/ingest', () => ({ ingestReportAction }));
+vi.mock('../../../utils/format', async (original) => ({
+ ...(await original<typeof Format>()),
+ outputJson,
+}));
+
+const ingested = (
+ roundIndex: number,
+ publishedEvidence: { checkItemId: string; evidenceId: string; position: number }[] = [],
+) => ({
+ acceptanceId: 'remote-acceptance',
+ acceptanceUrl: 'https://app.lobehub.com/acceptance/remote-acceptance',
+ failedEvidence: [],
+ missingEvidence: [],
+ publicationStatus: 'complete',
+ publishedEvidence,
+ roundIndex,
+ verifyRunId: `remote-run-${roundIndex}`,
+});
+
+/** Both artifacts of the fixture's `rename` check, uploaded in order. */
+const bothUploaded = [
+ { checkItemId: 'rename', evidenceId: 'remote-shot', position: 0 },
+ { checkItemId: 'rename', evidenceId: 'remote-api', position: 1 },
+];
+
+const remoteBundle = (evidence: { id: string }[]) => ({
+ checks: [
+ {
+ id: 'criterion-rename',
+ planItem: { id: 'rename' },
+ result: { id: 'remote-result' },
+ timeline: [{ evidence, verifyRunId: 'remote-run-1' }],
+ },
+ ],
+});
+
+describe('lh acceptance publish', () => {
+ let fixture: ReturnType<typeof createLocalAcceptance>;
+
+ beforeEach(() => {
+ vi.resetAllMocks();
+ vi.spyOn(log, 'warn').mockImplementation(() => {});
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ fixture = createLocalAcceptance([firstRound()], 'task-T-12');
+ vi.stubEnv('LOBEHUB_ACCEPTANCE_DOWNLOADS', path.join(fixture.root, 'Downloads'));
+ vi.stubEnv('HOME', fixture.root);
+ });
+
+ afterEach(() => {
+ fixture.cleanup();
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ });
+
+ it('replays unpublished rounds in order into one acceptance, and resumes after them', async () => {
+ loadLocalAcceptance(fixture.acceptanceDir, { create: true, requirement: 'Rename works' });
+ const second = firstRound();
+ second.dir = '20260102-090000-second';
+ fixture.addRound(second);
+ ingestReportAction.mockResolvedValueOnce(ingested(1)).mockResolvedValueOnce(ingested(2));
+
+ await publishAction(fixture.acceptanceDir, { json: true, reviews: false });
+
+ expect(
+ ingestReportAction.mock.calls.map(([dir, options]) => [path.basename(dir), options]),
+ ).toEqual([
+ // The first round names the subject the directory is keyed by, and the requirement.
+ [
+ '20260101-090000-first',
+ { quiet: true, requirement: 'Rename works', source: 'agent-testing', subject: 'task:T-12' },
+ ],
+ // Later rounds join the acceptance the first one created.
+ [
+ '20260102-090000-second',
+ { acceptance: 'remote-acceptance', quiet: true, source: 'agent-testing' },
+ ],
+ ]);
+ const stored = JSON.parse(
+ readFileSync(path.join(fixture.acceptanceDir, ACCEPTANCE_FILE), 'utf8'),
+ );
+ expect(stored.remote).toEqual({
+ acceptanceId: 'remote-acceptance',
+ acceptanceUrl: 'https://app.lobehub.com/acceptance/remote-acceptance',
+ rounds: [
+ { dir: '20260101-090000-first', evidence: {}, roundIndex: 1, verifyRunId: 'remote-run-1' },
+ {
+ dir: '20260102-090000-second',
+ evidence: {},
+ roundIndex: 2,
+ verifyRunId: 'remote-run-2',
+ },
+ ],
+ });
+ expect(outputJson.mock.calls[0]![0]).toMatchObject({
+ acceptanceUrl: 'https://app.lobehub.com/acceptance/remote-acceptance',
+ alreadyPublished: [],
+ publicationStatus: 'complete',
+ });
+
+ // Nothing new: nothing is ingested again.
+ ingestReportAction.mockClear();
+ await publishAction(fixture.acceptanceDir, { json: true, reviews: false });
+ expect(ingestReportAction).not.toHaveBeenCalled();
+ expect(outputJson.mock.calls[1]![0]).toMatchObject({
+ alreadyPublished: ['20260101-090000-first', '20260102-090000-second'],
+ published: [],
+ });
+ });
+
+ it("carries the reviewer's standing decisions, re-pointing regions at the uploads", async () => {
+ const { info, source } = loadLocalAcceptance(fixture.acceptanceDir, { create: true });
+ const local = assembleLocalAcceptance(source);
+ const check = local.checks.find((item) => item.id === 'rename')!;
+ writeReviewLog(fixture.acceptanceDir, info.id, [
+ {
+ action: 'reject',
+ annotations: [
+ {
+ comment: 'Title is cut off',
+ evidenceId: check.evidence[0]!.id,
+ rect: { height: 0.2, width: 0.2, x: 0.1, y: 0.1 },
+ },
+ ],
+ comment: 'Rename loses part of the title',
+ createdAt: '2026-01-01T10:00:00.000Z',
+ id: 'event-1',
+ kind: 'checks',
+ roundIndex: 1,
+ targets: [{ checkId: 'rename', resultId: check.result!.id }],
+ },
+ {
+ category: 'Rename',
+ comment: 'Also try a very long title',
+ createdAt: '2026-01-01T10:01:00.000Z',
+ id: 'event-2',
+ kind: 'group',
+ roundIndex: 1,
+ },
+ ]);
+ ingestReportAction.mockResolvedValueOnce(ingested(1, bothUploaded));
+ client.acceptance.getBundle.query.mockResolvedValue(
+ remoteBundle([{ id: 'remote-shot' }, { id: 'remote-api' }]),
+ );
+
+ await publishAction(fixture.acceptanceDir, { json: true });
+
+ expect(client.acceptance.reviewChecks.mutate).toHaveBeenCalledWith({
+ action: 'reject',
+ annotations: [
+ {
+ comment: 'Title is cut off',
+ evidenceId: 'remote-shot',
+ rect: { height: 0.2, width: 0.2, x: 0.1, y: 0.1 },
+ },
+ ],
+ checkItemIds: ['criterion-rename'],
+ comment: 'Rename loses part of the title',
+ id: 'remote-acceptance',
+ });
+ expect(client.acceptance.addGroupFeedback.mutate).toHaveBeenCalledWith({
+ category: 'Rename',
+ comment: 'Also try a very long title',
+ id: 'remote-acceptance',
+ });
+ expect(outputJson.mock.calls[0]![0].reviews).toEqual({ skipped: [], uploaded: 2 });
+ });
+ it('places a region only on its own upload when an earlier artifact failed', async () => {
+ const { info, source } = loadLocalAcceptance(fixture.acceptanceDir, { create: true });
+ const check = assembleLocalAcceptance(source).checks.find((item) => item.id === 'rename')!;
+ writeReviewLog(fixture.acceptanceDir, info.id, [
+ {
+ action: 'reject',
+ annotations: [
+ {
+ comment: 'Title is cut off',
+ evidenceId: check.evidence[0]!.id,
+ rect: { height: 0.2, width: 0.2, x: 0.1, y: 0.1 },
+ },
+ ],
+ createdAt: '2026-01-01T10:00:00.000Z',
+ id: 'event-1',
+ kind: 'checks',
+ roundIndex: 1,
+ targets: [{ checkId: 'rename', resultId: check.result!.id }],
+ },
+ ]);
+ // The screenshot failed to upload: the API log is the check's only remote artifact.
+ ingestReportAction.mockResolvedValueOnce(
+ ingested(1, [{ checkItemId: 'rename', evidenceId: 'remote-api', position: 1 }]),
+ );
+ client.acceptance.getBundle.query.mockResolvedValue(remoteBundle([{ id: 'remote-api' }]));
+
+ await publishAction(fixture.acceptanceDir, { json: true });
+
+ // Not drawn on the API log; the note survives as words.
+ expect(client.acceptance.reviewChecks.mutate).toHaveBeenCalledWith({
+ action: 'reject',
+ checkItemIds: ['criterion-rename'],
+ comment: 'Title is cut off',
+ id: 'remote-acceptance',
+ });
+ });
+
+ it('carries each local decision once, so a re-publish keeps newer online ones', async () => {
+ const { info, source } = loadLocalAcceptance(fixture.acceptanceDir, { create: true });
+ const check = assembleLocalAcceptance(source).checks.find((item) => item.id === 'rename')!;
+ const accept = {
+ action: 'accept' as const,
+ createdAt: '2026-01-01T10:00:00.000Z',
+ id: 'event-1',
+ kind: 'checks' as const,
+ roundIndex: 1,
+ targets: [{ checkId: 'rename', resultId: check.result!.id }],
+ };
+ const feedback = {
+ category: 'Rename',
+ comment: 'Also try a very long title',
+ createdAt: '2026-01-01T10:01:00.000Z',
+ id: 'event-2',
+ kind: 'group' as const,
+ roundIndex: 1,
+ };
+ writeReviewLog(fixture.acceptanceDir, info.id, [accept, feedback]);
+ ingestReportAction.mockResolvedValueOnce(ingested(1, bothUploaded));
+ client.acceptance.getBundle.query.mockResolvedValue(
+ remoteBundle([{ id: 'remote-shot' }, { id: 'remote-api' }]),
+ );
+
+ await publishAction(fixture.acceptanceDir, { json: true });
+ expect(client.acceptance.reviewChecks.mutate).toHaveBeenCalledTimes(1);
+ expect(client.acceptance.addGroupFeedback.mutate).toHaveBeenCalledTimes(1);
+
+ // Unchanged: nothing is replayed over what collaborators decided since.
+ await publishAction(fixture.acceptanceDir, { json: true });
+ expect(client.acceptance.reviewChecks.mutate).toHaveBeenCalledTimes(1);
+ expect(client.acceptance.addGroupFeedback.mutate).toHaveBeenCalledTimes(1);
+ expect(outputJson.mock.calls[1]![0].reviews).toEqual({ skipped: [], uploaded: 0 });
+
+ // A decision made locally afterwards still moves.
+ writeReviewLog(fixture.acceptanceDir, info.id, [
+ accept,
+ feedback,
+ { ...accept, action: 'reject', createdAt: '2026-01-02T10:00:00.000Z', id: 'event-3' },
+ ]);
+ await publishAction(fixture.acceptanceDir, { json: true });
+ expect(client.acceptance.reviewChecks.mutate).toHaveBeenCalledTimes(2);
+ expect(client.acceptance.reviewChecks.mutate).toHaveBeenLastCalledWith(
+ expect.objectContaining({ action: 'reject', checkItemIds: ['criterion-rename'] }),
+ );
+ expect(client.acceptance.addGroupFeedback.mutate).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports how to repair evidence a published round failed to upload', async () => {
+ loadLocalAcceptance(fixture.acceptanceDir, { create: true });
+ const failure = {
+ checkItemId: 'rename',
+ checkResultId: 'remote-result',
+ error: 'network down',
+ path: '/tmp/after shot.png',
+ reason: 'upload_failed',
+ retryArgs: ['acceptance', 'run', 'evidence', 'upload', '--check', 'remote-result'],
+ retryCommand: "lh acceptance run evidence upload '--check' 'remote-result'",
+ retryCommandShell: 'posix',
+ type: 'screenshot',
+ };
+ ingestReportAction.mockResolvedValueOnce({
+ ...ingested(1),
+ failedEvidence: [failure],
+ publicationStatus: 'partial',
+ });
+
+ await publishAction(fixture.acceptanceDir, { json: true, reviews: false });
+ expect(outputJson.mock.calls[0]![0]).toMatchObject({
+ published: [{ failedEvidence: [failure], publicationStatus: 'partial' }],
+ publicationStatus: 'partial',
+ });
+
+ // The human-readable form prints the same retry for the round it publishes.
+ const second = firstRound();
+ second.dir = '20260102-090000-second';
+ fixture.addRound(second);
+ ingestReportAction.mockResolvedValueOnce({
+ ...ingested(2),
+ failedEvidence: [failure],
+ publicationStatus: 'partial',
+ });
+ await publishAction(fixture.acceptanceDir, { reviews: false });
+ expect(vi.mocked(console.log).mock.calls.flat().join('\n')).toContain(failure.retryCommand);
+ process.exitCode = undefined;
+ });
+});
diff --git a/apps/cli/src/commands/acceptance/local/publish.ts b/apps/cli/src/commands/acceptance/local/publish.ts
new file mode 100644
index 00000000000..f647c1ee9ab
--- /dev/null
+++ b/apps/cli/src/commands/acceptance/local/publish.ts
@@ -0,0 +1,265 @@
+import path from 'node:path';
+
+import type { AcceptanceReviewAnnotation } from '@lobechat/types';
+import type { LocalAcceptanceRemote } from '@lobechat/utils/verify/localAcceptance';
+import {
+ assembleLocalAcceptance,
+ localSubjectFromKey,
+} from '@lobechat/utils/verify/localAcceptance';
+import type { Command } from 'commander';
+import pc from 'picocolors';
+
+import { getTrpcClient, type TrpcClient } from '../../../api/client';
+import { outputJson } from '../../../utils/format';
+import { log } from '../../../utils/logger';
+import { ingestReportAction, type IngestReportSummary } from '../run/ingest';
+import { ReportRoundError } from '../run/reportRound';
+import { localEvidenceId, writeAcceptanceInfo } from './acceptanceDir';
+import { loadLocalAcceptance, type LocalAcceptanceRead } from './localAcceptance';
+
+export interface PublishOptions {
+ json?: boolean | string;
+ requirement?: string;
+ /** commander's `--no-reviews` */
+ reviews?: boolean;
+ source?: string;
+}
+
+type RemoteBundle = Awaited<ReturnType<TrpcClient['acceptance']['getBundle']['query']>>;
+
+interface ReviewCarry {
+ /** Decisions that landed this time, recorded so a re-publish skips them. */
+ carried: string[];
+ skipped: { checkId: string; reason: string }[];
+ uploaded: number;
+}
+
+/**
+ * Carry the reviewer's standing decisions onto the published acceptance, so
+ * collaborators open it where the local review left off. Only the current
+ * verdict of each check moves (a reject a later round consumed stays local
+ * history), and a circled region is re-pointed at the same artifact's upload.
+ * Each decision moves once: replaying it on a later publish would overwrite
+ * whatever a collaborator decided online since.
+ */
+async function carryReviews(
+ client: TrpcClient,
+ read: LocalAcceptanceRead,
+ remote: LocalAcceptanceRemote,
+): Promise<ReviewCarry> {
+ const carry: ReviewCarry = { carried: [], skipped: [], uploaded: 0 };
+ const done = new Set(remote.carriedReviews);
+ const local = assembleLocalAcceptance(read.source);
+ const checkKey = (check: (typeof local.checks)[number]) => check.planItem?.id ?? check.id;
+ const standing = local.checks
+ .filter((check) => check.userReview && !check.userReview.stale)
+ .map((check) => ({ check, key: `check:${checkKey(check)}@${check.userReview!.createdAt}` }))
+ .filter(({ key }) => !done.has(key));
+ const latestRoundIndex = local.rounds.at(-1)?.run.roundIndex;
+ const groupFeedback = read.source.reviews.filter(
+ (event): event is Extract<typeof event, { kind: 'group' }> =>
+ event.kind === 'group' &&
+ event.roundIndex === latestRoundIndex &&
+ !done.has(`group:${event.id}`),
+ );
+ if (standing.length === 0 && groupFeedback.length === 0) return carry;
+
+ const bundle: RemoteBundle = await client.acceptance.getBundle.query({
+ id: remote.acceptanceId,
+ });
+ // Plan item ids survive publication; the remote row id is the criterion minted for it.
+ const remoteCheck = new Map(
+ bundle.checks.map((check) => [check.planItem?.id ?? check.id, check]),
+ );
+ // Matched by identity: a failed upload leaves no entry rather than shifting the rest.
+ const remoteEvidence = new Map(
+ remote.rounds.flatMap((round) => Object.entries(round.evidence ?? {})),
+ );
+
+ for (const { check, key } of standing) {
+ const review = check.userReview!;
+ const target = remoteCheck.get(checkKey(check));
+ if (!target?.result) {
+ carry.skipped.push({ checkId: check.id, reason: 'not on the published acceptance' });
+ continue;
+ }
+ const annotations = (review.annotations ?? []).flatMap(
+ (annotation): AcceptanceReviewAnnotation[] => {
+ const evidenceId = remoteEvidence.get(annotation.evidenceId);
+ return evidenceId ? [{ ...annotation, evidenceId }] : [];
+ },
+ );
+ // A region on an artifact that failed to upload cannot be placed; keep its words.
+ const lostNotes = (review.annotations ?? [])
+ .filter((annotation) => !remoteEvidence.has(annotation.evidenceId) && annotation.comment)
+ .map((annotation) => annotation.comment!);
+ const comment = [review.comment, ...lostNotes].filter(Boolean).join('\n') || undefined;
+ try {
+ await client.acceptance.reviewChecks.mutate({
+ action: review.action,
+ ...(annotations.length > 0 ? { annotations } : {}),
+ checkItemIds: [target.id],
+ comment,
+ id: remote.acceptanceId,
+ });
+ carry.carried.push(key);
+ carry.uploaded++;
+ } catch (error) {
+ carry.skipped.push({
+ checkId: check.id,
+ reason: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+
+ for (const entry of groupFeedback) {
+ try {
+ await client.acceptance.addGroupFeedback.mutate({
+ category: entry.category,
+ comment: entry.comment,
+ id: remote.acceptanceId,
+ });
+ carry.carried.push(`group:${entry.id}`);
+ carry.uploaded++;
+ } catch (error) {
+ carry.skipped.push({
+ checkId: `group:${entry.category}`,
+ reason: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ return carry;
+}
+
+/**
+ * Publish a local acceptance to LobeHub, for when the delivery needs other
+ * eyes: every round not yet published goes through `ingest`, oldest first,
+ * into one acceptance, keeping its immutable history; then the reviewer's
+ * standing decisions follow. Re-running publishes only the rounds added since.
+ */
+export async function publishAction(target: string, options: PublishOptions) {
+ // Fail on missing credentials before reading anything.
+ const client = await getTrpcClient();
+
+ let read: LocalAcceptanceRead;
+ try {
+ read = loadLocalAcceptance(target, { create: true, requirement: options.requirement });
+ } catch (error) {
+ if (error instanceof ReportRoundError) {
+ for (const line of error.lines) log.error(line);
+ process.exit(1);
+ }
+ throw error;
+ }
+ const { acceptanceDir, info } = read;
+ let remote = info.remote;
+ const published = new Set(remote?.rounds.map((round) => round.dir));
+ const pending = read.source.rounds.filter((round) => !published.has(round.dir));
+ const subject = localSubjectFromKey(info.subjectKey);
+ const results: { dir: string; summary: IngestReportSummary }[] = [];
+
+ for (const round of pending) {
+ const summary = await ingestReportAction(path.join(acceptanceDir, round.dir), {
+ ...(remote
+ ? { acceptance: remote.acceptanceId }
+ : {
+ requirement: info.requirement ?? undefined,
+ ...(subject.type === 'standalone'
+ ? { fallbackSubject: { subjectId: info.id, subjectType: 'standalone' as const } }
+ : { subject: `${subject.type}:${subject.id}` }),
+ }),
+ quiet: true,
+ source: options.source ?? 'agent-testing',
+ });
+ if (!summary) throw new Error(`${round.dir} was not published as an authored round`);
+ results.push({ dir: round.dir, summary });
+ remote = {
+ ...remote,
+ acceptanceId: summary.acceptanceId,
+ acceptanceUrl: summary.acceptanceUrl,
+ rounds: [
+ ...(remote?.rounds ?? []),
+ {
+ dir: round.dir,
+ evidence: Object.fromEntries(
+ summary.publishedEvidence.map((item) => [
+ localEvidenceId(info.id, round.dir, item.checkItemId, item.position),
+ item.evidenceId,
+ ]),
+ ),
+ roundIndex: summary.roundIndex,
+ verifyRunId: summary.verifyRunId,
+ },
+ ],
+ };
+ // Recorded per round: an interrupted publish resumes after the last one that landed.
+ writeAcceptanceInfo(acceptanceDir, { ...info, remote });
+ }
+
+ if (!remote) {
+ log.error(`${acceptanceDir} has no round to publish`);
+ process.exit(1);
+ }
+
+ const { carried, ...reviews } =
+ options.reviews === false
+ ? { carried: [], skipped: [], uploaded: 0 }
+ : await carryReviews(client, read, remote);
+ for (const skipped of reviews.skipped)
+ log.warn(`review of ${skipped.checkId} not carried over: ${skipped.reason}`);
+ if (carried.length > 0) {
+ remote = { ...remote, carriedReviews: [...(remote.carriedReviews ?? []), ...carried] };
+ writeAcceptanceInfo(acceptanceDir, { ...info, remote });
+ }
+
+ const partial = results.some(({ summary }) => summary.publicationStatus === 'partial');
+ if (partial) process.exitCode = 1;
+ const output = {
+ acceptanceId: remote.acceptanceId,
+ acceptanceUrl: remote.acceptanceUrl,
+ alreadyPublished: [...published],
+ published: results.map(({ dir, summary }) => ({
+ dir,
+ // A partial round is recorded as published and never re-ingested: what
+ // repairs it is retrying these artifacts, not publishing again.
+ failedEvidence: summary.failedEvidence,
+ missingEvidence: summary.missingEvidence,
+ publicationStatus: summary.publicationStatus,
+ recovery: summary.recovery,
+ roundIndex: summary.roundIndex,
+ verifyRunId: summary.verifyRunId,
+ })),
+ publicationStatus: partial ? ('partial' as const) : ('complete' as const),
+ reviews,
+ };
+
+ if (options.json !== undefined) {
+ outputJson(output, typeof options.json === 'string' ? options.json : undefined);
+ return;
+ }
+ console.log(
+ `${partial ? pc.yellow('⚠ Partially published') : pc.green('✓ Published')} ${results.length} round(s)` +
+ `${published.size > 0 ? pc.dim(` (${published.size} already published)`) : ''}` +
+ `${reviews.uploaded > 0 ? `, ${reviews.uploaded} review decision(s) carried over` : ''}`,
+ );
+ for (const { dir, summary } of results) {
+ for (const failure of summary.failedEvidence) {
+ console.log(`${pc.yellow('retry (POSIX shell)')} ${pc.dim(dir)}: ${failure.retryCommand}`);
+ console.log(
+ `${pc.dim('retryArgs (lh, shell disabled)')}: ${JSON.stringify(failure.retryArgs)}`,
+ );
+ }
+ }
+ console.log(`${pc.bold('acceptance')}: ${remote.acceptanceUrl}`);
+}
+
+export function withPublishOptions(cmd: Command): Command {
+ return cmd
+ .option('--source <source>', 'agent | agent-testing', 'agent-testing')
+ .option(
+ '--requirement <text>',
+ 'Acceptance requirement, when the local acceptance has none recorded yet',
+ )
+ .option('--no-reviews', "Publish the rounds only; keep the reviewer's local decisions local")
+ .option('--json [fields]', 'Output JSON');
+}
diff --git a/apps/cli/src/commands/acceptance/local/render.test.ts b/apps/cli/src/commands/acceptance/local/render.test.ts
new file mode 100644
index 00000000000..e41143c0e39
--- /dev/null
+++ b/apps/cli/src/commands/acceptance/local/render.test.ts
@@ -0,0 +1,177 @@
+import { EventEmitter } from 'node:events';
+import { readFileSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as Format from '../../../utils/format';
+import { log } from '../../../utils/logger';
+import { renderReportAction } from './render';
+import { renderReportHtml } from './reportTemplate';
+import { createLocalAcceptance, firstRound } from './testUtils';
+
+const { outputJson, spawn } = vi.hoisted(() => ({
+ outputJson: vi.fn(),
+ spawn: vi.fn(),
+}));
+vi.mock('node:child_process', () => ({ spawn }));
+vi.mock('../../../utils/format', async (original) => ({
+ ...(await original<typeof Format>()),
+ outputJson,
+}));
+
+const TEMPLATE =
+ '<html><head><!--ACCEPTANCE_LOCAL_TITLE--><script type="module">const slot = "<\\!--ACCEPTANCE_LOCAL_DATA-->";</script></head><body><!--ACCEPTANCE_LOCAL_DATA--></body></html>';
+
+const embedded = (html: string) => {
+ const match = html.match(
+ /<script id="acceptance-local-data" type="application\/json">(.*?)<\/script>/s,
+ );
+ return match ? JSON.parse(match[1]!) : undefined;
+};
+
+describe('lh acceptance run render', () => {
+ let fixture: ReturnType<typeof createLocalAcceptance>;
+ let originalExitCode: typeof process.exitCode;
+
+ beforeEach(() => {
+ originalExitCode = process.exitCode;
+ process.exitCode = undefined;
+ spawn.mockImplementation(() => Object.assign(new EventEmitter(), { unref: () => {} }));
+ vi.spyOn(log, 'warn').mockImplementation(() => {});
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ fixture = createLocalAcceptance([firstRound()]);
+ const template = path.join(fixture.root, 'acceptance-report.html');
+ writeFileSync(template, TEMPLATE);
+ vi.stubEnv('LOBEHUB_ACCEPTANCE_REPORT_TEMPLATE', template);
+ vi.stubEnv('LOBEHUB_ACCEPTANCE_DOWNLOADS', path.join(fixture.root, 'Downloads'));
+ vi.stubEnv('HOME', fixture.root);
+ });
+
+ afterEach(() => {
+ process.exitCode = originalExitCode;
+ fixture.cleanup();
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ });
+
+ it('writes the whole acceptance into one offline page next to its rounds', async () => {
+ const roundDir = path.join(fixture.acceptanceDir, '20260101-090000-first');
+ await renderReportAction(roundDir, { json: true, requirement: 'Users can rename a topic' });
+
+ const reportPath = path.join(fixture.acceptanceDir, 'report.html');
+ const html = readFileSync(reportPath, 'utf8');
+ expect(html).toContain('<title>Topic rename</title>');
+ // The data lands in <body>, not in the page script's look-alike string.
+ expect(html).toContain('const slot = "<\\!--ACCEPTANCE_LOCAL_DATA-->"');
+ const data = embedded(html);
+ expect(data.acceptance).toMatchObject({ requirement: 'Users can rename a topic' });
+ expect(data.rounds).toHaveLength(1);
+
+ const summary = outputJson.mock.calls[0]![0];
+ expect(summary).toMatchObject({
+ cases: 1,
+ droppedProgrammaticChecks: ['unit — Unit tests pass'],
+ missingEvidence: [{ checkItemId: 'enter', types: ['video'] }],
+ mode: 'local',
+ publicationStatus: 'partial',
+ reportPath,
+ roundIndex: 1,
+ rounds: 1,
+ });
+ expect(summary.reportUrl).toMatch(/^file:\/\//);
+ // Incomplete evidence fails like a partial ingest does.
+ expect(process.exitCode).toBe(1);
+ });
+
+ it('re-renders every round into the same page', async () => {
+ await renderReportAction(fixture.acceptanceDir, { json: true });
+ const round = firstRound();
+ round.dir = '20260102-090000-second';
+ fixture.addRound(round);
+ await renderReportAction(path.join(fixture.acceptanceDir, round.dir), { json: true });
+
+ const data = embedded(readFileSync(path.join(fixture.acceptanceDir, 'report.html'), 'utf8'));
+ expect(data.rounds.map((item: { dir: string }) => item.dir)).toEqual([
+ '20260101-090000-first',
+ '20260102-090000-second',
+ ]);
+ expect(outputJson.mock.calls.at(-1)![0]).toMatchObject({ roundIndex: 2, rounds: 2 });
+ });
+
+ it.each(['synchronous', 'asynchronous'])(
+ '%s browser failure keeps the rendered report usable',
+ async (failure) => {
+ const child = Object.assign(new EventEmitter(), { unref: () => {} });
+ const error = new Error('spawn xdg-open ENOENT');
+ spawn.mockImplementationOnce(() => {
+ if (failure === 'synchronous') throw error;
+ return child;
+ });
+ fixture.addRound({
+ dir: '20260102-090000-complete',
+ result: {
+ cases: [{ id: 'rename', name: 'Rename keeps the new title', status: 'pass' }],
+ title: 'Topic rename',
+ },
+ });
+
+ const summary = await renderReportAction(fixture.acceptanceDir, {
+ json: true,
+ open: true,
+ requirement: 'Users can rename a topic',
+ });
+ if (failure === 'asynchronous') {
+ await Promise.resolve();
+ expect(() => child.emit('error', error)).not.toThrow();
+ }
+
+ expect(summary.publicationStatus).toBe('complete');
+ expect(process.exitCode).toBeUndefined();
+ expect(embedded(readFileSync(summary.reportPath, 'utf8')).rounds).toHaveLength(2);
+ expect(log.warn).toHaveBeenCalledWith(expect.stringContaining(error.message));
+ },
+ );
+
+ it('opens the page on Windows without handing its path to a shell', async () => {
+ const platform = Object.getOwnPropertyDescriptor(process, 'platform')!;
+ Object.defineProperty(process, 'platform', { ...platform, value: 'win32' });
+ const roundDir = path.join(fixture.acceptanceDir, '20260101-090000-first');
+ try {
+ await renderReportAction(roundDir, { json: true, open: true });
+ } finally {
+ Object.defineProperty(process, 'platform', platform);
+ }
+
+ const reportPath = path.join(fixture.acceptanceDir, 'report.html');
+ expect(spawn).toHaveBeenCalledWith(
+ 'rundll32',
+ ['url.dll,FileProtocolHandler', reportPath],
+ expect.objectContaining({ detached: true }),
+ );
+ });
+});
+
+describe('renderReportHtml', () => {
+ it('keeps the embedded JSON from closing its script element', () => {
+ const html = renderReportHtml(
+ TEMPLATE,
+ {
+ acceptance: {
+ createdAt: '2026-01-01T00:00:00.000Z',
+ id: 'a',
+ requirement: '</script><script>alert(1)</script>',
+ subjectKey: 'standalone-x',
+ },
+ format: 1,
+ generatedAt: '2026-01-01T00:00:00.000Z',
+ reviews: [],
+ rounds: [],
+ },
+ 'A <b> title',
+ );
+ expect(html).toContain('<title>A &lt;b&gt; title</title>');
+ expect(html).not.toContain('</script><script>alert(1)');
+ expect(embedded(html).acceptance.requirement).toBe('</script><script>alert(1)</script>');
+ });
+});
diff --git a/apps/cli/src/commands/acceptance/local/render.ts b/apps/cli/src/commands/acceptance/local/render.ts
new file mode 100644
index 00000000000..c6e4fd77637
--- /dev/null
+++ b/apps/cli/src/commands/acceptance/local/render.ts
@@ -0,0 +1,150 @@
+import { spawn } from 'node:child_process';
+import { writeFileSync } from 'node:fs';
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+import type { Command } from 'commander';
+import pc from 'picocolors';
+
+import { ensureAcceptanceDirIgnoredFor } from '../../../utils/acceptanceDir';
+import { outputJson } from '../../../utils/format';
+import { log } from '../../../utils/logger';
+import { ReportRoundError } from '../run/reportRound';
+import { REPORT_FILE } from './acceptanceDir';
+import { loadLocalAcceptance } from './localAcceptance';
+import { readReportTemplate, renderReportHtml } from './reportTemplate';
+
+export interface RenderReportOptions {
+ json?: boolean | string;
+ open?: boolean;
+ requirement?: string;
+ reviews?: string;
+}
+
+/**
+ * Open a file in the default browser, without waiting on it. Never through a
+ * shell: the path is whatever directory the acceptance lives in, and `cmd`
+ * would parse its `&` or `^`.
+ */
+const openInBrowser = (file: string) => {
+ const [command, args] =
+ process.platform === 'darwin'
+ ? ['open', [file]]
+ : process.platform === 'win32'
+ ? ['rundll32', ['url.dll,FileProtocolHandler', file]]
+ : ['xdg-open', [file]];
+ const onError = (error: unknown) => {
+ log.warn(
+ `Could not open browser automatically: ${error instanceof Error ? error.message : String(error)}. Open the report path manually.`,
+ );
+ };
+ try {
+ const child = spawn(command, args, { detached: true, stdio: 'ignore' });
+ child.once('error', onError);
+ child.unref();
+ } catch (error) {
+ onError(error);
+ }
+};
+
+/**
+ * Render a local acceptance into one offline page — the acceptance page,
+ * without LobeHub. Re-rendering after a new round or after the reviewer saved
+ * their decisions refreshes the same `report.html`.
+ */
+export async function renderReportAction(reportDir: string, options: RenderReportOptions) {
+ ensureAcceptanceDirIgnoredFor(path.resolve(reportDir));
+ let read: ReturnType<typeof loadLocalAcceptance>;
+ try {
+ read = loadLocalAcceptance(reportDir, {
+ create: true,
+ requirement: options.requirement,
+ reviewsFile: options.reviews,
+ warnLatest: true,
+ });
+ } catch (error) {
+ if (error instanceof ReportRoundError) {
+ for (const line of error.lines) log.error(line);
+ process.exit(1);
+ }
+ throw error;
+ }
+
+ const { acceptanceDir, info, rounds, source } = read;
+ const latest = rounds.at(-1);
+ if (!latest) {
+ log.error(`${acceptanceDir} has no round yet — write a round directory with result.json first`);
+ process.exit(1);
+ }
+ if (read.keptRequirement)
+ log.warn(`The requirement is recorded once per acceptance; keeping "${read.keptRequirement}".`);
+ if (!info.requirement)
+ log.warn(
+ 'No requirement recorded — pass --requirement "<one-sentence business goal>" on the first render.',
+ );
+
+ const reportPath = path.join(acceptanceDir, REPORT_FILE);
+ const title = latest.source.run.title || latest.source.run.goal || path.basename(acceptanceDir);
+ writeFileSync(reportPath, renderReportHtml(readReportTemplate(), source, title));
+ const reportUrl = pathToFileURL(reportPath).toString();
+ if (options.open) openInBrowser(reportPath);
+
+ const partial = latest.failedEvidence.length > 0 || latest.missingEvidence.length > 0;
+ if (partial) {
+ process.exitCode = 1;
+ log.warn(
+ 'Report rendered, but its evidence is incomplete. Capture the missing evidence and write a new round; do not edit this one.',
+ );
+ }
+
+ const summary = {
+ acceptanceDir,
+ acceptanceId: info.id,
+ cases: latest.source.results.length,
+ droppedProgrammaticChecks: latest.droppedLabels,
+ evidence: latest.source.evidence.length,
+ failedEvidence: latest.failedEvidence,
+ missingEvidence: latest.missingEvidence,
+ mode: 'local' as const,
+ planItems: latest.source.run.plan?.length ?? 0,
+ publicationStatus: partial ? ('partial' as const) : ('complete' as const),
+ published: info.remote ? { acceptanceUrl: info.remote.acceptanceUrl } : null,
+ reportPath,
+ reportUrl,
+ reviews: {
+ imported: read.reviewsImported ?? null,
+ recorded: source.reviews.length,
+ },
+ roundIndex: latest.source.run.roundIndex,
+ rounds: rounds.length,
+ unexecuted: latest.unexecuted,
+ };
+
+ if (options.json !== undefined) {
+ outputJson(summary, typeof options.json === 'string' ? options.json : undefined);
+ return summary;
+ }
+
+ console.log(
+ `${partial ? pc.yellow('⚠ Rendered with gaps') : pc.green('✓ Rendered')} round ${summary.roundIndex} of ${summary.rounds}: ${pc.bold(String(summary.cases))} case(s), ${pc.bold(String(summary.evidence))} evidence artifact(s)` +
+ `${latest.droppedLabels.length > 0 ? pc.yellow(` — ${latest.droppedLabels.length} programmatic-test check(s) dropped`) : ''}`,
+ );
+ if (read.reviewsImported?.added)
+ console.log(
+ `${pc.bold('reviews')}: ${read.reviewsImported.added} new decision(s) read from ${read.reviewsImported.file}`,
+ );
+ console.log(`${pc.bold('acceptance')}: ${info.id} ${pc.dim('(local)')}`);
+ console.log(`${pc.bold('report')}: ${reportUrl}`);
+ return summary;
+}
+
+export function withRenderReportOptions(cmd: Command): Command {
+ return cmd
+ .option(
+ '--requirement <text>',
+ 'Acceptance requirement, recorded on the first render and kept for later rounds',
+ )
+ .option('--reviews <file>', 'Read the review log the report page saved from this file')
+ .option('--open', 'Open the rendered report in the default browser')
+ .option('--json [fields]', 'Output JSON');
+}
diff --git a/apps/cli/src/commands/acceptance/local/reportTemplate.ts b/apps/cli/src/commands/acceptance/local/reportTemplate.ts
new file mode 100644
index 00000000000..9af6ab09554
--- /dev/null
+++ b/apps/cli/src/commands/acceptance/local/reportTemplate.ts
@@ -0,0 +1,70 @@
+import { existsSync, readFileSync } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import type { LocalAcceptanceSource } from '@lobechat/utils/verify/localAcceptance';
+
+/**
+ * The offline acceptance page, built by `apps/workbench` (`build:report`) and
+ * shipped next to the CLI bundle. One self-contained HTML file: the CLI only
+ * writes the acceptance into it.
+ */
+export const REPORT_TEMPLATE_FILE = 'acceptance-report.html';
+
+const DATA_MARKER = '<!--ACCEPTANCE_LOCAL_DATA-->';
+const TITLE_MARKER = '<!--ACCEPTANCE_LOCAL_TITLE-->';
+/** Read back by `apps/workbench/src/localReport/localReportData.ts`. */
+const DATA_ELEMENT_ID = 'acceptance-local-data';
+
+const candidates = () => {
+ const here = path.dirname(fileURLToPath(import.meta.url));
+ return [
+ process.env.LOBEHUB_ACCEPTANCE_REPORT_TEMPLATE,
+ // The published bundle: dist/index.js beside dist/acceptance-report.html.
+ path.join(here, REPORT_TEMPLATE_FILE),
+ // A source checkout (`bun src/index.ts`): the workbench's build output.
+ path.resolve(here, '../../../../../workbench/dist-report', REPORT_TEMPLATE_FILE),
+ ].filter((file): file is string => Boolean(file));
+};
+
+export const resolveReportTemplate = (): string => {
+ const found = candidates().find((file) => existsSync(file));
+ if (!found)
+ throw new Error(
+ `The local report page is missing from this CLI (${REPORT_TEMPLATE_FILE}). Reinstall @lobehub/cli, or build it with \`bun run build:report\` in apps/workbench.`,
+ );
+ return found;
+};
+
+const escapeHtml = (text: string) =>
+ text.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
+
+/** JSON that cannot close or confuse the `<script>` element carrying it. */
+const scriptJson = (value: unknown) =>
+ JSON.stringify(value)
+ .replaceAll('<', '\\u003c')
+ .replaceAll('\u2028', '\\u2028')
+ .replaceAll('\u2029', '\\u2029');
+
+const replaceMarker = (html: string, marker: string, value: string, last = false) => {
+ const index = last ? html.lastIndexOf(marker) : html.indexOf(marker);
+ if (index === -1) throw new Error(`The local report page has no ${marker} slot`);
+ return html.slice(0, index) + value + html.slice(index + marker.length);
+};
+
+export const renderReportHtml = (
+ template: string,
+ source: LocalAcceptanceSource,
+ title: string,
+): string => {
+ const withTitle = replaceMarker(template, TITLE_MARKER, `<title>${escapeHtml(title)}</title>`);
+ // The slot sits in <body>, after the inlined page script in <head>.
+ return replaceMarker(
+ withTitle,
+ DATA_MARKER,
+ `<script id="${DATA_ELEMENT_ID}" type="application/json">${scriptJson(source)}</script>`,
+ true,
+ );
+};
+
+export const readReportTemplate = () => readFileSync(resolveReportTemplate(), 'utf8');
diff --git a/apps/cli/src/commands/acceptance/local/testUtils.ts b/apps/cli/src/commands/acceptance/local/testUtils.ts
new file mode 100644
index 00000000000..872d409cb7f
--- /dev/null
+++ b/apps/cli/src/commands/acceptance/local/testUtils.ts
@@ -0,0 +1,85 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+/** A PNG header for a `width`×`height` image — enough for the size reader. */
+export const pngHeader = (width: number, height: number) => {
+ const buf = Buffer.alloc(33);
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(buf, 0);
+ buf.writeUInt32BE(13, 8);
+ buf.write('IHDR', 12, 'ascii');
+ buf.writeUInt32BE(width, 16);
+ buf.writeUInt32BE(height, 20);
+ return buf;
+};
+
+export interface FixtureRound {
+ assets?: Record<string, Buffer | string>;
+ dir: string;
+ proposal?: string;
+ report?: string;
+ result: Record<string, unknown>;
+}
+
+/**
+ * A project with one local acceptance under `.acceptances/<subjectKey>/`, its
+ * rounds written the way the skill writes them. Call `cleanup` in `afterEach`.
+ */
+export const createLocalAcceptance = (rounds: FixtureRound[], subjectKey = 'standalone-demo') => {
+ const root = mkdtempSync(path.join(tmpdir(), 'lh-local acceptance-'));
+ const acceptanceDir = path.join(root, '.acceptances', subjectKey);
+ const addRound = (round: FixtureRound) => {
+ const roundDir = path.join(acceptanceDir, round.dir);
+ mkdirSync(path.join(roundDir, 'assets'), { recursive: true });
+ writeFileSync(path.join(roundDir, 'result.json'), JSON.stringify(round.result));
+ if (round.proposal) writeFileSync(path.join(roundDir, 'proposal.md'), round.proposal);
+ if (round.report) writeFileSync(path.join(roundDir, 'report.md'), round.report);
+ for (const [name, content] of Object.entries(round.assets ?? {}))
+ writeFileSync(path.join(roundDir, 'assets', name), content);
+ return roundDir;
+ };
+ for (const round of rounds) addRound(round);
+ return {
+ acceptanceDir,
+ addRound,
+ cleanup: () => rmSync(root, { force: true, recursive: true }),
+ root,
+ };
+};
+
+/** A round with one screenshot check that passed and one planned video check that never ran. */
+export const firstRound = (): FixtureRound => ({
+ assets: {
+ 'after shot.png': pngHeader(800, 600),
+ 'api.txt': '$ curl /api/topic\n{"title":"Weekly sync"}\n',
+ },
+ dir: '20260101-090000-first',
+ proposal: 'Rename keeps the new title.',
+ report: '## Verification\n\n- tests pass',
+ result: {
+ cases: [
+ {
+ evidence: [
+ { description: 'The renamed topic', path: 'assets/after shot.png' },
+ { description: 'API read-back', path: 'assets/api.txt' },
+ ],
+ id: 'rename',
+ name: 'Rename keeps the new title',
+ observation: 'The list shows the new title.',
+ status: 'pass',
+ },
+ { id: 'unit', method: 'run bun run test', name: 'Unit tests pass', status: 'pass' },
+ ],
+ plan: [
+ {
+ category: 'Rename',
+ id: 'rename',
+ requiredEvidence: ['screenshot', 'text'],
+ title: 'Rename keeps the new title',
+ },
+ { category: 'Keyboard', id: 'enter', requiredEvidence: ['video'], title: 'Enter saves' },
+ ],
+ summary: { conclusion: 'Rename works; Enter not covered.', verdict: 'pass' },
+ title: 'Topic rename',
+ },
+});
diff --git a/apps/cli/src/commands/acceptance/run/evidenceUpload.ts b/apps/cli/src/commands/acceptance/run/evidenceUpload.ts
index 8b43cccf16e..cf59c66b33e 100644
--- a/apps/cli/src/commands/acceptance/run/evidenceUpload.ts
+++ b/apps/cli/src/commands/acceptance/run/evidenceUpload.ts
@@ -102,10 +102,12 @@ export async function uploadReportEvidence(
params: { checkResultId: string; dir: string; evidence: unknown },
) {
const failedEvidence: FailedReportEvidence[] = [];
+ /** Each stored artifact by its position in the authored `evidence` list. */
+ const published: { evidenceId: string; position: number }[] = [];
const types = new Set<EvidenceType>();
let count = 0;
let inlined = 0;
- for (const input of reportEvidence(params.evidence)) {
+ for (const [position, input] of reportEvidence(params.evidence).entries()) {
const absolutePath = path.resolve(params.dir, input.path);
const type = evidenceTypeForFile(absolutePath);
const description = evidenceDescriptionForFile(input.description, absolutePath);
@@ -127,7 +129,7 @@ export async function uploadReportEvidence(
}
const content = inlineTextEvidenceForFile(absolutePath, type);
if (content === undefined) fileId = (await uploadLocalFile(client, absolutePath)).id;
- await client.verify.uploadEvidence.mutate({
+ const row = await client.verify.uploadEvidence.mutate({
capturedBy: 'cli',
checkResultId: params.checkResultId,
content,
@@ -136,6 +138,7 @@ export async function uploadReportEvidence(
metadata,
type,
});
+ if (row?.id) published.push({ evidenceId: row.id, position });
types.add(type);
count += 1;
if (content !== undefined) inlined += 1;
@@ -173,5 +176,5 @@ export async function uploadReportEvidence(
log.warn(`evidence not published: ${path.basename(absolutePath)}: ${message}`);
}
}
- return { count, failedEvidence, inlined, types };
+ return { count, failedEvidence, inlined, published, types };
}
diff --git a/apps/cli/src/commands/acceptance/run/index.ts b/apps/cli/src/commands/acceptance/run/index.ts
index ed0d2c516ef..f9ea370bad5 100644
--- a/apps/cli/src/commands/acceptance/run/index.ts
+++ b/apps/cli/src/commands/acceptance/run/index.ts
@@ -5,6 +5,7 @@ import { Option } from 'commander';
import { createPublicLambdaClient } from '../../../api/client';
import { outputJson } from '../../../utils/format';
import { installAction, type InstallOptions, withInstallOptions } from '../install';
+import { renderReportAction, withRenderReportOptions } from '../local/render';
import { DECISIONS } from '../utils';
import {
evidenceDeleteAction,
@@ -116,6 +117,14 @@ export function attachAcceptanceRunCommands(acceptance: Command): void {
),
).action(ingestReportAction);
+ withRenderReportOptions(
+ run
+ .command('render <reportDir>')
+ .description(
+ 'Render a local round and every earlier round of its acceptance into one offline report.html — no login, nothing uploaded',
+ ),
+ ).action(renderReportAction);
+
withRunCreateOptions(
run.command('create').description('Create a standalone round (verification session)'),
).action(runCreateAction);
diff --git a/apps/cli/src/commands/acceptance/run/ingest.test.ts b/apps/cli/src/commands/acceptance/run/ingest.test.ts
index 55524bbe86c..9ac006a7921 100644
--- a/apps/cli/src/commands/acceptance/run/ingest.test.ts
+++ b/apps/cli/src/commands/acceptance/run/ingest.test.ts
@@ -1,4 +1,5 @@
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
@@ -7,6 +8,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { log } from '../../../utils/logger';
import { registerVerifyCommand } from '../deprecatedVerify';
+import { registerAcceptanceCommands } from '../index';
+import { loadLocalAcceptance } from '../local/localAcceptance';
const { mockTrpcClient } = vi.hoisted(() => ({
mockTrpcClient: {
@@ -163,6 +166,70 @@ describe('verify ingest-report — every run is an immutable acceptance round',
});
});
+ it.each([undefined, 'topic:authored-topic', { id: 'authored-task', type: 'task' }])(
+ 'publishes local histories independently of the ambient topic, preserving authored subject %j',
+ async (authoredSubject) => {
+ const acceptances = new Map<string, { id: string; subjectId: string; subjectType: string }>();
+ mockTrpcClient.acceptance.ensure.mutate.mockImplementation(
+ async (input: { subjectId: string; subjectType: string }) => {
+ const acceptance = { ...input, id: `acceptance-${input.subjectId}`, status: 'delivered' };
+ acceptances.set(acceptance.id, acceptance);
+ return acceptance;
+ },
+ );
+ mockTrpcClient.acceptance.getBundle.query.mockImplementation(
+ async ({ id }: { id: string }) => ({
+ acceptance: acceptances.get(id),
+ }),
+ );
+ vi.stubEnv('HOME', dir);
+ vi.stubEnv('LOBEHUB_ACCEPTANCE_DOWNLOADS', path.join(dir, 'Downloads'));
+
+ const publishedIds = [];
+ // Same directory name in two projects must not collapse two independent histories.
+ for (const project of ['first', 'second']) {
+ const acceptanceDir = path.join(dir, project, 'standalone-demo');
+ for (const round of ['20260101-090000-first', '20260102-090000-second']) {
+ const roundDir = path.join(acceptanceDir, round);
+ await mkdir(roundDir, { recursive: true });
+ await writeFile(
+ path.join(roundDir, 'result.json'),
+ JSON.stringify({ cases: [], subject: authoredSubject, title: 'Local delivery' }),
+ );
+ }
+ const { info } = loadLocalAcceptance(acceptanceDir, { create: true });
+ const program = new Command();
+ program.exitOverride();
+ registerAcceptanceCommands(program);
+ await program.parseAsync([
+ 'node',
+ 'lh',
+ 'acceptance',
+ 'publish',
+ acceptanceDir,
+ '--no-reviews',
+ '--json',
+ ]);
+
+ const published = JSON.parse(String(consoleSpy.mock.calls.at(-1)![0]));
+ const expectedSubjectId = authoredSubject
+ ? typeof authoredSubject === 'string'
+ ? 'authored-topic'
+ : 'authored-task'
+ : info.id;
+ expect(published.acceptanceId).toBe(`acceptance-${expectedSubjectId}`);
+ expect(published.published).toHaveLength(2);
+ const stored = JSON.parse(
+ await readFile(path.join(acceptanceDir, 'acceptance.json'), 'utf8'),
+ );
+ expect(stored.remote.acceptanceId).toBe(published.acceptanceId);
+ expect(stored.remote.rounds).toHaveLength(2);
+ publishedIds.push(published.acceptanceId);
+ }
+ expect(new Set(publishedIds).size).toBe(authoredSubject ? 1 : 2);
+ },
+ );
+
it('reuses the asset when the acceptance row is keyed by criterion rather than plan item', async () => {
mockTrpcClient.acceptance.getBundle.query.mockResolvedValue({
acceptance: {
@@ -297,6 +364,51 @@ describe('verify ingest-report — every run is an immutable acceptance round',
},
);
+ it.each([
+ { authored: 'task:T-12', name: 'the acceptance it already names', published: true },
+ { authored: 'task:T-99', name: 'another subject', published: false },
+ ])(
+ 'with --acceptance, accepts an authored subject only when it is $name',
+ async ({ authored, published }) => {
+ // `lh acceptance publish` appends a local acceptance's later rounds by
+ // id; their result.json keeps the subject the first round was filed under.
+ mockTrpcClient.acceptance.getBundle.query.mockResolvedValue({
+ acceptance: {
+ id: 'acceptance-existing',
+ status: 'delivered',
+ subjectId: 'T-12',
+ subjectType: 'task',
+ },
+ });
+ writeFileSync(
+ path.join(dir, 'result.json'),
+ JSON.stringify({ cases: [], subject: authored }),
+ );
+ const errorSpy = vi.spyOn(log, 'error').mockImplementation(() => {});
+ const exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
+ throw new Error(`process.exit ${code}`);
+ }) as never);
+ try {
+ const ingest = run(['ingest-report', dir, '--acceptance', 'acceptance-existing', '--json']);
+ if (published) await ingest;
+ else await expect(ingest).rejects.toThrow('process.exit 1');
+ } finally {
+ exitSpy.mockRestore();
+ errorSpy.mockRestore();
+ }
+
+ expect(mockTrpcClient.acceptance.ensure.mutate).not.toHaveBeenCalled();
+ if (published) {
+ expect(mockTrpcClient.acceptance.attachRun.mutate).toHaveBeenCalledWith({
+ acceptanceId: 'acceptance-existing',
+ verifyRunId: 'run-new',
+ });
+ } else {
+ expect(mockTrpcClient.verify.createRun.mutate).not.toHaveBeenCalled();
+ }
+ },
+ );
+
it.each([
{ effectiveWorkspace: null, name: 'revoked workspace membership' },
{ effectiveWorkspace: { id: 'workspace-other' }, name: 'a different server workspace' },
diff --git a/apps/cli/src/commands/acceptance/run/ingest.ts b/apps/cli/src/commands/acceptance/run/ingest.ts
index 5009bccd43c..7e8d219cf2e 100644
--- a/apps/cli/src/commands/acceptance/run/ingest.ts
+++ b/apps/cli/src/commands/acceptance/run/ingest.ts
@@ -1,9 +1,7 @@
import { randomUUID } from 'node:crypto';
-import { existsSync, readFileSync } from 'node:fs';
import path from 'node:path';
import { acceptanceSubjectTypes } from '@lobechat/const/verify';
-import type { VerifyAgentPlanConfig, VerifyCheckItem } from '@lobechat/types';
import type { Command } from 'commander';
import pc from 'picocolors';
@@ -16,30 +14,32 @@ import { log } from '../../../utils/logger';
import { assertReportLanguage, ingestLanguageFields, languageSummary } from '../language';
import { projectEnsureInput, resolveAcceptanceProject, warnIfFiledElsewhere } from '../project';
import {
- deriveReportVerdict,
+ type AcceptanceSubjectRef,
type EvidenceType,
findIdenticalLatestRound,
- genericContextFromResult,
interactionCostFromReportDir,
metadataForReport,
originFromEnv,
parseSubjectRef,
- planFromResult,
- pullRequestFromBranch,
- pullRequestFromResult,
reuseSourceCriteria,
- scenarioFromResult,
- screenProgrammaticTestChecks,
subjectFromEnv,
subjectFromResult,
- surfacesFromResult,
- toVerdict,
type Verdict,
- visualizationMetadata,
} from '../utils';
import type { FailedReportEvidence } from './evidenceUpload';
import { storageQuotaRecovery, uploadReportEvidence } from './evidenceUpload';
import { ingestIntoPlanRound } from './planRound';
+import {
+ caseResult,
+ missingEvidenceLimitation,
+ publishedVerdictFor,
+ readReportRound,
+ type ReportRound,
+ ReportRoundError,
+ requiredEvidenceGaps,
+ settleReport,
+ unexecutedEvidenceGaps,
+} from './reportRound';
// ── ingest-report (aggregate convenience over the atomic commands) ──
@@ -47,153 +47,68 @@ export interface IngestReportOptions {
acceptance?: string;
/** Run every local check, including the report language, then stop before publishing. */
dryRun?: boolean;
+ /** Local publication's stable subject, used only without an authored subject. Not a CLI flag. */
+ fallbackSubject?: AcceptanceSubjectRef;
goal?: string;
json?: boolean | string;
open?: boolean;
operation?: string;
project?: string;
+ /**
+ * Programmatic callers (`lh acceptance publish`): print nothing on success and
+ * return the summary `--json` would print. Not a command-line flag.
+ */
+ quiet?: boolean;
requirement?: string;
source?: string;
subject?: string;
title?: string;
}
-export async function ingestReportAction(
- reportDir: string,
- options: IngestReportOptions,
-): Promise<void> {
+/** What a published authored round reports back (`--json`). */
+export type IngestReportSummary = Exclude<Awaited<ReturnType<typeof ingestReportAction>>, void>;
+
+export async function ingestReportAction(reportDir: string, options: IngestReportOptions) {
const dir = path.resolve(reportDir);
// The guarantee has to hold however the round got here — a project that never
// ran `acceptance install`, or an agent that wrote the round by hand, still
// must not leave evidence binaries untracked in someone's repo.
ensureAcceptanceDirIgnoredFor(dir);
- const resultPath = path.join(dir, 'result.json');
- if (!existsSync(resultPath)) {
- log.error(`result.json not found in ${dir}`);
- process.exit(1);
- }
-
- let result: any;
+ let round: ReportRound;
try {
- result = JSON.parse(readFileSync(resultPath, 'utf8'));
- } catch {
- log.error('result.json is not valid JSON');
+ round = readReportRound(dir, { goal: options.goal, title: options.title });
+ } catch (error) {
+ if (!(error instanceof ReportRoundError)) throw error;
+ for (const line of error.lines) log.error(line);
process.exit(1);
}
-
- // Unit tests, type-checks and lint gates are preconditions of shipping, not
- // things a person accepts — a page full of them buries the checks that
- // actually needed a human eye. Screen them out of both the plan and the cases
- // before anything is published.
- const { droppedIds, droppedLabels } = screenProgrammaticTestChecks(result);
- const allCases: any[] = Array.isArray(result.cases) ? result.cases : [];
- // Freeze each case's id BEFORE filtering: the fallback id is position-based
- // (`case-N`), so dropping an earlier case would re-enumerate the survivors in
- // the ingest loop — pairing them with the wrong plan items and publishing
- // orphaned results into the immutable round.
- const casesWithIds = allCases.map((c, index) => ({
- case: c,
- checkItemId: String(c?.id ?? c?.checkItemId ?? `case-${index + 1}`),
- }));
- const cases = casesWithIds.filter(({ checkItemId }) => !droppedIds.has(checkItemId));
- // Every check was a gate: there is nothing here for a person to accept, and
- // publishing an empty round would just create a verdict-less page. Fail before
- // the first remote mutation, while the author can still fix the report.
- if (cases.length === 0 && allCases.length > 0) {
- log.error(
- 'every check in this round is a programmatic gate (tests / type-check / lint) — nothing here needs a human decision.',
- );
- log.error(
- ' Verify what the delivery does, shows, or produces, and keep the gates as one line of report.md.',
- );
- process.exit(1);
- }
- // Validate every schemaless visualization before the first remote mutation.
- // An ingest that cannot render must not create or attach a partial immutable round.
- const caseMetadata = cases.map(({ case: item, checkItemId }) => {
- try {
- return visualizationMetadata(item);
- } catch (error) {
- throw new Error(
- `case ${checkItemId}: ${error instanceof Error ? error.message : String(error)}`,
- { cause: error },
- );
- }
- });
- const summary = result.summary ?? {};
- const reportMdPath = path.join(dir, 'report.md');
- const content = existsSync(reportMdPath) ? readFileSync(reportMdPath, 'utf8') : undefined;
-
- // What this round is, said to the person who has to accept it, in their
- // language — the delivery's own note, not the verification write-up. It
- // posts into the discussion as a message from whoever ran the ingest, so a
- // reviewer reads it where the conversation already is rather than behind a
- // report link.
- const proposalMdPath = path.join(dir, 'proposal.md');
- const proposal = (
- existsSync(proposalMdPath)
- ? readFileSync(proposalMdPath, 'utf8')
- : typeof result.proposal === 'string'
- ? result.proposal
- : ''
- ).trim();
-
- // What kind of delivery this report verified (default: coding).
- const scenario = scenarioFromResult(result);
-
- // The scenario's context for the report's scope header. Coding lifts the
- // well-known top-level fields (branch / commit / surfaces / PR); every
- // other scenario passes result.json `context` through as its own bag.
- // `pullRequest` is hoisted: the success output (text and --json) prints
- // the PR link after the ingest, whatever the scenario resolved to.
- let context: Record<string, unknown> | undefined;
- let pullRequest: ReturnType<typeof pullRequestFromResult>;
- // Only a PR the report names is a delivery claim; the branch lookup below is
- // best-effort provenance and may find a long-lived branch's unrelated PR.
- let authoredPullRequest: ReturnType<typeof pullRequestFromResult>;
- if (scenario === 'coding') {
- const branch = typeof result.branch === 'string' ? result.branch : undefined;
- const surfaces = surfacesFromResult(result);
- // An authored PR wins; otherwise ask `gh` what the branch's PR is, so the
- // report links to it without the author having to remember the field.
- authoredPullRequest = pullRequestFromResult(result);
- pullRequest = authoredPullRequest ?? pullRequestFromBranch(branch);
- const contextEntries = Object.entries({
- branch,
- commit: typeof result.commit === 'string' ? result.commit : undefined,
- entry: typeof result.entry === 'string' ? result.entry : undefined,
- pullRequest,
- surfaces,
- testedAt: typeof result.createdAt === 'string' ? result.createdAt : undefined,
- }).filter(([, v]) => v !== undefined);
- context = contextEntries.length > 0 ? Object.fromEntries(contextEntries) : undefined;
- } else {
- context = genericContextFromResult(result);
- }
-
- // What the run set out to check, written before it ran. Paired with the
- // results by `id`, so the report can show a planned item that never ran.
- let plan: VerifyCheckItem[] | undefined = planFromResult(result, droppedIds);
-
- const goal = options.goal ?? (typeof result.focus === 'string' ? result.focus : undefined);
- const title = options.title ?? result.title;
- // The title is the run's identity in every list surface — an untitled
- // run renders as a placeholder forever, so say so before it ships.
- if (!title) {
- log.warn(
- 'result.json has no "title" — the run will list as untitled; set result.title (or pass --title)',
- );
- }
+ const {
+ allCases,
+ authoredPullRequest,
+ caseMetadata,
+ cases,
+ conclusion,
+ content,
+ context,
+ droppedLabels,
+ goal,
+ proposal,
+ pullRequest,
+ result,
+ scenario,
+ summary,
+ title,
+ } = round;
+ let plan = round.plan;
const requestedAcceptanceId = options.acceptance?.trim();
- if (requestedAcceptanceId && (options.subject || result.subject)) {
- log.error(
- 'Choose one acceptance target: pass --acceptance <id>, or use --subject/result.json `subject`.',
- );
+ if (requestedAcceptanceId && options.subject) {
+ log.error('Choose one acceptance target: pass --acceptance <id>, or use --subject.');
process.exit(1);
}
- // Explicit subject input wins, then result.json, then the authoring topic.
+ // Explicit subject input wins, then result.json, then the local publisher's
+ // stable identity (if any), then the authoring topic.
// An external repository has none of those, so create a first-class
// standalone subject instead of making the caller manufacture a Task ID.
let subject = subjectFromResult(result);
@@ -211,10 +126,10 @@ export async function ingestReportAction(
log.error('result.json `subject` is malformed (expected "type:id" or {type,id})');
process.exit(1);
} else if (!requestedAcceptanceId && !subject) {
- const ref = subjectFromEnv();
+ const ref = options.fallbackSubject ?? subjectFromEnv();
if (ref) subject = { ref };
// Only the ambient topic may be folded onto its Task; an explicit subject stays exact.
- foldTaskRunTopic = Boolean(ref);
+ foldTaskRunTopic = !options.fallbackSubject && Boolean(ref);
}
if (!requestedAcceptanceId && !subject) {
subject = {
@@ -223,15 +138,6 @@ export async function ingestReportAction(
}
const requirement = options.requirement ?? subject?.requirement;
- // The overall conclusion, rendered at the top of the report page. Read up
- // front so the duplicate check below compares what would land.
- const conclusion =
- typeof summary.conclusion === 'string'
- ? summary.conclusion
- : typeof summary.note === 'string'
- ? summary.note
- : undefined;
-
const client = await getTrpcClient();
// Before the first remote mutation: a round in the wrong language cannot be
// fixed in place, only replaced by another immutable round.
@@ -316,6 +222,19 @@ export async function ingestReportAction(
if (requestedAcceptanceId) {
bundle = await client.acceptance.getBundle.query({ id: requestedAcceptanceId });
acceptance = bundle.acceptance;
+ // A round's authored `subject` may ride along with the acceptance that
+ // already holds it (`lh acceptance publish` appends later rounds by id);
+ // one naming another subject is a conflicting target, not a hint.
+ if (
+ result.subject &&
+ (subject?.ref.subjectType !== acceptance.subjectType ||
+ subject.ref.subjectId !== acceptance.subjectId)
+ ) {
+ log.error(
+ `result.json \`subject\` does not match acceptance "${acceptance.id}" (${acceptance.subjectType}:${acceptance.subjectId}). Drop --acceptance, or the subject.`,
+ );
+ process.exit(1);
+ }
// ID-based reads can cross scopes, but creating a run uses the CLI's scope.
// Reject before any writes instead of leaving an unattachable run behind.
const currentWorkspaceId = resolveWorkspaceId();
@@ -471,28 +390,19 @@ export async function ingestReportAction(
let evidenceCount = 0;
let inlined = 0;
const failedEvidence: (FailedReportEvidence & { checkItemId: string })[] = [];
+ // What landed, by authored position: a caller holding its own copy of the
+ // round (`lh acceptance publish`) maps its artifacts onto these by identity.
+ const publishedEvidence: { checkItemId: string; evidenceId: string; position: number }[] = [];
const missingEvidence: { checkItemId: string; types: EvidenceType[] }[] = [];
const publishedVerdicts: Verdict[] = [];
for (const [index, { case: c, checkItemId }] of cases.entries()) {
seenCheckItemIds.add(checkItemId);
- const verdict = toVerdict(c.result ?? c.status ?? c.verdict);
- const observation = c.keyObservation ?? c.observation ?? c.note;
const checkInput = {
- checkItemId,
- checkItemIndex: index,
- checkItemTitle: c.name ?? c.case ?? c.title ?? checkItemId,
- metadata: caseMetadata[index],
- required: c.required ?? true,
- // The case's key observation is recorded as Toulmin evidence; a real
- // remediation hint (if the report provides one) goes to `suggestion`.
- // Absent → explicit `null`, so this immutable snapshot records the
- // absence instead of relying on upsert defaults.
- suggestion: typeof c.suggestion === 'string' ? c.suggestion : null,
- toulmin: typeof observation === 'string' ? { evidence: observation } : null,
- verdict,
+ ...caseResult(c, checkItemId, index, caseMetadata[index]),
verifierType: 'agent' as const,
verifyRunId: runId,
};
+ const { verdict } = checkInput;
const checkResult = await client.verify.ingestResult.mutate(checkInput);
const uploaded = await uploadReportEvidence(client, {
checkResultId: checkResult.id,
@@ -502,17 +412,13 @@ export async function ingestReportAction(
evidenceCount += uploaded.count;
inlined += uploaded.inlined;
failedEvidence.push(...uploaded.failedEvidence.map((failure) => ({ ...failure, checkItemId })));
- const config = plan?.find((item) => item.id === checkItemId)?.verifierConfig as
- VerifyAgentPlanConfig | undefined;
- const required = config?.requiredEvidence;
- const gaps = [...new Set(required?.map((spec) => spec.type) ?? [])].filter(
- (type) => !uploaded.types.has(type),
- );
- const publishedVerdict = gaps.length > 0 && verdict === 'passed' ? 'uncertain' : verdict;
+ publishedEvidence.push(...uploaded.published.map((item) => ({ ...item, checkItemId })));
+ const gaps = requiredEvidenceGaps(plan, checkItemId, uploaded.types);
+ const publishedVerdict = publishedVerdictFor(verdict, gaps);
publishedVerdicts.push(publishedVerdict);
if (gaps.length > 0) {
missingEvidence.push({ checkItemId, types: gaps });
- const limitation = `Required evidence not published: ${gaps.join(', ')}.`;
+ const limitation = missingEvidenceLimitation(gaps);
log.warn(`${checkItemId}: ${limitation}`);
await client.verify.ingestResult.mutate({
...checkInput,
@@ -523,10 +429,7 @@ export async function ingestReportAction(
}
const unexecuted = plan?.filter((item) => !seenCheckItemIds.has(item.id)) ?? [];
- for (const item of unexecuted) {
- const config = item.verifierConfig as VerifyAgentPlanConfig;
- const types = [...new Set(config.requiredEvidence?.map((spec) => spec.type) ?? [])];
- if (types.length === 0) continue;
+ for (const { item, types } of unexecutedEvidenceGaps(plan, seenCheckItemIds)) {
missingEvidence.push({ checkItemId: item.id, types });
// Count the gap without inventing an execution result for an unexecuted check.
publishedVerdicts.push('uncertain');
@@ -535,39 +438,16 @@ export async function ingestReportAction(
// 3. Write the report. `summary` is the overall conclusion (read above);
// `content` is the full markdown detail.
- // A 0-100 quality score lands on overallConfidence (0-1); the report page
- // surfaces it as the `score` stat.
- const score =
- typeof summary.score === 'number' ? Math.max(0, Math.min(1, summary.score / 100)) : undefined;
- // The authored counts describe the report the author wrote. Once a
- // programmatic-test check is screened out they no longer match what was
- // published, so recount the landed cases and unexecuted evidence gaps — a
- // stats block that disagrees with the visible check list is worse than no stats.
- const recount = cases.length !== allCases.length || missingEvidence.length > 0;
- const counted = (verdict: Verdict) => publishedVerdicts.filter((v) => v === verdict).length;
- const derivedVerdict = deriveReportVerdict(publishedVerdicts.map((verdict) => ({ verdict })));
- const reportVerdict =
- summary.verdict && cases.length === allCases.length
- ? toVerdict(summary.verdict)
- : derivedVerdict;
await client.verify.upsertReport.mutate({
- content,
- failedChecks: recount ? counted('failed') : summary.failed,
- overallConfidence: score,
- passedChecks: recount ? counted('passed') : summary.passed,
- summary: conclusion,
- totalChecks: recount ? publishedVerdicts.length : (summary.total ?? cases.length),
- uncertainChecks: recount
- ? counted('uncertain') || undefined
- : (summary.blocked ?? 0) + (summary.uncertain ?? 0) || undefined,
- // Missing evidence cannot be overridden by an authored "passed" summary.
- // Keep a real failure rather than hiding it behind an evidence warning.
- verdict:
- missingEvidence.length > 0
- ? reportVerdict === 'failed' || derivedVerdict === 'failed'
- ? 'failed'
- : 'uncertain'
- : reportVerdict,
+ ...settleReport({
+ allCasesCount: allCases.length,
+ casesCount: cases.length,
+ conclusion,
+ content,
+ missingEvidenceCount: missingEvidence.length,
+ publishedVerdicts,
+ summary,
+ }),
verifyRunId: runId,
});
@@ -641,35 +521,35 @@ export async function ingestReportAction(
if (recovery) log.warn(recovery.message);
}
+ const published = {
+ acceptanceId,
+ acceptanceUrl,
+ cases: cases.length,
+ droppedProgrammaticChecks: droppedLabels,
+ evidence: evidenceCount,
+ failedEvidence,
+ inlined,
+ missingEvidence,
+ origin,
+ planItems: plan?.length ?? 0,
+ proposalPosted,
+ publicationStatus: partial ? 'partial' : 'complete',
+ publishedEvidence,
+ pullRequest,
+ recovery,
+ roundIndex,
+ roundUrl,
+ scenario,
+ subject: subject!.ref,
+ unexecuted: unexecuted.map((item) => item.id),
+ unplanned,
+ unresolvedSupersedes,
+ verifyRunId: runId,
+ };
+ if (options.quiet) return published;
if (options.json !== undefined) {
- outputJson(
- {
- acceptanceId,
- acceptanceUrl,
- cases: cases.length,
- droppedProgrammaticChecks: droppedLabels,
- evidence: evidenceCount,
- failedEvidence,
- inlined,
- missingEvidence,
- origin,
- planItems: plan?.length ?? 0,
- proposalPosted,
- publicationStatus: partial ? 'partial' : 'complete',
- pullRequest,
- recovery,
- roundIndex,
- roundUrl,
- scenario,
- subject: subject!.ref,
- unexecuted: unexecuted.map((item) => item.id),
- unplanned,
- unresolvedSupersedes,
- verifyRunId: runId,
- },
- typeof options.json === 'string' ? options.json : undefined,
- );
- return;
+ outputJson(published, typeof options.json === 'string' ? options.json : undefined);
+ return published;
}
console.log(
@@ -710,6 +590,7 @@ export async function ingestReportAction(
console.log(`${pc.bold('round snapshot')}: ${roundUrl}`);
}
}
+ return published;
}
export function withIngestReportOptions(cmd: Command): Command {
diff --git a/apps/cli/src/commands/acceptance/run/reportRound.ts b/apps/cli/src/commands/acceptance/run/reportRound.ts
new file mode 100644
index 00000000000..a8ed2caaf99
--- /dev/null
+++ b/apps/cli/src/commands/acceptance/run/reportRound.ts
@@ -0,0 +1,338 @@
+import { existsSync, readFileSync } from 'node:fs';
+import path from 'node:path';
+
+import type { VerifyAgentPlanConfig, VerifyCheckItem } from '@lobechat/types';
+
+import { log } from '../../../utils/logger';
+import {
+ deriveReportVerdict,
+ type EvidenceType,
+ genericContextFromResult,
+ planFromResult,
+ pullRequestFromBranch,
+ pullRequestFromResult,
+ scenarioFromResult,
+ screenProgrammaticTestChecks,
+ surfacesFromResult,
+ toVerdict,
+ type Verdict,
+ visualizationMetadata,
+} from '../utils';
+
+// ============================================
+// One round directory (`result.json` + `report.md` + `proposal.md` +
+// `assets/`), read the way every publication of it reads it. `ingest` uploads
+// what this returns; a local report renders it. Sharing the reader is what
+// keeps the two from disagreeing about which checks a round has, what each
+// verdict is, or which evidence a pass is missing.
+// ============================================
+
+/** A round the author must fix before anything is published or rendered. */
+export class ReportRoundError extends Error {
+ readonly lines: string[];
+
+ constructor(lines: string[]) {
+ super(lines.join('\n'));
+ this.lines = lines;
+ this.name = 'ReportRoundError';
+ }
+}
+
+export interface ReportRoundCase {
+ case: any;
+ checkItemId: string;
+}
+
+export interface ReportRound {
+ allCases: any[];
+ /** A PR the report itself names — a delivery claim, unlike the branch lookup. */
+ authoredPullRequest: ReturnType<typeof pullRequestFromResult>;
+ caseMetadata: ReturnType<typeof visualizationMetadata>[];
+ cases: ReportRoundCase[];
+ conclusion?: string;
+ /** `report.md` — the narrative tail. */
+ content?: string;
+ context?: Record<string, unknown>;
+ dir: string;
+ droppedIds: Set<string>;
+ droppedLabels: string[];
+ goal?: string;
+ plan?: VerifyCheckItem[];
+ proposal: string;
+ pullRequest: ReturnType<typeof pullRequestFromResult>;
+ result: any;
+ scenario: ReturnType<typeof scenarioFromResult>;
+ summary: any;
+ title?: string;
+}
+
+/**
+ * Read a round directory. Throws {@link ReportRoundError} for a report that
+ * cannot become a round (missing or invalid `result.json`, a gates-only round,
+ * a visualization that cannot render) — before the first remote write.
+ */
+export function readReportRound(
+ reportDir: string,
+ options: {
+ goal?: string;
+ /** Ask `gh` for the branch's PR when the report names none (default: yes). */
+ inferPullRequest?: boolean;
+ /** Skip authoring warnings — the round is being re-read, not published. */
+ quiet?: boolean;
+ title?: string;
+ } = {},
+): ReportRound {
+ const dir = path.resolve(reportDir);
+ const resultPath = path.join(dir, 'result.json');
+ if (!existsSync(resultPath)) throw new ReportRoundError([`result.json not found in ${dir}`]);
+
+ let result: any;
+ try {
+ result = JSON.parse(readFileSync(resultPath, 'utf8'));
+ } catch {
+ throw new ReportRoundError(['result.json is not valid JSON']);
+ }
+
+ // Unit tests, type-checks and lint gates are preconditions of shipping, not
+ // things a person accepts — a page full of them buries the checks that
+ // actually needed a human eye. Screen them out of both the plan and the cases
+ // before anything is published.
+ const { droppedIds, droppedLabels } = screenProgrammaticTestChecks(result, {
+ quiet: options.quiet,
+ });
+ const allCases: any[] = Array.isArray(result.cases) ? result.cases : [];
+ // Freeze each case's id BEFORE filtering: the fallback id is position-based
+ // (`case-N`), so dropping an earlier case would re-enumerate the survivors in
+ // the ingest loop — pairing them with the wrong plan items and publishing
+ // orphaned results into the immutable round.
+ const casesWithIds = allCases.map((c, index) => ({
+ case: c,
+ checkItemId: String(c?.id ?? c?.checkItemId ?? `case-${index + 1}`),
+ }));
+ const cases = casesWithIds.filter(({ checkItemId }) => !droppedIds.has(checkItemId));
+ // Every check was a gate: there is nothing here for a person to accept, and
+ // publishing an empty round would just create a verdict-less page. Fail before
+ // the first remote mutation, while the author can still fix the report.
+ if (cases.length === 0 && allCases.length > 0) {
+ throw new ReportRoundError([
+ 'every check in this round is a programmatic gate (tests / type-check / lint) — nothing here needs a human decision.',
+ ' Verify what the delivery does, shows, or produces, and keep the gates as one line of report.md.',
+ ]);
+ }
+ // Validate every schemaless visualization before the first remote mutation.
+ // An ingest that cannot render must not create or attach a partial immutable round.
+ const caseMetadata = cases.map(({ case: item, checkItemId }) => {
+ try {
+ return visualizationMetadata(item);
+ } catch (error) {
+ throw new Error(
+ `case ${checkItemId}: ${error instanceof Error ? error.message : String(error)}`,
+ { cause: error },
+ );
+ }
+ });
+ const summary = result.summary ?? {};
+ const reportMdPath = path.join(dir, 'report.md');
+ const content = existsSync(reportMdPath) ? readFileSync(reportMdPath, 'utf8') : undefined;
+
+ // What this round is, said to the person who has to accept it, in their
+ // language — the delivery's own note, not the verification write-up. It
+ // posts into the discussion as a message from whoever ran the ingest, so a
+ // reviewer reads it where the conversation already is rather than behind a
+ // report link.
+ const proposalMdPath = path.join(dir, 'proposal.md');
+ const proposal = (
+ existsSync(proposalMdPath)
+ ? readFileSync(proposalMdPath, 'utf8')
+ : typeof result.proposal === 'string'
+ ? result.proposal
+ : ''
+ ).trim();
+
+ // What kind of delivery this report verified (default: coding).
+ const scenario = scenarioFromResult(result);
+
+ // The scenario's context for the report's scope header. Coding lifts the
+ // well-known top-level fields (branch / commit / surfaces / PR); every
+ // other scenario passes result.json `context` through as its own bag.
+ // `pullRequest` is hoisted: the success output (text and --json) prints
+ // the PR link after the ingest, whatever the scenario resolved to.
+ let context: Record<string, unknown> | undefined;
+ let pullRequest: ReturnType<typeof pullRequestFromResult>;
+ // Only a PR the report names is a delivery claim; the branch lookup below is
+ // best-effort provenance and may find a long-lived branch's unrelated PR.
+ let authoredPullRequest: ReturnType<typeof pullRequestFromResult>;
+ if (scenario === 'coding') {
+ const branch = typeof result.branch === 'string' ? result.branch : undefined;
+ const surfaces = surfacesFromResult(result);
+ // An authored PR wins; otherwise ask `gh` what the branch's PR is, so the
+ // report links to it without the author having to remember the field.
+ authoredPullRequest = pullRequestFromResult(result);
+ pullRequest =
+ authoredPullRequest ??
+ (options.inferPullRequest === false ? undefined : pullRequestFromBranch(branch));
+ const contextEntries = Object.entries({
+ branch,
+ commit: typeof result.commit === 'string' ? result.commit : undefined,
+ entry: typeof result.entry === 'string' ? result.entry : undefined,
+ pullRequest,
+ surfaces,
+ testedAt: typeof result.createdAt === 'string' ? result.createdAt : undefined,
+ }).filter(([, v]) => v !== undefined);
+ context = contextEntries.length > 0 ? Object.fromEntries(contextEntries) : undefined;
+ } else {
+ context = genericContextFromResult(result);
+ }
+
+ // What the run set out to check, written before it ran. Paired with the
+ // results by `id`, so the report can show a planned item that never ran.
+ const plan: VerifyCheckItem[] | undefined = planFromResult(result, droppedIds);
+
+ const goal = options.goal ?? (typeof result.focus === 'string' ? result.focus : undefined);
+ const title = options.title ?? result.title;
+ // The title is the run's identity in every list surface — an untitled
+ // run renders as a placeholder forever, so say so before it ships.
+ if (!title && !options.quiet) {
+ log.warn(
+ 'result.json has no "title" — the run will list as untitled; set result.title (or pass --title)',
+ );
+ }
+
+ // The overall conclusion, rendered at the top of the report page.
+ const conclusion =
+ typeof summary.conclusion === 'string'
+ ? summary.conclusion
+ : typeof summary.note === 'string'
+ ? summary.note
+ : undefined;
+
+ return {
+ allCases,
+ authoredPullRequest,
+ caseMetadata,
+ cases,
+ conclusion,
+ content,
+ context,
+ dir,
+ droppedIds,
+ droppedLabels,
+ goal,
+ plan,
+ proposal,
+ pullRequest,
+ result,
+ scenario,
+ summary,
+ title,
+ };
+}
+
+/** One case as the check result a round records for it. */
+export function caseResult(
+ c: any,
+ checkItemId: string,
+ index: number,
+ metadata: ReturnType<typeof visualizationMetadata>,
+) {
+ const verdict = toVerdict(c.result ?? c.status ?? c.verdict);
+ const observation = c.keyObservation ?? c.observation ?? c.note;
+ return {
+ checkItemId,
+ checkItemIndex: index,
+ checkItemTitle: c.name ?? c.case ?? c.title ?? checkItemId,
+ metadata,
+ required: c.required ?? true,
+ // The case's key observation is recorded as Toulmin evidence; a real
+ // remediation hint (if the report provides one) goes to `suggestion`.
+ // Absent → explicit `null`, so this immutable snapshot records the
+ // absence instead of relying on upsert defaults.
+ suggestion: typeof c.suggestion === 'string' ? c.suggestion : null,
+ toulmin: typeof observation === 'string' ? { evidence: observation } : null,
+ verdict,
+ };
+}
+
+/** The evidence media a check requires that its published evidence lacks. */
+export function requiredEvidenceGaps(
+ plan: VerifyCheckItem[] | undefined,
+ checkItemId: string,
+ published: Set<EvidenceType>,
+): EvidenceType[] {
+ const config = plan?.find((item) => item.id === checkItemId)?.verifierConfig as
+ VerifyAgentPlanConfig | undefined;
+ const required = config?.requiredEvidence;
+ return [...new Set(required?.map((spec) => spec.type as EvidenceType) ?? [])].filter(
+ (type) => !published.has(type),
+ );
+}
+
+/** A pass that lacks required evidence is published as uncertain, never as a pass. */
+export function publishedVerdictFor(verdict: Verdict, gaps: EvidenceType[]): Verdict {
+ return gaps.length > 0 && verdict === 'passed' ? 'uncertain' : verdict;
+}
+
+export const missingEvidenceLimitation = (gaps: EvidenceType[]) =>
+ `Required evidence not published: ${gaps.join(', ')}.`;
+
+/** Planned items that produced no case but required evidence: open gaps, not passes. */
+export function unexecutedEvidenceGaps(
+ plan: VerifyCheckItem[] | undefined,
+ executed: Set<string>,
+): { item: VerifyCheckItem; types: EvidenceType[] }[] {
+ const unexecuted = plan?.filter((item) => !executed.has(item.id)) ?? [];
+ return unexecuted.flatMap((item) => {
+ const config = item.verifierConfig as VerifyAgentPlanConfig;
+ const types = [
+ ...new Set(config.requiredEvidence?.map((spec) => spec.type as EvidenceType) ?? []),
+ ];
+ return types.length > 0 ? [{ item, types }] : [];
+ });
+}
+
+/**
+ * The round's report row: the author's summary, recounted whenever screening
+ * dropped a case or evidence is missing — a stats block that disagrees with the
+ * visible check list is worse than no stats.
+ */
+export function settleReport(input: {
+ allCasesCount: number;
+ casesCount: number;
+ conclusion?: string;
+ content?: string;
+ missingEvidenceCount: number;
+ publishedVerdicts: Verdict[];
+ summary: any;
+}) {
+ const { summary, publishedVerdicts } = input;
+ // A 0-100 quality score lands on overallConfidence (0-1); the report page
+ // surfaces it as the `score` stat.
+ const score =
+ typeof summary.score === 'number' ? Math.max(0, Math.min(1, summary.score / 100)) : undefined;
+ const recount = input.casesCount !== input.allCasesCount || input.missingEvidenceCount > 0;
+ const counted = (verdict: Verdict) => publishedVerdicts.filter((v) => v === verdict).length;
+ const derivedVerdict = deriveReportVerdict(publishedVerdicts.map((verdict) => ({ verdict })));
+ const reportVerdict =
+ summary.verdict && input.casesCount === input.allCasesCount
+ ? toVerdict(summary.verdict)
+ : derivedVerdict;
+ return {
+ content: input.content,
+ failedChecks: recount ? counted('failed') : summary.failed,
+ overallConfidence: score,
+ passedChecks: recount ? counted('passed') : summary.passed,
+ summary: input.conclusion,
+ totalChecks: recount ? publishedVerdicts.length : (summary.total ?? input.casesCount),
+ uncertainChecks: recount
+ ? counted('uncertain') || undefined
+ : (summary.blocked ?? 0) + (summary.uncertain ?? 0) || undefined,
+ // Missing evidence cannot be overridden by an authored "passed" summary.
+ // Keep a real failure rather than hiding it behind an evidence warning.
+ verdict:
+ input.missingEvidenceCount > 0
+ ? reportVerdict === 'failed' || derivedVerdict === 'failed'
+ ? 'failed'
+ : 'uncertain'
+ : reportVerdict,
+ };
+}
diff --git a/apps/cli/src/commands/acceptance/utils/plan.ts b/apps/cli/src/commands/acceptance/utils/plan.ts
index 33f2b7ed6bc..9356b129abe 100644
--- a/apps/cli/src/commands/acceptance/utils/plan.ts
+++ b/apps/cli/src/commands/acceptance/utils/plan.ts
@@ -41,6 +41,7 @@ export interface ProgrammaticTestScreen {
*/
export function screenProgrammaticTestChecks(
result: Record<string, unknown>,
+ options: { quiet?: boolean } = {},
): ProgrammaticTestScreen {
const droppedIds = new Set<string>();
const droppedLabels: string[] = [];
@@ -75,7 +76,7 @@ export function screenProgrammaticTestChecks(
);
}
- if (droppedLabels.length > 0) {
+ if (droppedLabels.length > 0 && !options.quiet) {
log.warn(
`dropping ${droppedLabels.length} programmatic-test check(s) from this acceptance round:`,
);
diff --git a/apps/server/src/services/verify/acceptanceService/attachGuards.ts b/apps/server/src/services/verify/acceptanceService/attachGuards.ts
index cf617d6a4cc..2fbb4917a18 100644
--- a/apps/server/src/services/verify/acceptanceService/attachGuards.ts
+++ b/apps/server/src/services/verify/acceptanceService/attachGuards.ts
@@ -1,11 +1,11 @@
import type { VerifyCheckItem } from '@lobechat/types';
+import { buildCheckReviewOverlay } from '@lobechat/utils/verify/acceptanceReviewOverlay';
import type { VerifyCheckResultItem, VerifyRunItem } from '@/database/schemas/verify';
import { findUnresolvedSupersedes } from '../acceptanceMerge';
import { buildAcceptanceCheckUnion } from './checkUnion';
import type { AcceptanceServiceDeps } from './deps';
-import { buildCheckReviewOverlay } from './reviewOverlay';
/** A run chained onto an acceptance, with anything the author should fix. */
export type AttachedRun = VerifyRunItem & {
diff --git a/apps/server/src/services/verify/acceptanceService/checkUnion.ts b/apps/server/src/services/verify/acceptanceService/checkUnion.ts
index b8756cfe7f6..8037031532e 100644
--- a/apps/server/src/services/verify/acceptanceService/checkUnion.ts
+++ b/apps/server/src/services/verify/acceptanceService/checkUnion.ts
@@ -1,278 +1,16 @@
-import { normalizeVerifySurface } from '@lobechat/const/verify';
-import type {
- AcceptanceCheckGroup,
- VerifyAgentPlanConfig,
- VerifyCheckItem,
- VerifyCheckTally,
- VerifySurface,
-} from '@lobechat/types';
-
-import type { VerifyCheckResultItem, VerifyRunItem } from '@/database/schemas/verify';
-
-// ============================================
-// 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;
- /**
- * Stable 1-based label across the whole union ("C3") — first-appearance
- * order over the round chain, so earlier rounds' numbering never shifts when
- * a new round lands. Feedback and annotations reference checks by it.
- * (Folding a superseded generation removes its row, so numbering after the
- * folded id shifts by one — the successor keeps its own slot.)
- */
- seq: 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[],
- groups: AcceptanceCheckGroup[] = [],
-): 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>();
- // A `supersedes` entry names the check the author knew: often the plan item id
- // they wrote, while the row is keyed by the criterion minted for it. Remember
- // every plan item id's row so the fold below resolves either spelling.
- const logicalIdByPlanItemId = new Map<string, string>();
-
- 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,
- seq: 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]));
- const logicalIdByCheckItemId = new Map(
- plan.map((item) => [
- item.id,
- item.sourceFlowNode ? item.id : (item.sourceCriterionId ?? item.id),
- ]),
- );
-
- for (const item of plan) {
- const logicalId = item.sourceFlowNode ? item.id : (item.sourceCriterionId ?? item.id);
- const row = ensureRow(logicalId, roundIndex);
- logicalIdByPlanItemId.set(item.id, logicalId);
- // The latest snapshot wins: repair rounds may refine method/expected.
- if (item.sourceFlowNode) {
- // A rerun is a fresh execution; historical evidence stays in the timeline.
- row.result = undefined;
- row.resultRound = undefined;
- }
- 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(logicalId, roundIndex);
- }
-
- for (const result of results) {
- const logicalId = logicalIdByCheckItemId.get(result.checkItemId) ?? result.checkItemId;
- const row = ensureRow(logicalId, 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 ?? []).map((id) =>
- rows.has(id) ? id : (logicalIdByPlanItemId.get(id) ?? id),
- );
- 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);
- }
- }
-
- // Number the surviving rows by first appearance (Map insertion order) —
- // stable as rounds accrue, because a new round only appends new ids.
- let seq = 0;
- for (const row of rows.values()) row.seq = ++seq;
-
- 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;
- }
- }
-
- // Organization belongs to the current acceptance, not its immutable execution
- // snapshots. Preserve IDs, numbering and result references when a check moves.
- const grouped = new Map<string, AcceptanceCheckRow>();
- for (const group of groups) {
- for (const id of group.checkItemIds) {
- const row = rows.get(id);
- if (row) grouped.set(id, { ...row, category: group.title });
- }
- }
- return [...grouped.values(), ...[...rows.values()].filter((row) => !grouped.has(row.id))];
-};
-
-/**
- * The union's own three-way split, counted — the number a summary can show
- * without opening the list.
- *
- * It counts UNION ROWS, not one round's result rows. A repair round re-runs the
- * check it was asked to fix and carries the rest forward, so the current round's
- * rows are a subset of the union: counting them would print "1 passed" beside a
- * list that expands to the repaired check plus everything it carried, and the
- * two readings of one acceptance would contradict each other.
- */
-export const tallyCheckUnion = (checks: AcceptanceCheckRow[]): VerifyCheckTally => {
- let failed = 0;
- let passed = 0;
- let unjudged = 0;
- for (const check of checks) {
- if (check.state === 'passed') passed++;
- else if (check.state === 'failed') failed++;
- // `uncertain` and `not_executed` are both "planned, never judged" — the same
- // split the acceptance's criteria list draws.
- else unjudged++;
- }
- return { failed, passed, total: checks.length, unjudged };
-};
+import type { AcceptanceCheckRow as SharedAcceptanceCheckRow } from '@lobechat/utils/verify/acceptanceCheckUnion';
+
+import type { VerifyCheckResultItem } from '@/database/schemas/verify';
+
+// The union is pure and shared with the CLI's local reports; the server reads
+// it over its own result rows.
+export type {
+ AcceptanceCheckHistoryEntry,
+ AcceptanceTimelineEntry,
+} from '@lobechat/utils/verify/acceptanceCheckUnion';
+export {
+ buildAcceptanceCheckUnion,
+ tallyCheckUnion,
+} from '@lobechat/utils/verify/acceptanceCheckUnion';
+
+export type AcceptanceCheckRow = SharedAcceptanceCheckRow<VerifyCheckResultItem>;
diff --git a/apps/server/src/services/verify/acceptanceService/index.ts b/apps/server/src/services/verify/acceptanceService/index.ts
index 1c852a37bf8..2807f53a964 100644
--- a/apps/server/src/services/verify/acceptanceService/index.ts
+++ b/apps/server/src/services/verify/acceptanceService/index.ts
@@ -7,6 +7,7 @@ import type {
VerifyCheckTally,
VerifyRunDecisionDetail,
} from '@lobechat/types';
+import { statusFromRound } from '@lobechat/utils/verify/acceptanceStatus';
import debug from 'debug';
import { AcceptanceModel } from '@/database/models/acceptance';
@@ -44,7 +45,6 @@ import {
} from './listing';
import { findRepairOrigin, resolveOrigin } from './origin';
import { reviewChecks } from './reviewChecks';
-import { statusFromRound } from './statusRollup';
import {
type AcceptanceSubjectSummary,
assertProjectExists,
@@ -68,13 +68,13 @@ export type {
} from './checkUnion';
export { buildAcceptanceCheckUnion, tallyCheckUnion } from './checkUnion';
export type { AcceptanceListFilter, AcceptanceListOptions } from './listing';
+export type { AcceptanceSubjectSummary } from './subjects';
export type {
AcceptanceCheckReviewEvent,
AcceptanceCheckReviewOverlay,
AcceptanceCheckUserReview,
-} from './reviewOverlay';
-export { buildCheckReviewOverlay } from './reviewOverlay';
-export type { AcceptanceSubjectSummary } from './subjects';
+} from '@lobechat/utils/verify/acceptanceReviewOverlay';
+export { buildCheckReviewOverlay } from '@lobechat/utils/verify/acceptanceReviewOverlay';
const log = debug('lobe-server:verify-acceptance');
diff --git a/apps/workbench/.gitignore b/apps/workbench/.gitignore
index b1480192792..9cad9b93b64 100644
--- a/apps/workbench/.gitignore
+++ b/apps/workbench/.gitignore
@@ -4,3 +4,4 @@
build/
build-inputs.txt
output-hash.txt
+dist-report/
diff --git a/apps/workbench/package.json b/apps/workbench/package.json
index b0c720cbf62..66bc5c79b0d 100644
--- a/apps/workbench/package.json
+++ b/apps/workbench/package.json
@@ -5,6 +5,7 @@
"type": "module",
"scripts": {
"build": "vite build",
+ "build:report": "NODE_ENV=production vite build -c vite.config.report.mts",
"build:rr": "react-router build -c vite.config.rr.mts",
"deploy": "bun scripts/deploy.ts",
"deploy:rr": "wrangler deploy --dry-run",
diff --git a/apps/workbench/report.html b/apps/workbench/report.html
new file mode 100644
index 00000000000..8f8f16673fd
--- /dev/null
+++ b/apps/workbench/report.html
@@ -0,0 +1,47 @@
+<!doctype html>
+<html>
+ <head>
+ <meta charset="utf-8" />
+ <!-- The report runs from disk; only adjacent evidence and embedded assets may load. -->
+ <!-- Bundled code may compile JS/Wasm (Zod/diagrams), but cannot load script URLs. -->
+ <meta
+ http-equiv="Content-Security-Policy"
+ content="default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval'; style-src 'unsafe-inline'; img-src 'self' file: data: blob:; media-src 'self' file: data: blob:; font-src data:; connect-src 'none'; base-uri 'none'; form-action 'none'"
+ />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <meta name="robots" content="noindex, nofollow" />
+ <!--ACCEPTANCE_LOCAL_TITLE-->
+ <style>
+ html body {
+ background: #f8f8f8;
+ }
+ html[data-theme='dark'] body {
+ background-color: #000;
+ }
+ </style>
+ <script>
+ (function () {
+ var theme = 'system';
+ try {
+ theme = localStorage.getItem('theme') || 'system';
+ } catch (_) {}
+ var systemTheme =
+ window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
+ ? 'dark'
+ : 'light';
+ var resolvedTheme = theme === 'system' ? systemTheme : theme;
+ if (resolvedTheme === 'dark' || resolvedTheme === 'light') {
+ document.documentElement.setAttribute('data-theme', resolvedTheme);
+ }
+ var hl = new URLSearchParams(location.search).get('hl');
+ document.documentElement.lang = hl || navigator.language || 'en-US';
+ })();
+ </script>
+ </head>
+
+ <body>
+ <div id="root" style="height: 100%"></div>
+ <!--ACCEPTANCE_LOCAL_DATA-->
+ <script type="module" src="/src/localReport/entry.tsx"></script>
+ </body>
+</html>
diff --git a/apps/workbench/scripts/verify-local-report.mjs b/apps/workbench/scripts/verify-local-report.mjs
new file mode 100644
index 00000000000..f44e03fb6f6
--- /dev/null
+++ b/apps/workbench/scripts/verify-local-report.mjs
@@ -0,0 +1,114 @@
+import assert from 'node:assert/strict';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+import { chromium, expect } from '@playwright/test';
+
+// Build workbench:build:report and the CLI first. Optional args select a built
+// CLI and an installed Chromium executable; no account or server is needed.
+const cli = path.resolve(
+ process.argv[2] ?? fileURLToPath(new URL('../../cli/dist/index.js', import.meta.url)),
+);
+const root = mkdtempSync(path.join(tmpdir(), 'lh-offline-report-'));
+const acceptance = path.join(root, '.acceptances/standalone-offline');
+const round = path.join(acceptance, '20260101-090000-resources');
+const downloads = path.join(root, 'Downloads');
+const run = (...args) =>
+ JSON.parse(
+ execFileSync(process.execPath, [cli, 'acceptance', ...args, '--json'], {
+ cwd: root,
+ encoding: 'utf8',
+ env: { HOME: root, LOBEHUB_ACCEPTANCE_DOWNLOADS: downloads, PATH: process.env.PATH },
+ }),
+ );
+let browser;
+
+try {
+ mkdirSync(path.join(round, 'assets'), { recursive: true });
+ mkdirSync(downloads);
+ writeFileSync(
+ path.join(round, 'assets/resources.md'),
+ [
+ '# Offline resources',
+ '中文与 English. This is a synthetic rendering fixture, not acceptance evidence.',
+ '```js\nconst total = 12.35 * 3;\n```',
+ '$E=mc^2$',
+ '$$\\frac{1}{2}+\\sum_{n=1}^{3}n=6.5$$',
+ '```mermaid\nflowchart LR\n A[Local files] --> B[Offline report]\n```',
+ '![Remote image](https://example.com/image.png)',
+ '![Protocol relative](//example.com/image.png)',
+ '<video src="https://example.com/video.mp4" />',
+ ].join('\n\n'),
+ );
+ writeFileSync(
+ path.join(round, 'result.json'),
+ JSON.stringify({
+ cases: [
+ {
+ evidence: [{ path: 'assets/resources.md' }],
+ id: 'resources',
+ name: 'Read offline',
+ status: 'uncertain',
+ },
+ ],
+ plan: [{ id: 'resources', requiredEvidence: ['markdown'], title: 'Read offline' }],
+ summary: { conclusion: 'Synthetic rendering fixture', verdict: 'uncertain' },
+ title: 'Offline report regression',
+ }),
+ );
+ const rendered = run('run', 'render', round, '--requirement', 'Review without network access');
+ browser = await chromium.launch({
+ ...(process.argv[3] ? { executablePath: process.argv[3] } : { channel: 'chrome' }),
+ headless: true,
+ });
+ const context = await browser.newContext({ acceptDownloads: true, offline: true });
+ const page = await context.newPage();
+ const requests = [];
+ const errors = [];
+ page.on('request', (request) => {
+ if (/^https?:/.test(request.url())) requests.push(request.url());
+ });
+ page.on('websocket', (socket) => requests.push(socket.url()));
+ page.on('pageerror', (error) => errors.push(error.message));
+ await page.goto(`${pathToFileURL(rendered.reportPath).href}?hl=en-US`);
+ await expect(page.getByRole('heading', { name: 'Offline report regression' })).toBeVisible();
+ await page.getByRole('button', { name: 'resources.md', exact: true }).click();
+ await expect(page.locator('.katex')).toHaveCount(2);
+ await page.evaluate(() => document.fonts.ready);
+ await expect(page.locator('svg.lobe-brand-lobe-hub')).toBeVisible();
+ await expect(page.locator('.lobe-mermaid svg')).toBeVisible();
+ await expect(
+ page.getByText('External media is not loaded in local reports.', { exact: false }),
+ ).toHaveCount(3);
+ await expect(page.getByRole('link', { name: 'Protocol relative' })).toHaveAttribute(
+ 'href',
+ 'https://example.com/image.png',
+ );
+ assert.ok(
+ await page.evaluate(() =>
+ [...document.fonts].some((font) => font.family === 'KaTeX_Main' && font.status === 'loaded'),
+ ),
+ );
+ await page.getByRole('button', { name: 'Accept', exact: true }).click();
+ const downloading = page.waitForEvent('download');
+ await page.getByRole('button', { name: 'Save reviews', exact: true }).click();
+ const download = await downloading;
+ await download.saveAs(path.join(downloads, download.suggestedFilename()));
+ const bundle = run('view', acceptance);
+ assert.equal(bundle.checks[0].userReview.action, 'accept');
+ assert.equal(
+ JSON.parse(readFileSync(path.join(acceptance, 'reviews.json'), 'utf8')).events.length,
+ 1,
+ );
+ assert.deepEqual(requests, []);
+ assert.deepEqual(errors, []);
+ console.log(
+ 'PASS: packaged report, offline logo/math/diagram, external media links, saved review JSON',
+ );
+} finally {
+ await browser?.close();
+ rmSync(root, { force: true, recursive: true });
+}
diff --git a/apps/workbench/src/localReport/LocalAcceptanceReport.tsx b/apps/workbench/src/localReport/LocalAcceptanceReport.tsx
new file mode 100644
index 00000000000..8d5478b119e
--- /dev/null
+++ b/apps/workbench/src/localReport/LocalAcceptanceReport.tsx
@@ -0,0 +1,80 @@
+'use client';
+
+import { Flexbox, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import { media } from '@lobehub/ui/stylex/media.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { useTranslation } from 'react-i18next';
+
+import {
+ AcceptanceBundleGate,
+ AcceptanceScope,
+} from '@/features/Acceptance/Viewer/AcceptanceScope';
+import AcceptanceCheckInventory from '@/features/Acceptance/Viewer/Checks/AcceptanceCheckInventory';
+import AcceptanceGoal from '@/features/Acceptance/Viewer/Header/AcceptanceGoal';
+import AcceptanceIdentity from '@/features/Acceptance/Viewer/Header/AcceptanceIdentity';
+import ReadDiscussion from '@/features/Acceptance/Viewer/ReadOnly/Discussion';
+
+import { LocalReviewBar } from './LocalReviewBar';
+
+const styles = stylex.create({
+ body: {
+ flex: '1',
+ minHeight: 0,
+ overflow: 'auto',
+ },
+ header: {
+ backgroundColor: cssVar.colorBgContainer,
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ borderBlockEndStyle: 'solid',
+ borderBlockEndWidth: 1,
+ flex: 'none',
+ minHeight: 48,
+ paddingInline: 12,
+ },
+ page: {
+ backgroundColor: cssVar.colorBgContainer,
+ height: '100dvh',
+ width: '100%',
+ },
+ report: {
+ marginBlock: 0,
+ marginInline: 'auto',
+ maxWidth: 920,
+ paddingBlock: { default: 20, [media.md]: 16 },
+ paddingInline: { default: 24, [media.md]: 12 },
+ width: '100%',
+ },
+});
+
+/**
+ * The offline acceptance page: the workbench detail's reading and reviewing
+ * atoms over the local bundle. Sharing, the comment composer and every other
+ * collaboration surface are simply not mounted — they need LobeHub.
+ */
+export const LocalAcceptanceReport = ({ acceptanceId }: { acceptanceId: string }) => {
+ const { t } = useTranslation('verify');
+
+ return (
+ <AcceptanceScope embedded acceptanceId={acceptanceId}>
+ <Flexbox {...stylex.props(styles.page)}>
+ <Flexbox justify={'center'} {...stylex.props(styles.header)}>
+ <LocalReviewBar />
+ </Flexbox>
+ <div {...stylex.props(styles.body)}>
+ <AcceptanceBundleGate height={'100%'}>
+ <Flexbox gap={16} {...stylex.props(styles.report)}>
+ <AcceptanceIdentity />
+ <AcceptanceGoal />
+ <AcceptanceCheckInventory />
+ <section aria-label={t('acceptance.comments.title')}>
+ <Text as={'h2'}>{t('acceptance.comments.title')}</Text>
+ <ReadDiscussion />
+ </section>
+ </Flexbox>
+ </AcceptanceBundleGate>
+ </div>
+ </Flexbox>
+ </AcceptanceScope>
+ );
+};
diff --git a/apps/workbench/src/localReport/LocalMarkdown.tsx b/apps/workbench/src/localReport/LocalMarkdown.tsx
new file mode 100644
index 00000000000..84d60447a5a
--- /dev/null
+++ b/apps/workbench/src/localReport/LocalMarkdown.tsx
@@ -0,0 +1,65 @@
+import Markdown from '@lobehub/ui/es/Markdown/Markdown';
+import { Image, Video } from '@lobehub/ui/mdx';
+import type { ComponentProps } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { mediaSource } from './mediaSource';
+
+const ExternalMedia = ({
+ alt,
+ source,
+}: {
+ alt?: string;
+ source: ReturnType<typeof mediaSource>;
+}) => {
+ const { t } = useTranslation('verify');
+ return (
+ <span style={{ display: 'block' }}>
+ {t('acceptance.local.externalMedia')}{' '}
+ {source.type === 'external' && (
+ <a
+ href={source.url}
+ rel={'noreferrer'}
+ style={{ display: 'inline-block', maxWidth: '100%', overflowWrap: 'anywhere' }}
+ target={'_blank'}
+ >
+ {alt || t('acceptance.local.openExternalMedia')}
+ </a>
+ )}
+ </span>
+ );
+};
+
+const LocalImage = ({ alt, height, src, title, width }: ComponentProps<'img'>) => {
+ const source = mediaSource(typeof src === 'string' ? src : undefined);
+ return source.type === 'local' ? (
+ <Image alt={alt} height={height} src={source.url} title={title} width={width} />
+ ) : (
+ <ExternalMedia alt={alt} source={source} />
+ );
+};
+
+const LocalVideo = ({ height, poster, src, width }: ComponentProps<'video'>) => {
+ const source = mediaSource(typeof src === 'string' ? src : undefined);
+ return source.type === 'local' ? (
+ <Video
+ height={height}
+ poster={mediaSource(poster).type === 'local' ? poster : undefined}
+ src={source.url}
+ width={width}
+ />
+ ) : (
+ <ExternalMedia source={source} />
+ );
+};
+
+/** Keep the normal renderer, but do not turn authored URLs into network requests. */
+export const LocalMarkdown = ({ components, ...props }: ComponentProps<typeof Markdown>) => (
+ <Markdown
+ {...props}
+ components={Object.assign({}, components, {
+ img: LocalImage,
+ video: LocalVideo,
+ })}
+ />
+);
diff --git a/apps/workbench/src/localReport/LocalReviewBar.tsx b/apps/workbench/src/localReport/LocalReviewBar.tsx
new file mode 100644
index 00000000000..4470982d0d6
--- /dev/null
+++ b/apps/workbench/src/localReport/LocalReviewBar.tsx
@@ -0,0 +1,151 @@
+'use client';
+
+import {
+ Button,
+ copyToClipboard,
+ Flexbox,
+ Popover,
+ Tag,
+ Text,
+ toast,
+ useResponsive,
+} from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { Download, Share2 } from 'lucide-react';
+import { useSyncExternalStore } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { ProductLogo } from '@/components/Branding';
+import { isCustomBranding } from '@/const/version';
+
+import { getLocalReport } from './localReportData';
+
+const styles = stylex.create({
+ command: {
+ backgroundColor: cssVar.colorFillTertiary,
+ borderRadius: cssVar.borderRadius,
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: 12,
+ overflowWrap: 'anywhere',
+ paddingBlock: 6,
+ paddingInline: 8,
+ },
+ divider: {
+ backgroundColor: cssVar.colorBorderSecondary,
+ flex: 'none',
+ height: 16,
+ width: 1,
+ },
+ share: {
+ width: 320,
+ },
+ title: {
+ flex: '1',
+ minWidth: 0,
+ overflow: 'hidden',
+ },
+});
+
+/** `reviews.json` content, downloaded where the CLI looks for it. */
+export const reviewExportFileName = (acceptanceId: string) =>
+ `acceptance-reviews-${acceptanceId}.json`;
+
+const download = (fileName: string, content: string) => {
+ const url = URL.createObjectURL(new Blob([content], { type: 'application/json' }));
+ const anchor = document.createElement('a');
+ anchor.href = url;
+ anchor.download = fileName;
+ document.body.append(anchor);
+ anchor.click();
+ anchor.remove();
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+};
+
+/**
+ * The page's own chrome: where the report lives, how many decisions are not
+ * saved yet, and the one way out to collaboration.
+ *
+ * A file opened from disk cannot write next to itself, so "save" downloads the
+ * review log; the CLI picks the newest download up on its next `view` or
+ * `feedback` and files it beside the rounds.
+ */
+export const LocalReviewBar = () => {
+ const { t } = useTranslation('verify');
+ const { md = true } = useResponsive();
+ const report = getLocalReport();
+ useSyncExternalStore(report.subscribe, report.getVersion);
+ const pending = report.pendingCount();
+ const unsaved = report.unsavedCount();
+ const title = report.bundle().subject.title;
+ const publishCommand = `lh acceptance publish .acceptances/${report.source.acceptance.subjectKey}`;
+
+ const save = () => {
+ const fileName = reviewExportFileName(report.acceptanceId);
+ download(fileName, `${JSON.stringify(report.exportLog(), null, 2)}\n`);
+ report.markExported();
+ toast.success(t('acceptance.local.saved', { file: fileName }));
+ };
+
+ return (
+ <Flexbox horizontal align={'center'} gap={8} width={'100%'}>
+ <ProductLogo size={22} type={isCustomBranding ? 'text' : 'flat'} />
+ <div {...stylex.props(styles.divider)} />
+ <Flexbox horizontal align={'center'} gap={8} {...stylex.props(styles.title)}>
+ {/* A phone has room for the badge; the page heading names the delivery. */}
+ {md && (
+ <Text ellipsis strong style={{ minWidth: 0 }}>
+ {title ?? t('acceptance.local.badge')}
+ </Text>
+ )}
+ <Tag title={t('acceptance.local.badgeHint')}>{t('acceptance.local.badge')}</Tag>
+ </Flexbox>
+ {md && (
+ <Text fontSize={12} type={'secondary'}>
+ {unsaved > 0
+ ? t('acceptance.local.unsaved', { count: unsaved })
+ : pending > 0
+ ? t('acceptance.local.downloaded')
+ : report.source.reviews.length > 0
+ ? t('acceptance.local.allSaved')
+ : t('acceptance.local.noReviews')}
+ </Text>
+ )}
+ <Popover
+ placement={'bottomRight'}
+ trigger={'click'}
+ content={
+ <Flexbox gap={8} {...stylex.props(styles.share)}>
+ <Text strong>{t('acceptance.local.shareTitle')}</Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t('acceptance.local.shareHint')}
+ </Text>
+ <div {...stylex.props(styles.command)}>{publishCommand}</div>
+ <Button
+ size={'small'}
+ onClick={async () => {
+ await copyToClipboard(publishCommand);
+ toast.success(t('acceptance.local.copied'));
+ }}
+ >
+ {t('acceptance.local.copy')}
+ </Button>
+ </Flexbox>
+ }
+ >
+ <Button icon={Share2} title={t('acceptance.local.share')}>
+ {md && t('acceptance.local.share')}
+ </Button>
+ </Popover>
+ <Button
+ disabled={pending === 0}
+ icon={Download}
+ title={t('acceptance.local.save')}
+ type={'primary'}
+ onClick={save}
+ >
+ {md ? t('acceptance.local.save') : unsaved > 0 ? unsaved : undefined}
+ </Button>
+ </Flexbox>
+ );
+};
diff --git a/apps/workbench/src/localReport/entry.tsx b/apps/workbench/src/localReport/entry.tsx
new file mode 100644
index 00000000000..d3757ef6770
--- /dev/null
+++ b/apps/workbench/src/localReport/entry.tsx
@@ -0,0 +1,55 @@
+import '@/styles/stylex.css';
+import 'katex/dist/katex.min.css';
+
+import { Center, Empty } from '@lobehub/ui';
+import dayjs from 'dayjs';
+import zhCn from 'dayjs/locale/zh-cn';
+import { createRoot } from 'react-dom/client';
+import { MemoryRouter } from 'react-router';
+
+import BootErrorBoundary from '@/components/BootErrorBoundary';
+import NextThemeProvider from '@/layout/GlobalProvider/NextThemeProvider';
+import { normalizeDayjsLocale } from '@/utils/dayjsLocale';
+
+import { loadWorkbenchResources } from '../shell/createWorkbenchI18n';
+import WorkbenchShell from '../shell/WorkbenchShell';
+import { LocalAcceptanceReport } from './LocalAcceptanceReport';
+import { getLocalReport } from './localReportData';
+
+const render = async () => {
+ const locale = document.documentElement.lang || navigator.language || 'en-US';
+ const resources = await loadWorkbenchResources(locale);
+ // Relative times render once — nothing re-renders a static page after the
+ // shell's async locale load — so the date locale is set before the first paint.
+ // The locale object, not its name: it registers on this dayjs instance.
+ if (normalizeDayjsLocale(locale) === 'zh-cn') dayjs.locale(zhCn);
+
+ let acceptanceId: string | undefined;
+ let failure: string | undefined;
+ try {
+ acceptanceId = getLocalReport().acceptanceId;
+ } catch (error) {
+ failure = error instanceof Error ? error.message : String(error);
+ }
+
+ createRoot(document.getElementById('root')!).render(
+ <BootErrorBoundary>
+ <NextThemeProvider>
+ <WorkbenchShell enableCustomFonts={false} locale={locale} resources={resources}>
+ {/* The viewer's filters and links read a router; the page has one URL. */}
+ <MemoryRouter>
+ {acceptanceId ? (
+ <LocalAcceptanceReport acceptanceId={acceptanceId} />
+ ) : (
+ <Center height={'100dvh'}>
+ <Empty description={failure} title={'This report could not be opened'} />
+ </Center>
+ )}
+ </MemoryRouter>
+ </WorkbenchShell>
+ </NextThemeProvider>
+ </BootErrorBoundary>,
+ );
+};
+
+void render();
diff --git a/apps/workbench/src/localReport/localEventId.ts b/apps/workbench/src/localReport/localEventId.ts
new file mode 100644
index 00000000000..1b50c6372b4
--- /dev/null
+++ b/apps/workbench/src/localReport/localEventId.ts
@@ -0,0 +1,13 @@
+/**
+ * A random event id. `crypto.randomUUID` exists only in secure contexts, and a
+ * report opened straight from disk may not be one; `getRandomValues` is
+ * available everywhere.
+ */
+export const localEventId = () => {
+ if (typeof crypto.randomUUID === 'function') return crypto.randomUUID();
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
+ bytes[6] = (bytes[6]! & 0x0f) | 0x40;
+ bytes[8] = (bytes[8]! & 0x3f) | 0x80;
+ const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, '0')).join('');
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
+};
diff --git a/apps/workbench/src/localReport/localReportData.test.ts b/apps/workbench/src/localReport/localReportData.test.ts
new file mode 100644
index 00000000000..548d5793321
--- /dev/null
+++ b/apps/workbench/src/localReport/localReportData.test.ts
@@ -0,0 +1,114 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The offline report keeps the reader's decisions in the browser until they are
+ * saved, and forgets each one only once a re-rendered page carries it.
+ */
+import type {
+ LocalAcceptanceSource,
+ LocalReviewEvent,
+} from '@lobechat/utils/verify/localAcceptance';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const source = (reviews: LocalReviewEvent[] = []): LocalAcceptanceSource => ({
+ acceptance: {
+ createdAt: '2026-01-01T00:00:00.000Z',
+ id: 'acc-1',
+ requirement: 'Rename keeps the title',
+ subjectKey: 'standalone-rename',
+ },
+ format: 1,
+ generatedAt: '2026-01-01T00:00:00.000Z',
+ reviews,
+ rounds: [
+ {
+ dir: '20260101-000000-first',
+ evidence: [],
+ proposal: null,
+ report: null,
+ results: [
+ {
+ checkItemId: 'rename',
+ checkItemIndex: 0,
+ checkItemTitle: 'Rename keeps the title',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ id: 'result-1',
+ metadata: null,
+ required: true,
+ suggestion: null,
+ toulmin: null,
+ verdict: 'passed',
+ },
+ ],
+ run: {
+ context: null,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ goal: null,
+ id: 'run-1',
+ metadata: null,
+ plan: null,
+ roundIndex: 1,
+ scenario: 'coding',
+ title: 'Rename',
+ },
+ },
+ ],
+});
+
+const accept: LocalReviewEvent = {
+ action: 'accept',
+ createdAt: '2026-01-01T01:00:00.000Z',
+ id: 'event-1',
+ kind: 'checks',
+ roundIndex: 1,
+ targets: [{ checkId: 'rename', resultId: 'result-1' }],
+};
+
+/** A fresh page load: new document data, new module instance, same localStorage. */
+const openPage = async (data: LocalAcceptanceSource) => {
+ document.body.innerHTML = `<script id="acceptance-local-data" type="application/json">${JSON.stringify(data)}</script>`;
+ vi.resetModules();
+ const { getLocalReport } = await import('./localReportData');
+ return getLocalReport();
+};
+
+describe('local report data', () => {
+ beforeEach(() => localStorage.clear());
+ afterEach(() => {
+ document.body.innerHTML = '';
+ });
+
+ it('holds a decision across reloads until it is saved', async () => {
+ const page = await openPage(source());
+ page.append(accept);
+ expect(page.bundle().checks[0]!.userReview).toMatchObject({ action: 'accept' });
+ expect(page.unsavedCount()).toBe(1);
+
+ page.markExported();
+ expect(page.unsavedCount()).toBe(0);
+ expect(page.pendingCount()).toBe(1);
+ expect(page.exportLog()).toEqual({ acceptanceId: 'acc-1', events: [accept], format: 1 });
+
+ const reloaded = await openPage(source());
+ expect(reloaded.pendingCount()).toBe(1);
+ expect(reloaded.unsavedCount()).toBe(0);
+ expect(reloaded.bundle().checks[0]!.userReview).toMatchObject({ action: 'accept' });
+ });
+
+ it('forgets a decision once the re-rendered page carries it', async () => {
+ const page = await openPage(source());
+ page.append(accept);
+
+ const rerendered = await openPage(source([accept]));
+ expect(rerendered.pendingCount()).toBe(0);
+ expect(rerendered.exportLog().events).toEqual([accept]);
+ expect(rerendered.bundle().checks[0]!.userReview).toMatchObject({ action: 'accept' });
+ });
+
+ it('refuses a page without acceptance data', async () => {
+ document.body.innerHTML = '';
+ vi.resetModules();
+ const { getLocalReport } = await import('./localReportData');
+ expect(() => getLocalReport()).toThrow('no acceptance data');
+ });
+});
diff --git a/apps/workbench/src/localReport/localReportData.ts b/apps/workbench/src/localReport/localReportData.ts
new file mode 100644
index 00000000000..543783d278e
--- /dev/null
+++ b/apps/workbench/src/localReport/localReportData.ts
@@ -0,0 +1,120 @@
+import type {
+ LocalAcceptanceSource,
+ LocalReviewEvent,
+ LocalReviewLog,
+} from '@lobechat/utils/verify/localAcceptance';
+import {
+ assembleLocalAcceptance,
+ LOCAL_ACCEPTANCE_FORMAT,
+ localAcceptanceComments,
+ mergeLocalReviewEvents,
+} from '@lobechat/utils/verify/localAcceptance';
+
+/** The `<script type="application/json">` the CLI writes the acceptance into. */
+export const LOCAL_DATA_ELEMENT_ID = 'acceptance-local-data';
+
+/**
+ * The page has no server to write to: a decision lands in the browser first
+ * and reaches `reviews.json` when the reviewer saves it (the CLI reads the
+ * saved file on its next `view` / `feedback`). Until then it lives here, so a
+ * reload keeps it.
+ */
+const pendingKey = (acceptanceId: string) => `lobehub-acceptance-local:${acceptanceId}:reviews`;
+/** Pending decisions already downloaded in a saved review log. */
+const exportedKey = (acceptanceId: string) => `lobehub-acceptance-local:${acceptanceId}:exported`;
+
+const readSource = (): LocalAcceptanceSource => {
+ const element = document.getElementById(LOCAL_DATA_ELEMENT_ID);
+ if (!element?.textContent) throw new Error('This report has no acceptance data.');
+ const source = JSON.parse(element.textContent) as LocalAcceptanceSource;
+ if (source.format !== LOCAL_ACCEPTANCE_FORMAT)
+ throw new Error(`Unsupported local acceptance format: ${String(source.format)}`);
+ return source;
+};
+
+const readList = <T>(key: string): T[] => {
+ try {
+ const raw = window.localStorage.getItem(key);
+ const value = raw ? (JSON.parse(raw) as unknown) : [];
+ return Array.isArray(value) ? (value as T[]) : [];
+ } catch {
+ return [];
+ }
+};
+
+const writeList = (key: string, value: unknown[]) => {
+ try {
+ if (value.length === 0) window.localStorage.removeItem(key);
+ else window.localStorage.setItem(key, JSON.stringify(value));
+ } catch {
+ // Private mode or a full quota: the decision still holds for this visit.
+ }
+};
+
+const createLocalReport = () => {
+ const source = readSource();
+ const id = source.acceptance.id;
+ // Decisions the report already carries were saved and read back by the CLI.
+ const saved = new Set(source.reviews.map((event) => event.id));
+ let pending = readList<LocalReviewEvent>(pendingKey(id)).filter((event) => !saved.has(event.id));
+ let exported = new Set(
+ readList<string>(exportedKey(id)).filter((eventId) => !saved.has(eventId)),
+ );
+ writeList(pendingKey(id), pending);
+ writeList(exportedKey(id), [...exported]);
+ let version = 0;
+ let cache: { bundle: ReturnType<typeof assembleLocalAcceptance>; version: number } | undefined;
+ const listeners = new Set<() => void>();
+
+ const events = () => mergeLocalReviewEvents(source.reviews, pending);
+ const notify = () => {
+ version++;
+ for (const listener of listeners) listener();
+ };
+
+ return {
+ acceptanceId: id,
+ append: (event: LocalReviewEvent) => {
+ pending = [...pending, event];
+ writeList(pendingKey(id), pending);
+ notify();
+ },
+ bundle: () => {
+ if (cache?.version !== version)
+ cache = { bundle: assembleLocalAcceptance({ ...source, reviews: events() }), version };
+ return cache.bundle;
+ },
+ comments: () => localAcceptanceComments(source),
+ /** Everything decided on this acceptance, saved or not — what `reviews.json` holds. */
+ exportLog: (): LocalReviewLog => ({
+ acceptanceId: id,
+ events: events(),
+ format: LOCAL_ACCEPTANCE_FORMAT,
+ }),
+ getVersion: () => version,
+ /** Record that every pending decision is in a downloaded review log. */
+ markExported: () => {
+ exported = new Set(pending.map((event) => event.id));
+ writeList(exportedKey(id), [...exported]);
+ notify();
+ },
+ pendingCount: () => pending.length,
+ /** Pending decisions not in any downloaded review log yet. */
+ unsavedCount: () => pending.filter((event) => !exported.has(event.id)).length,
+ source,
+ subscribe: (listener: () => void) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ };
+};
+
+export type LocalReport = ReturnType<typeof createLocalReport>;
+
+let instance: LocalReport | undefined;
+
+/** The acceptance this page was rendered with, plus the reviewer's decisions so far. */
+export const getLocalReport = (): LocalReport => {
+ instance ??= createLocalReport();
+ return instance;
+};
diff --git a/apps/workbench/src/localReport/mediaSource.test.ts b/apps/workbench/src/localReport/mediaSource.test.ts
new file mode 100644
index 00000000000..f442b651f45
--- /dev/null
+++ b/apps/workbench/src/localReport/mediaSource.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from 'vitest';
+
+import { mediaSource } from './mediaSource';
+
+describe('local report media', () => {
+ it.each([
+ 'round/assets/screen%20one.png',
+ './截图.png',
+ '../assets/clip.mp4',
+ 'data:image/png;base64,AA==',
+ 'blob:null/123',
+ ])('keeps an adjacent or embedded asset: %s', (src) =>
+ expect(mediaSource(src)).toEqual({ type: 'local', url: src }),
+ );
+
+ it.each([
+ ['https://example.com/image.png', 'https://example.com/image.png'],
+ ['//example.com/image.png', 'https://example.com/image.png'],
+ ['\\\\example.com/video.mp4', 'https://example.com/video.mp4'],
+ [' ht\ntps://example.com/image.png ', 'https://example.com/image.png'],
+ ['https://local-report.invalid/image.png', 'https://local-report.invalid/image.png'],
+ ])('makes a remote source explicit, never loadable: %s', (src, url) => {
+ expect(mediaSource(src)).toEqual({ type: 'external', url });
+ });
+
+ it.each([
+ undefined,
+ '',
+ ' ',
+ 'javascript:alert(1)',
+ 'file:///etc/passwd',
+ 'file://host/share/image.png',
+ '/absolute/image.png',
+ 'https://[invalid',
+ ])('does not turn missing, invalid or executable sources into links: %s', (src) =>
+ expect(mediaSource(src)).toEqual({ type: 'unavailable' }),
+ );
+});
diff --git a/apps/workbench/src/localReport/mediaSource.ts b/apps/workbench/src/localReport/mediaSource.ts
new file mode 100644
index 00000000000..d5d87314d09
--- /dev/null
+++ b/apps/workbench/src/localReport/mediaSource.ts
@@ -0,0 +1,26 @@
+type MediaSource = { type: 'external' | 'local'; url: string } | { type: 'unavailable' };
+
+/** Local reports never fetch remote media, even when the browser is online. */
+export const mediaSource = (src?: string): MediaSource => {
+ if (!src?.trim()) return { type: 'unavailable' };
+ // URL parsers normalize backslashes and control characters; check the parsed
+ // destination rather than trusting a prefix such as "./" or "https:".
+ try {
+ const url = new URL(src, 'https://local-report.invalid/');
+ if (url.protocol === 'data:' || url.protocol === 'blob:') return { type: 'local', url: src };
+ if (/^https?:$/.test(url.protocol)) {
+ // eslint-disable-next-line no-control-regex
+ const hasControlCharacters = /[\u0000-\u001F\u007F]/.test(src);
+ const relative = !/^[a-z][\w+.-]*:|^[\\/]/i.test(src.trim()) && !hasControlCharacters;
+ if (relative && url.origin === 'https://local-report.invalid')
+ return { type: 'local', url: src };
+ // An absolute disk path cannot travel with the report. Do not invent a
+ // link to the synthetic parsing origin for it.
+ if (/^[\\/](?![\\/])/.test(src.trim())) return { type: 'unavailable' };
+ return { type: 'external', url: url.href };
+ }
+ } catch {
+ // Invalid and executable URLs are not made into links.
+ }
+ return { type: 'unavailable' };
+};
diff --git a/apps/workbench/src/localReport/stubs/acceptanceCommentService.ts b/apps/workbench/src/localReport/stubs/acceptanceCommentService.ts
new file mode 100644
index 00000000000..d24d147050f
--- /dev/null
+++ b/apps/workbench/src/localReport/stubs/acceptanceCommentService.ts
@@ -0,0 +1,21 @@
+import { getLocalReport } from '../localReportData';
+import { needsPublishedAcceptance } from './unavailable';
+
+const commentsNeedSharing = async (): Promise<never> => {
+ throw needsPublishedAcceptance('Comments');
+};
+
+/**
+ * `@/services/acceptanceComment` for the offline report. The discussion holds
+ * each round's proposal; talking to other people is what publishing is for, so
+ * the list reports `canComment: false` and every write refuses.
+ */
+export const acceptanceCommentService = {
+ answerAccessRequest: commentsNeedSharing,
+ create: commentsNeedSharing,
+ delete: commentsNeedSharing,
+ list: async (_acceptanceId: string) => getLocalReport().comments(),
+ react: commentsNeedSharing,
+ requestAccess: commentsNeedSharing,
+ setResolved: commentsNeedSharing,
+};
diff --git a/apps/workbench/src/localReport/stubs/loadI18nNamespaceModule.ts b/apps/workbench/src/localReport/stubs/loadI18nNamespaceModule.ts
new file mode 100644
index 00000000000..6c45818e5b2
--- /dev/null
+++ b/apps/workbench/src/localReport/stubs/loadI18nNamespaceModule.ts
@@ -0,0 +1,50 @@
+type NamespaceModule = { default: Record<string, unknown> };
+type NamespaceLoaderMap = Record<string, () => Promise<NamespaceModule>>;
+
+// The offline report is one file: every namespace it renders is bundled, in
+// the default language plus Simplified Chinese. Other locales fall back to
+// English rather than adding a megabyte per language to every report. The
+// i18n guard in vite.config.report.mts fails the build when the page graph
+// asks for a namespace missing here; keep both lists in sync.
+const defaultLoaders = import.meta.glob([
+ '../../../../../packages/locales/src/default/chat.ts',
+ '../../../../../packages/locales/src/default/common.ts',
+ '../../../../../packages/locales/src/default/components.ts',
+ '../../../../../packages/locales/src/default/error.ts',
+ '../../../../../packages/locales/src/default/file.ts',
+ '../../../../../packages/locales/src/default/verify.ts',
+]) as NamespaceLoaderMap;
+const localeLoaders = import.meta.glob([
+ '../../../../../locales/zh-CN/chat.json',
+ '../../../../../locales/zh-CN/common.json',
+ '../../../../../locales/zh-CN/components.json',
+ '../../../../../locales/zh-CN/error.json',
+ '../../../../../locales/zh-CN/file.json',
+ '../../../../../locales/zh-CN/verify.json',
+]) as NamespaceLoaderMap;
+
+export interface LoadI18nNamespaceModuleParams {
+ defaultLang: string;
+ lng: string;
+ normalizeLocale: (locale?: string) => string;
+ ns: string;
+}
+
+export const loadI18nNamespaceModule = async (
+ params: LoadI18nNamespaceModuleParams,
+): Promise<NamespaceModule> => {
+ const { defaultLang, normalizeLocale, lng, ns } = params;
+
+ const loadDefault = defaultLoaders[`../../../../../packages/locales/src/default/${ns}.ts`];
+ // An unbundled namespace renders its keys instead of failing the page.
+ if (!loadDefault) return { default: {} };
+
+ if (lng !== defaultLang) {
+ const loadLocale = localeLoaders[`../../../../../locales/${normalizeLocale(lng)}/${ns}.json`];
+ if (loadLocale) return loadLocale();
+ }
+
+ return loadDefault();
+};
+
+export const loadI18nNamespaceModuleWithFallback = loadI18nNamespaceModule;
diff --git a/apps/workbench/src/localReport/stubs/unavailable.ts b/apps/workbench/src/localReport/stubs/unavailable.ts
new file mode 100644
index 00000000000..72f24d0dbf0
--- /dev/null
+++ b/apps/workbench/src/localReport/stubs/unavailable.ts
@@ -0,0 +1,5 @@
+/** What a local report cannot do: anything that needs another person or a server. */
+export const needsPublishedAcceptance = (what: string) =>
+ new Error(
+ `${what} needs a shared acceptance. Publish this report to LobeHub with \`lh acceptance publish\`.`,
+ );
diff --git a/apps/workbench/src/localReport/stubs/userStore.ts b/apps/workbench/src/localReport/stubs/userStore.ts
new file mode 100644
index 00000000000..8f902cd18e3
--- /dev/null
+++ b/apps/workbench/src/localReport/stubs/userStore.ts
@@ -0,0 +1,22 @@
+// The person reading a local report is its only reviewer. Their decisions are
+// stamped `decidedBy: 'local'` (see `localAcceptance.ts`), so the same id here
+// lets the viewer label them as the reader's own.
+const LOCAL_USER = { fullName: '', id: 'local', username: '' };
+
+const emptyState = {
+ isLoaded: true,
+ isSignedIn: false,
+ user: LOCAL_USER,
+};
+
+/**
+ * `@/store/user` for the offline report. The real store boots the whole app
+ * (agents, chat, model runtimes); the viewer only asks who is reading.
+ */
+export const useUserStore = <T = unknown>(selector?: (state: typeof emptyState) => T): T =>
+ selector ? selector(emptyState) : (emptyState as T);
+
+useUserStore.getState = () => emptyState;
+useUserStore.subscribe = () => () => {};
+
+export const getUserStoreState = () => emptyState;
diff --git a/apps/workbench/src/localReport/stubs/verifyService.ts b/apps/workbench/src/localReport/stubs/verifyService.ts
new file mode 100644
index 00000000000..d3157cb60fe
--- /dev/null
+++ b/apps/workbench/src/localReport/stubs/verifyService.ts
@@ -0,0 +1,66 @@
+import type { AcceptanceCheckReviewAction, AcceptanceReviewAnnotation } from '@lobechat/types';
+import { localReviewTargets } from '@lobechat/utils/verify/localAcceptance';
+
+import { localEventId } from '../localEventId';
+import { getLocalReport } from '../localReportData';
+import { needsPublishedAcceptance } from './unavailable';
+
+const currentRoundIndex = () => getLocalReport().bundle().rounds.at(-1)?.run.roundIndex ?? 0;
+
+const getAcceptanceBundle = async (_id: string) => getLocalReport().bundle();
+
+const reviewChecks = async (input: {
+ action: AcceptanceCheckReviewAction;
+ annotations?: AcceptanceReviewAnnotation[];
+ checkItemIds: string[];
+ comment?: string;
+ fileIds?: string[];
+}) => {
+ if (input.fileIds?.length) throw needsPublishedAcceptance('Attaching files');
+ const report = getLocalReport();
+ const targets = localReviewTargets(report.bundle(), input.checkItemIds);
+ report.append({
+ action: input.action,
+ ...(input.annotations?.length ? { annotations: input.annotations } : {}),
+ ...(input.comment?.trim() ? { comment: input.comment.trim() } : {}),
+ createdAt: new Date().toISOString(),
+ id: localEventId(),
+ kind: 'checks',
+ roundIndex: currentRoundIndex(),
+ targets,
+ });
+ return { resultIds: targets.map((target) => target.resultId) };
+};
+
+const addGroupFeedback = async (input: {
+ category: string;
+ comment: string;
+ fileIds?: string[];
+}) => {
+ if (input.fileIds?.length) throw needsPublishedAcceptance('Attaching files');
+ const entry = {
+ category: input.category,
+ comment: input.comment.trim(),
+ createdAt: new Date().toISOString(),
+ };
+ const roundIndex = currentRoundIndex();
+ getLocalReport().append({ ...entry, id: localEventId(), kind: 'group', roundIndex });
+ return { entry: { ...entry, roundIndex }, success: true };
+};
+
+const adjudicateProposal = async (): Promise<never> => {
+ throw needsPublishedAcceptance('Review proposals');
+};
+
+/**
+ * `@/services/verify` for the offline report: the bundle is the local one, and
+ * a review is appended to the page's local review log instead of a server
+ * mutation. The write rules are the server's — the same targets, the same
+ * refusals — so the page answers a click exactly as the hosted one would.
+ */
+export const verifyService = {
+ addGroupFeedback,
+ adjudicateProposal,
+ getAcceptanceBundle,
+ reviewChecks,
+};
diff --git a/apps/workbench/src/localReport/stubs/verifyStore.ts b/apps/workbench/src/localReport/stubs/verifyStore.ts
new file mode 100644
index 00000000000..7c2eb31898b
--- /dev/null
+++ b/apps/workbench/src/localReport/stubs/verifyStore.ts
@@ -0,0 +1,67 @@
+import { useSyncExternalStore } from 'react';
+
+import type { AcceptanceBundle } from '@/services/verify';
+
+import { getLocalReport } from '../localReportData';
+
+/**
+ * The page data, typed as the hosted bundle. This assignment is the contract
+ * check between the local assembler and the viewer: when the server's bundle
+ * gains a field the viewer reads, the local one has to produce it too.
+ */
+const readBundleMap = (): Record<string, AcceptanceBundle> => {
+ try {
+ const report = getLocalReport();
+ const bundle: AcceptanceBundle = report.bundle();
+ return { [report.acceptanceId]: bundle };
+ } catch {
+ // The entry renders the reason; the viewer just sees nothing to show.
+ return {};
+ }
+};
+
+const sync = {
+ error: undefined,
+ isHydrated: true,
+ isValidating: false,
+ revalidate: async () => undefined,
+};
+
+const listeners = new Set<() => void>();
+const subscribe = (listener: () => void) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+};
+
+const useFetchAcceptanceBundle = (
+ _acceptanceId?: string | null,
+ _options?: { enabled?: boolean; refreshInterval?: number },
+) => sync;
+
+const refreshAcceptanceBundle = async (_acceptanceId: string) => {
+ state = { ...state, acceptanceBundleMap: readBundleMap() };
+ for (const listener of listeners) listener();
+};
+
+const emptyState = {
+ acceptanceBundleMap: readBundleMap(),
+ refreshAcceptanceBundle,
+ useFetchAcceptanceBundle,
+};
+
+let state = emptyState;
+
+/**
+ * `@/store/verify` for the offline report: the bundle map holds the one local
+ * acceptance, recomputed whenever the reviewer records a decision.
+ */
+export const useVerifyStore = <T>(selector: (current: typeof emptyState) => T): T =>
+ useSyncExternalStore(subscribe, () => selector(state));
+
+useVerifyStore.getState = () => state;
+
+try {
+ getLocalReport().subscribe(() => void refreshAcceptanceBundle(getLocalReport().acceptanceId));
+} catch {
+ // No data: nothing will change either.
+}
diff --git a/apps/workbench/src/shell/WorkbenchShell.tsx b/apps/workbench/src/shell/WorkbenchShell.tsx
index d1573d85d83..28f48a47369 100644
--- a/apps/workbench/src/shell/WorkbenchShell.tsx
+++ b/apps/workbench/src/shell/WorkbenchShell.tsx
@@ -7,25 +7,28 @@ import WorkbenchLocale from './WorkbenchLocale';
import WorkbenchTheme from './WorkbenchTheme';
interface WorkbenchShellProps extends PropsWithChildren {
+ enableCustomFonts?: boolean;
locale?: string;
resources?: Record<string, unknown>;
}
-const WorkbenchShell = memo<WorkbenchShellProps>(({ children, resources, locale: localeProp }) => {
- const locale =
- localeProp ??
- (typeof document === 'undefined' ? 'en-US' : document.documentElement.lang || 'en-US');
+const WorkbenchShell = memo<WorkbenchShellProps>(
+ ({ children, enableCustomFonts, resources, locale: localeProp }) => {
+ const locale =
+ localeProp ??
+ (typeof document === 'undefined' ? 'en-US' : document.documentElement.lang || 'en-US');
- return (
- <WorkbenchLocale defaultLang={locale} resources={resources}>
- <WorkbenchTheme>
- <TooltipGroup layoutAnimation={false}>{children}</TooltipGroup>
- <ModalHost />
- <ToastHost />
- </WorkbenchTheme>
- </WorkbenchLocale>
- );
-});
+ return (
+ <WorkbenchLocale defaultLang={locale} resources={resources}>
+ <WorkbenchTheme enableCustomFonts={enableCustomFonts}>
+ <TooltipGroup layoutAnimation={false}>{children}</TooltipGroup>
+ <ModalHost />
+ <ToastHost />
+ </WorkbenchTheme>
+ </WorkbenchLocale>
+ );
+ },
+);
WorkbenchShell.displayName = 'WorkbenchShell';
diff --git a/apps/workbench/src/shell/WorkbenchTheme.tsx b/apps/workbench/src/shell/WorkbenchTheme.tsx
index 26429ec7f3c..f374b14b80d 100644
--- a/apps/workbench/src/shell/WorkbenchTheme.tsx
+++ b/apps/workbench/src/shell/WorkbenchTheme.tsx
@@ -12,9 +12,17 @@ import { memo, type PropsWithChildren } from 'react';
import Image from '@/libs/next/Image';
import Link from '@/libs/next/Link';
-const WorkbenchTheme = memo<PropsWithChildren>(({ children }) => {
+interface WorkbenchThemeProps extends PropsWithChildren {
+ enableCustomFonts?: boolean;
+}
+
+const WorkbenchTheme = memo<WorkbenchThemeProps>(({ children, enableCustomFonts }) => {
return (
- <ConfigProvider config={{ aAs: Link, imgAs: Image, imgUnoptimized: true }} motion={m}>
+ <ConfigProvider
+ config={{ aAs: Link, imgAs: Image, imgUnoptimized: true }}
+ enableCustomFonts={enableCustomFonts}
+ motion={m}
+ >
<div
className={'workbench-layout'}
style={{ height: '100%', minHeight: '100dvh', width: '100%' }}
diff --git a/apps/workbench/tsconfig.json b/apps/workbench/tsconfig.json
index 7c7c06579da..ccc3a743bc1 100644
--- a/apps/workbench/tsconfig.json
+++ b/apps/workbench/tsconfig.json
@@ -13,6 +13,7 @@
"workers/**/*.ts",
"vite.config.ts",
"vite.config.rr.mts",
+ "vite.config.report.mts",
"react-router.config.ts",
"../../src/types/global.d.ts"
]
diff --git a/apps/workbench/vite.config.report.mts b/apps/workbench/vite.config.report.mts
new file mode 100644
index 00000000000..89b5b7315ea
--- /dev/null
+++ b/apps/workbench/vite.config.report.mts
@@ -0,0 +1,294 @@
+import { readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { createRequire } from 'node:module';
+import path from 'node:path';
+
+import type { Plugin, PluginOption } from 'vite';
+import { defineConfig } from 'vite';
+import tsconfigPaths from 'vite-tsconfig-paths';
+
+import {
+ sharedRendererDefine,
+ sharedRendererPlugins,
+} from '../../plugins/vite/sharedRendererConfig';
+import { isShikiSource } from './app/stubs/shikiSource';
+import { reportStubSurfaceGaps } from './app/stubs/surface';
+
+/**
+ * The offline acceptance report: one self-contained HTML file the CLI fills
+ * with a local acceptance (`lh acceptance run render`). Opened from disk, a
+ * page may not load module scripts or fetch siblings, so every script, style
+ * and font is inlined and nothing is loaded at runtime — no CDN, no API.
+ *
+ * Output: dist-report/acceptance-report.html, copied into the CLI package.
+ */
+
+const repoRoot = path.resolve(import.meta.dirname, '../..');
+const stubDir = path.resolve(import.meta.dirname, 'src/localReport/stubs');
+const appStubDir = path.resolve(import.meta.dirname, 'app/stubs');
+// Use the exact KaTeX installed for the Markdown renderer, not a CDN version.
+const uiRequire = createRequire(createRequire(import.meta.url).resolve('@lobehub/ui'));
+
+const stubs: Record<string, string> = {
+ '@/libs/trpc/client': path.resolve(appStubDir, 'trpcClient.ts'),
+ '@/services/acceptanceComment': path.resolve(stubDir, 'acceptanceCommentService.ts'),
+ '@/services/global': path.resolve(appStubDir, 'globalService.ts'),
+ '@/services/verify': path.resolve(stubDir, 'verifyService.ts'),
+ '@/store/electron': path.resolve(appStubDir, 'electronStore.ts'),
+ '@/store/file': path.resolve(appStubDir, 'fileStore.ts'),
+ '@/store/user': path.resolve(stubDir, 'userStore.ts'),
+ '@/store/verify': path.resolve(stubDir, 'verifyStore.ts'),
+ '@/utils/i18n/loadI18nNamespaceModule': path.resolve(stubDir, 'loadI18nNamespaceModule.ts'),
+};
+const shikiStub = path.resolve(appStubDir, 'shiki.ts');
+
+/** GitHub alert icons in Markdown: five glyphs out of a 1 MB icon set. */
+const OCTICONS = '\0acceptance-report:octicons';
+const ALERT_ICONS = ['alert', 'info', 'light-bulb', 'report', 'stop'];
+
+/** The reaction picker's emoji set: comments are a shared-acceptance feature. */
+const EMOJI_DATA = '\0acceptance-report:emoji-data';
+
+/** Only this host replaces Markdown's remote media with explicit links. */
+const LOCAL_MARKDOWN = '\0acceptance-report:markdown';
+const localMarkdown = path.resolve(import.meta.dirname, 'src/localReport/LocalMarkdown.tsx');
+
+const localReportStubs = (): Plugin => ({
+ enforce: 'pre',
+ load(id) {
+ if (id === LOCAL_MARKDOWN)
+ return `export { LocalMarkdown as default } from ${JSON.stringify(localMarkdown)};`;
+ if (id === EMOJI_DATA)
+ return 'export default { aliases: {}, categories: [], emojis: {}, natives: {}, sheet: { cols: 0, rows: 0 } };';
+ if (!id.startsWith(OCTICONS)) return;
+ const entry = id.slice(OCTICONS.length + 1);
+ const data = JSON.parse(
+ readFileSync(path.resolve(path.dirname(entry), 'build/data.json'), 'utf8'),
+ ) as Record<string, { heights: Record<string, { path: string }> }>;
+ const icons = Object.fromEntries(
+ ALERT_ICONS.map((name) => [
+ name,
+ { heights: { 16: { path: data[name]!.heights[16]!.path } } },
+ ]),
+ );
+ return `export default ${JSON.stringify(icons)};`;
+ },
+ name: 'acceptance-report-stubs',
+ async resolveId(source, importer, options) {
+ if (stubs[source]) return stubs[source];
+ if (source === 'katex/dist/katex.min.css') return uiRequire.resolve(source);
+ // lobeUiImports resolves the root barrel's Markdown export to this entry.
+ // The wrapper itself must still reach the original component.
+ if (source === '@lobehub/ui/es/Markdown/Markdown' && importer !== localMarkdown)
+ return LOCAL_MARKDOWN;
+ if (source === '@emoji-mart/data') return EMOJI_DATA;
+ if (source === '@primer/octicons') {
+ const real = await this.resolve(source, importer, { ...options, skipSelf: true });
+ return real && `${OCTICONS}?${real.id}`;
+ }
+ // Grammars, themes and the wasm engine are megabytes; code renders plain.
+ if (isShikiSource(source, importer)) return shikiStub;
+ },
+});
+
+/** Fail the build when the page graph uses a stub member the stub does not implement. */
+const stubSurfaceGuard = (): Plugin => ({
+ apply: 'build',
+ buildEnd() {
+ if (!this.getModuleInfo(localMarkdown))
+ this.error('The local report must use LocalMarkdown to keep external media offline.');
+ const stubEntries = Object.entries(stubs).map(([specifier, file]) => ({
+ source: readFileSync(file, 'utf8'),
+ specifier,
+ }));
+ const files: Array<{ rel: string; source: string }> = [];
+ for (const id of this.getModuleIds()) {
+ if (!id.startsWith(repoRoot) || id.includes('/node_modules/') || id.includes('\0')) continue;
+ const file = id.split('?')[0]!;
+ if (!/\.[cm]?[jt]sx?$/.test(file)) continue;
+ const rel = path.relative(repoRoot, file);
+ if (
+ rel.startsWith('apps/workbench/app/stubs/') ||
+ rel.startsWith('apps/workbench/src/localReport/stubs/')
+ )
+ continue;
+ try {
+ files.push({ rel, source: readFileSync(file, 'utf8') });
+ } catch {
+ continue;
+ }
+ }
+ const lines = reportStubSurfaceGaps(files, stubEntries);
+ if (lines.length > 0) {
+ this.error(
+ `Local report stub is missing APIs used by the module graph:\n${lines.join('\n')}\n` +
+ `Add the member to the matching stub, or keep the importer off the report graph.`,
+ );
+ }
+ },
+ name: 'acceptance-report-stub-surface-guard',
+});
+
+/** `REPORT_TRACE_MODULE=<path fragment>` prints who pulls a module into the report. */
+const moduleTrace = (needle: string): Plugin => ({
+ buildEnd() {
+ for (const target of [...this.getModuleIds()].filter((id) => id.includes(needle)).slice(0, 2)) {
+ const parent = new Map<string, string | null>([[target, null]]);
+ const queue = [target];
+ let found: string | null = null;
+ while (queue.length > 0 && !found) {
+ const current = queue.shift()!;
+ const info = this.getModuleInfo(current);
+ for (const importer of [...(info?.importers ?? []), ...(info?.dynamicImporters ?? [])]) {
+ if (parent.has(importer)) continue;
+ parent.set(importer, current);
+ queue.push(importer);
+ if (importer.includes('src/localReport/entry')) {
+ found = importer;
+ break;
+ }
+ }
+ }
+ const chain: string[] = [];
+ for (let cursor = found; cursor; cursor = parent.get(cursor) ?? null) chain.push(cursor);
+ console.info(
+ `\n=== module trace: ${target}\n${chain.join('\n -> ') || '(no importer path)'}`,
+ );
+ }
+ },
+ name: 'acceptance-report-module-trace',
+});
+
+/** `</script` or `<!--` inside an inline script would end or confuse the element. */
+const escapeInlineScript = (code: string) =>
+ code.replaceAll('</script', String.raw`<\/script`).replaceAll('<!--', String.raw`<\!--`);
+
+/**
+ * Inline every script and stylesheet into the HTML, leaving one file. Runs once
+ * the whole bundle is on disk, so CSS appended by later `generateBundle` hooks
+ * (StyleX) is included too.
+ */
+const singleFile = (outDir: string): Plugin => {
+ let written = false;
+ return {
+ apply: 'build',
+ closeBundle() {
+ // Do not mask a compilation error with a missing-output error.
+ if (!written) return;
+ const htmlPath = path.join(outDir, 'report.html');
+ let html = readFileSync(htmlPath, 'utf8');
+ const inlined = new Set<string>([htmlPath]);
+ const read = (url: string) => {
+ const file = path.resolve(outDir, url);
+ inlined.add(file);
+ return readFileSync(file, 'utf8');
+ };
+
+ html = html.replaceAll(
+ /<script type="module" crossorigin src="([^"]+)"><\/script>/g,
+ (_tag, url: string) => `<script type="module">${escapeInlineScript(read(url))}</script>`,
+ );
+ html = html.replaceAll(
+ /<link rel="stylesheet" crossorigin href="([^"]+)">/g,
+ (_tag, url: string) => `<style>${read(url)}</style>`,
+ );
+ const files = readdirSync(outDir, { recursive: true, withFileTypes: true })
+ .filter((entry) => entry.isFile())
+ .map((entry) => path.join(entry.parentPath, entry.name));
+ const unlinkedCss = files.filter((file) => file.endsWith('.css') && !inlined.has(file));
+ if (unlinkedCss.length > 0) {
+ const css = unlinkedCss.map((file) => read(path.relative(outDir, file))).join('\n');
+ html = html.replace('</head>', () => `<style>${css}</style></head>`);
+ }
+
+ const leftovers = files.filter((file) => !inlined.has(file));
+ if (leftovers.length > 0)
+ throw new Error(
+ `The report must be one file; not inlined: ${leftovers.map((file) => path.relative(outDir, file)).join(', ')}`,
+ );
+ for (const file of inlined) rmSync(file);
+ for (const entry of readdirSync(outDir))
+ rmSync(path.join(outDir, entry), { recursive: true });
+ writeFileSync(path.join(outDir, 'acceptance-report.html'), html);
+ },
+ name: 'acceptance-report-single-file',
+ writeBundle() {
+ written = true;
+ },
+ };
+};
+
+/** Shared renderer plugins that emit files a report page never loads. */
+const UNUSED_PLUGINS = new Set(['lobe-canvas-runtime', 'lobe-completion-sounds']);
+
+const outDir = path.resolve(import.meta.dirname, 'dist-report');
+
+/** `REPORT_ANALYZE=1` prints the heaviest packages in the report. */
+const analyze = (): Plugin => ({
+ generateBundle(_options, bundle) {
+ const sizes = new Map<string, number>();
+ for (const item of Object.values(bundle)) {
+ if (item.type !== 'chunk') continue;
+ for (const [id, info] of Object.entries(item.modules)) {
+ const rel = path.relative(repoRoot, id);
+ const pkg = rel.includes('node_modules/')
+ ? rel
+ .split('node_modules/')
+ .at(-1)!
+ .split('/')
+ .slice(0, rel.split('node_modules/').at(-1)!.startsWith('@') ? 2 : 1)
+ .join('/')
+ : rel.split('/').slice(0, 3).join('/');
+ sizes.set(pkg, (sizes.get(pkg) ?? 0) + info.renderedLength);
+ }
+ }
+ const top = [...sizes].sort((a, b) => b[1] - a[1]).slice(0, 40);
+ console.info(
+ top.map(([name, size]) => `${(size / 1024).toFixed(0).padStart(7)} KB ${name}`).join('\n'),
+ );
+ },
+ name: 'acceptance-report-analyze',
+});
+
+export default defineConfig({
+ base: './',
+ build: {
+ assetsInlineLimit: Number.MAX_SAFE_INTEGER,
+ cssCodeSplit: false,
+ emptyOutDir: true,
+ modulePreload: false,
+ outDir,
+ reportCompressedSize: false,
+ rolldownOptions: {
+ input: path.resolve(import.meta.dirname, 'report.html'),
+ output: { codeSplitting: false },
+ },
+ },
+ define: {
+ ...sharedRendererDefine({ isElectron: false, isMobile: true }),
+ __WORKBENCH__: 'true',
+ },
+ plugins: [
+ // Before path aliases: a stub replaces the module `@/…` would resolve to.
+ localReportStubs(),
+ tsconfigPaths({
+ ignoreConfigErrors: true,
+ projects: [path.resolve(repoRoot, 'tsconfig.json')],
+ root: repoRoot,
+ }),
+ process.env.REPORT_TRACE_MODULE ? moduleTrace(process.env.REPORT_TRACE_MODULE) : undefined,
+ process.env.REPORT_ANALYZE ? analyze() : undefined,
+ stubSurfaceGuard(),
+ ...sharedRendererPlugins({ platform: 'mobile' }).filter(
+ (plugin) => !(plugin && 'name' in plugin && UNUSED_PLUGINS.has(plugin.name)),
+ ),
+ singleFile(outDir),
+ ].filter(Boolean) as PluginOption[],
+ // Nothing is served next to the file.
+ publicDir: false,
+ resolve: {
+ // One copy of every module-level singleton: a second dayjs, reached through
+ // a workspace package's own install, keeps its locale apart from the page's.
+ dedupe: ['@lobehub/editor', '@lobehub/ui', 'dayjs', 'react', 'react-dom'],
+ },
+ root: import.meta.dirname,
+});
diff --git a/locales/en-US/verify.json b/locales/en-US/verify.json
index 9ee0b1dd77c..8426a871b8f 100644
--- a/locales/en-US/verify.json
+++ b/locales/en-US/verify.json
@@ -310,6 +310,21 @@
"acceptance.ledger.pending": "Awaiting review",
"acceptance.ledger.title": "Runs",
"acceptance.ledger.viewReport": "View round report",
+ "acceptance.local.allSaved": "All reviews saved",
+ "acceptance.local.badge": "Local report",
+ "acceptance.local.badgeHint": "Rendered on this computer. Nothing was uploaded.",
+ "acceptance.local.copied": "Command copied",
+ "acceptance.local.copy": "Copy command",
+ "acceptance.local.downloaded": "Reviews saved to Downloads",
+ "acceptance.local.externalMedia": "External media is not loaded in local reports.",
+ "acceptance.local.noReviews": "Not reviewed yet",
+ "acceptance.local.openExternalMedia": "Open external media",
+ "acceptance.local.save": "Save reviews",
+ "acceptance.local.saved": "Saved {{file}}. Tell your agent you have finished reviewing.",
+ "acceptance.local.share": "Share",
+ "acceptance.local.shareHint": "Comments, mentions and a shareable link need LobeHub. Ask your agent to publish this acceptance, or run:",
+ "acceptance.local.shareTitle": "Review with your team",
+ "acceptance.local.unsaved": "{{count}} unsaved review(s)",
"acceptance.notFound.description": "It may have been deleted, or it was never shared with you.",
"acceptance.notFound.title": "Acceptance not found",
"acceptance.origin.agentFallback": "Agent",
diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.json
index c25b9ab7f17..f3257ce082f 100644
--- a/locales/zh-CN/verify.json
+++ b/locales/zh-CN/verify.json
@@ -310,6 +310,21 @@
"acceptance.ledger.pending": "待验收",
"acceptance.ledger.title": "运行记录",
"acceptance.ledger.viewReport": "查看该轮报告",
+ "acceptance.local.allSaved": "评审已全部保存",
+ "acceptance.local.badge": "本地报告",
+ "acceptance.local.badgeHint": "在这台电脑上生成,没有上传任何内容。",
+ "acceptance.local.copied": "命令已复制",
+ "acceptance.local.copy": "复制命令",
+ "acceptance.local.downloaded": "评审已保存到下载文件夹",
+ "acceptance.local.externalMedia": "本地报告不会自动加载外部媒体。",
+ "acceptance.local.noReviews": "尚未评审",
+ "acceptance.local.openExternalMedia": "打开外部媒体",
+ "acceptance.local.save": "保存评审",
+ "acceptance.local.saved": "已保存 {{file}}。告诉 Agent 你已评审完即可。",
+ "acceptance.local.share": "分享",
+ "acceptance.local.shareHint": "评论、@ 提及和分享链接需要 LobeHub。让 Agent 发布这份验收,或运行:",
+ "acceptance.local.shareTitle": "和团队一起评审",
+ "acceptance.local.unsaved": "{{count}} 条评审未保存",
"acceptance.notFound.description": "它可能已被删除,也可能没有分享给你。",
"acceptance.notFound.title": "找不到这条验收",
"acceptance.origin.agentFallback": "智能体",
diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.ts
index 18b121e4b59..5a8fbf15a35 100644
--- a/packages/locales/src/default/verify.ts
+++ b/packages/locales/src/default/verify.ts
@@ -249,6 +249,22 @@ export default {
'acceptance.error.title': 'Unable to load acceptance',
'acceptance.notFound.description': 'It may have been deleted, or it was never shared with you.',
'acceptance.notFound.title': 'Acceptance not found',
+ 'acceptance.local.allSaved': 'All reviews saved',
+ 'acceptance.local.badge': 'Local report',
+ 'acceptance.local.badgeHint': 'Rendered on this computer. Nothing was uploaded.',
+ 'acceptance.local.copied': 'Command copied',
+ 'acceptance.local.copy': 'Copy command',
+ 'acceptance.local.downloaded': 'Reviews saved to Downloads',
+ 'acceptance.local.externalMedia': 'External media is not loaded in local reports.',
+ 'acceptance.local.noReviews': 'Not reviewed yet',
+ 'acceptance.local.openExternalMedia': 'Open external media',
+ 'acceptance.local.save': 'Save reviews',
+ 'acceptance.local.saved': 'Saved {{file}}. Tell your agent you have finished reviewing.',
+ 'acceptance.local.share': 'Share',
+ 'acceptance.local.shareHint':
+ 'Comments, mentions and a shareable link need LobeHub. Ask your agent to publish this acceptance, or run:',
+ 'acceptance.local.shareTitle': 'Review with your team',
+ 'acceptance.local.unsaved': '{{count}} unsaved review(s)',
'acceptance.comments.title': 'Discussion',
'acceptance.comments.moreActions': 'More actions',
'acceptance.comments.placeholder': 'Comment on this delivery…',
diff --git a/packages/utils/src/verify/acceptanceCheckUnion.ts b/packages/utils/src/verify/acceptanceCheckUnion.ts
new file mode 100644
index 00000000000..0502f7645a9
--- /dev/null
+++ b/packages/utils/src/verify/acceptanceCheckUnion.ts
@@ -0,0 +1,297 @@
+import { normalizeVerifySurface } from '@lobechat/const/verify';
+import type {
+ AcceptanceCheckGroup,
+ VerifyAgentPlanConfig,
+ VerifyCheckItem,
+ VerifyCheckTally,
+ VerifySurface,
+} from '@lobechat/types';
+
+/**
+ * The fields of a result row the union reads. The server passes its Drizzle
+ * rows; a local report passes rows it assembled from `result.json`. Both get
+ * their own row type back on `AcceptanceCheckRow.result`.
+ */
+export interface CheckUnionResult {
+ checkItemId: string;
+ checkItemTitle: string | null;
+ id: string;
+ required: boolean;
+ status: string;
+ verdict: string | null;
+}
+
+/** The fields of a round's run the union reads. */
+export interface CheckUnionRun {
+ id: string;
+ plan: VerifyCheckItem[] | null;
+ roundIndex: number | null;
+}
+
+// ============================================
+// 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: CheckUnionResult): 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<R extends CheckUnionResult = CheckUnionResult> {
+ /**
+ * 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?: R;
+ /** Round the final result came from. */
+ resultRound?: number;
+ /** How many executed steps the timeline holds (re-runs + folded generations). */
+ revisions: number;
+ /**
+ * Stable 1-based label across the whole union ("C3") — first-appearance
+ * order over the round chain, so earlier rounds' numbering never shifts when
+ * a new round lands. Feedback and annotations reference checks by it.
+ * (Folding a superseded generation removes its row, so numbering after the
+ * folded id shifts by one — the successor keeps its own slot.)
+ */
+ seq: 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<R extends CheckUnionResult> {
+ results: R[];
+ run: CheckUnionRun;
+}
+
+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 = <R extends CheckUnionResult>(
+ rounds: RoundInput<R>[],
+ groups: AcceptanceCheckGroup[] = [],
+): AcceptanceCheckRow<R>[] => {
+ const ordered = [...rounds].sort((a, b) => (a.run.roundIndex ?? 0) - (b.run.roundIndex ?? 0));
+
+ const rows = new Map<string, AcceptanceCheckRow<R>>();
+ // Last round whose PLAN named each item — drives the carried-forward flag.
+ const lastPlannedRound = new Map<string, number>();
+ // A `supersedes` entry names the check the author knew: often the plan item id
+ // they wrote, while the row is keyed by the criterion minted for it. Remember
+ // every plan item id's row so the fold below resolves either spelling.
+ const logicalIdByPlanItemId = new Map<string, string>();
+
+ const ensureRow = (id: string, roundIndex: number): AcceptanceCheckRow<R> => {
+ const existing = rows.get(id);
+ if (existing) return existing;
+ const row: AcceptanceCheckRow<R> = {
+ category: null,
+ fixed: false,
+ history: [],
+ id,
+ introducedAtRound: roundIndex,
+ required: true,
+ revisions: 0,
+ seq: 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 ?? [];
+ const planById = new Map(plan.map((item) => [item.id, item]));
+ const logicalIdByCheckItemId = new Map(
+ plan.map((item) => [
+ item.id,
+ item.sourceFlowNode ? item.id : (item.sourceCriterionId ?? item.id),
+ ]),
+ );
+
+ for (const item of plan) {
+ const logicalId = item.sourceFlowNode ? item.id : (item.sourceCriterionId ?? item.id);
+ const row = ensureRow(logicalId, roundIndex);
+ logicalIdByPlanItemId.set(item.id, logicalId);
+ // The latest snapshot wins: repair rounds may refine method/expected.
+ if (item.sourceFlowNode) {
+ // A rerun is a fresh execution; historical evidence stays in the timeline.
+ row.result = undefined;
+ row.resultRound = undefined;
+ }
+ 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(logicalId, roundIndex);
+ }
+
+ for (const result of results) {
+ const logicalId = logicalIdByCheckItemId.get(result.checkItemId) ?? result.checkItemId;
+ const row = ensureRow(logicalId, 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 ?? []).map((id) =>
+ rows.has(id) ? id : (logicalIdByPlanItemId.get(id) ?? id),
+ );
+ 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);
+ }
+ }
+
+ // Number the surviving rows by first appearance (Map insertion order) —
+ // stable as rounds accrue, because a new round only appends new ids.
+ let seq = 0;
+ for (const row of rows.values()) row.seq = ++seq;
+
+ 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;
+ }
+ }
+
+ // Organization belongs to the current acceptance, not its immutable execution
+ // snapshots. Preserve IDs, numbering and result references when a check moves.
+ const grouped = new Map<string, AcceptanceCheckRow<R>>();
+ for (const group of groups) {
+ for (const id of group.checkItemIds) {
+ const row = rows.get(id);
+ if (row) grouped.set(id, { ...row, category: group.title });
+ }
+ }
+ return [...grouped.values(), ...[...rows.values()].filter((row) => !grouped.has(row.id))];
+};
+
+/**
+ * The union's own three-way split, counted — the number a summary can show
+ * without opening the list.
+ *
+ * It counts UNION ROWS, not one round's result rows. A repair round re-runs the
+ * check it was asked to fix and carries the rest forward, so the current round's
+ * rows are a subset of the union: counting them would print "1 passed" beside a
+ * list that expands to the repaired check plus everything it carried, and the
+ * two readings of one acceptance would contradict each other.
+ */
+export const tallyCheckUnion = (checks: AcceptanceCheckRow[]): VerifyCheckTally => {
+ let failed = 0;
+ let passed = 0;
+ let unjudged = 0;
+ for (const check of checks) {
+ if (check.state === 'passed') passed++;
+ else if (check.state === 'failed') failed++;
+ // `uncertain` and `not_executed` are both "planned, never judged" — the same
+ // split the acceptance's criteria list draws.
+ else unjudged++;
+ }
+ return { failed, passed, total: checks.length, unjudged };
+};
diff --git a/apps/server/src/services/verify/acceptanceService/reviewOverlay.ts b/packages/utils/src/verify/acceptanceReviewOverlay.ts
similarity index 91%
rename from apps/server/src/services/verify/acceptanceService/reviewOverlay.ts
rename to packages/utils/src/verify/acceptanceReviewOverlay.ts
index 575861176e3..00cc963350e 100644
--- a/apps/server/src/services/verify/acceptanceService/reviewOverlay.ts
+++ b/packages/utils/src/verify/acceptanceReviewOverlay.ts
@@ -2,11 +2,19 @@ import type {
AcceptanceAttachment,
AcceptanceCheckReviewAction,
AcceptanceReviewAnnotation,
+ VerifyCheckDecisionDetail,
} from '@lobechat/types';
-import type { VerifyCheckResultItem } from '@/database/schemas/verify';
+import type { AcceptanceCheckRow } from './acceptanceCheckUnion';
-import type { AcceptanceCheckRow } from './checkUnion';
+/** The fields of a result row the overlay reads: the decision stamped on it. */
+export interface ReviewOverlayResult {
+ completedAt: Date | null;
+ createdAt: Date;
+ id: string;
+ userDecision: string | null;
+ userDecisionDetail: VerifyCheckDecisionDetail | null;
+}
// ============================================
// User review overlay — the per-check human verdict layered onto the union.
@@ -67,7 +75,7 @@ export interface AcceptanceCheckReviewOverlay {
*/
export const buildCheckReviewOverlay = (
check: Pick<AcceptanceCheckRow, 'timeline'> & Partial<Pick<AcceptanceCheckRow, 'planItem'>>,
- resultsById: Map<string, VerifyCheckResultItem>,
+ resultsById: Map<string, ReviewOverlayResult>,
currentRoundIndex: number,
): AcceptanceCheckReviewOverlay => {
const reviews: AcceptanceCheckReviewEvent[] = [];
diff --git a/apps/server/src/services/verify/acceptanceService/statusRollup.ts b/packages/utils/src/verify/acceptanceStatus.ts
similarity index 88%
rename from apps/server/src/services/verify/acceptanceService/statusRollup.ts
rename to packages/utils/src/verify/acceptanceStatus.ts
index a775018d909..e9b74d36e16 100644
--- a/apps/server/src/services/verify/acceptanceService/statusRollup.ts
+++ b/packages/utils/src/verify/acceptanceStatus.ts
@@ -1,7 +1,5 @@
import type { AcceptanceStatus } from '@lobechat/types';
-import type { VerifyRunItem } from '@/database/schemas/verify';
-
// ============================================
// Status rollup — the aggregate's user-facing lifecycle state, derived from the
// current (highest) round. `accepted` is terminal and user-owned: recompute
@@ -9,7 +7,10 @@ import type { VerifyRunItem } from '@/database/schemas/verify';
// ============================================
/** Derive the aggregate status from the current round's pipeline state. */
-export const statusFromRound = (run: VerifyRunItem, hasReport: boolean): AcceptanceStatus => {
+export const statusFromRound = (
+ run: { status: string | null },
+ hasReport: boolean,
+): AcceptanceStatus => {
switch (run.status) {
case 'planned': {
return 'planned';
diff --git a/packages/utils/src/verify/localAcceptance.test.ts b/packages/utils/src/verify/localAcceptance.test.ts
new file mode 100644
index 00000000000..6962df0bf23
--- /dev/null
+++ b/packages/utils/src/verify/localAcceptance.test.ts
@@ -0,0 +1,267 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ assembleLocalAcceptance,
+ localAcceptanceComments,
+ type LocalAcceptanceSource,
+ type LocalReviewEvent,
+ localReviewTargets,
+ type LocalRoundSource,
+ localSubjectFromKey,
+ mergeLocalReviewEvents,
+} from './localAcceptance';
+
+const planItem = (id: string, title: string) => ({
+ id,
+ index: 0,
+ onFail: 'manual' as const,
+ required: true,
+ title,
+ verifierConfig: { requiredEvidence: [{ type: 'screenshot' as const }] },
+ verifierType: 'agent' as const,
+});
+
+const round = (
+ roundIndex: number,
+ cases: { id: string; title: string; verdict: 'failed' | 'passed' | 'uncertain' }[],
+ extra: Partial<LocalRoundSource> = {},
+): LocalRoundSource => ({
+ dir: `2026010${roundIndex}-000000-round`,
+ evidence: cases.map((item) => ({
+ checkResultId: `r${roundIndex}-${item.id}`,
+ content: null,
+ createdAt: `2026-01-0${roundIndex}T00:00:00.000Z`,
+ description: `${item.title} screenshot`,
+ fileHeight: 600,
+ fileName: `${item.id}.png`,
+ fileUrl: `2026010${roundIndex}-000000-round/assets/${item.id}.png`,
+ fileWidth: 800,
+ id: `e${roundIndex}-${item.id}`,
+ metadata: null,
+ type: 'screenshot' as const,
+ })),
+ proposal: null,
+ report: {
+ content: 'narrative',
+ failedChecks: cases.filter((item) => item.verdict === 'failed').length,
+ overallConfidence: null,
+ passedChecks: cases.filter((item) => item.verdict === 'passed').length,
+ summary: `round ${roundIndex}`,
+ totalChecks: cases.length,
+ uncertainChecks: null,
+ verdict: cases.every((item) => item.verdict === 'passed') ? 'passed' : 'failed',
+ },
+ results: cases.map((item, index) => ({
+ checkItemId: item.id,
+ checkItemIndex: index,
+ checkItemTitle: item.title,
+ createdAt: `2026-01-0${roundIndex}T00:00:00.000Z`,
+ id: `r${roundIndex}-${item.id}`,
+ metadata: null,
+ required: true,
+ suggestion: null,
+ toulmin: { evidence: `${item.title}: ${item.verdict}` },
+ verdict: item.verdict,
+ })),
+ run: {
+ context: { pullRequest: { title: 'Fix', url: 'https://github.com/lobehub/demo/pull/7' } },
+ createdAt: `2026-01-0${roundIndex}T00:00:00.000Z`,
+ goal: null,
+ id: `run-${roundIndex}`,
+ metadata: null,
+ plan: cases.map((item) => planItem(item.id, item.title)),
+ roundIndex,
+ scenario: 'coding',
+ title: `Round ${roundIndex}`,
+ },
+ ...extra,
+});
+
+const source = (
+ rounds: LocalRoundSource[],
+ reviews: LocalReviewEvent[] = [],
+): LocalAcceptanceSource => ({
+ acceptance: {
+ createdAt: '2026-01-01T00:00:00.000Z',
+ id: 'acc-local',
+ requirement: 'Users can rename a topic',
+ subjectKey: 'standalone-rename',
+ },
+ format: 1,
+ generatedAt: '2026-01-03T00:00:00.000Z',
+ reviews,
+ rounds,
+});
+
+describe('assembleLocalAcceptance', () => {
+ it('folds rounds into the union the acceptance page renders', () => {
+ const bundle = assembleLocalAcceptance(
+ source([
+ round(1, [
+ { id: 'rename', title: 'Rename keeps focus', verdict: 'failed' },
+ { id: 'toast', title: 'Toast copy', verdict: 'passed' },
+ ]),
+ round(2, [{ id: 'rename', title: 'Rename keeps focus', verdict: 'passed' }]),
+ ]),
+ );
+
+ expect(bundle.checks.map((check) => [check.id, check.seq, check.state])).toEqual([
+ ['rename', 1, 'passed'],
+ ['toast', 2, 'passed'],
+ ]);
+ const rename = bundle.checks[0]!;
+ expect(rename.fixed).toBe(true);
+ expect(rename.timeline.map((entry) => entry.evidence[0]?.fileUrl)).toEqual([
+ '20260101-000000-round/assets/rename.png',
+ '20260102-000000-round/assets/rename.png',
+ ]);
+ expect(rename.evidence[0]?.checkItemId).toBe('rename');
+ // Round 2 planned only `rename`; `toast` keeps its round-1 evidence.
+ expect(bundle.checks[1]!.resultRound).toBe(1);
+ expect(bundle.acceptance.status).toBe('delivered');
+ expect(bundle.latestReport?.summary).toBe('round 2');
+ expect(bundle.subject).toEqual({
+ id: 'standalone-rename',
+ title: 'Round 2',
+ type: 'standalone',
+ });
+ expect(bundle.pullRequests).toMatchObject([
+ { number: 7, repoFullName: 'lobehub/demo', source: 'manual' },
+ ]);
+ expect(bundle.canReview).toBe(true);
+ });
+
+ it('keeps a decision on the round it judged, so a re-run makes a reject stale', () => {
+ const rounds = [
+ round(1, [
+ { id: 'rename', title: 'Rename keeps focus', verdict: 'passed' },
+ { id: 'toast', title: 'Toast copy', verdict: 'passed' },
+ ]),
+ ];
+ const first = assembleLocalAcceptance(source(rounds));
+ const reviews: LocalReviewEvent[] = [
+ {
+ action: 'reject',
+ annotations: [
+ {
+ comment: 'Caret jumps to the start',
+ evidenceId: 'e1-rename',
+ rect: { h: 0.2, w: 0.2, x: 0.1, y: 0.1 },
+ },
+ ],
+ comment: 'Focus is lost',
+ createdAt: '2026-01-01T10:00:00.000Z',
+ id: 'ev-1',
+ kind: 'checks',
+ roundIndex: 1,
+ targets: localReviewTargets(first, ['rename']),
+ },
+ {
+ action: 'accept',
+ createdAt: '2026-01-01T10:01:00.000Z',
+ id: 'ev-2',
+ kind: 'checks',
+ roundIndex: 1,
+ targets: localReviewTargets(first, ['toast']),
+ },
+ {
+ category: 'Rename',
+ comment: 'Also check keyboard-only',
+ createdAt: '2026-01-01T10:02:00.000Z',
+ id: 'ev-3',
+ kind: 'group',
+ roundIndex: 1,
+ },
+ ];
+
+ const reviewed = assembleLocalAcceptance(source(rounds, reviews));
+ expect(reviewed.checks[0]!.userReview).toMatchObject({
+ action: 'reject',
+ comment: 'Focus is lost',
+ stale: false,
+ });
+ expect(reviewed.checks[0]!.userReview?.annotations?.[0]?.evidenceId).toBe('e1-rename');
+ expect(reviewed.checks[1]!.userReview).toMatchObject({ action: 'accept', stale: false });
+ expect(reviewed.rounds[0]!.run.decisionDetail?.groupFeedback).toEqual([
+ {
+ category: 'Rename',
+ comment: 'Also check keyboard-only',
+ createdAt: '2026-01-01T10:02:00.000Z',
+ },
+ ]);
+
+ const repaired = assembleLocalAcceptance(
+ source(
+ [...rounds, round(2, [{ id: 'rename', title: 'Rename keeps focus', verdict: 'passed' }])],
+ reviews,
+ ),
+ );
+ // The reject stays on round 1's row: history now, not the round-2 verdict.
+ expect(repaired.checks[0]!.userReview).toMatchObject({ action: 'reject', stale: true });
+ expect(repaired.checks[0]!.reviews).toHaveLength(1);
+ // An accept is sticky across rounds.
+ expect(repaired.checks[1]!.userReview).toMatchObject({ action: 'accept', stale: false });
+ });
+});
+
+describe('localReviewTargets', () => {
+ it('refuses unknown and never-executed checks, like the server', () => {
+ const bundle = assembleLocalAcceptance(
+ source([
+ round(1, [{ id: 'rename', title: 'Rename', verdict: 'passed' }], {
+ run: {
+ ...round(1, []).run,
+ plan: [planItem('rename', 'Rename'), planItem('later', 'Later')],
+ },
+ }),
+ ]),
+ );
+ expect(() => localReviewTargets(bundle, ['missing'])).toThrow('Unknown check item(s): missing');
+ expect(() => localReviewTargets(bundle, ['later'])).toThrow('never executed');
+ expect(localReviewTargets(bundle, ['rename'])).toEqual([
+ { checkId: 'rename', resultId: 'r1-rename' },
+ ]);
+ });
+});
+
+describe('localAcceptanceComments', () => {
+ it('posts each round proposal as that round’s note', () => {
+ const list = localAcceptanceComments(
+ source([round(1, [], { proposal: ' Rename now keeps focus. ' }), round(2, [])]),
+ );
+ expect(list.canComment).toBe(false);
+ expect(list.items).toHaveLength(1);
+ expect(list.items[0]).toMatchObject({
+ content: 'Rename now keeps focus.',
+ contextRoundIndex: 1,
+ contextRunId: 'run-1',
+ kind: 'proposal',
+ });
+ });
+});
+
+describe('localSubjectFromKey', () => {
+ it('reads the subject the directory is keyed by', () => {
+ expect(localSubjectFromKey('task-T-12')).toEqual({ id: 'T-12', type: 'task' });
+ expect(localSubjectFromKey('standalone-rename')).toEqual({
+ id: 'standalone-rename',
+ type: 'standalone',
+ });
+ expect(localSubjectFromKey('my-feature')).toEqual({ id: 'my-feature', type: 'standalone' });
+ });
+});
+
+describe('mergeLocalReviewEvents', () => {
+ it('dedupes by id and orders by time', () => {
+ const a: LocalReviewEvent = {
+ category: 'A',
+ comment: 'a',
+ createdAt: '2026-01-02T00:00:00.000Z',
+ id: 'a',
+ kind: 'group',
+ roundIndex: 1,
+ };
+ const b: LocalReviewEvent = { ...a, createdAt: '2026-01-01T00:00:00.000Z', id: 'b' };
+ expect(mergeLocalReviewEvents([a], [b, a]).map((event) => event.id)).toEqual(['b', 'a']);
+ });
+});
diff --git a/packages/utils/src/verify/localAcceptance.ts b/packages/utils/src/verify/localAcceptance.ts
new file mode 100644
index 00000000000..0f80a58be68
--- /dev/null
+++ b/packages/utils/src/verify/localAcceptance.ts
@@ -0,0 +1,719 @@
+import type {
+ AcceptanceSubjectType,
+ AcceptanceVisibility,
+ VerifierType,
+ VerifyCheckResultStatus,
+ VerifyEvidenceCapturedBy,
+ VerifyEvidenceType,
+ VerifyRunSource,
+ VerifyRunStatus,
+ VerifyUserDecision,
+ VerifyVerdict,
+ VerifyVisibility,
+} from '@lobechat/const/verify';
+import { acceptanceSubjectTypes } from '@lobechat/const/verify';
+import type {
+ AcceptanceCheckReviewAction,
+ AcceptanceCommentItem,
+ AcceptanceCommentList,
+ AcceptanceConfig,
+ AcceptanceMetadata,
+ AcceptanceReviewAnnotation,
+ AcceptanceStatus,
+ AcceptanceVisualRender,
+ ToulminVerdict,
+ VerifyCheckDecisionDetail,
+ VerifyCheckItem,
+ VerifyCheckResultMetadata,
+ VerifyFlowSnapshot,
+ VerifyRunContext,
+ VerifyRunDecisionDetail,
+ VerifyRunMetadata,
+ VerifyRunScenario,
+} from '@lobechat/types';
+
+import {
+ type AcceptanceCheckRow,
+ type AcceptanceTimelineEntry,
+ buildAcceptanceCheckUnion,
+} from './acceptanceCheckUnion';
+import {
+ type AcceptanceCheckReviewEvent,
+ type AcceptanceCheckUserReview,
+ buildCheckReviewOverlay,
+} from './acceptanceReviewOverlay';
+import { statusFromRound } from './acceptanceStatus';
+
+// ============================================
+// Local acceptance — the same acceptance page, read from `.acceptances/`
+// instead of the server. The CLI reads each round directory into the rows an
+// ingest would publish; this module folds them (plus the reviewer's local
+// decisions) into the bundle the acceptance viewer renders, with the same
+// union, review overlay and status rollup the server uses. Everything here is
+// pure and JSON-in: the CLI runs it for `view` / `feedback`, and the offline
+// report page runs it again in the browser after every review.
+// ============================================
+
+export const LOCAL_ACCEPTANCE_FORMAT = 1;
+
+/** The account every local row is owned by — there is no account. */
+export const LOCAL_ACCEPTANCE_USER_ID = 'local';
+
+/** ISO 8601 timestamp, as stored in `acceptance.json`, `reviews.json` and the page data. */
+type IsoDate = string;
+
+/** `acceptance.json` — the identity of one local acceptance directory. */
+export interface LocalAcceptanceInfo {
+ createdAt: IsoDate;
+ /** Stable local id (a UUID), minted on the first render and kept forever. */
+ id: string;
+ /** Present once the rounds were published to LobeHub with `lh acceptance publish`. */
+ remote?: LocalAcceptanceRemote;
+ /** The durable business goal; immutable once recorded, like the server's. */
+ requirement: string | null;
+ /** The directory name under `.acceptances/` (`standalone-<slug>`, `task-T-12`, …). */
+ subjectKey: string;
+}
+
+export interface LocalAcceptanceRemote {
+ acceptanceId: string;
+ acceptanceUrl: string;
+ /**
+ * Local review decisions already carried onto the published acceptance, so a
+ * re-publish never replays one over a collaborator's newer decision online.
+ */
+ carriedReviews?: string[];
+ /** Round directories already published, oldest first, with the run each became. */
+ rounds: {
+ dir: string;
+ /** Local evidence id → its upload's id. An artifact that failed to upload is absent. */
+ evidence?: Record<string, string>;
+ roundIndex: number | null;
+ verifyRunId: string;
+ }[];
+}
+
+export interface LocalRunSource {
+ context: VerifyRunContext | null;
+ createdAt: IsoDate;
+ goal: string | null;
+ id: string;
+ metadata: VerifyRunMetadata | null;
+ plan: VerifyCheckItem[] | null;
+ roundIndex: number;
+ scenario: VerifyRunScenario | null;
+ title: string | null;
+}
+
+export interface LocalResultSource {
+ checkItemId: string;
+ checkItemIndex: number;
+ checkItemTitle: string;
+ createdAt: IsoDate;
+ id: string;
+ metadata: VerifyCheckResultMetadata | null;
+ required: boolean;
+ suggestion: string | null;
+ toulmin: ToulminVerdict | null;
+ verdict: VerifyVerdict;
+}
+
+export interface LocalEvidenceSource {
+ checkResultId: string;
+ content: string | null;
+ createdAt: IsoDate;
+ description: string | null;
+ fileHeight: number | null;
+ fileName: string | null;
+ /** Path relative to the acceptance directory (where `report.html` lives). */
+ fileUrl: string | null;
+ fileWidth: number | null;
+ id: string;
+ metadata: unknown;
+ type: VerifyEvidenceType;
+}
+
+export interface LocalReportSource {
+ content: string | null;
+ failedChecks: number | null;
+ overallConfidence: number | null;
+ passedChecks: number | null;
+ summary: string | null;
+ totalChecks: number | null;
+ uncertainChecks: number | null;
+ verdict: VerifyVerdict | null;
+}
+
+/** One round directory, read into the rows an ingest would publish. */
+export interface LocalRoundSource {
+ /** The round directory name, relative to the acceptance directory. */
+ dir: string;
+ evidence: LocalEvidenceSource[];
+ /** `proposal.md` — the round's note to the reviewer. */
+ proposal: string | null;
+ report: LocalReportSource | null;
+ results: LocalResultSource[];
+ run: LocalRunSource;
+}
+
+/**
+ * One reviewer decision, appended to the acceptance's local review log.
+ *
+ * A check decision names the RESULT rows it judged, resolved when it was
+ * made: a later round re-runs the check into a new row, and the decision must
+ * stay on the evidence it was made against — exactly what the server's
+ * `user_decision` column does.
+ */
+export type LocalReviewEvent =
+ | {
+ action: AcceptanceCheckReviewAction;
+ annotations?: AcceptanceReviewAnnotation[];
+ comment?: string;
+ createdAt: IsoDate;
+ id: string;
+ kind: 'checks';
+ roundIndex: number;
+ targets: { checkId: string; resultId: string }[];
+ }
+ | {
+ category: string;
+ comment: string;
+ createdAt: IsoDate;
+ id: string;
+ kind: 'group';
+ roundIndex: number;
+ };
+
+/** `reviews.json` — the local review log of one acceptance. */
+export interface LocalReviewLog {
+ acceptanceId: string;
+ events: LocalReviewEvent[];
+ format: typeof LOCAL_ACCEPTANCE_FORMAT;
+}
+
+/** Everything a local report renders from — what the CLI embeds into `report.html`. */
+export interface LocalAcceptanceSource {
+ acceptance: LocalAcceptanceInfo;
+ format: typeof LOCAL_ACCEPTANCE_FORMAT;
+ generatedAt: IsoDate;
+ reviews: LocalReviewEvent[];
+ rounds: LocalRoundSource[];
+}
+
+// --- the bundle rows, shaped like the server's ---
+
+interface LocalAcceptanceRow {
+ accessedAt: Date;
+ completedAt: Date | null;
+ config: AcceptanceConfig | null;
+ createdAt: Date;
+ id: string;
+ metadata: AcceptanceMetadata | null;
+ projectId: string | null;
+ requirement: string | null;
+ status: AcceptanceStatus;
+ subjectId: string;
+ subjectType: AcceptanceSubjectType;
+ updatedAt: Date;
+ userId: string;
+ visibility: AcceptanceVisibility;
+ visualRender: AcceptanceVisualRender | null;
+ workspaceId: string | null;
+}
+
+interface LocalRunRow {
+ acceptanceId: string | null;
+ accessedAt: Date;
+ context: VerifyRunContext | null;
+ createdAt: Date;
+ decisionDetail: VerifyRunDecisionDetail | null;
+ flowSnapshots: VerifyFlowSnapshot[] | null;
+ goal: string | null;
+ id: string;
+ metadata: VerifyRunMetadata | null;
+ operationId: string | null;
+ plan: VerifyCheckItem[] | null;
+ planConfirmedAt: Date | null;
+ roundIndex: number | null;
+ scenario: VerifyRunScenario | null;
+ source: VerifyRunSource;
+ status: VerifyRunStatus | null;
+ title: string | null;
+ updatedAt: Date;
+ userDecision: string | null;
+ userId: string;
+ visibility: VerifyVisibility;
+ workspaceId: string | null;
+}
+
+export interface LocalResultRow {
+ checkItemId: string;
+ checkItemIndex: number | null;
+ checkItemTitle: string | null;
+ completedAt: Date | null;
+ confidence: number | null;
+ createdAt: Date;
+ id: string;
+ isFalseNegative: boolean | null;
+ isFalsePositive: boolean | null;
+ metadata: VerifyCheckResultMetadata | null;
+ operationId: string | null;
+ repairOperationId: string | null;
+ required: boolean;
+ sourceCriterionId: string | null;
+ startedAt: Date | null;
+ status: VerifyCheckResultStatus;
+ suggestion: string | null;
+ toulmin: ToulminVerdict | null;
+ userDecision: VerifyUserDecision | null;
+ userDecisionDetail: VerifyCheckDecisionDetail | null;
+ userId: string;
+ verdict: VerifyVerdict | null;
+ verifierConfigHash: string | null;
+ verifierOperationId: string | null;
+ verifierTracingId: string | null;
+ verifierType: VerifierType;
+ verifyRunId: string | null;
+ workspaceId: string | null;
+}
+
+export interface LocalEvidenceRow {
+ capturedAt: Date | null;
+ capturedBy: VerifyEvidenceCapturedBy | null;
+ checkItemId: string;
+ checkResultId: string;
+ content: string | null;
+ createdAt: Date;
+ description: string | null;
+ documentId: string | null;
+ fileHeight: number | null;
+ fileId: string | null;
+ fileName: string | null;
+ fileUrl: string | null;
+ fileWidth: number | null;
+ id: string;
+ metadata: unknown;
+ type: VerifyEvidenceType;
+ userId: string;
+ verifyRunId: string;
+ workspaceId: string | null;
+}
+
+interface LocalReportRow {
+ content: string | null;
+ createdAt: Date;
+ failedChecks: number | null;
+ generatedAt: Date;
+ generatedBy: string | null;
+ id: string;
+ operationId: string | null;
+ overallConfidence: number | null;
+ passedChecks: number | null;
+ reviewedByUser: boolean | null;
+ summary: string | null;
+ totalChecks: number | null;
+ uncertainChecks: number | null;
+ userId: string;
+ verdict: VerifyVerdict | null;
+ verifyRunId: string | null;
+ workspaceId: string | null;
+}
+
+/** A pull request the rounds name — a hand link nothing has vouched for. */
+interface LocalPullRequest {
+ ciStatus: null;
+ isDraft: boolean;
+ mergedAt: Date | null;
+ number: number;
+ provider: string;
+ repoFullName: string;
+ reviewDecision: null;
+ source: 'manual';
+ state: null;
+ title: string | null;
+ url: string;
+}
+
+type LocalCheck = Omit<AcceptanceCheckRow<LocalResultRow>, 'timeline'> & {
+ evidence: LocalEvidenceRow[];
+ prediction: null;
+ predictionStatus: null;
+ reviews: AcceptanceCheckReviewEvent[];
+ timeline: (AcceptanceTimelineEntry & { evidence: LocalEvidenceRow[] })[];
+ userReview: AcceptanceCheckUserReview | undefined;
+};
+
+/** The acceptance bundle of a local acceptance — the server's `getBundle` shape. */
+export interface LocalAcceptanceBundle {
+ acceptance: LocalAcceptanceRow;
+ /** Whoever ran the agent on this machine — there is no account to name. */
+ author: { avatar: string | null; fullName: string | null; id: string; username: string | null };
+ canCollaborate: false;
+ canReject: boolean;
+ canReview: boolean;
+ checks: LocalCheck[];
+ collaboration: null;
+ flows: never[];
+ isOwner: boolean;
+ latestReport: LocalReportRow | null;
+ origin: null;
+ pullRequests: LocalPullRequest[];
+ repairDispatchAvailable: false;
+ rounds: { report: LocalReportRow | null; run: LocalRunRow; usage: null }[];
+ subject: { id: string; title: string | null; type: AcceptanceSubjectType };
+}
+
+const date = (value: IsoDate | null | undefined, fallback: Date) => {
+ if (!value) return fallback;
+ const parsed = new Date(value);
+ return Number.isNaN(parsed.getTime()) ? fallback : parsed;
+};
+
+const decisionFor = (action: AcceptanceCheckReviewAction): VerifyUserDecision =>
+ action === 'accept' ? 'accepted' : action === 'ignore' ? 'overridden' : 'rejected';
+
+/** `task-T-12` → task subject; anything unrecognized (and `standalone-*`) is standalone. */
+export const localSubjectFromKey = (
+ subjectKey: string,
+): { id: string; type: AcceptanceSubjectType } => {
+ const separator = subjectKey.indexOf('-');
+ const type = subjectKey.slice(0, separator) as AcceptanceSubjectType;
+ if (
+ separator > 0 &&
+ type !== 'standalone' &&
+ (acceptanceSubjectTypes as readonly string[]).includes(type)
+ )
+ return { id: subjectKey.slice(separator + 1), type };
+ return { id: subjectKey, type: 'standalone' };
+};
+
+const GITHUB_PULL = /^https?:\/\/github\.com\/([^/]+\/[^/]+)\/pull\/(\d+)/i;
+
+const pullRequestsOf = (rounds: LocalRunRow[]): LocalPullRequest[] => {
+ const seen = new Map<string, LocalPullRequest>();
+ for (const run of rounds) {
+ const context = run.context as { pullRequest?: { title?: unknown; url?: unknown } } | null;
+ const url = typeof context?.pullRequest?.url === 'string' ? context.pullRequest.url : null;
+ const match = url?.match(GITHUB_PULL);
+ if (!url || !match) continue;
+ seen.set(url.toLowerCase(), {
+ ciStatus: null,
+ isDraft: false,
+ mergedAt: null,
+ number: Number(match[2]),
+ provider: 'github',
+ repoFullName: match[1]!,
+ reviewDecision: null,
+ source: 'manual',
+ state: null,
+ title: typeof context?.pullRequest?.title === 'string' ? context.pullRequest.title : null,
+ url,
+ });
+ }
+ return [...seen.values()];
+};
+
+/**
+ * Fold a local acceptance into the bundle the acceptance viewer renders.
+ *
+ * Review events are applied in order onto the rows they name, the way the
+ * server stamps `user_decision` (a later decision on the same row replaces the
+ * earlier one) and appends group feedback to the round's decision detail.
+ */
+export const assembleLocalAcceptance = (source: LocalAcceptanceSource): LocalAcceptanceBundle => {
+ const { acceptance: info } = source;
+ const createdAt = date(info.createdAt, new Date(0));
+ const ordered = [...source.rounds].sort((a, b) => a.run.roundIndex - b.run.roundIndex);
+
+ const runs: LocalRunRow[] = ordered.map(({ run }) => {
+ const runCreatedAt = date(run.createdAt, createdAt);
+ return {
+ acceptanceId: info.id,
+ accessedAt: runCreatedAt,
+ context: run.context,
+ createdAt: runCreatedAt,
+ decisionDetail: null,
+ flowSnapshots: null,
+ goal: run.goal,
+ id: run.id,
+ metadata: run.metadata,
+ operationId: null,
+ plan: run.plan,
+ planConfirmedAt: null,
+ roundIndex: run.roundIndex,
+ scenario: run.scenario,
+ source: 'agent-testing',
+ status: null,
+ title: run.title,
+ updatedAt: runCreatedAt,
+ userDecision: null,
+ userId: LOCAL_ACCEPTANCE_USER_ID,
+ visibility: 'private',
+ workspaceId: null,
+ };
+ });
+ const runByIndex = new Map(runs.map((run) => [run.roundIndex, run]));
+
+ const resultsById = new Map<string, LocalResultRow>();
+ const resultsByRun = new Map<string, LocalResultRow[]>();
+ const evidenceByResult = new Map<string, LocalEvidenceRow[]>();
+ const reports = new Map<string, LocalReportRow>();
+ for (const [index, round] of ordered.entries()) {
+ const run = runs[index]!;
+ const rows = round.results.map((result): LocalResultRow => {
+ const resultCreatedAt = date(result.createdAt, run.createdAt);
+ return {
+ checkItemId: result.checkItemId,
+ checkItemIndex: result.checkItemIndex,
+ checkItemTitle: result.checkItemTitle,
+ completedAt: resultCreatedAt,
+ confidence: null,
+ createdAt: resultCreatedAt,
+ id: result.id,
+ isFalseNegative: null,
+ isFalsePositive: null,
+ metadata: result.metadata,
+ operationId: null,
+ repairOperationId: null,
+ required: result.required,
+ sourceCriterionId: null,
+ startedAt: null,
+ // Same rule as the server's ingest: only a pass settles as passed.
+ status: result.verdict === 'passed' ? 'passed' : 'failed',
+ suggestion: result.suggestion,
+ toulmin: result.toulmin,
+ userDecision: null,
+ userDecisionDetail: null,
+ userId: LOCAL_ACCEPTANCE_USER_ID,
+ verdict: result.verdict,
+ verifierConfigHash: null,
+ verifierOperationId: null,
+ verifierTracingId: null,
+ verifierType: 'agent',
+ verifyRunId: run.id,
+ workspaceId: null,
+ };
+ });
+ resultsByRun.set(run.id, rows);
+ for (const row of rows) resultsById.set(row.id, row);
+
+ const checkItemByResult = new Map(rows.map((row) => [row.id, row.checkItemId]));
+ for (const evidence of round.evidence) {
+ const checkItemId = checkItemByResult.get(evidence.checkResultId);
+ if (!checkItemId) continue;
+ const evidenceCreatedAt = date(evidence.createdAt, run.createdAt);
+ const bucket = evidenceByResult.get(evidence.checkResultId) ?? [];
+ bucket.push({
+ capturedAt: evidenceCreatedAt,
+ capturedBy: 'cli',
+ checkItemId,
+ checkResultId: evidence.checkResultId,
+ content: evidence.content,
+ createdAt: evidenceCreatedAt,
+ description: evidence.description,
+ documentId: null,
+ fileHeight: evidence.fileHeight,
+ fileId: evidence.fileUrl,
+ fileName: evidence.fileName,
+ fileUrl: evidence.fileUrl,
+ fileWidth: evidence.fileWidth,
+ id: evidence.id,
+ metadata: evidence.metadata ?? null,
+ type: evidence.type,
+ userId: LOCAL_ACCEPTANCE_USER_ID,
+ verifyRunId: run.id,
+ workspaceId: null,
+ });
+ evidenceByResult.set(evidence.checkResultId, bucket);
+ }
+
+ if (round.report) {
+ reports.set(run.id, {
+ ...round.report,
+ createdAt: run.createdAt,
+ generatedAt: run.createdAt,
+ generatedBy: 'agent',
+ id: `${run.id}:report`,
+ operationId: null,
+ reviewedByUser: false,
+ userId: LOCAL_ACCEPTANCE_USER_ID,
+ verifyRunId: run.id,
+ workspaceId: null,
+ });
+ }
+ }
+
+ for (const event of source.reviews) {
+ if (event.kind === 'checks') {
+ const detail: VerifyCheckDecisionDetail = {
+ decidedAt: event.createdAt,
+ decidedBy: LOCAL_ACCEPTANCE_USER_ID,
+ roundIndex: event.roundIndex,
+ ...(event.comment ? { comment: event.comment } : {}),
+ ...(event.annotations?.length ? { annotations: event.annotations } : {}),
+ };
+ for (const target of event.targets) {
+ const row = resultsById.get(target.resultId);
+ if (!row) continue;
+ row.userDecision = decisionFor(event.action);
+ row.userDecisionDetail = detail;
+ }
+ continue;
+ }
+ const run = runByIndex.get(event.roundIndex);
+ if (!run) continue;
+ run.decisionDetail = {
+ ...run.decisionDetail,
+ groupFeedback: [
+ ...(run.decisionDetail?.groupFeedback ?? []),
+ { category: event.category, comment: event.comment, createdAt: event.createdAt },
+ ],
+ };
+ }
+
+ const union = buildAcceptanceCheckUnion(
+ runs.map((run) => ({ results: resultsByRun.get(run.id) ?? [], run })),
+ );
+ const currentRoundIndex = runs.at(-1)?.roundIndex ?? 0;
+ const checks: LocalCheck[] = union.map((check) => {
+ const { reviews, userReview } = buildCheckReviewOverlay(check, resultsById, currentRoundIndex);
+ return {
+ ...check,
+ evidence: check.result ? (evidenceByResult.get(check.result.id) ?? []) : [],
+ prediction: null,
+ predictionStatus: null,
+ reviews,
+ timeline: check.timeline.map((entry) => ({
+ ...entry,
+ evidence: evidenceByResult.get(entry.resultId) ?? [],
+ })),
+ userReview,
+ };
+ });
+
+ const rounds = runs.map((run) => ({ report: reports.get(run.id) ?? null, run, usage: null }));
+ const latestReport = [...rounds].reverse().find((round) => round.report)?.report ?? null;
+ const current = runs.at(-1);
+ const updatedAt = current?.createdAt ?? createdAt;
+ const subject = localSubjectFromKey(info.subjectKey);
+ const title = current?.title || current?.goal || null;
+
+ return {
+ acceptance: {
+ accessedAt: updatedAt,
+ completedAt: null,
+ config: {},
+ createdAt,
+ id: info.id,
+ metadata: title ? { title } : null,
+ projectId: null,
+ requirement: info.requirement,
+ status: current ? statusFromRound(current, reports.has(current.id)) : 'pending',
+ subjectId: subject.id,
+ subjectType: subject.type,
+ updatedAt,
+ userId: LOCAL_ACCEPTANCE_USER_ID,
+ visibility: 'private',
+ visualRender: null,
+ workspaceId: null,
+ },
+ author: { avatar: null, fullName: null, id: LOCAL_ACCEPTANCE_USER_ID, username: null },
+ canCollaborate: false,
+ canReject: true,
+ canReview: true,
+ checks,
+ collaboration: null,
+ flows: [],
+ isOwner: true,
+ latestReport,
+ origin: null,
+ pullRequests: pullRequestsOf(runs),
+ repairDispatchAvailable: false,
+ rounds,
+ subject: { id: subject.id, title, type: subject.type },
+ };
+};
+
+/**
+ * The discussion of a local acceptance: each round's `proposal.md`, posted as
+ * the round's own note the way ingest posts it. There is nobody else to talk
+ * to — writing comments is what publishing to LobeHub is for.
+ */
+export const localAcceptanceComments = (source: LocalAcceptanceSource): AcceptanceCommentList => ({
+ canApprove: false,
+ canComment: false,
+ canManageAccess: false,
+ items: source.rounds
+ .filter((round) => round.proposal?.trim())
+ .map((round): AcceptanceCommentItem => {
+ const at = date(round.run.createdAt, new Date(0));
+ return {
+ acceptanceId: source.acceptance.id,
+ anchorType: 'acceptance',
+ attachments: [],
+ author: {
+ avatar: null,
+ fullName: null,
+ id: null,
+ status: 'active',
+ type: 'agent',
+ username: 'Agent',
+ },
+ authorAgentId: null,
+ authorUserId: null,
+ canDelete: false,
+ clientId: `proposal:${round.run.id}`,
+ content: round.proposal!.trim(),
+ contextRoundIndex: round.run.roundIndex,
+ contextRunId: round.run.id,
+ createdAt: at,
+ deletedAt: null,
+ editorData: null,
+ id: `proposal:${round.run.id}`,
+ kind: 'proposal',
+ parentCommentId: null,
+ reactions: [],
+ resolvedAt: null,
+ resolvedByUserId: null,
+ source: null,
+ updatedAt: at,
+ };
+ }),
+});
+
+/**
+ * Resolve the checks a reviewer decided on to the result rows the decision is
+ * stamped on — the union row's final result, accepting a superseded id as an
+ * alias of its successor. Same refusals as the server: an unknown id, or a
+ * check that never ran (there is no evidence to judge).
+ */
+export const localReviewTargets = (
+ bundle: Pick<LocalAcceptanceBundle, 'checks'>,
+ checkIds: string[],
+): { checkId: string; resultId: string }[] => {
+ const byId = new Map<string, LocalCheck>();
+ for (const check of bundle.checks) {
+ byId.set(check.id, check);
+ for (const oldId of check.supersededIds) byId.set(oldId, check);
+ }
+ const unknown = checkIds.filter((id) => !byId.has(id));
+ if (unknown.length > 0) throw new Error(`Unknown check item(s): ${unknown.join(', ')}`);
+ const notExecuted = checkIds.filter((id) => !byId.get(id)!.result);
+ if (notExecuted.length > 0)
+ throw new Error(`Check(s) never executed — nothing to review: ${notExecuted.join(', ')}`);
+ return checkIds.map((id) => {
+ const check = byId.get(id)!;
+ return { checkId: check.id, resultId: check.result!.id };
+ });
+};
+
+/** Merge two review logs by event id, oldest first — an export re-read changes nothing. */
+export const mergeLocalReviewEvents = (
+ ...logs: (LocalReviewEvent[] | undefined)[]
+): LocalReviewEvent[] => {
+ const byId = new Map<string, LocalReviewEvent>();
+ for (const events of logs) for (const event of events ?? []) byId.set(event.id, event);
+ return [...byId.values()].sort(
+ (a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id),
+ );
+};