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.

💄 style(acceptance): make the AI review round always report its outcome (#18672)

Arvin Xu353b0c0f8b1e
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.md
index 5576be8a5ae..a810beebc6d 100644
--- a/.agents/acceptance/probe-mock-patterns.md
+++ b/.agents/acceptance/probe-mock-patterns.md
@@ -217,6 +217,41 @@ before schema parsing.
return a standard JSON chat completion for `stream: false`; set `STUB_TEXT` to the
schema-valid JSON required by the check.
+#### Driving the Acceptance AI-review predictor locally: pinned Gemini, image fetch-back, and stub JSON
+
+**Situation:** verifying the ✨ "ask AI to review" round on `/acceptance/<id>` (the
+`review_predict` generation, its toast, the proposal cards) without a real vision key.
+
+**Doesn't work:** three separate things, each of which reads as "the predictor never
+ran" — the button spins, no card, no error.
+
+- Pointing any provider at `llm-stub.mjs`. The predictor does not follow the verifier's
+ model: it is pinned to `DEFAULT_REVIEW_PREDICT_{MODEL,PROVIDER}` in
+ `packages/business/const/src/llm.ts` (Gemini native protocol, which the OpenAI-shaped
+ stub cannot serve), so the provider you configured is simply never called.
+- Running the dev server without `SSRF_ALLOW_PRIVATE_IP_ADDRESS=1`. The OpenAI context
+ builder fetches every `image_url` back and inlines it as base64; the local s3rver
+ presigned URL is `127.0.0.1`, so the fetch is refused and the attempt lands as an
+ `errored` row with no model call (the "SSRF protection blocked request" entry above).
+- Expecting a `pending` state in `verify_review_predictions`. There is none: a check is
+ "awaiting" only while it has NO row for the current (provider, model, promptVersion);
+ `predictReviews` deletes the previous unadjudicated rows before dispatch, so reading
+ the table mid-batch shows gaps, not placeholders.
+
+**Works:** (1) temporarily pin the constants to `gpt-4o` / `openai` with an
+`[AGENT-TEST]` marker (snapshot the file first, restore byte-identically at teardown —
+the model-bank vision test guards the real value), then
+`aiInfra().updateAiProviderConfig('openai', { keyVaults: { apiKey: 'sk-stub', baseURL:
+'http://localhost:41100/v1' } })`; (2) start the dev server with
+`SSRF_ALLOW_PRIVATE_IP_ADDRESS=1`; (3) set `STUB_TEXT` to a `ReviewPredictionSchema`
+JSON (`{"action":"reject","regions":[{"imageIndex":0,...}]}`) — the runtime sends
+`response_format: json_schema` with `stream: false`, which the stub answers as a plain
+completion whose `content` is parsed as the object. A text-only evidence check is
+`skipped` without a call; `STUB_FAIL=500` yields `errored` — note the SDK retries a
+5xx three times, so any delay you put in front of the stub is paid ×3 on that path.
+Assert the round from three places together: the toast copy (a MutationObserver on
+`document.body`), the rows' `status`/`action`/`created_at`, and the card count.
+
#### A CLI-created topic has no trigger/status and is filtered out of the Agent paged view
**Situation:** building a topic fixture with `lh topic create`, writing fields such as
diff --git a/apps/server/src/routers/lambda/acceptance.ts b/apps/server/src/routers/lambda/acceptance.ts
index b0f7c44652f..cc261162a1f 100644
--- a/apps/server/src/routers/lambda/acceptance.ts
+++ b/apps/server/src/routers/lambda/acceptance.ts
@@ -30,6 +30,7 @@ import {
buildAcceptanceCheckUnion,
buildCheckReviewOverlay,
createEvidenceFileResolver,
+ isCurrentReviewPrediction,
mapWithConcurrency,
REVIEW_PREDICT_CONCURRENCY,
REVIEW_PREDICT_MODEL_CONFIG,
@@ -425,6 +426,9 @@ export const acceptanceRouter = router({
// Newest-first from the model, so the first write per check item wins and
// later (older) rows are ignored.
for (const prediction of predictions) {
+ // Rows from an earlier pin (another model / prompt version) stay in
+ // the table for the comparison set but are not this page's reviewer.
+ if (!isCurrentReviewPrediction(prediction, REVIEW_PREDICT_MODEL_CONFIG)) continue;
if (!predictionByResult.has(prediction.checkResultId)) {
predictionByResult.set(prediction.checkResultId, prediction);
}
@@ -459,6 +463,12 @@ export const acceptanceRouter = router({
evidence: check.result ? (evidenceByResult.get(check.result.id) ?? []) : [],
prediction:
prediction && shouldSurfaceProposal(prediction, settled) ? prediction : null,
+ // The card above is gated to actionable rejects, but the FACT that
+ // the predictor finished with this check must stay visible: an
+ // `accept`, a skip and an error all render no card, and without
+ // this the predict button's poll cannot tell "still running" from
+ // "reviewed, nothing to say" — it spins to timeout on a clean bill.
+ predictionStatus: prediction?.status ?? null,
reviews: resolvedReviews,
timeline: check.timeline.map((entry) => ({
...entry,
@@ -743,6 +753,15 @@ export const acceptanceRouter = router({
// check spends budget to argue with a decision that is already made.
const pending = checks.filter((check) => check.result && !check.result.userDecision);
+ // Forget the previous batch's unanswered rows BEFORE responding: the
+ // client waits for every queued check to carry a recorded attempt, and
+ // with the old rows still in place that condition holds on the first
+ // poll — before a single new judgement has landed.
+ await predictor.resetPending(
+ pending.map((check) => check.result!.id),
+ modelConfig,
+ );
+
// Dispatched AFTER the response, with a ceiling on how many model calls
// are open at once.
//
diff --git a/apps/server/src/services/verify/__tests__/reviewPredictor.test.ts b/apps/server/src/services/verify/__tests__/reviewPredictor.test.ts
index 7a46391a766..5fd7e97e202 100644
--- a/apps/server/src/services/verify/__tests__/reviewPredictor.test.ts
+++ b/apps/server/src/services/verify/__tests__/reviewPredictor.test.ts
@@ -1,6 +1,7 @@
+import { REVIEW_PREDICT_PROMPT_VERSION } from '@lobechat/prompts';
import { describe, expect, it } from 'vitest';
-import { shouldSurfaceProposal } from '../reviewPredictor';
+import { isCurrentReviewPrediction, shouldSurfaceProposal } from '../reviewPredictor';
/**
* Regression: a dismissed proposal came back on every reload.
@@ -66,3 +67,35 @@ describe('shouldSurfaceProposal', () => {
expect(shouldSurfaceProposal({ action: 'reject' }, settled)).toBe(false);
});
});
+
+/**
+ * Regression: the bundle took the newest row across ALL models. After the
+ * pinned model changed, a stale row from the old one satisfied "the batch
+ * finished" the instant the current model's row was cleared for re-judging.
+ */
+describe('isCurrentReviewPrediction', () => {
+ const current = { model: 'gemini-3.6-flash', provider: 'google' };
+
+ it('accepts a row from the pinned model on the current prompt version', () => {
+ expect(
+ isCurrentReviewPrediction(
+ { ...current, promptVersion: REVIEW_PREDICT_PROMPT_VERSION },
+ current,
+ ),
+ ).toBe(true);
+ });
+
+ it('rejects rows from another model, provider, or prompt version', () => {
+ expect(
+ isCurrentReviewPrediction(
+ {
+ model: 'deepseek-v4-pro',
+ promptVersion: REVIEW_PREDICT_PROMPT_VERSION,
+ provider: 'lobehub',
+ },
+ current,
+ ),
+ ).toBe(false);
+ expect(isCurrentReviewPrediction({ ...current, promptVersion: 'v0' }, current)).toBe(false);
+ });
+});
diff --git a/apps/server/src/services/verify/index.ts b/apps/server/src/services/verify/index.ts
index 8d5501093a9..f411e073904 100644
--- a/apps/server/src/services/verify/index.ts
+++ b/apps/server/src/services/verify/index.ts
@@ -49,6 +49,7 @@ export {
} from './repairService';
export { type GenerateReportParams, VerifyReporterService } from './reporter';
export {
+ isCurrentReviewPrediction,
type PredictReviewParams,
REVIEW_PREDICT_CONCURRENCY,
shouldSurfaceProposal,
diff --git a/apps/server/src/services/verify/reviewPredictor.ts b/apps/server/src/services/verify/reviewPredictor.ts
index 5223e29aed8..7f480c283dc 100644
--- a/apps/server/src/services/verify/reviewPredictor.ts
+++ b/apps/server/src/services/verify/reviewPredictor.ts
@@ -78,6 +78,23 @@ export const shouldSurfaceProposal = <
): prediction is T & { action: 'reject' } =>
prediction.action === 'reject' && !hasUserReview && !prediction.adjudication;
+/**
+ * Whether a stored row is the opinion of the reviewer currently in service.
+ *
+ * Rows from an earlier pin (a different model, or an older prompt version)
+ * stay in the table for the comparison set, but they are not what the page
+ * shows or what a fresh request is waiting on: reading the newest row across
+ * models let a stale verdict satisfy "the batch finished" the moment the
+ * current model's row was cleared for re-judging.
+ */
+export const isCurrentReviewPrediction = (
+ prediction: { model: string; promptVersion: string; provider: string },
+ modelConfig: { model: string; provider: string },
+): boolean =>
+ prediction.provider === modelConfig.provider &&
+ prediction.model === modelConfig.model &&
+ prediction.promptVersion === REVIEW_PREDICT_PROMPT_VERSION;
+
/**
* Produces an automated second opinion on a check the verifier already judged.
*
@@ -110,6 +127,20 @@ export class VerifyReviewPredictorService {
this.fileService = new FileService(db, userId, workspaceId);
}
+ /**
+ * Forget the unanswered attempts a new batch is about to replace, so that a
+ * missing row means "not judged yet" for every check in the batch. Called
+ * BEFORE the batch is dispatched — the reset is what lets a poller tell a
+ * finished batch from the previous run's leftovers.
+ */
+ async resetPending(checkResultIds: string[], modelConfig: { model: string; provider: string }) {
+ await this.predictionModel.resetUnadjudicated(checkResultIds, {
+ model: modelConfig.model,
+ promptVersion: REVIEW_PREDICT_PROMPT_VERSION,
+ provider: modelConfig.provider,
+ });
+ }
+
/**
* Re-judge one check.
*
diff --git a/locales/en-US/verify.json b/locales/en-US/verify.json
index 292c9939ebd..b2c0b8c21eb 100644
--- a/locales/en-US/verify.json
+++ b/locales/en-US/verify.json
@@ -146,6 +146,11 @@
"acceptance.origin.agentFallback": "Agent",
"acceptance.origin.backToRuns": "Back to runs",
"acceptance.origin.openTopic": "Open topic",
+ "acceptance.predict.allClear": "AI reviewed {{count}} pending check(s) and agrees with the current verdicts — nothing new to flag.",
+ "acceptance.predict.inconclusive": "AI could not form an opinion — no readable screenshot evidence, or the review call failed.",
+ "acceptance.predict.nonePending": "Nothing left to review — every check already has a verdict.",
+ "acceptance.predict.proposals": "AI review finished: {{count}} check(s) flagged for you.",
+ "acceptance.predict.stillRunning": "AI review is still running — refresh in a moment to see the results.",
"acceptance.proposal.confirm": "Confirm and send back",
"acceptance.proposal.misidentified": "Real problem, wrong spot",
"acceptance.proposal.notAnIssue": "Not a problem",
diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.json
index 9a1f93df741..38955a2d431 100644
--- a/locales/zh-CN/verify.json
+++ b/locales/zh-CN/verify.json
@@ -146,6 +146,11 @@
"acceptance.origin.agentFallback": "智能体",
"acceptance.origin.backToRuns": "返回运行记录",
"acceptance.origin.openTopic": "打开话题",
+ "acceptance.predict.allClear": "AI 已复核 {{count}} 项待定检查,与现有判定一致,未发现新问题",
+ "acceptance.predict.inconclusive": "AI 未能给出复核意见——缺少可判读的截图证据,或复核调用失败",
+ "acceptance.predict.nonePending": "没有待复核的检查项,所有检查都已有判定",
+ "acceptance.predict.proposals": "AI 复核完成:{{count}} 项检查提出异议,请查看卡片",
+ "acceptance.predict.stillRunning": "AI 复核仍在进行中,稍后刷新即可查看结果",
"acceptance.proposal.confirm": "确认并打回",
"acceptance.proposal.misidentified": "确有问题,但位置不对",
"acceptance.proposal.notAnIssue": "这不是问题",
diff --git a/packages/database/src/models/__tests__/verifyReviewPrediction.test.ts b/packages/database/src/models/__tests__/verifyReviewPrediction.test.ts
new file mode 100644
index 00000000000..5c27ccf84d3
--- /dev/null
+++ b/packages/database/src/models/__tests__/verifyReviewPrediction.test.ts
@@ -0,0 +1,112 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import {
+ agentOperations,
+ users,
+ verifyCheckResults,
+ verifyReviewPredictions,
+ verifyRuns,
+} from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { AgentOperationModel } from '../agentOperation';
+import { VerifyCheckResultModel } from '../verifyCheckResult';
+import { VerifyReviewPredictionModel } from '../verifyReviewPrediction';
+import { VerifyRunModel } from '../verifyRun';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'verify-prediction-test-user';
+const operationId = 'verify-prediction-test-op';
+
+const identity = { model: 'gemini-3.6-flash', promptVersion: 'v1', provider: 'google' };
+
+let resultIds: string[];
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }]);
+ await new AgentOperationModel(serverDB, userId).recordStart({ operationId });
+ const run = await new VerifyRunModel(serverDB, userId).ensureForOperation(operationId);
+ const rows = await new VerifyCheckResultModel(serverDB, userId).createMany([
+ { checkItemId: 'a', checkItemIndex: 0, verifierType: 'llm', verifyRunId: run.id },
+ { checkItemId: 'b', checkItemIndex: 1, verifierType: 'llm', verifyRunId: run.id },
+ ]);
+ resultIds = rows.map((r) => r.id);
+});
+
+afterEach(async () => {
+ await serverDB.delete(verifyReviewPredictions);
+ await serverDB.delete(verifyCheckResults);
+ await serverDB.delete(verifyRuns);
+ await serverDB.delete(agentOperations);
+ await serverDB.delete(users);
+});
+
+describe('VerifyReviewPredictionModel.resetUnadjudicated', () => {
+ /**
+ * Regression: a re-request left the previous batch's rows in place until each
+ * replacement upserted over them, so a poller waiting for "every check has a
+ * recorded attempt" saw that condition met on its first tick. The reset must
+ * clear the unanswered rows of the current reviewer — and only those.
+ */
+ it('clears unanswered rows of the same reviewer and keeps adjudicated ones', async () => {
+ const model = new VerifyReviewPredictionModel(serverDB, userId);
+ const unanswered = await model.upsert({
+ action: 'accept',
+ checkResultId: resultIds[0],
+ status: 'judged',
+ ...identity,
+ });
+ const answered = await model.upsert({
+ action: 'reject',
+ checkResultId: resultIds[1],
+ status: 'judged',
+ ...identity,
+ });
+ await model.adjudicate(answered.id, { adjudication: 'not-an-issue' });
+
+ await model.resetUnadjudicated(resultIds, identity);
+
+ expect(await model.findById(unanswered.id)).toBeUndefined();
+ expect((await model.findById(answered.id))?.adjudication).toBe('not-an-issue');
+ });
+
+ it('leaves rows from another model or prompt version untouched', async () => {
+ const model = new VerifyReviewPredictionModel(serverDB, userId);
+ const otherModel = await model.upsert({
+ action: 'accept',
+ checkResultId: resultIds[0],
+ status: 'judged',
+ ...identity,
+ model: 'deepseek-v4-pro',
+ });
+ const otherPrompt = await model.upsert({
+ action: 'accept',
+ checkResultId: resultIds[0],
+ status: 'judged',
+ ...identity,
+ promptVersion: 'v0',
+ });
+
+ await model.resetUnadjudicated(resultIds, identity);
+
+ expect(await model.findById(otherModel.id)).toBeDefined();
+ expect(await model.findById(otherPrompt.id)).toBeDefined();
+ });
+
+ it('is a no-op for an empty id list', async () => {
+ const model = new VerifyReviewPredictionModel(serverDB, userId);
+ const row = await model.upsert({
+ action: 'accept',
+ checkResultId: resultIds[0],
+ status: 'judged',
+ ...identity,
+ });
+
+ await model.resetUnadjudicated([], identity);
+
+ expect(await model.findById(row.id)).toBeDefined();
+ });
+});
diff --git a/packages/database/src/models/verifyReviewPrediction.ts b/packages/database/src/models/verifyReviewPrediction.ts
index c6857eccfb1..40161189d14 100644
--- a/packages/database/src/models/verifyReviewPrediction.ts
+++ b/packages/database/src/models/verifyReviewPrediction.ts
@@ -1,5 +1,5 @@
import type { ReviewAdjudication, ReviewProposalEdit } from '@lobechat/types';
-import { and, desc, eq, inArray, isNotNull } from 'drizzle-orm';
+import { and, desc, eq, inArray, isNotNull, isNull } from 'drizzle-orm';
import type { NewVerifyReviewPrediction } from '../schemas/verify';
import { verifyCheckResults, verifyReviewPredictions } from '../schemas/verify';
@@ -128,6 +128,37 @@ export class VerifyReviewPredictionModel {
),
});
+ /**
+ * Clear the unanswered opinions of one model + prompt version on a set of
+ * results, so a fresh batch starts from "no attempt recorded".
+ *
+ * The predictor upserts on completion, which means a re-request leaves the
+ * PREVIOUS attempt sitting under each check until its replacement lands —
+ * and a client waiting for "every check has a recorded attempt" then sees
+ * that condition met before a single new call has finished. Nothing is lost
+ * that the upsert would not have overwritten anyway; adjudicated rows are
+ * kept because they are recorded labels and the predictor skips them.
+ */
+ resetUnadjudicated = async (
+ checkResultIds: string[],
+ identity: { model: string; promptVersion: string; provider: string },
+ ) => {
+ if (checkResultIds.length === 0) return;
+
+ await this.db
+ .delete(verifyReviewPredictions)
+ .where(
+ and(
+ inArray(verifyReviewPredictions.checkResultId, checkResultIds),
+ eq(verifyReviewPredictions.provider, identity.provider),
+ eq(verifyReviewPredictions.model, identity.model),
+ eq(verifyReviewPredictions.promptVersion, identity.promptVersion),
+ isNull(verifyReviewPredictions.adjudication),
+ this.ownership(),
+ ),
+ );
+ };
+
findById = async (id: string) =>
this.db.query.verifyReviewPredictions.findFirst({
where: and(eq(verifyReviewPredictions.id, id), this.ownership()),
diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.ts
index fc31f4c7319..928c6d9f624 100644
--- a/packages/locales/src/default/verify.ts
+++ b/packages/locales/src/default/verify.ts
@@ -182,6 +182,14 @@ export default {
'acceptance.review.annotateHint':
'Drag on the image to circle a region, then leave a note for it.',
'acceptance.review.annotationPlaceholder': 'What is wrong in region {{index}}…',
+ 'acceptance.predict.allClear':
+ 'AI reviewed {{count}} pending check(s) and agrees with the current verdicts — nothing new to flag.',
+ 'acceptance.predict.inconclusive':
+ 'AI could not form an opinion — no readable screenshot evidence, or the review call failed.',
+ 'acceptance.predict.nonePending': 'Nothing left to review — every check already has a verdict.',
+ 'acceptance.predict.proposals': 'AI review finished: {{count}} check(s) flagged for you.',
+ 'acceptance.predict.stillRunning':
+ 'AI review is still running — refresh in a moment to see the results.',
'acceptance.proposal.confirm': 'Confirm and send back',
'acceptance.proposal.misidentified': 'Real problem, wrong spot',
'acceptance.proposal.notAnIssue': 'Not a problem',
diff --git a/src/features/Verify/Acceptance/AcceptanceCheckOwnerToolbar.tsx b/src/features/Verify/Acceptance/AcceptanceCheckOwnerToolbar.tsx
index f9d3155f020..e94ba476bcd 100644
--- a/src/features/Verify/Acceptance/AcceptanceCheckOwnerToolbar.tsx
+++ b/src/features/Verify/Acceptance/AcceptanceCheckOwnerToolbar.tsx
@@ -13,9 +13,12 @@ import { verifyService } from '@/services/verify';
import { useAcceptanceScope } from './AcceptanceScope';
import { openAddCheckModal } from './AddCheckModal';
import { hasVisualEvidence } from './CheckList';
+import { countAwaitingPrediction, summarizePredictRound } from './predictRound';
import { useAcceptanceBundle } from './useAcceptanceBundle';
+/** How long to wait between bundle re-fetches while the batch runs. */
const PREDICT_POLL_INTERVAL_MS = 4000;
+/** ~2 minutes: a bounded batch of 4-concurrent generations settles well inside this. */
const PREDICT_POLL_ATTEMPTS = 30;
const AcceptanceCheckOwnerToolbar = () => {
@@ -45,19 +48,57 @@ const AcceptanceCheckOwnerToolbar = () => {
loading={predicting}
size={'small'}
title={t('acceptance.proposal.request')}
+ // The server dispatches the batch AFTER responding, so the mutation
+ // returns in milliseconds with nothing to show. Poll the bundle until
+ // every queued check records an attempt (`predictionStatus`) — waiting
+ // for CARDS would never terminate on a clean delivery, because an
+ // agreeing verdict renders none.
+ //
+ // The round always ends in a toast. Zero cards is a real result with
+ // two different meanings ("reviewed, agrees" vs "couldn't judge"), and
+ // without saying which, a clean round is indistinguishable from a
+ // broken feature.
onClick={async () => {
setPredicting(true);
try {
const { queued } = await verifyService.predictReviews(data.acceptance.id);
- if (queued === 0) return;
+ if (queued === 0) {
+ toast.info({ title: t('acceptance.predict.nonePending') });
+ return;
+ }
+
+ let checks: Parameters<typeof countAwaitingPrediction>[0] = [];
+ let awaiting = queued;
for (let attempt = 0; attempt < PREDICT_POLL_ATTEMPTS; attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, PREDICT_POLL_INTERVAL_MS));
const next = await mutate();
- const settled = (next?.checks ?? []).filter(
- (check) => check.prediction || check.result?.userDecision,
- ).length;
- if (settled >= queued) break;
+ checks = next?.checks ?? checks;
+ awaiting = countAwaitingPrediction(checks);
+ if (awaiting === 0) break;
+ }
+
+ if (awaiting > 0) {
+ // Bounded batch overran the poll window — the rows land eventually.
+ toast.info({ title: t('acceptance.predict.stillRunning') });
+ return;
+ }
+ const { judged, outcome, proposals } = summarizePredictRound(checks);
+ // Tone follows the outcome: a verdict either way is a success, but
+ // "could not judge" is a warning — a green tick on it would read as
+ // the review having passed, which is the ambiguity this toast
+ // exists to remove.
+ if (outcome === 'inconclusive') {
+ toast.warning({ title: t('acceptance.predict.inconclusive') });
+ return;
}
+ toast.success({
+ title:
+ outcome === 'proposals'
+ ? t('acceptance.predict.proposals', { count: proposals })
+ : t('acceptance.predict.allClear', { count: judged }),
+ });
+ } catch (error) {
+ toast.error(error instanceof Error ? error.message : t('acceptance.actionError'));
} finally {
setPredicting(false);
}
diff --git a/src/features/Verify/Acceptance/predictRound.test.ts b/src/features/Verify/Acceptance/predictRound.test.ts
new file mode 100644
index 00000000000..d3b6dfac06c
--- /dev/null
+++ b/src/features/Verify/Acceptance/predictRound.test.ts
@@ -0,0 +1,83 @@
+import { describe, expect, it } from 'vitest';
+
+import { countAwaitingPrediction, summarizePredictRound } from './predictRound';
+
+const pendingCheck = (overrides: Record<string, unknown> = {}) => ({
+ prediction: null,
+ predictionStatus: null,
+ result: { userDecision: null },
+ ...overrides,
+});
+
+describe('countAwaitingPrediction', () => {
+ /**
+ * Regression: an `accept` renders no proposal card, so the old poll (which
+ * counted `prediction || userDecision`) never saw an all-accept batch finish
+ * and span the full two-minute timeout on every clean delivery.
+ */
+ it('treats a judged accept (no card) as answered', () => {
+ expect(countAwaitingPrediction([pendingCheck({ predictionStatus: 'judged' })])).toBe(0);
+ });
+
+ it('treats skips and errors as answered — they will never produce a card', () => {
+ expect(
+ countAwaitingPrediction([
+ pendingCheck({ predictionStatus: 'skipped' }),
+ pendingCheck({ predictionStatus: 'errored' }),
+ ]),
+ ).toBe(0);
+ });
+
+ it('keeps waiting on checks with no recorded attempt', () => {
+ expect(
+ countAwaitingPrediction([pendingCheck(), pendingCheck({ predictionStatus: 'judged' })]),
+ ).toBe(1);
+ });
+
+ it('never waits on user-decided or unexecuted checks — the batch skips them', () => {
+ expect(
+ countAwaitingPrediction([
+ pendingCheck({ result: { userDecision: 'accept' } }),
+ { prediction: null, predictionStatus: null, result: null },
+ ]),
+ ).toBe(0);
+ });
+});
+
+describe('summarizePredictRound', () => {
+ it('reports proposals when any card surfaced', () => {
+ const summary = summarizePredictRound([
+ pendingCheck({ prediction: { id: 'p1' }, predictionStatus: 'judged' }),
+ pendingCheck({ predictionStatus: 'judged' }),
+ ]);
+ expect(summary).toEqual({ judged: 2, outcome: 'proposals', proposals: 1 });
+ });
+
+ it('reports a clean bill when every verdict agreed (no cards)', () => {
+ const summary = summarizePredictRound([
+ pendingCheck({ predictionStatus: 'judged' }),
+ pendingCheck({ predictionStatus: 'judged' }),
+ ]);
+ expect(summary).toEqual({ judged: 2, outcome: 'allClear', proposals: 0 });
+ });
+
+ it('reports inconclusive when nothing could be judged (all skipped/errored)', () => {
+ const summary = summarizePredictRound([
+ pendingCheck({ predictionStatus: 'skipped' }),
+ pendingCheck({ predictionStatus: 'errored' }),
+ ]);
+ expect(summary).toEqual({ judged: 0, outcome: 'inconclusive', proposals: 0 });
+ });
+
+ it('ignores checks the reviewer already ruled on', () => {
+ const summary = summarizePredictRound([
+ pendingCheck({
+ prediction: { id: 'p1' },
+ predictionStatus: 'judged',
+ result: { userDecision: 'reject' },
+ }),
+ pendingCheck({ predictionStatus: 'judged' }),
+ ]);
+ expect(summary).toEqual({ judged: 1, outcome: 'allClear', proposals: 0 });
+ });
+});
diff --git a/src/features/Verify/Acceptance/predictRound.ts b/src/features/Verify/Acceptance/predictRound.ts
new file mode 100644
index 00000000000..201845d9a63
--- /dev/null
+++ b/src/features/Verify/Acceptance/predictRound.ts
@@ -0,0 +1,50 @@
+/**
+ * Pure state readers for the "ask AI to review" round-trip.
+ *
+ * The server dispatches the prediction batch after responding, so the client
+ * polls the bundle until every queued check has an answer. The subtlety both
+ * helpers encode: a prediction that AGREES with the verifier (or skips, or
+ * errors) renders no proposal card — `prediction` stays null in the bundle and
+ * only `predictionStatus` records that the attempt finished. Reading the card
+ * alone makes a clean bill of health indistinguishable from a batch that never
+ * ran, which is exactly the bug that shipped: the button span the full timeout
+ * and then said nothing.
+ */
+
+interface PredictRoundCheck {
+ /** The surfaced proposal card — rejects awaiting the reviewer only. */
+ prediction?: unknown | null;
+ /** Recorded outcome of the attempt: `judged` / `skipped` / `errored`. */
+ predictionStatus?: string | null;
+ result?: { userDecision?: string | null } | null;
+}
+
+/** The checks this batch still owes an answer — the poll's exit condition. */
+export const countAwaitingPrediction = (checks: PredictRoundCheck[]): number =>
+ checks.filter((check) => check.result && !check.result.userDecision && !check.predictionStatus)
+ .length;
+
+export interface PredictRoundSummary {
+ /** Attempts that produced a verdict (accepts included). */
+ judged: number;
+ outcome: 'allClear' | 'inconclusive' | 'proposals';
+ /** Cards the reviewer now has to look at. */
+ proposals: number;
+}
+
+/**
+ * What the finished round should tell the reviewer. Zero cards is a meaningful
+ * result, not silence — "reviewed and agreed" and "could not review" both need
+ * saying, or the button reads as broken every time the delivery is clean.
+ */
+export const summarizePredictRound = (checks: PredictRoundCheck[]): PredictRoundSummary => {
+ const pending = checks.filter((check) => check.result && !check.result.userDecision);
+ const proposals = pending.filter((check) => check.prediction).length;
+ const judged = pending.filter((check) => check.predictionStatus === 'judged').length;
+
+ return {
+ judged,
+ outcome: proposals > 0 ? 'proposals' : judged > 0 ? 'allClear' : 'inconclusive',
+ proposals,
+ };
+};