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.

πŸ› fix(acceptance): let a local report accept or reject the delivery (#21947)

AmAzing-83557c66859e
diff --git a/apps/cli/src/commands/acceptance/index.ts b/apps/cli/src/commands/acceptance/index.ts
index 3c024610087..887d54eade3 100644
--- a/apps/cli/src/commands/acceptance/index.ts
+++ b/apps/cli/src/commands/acceptance/index.ts
@@ -26,6 +26,7 @@ import {
responseLanguageSettingsUrl,
unsetLanguageWarning,
} from './language';
+import { decideLocalAcceptance } from './local/decision';
import { localAcceptanceTarget, readLocalBundle } from './local/localBundle';
import { isSignedOut, LOCAL_MODE_INSTRUCTION } from './local/mode';
import { publishAction, withPublishOptions } from './local/publish';
@@ -706,10 +707,14 @@ export function registerAcceptanceCommands(parent: Command, options?: { deprecat
acceptance
.command('accept <idOrSubject>')
- .description('Accept the delivery β€” the terminal user decision that closes the acceptance')
+ .description(
+ 'Accept the delivery β€” the terminal user decision that closes the acceptance; a local acceptance directory records it offline',
+ )
.option('--comment <text>', 'Optional note recorded with the decision')
.option('--json [fields]', 'Output JSON')
.action(async (idOrSubject: string, options: { comment?: string; json?: boolean | string }) => {
+ const local = localAcceptanceTarget(idOrSubject);
+ if (local) return decideLocalAcceptance(local, 'accept', options);
const id = await resolveAcceptanceId(idOrSubject);
const client = await getTrpcClient();
const result = await client.acceptance.accept.mutate({ comment: options.comment, id });
@@ -726,10 +731,14 @@ export function registerAcceptanceCommands(parent: Command, options?: { deprecat
acceptance
.command('reject <idOrSubject>')
- .description('Reject the delivery β€” the comment seeds the next repair round')
+ .description(
+ 'Reject the delivery β€” the comment seeds the next repair round; a local acceptance directory records it offline',
+ )
.requiredOption('--comment <text>', 'Why the delivery is rejected (the re-tasking input)')
.option('--json [fields]', 'Output JSON')
.action(async (idOrSubject: string, options: { comment: string; json?: boolean | string }) => {
+ const local = localAcceptanceTarget(idOrSubject);
+ if (local) return decideLocalAcceptance(local, 'reject', options);
const id = await resolveAcceptanceId(idOrSubject);
const client = await getTrpcClient();
const result = await client.acceptance.reject.mutate({ comment: options.comment, id });
diff --git a/apps/cli/src/commands/acceptance/local/acceptanceDir.ts b/apps/cli/src/commands/acceptance/local/acceptanceDir.ts
index 911967fffba..6db301bfeb6 100644
--- a/apps/cli/src/commands/acceptance/local/acceptanceDir.ts
+++ b/apps/cli/src/commands/acceptance/local/acceptanceDir.ts
@@ -5,6 +5,8 @@ import path from 'node:path';
import type { LocalAcceptanceInfo } from '@lobechat/utils/verify/localAcceptance';
import { LOCAL_ACCEPTANCE_FORMAT } from '@lobechat/utils/verify/localAcceptance';
+import { ACCEPTANCE_DIR } from '../../../utils/acceptanceDir';
+
// ============================================
// A local acceptance is a directory under `.acceptances/`: one subdirectory
// per immutable round, plus `acceptance.json` (its identity), `reviews.json`
@@ -35,6 +37,19 @@ export const resolveAcceptanceDir = (target: string): string | undefined => {
return undefined;
};
+/**
+ * How a command should name an acceptance directory: from the project root
+ * when it sits under an `.acceptances/` tree (independent of the shell's
+ * working directory), else its absolute path β€” the only unambiguous name for
+ * a directory kept anywhere else.
+ */
+export const commandAcceptanceDir = (acceptanceDir: string): string => {
+ const segments = path.resolve(acceptanceDir).split(path.sep);
+ const index = segments.lastIndexOf(ACCEPTANCE_DIR);
+ if (index <= 0 || index === segments.length - 1) return path.resolve(acceptanceDir);
+ return segments.slice(index).join('/');
+};
+
/** Round directory names, oldest first β€” the order `new_round`'s timestamps sort in. */
export const listRoundDirs = (acceptanceDir: string): string[] =>
readdirSync(acceptanceDir, { withFileTypes: true })
diff --git a/apps/cli/src/commands/acceptance/local/decision.test.ts b/apps/cli/src/commands/acceptance/local/decision.test.ts
new file mode 100644
index 00000000000..dfe7d903152
--- /dev/null
+++ b/apps/cli/src/commands/acceptance/local/decision.test.ts
@@ -0,0 +1,87 @@
+import { existsSync, 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 { REPORT_FILE, REVIEWS_FILE } from './acceptanceDir';
+import { decideLocalAcceptance } from './decision';
+import { loadLocalAcceptance } from './localAcceptance';
+import { readLocalBundle } from './localBundle';
+import { createLocalAcceptance, firstRound } from './testUtils';
+
+const { outputJson } = vi.hoisted(() => ({ outputJson: vi.fn() }));
+vi.mock('../../../utils/format', async (original) => ({
+ ...(await original<typeof Format>()),
+ outputJson,
+}));
+
+const TEMPLATE =
+ '<html><head><!--ACCEPTANCE_LOCAL_TITLE--></head><body><!--ACCEPTANCE_LOCAL_DATA--></body></html>';
+
+describe('lh acceptance accept|reject <acceptanceDir>', () => {
+ let fixture: ReturnType<typeof createLocalAcceptance>;
+
+ beforeEach(() => {
+ vi.resetAllMocks();
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ fixture = createLocalAcceptance([firstRound()]);
+ vi.stubEnv('LOBEHUB_ACCEPTANCE_DOWNLOADS', path.join(fixture.root, 'Downloads'));
+ vi.stubEnv('HOME', fixture.root);
+ const template = path.join(fixture.root, 'template.html');
+ writeFileSync(template, TEMPLATE);
+ vi.stubEnv('LOBEHUB_ACCEPTANCE_REPORT_TEMPLATE', template);
+ loadLocalAcceptance(fixture.acceptanceDir, { create: true });
+ });
+
+ afterEach(() => {
+ fixture.cleanup();
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ });
+
+ it('accepts the delivery offline, so view reads it accepted', async () => {
+ const reportPath = path.join(fixture.acceptanceDir, REPORT_FILE);
+ writeFileSync(reportPath, 'stale');
+
+ await decideLocalAcceptance(fixture.acceptanceDir, 'accept', { json: true });
+
+ expect(outputJson.mock.calls[0]![0]).toMatchObject({
+ decision: { action: 'accept', kind: 'decision', roundIndex: 1 },
+ reportPath,
+ status: 'accepted',
+ });
+ expect(readLocalBundle(fixture.acceptanceDir).bundle.acceptance.status).toBe('accepted');
+ // The page carries the decision too.
+ expect(readFileSync(reportPath, 'utf8')).toContain('"kind":"decision"');
+ });
+
+ it('records the reject reason the next round reads, without a page to refresh', async () => {
+ await decideLocalAcceptance(fixture.acceptanceDir, 'reject', {
+ comment: 'Focus is lost',
+ json: true,
+ });
+ const { bundle } = readLocalBundle(fixture.acceptanceDir);
+ expect(bundle.acceptance.status).toBe('rejected');
+ expect(bundle.rounds[0]!.run.decisionDetail?.comment).toBe('Focus is lost');
+ expect(outputJson.mock.calls[0]![0].reportPath).toBeNull();
+ expect(existsSync(path.join(fixture.acceptanceDir, REPORT_FILE))).toBe(false);
+ });
+
+ it('refuses a second decision on the same round, like the server', async () => {
+ await decideLocalAcceptance(fixture.acceptanceDir, 'accept', { json: true });
+ const error = vi.spyOn(log, 'error').mockImplementation(() => {});
+ const exit = vi.spyOn(process, 'exit').mockImplementation((() => {
+ throw new Error('exit');
+ }) as never);
+
+ await expect(
+ decideLocalAcceptance(fixture.acceptanceDir, 'reject', { comment: 'late' }),
+ ).rejects.toThrow('exit');
+ expect(error).toHaveBeenCalledWith('This delivery has already been accepted');
+ expect(exit).toHaveBeenCalledWith(1);
+ const saved = JSON.parse(readFileSync(path.join(fixture.acceptanceDir, REVIEWS_FILE), 'utf8'));
+ expect(saved.events).toHaveLength(1);
+ });
+});
diff --git a/apps/cli/src/commands/acceptance/local/decision.ts b/apps/cli/src/commands/acceptance/local/decision.ts
new file mode 100644
index 00000000000..fb4659f2000
--- /dev/null
+++ b/apps/cli/src/commands/acceptance/local/decision.ts
@@ -0,0 +1,81 @@
+import { randomUUID } from 'node:crypto';
+import { existsSync } from 'node:fs';
+import path from 'node:path';
+
+import type { LocalDeliveryDecision } from '@lobechat/utils/verify/localAcceptance';
+import {
+ assembleLocalAcceptance,
+ localDecisionEvent,
+ mergeLocalReviewEvents,
+} from '@lobechat/utils/verify/localAcceptance';
+import pc from 'picocolors';
+
+import { outputJson } from '../../../utils/format';
+import { log } from '../../../utils/logger';
+import { REPORT_FILE } from './acceptanceDir';
+import { loadLocalAcceptance, writeReviewLog } from './localAcceptance';
+import { writeReportPage } from './render';
+
+/**
+ * `lh acceptance accept|reject <acceptanceDir>`: the decision on the whole
+ * delivery, recorded in the local review log the way the report page records
+ * it, with the server's refusals. A rendered `report.html` is refreshed so the
+ * page shows the decision too.
+ */
+export async function decideLocalAcceptance(
+ target: string,
+ action: LocalDeliveryDecision,
+ options: { comment?: string; json?: boolean | string },
+) {
+ // Reading first files any review the page saved since, so the decision
+ // lands on the acceptance as the reviewer last left it.
+ const read = loadLocalAcceptance(target);
+ const decide = () => {
+ try {
+ return localDecisionEvent(assembleLocalAcceptance(read.source), {
+ action,
+ comment: options.comment,
+ createdAt: new Date().toISOString(),
+ id: randomUUID(),
+ });
+ } catch (error) {
+ log.error(error instanceof Error ? error.message : String(error));
+ process.exit(1);
+ }
+ };
+ const event = decide();
+
+ const reviews = mergeLocalReviewEvents(read.source.reviews, [event]);
+ writeReviewLog(read.acceptanceDir, read.info.id, reviews);
+ const source = { ...read.source, reviews };
+ const { acceptance } = assembleLocalAcceptance(source);
+
+ let reportPath: string | null = null;
+ if (existsSync(path.join(read.acceptanceDir, REPORT_FILE))) {
+ try {
+ reportPath = writeReportPage(read.acceptanceDir, source);
+ } catch (error) {
+ log.warn(
+ `Decision recorded, but report.html was not refreshed: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+ }
+
+ const result = {
+ acceptanceDir: read.acceptanceDir,
+ acceptanceId: read.info.id,
+ decision: event,
+ reportPath,
+ status: acceptance.status,
+ };
+ if (options.json !== undefined) {
+ outputJson(result, typeof options.json === 'string' ? options.json : undefined);
+ return;
+ }
+ console.log(
+ action === 'accept'
+ ? `${pc.green('βœ“')} Delivery accepted (${read.info.id}, local)`
+ : `${pc.red('βœ—')} Delivery rejected (${read.info.id}, local) β€” the next round re-opens it`,
+ );
+ if (reportPath) console.log(`${pc.bold('report')}: ${reportPath}`);
+}
diff --git a/apps/cli/src/commands/acceptance/local/localAcceptance.test.ts b/apps/cli/src/commands/acceptance/local/localAcceptance.test.ts
index cc9a51791d9..03d93b8ddd0 100644
--- a/apps/cli/src/commands/acceptance/local/localAcceptance.test.ts
+++ b/apps/cli/src/commands/acceptance/local/localAcceptance.test.ts
@@ -1,4 +1,4 @@
-import { mkdirSync, readFileSync, utimesSync, writeFileSync } from 'node:fs';
+import { mkdirSync, readFileSync, renameSync, utimesSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import { assembleLocalAcceptance } from '@lobechat/utils/verify/localAcceptance';
@@ -184,4 +184,17 @@ describe('loadLocalAcceptance', () => {
it('needs a render before read-only commands', () => {
expect(() => loadLocalAcceptance(fixture.acceptanceDir)).toThrow('no acceptance.json yet');
});
+
+ it('names the directory the way a later command must, wherever it is kept', () => {
+ // From the project root, whatever the shell's working directory.
+ expect(loadLocalAcceptance(fixture.acceptanceDir, { create: true }).source.acceptanceDir).toBe(
+ '.acceptances/standalone-demo',
+ );
+
+ // Kept outside `.acceptances/`: only its absolute path names it.
+ const elsewhere = path.join(fixture.root, 'qa', 'rename-review');
+ mkdirSync(path.dirname(elsewhere), { recursive: true });
+ renameSync(fixture.acceptanceDir, elsewhere);
+ expect(loadLocalAcceptance(elsewhere).source.acceptanceDir).toBe(elsewhere);
+ });
});
diff --git a/apps/cli/src/commands/acceptance/local/localAcceptance.ts b/apps/cli/src/commands/acceptance/local/localAcceptance.ts
index 168f6791bd9..9c3f6c6f571 100644
--- a/apps/cli/src/commands/acceptance/local/localAcceptance.ts
+++ b/apps/cli/src/commands/acceptance/local/localAcceptance.ts
@@ -14,6 +14,7 @@ import {
} from '@lobechat/utils/verify/localAcceptance';
import {
+ commandAcceptanceDir,
ensureAcceptanceInfo,
listRoundDirs,
readAcceptanceInfo,
@@ -173,6 +174,7 @@ export function loadLocalAcceptance(
rounds,
source: {
acceptance: info,
+ acceptanceDir: commandAcceptanceDir(acceptanceDir),
format: LOCAL_ACCEPTANCE_FORMAT,
generatedAt: new Date().toISOString(),
reviews: events,
diff --git a/apps/cli/src/commands/acceptance/local/publish.test.ts b/apps/cli/src/commands/acceptance/local/publish.test.ts
index 3f448cd7526..a67221f6168 100644
--- a/apps/cli/src/commands/acceptance/local/publish.test.ts
+++ b/apps/cli/src/commands/acceptance/local/publish.test.ts
@@ -14,8 +14,10 @@ import { createLocalAcceptance, firstRound } from './testUtils';
const { client, ingestReportAction, outputJson } = vi.hoisted(() => ({
client: {
acceptance: {
+ accept: { mutate: vi.fn() },
addGroupFeedback: { mutate: vi.fn() },
getBundle: { query: vi.fn() },
+ reject: { mutate: vi.fn() },
reviewChecks: { mutate: vi.fn() },
},
},
@@ -49,7 +51,9 @@ const bothUploaded = [
{ checkItemId: 'rename', evidenceId: 'remote-api', position: 1 },
];
-const remoteBundle = (evidence: { id: string }[]) => ({
+/** `latestRunId` is the published acceptance's current round. */
+const remoteBundle = (evidence: { id: string }[], latestRunId = 'remote-run-1') => ({
+ rounds: [{ run: { id: latestRunId } }],
checks: [
{
id: 'criterion-rename',
@@ -276,6 +280,117 @@ describe('lh acceptance publish', () => {
expect(client.acceptance.addGroupFeedback.mutate).toHaveBeenCalledTimes(1);
});
+ it("carries the latest round's delivery decision last, bound to that round, once", 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 decision = {
+ action: 'accept' as const,
+ comment: 'Ship it',
+ createdAt: '2026-01-01T10:05:00.000Z',
+ id: 'event-2',
+ kind: 'decision' as const,
+ roundIndex: 1,
+ };
+ writeReviewLog(fixture.acceptanceDir, info.id, [accept, decision]);
+ 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.accept.mutate).toHaveBeenCalledWith({
+ comment: 'Ship it',
+ id: 'remote-acceptance',
+ roundId: 'remote-run-1',
+ });
+ expect(client.acceptance.reviewChecks.mutate.mock.invocationCallOrder[0]).toBeLessThan(
+ client.acceptance.accept.mutate.mock.invocationCallOrder[0]!,
+ );
+ expect(outputJson.mock.calls[0]![0].reviews).toEqual({ skipped: [], uploaded: 2 });
+
+ await publishAction(fixture.acceptanceDir, { json: true });
+ expect(client.acceptance.accept.mutate).toHaveBeenCalledTimes(1);
+ });
+
+ it('records a local send-back without dispatching it again, and leaves older rounds alone', async () => {
+ const { info } = loadLocalAcceptance(fixture.acceptanceDir, { create: true });
+ const second = firstRound();
+ second.dir = '20260102-090000-second';
+ fixture.addRound(second);
+ const reject = {
+ action: 'reject' as const,
+ comment: 'Focus is lost',
+ createdAt: '2026-01-02T10:00:00.000Z',
+ id: 'event-1',
+ kind: 'decision' as const,
+ roundIndex: 2,
+ };
+ // A decision on a round a later one re-opened is history, not the current call.
+ writeReviewLog(fixture.acceptanceDir, info.id, [
+ {
+ ...reject,
+ action: 'accept',
+ createdAt: '2026-01-01T10:00:00.000Z',
+ id: 'old',
+ roundIndex: 1,
+ },
+ reject,
+ ]);
+ ingestReportAction.mockResolvedValueOnce(ingested(1)).mockResolvedValueOnce(ingested(2));
+ client.acceptance.getBundle.query.mockResolvedValue(remoteBundle([], 'remote-run-2'));
+
+ await publishAction(fixture.acceptanceDir, { json: true });
+ expect(client.acceptance.accept.mutate).not.toHaveBeenCalled();
+ expect(client.acceptance.reject.mutate).toHaveBeenCalledWith({
+ comment: 'Focus is lost',
+ dispatch: false,
+ id: 'remote-acceptance',
+ roundId: 'remote-run-2',
+ });
+ });
+
+ it('refuses a decision once the published acceptance moved past the round it judged', async () => {
+ const { info } = loadLocalAcceptance(fixture.acceptanceDir, { create: true });
+ ingestReportAction.mockResolvedValueOnce(ingested(1));
+ await publishAction(fixture.acceptanceDir, { json: true, reviews: false });
+
+ // Online, someone ingested a newer round; locally the reviewer accepted round 1.
+ writeReviewLog(fixture.acceptanceDir, info.id, [
+ {
+ action: 'accept',
+ createdAt: '2026-01-01T10:00:00.000Z',
+ id: 'event-1',
+ kind: 'decision',
+ roundIndex: 1,
+ },
+ ]);
+ client.acceptance.getBundle.query.mockResolvedValue(remoteBundle([], 'remote-run-2'));
+
+ await publishAction(fixture.acceptanceDir, { json: true });
+ expect(client.acceptance.accept.mutate).not.toHaveBeenCalled();
+ expect(outputJson.mock.calls[1]![0].reviews).toEqual({
+ skipped: [
+ {
+ checkId: 'decision:accept',
+ reason: 'the published acceptance has a newer round than the one this decision judged',
+ },
+ ],
+ uploaded: 0,
+ });
+ const stored = JSON.parse(
+ readFileSync(path.join(fixture.acceptanceDir, ACCEPTANCE_FILE), 'utf8'),
+ );
+ expect(stored.remote.carriedReviews).toBeUndefined();
+ });
+
it('reports how to repair evidence a published round failed to upload', async () => {
loadLocalAcceptance(fixture.acceptanceDir, { create: true });
const failure = {
diff --git a/apps/cli/src/commands/acceptance/local/publish.ts b/apps/cli/src/commands/acceptance/local/publish.ts
index f647c1ee9ab..3a27fe77f4e 100644
--- a/apps/cli/src/commands/acceptance/local/publish.ts
+++ b/apps/cli/src/commands/acceptance/local/publish.ts
@@ -62,7 +62,14 @@ async function carryReviews(
event.roundIndex === latestRoundIndex &&
!done.has(`group:${event.id}`),
);
- if (standing.length === 0 && groupFeedback.length === 0) return carry;
+ // The delivery decision of the latest round moves last, once its feedback is
+ // there: it is what closes (or sends back) the published acceptance.
+ const decision = read.source.reviews.findLast(
+ (event): event is Extract<typeof event, { kind: 'decision' }> =>
+ event.kind === 'decision' && event.roundIndex === latestRoundIndex,
+ );
+ const pendingDecision = decision && !done.has(`decision:${decision.id}`) ? decision : undefined;
+ if (standing.length === 0 && groupFeedback.length === 0 && !pendingDecision) return carry;
const bundle: RemoteBundle = await client.acceptance.getBundle.query({
id: remote.acceptanceId,
@@ -128,6 +135,44 @@ async function carryReviews(
});
}
}
+ const latestDir = [...read.source.rounds]
+ .sort((a, b) => a.run.roundIndex - b.run.roundIndex)
+ .at(-1)?.dir;
+ const roundId = remote.rounds.find((round) => round.dir === latestDir)?.verifyRunId;
+ // Bound to the round it judged. The server checks `roundId` only for some
+ // subjects and otherwise stamps whatever round is newest, so a decision on a
+ // round that is no longer the published acceptance's current one is refused
+ // here rather than landing on a delivery nobody reviewed.
+ if (pendingDecision && (!roundId || bundle.rounds.at(-1)?.run.id !== roundId)) {
+ carry.skipped.push({
+ checkId: `decision:${pendingDecision.action}`,
+ reason: 'the published acceptance has a newer round than the one this decision judged',
+ });
+ } else if (pendingDecision) {
+ try {
+ if (pendingDecision.action === 'accept')
+ await client.acceptance.accept.mutate({
+ comment: pendingDecision.comment,
+ id: remote.acceptanceId,
+ roundId,
+ });
+ // Recorded only: the reviewer already handed the repair prompt over locally.
+ else
+ await client.acceptance.reject.mutate({
+ comment: pendingDecision.comment,
+ dispatch: false,
+ id: remote.acceptanceId,
+ roundId,
+ });
+ carry.carried.push(`decision:${pendingDecision.id}`);
+ carry.uploaded++;
+ } catch (error) {
+ carry.skipped.push({
+ checkId: `decision:${pendingDecision.action}`,
+ reason: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
return carry;
}
diff --git a/apps/cli/src/commands/acceptance/local/render.ts b/apps/cli/src/commands/acceptance/local/render.ts
index c6e4fd77637..acbf5378c84 100644
--- a/apps/cli/src/commands/acceptance/local/render.ts
+++ b/apps/cli/src/commands/acceptance/local/render.ts
@@ -3,6 +3,7 @@ import { writeFileSync } from 'node:fs';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
+import type { LocalAcceptanceSource } from '@lobechat/utils/verify/localAcceptance';
import type { Command } from 'commander';
import pc from 'picocolors';
@@ -47,6 +48,15 @@ const openInBrowser = (file: string) => {
}
};
+/** Write `report.html` from the acceptance as it stands now, and return its path. */
+export const writeReportPage = (acceptanceDir: string, source: LocalAcceptanceSource) => {
+ const run = source.rounds.at(-1)?.run;
+ const title = run?.title || run?.goal || path.basename(acceptanceDir);
+ const reportPath = path.join(acceptanceDir, REPORT_FILE);
+ writeFileSync(reportPath, renderReportHtml(readReportTemplate(), source, title));
+ return reportPath;
+};
+
/**
* Render a local acceptance into one offline page β€” the acceptance page,
* without LobeHub. Re-rendering after a new round or after the reviewer saved
@@ -83,9 +93,7 @@ export async function renderReportAction(reportDir: string, options: RenderRepor
'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 reportPath = writeReportPage(acceptanceDir, source);
const reportUrl = pathToFileURL(reportPath).toString();
if (options.open) openInBrowser(reportPath);
diff --git a/apps/workbench/src/localReport/LocalAcceptanceReport.tsx b/apps/workbench/src/localReport/LocalAcceptanceReport.tsx
index 8d5478b119e..07fa47f75ad 100644
--- a/apps/workbench/src/localReport/LocalAcceptanceReport.tsx
+++ b/apps/workbench/src/localReport/LocalAcceptanceReport.tsx
@@ -15,6 +15,7 @@ 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 { LocalDecision } from './LocalDecision';
import { LocalReviewBar } from './LocalReviewBar';
const styles = stylex.create({
@@ -49,8 +50,9 @@ const styles = stylex.create({
/**
* 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.
+ * atoms over the local bundle, and the decision on the whole delivery.
+ * 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');
@@ -67,6 +69,8 @@ export const LocalAcceptanceReport = ({ acceptanceId }: { acceptanceId: string }
<AcceptanceIdentity />
<AcceptanceGoal />
<AcceptanceCheckInventory />
+ {/* Deciding belongs where the evidence is, as on the hosted page. */}
+ <LocalDecision />
<section aria-label={t('acceptance.comments.title')}>
<Text as={'h2'}>{t('acceptance.comments.title')}</Text>
<ReadDiscussion />
diff --git a/apps/workbench/src/localReport/LocalDecision.tsx b/apps/workbench/src/localReport/LocalDecision.tsx
new file mode 100644
index 00000000000..06e3348ec1d
--- /dev/null
+++ b/apps/workbench/src/localReport/LocalDecision.tsx
@@ -0,0 +1,142 @@
+'use client';
+
+import { buildLocalAcceptanceRepairPrompt } from '@lobechat/prompts';
+import { copyToClipboard, toast } from '@lobehub/ui';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useAcceptanceScope } from '@/features/Acceptance/Viewer/AcceptanceScope';
+import { isException } from '@/features/Acceptance/Viewer/Checks/checkState';
+import DecisionBar from '@/features/Acceptance/Viewer/Review/DecisionBar';
+import { resolveDecisionView } from '@/features/Acceptance/Viewer/Review/decisionView';
+import FeedbackDrawer from '@/features/Acceptance/Viewer/Review/FeedbackDrawer';
+import {
+ openAcceptModal,
+ openGroupFeedbackModal,
+ openRejectModal,
+} from '@/features/Acceptance/Viewer/Review/modals';
+import { useAcceptanceBundle } from '@/features/Acceptance/Viewer/useAcceptanceBundle';
+import { useIsHydrated } from '@/hooks/useIsHydrated';
+import { verifyService } from '@/services/verify';
+
+import { getLocalReport } from './localReportData';
+import { saveReviewLog } from './saveReviewLog';
+
+/**
+ * The decision on the whole delivery, offline: the hosted decision bar over
+ * the local review log. Nothing can be sent back to an agent from here, so a
+ * send-back hands the reviewer the repair prompt, and every hand-off saves the
+ * review log the agent's CLI reads.
+ */
+export const LocalDecision = () => {
+ const { t } = useTranslation('verify');
+ const hydrated = useIsHydrated();
+ const { acceptanceId } = useAcceptanceScope();
+ const { data } = useAcceptanceBundle(acceptanceId);
+ const [pending, setPending] = useState(false);
+ const [feedbackOpen, setFeedbackOpen] = useState(false);
+ if (!data || data.acceptance.status === 'closed') return null;
+
+ const { acceptance, checks } = data;
+ const view = resolveDecisionView(data, t, { hydrated });
+ const report = getLocalReport();
+
+ const save = () => toast.success(t('acceptance.local.saved', { file: saveReviewLog() }));
+
+ const runAction = async (action: () => Promise<unknown>) => {
+ setPending(true);
+ try {
+ await action();
+ save();
+ return true;
+ } catch (cause) {
+ console.error('[acceptance:local-decision]', cause);
+ toast.error(cause instanceof Error ? cause.message : t('acceptance.actionError'));
+ return false;
+ } finally {
+ setPending(false);
+ }
+ };
+
+ const copyReview = async (rejectComment?: string) => {
+ await copyToClipboard(buildLocalAcceptanceRepairPrompt(report.acceptanceDir, rejectComment));
+ toast.success({ placement: 'top', title: t('acceptance.bar.copied') });
+ };
+
+ return (
+ <>
+ <DecisionBar
+ acceptedCount={view.acceptedCount}
+ embedded={false}
+ feedbackCount={view.feedbackEntries.filter((entry) => !entry.stale).length}
+ ignoredCount={view.ignoredCount}
+ needsFixCount={view.needsFixCount}
+ pending={pending}
+ rerunAvailable={false}
+ rerunPending={false}
+ state={view.barState}
+ statusText={view.statusText}
+ subText={view.subText}
+ totalCount={view.reviewTotal}
+ onOpenFeedback={() => setFeedbackOpen(true)}
+ onRerun={() => {}}
+ onAccept={() =>
+ openAcceptModal({
+ exceptions: checks.filter((check) => isException(check)).map((check) => check.title),
+ onConfirm: () => runAction(() => verifyService.acceptDelivery(acceptance.id)),
+ subjectTitle: data.subject.title ?? data.subject.id,
+ })
+ }
+ onAddComment={() =>
+ openGroupFeedbackModal({
+ description: t('acceptance.bar.addCommentDescription'),
+ groupLabel: t('acceptance.feedback.global'),
+ onConfirm: async (comment, fileIds) => {
+ try {
+ await verifyService.addGroupFeedback({
+ category: '',
+ comment,
+ fileIds: fileIds.length > 0 ? fileIds : undefined,
+ id: acceptance.id,
+ });
+ return true;
+ } catch (cause) {
+ toast.error(cause instanceof Error ? cause.message : t('acceptance.actionError'));
+ return false;
+ }
+ },
+ title: t('acceptance.bar.addComment'),
+ })
+ }
+ onCopyReview={async () => {
+ // The clipboard write needs the click's activation, so it goes first.
+ await copyReview();
+ if (report.unsavedCount() > 0) save();
+ }}
+ onRejectComment={() =>
+ openRejectModal({
+ acceptanceId: acceptance.id,
+ dispatchAvailable: false,
+ onConfirm: async (comment) => {
+ await copyReview(comment || undefined);
+ return runAction(() => verifyService.rejectDelivery(acceptance.id, comment));
+ },
+ })
+ }
+ />
+ <FeedbackDrawer
+ entries={view.feedbackEntries}
+ open={feedbackOpen}
+ onClose={() => setFeedbackOpen(false)}
+ onJumpToCheck={(checkId) => {
+ setFeedbackOpen(false);
+ setTimeout(() => {
+ document
+ .querySelector(`[data-check-row="${checkId}"]`)
+ ?.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ }, 80);
+ }}
+ />
+ </>
+ );
+};
diff --git a/apps/workbench/src/localReport/LocalReviewBar.tsx b/apps/workbench/src/localReport/LocalReviewBar.tsx
index 4470982d0d6..9c058ab746a 100644
--- a/apps/workbench/src/localReport/LocalReviewBar.tsx
+++ b/apps/workbench/src/localReport/LocalReviewBar.tsx
@@ -20,6 +20,7 @@ import { ProductLogo } from '@/components/Branding';
import { isCustomBranding } from '@/const/version';
import { getLocalReport } from './localReportData';
+import { saveReviewLog } from './saveReviewLog';
const styles = stylex.create({
command: {
@@ -47,28 +48,12 @@ const styles = stylex.create({
},
});
-/** `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.
+ * review log (see `saveReviewLog`).
*/
export const LocalReviewBar = () => {
const { t } = useTranslation('verify');
@@ -78,13 +63,10 @@ export const LocalReviewBar = () => {
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 publishCommand = `lh acceptance publish ${report.acceptanceDir}`;
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 }));
+ toast.success(t('acceptance.local.saved', { file: saveReviewLog() }));
};
return (
diff --git a/apps/workbench/src/localReport/localReportData.test.ts b/apps/workbench/src/localReport/localReportData.test.ts
index 548d5793321..47293d5276c 100644
--- a/apps/workbench/src/localReport/localReportData.test.ts
+++ b/apps/workbench/src/localReport/localReportData.test.ts
@@ -105,6 +105,13 @@ describe('local report data', () => {
expect(rerendered.bundle().checks[0]!.userReview).toMatchObject({ action: 'accept' });
});
+ it('hands commands the directory the CLI rendered from', async () => {
+ const custom = await openPage({ ...source(), acceptanceDir: '/work/qa/rename-review' });
+ expect(custom.acceptanceDir).toBe('/work/qa/rename-review');
+ // A page rendered before the CLI embedded it.
+ expect((await openPage(source())).acceptanceDir).toBe('.acceptances/standalone-rename');
+ });
+
it('refuses a page without acceptance data', async () => {
document.body.innerHTML = '';
vi.resetModules();
diff --git a/apps/workbench/src/localReport/localReportData.ts b/apps/workbench/src/localReport/localReportData.ts
index 543783d278e..016973d7ca0 100644
--- a/apps/workbench/src/localReport/localReportData.ts
+++ b/apps/workbench/src/localReport/localReportData.ts
@@ -73,6 +73,8 @@ const createLocalReport = () => {
};
return {
+ /** The acceptance directory as a command names it (see `LocalAcceptanceSource`). */
+ acceptanceDir: source.acceptanceDir ?? `.acceptances/${source.acceptance.subjectKey}`,
acceptanceId: id,
append: (event: LocalReviewEvent) => {
pending = [...pending, event];
diff --git a/apps/workbench/src/localReport/saveReviewLog.ts b/apps/workbench/src/localReport/saveReviewLog.ts
new file mode 100644
index 00000000000..7f91e53544d
--- /dev/null
+++ b/apps/workbench/src/localReport/saveReviewLog.ts
@@ -0,0 +1,30 @@
+import { getLocalReport } from './localReportData';
+
+/** `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);
+};
+
+/**
+ * Download every decision made on this acceptance as its review log, and
+ * return the file name. A file opened from disk cannot write next to itself;
+ * the CLI picks the newest download up on its next `view` or `feedback` and
+ * files it beside the rounds.
+ */
+export const saveReviewLog = () => {
+ const report = getLocalReport();
+ const fileName = reviewExportFileName(report.acceptanceId);
+ download(fileName, `${JSON.stringify(report.exportLog(), null, 2)}\n`);
+ report.markExported();
+ return fileName;
+};
diff --git a/apps/workbench/src/localReport/stubs/verifyService.test.ts b/apps/workbench/src/localReport/stubs/verifyService.test.ts
new file mode 100644
index 00000000000..5126df8dfae
--- /dev/null
+++ b/apps/workbench/src/localReport/stubs/verifyService.test.ts
@@ -0,0 +1,114 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The offline report decides the whole delivery the way the hosted page does:
+ * the decision lands in the local review log, and the acceptance settles.
+ */
+import type { LocalAcceptanceSource } from '@lobechat/utils/verify/localAcceptance';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const source = (settled: boolean): 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: settled
+ ? {
+ content: null,
+ failedChecks: 0,
+ overallConfidence: null,
+ passedChecks: 1,
+ summary: null,
+ totalChecks: 1,
+ uncertainChecks: null,
+ verdict: 'passed',
+ }
+ : 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',
+ },
+ },
+ ],
+});
+
+/** A fresh page load: new document data, new module instances, 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');
+ const { verifyService } = await import('./verifyService');
+ return { report: getLocalReport(), verifyService };
+};
+
+describe('local verifyService delivery decisions', () => {
+ beforeEach(() => localStorage.clear());
+ afterEach(() => {
+ document.body.innerHTML = '';
+ });
+
+ it('accepts the delivery into the review log, and keeps it across reloads', async () => {
+ const { report, verifyService } = await openPage(source(true));
+ await verifyService.reviewChecks({ action: 'accept', checkItemIds: ['rename'] });
+ expect(report.bundle().acceptance.status).toBe('delivered');
+
+ const accepted = await verifyService.acceptDelivery('acc-1');
+ expect(accepted.status).toBe('accepted');
+ expect(report.exportLog().events.at(-1)).toMatchObject({
+ action: 'accept',
+ kind: 'decision',
+ roundIndex: 1,
+ });
+
+ const reloaded = await openPage(source(true));
+ expect(reloaded.report.bundle().acceptance.status).toBe('accepted');
+ await expect(reloaded.verifyService.rejectDelivery('acc-1', 'late')).rejects.toThrow(
+ 'already been accepted',
+ );
+ });
+
+ it('rejects with the reason the next round reads', async () => {
+ const { report, verifyService } = await openPage(source(true));
+ await verifyService.rejectDelivery('acc-1', 'Focus is lost');
+ const round = report.bundle().rounds[0]!.run;
+ expect(report.bundle().acceptance.status).toBe('rejected');
+ expect(round.userDecision).toBe('reject');
+ expect(round.decisionDetail?.comment).toBe('Focus is lost');
+ });
+
+ it('refuses a decision before the round settles, like the server', async () => {
+ const { verifyService } = await openPage(source(false));
+ await expect(verifyService.acceptDelivery('acc-1')).rejects.toThrow('still in progress');
+ });
+});
diff --git a/apps/workbench/src/localReport/stubs/verifyService.ts b/apps/workbench/src/localReport/stubs/verifyService.ts
index d3157cb60fe..18c6687c92b 100644
--- a/apps/workbench/src/localReport/stubs/verifyService.ts
+++ b/apps/workbench/src/localReport/stubs/verifyService.ts
@@ -1,5 +1,6 @@
import type { AcceptanceCheckReviewAction, AcceptanceReviewAnnotation } from '@lobechat/types';
-import { localReviewTargets } from '@lobechat/utils/verify/localAcceptance';
+import type { LocalDeliveryDecision } from '@lobechat/utils/verify/localAcceptance';
+import { localDecisionEvent, localReviewTargets } from '@lobechat/utils/verify/localAcceptance';
import { localEventId } from '../localEventId';
import { getLocalReport } from '../localReportData';
@@ -48,6 +49,24 @@ const addGroupFeedback = async (input: {
return { entry: { ...entry, roundIndex }, success: true };
};
+const decideDelivery = (action: LocalDeliveryDecision, comment?: string) => {
+ const report = getLocalReport();
+ report.append(
+ localDecisionEvent(report.bundle(), {
+ action,
+ comment,
+ createdAt: new Date().toISOString(),
+ id: localEventId(),
+ }),
+ );
+ return report.bundle().acceptance;
+};
+
+const acceptDelivery = async (_id: string, comment?: string) => decideDelivery('accept', comment);
+
+/** Nothing to send the delivery back to: the page hands the repair prompt over itself. */
+const rejectDelivery = async (_id: string, comment?: string) => decideDelivery('reject', comment);
+
const adjudicateProposal = async (): Promise<never> => {
throw needsPublishedAcceptance('Review proposals');
};
@@ -59,8 +78,10 @@ const adjudicateProposal = async (): Promise<never> => {
* refusals β€” so the page answers a click exactly as the hosted one would.
*/
export const verifyService = {
+ acceptDelivery,
addGroupFeedback,
adjudicateProposal,
getAcceptanceBundle,
+ rejectDelivery,
reviewChecks,
};
diff --git a/packages/prompts/src/prompts/verify/index.test.ts b/packages/prompts/src/prompts/verify/index.test.ts
index f832d1c9d27..1c6fec756bf 100644
--- a/packages/prompts/src/prompts/verify/index.test.ts
+++ b/packages/prompts/src/prompts/verify/index.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, it } from 'vitest';
-import { buildAcceptanceRepairPrompt, buildVerifierPrompt } from './index';
+import {
+ buildAcceptanceRepairPrompt,
+ buildLocalAcceptanceRepairPrompt,
+ buildVerifierPrompt,
+} from './index';
const checkItem = {
id: 'check-1',
@@ -57,3 +61,15 @@ describe('buildAcceptanceRepairPrompt', () => {
expect(buildAcceptanceRepairPrompt('acc-1')).toMatch(/^Use the LobeHub CLI/);
});
});
+
+describe('buildLocalAcceptanceRepairPrompt', () => {
+ it('reads feedback from the acceptance directory and renders the repair back into it', () => {
+ const prompt = buildLocalAcceptanceRepairPrompt('.acceptances/task-T-12', 'Focus is lost');
+ expect(
+ prompt.startsWith('The reviewer sent this delivery back with this reason:\n\nFocus is lost'),
+ ).toBe(true);
+ expect(prompt).toContain('lh acceptance feedback .acceptances/task-T-12 --actionable');
+ expect(prompt).toContain('lh acceptance run render <roundDir>');
+ expect(prompt).not.toContain('ingest');
+ });
+});
diff --git a/packages/prompts/src/prompts/verify/index.ts b/packages/prompts/src/prompts/verify/index.ts
index f529278383a..df6b60b7a83 100644
--- a/packages/prompts/src/prompts/verify/index.ts
+++ b/packages/prompts/src/prompts/verify/index.ts
@@ -108,3 +108,16 @@ Every entry it prints (per-check comments, circled-region annotations on the evi
? `publish the repaired delivery to this Task's own acceptance, following the Task verification instructions. The standing Site acceptance ${acceptanceId} is the source discussion, not an ingest target. Include a link to that source in the repair report, and post the repair acceptance and accessible preview back to that discussion using the acceptance comment CLI.`
: 'ingest the new result back into the SAME acceptance (reuse the existing check ids, and use supersedes for any check whose meaning changed).'
} Do not resolve human review threads: the reviewer confirms whether the fix works. Keep the final report in the same language the previous rounds used.`;
+
+/**
+ * The send-back prompt for a delivery reviewed in a local (offline) report.
+ * Same handoff as {@link buildAcceptanceRepairPrompt}, but the acceptance is a
+ * directory: the feedback is the review the reviewer saved from `report.html`,
+ * and the repaired round is rendered back into that directory, not ingested.
+ */
+export const buildLocalAcceptanceRepairPrompt = (acceptanceDir: string, rejectComment?: string) =>
+ `${rejectComment ? `The reviewer sent this delivery back with this reason:\n\n${rejectComment}\n\n` : ''}Use the LobeHub CLI to read the latest review feedback for the local acceptance ${acceptanceDir}:
+
+lh acceptance feedback ${acceptanceDir} --actionable
+
+It reads the review the reviewer saved from the acceptance's report.html; if it finds no saved review, ask the reviewer to click "Save reviews" in the report first. Every entry it prints (per-check comments and circled-region annotations on the evidence screenshots) supplies the review context. Fix the code item by item; then re-run verification, write the new round into the SAME acceptance directory (reuse the existing check ids, and use supersedes for any check whose meaning changed) and render it with \`lh acceptance run render <roundDir>\`. Keep the final report in the same language the previous rounds used.`;
diff --git a/packages/utils/src/verify/localAcceptance.test.ts b/packages/utils/src/verify/localAcceptance.test.ts
index 6962df0bf23..4ac938498e0 100644
--- a/packages/utils/src/verify/localAcceptance.test.ts
+++ b/packages/utils/src/verify/localAcceptance.test.ts
@@ -4,6 +4,7 @@ import {
assembleLocalAcceptance,
localAcceptanceComments,
type LocalAcceptanceSource,
+ localDecisionEvent,
type LocalReviewEvent,
localReviewTargets,
type LocalRoundSource,
@@ -202,6 +203,108 @@ describe('assembleLocalAcceptance', () => {
// An accept is sticky across rounds.
expect(repaired.checks[1]!.userReview).toMatchObject({ action: 'accept', stale: false });
});
+
+ it('settles the delivery only through a decision on the current round', () => {
+ const rounds = [round(1, [{ id: 'rename', title: 'Rename keeps focus', verdict: 'passed' }])];
+ const reviews: LocalReviewEvent[] = [
+ {
+ action: 'accept',
+ createdAt: '2026-01-01T10:00:00.000Z',
+ id: 'ev-1',
+ kind: 'checks',
+ roundIndex: 1,
+ targets: [{ checkId: 'rename', resultId: 'r1-rename' }],
+ },
+ {
+ category: 'Rename',
+ comment: 'Also check keyboard-only',
+ createdAt: '2026-01-01T10:01:00.000Z',
+ id: 'ev-2',
+ kind: 'group',
+ roundIndex: 1,
+ },
+ ];
+
+ // Every check accepted is still a delivery awaiting its decision.
+ expect(assembleLocalAcceptance(source(rounds, reviews)).acceptance.status).toBe('delivered');
+
+ const accepted = assembleLocalAcceptance(
+ source(rounds, [
+ ...reviews,
+ {
+ action: 'accept',
+ comment: 'Ship it',
+ createdAt: '2026-01-01T10:02:00.000Z',
+ id: 'ev-3',
+ kind: 'decision',
+ roundIndex: 1,
+ },
+ ]),
+ );
+ expect(accepted.acceptance.status).toBe('accepted');
+ expect(accepted.acceptance.completedAt?.toISOString()).toBe('2026-01-01T10:02:00.000Z');
+ expect(accepted.rounds[0]!.run.userDecision).toBe('accept');
+ expect(accepted.rounds[0]!.run.decisionDetail).toMatchObject({
+ comment: 'Ship it',
+ decidedAt: '2026-01-01T10:02:00.000Z',
+ groupFeedback: [{ category: 'Rename', comment: 'Also check keyboard-only' }],
+ });
+
+ const rejected = [
+ {
+ action: 'reject' as const,
+ comment: 'Focus is lost',
+ createdAt: '2026-01-01T10:02:00.000Z',
+ id: 'ev-3',
+ kind: 'decision' as const,
+ roundIndex: 1,
+ },
+ ];
+ expect(assembleLocalAcceptance(source(rounds, rejected)).acceptance.status).toBe('rejected');
+ // A newer round re-opens a rejected delivery.
+ const reopened = assembleLocalAcceptance(
+ source(
+ [...rounds, round(2, [{ id: 'rename', title: 'Rename keeps focus', verdict: 'passed' }])],
+ rejected,
+ ),
+ );
+ expect(reopened.acceptance.status).toBe('delivered');
+ expect(reopened.rounds[0]!.run.userDecision).toBe('reject');
+ });
+});
+
+describe('localDecisionEvent', () => {
+ const at = { createdAt: '2026-01-01T10:00:00.000Z', id: 'ev-d' };
+ const rounds = [round(1, [{ id: 'rename', title: 'Rename', verdict: 'passed' }])];
+
+ it('records the decision on the current round', () => {
+ expect(
+ localDecisionEvent(assembleLocalAcceptance(source(rounds)), {
+ ...at,
+ action: 'reject',
+ comment: ' Focus is lost ',
+ }),
+ ).toEqual({
+ ...at,
+ action: 'reject',
+ comment: 'Focus is lost',
+ kind: 'decision',
+ roundIndex: 1,
+ });
+ });
+
+ it('refuses a decided or unsettled delivery, like the server', () => {
+ const decided = assembleLocalAcceptance(
+ source(rounds, [{ ...at, action: 'accept', kind: 'decision', roundIndex: 1 }]),
+ );
+ expect(() => localDecisionEvent(decided, { ...at, action: 'reject' })).toThrow(
+ 'already been accepted',
+ );
+ const open = assembleLocalAcceptance(source([{ ...rounds[0]!, report: null }]));
+ expect(() => localDecisionEvent(open, { ...at, action: 'accept' })).toThrow(
+ 'still in progress (verifying)',
+ );
+ });
});
describe('localReviewTargets', () => {
diff --git a/packages/utils/src/verify/localAcceptance.ts b/packages/utils/src/verify/localAcceptance.ts
index 0f80a58be68..e8d53a8689a 100644
--- a/packages/utils/src/verify/localAcceptance.ts
+++ b/packages/utils/src/verify/localAcceptance.ts
@@ -182,8 +182,22 @@ export type LocalReviewEvent =
id: string;
kind: 'group';
roundIndex: number;
+ }
+ | {
+ /**
+ * The reviewer's decision on the whole delivery of `roundIndex` β€” what
+ * `acceptance.accept` / `acceptance.reject` stamp on the current round.
+ */
+ action: LocalDeliveryDecision;
+ comment?: string;
+ createdAt: IsoDate;
+ id: string;
+ kind: 'decision';
+ roundIndex: number;
};
+export type LocalDeliveryDecision = 'accept' | 'reject';
+
/** `reviews.json` β€” the local review log of one acceptance. */
export interface LocalReviewLog {
acceptanceId: string;
@@ -194,6 +208,12 @@ export interface LocalReviewLog {
/** Everything a local report renders from β€” what the CLI embeds into `report.html`. */
export interface LocalAcceptanceSource {
acceptance: LocalAcceptanceInfo;
+ /**
+ * The acceptance directory as a command names it: `.acceptances/<key>` from
+ * the project root, or an absolute path for one kept elsewhere. Pages
+ * rendered before it existed assume `.acceptances/<subjectKey>`.
+ */
+ acceptanceDir?: string;
format: typeof LOCAL_ACCEPTANCE_FORMAT;
generatedAt: IsoDate;
reviews: LocalReviewEvent[];
@@ -208,7 +228,7 @@ interface LocalAcceptanceRow {
config: AcceptanceConfig | null;
createdAt: Date;
id: string;
- metadata: AcceptanceMetadata | null;
+ metadata: AcceptanceMetadata;
projectId: string | null;
requirement: string | null;
status: AcceptanceStatus;
@@ -350,6 +370,8 @@ export interface LocalAcceptanceBundle {
author: { avatar: string | null; fullName: string | null; id: string; username: string | null };
canCollaborate: false;
canReject: boolean;
+ /** Feedback hand-offs to an agent are a LobeHub feature. */
+ canRequestRepair: false;
canReview: boolean;
checks: LocalCheck[];
collaboration: null;
@@ -358,7 +380,9 @@ export interface LocalAcceptanceBundle {
latestReport: LocalReportRow | null;
origin: null;
pullRequests: LocalPullRequest[];
+ repair: null;
repairDispatchAvailable: false;
+ repairSource: null;
rounds: { report: LocalReportRow | null; run: LocalRunRow; usage: null }[];
subject: { id: string; title: string | null; type: AcceptanceSubjectType };
}
@@ -562,6 +586,19 @@ export const assembleLocalAcceptance = (source: LocalAcceptanceSource): LocalAcc
}
const run = runByIndex.get(event.roundIndex);
if (!run) continue;
+ if (event.kind === 'decision') {
+ // A later decision on the same round replaces the earlier one, as the
+ // server's `setDecision` does; the round's group feedback stays.
+ const groupFeedback = run.decisionDetail?.groupFeedback;
+ run.userDecision = event.action;
+ run.decisionDetail = {
+ decidedAt: event.createdAt,
+ decidedBy: LOCAL_ACCEPTANCE_USER_ID,
+ ...(event.comment ? { comment: event.comment } : {}),
+ ...(groupFeedback ? { groupFeedback } : {}),
+ };
+ continue;
+ }
run.decisionDetail = {
...run.decisionDetail,
groupFeedback: [
@@ -597,18 +634,30 @@ export const assembleLocalAcceptance = (source: LocalAcceptanceSource): LocalAcc
const updatedAt = current?.createdAt ?? createdAt;
const subject = localSubjectFromKey(info.subjectKey);
const title = current?.title || current?.goal || null;
+ // Only a decision on the current round settles the delivery: a newer round
+ // re-opens it, the way a new round re-opens a rejected acceptance online.
+ const decision = current?.userDecision;
+ const status: AcceptanceStatus =
+ decision === 'accept'
+ ? 'accepted'
+ : decision === 'reject'
+ ? 'rejected'
+ : current
+ ? statusFromRound(current, reports.has(current.id))
+ : 'pending';
return {
acceptance: {
accessedAt: updatedAt,
- completedAt: null,
+ completedAt:
+ status === 'accepted' ? date(current?.decisionDetail?.decidedAt, updatedAt) : null,
config: {},
createdAt,
id: info.id,
- metadata: title ? { title } : null,
+ metadata: title ? { title } : {},
projectId: null,
requirement: info.requirement,
- status: current ? statusFromRound(current, reports.has(current.id)) : 'pending',
+ status,
subjectId: subject.id,
subjectType: subject.type,
updatedAt,
@@ -620,6 +669,7 @@ export const assembleLocalAcceptance = (source: LocalAcceptanceSource): LocalAcc
author: { avatar: null, fullName: null, id: LOCAL_ACCEPTANCE_USER_ID, username: null },
canCollaborate: false,
canReject: true,
+ canRequestRepair: false,
canReview: true,
checks,
collaboration: null,
@@ -628,7 +678,9 @@ export const assembleLocalAcceptance = (source: LocalAcceptanceSource): LocalAcc
latestReport,
origin: null,
pullRequests: pullRequestsOf(runs),
+ repair: null,
repairDispatchAvailable: false,
+ repairSource: null,
rounds,
subject: { id: subject.id, title, type: subject.type },
};
@@ -707,6 +759,35 @@ export const localReviewTargets = (
});
};
+/**
+ * The reviewer's decision on the whole delivery, as the event the review log
+ * records. Same refusals as the server's `requireDecidableAcceptance`: the
+ * current round must have settled, and a decided delivery stays decided until
+ * a newer round re-opens it.
+ */
+export const localDecisionEvent = (
+ bundle: Pick<LocalAcceptanceBundle, 'acceptance' | 'rounds'>,
+ input: { action: LocalDeliveryDecision; comment?: string; createdAt: IsoDate; id: string },
+): Extract<LocalReviewEvent, { kind: 'decision' }> => {
+ const { status } = bundle.acceptance;
+ if (status === 'accepted') throw new Error('This delivery has already been accepted');
+ if (status === 'rejected')
+ throw new Error('This delivery was rejected β€” the next verification round re-opens it');
+ if (status !== 'delivered' && status !== 'errored')
+ throw new Error(
+ `Verification is still in progress (${status}) β€” the decision comes once the round settles`,
+ );
+ const comment = input.comment?.trim();
+ return {
+ action: input.action,
+ ...(comment ? { comment } : {}),
+ createdAt: input.createdAt,
+ id: input.id,
+ kind: 'decision',
+ roundIndex: bundle.rounds.at(-1)!.run.roundIndex!,
+ };
+};
+
/** Merge two review logs by event id, oldest first β€” an export re-read changes nothing. */
export const mergeLocalReviewEvents = (
...logs: (LocalReviewEvent[] | undefined)[]
diff --git a/src/features/Acceptance/Viewer/Review/AcceptanceDecision.tsx b/src/features/Acceptance/Viewer/Review/AcceptanceDecision.tsx
index 523757a5386..69e326b1da4 100644
--- a/src/features/Acceptance/Viewer/Review/AcceptanceDecision.tsx
+++ b/src/features/Acceptance/Viewer/Review/AcceptanceDecision.tsx
@@ -2,7 +2,6 @@
import { buildAcceptanceRepairPrompt } from '@lobechat/prompts';
import { Button, copyToClipboard, Flexbox, Text, toast } from '@lobehub/ui';
-import dayjs from 'dayjs';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -13,20 +12,20 @@ import { isAcceptanceListKey } from '@/libs/swr/keys';
import { verifyService } from '@/services/verify';
import { useAcceptanceScope } from '../AcceptanceScope';
-import { checkFilterState, isException } from '../Checks/checkState';
+import { isException } from '../Checks/checkState';
import { useAcceptanceComments } from '../Comments/hooks';
import { flowPlanPhase } from '../Plan/planReview';
import { acceptanceCheckPath, useAcceptanceRouteBase } from '../routes';
import { useAcceptanceBundle } from '../useAcceptanceBundle';
import { useAcceptanceTurn } from '../useAcceptanceTurn';
-import { formatAcceptanceCountsText, LIVE_ACCEPTANCE_STATUSES } from '../verdict';
import {
canRejectAcceptanceOnly,
canReviewAcceptance,
isReadOnlyAcceptanceDecider,
} from '../visibility';
import DecisionBar from './DecisionBar';
-import FeedbackDrawer, { type FeedbackListEntry } from './FeedbackDrawer';
+import { resolveDecisionView } from './decisionView';
+import FeedbackDrawer from './FeedbackDrawer';
import { draftRepairPromptInMobile } from './mobileBridge';
import { openAcceptModal, openGroupFeedbackModal, openRejectModal } from './modals';
import { rejectCopyOnly } from './rejectCopyOnly';
@@ -68,70 +67,18 @@ const AcceptanceDecision = ({ onDraftToComposer }: AcceptanceDecisionProps) => {
</Button>
</Flexbox>
);
- const { acceptance, checks, rounds } = data;
- const currentRound = rounds.at(-1);
- const acceptedCount = checks.filter((check) => checkFilterState(check) === 'accepted').length;
- const needsFixCount = checks.filter((check) => checkFilterState(check) === 'needsFix').length;
- const ignoredCount = checks.filter((check) => checkFilterState(check) === 'ignored').length;
- const reviewTotal = checks.length;
- const pendingCount = reviewTotal - acceptedCount - needsFixCount - ignoredCount;
- const decidedCount = acceptedCount + needsFixCount + ignoredCount;
- const countsText = formatAcceptanceCountsText(t, {
- failed: checks.filter((check) => check.state === 'failed').length,
- notExecuted: checks.filter((check) => check.state === 'not_executed').length,
- passed: checks.filter((check) => check.state === 'passed').length,
- uncertain: checks.filter((check) => check.state === 'uncertain').length,
- });
- const barState = LIVE_ACCEPTANCE_STATUSES.has(acceptance.status)
- ? ('live' as const)
- : acceptance.status === 'accepted'
- ? ('accepted' as const)
- : acceptance.status === 'rejected'
- ? ('rejected' as const)
- : ('settled' as const);
- const barTexts = {
- accepted: {
- statusText: t('acceptance.banner.accepted', {
- time:
- hydrated && acceptance.completedAt
- ? dayjs(acceptance.completedAt).format('YYYY-MM-DD HH:mm')
- : '',
- }),
- subText: `${countsText} Β· ${t('acceptance.banner.acceptedHint', { count: rounds.length })}`,
- },
- live: {
- statusText: t(`acceptance.status.${acceptance.status}`),
- subText: t('acceptance.banner.liveHint'),
- },
- rejected: {
- statusText: t('acceptance.banner.rejected'),
- subText: currentRound?.run.decisionDetail?.comment ?? t('acceptance.banner.rejectedHint'),
- },
- settled:
- decidedCount === 0
- ? {
- statusText: t('acceptance.bar.progressZero', { total: reviewTotal }),
- subText: undefined,
- }
- : pendingCount === 0
- ? needsFixCount === 0
- ? {
- statusText: t('acceptance.bar.progressDone', { total: reviewTotal }),
- subText: undefined,
- }
- : {
- statusText: t('acceptance.bar.needsFix', { count: needsFixCount }),
- subText: undefined,
- }
- : {
- statusText: t('acceptance.bar.progress', {
- done: decidedCount,
- rest: pendingCount,
- total: reviewTotal,
- }),
- subText: undefined,
- },
- }[barState];
+ const { acceptance, checks } = data;
+ const {
+ acceptedCount,
+ barState,
+ currentRound,
+ feedbackEntries,
+ ignoredCount,
+ needsFixCount,
+ reviewTotal,
+ statusText,
+ subText,
+ } = resolveDecisionView(data, t, { hydrated });
// Teammates' approvals ride along the state line: they are opinions the
// decider reads, never the decision itself. Only this round's count β€” an
@@ -158,44 +105,7 @@ const AcceptanceDecision = ({ onDraftToComposer }: AcceptanceDecisionProps) => {
pendingAccessCount > 0
? t('acceptance.access.pendingCount', { count: pendingAccessCount })
: undefined;
- const subTextWithApprovals = [barTexts.subText, approvalText, accessText]
- .filter(Boolean)
- .join(' Β· ');
-
- const currentRoundIndex = currentRound?.run.roundIndex ?? 0;
- const groupFeedbackEntries = rounds.flatMap((round) =>
- (round.run.decisionDetail?.groupFeedback ?? []).map((entry) => ({
- ...entry,
- roundIndex: round.run.roundIndex ?? 0,
- })),
- );
- const feedbackEntries: FeedbackListEntry[] = [
- ...checks.flatMap((check) =>
- check.reviews
- .filter((review) => review.action === 'reject')
- .map((review) => ({
- annotationCount: review.annotations?.length || undefined,
- attachments: review.attachments,
- checkId: check.id,
- checkSeq: check.seq,
- comment: review.comment ?? '',
- createdAt: review.createdAt,
- kind: 'check' as const,
- roundIndex: review.roundIndex,
- stale: review.roundIndex < currentRoundIndex,
- title: check.title,
- })),
- ),
- ...groupFeedbackEntries.map((entry) => ({
- attachments: entry.attachments,
- comment: entry.comment,
- createdAt: entry.createdAt,
- groupLabel: entry.category,
- kind: 'group' as const,
- roundIndex: entry.roundIndex,
- stale: entry.roundIndex < currentRoundIndex,
- })),
- ].sort((a, b) => b.createdAt.localeCompare(a.createdAt));
+ const subTextWithApprovals = [subText, approvalText, accessText].filter(Boolean).join(' Β· ');
const runAction = async (action: () => Promise<unknown>) => {
setPending(true);
@@ -230,7 +140,7 @@ const AcceptanceDecision = ({ onDraftToComposer }: AcceptanceDecisionProps) => {
rerunAvailable={embedded}
rerunPending={false}
state={barState}
- statusText={barTexts.statusText}
+ statusText={statusText}
subText={subTextWithApprovals || undefined}
totalCount={reviewTotal}
onOpenFeedback={() => setFeedbackOpen(true)}
diff --git a/src/features/Acceptance/Viewer/Review/decisionView.ts b/src/features/Acceptance/Viewer/Review/decisionView.ts
new file mode 100644
index 00000000000..ef934957048
--- /dev/null
+++ b/src/features/Acceptance/Viewer/Review/decisionView.ts
@@ -0,0 +1,132 @@
+import dayjs from 'dayjs';
+import type { TFunction } from 'i18next';
+
+import type { AcceptanceBundle } from '@/services/verify';
+
+import { checkFilterState } from '../Checks/checkState';
+import { formatAcceptanceCountsText, LIVE_ACCEPTANCE_STATUSES } from '../verdict';
+import type { FeedbackListEntry } from './FeedbackDrawer';
+
+type DecisionBundle = Pick<AcceptanceBundle, 'acceptance' | 'checks' | 'rounds'>;
+
+/**
+ * What the decision bar reads out β€” review progress, the state line, and the
+ * feedback this acceptance has queued β€” derived from the bundle alone, so every
+ * host that mounts the bar words the same state the same way.
+ */
+export const resolveDecisionView = (
+ { acceptance, checks, rounds }: DecisionBundle,
+ t: TFunction<'verify'>,
+ { hydrated }: { hydrated: boolean },
+) => {
+ const currentRound = rounds.at(-1);
+ const acceptedCount = checks.filter((check) => checkFilterState(check) === 'accepted').length;
+ const needsFixCount = checks.filter((check) => checkFilterState(check) === 'needsFix').length;
+ const ignoredCount = checks.filter((check) => checkFilterState(check) === 'ignored').length;
+ const reviewTotal = checks.length;
+ const pendingCount = reviewTotal - acceptedCount - needsFixCount - ignoredCount;
+ const decidedCount = acceptedCount + needsFixCount + ignoredCount;
+ const countsText = formatAcceptanceCountsText(t, {
+ failed: checks.filter((check) => check.state === 'failed').length,
+ notExecuted: checks.filter((check) => check.state === 'not_executed').length,
+ passed: checks.filter((check) => check.state === 'passed').length,
+ uncertain: checks.filter((check) => check.state === 'uncertain').length,
+ });
+ const barState = LIVE_ACCEPTANCE_STATUSES.has(acceptance.status)
+ ? ('live' as const)
+ : acceptance.status === 'accepted'
+ ? ('accepted' as const)
+ : acceptance.status === 'rejected'
+ ? ('rejected' as const)
+ : ('settled' as const);
+ const barTexts: { statusText: string; subText: string | undefined } = {
+ accepted: {
+ statusText: t('acceptance.banner.accepted', {
+ time:
+ hydrated && acceptance.completedAt
+ ? dayjs(acceptance.completedAt).format('YYYY-MM-DD HH:mm')
+ : '',
+ }),
+ subText: `${countsText} Β· ${t('acceptance.banner.acceptedHint', { count: rounds.length })}`,
+ },
+ live: {
+ statusText: t(`acceptance.status.${acceptance.status}`),
+ subText: t('acceptance.banner.liveHint'),
+ },
+ rejected: {
+ statusText: t('acceptance.banner.rejected'),
+ subText: currentRound?.run.decisionDetail?.comment ?? t('acceptance.banner.rejectedHint'),
+ },
+ settled:
+ decidedCount === 0
+ ? {
+ statusText: t('acceptance.bar.progressZero', { total: reviewTotal }),
+ subText: undefined,
+ }
+ : pendingCount === 0
+ ? needsFixCount === 0
+ ? {
+ statusText: t('acceptance.bar.progressDone', { total: reviewTotal }),
+ subText: undefined,
+ }
+ : {
+ statusText: t('acceptance.bar.needsFix', { count: needsFixCount }),
+ subText: undefined,
+ }
+ : {
+ statusText: t('acceptance.bar.progress', {
+ done: decidedCount,
+ rest: pendingCount,
+ total: reviewTotal,
+ }),
+ subText: undefined,
+ },
+ }[barState];
+
+ const currentRoundIndex = currentRound?.run.roundIndex ?? 0;
+ const groupFeedbackEntries = rounds.flatMap((round) =>
+ (round.run.decisionDetail?.groupFeedback ?? []).map((entry) => ({
+ ...entry,
+ roundIndex: round.run.roundIndex ?? 0,
+ })),
+ );
+ const feedbackEntries: FeedbackListEntry[] = [
+ ...checks.flatMap((check) =>
+ check.reviews
+ .filter((review) => review.action === 'reject')
+ .map((review) => ({
+ annotationCount: review.annotations?.length || undefined,
+ attachments: review.attachments,
+ checkId: check.id,
+ checkSeq: check.seq,
+ comment: review.comment ?? '',
+ createdAt: review.createdAt,
+ kind: 'check' as const,
+ roundIndex: review.roundIndex,
+ stale: review.roundIndex < currentRoundIndex,
+ title: check.title,
+ })),
+ ),
+ ...groupFeedbackEntries.map((entry) => ({
+ attachments: entry.attachments,
+ comment: entry.comment,
+ createdAt: entry.createdAt,
+ groupLabel: entry.category,
+ kind: 'group' as const,
+ roundIndex: entry.roundIndex,
+ stale: entry.roundIndex < currentRoundIndex,
+ })),
+ ].sort((a, b) => b.createdAt.localeCompare(a.createdAt));
+
+ return {
+ acceptedCount,
+ barState,
+ currentRound,
+ feedbackEntries,
+ ignoredCount,
+ needsFixCount,
+ reviewTotal,
+ statusText: barTexts.statusText,
+ subText: barTexts.subText,
+ };
+};