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(verify): send evidence frames inline and stop review errors from spending Task attempts (#19565)

Arvin Xua452cb6b7147
diff --git a/apps/server/src/services/goal/decideNextMove.test.ts b/apps/server/src/services/goal/decideNextMove.test.ts
index 6f15d317b6b..9f0478d643a 100644
--- a/apps/server/src/services/goal/decideNextMove.test.ts
+++ b/apps/server/src/services/goal/decideNextMove.test.ts
@@ -1,4 +1,7 @@
-import { VERIFICATION_UNJUDGEABLE_ERROR } from '@lobechat/const/goal';
+import {
+ ACCEPTANCE_REVIEW_ERRORED_ERROR,
+ VERIFICATION_UNJUDGEABLE_ERROR,
+} from '@lobechat/const/goal';
import type { GoalGraphNode, GoalGraphSnapshot, TaskItem } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
@@ -202,6 +205,15 @@ describe('decideNextMove', () => {
frontierTask: task({ error: VERIFICATION_UNJUDGEABLE_ERROR, status: 'paused' }),
}),
).toMatchObject({ branch: 'failure_decision', outcome: 'waiting_human' });
+
+ // A review that still could not run after its own retry is a reviewer
+ // problem. Another builder attempt would re-deliver into the same broken
+ // review and spend the attempt budget, so it goes to a person.
+ expect(
+ decide(snapshot, {
+ frontierTask: task({ error: ACCEPTANCE_REVIEW_ERRORED_ERROR, status: 'paused' }),
+ }),
+ ).toMatchObject({ branch: 'failure_decision', outcome: 'waiting_human' });
});
it('treats a plain pause as waiting on a person and a run as waiting on the world', () => {
diff --git a/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts b/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts
index 5c536b9c42b..a9844b2275f 100644
--- a/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts
+++ b/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts
@@ -1,5 +1,8 @@
// @vitest-environment node
-import { VERIFICATION_UNJUDGEABLE_ERROR } from '@lobechat/const/goal';
+import {
+ ACCEPTANCE_REVIEW_ERRORED_ERROR,
+ VERIFICATION_UNJUDGEABLE_ERROR,
+} from '@lobechat/const/goal';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { scheduleGoalAdvance } from '@/server/services/goal/scheduler';
@@ -145,6 +148,38 @@ describe('driveTaskFromVerify', () => {
});
});
+ /**
+ * Regression: a review that could not run paused the Task with the errored
+ * contract string, which the coordinator recovers by starting another builder
+ * attempt. A review that failed the same way every time β€” its model could not
+ * download a screenshot β€” re-delivered the same work until the attempt budget
+ * ran out, without the delivery ever being judged.
+ */
+ it('parks a review that keeps failing on a person instead of another attempt', async () => {
+ runFindByOperation.mockResolvedValue({
+ id: 'run-1',
+ acceptanceId: 'acceptance-1',
+ status: 'passed',
+ });
+ vi.mocked(reviewGoalDelivery).mockResolvedValue({
+ status: 'errored',
+ feedback: 'Error while downloading file. Upstream status code: 407.',
+ predictionIds: [],
+ });
+
+ await driveTaskFromVerify(db, 'u1', 'op-1');
+
+ // The review retries its own errored checks; the settle path must not rerun
+ // the whole review, which would re-ask checks that already rejected.
+ expect(reviewGoalDelivery).toHaveBeenCalledTimes(1);
+ expect(serviceUpdateStatus).not.toHaveBeenCalled();
+ expect(taskUpdateStatus).toHaveBeenCalledWith('task-1', 'paused', {
+ error: ACCEPTANCE_REVIEW_ERRORED_ERROR,
+ });
+ // The creator still hears the delivery was not evaluated, not that it failed.
+ expect(deliverMock.mock.calls[0][0].errorMessage.toLowerCase()).toContain('internal error');
+ });
+
it('does not launch a duplicate review when task drive is already claimed', async () => {
runFindByOperation.mockResolvedValue({
id: 'run-1',
diff --git a/apps/server/src/services/verify/__tests__/goalReview.test.ts b/apps/server/src/services/verify/__tests__/goalReview.test.ts
index 457f494c2f7..f1b1ad7b765 100644
--- a/apps/server/src/services/verify/__tests__/goalReview.test.ts
+++ b/apps/server/src/services/verify/__tests__/goalReview.test.ts
@@ -217,6 +217,36 @@ describe('Goal automatic Acceptance review', () => {
statusReason: 'provider unavailable',
});
expect(await reviewGoalDelivery(db, 'u1', 't1', 'op1')).toMatchObject({ status: 'errored' });
+ // Retried once before giving up.
+ expect(mocks.predict).toHaveBeenCalledTimes(2);
+ });
+
+ /**
+ * Regression: a review that could not run on one check was retried by
+ * rerunning the whole review. Every other check was re-asked and its opinion
+ * upserted over the first one, so a nondeterministic second pass could turn a
+ * rejection into an acceptance and let the delivery complete.
+ */
+ it('retries only the check whose review could not run, keeping the other verdicts', async () => {
+ const second = { ...check, id: 'c2', index: 1, title: 'Chart rendered' };
+ mocks.rounds.mockResolvedValue({
+ runs: [{ id: 'r1', roundIndex: 1, plan: [check, second] }],
+ results: [result, { ...result, id: 'result2', checkItemId: 'c2' }],
+ });
+ let firstCheckAttempts = 0;
+ mocks.predict.mockImplementation(async ({ checkResultId }: { checkResultId: string }) => {
+ if (checkResultId === 'result2')
+ return { id: 'p2', status: 'judged', action: 'reject', comment: 'The chart is blank.' };
+ firstCheckAttempts += 1;
+ return firstCheckAttempts === 1
+ ? { id: 'p1', status: 'errored', statusReason: 'ECONNRESET' }
+ : { id: 'p1', status: 'judged', action: 'accept' };
+ });
+
+ expect(await reviewGoalDelivery(db, 'u1', 't1', 'op1')).toMatchObject({ status: 'rejected' });
+ const calls = mocks.predict.mock.calls.map(([params]) => params.checkResultId);
+ expect(calls.filter((id) => id === 'result1')).toHaveLength(2);
+ expect(calls.filter((id) => id === 'result2')).toHaveLength(1);
});
});
diff --git a/apps/server/src/services/verify/__tests__/goalReviewEvidence.test.ts b/apps/server/src/services/verify/__tests__/goalReviewEvidence.test.ts
index 1d29ca5b8f2..765f424fdbd 100644
--- a/apps/server/src/services/verify/__tests__/goalReviewEvidence.test.ts
+++ b/apps/server/src/services/verify/__tests__/goalReviewEvidence.test.ts
@@ -16,6 +16,7 @@ const mocks = vi.hoisted(() => ({
file: vi.fn(),
content: vi.fn(),
url: vi.fn(),
+ bytes: vi.fn(),
}));
vi.mock('@/database/models/verifyCheckResult', () => ({
VerifyCheckResultModel: vi.fn(function () {
@@ -47,7 +48,11 @@ vi.mock('@/database/models/file', () => ({
}));
vi.mock('@/server/services/file', () => ({
FileService: vi.fn(function () {
- return { getFileAccessUrl: mocks.url, getFileContent: mocks.content };
+ return {
+ getFileAccessUrl: mocks.url,
+ getFileByteArray: mocks.bytes,
+ getFileContent: mocks.content,
+ };
}),
}));
vi.mock('@/server/services/aiGeneration', () => ({
@@ -165,6 +170,39 @@ describe('Goal review evidence', () => {
expect(prediction?.statusReason).toContain('1 more frame(s)');
});
+ /**
+ * Regression: frames went to the provider as links it had to download. A
+ * provider that could not reach the storage behind them (a bucket on
+ * localhost or a private network) failed every review of the check with
+ * "Error while downloading file", and a Goal Task spent its whole attempt
+ * budget re-delivering into a review that could never open its screenshot.
+ */
+ it('sends a stored frame inline instead of a link the provider must fetch', async () => {
+ mocks.evidence.mockResolvedValue([{ fileId: 'f1', id: 's1', type: 'screenshot' }]);
+ mocks.file.mockResolvedValue({ fileType: 'image/png', id: 'f1', size: 4, url: 'key-f1' });
+ mocks.bytes.mockResolvedValue(new Uint8Array([0x89, 0x50, 0x4e, 0x47]));
+
+ await review().predict(params);
+ const payload = JSON.stringify(mocks.generate.mock.calls[0][0].messages);
+ expect(payload).toContain('data:image/png;base64,iVBORw==');
+ expect(mocks.url).not.toHaveBeenCalled();
+ });
+
+ it('links a frame too large to send inline', async () => {
+ mocks.evidence.mockResolvedValue([{ fileId: 'f1', id: 's1', type: 'screenshot' }]);
+ mocks.file.mockResolvedValue({
+ fileType: 'image/png',
+ id: 'f1',
+ size: 50 * 1024 * 1024,
+ url: 'key-f1',
+ });
+ mocks.url.mockResolvedValue('https://x/f1');
+
+ await review().predict(params);
+ expect(JSON.stringify(mocks.generate.mock.calls[0][0].messages)).toContain('https://x/f1');
+ expect(mocks.bytes).not.toHaveBeenCalled();
+ });
+
it('leaves no caveat on a check whose evidence was fully shown', async () => {
const prediction = await review().predict({ ...params, includeTextEvidence: true });
expect(prediction?.statusReason).toBeUndefined();
diff --git a/apps/server/src/services/verify/executor.ts b/apps/server/src/services/verify/executor.ts
index 6727877418a..7653982cb8c 100644
--- a/apps/server/src/services/verify/executor.ts
+++ b/apps/server/src/services/verify/executor.ts
@@ -30,6 +30,7 @@ import { FileService } from '@/server/services/file';
import { coverageGaps, readRequiredEvidence } from './evidenceCoverage';
import { planEvidenceVerification } from './evidencePlanner';
+import { resolveModelReadableFrameUrl } from './modelFrames';
import { planItemToPendingResult } from './resultSnapshot';
import { BatchVerdictSchema, type SingleVerdict, SingleVerdictSchema } from './schema';
import { VerifyStatusService } from './statusService';
@@ -234,10 +235,7 @@ export class VerifyExecutorService {
if (!item.fileId || (item.type !== 'screenshot' && item.type !== 'gif')) return item;
const file = await this.fileModel.findById(item.fileId);
if (!file) return item;
- return {
- ...item,
- accessUrl: await this.fileService.getFileAccessUrl({ id: file.id, url: file.url }),
- };
+ return { ...item, accessUrl: await resolveModelReadableFrameUrl(this.fileService, file) };
}),
);
}
diff --git a/apps/server/src/services/verify/goalReview.ts b/apps/server/src/services/verify/goalReview.ts
index 27d65be7905..04a7e338229 100644
--- a/apps/server/src/services/verify/goalReview.ts
+++ b/apps/server/src/services/verify/goalReview.ts
@@ -97,19 +97,27 @@ export const reviewGoalDelivery = async (
);
return;
}
- const prediction = await predictor
- .predict({
- checkResultId: check.result.id,
- includeTextEvidence: true,
- instructionDocumentId: check.planItem?.documentId,
- modelConfig,
- requirement: acceptance.requirement,
- surface: check.surface,
- })
- .catch((error) => {
- console.error('[goal-review] Check review failed:', error);
- return null;
- });
+ const checkResultId = check.result.id;
+ const judge = () =>
+ predictor
+ .predict({
+ checkResultId,
+ includeTextEvidence: true,
+ instructionDocumentId: check.planItem?.documentId,
+ modelConfig,
+ requirement: acceptance.requirement,
+ surface: check.surface,
+ })
+ .catch((error) => {
+ console.error('[goal-review] Check review failed:', error);
+ return null;
+ });
+ let prediction = await judge();
+ // A check whose review could not run is retried once, on its own, which
+ // absorbs a dropped connection. Retrying the whole review instead re-asks
+ // every other check, and a nondeterministic second opinion can overwrite a
+ // first-pass rejection and let the delivery through.
+ if (!prediction || prediction.status === 'errored') prediction = await judge();
if (prediction) review.predictionIds.push(prediction.id);
if (prediction?.status === 'judged' && prediction.action === 'accept') return;
if (prediction?.status === 'errored' || !prediction) {
diff --git a/apps/server/src/services/verify/modelFrames.ts b/apps/server/src/services/verify/modelFrames.ts
new file mode 100644
index 00000000000..5905bfeb6f8
--- /dev/null
+++ b/apps/server/src/services/verify/modelFrames.ts
@@ -0,0 +1,63 @@
+import debug from 'debug';
+
+import type { FileService } from '@/server/services/file';
+
+const log = debug('lobe-server:verify-model-frames');
+
+/**
+ * Ceiling on a frame sent inline. Evidence screenshots sit far below it; past it
+ * the base64 body (a third larger than the file) would push a multi-frame
+ * request toward provider payload limits, so the frame falls back to a link.
+ */
+export const MAX_INLINE_FRAME_BYTES = 5 * 1024 * 1024;
+
+interface StoredFrame {
+ fileType?: string | null;
+ id: string;
+ size?: number | null;
+ url: string;
+}
+
+/** Recognize the image formats a vision model accepts from their leading bytes. */
+const sniffImageMimeType = (bytes: Uint8Array): string | undefined => {
+ const startsWith = (...signature: number[]) =>
+ signature.every((byte, index) => bytes[index] === byte);
+ if (startsWith(0x89, 0x50, 0x4e, 0x47)) return 'image/png';
+ if (startsWith(0xff, 0xd8, 0xff)) return 'image/jpeg';
+ if (startsWith(0x47, 0x49, 0x46, 0x38)) return 'image/gif';
+ if (
+ startsWith(0x52, 0x49, 0x46, 0x46) &&
+ String.fromCharCode(...bytes.subarray(8, 12)) === 'WEBP'
+ )
+ return 'image/webp';
+};
+
+/**
+ * The URL a judging model is given for a stored evidence frame.
+ *
+ * The frame is read from our own storage and sent as a data URI. A link makes
+ * the provider download the file itself, which is the one step of the request
+ * we do not control: a bucket on localhost or a private network is unreachable
+ * from the provider, and the model call fails with "Error while downloading
+ * file" on every attempt, however many times the review is retried.
+ *
+ * Falls back to the access URL when the frame is too large to inline, is not a
+ * recognizable image, or cannot be read.
+ */
+export const resolveModelReadableFrameUrl = async (
+ fileService: FileService,
+ file: StoredFrame,
+): Promise<string> => {
+ if (typeof file.size === 'number' && file.size > 0 && file.size <= MAX_INLINE_FRAME_BYTES) {
+ try {
+ const bytes = await fileService.getFileByteArray(file.url);
+ const mimeType = file.fileType?.startsWith('image/')
+ ? file.fileType
+ : sniffImageMimeType(bytes);
+ if (mimeType) return `data:${mimeType};base64,${Buffer.from(bytes).toString('base64')}`;
+ } catch (error) {
+ log('could not inline frame %s, linking it instead: %O', file.id, error);
+ }
+ }
+ return fileService.getFileAccessUrl({ id: file.id, url: file.url });
+};
diff --git a/apps/server/src/services/verify/reviewPredictor.ts b/apps/server/src/services/verify/reviewPredictor.ts
index 59eedda7e64..c43f29db0f2 100644
--- a/apps/server/src/services/verify/reviewPredictor.ts
+++ b/apps/server/src/services/verify/reviewPredictor.ts
@@ -18,6 +18,7 @@ import type { LobeChatDatabase } from '@/database/type';
import { AiGenerationService } from '@/server/services/aiGeneration';
import { FileService } from '@/server/services/file';
+import { resolveModelReadableFrameUrl } from './modelFrames';
import type { ReviewEvidenceRow } from './reviewEvidence';
import { formatTextEvidence, TEXT_EVIDENCE_TYPES } from './reviewEvidence';
import { describeWithheldEvidence } from './reviewInspection';
@@ -359,7 +360,7 @@ export class VerifyReviewPredictorService {
const file = await this.fileModel.findById(row.fileId!);
if (!file) return null;
return {
- accessUrl: await this.fileService.getFileAccessUrl({ id: file.id, url: file.url }),
+ accessUrl: await resolveModelReadableFrameUrl(this.fileService, file),
description: row.description,
evidenceId: row.id,
};
diff --git a/apps/server/src/services/verify/settle.ts b/apps/server/src/services/verify/settle.ts
index 63719a72b32..fdd126f9f68 100644
--- a/apps/server/src/services/verify/settle.ts
+++ b/apps/server/src/services/verify/settle.ts
@@ -1,4 +1,5 @@
import {
+ ACCEPTANCE_REVIEW_ERRORED_ERROR,
VERIFICATION_ERRORED_ERROR,
VERIFICATION_FAILED_ERROR,
VERIFICATION_UNJUDGEABLE_ERROR,
@@ -104,6 +105,9 @@ export const driveTaskFromVerify = async (
const task = await taskModel.findById(taskOperation.taskId);
if (!task || TERMINAL_TASK_STATUS.has(task.status)) return; // task already settled
+ // The review already retries a check whose review could not run. An
+ // `errored` result here is the reviewer's problem, and another builder
+ // attempt would only re-deliver into the same broken review.
const goalReview =
run.status === 'passed'
? await reviewGoalDelivery(db, userId, taskOperation.taskId, operationId, workspaceId)
@@ -112,7 +116,7 @@ export const driveTaskFromVerify = async (
goalReview?.status === 'rejected'
? 'failed'
: goalReview?.status === 'errored'
- ? 'errored'
+ ? 'review_errored'
: goalReview?.status === 'unjudgeable'
? 'unjudgeable'
: run.status;
@@ -137,27 +141,32 @@ export const driveTaskFromVerify = async (
log('verify passed β†’ task %s completed', taskOperation.taskId);
}
} else {
- // Three non-pass outcomes, kept distinct so an infra error never reads as a
+ // Four non-pass outcomes, kept distinct so an infra error never reads as a
// rejected delivery:
- // - failed: the verifier ran and judged the delivery short of the criteria.
- // - errored: the verifier could not run (infra) β€” the delivery was NOT
- // evaluated, so we must not claim it "did not pass".
- // - unjudgeable: the review read the evidence and the criterion turned out
- // undecidable from it. Another attempt would re-deliver the
- // same artifacts against the same unprovable criterion, so
- // this one routes to a person instead of a retry.
- const isErrored = outcome === 'errored';
+ // - failed: the verifier ran and judged the delivery short of the criteria.
+ // - errored: the verifier could not run (infra) β€” the delivery was NOT
+ // evaluated, so we must not claim it "did not pass".
+ // - review_errored: the verifiers passed, but the Acceptance review on top of
+ // them still could not run after its retry. The builder
+ // cannot fix a broken reviewer, so this routes to a person.
+ // - unjudgeable: the review read the evidence and the criterion turned out
+ // undecidable from it. Another attempt would re-deliver the
+ // same artifacts against the same unprovable criterion, so
+ // this one routes to a person instead of a retry.
+ const isErrored = outcome === 'errored' || outcome === 'review_errored';
- // All three summaries are contract strings, not copy: the Goal coordinator
+ // Every summary is a contract string, not copy: the Goal coordinator
// matches on them to decide whether a paused Goal Task starts another
// attempt or opens a decision gate. They live in `@lobechat/const/goal`
// so the writer and the reader cannot drift apart.
const pauseSummary =
outcome === 'unjudgeable'
? VERIFICATION_UNJUDGEABLE_ERROR
- : isErrored
- ? VERIFICATION_ERRORED_ERROR
- : VERIFICATION_FAILED_ERROR;
+ : outcome === 'review_errored'
+ ? ACCEPTANCE_REVIEW_ERRORED_ERROR
+ : isErrored
+ ? VERIFICATION_ERRORED_ERROR
+ : VERIFICATION_FAILED_ERROR;
if (task.automationMode) {
// Mirror of the pass branch: verify judges THIS tick, not the lifetime
// schedule. Pausing here would permanently disarm the cron (the
@@ -189,7 +198,7 @@ export const driveTaskFromVerify = async (
const errorMessage =
outcome === 'failed'
? 'Delivery did not pass verification.'
- : outcome === 'errored'
+ : outcome === 'errored' || outcome === 'review_errored'
? 'Verification could not be completed due to an internal error; the delivery was not evaluated. Please retry or review it manually.'
: outcome === 'unjudgeable'
? 'Acceptance review could not judge this delivery from the captured evidence. Review it manually, or restate the check so evidence can settle it.'
diff --git a/packages/const/src/goal.ts b/packages/const/src/goal.ts
index b26863a864c..cbc442d4d8d 100644
--- a/packages/const/src/goal.ts
+++ b/packages/const/src/goal.ts
@@ -76,3 +76,15 @@ export const VERIFICATION_ERRORED_ERROR =
*/
export const VERIFICATION_UNJUDGEABLE_ERROR =
'Acceptance review could not judge the delivery from evidence alone; the criterion needs a judge that can act on the system.';
+/**
+ * The delivery's own verifiers ran and passed, but the Acceptance review layered
+ * on top of them could not run β€” a provider outage that outlived the in-place
+ * retry, a reviewer without credentials, an artifact the review model could not
+ * open.
+ *
+ * Deliberately has NO recovery branch. Recovering it like a rejection started a
+ * fresh builder attempt, which re-delivered into the same broken review and spent
+ * the Task's attempt budget without the delivery ever being judged.
+ */
+export const ACCEPTANCE_REVIEW_ERRORED_ERROR =
+ 'Acceptance review could not run; the delivery passed its verifiers but was never reviewed.';