Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(acceptance): run each Task's Acceptance inside its own run (#19139)

Arvin Xu150f3fd8e176
diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.ts
index cbb2f97f393..7d4648d82a2 100644
--- a/apps/server/src/services/goal/index.test.ts
+++ b/apps/server/src/services/goal/index.test.ts
@@ -696,9 +696,7 @@ describe('GoalService', () => {
'Current Task contract (authoritative execution scope): Generate training data',
);
expect(task?.instruction).toContain('Do not implement, validate, or pre-empt any sibling');
- expect(task?.instruction).toContain(
- 'Do not invoke Acceptance skills or Acceptance CLI commands',
- );
+ expect(task?.instruction).toContain('run it inside this Task');
expect(task?.instruction).toContain(
'Include the relevant artifact contents or exact excerpts and the raw outputs of decisive verification commands',
);
diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.ts
index 50aba38fce4..da84583409d 100644
--- a/apps/server/src/services/goal/index.ts
+++ b/apps/server/src/services/goal/index.ts
@@ -1254,7 +1254,7 @@ export class GoalService {
`Current Task contract (authoritative execution scope): ${title}`,
description,
'Execute only the Current Task contract. Do not implement, validate, or pre-empt any sibling or downstream Task node, even when the overall goal context describes it.',
- 'The complete requirements for this Task are included here. Do not inspect unrelated agent documents to recover requirements. Do not invoke Acceptance skills or Acceptance CLI commands during the main Task; a dedicated post-run phase will ask you to submit your evidence before an independent verifier judges it.',
+ 'The complete requirements for this Task are included here. Do not inspect unrelated agent documents to recover requirements. This Task carries its own Acceptance: run it inside this Task β€” drive the real product surface, capture the evidence, and submit it against your own criteria while you work. Submit evidence only; an independent verifier judges whether this Task is complete.',
'Create implementation-level subtasks when useful. Finish the operation once the Current Task deliverable and its concrete evidence are ready; Acceptance verification will decide whether this Task is complete.',
'Make the final delivery self-contained for an independent verifier that may not have workspace access. Include the relevant artifact contents or exact excerpts and the raw outputs of decisive verification commands; file paths and claims that checks passed are not sufficient evidence by themselves.',
'Return the produced artifacts, evidence, key findings, and the recommended next action. Do not mark the overall Goal complete.',
diff --git a/apps/server/src/services/taskRunner/buildTaskPrompt.ts b/apps/server/src/services/taskRunner/buildTaskPrompt.ts
index da5bd761632..cc55441d376 100644
--- a/apps/server/src/services/taskRunner/buildTaskPrompt.ts
+++ b/apps/server/src/services/taskRunner/buildTaskPrompt.ts
@@ -89,6 +89,9 @@ export interface BuildTaskPromptDeps {
}
export interface BuiltTaskPrompt {
+ /** The Task carries an active Acceptance, so the builder needs the evidence
+ * tool mounted for the whole run β€” it submits while it works. */
+ acceptanceEnabled: boolean;
/** Merged, deduplicated list of fileIds (task instruction + all comments)
* to forward to execAgent so files arrive as multimodal inputs. */
fileIds: string[];
@@ -373,5 +376,5 @@ export async function buildTaskPrompt(
}),
});
- return { fileIds: allFileIds, prompt };
+ return { acceptanceEnabled: verifyEnabled, fileIds: allFileIds, prompt };
}
diff --git a/apps/server/src/services/taskRunner/index.ts b/apps/server/src/services/taskRunner/index.ts
index 267811c8a50..93bf812563f 100644
--- a/apps/server/src/services/taskRunner/index.ts
+++ b/apps/server/src/services/taskRunner/index.ts
@@ -1,4 +1,5 @@
import { TaskIdentifier as TaskSkillIdentifier } from '@lobechat/builtin-skills';
+import { AcceptanceEvidenceIdentifier } from '@lobechat/builtin-tool-acceptance-evidence';
import { BriefIdentifier } from '@lobechat/builtin-tool-brief';
import { INBOX_SESSION_ID } from '@lobechat/const';
import type { ExecAgentResult, TaskItem, TaskRunTrigger } from '@lobechat/types';
@@ -133,7 +134,11 @@ export class TaskRunnerService {
}
}
- const { fileIds: attachmentFileIds, prompt } = await buildTaskPrompt(
+ const {
+ acceptanceEnabled,
+ fileIds: attachmentFileIds,
+ prompt,
+ } = await buildTaskPrompt(
task,
{
briefModel: this.briefModel,
@@ -184,6 +189,11 @@ export class TaskRunnerService {
if (briefMode === 'agent' && !reviewConfig?.enabled && checkpoint.onAgentRequest !== false) {
pluginIds.push(BriefIdentifier);
}
+ // The Acceptance runs inside the Task, so the builder needs listCriteria +
+ // submitEvidence for the whole run β€” not only in the post-run evidence
+ // turn, which mounts this tool exclusively and therefore can only ever
+ // restate text it already wrote.
+ if (acceptanceEnabled) pluginIds.push(AcceptanceEvidenceIdentifier);
const taskConfig = (task.config ?? {}) as Record<string, unknown>;
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/browser.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/browser.test.ts
index d5172ff72ed..33ceb242bff 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/browser.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/browser.test.ts
@@ -11,6 +11,11 @@ vi.mock('@/server/services/deviceGateway', () => ({
},
}));
+const mockUploadBase64 = vi.fn();
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn(() => ({ uploadBase64: mockUploadBase64 })),
+}));
+
// Import after mock setup
const { browserRuntime } = await import('../browser');
@@ -19,6 +24,98 @@ describe('browserRuntime', () => {
vi.clearAllMocks();
});
+ describe('screenshot', () => {
+ const screenshotContext = {
+ activeDeviceId: 'device-1',
+ agentId: 'agt-1',
+ operationId: 'op-1',
+ serverDB: {} as any,
+ toolManifestMap: {},
+ topicId: 'tpc-1',
+ userId: 'user-1',
+ } as ToolExecutionContext;
+
+ it('stores the capture as a file and exposes it on state.images', async () => {
+ // The heterogeneous pipeline already uploads a tool_result image and
+ // rewrites it to { fileId, url }. Proxying the device dataUrl verbatim
+ // left this runtime as the only image-producing tool with no file behind
+ // it β€” the model could not see its own screenshot and nothing downstream
+ // had an id to cite.
+ mockExecuteToolCall.mockResolvedValue({
+ content: '',
+ state: { dataUrl: 'data:image/jpeg;base64,QUJD', height: 100, width: 200 },
+ success: true,
+ });
+ mockUploadBase64.mockResolvedValue({
+ fileId: 'file_1',
+ key: 'k',
+ url: 'https://cdn.example.com/shot.jpeg',
+ });
+
+ const runtime = browserRuntime.factory(screenshotContext);
+ const result = await runtime.screenshot({});
+
+ expect(mockUploadBase64).toHaveBeenCalledWith(
+ 'QUJD',
+ expect.stringMatching(/^files\/\d{4}-\d{2}-\d{2}\/browser-screenshot-\d+\.jpg$/),
+ { fileType: 'image/jpeg' },
+ );
+ // `state` reaches the model as image parts, not text, so the id has to be
+ // named in `content` or a builder can see the shot without being able to
+ // cite it.
+ expect(result.content).toContain('file_1');
+ expect(result.state).toEqual({
+ height: 100,
+ images: [
+ { fileId: 'file_1', mediaType: 'image/jpeg', url: 'https://cdn.example.com/shot.jpeg' },
+ ],
+ // `dataUrl` was both the model's copy and the chat renderer's src, so
+ // dropping it without a replacement blanked every proxied screenshot.
+ url: 'https://cdn.example.com/shot.jpeg',
+ width: 200,
+ });
+ // The base64 must not survive into the persisted tool state.
+ expect(result.state.dataUrl).toBeUndefined();
+ });
+
+ it('passes the capture through unchanged when the upload fails', async () => {
+ mockExecuteToolCall.mockResolvedValue({
+ content: '',
+ state: { dataUrl: 'data:image/jpeg;base64,QUJD' },
+ success: true,
+ });
+ mockUploadBase64.mockRejectedValue(new Error('s3 down'));
+
+ const runtime = browserRuntime.factory(screenshotContext);
+ const result = await runtime.screenshot({});
+
+ expect(result.state).toEqual({ dataUrl: 'data:image/jpeg;base64,QUJD' });
+ });
+
+ it('does not upload a stale dataUrl from a failed capture', async () => {
+ mockExecuteToolCall.mockResolvedValue({
+ content: 'Browser action failed',
+ state: { dataUrl: 'data:image/jpeg;base64,QUJD' },
+ success: false,
+ });
+
+ const runtime = browserRuntime.factory(screenshotContext);
+ const result = await runtime.screenshot({});
+
+ expect(mockUploadBase64).not.toHaveBeenCalled();
+ expect(result.success).toBe(false);
+ });
+
+ it('leaves non-screenshot apis untouched', async () => {
+ mockExecuteToolCall.mockResolvedValue({ content: 'OK', success: true });
+
+ const runtime = browserRuntime.factory(screenshotContext);
+ await runtime.navigate({ url: 'https://example.com' });
+
+ expect(mockUploadBase64).not.toHaveBeenCalled();
+ });
+ });
+
it('should have the correct identifier', () => {
expect(browserRuntime.identifier).toBe(BrowserIdentifier);
});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.test.ts
index 137500d9570..d4af3866b37 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.test.ts
@@ -6,6 +6,7 @@ import { acceptanceEvidenceRuntime } from './acceptanceEvidence';
const mocks = vi.hoisted(() => ({
documentFindByIds: vi.fn(),
evidenceCreateMany: vi.fn(),
+ evidenceListByRun: vi.fn(),
fileFindById: vi.fn(),
operationFindById: vi.fn(),
resultUpsert: vi.fn(),
@@ -25,7 +26,10 @@ vi.mock('@/database/models/verifyCheckResult', () => ({
VerifyCheckResultModel: vi.fn(() => ({ upsertByCheckItem: mocks.resultUpsert })),
}));
vi.mock('@/database/models/verifyEvidence', () => ({
- VerifyEvidenceModel: vi.fn(() => ({ createMany: mocks.evidenceCreateMany })),
+ VerifyEvidenceModel: vi.fn(() => ({
+ createMany: mocks.evidenceCreateMany,
+ listByRun: mocks.evidenceListByRun,
+ })),
}));
vi.mock('@/database/models/verifyRun', () => ({
VerifyRunModel: vi.fn(() => ({ findByOperation: mocks.runFindByOperation })),
@@ -34,7 +38,10 @@ vi.mock('@/database/models/verifyRun', () => ({
describe('acceptanceEvidenceRuntime', () => {
beforeEach(() => {
vi.clearAllMocks();
- mocks.operationFindById.mockResolvedValue({ parentOperationId: 'parent-op' });
+ mocks.operationFindById.mockResolvedValue({
+ id: 'evidence-op',
+ parentOperationId: 'parent-op',
+ });
mocks.runFindByOperation.mockResolvedValue({
id: 'run-1',
plan: [
@@ -43,6 +50,7 @@ describe('acceptanceEvidenceRuntime', () => {
});
mocks.resultUpsert.mockResolvedValue({ id: 'result-1' });
mocks.evidenceCreateMany.mockResolvedValue([]);
+ mocks.evidenceListByRun.mockResolvedValue([]);
});
it('records a documents.id reference as first-class evidence', async () => {
@@ -84,6 +92,239 @@ describe('acceptanceEvidenceRuntime', () => {
expect(mocks.evidenceCreateMany).not.toHaveBeenCalled();
});
+ it('submits against its own run when the builder captures evidence inside the main Task', async () => {
+ // A main Task run has no parentOperationId. Resolving only the parent made
+ // every in-run submit fail NO_PARENT_OPERATION, which is why the Acceptance
+ // could only ever be evidenced by the text-only post-run turn.
+ mocks.operationFindById.mockResolvedValue({ id: 'task-op', parentOperationId: null });
+ mocks.fileFindById.mockResolvedValue({ id: 'files_shot' });
+ const runtime = acceptanceEvidenceRuntime.factory({
+ operationId: 'task-op',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ userId: 'user-1',
+ });
+
+ const result = await runtime.submitEvidence({
+ checkItemId: 'criterion-1',
+ evidence: [{ fileId: 'files_shot', type: 'screenshot' }],
+ });
+
+ expect(result.success).toBe(true);
+ expect(mocks.runFindByOperation).toHaveBeenCalledWith('task-op');
+ expect(mocks.resultUpsert).toHaveBeenCalledWith(
+ expect.objectContaining({ operationId: 'task-op' }),
+ );
+ });
+
+ it('keeps writing into the parent run from the post-run evidence turn', async () => {
+ const runtime = acceptanceEvidenceRuntime.factory({
+ operationId: 'evidence-op',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ userId: 'user-1',
+ });
+
+ const result = await runtime.submitEvidence({
+ checkItemId: 'criterion-1',
+ evidence: [{ content: 'raw output', type: 'text' }],
+ });
+
+ expect(result.success).toBe(true);
+ expect(mocks.runFindByOperation).toHaveBeenCalledWith('parent-op');
+ });
+
+ it('lists the run criteria with the evidence already captured for each', async () => {
+ mocks.operationFindById.mockResolvedValue({ id: 'task-op', parentOperationId: null });
+ mocks.runFindByOperation.mockResolvedValue({
+ id: 'run-1',
+ plan: [
+ {
+ id: 'criterion-1',
+ index: 0,
+ required: true,
+ title: 'Document',
+ verifierConfig: { requiredEvidence: [{ hint: 'full page', type: 'screenshot' }] },
+ verifierType: 'llm',
+ },
+ { id: 'criterion-2', index: 1, required: false, title: 'Clean', verifierType: 'llm' },
+ ],
+ });
+ mocks.evidenceListByRun.mockResolvedValue([
+ { checkItemId: 'criterion-1' },
+ { checkItemId: 'criterion-1' },
+ ]);
+
+ const runtime = acceptanceEvidenceRuntime.factory({
+ operationId: 'task-op',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ userId: 'user-1',
+ });
+
+ const result = await runtime.listCriteria();
+
+ expect(result).toEqual(
+ expect.objectContaining({
+ criteria: [
+ {
+ id: 'criterion-1',
+ index: 0,
+ required: true,
+ requiredEvidence: [{ hint: 'full page', type: 'screenshot' }],
+ submittedEvidence: 2,
+ title: 'Document',
+ },
+ {
+ id: 'criterion-2',
+ index: 1,
+ required: false,
+ submittedEvidence: 0,
+ title: 'Clean',
+ },
+ ],
+ success: true,
+ }),
+ );
+ });
+
+ it('treats padded empty-string ids as absent instead of failing the lookup', async () => {
+ // A live builder run submitted { content, documentId: '', fileId: '' } nine
+ // times and every call was rejected as UNKNOWN_FILE, so the acceptance
+ // ended with zero evidence. Empty strings are absent, not references.
+ mocks.operationFindById.mockResolvedValue({ id: 'task-op', parentOperationId: null });
+ const runtime = acceptanceEvidenceRuntime.factory({
+ operationId: 'task-op',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ userId: 'user-1',
+ });
+
+ const result = await runtime.submitEvidence({
+ checkItemId: 'criterion-1',
+ evidence: [{ content: 'raw output', documentId: '', fileId: '', type: 'markdown' }],
+ });
+
+ expect(result.success).toBe(true);
+ expect(mocks.fileFindById).not.toHaveBeenCalled();
+ expect(mocks.documentFindByIds).not.toHaveBeenCalled();
+ expect(mocks.evidenceCreateMany).toHaveBeenCalledWith([
+ expect.objectContaining({ content: 'raw output', documentId: null, fileId: null }),
+ ]);
+ });
+
+ it('returns readable content so the model does not see a synthetic tool failure', async () => {
+ // A tool result with no readable `content` is replaced downstream by
+ // `{"error":"Tool call failed"}`, which made a live builder abandon the
+ // plan-driven path on its first call.
+ mocks.operationFindById.mockResolvedValue({ id: 'task-op', parentOperationId: null });
+ const runtime = acceptanceEvidenceRuntime.factory({
+ operationId: 'task-op',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ userId: 'user-1',
+ });
+
+ const result = await runtime.listCriteria();
+
+ expect(typeof result.content).toBe('string');
+ expect(result.content).toContain('criterion-1');
+ expect(result.content).toContain('Document');
+ });
+
+ it('accepts a caption alongside a cited artifact', async () => {
+ // A live builder that had captured a screenshot AND wanted to describe it
+ // was rejected, dropped the fileId, and resubmitted prose with the id
+ // written into the text β€” the text-only outcome this path exists to prevent.
+ mocks.operationFindById.mockResolvedValue({ id: 'task-op', parentOperationId: null });
+ mocks.fileFindById.mockResolvedValue({ id: 'files_shot' });
+ const runtime = acceptanceEvidenceRuntime.factory({
+ operationId: 'task-op',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ userId: 'user-1',
+ });
+
+ const result = await runtime.submitEvidence({
+ checkItemId: 'criterion-1',
+ evidence: [{ content: 'The sign-in page rendered', fileId: 'files_shot', type: 'screenshot' }],
+ });
+
+ expect(result.success).toBe(true);
+ expect(mocks.evidenceCreateMany).toHaveBeenCalledWith([
+ expect.objectContaining({ content: 'The sign-in page rendered', fileId: 'files_shot' }),
+ ]);
+ });
+
+ it('rejects an item that references both a document and a file', async () => {
+ mocks.operationFindById.mockResolvedValue({ id: 'task-op', parentOperationId: null });
+ const runtime = acceptanceEvidenceRuntime.factory({
+ operationId: 'task-op',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ userId: 'user-1',
+ });
+
+ const result = await runtime.submitEvidence({
+ checkItemId: 'criterion-1',
+ evidence: [{ documentId: 'docs_1', fileId: 'files_1', type: 'markdown' }],
+ });
+
+ expect(result).toEqual(
+ expect.objectContaining({ error: 'INVALID_EVIDENCE', success: false }),
+ );
+ });
+
+ it('waits for a plan that the fire-and-forget run-start instantiation has not landed yet', async () => {
+ // Answering NO_ACCEPTANCE_PLAN to a builder that asks what to prove as its
+ // first move reads as "this Task has no Acceptance", and the run then ends
+ // with no evidence at all.
+ mocks.operationFindById.mockResolvedValue({ id: 'task-op', parentOperationId: null });
+ mocks.runFindByOperation
+ .mockResolvedValueOnce(undefined)
+ .mockResolvedValueOnce({ id: 'run-1', plan: [] })
+ .mockResolvedValue({
+ id: 'run-1',
+ plan: [{ id: 'criterion-1', index: 0, required: true, title: 'Late', verifierType: 'llm' }],
+ });
+
+ const runtime = acceptanceEvidenceRuntime.factory({
+ operationId: 'task-op',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ userId: 'user-1',
+ });
+
+ const result = await runtime.listCriteria();
+
+ expect(result.success).toBe(true);
+ expect(result.criteria).toHaveLength(1);
+ expect(mocks.runFindByOperation.mock.calls.length).toBeGreaterThan(2);
+ });
+
+ it('rejects a visual type that has no artifact behind it', async () => {
+ // A live builder submitted { type: 'screenshot', content: '…(see the
+ // screenshot file)' } with no file, which would render on the acceptance
+ // as a visual check with nothing to open.
+ mocks.operationFindById.mockResolvedValue({ id: 'task-op', parentOperationId: null });
+ const runtime = acceptanceEvidenceRuntime.factory({
+ operationId: 'task-op',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ userId: 'user-1',
+ });
+
+ const result = await runtime.submitEvidence({
+ checkItemId: 'criterion-1',
+ evidence: [{ content: 'I opened the page and captured it', fileId: '', type: 'screenshot' }],
+ });
+
+ expect(result).toEqual(
+ expect.objectContaining({ error: 'UNBACKED_VISUAL_EVIDENCE', success: false }),
+ );
+ expect(mocks.evidenceCreateMany).not.toHaveBeenCalled();
+ });
+
it('rejects an unknown files.id before the evidence foreign key is evaluated', async () => {
mocks.fileFindById.mockResolvedValue(undefined);
const runtime = acceptanceEvidenceRuntime.factory({
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.ts b/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.ts
index 99e42b2551d..eff78d4c236 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/acceptanceEvidence.ts
@@ -1,4 +1,7 @@
-import type { SubmitAcceptanceEvidenceParams } from '@lobechat/builtin-tool-acceptance-evidence';
+import type {
+ AcceptanceCriterionSummary,
+ SubmitAcceptanceEvidenceParams,
+} from '@lobechat/builtin-tool-acceptance-evidence';
import { AcceptanceEvidenceIdentifier } from '@lobechat/builtin-tool-acceptance-evidence';
import { AgentOperationModel } from '@/database/models/agentOperation';
@@ -11,6 +14,10 @@ import type { LobeChatDatabase } from '@/database/type';
import type { ServerRuntimeRegistration } from './types';
+/** Bounded wait for the run-start plan instantiation to land (~3s total). */
+const PLAN_WAIT_ATTEMPTS = 6;
+const PLAN_WAIT_INTERVAL_MS = 500;
+
class AcceptanceEvidenceExecutionRuntime {
constructor(
private readonly db: LobeChatDatabase,
@@ -19,34 +26,167 @@ class AcceptanceEvidenceExecutionRuntime {
private readonly workspaceId?: string,
) {}
- submitEvidence = async (params: SubmitAcceptanceEvidenceParams) => {
+ /**
+ * The Agent Run whose verify plan this tool writes into.
+ *
+ * The builder now captures evidence inside the main Task run, so the plan
+ * hangs off the operation the tool is called from. The post-run
+ * evidence-submission turn is a *child* operation, and its plan still lives
+ * on the parent β€” hence the parent wins when there is one. Resolving only the
+ * parent (the original shape) made every in-run call fail NO_PARENT_OPERATION.
+ */
+ private resolveRunOperationId = async () => {
+ if (!this.operationId) return undefined;
+ const operation = await new AgentOperationModel(
+ this.db,
+ this.userId,
+ this.workspaceId,
+ ).findById(this.operationId);
+ if (!operation) return undefined;
+ return operation.parentOperationId ?? operation.id;
+ };
+
+ listCriteria = async () => {
if (!this.operationId) return { error: 'NO_OPERATION', success: false };
- if (!params.checkItemId || !params.evidence?.length) {
- return { error: 'INVALID_ARGUMENTS', success: false };
+
+ const runOperationId = await this.resolveRunOperationId();
+ if (!runOperationId) return { error: 'NO_OPERATION', success: false };
+
+ // The plan is instantiated fire-and-forget at run start, so a builder that
+ // asks what to prove as its first move can legitimately arrive before it
+ // lands. Answering NO_ACCEPTANCE_PLAN then reads as "this Task has no
+ // Acceptance" and the run finishes with no evidence at all, so wait out the
+ // race instead of racing it.
+ const runModel = new VerifyRunModel(this.db, this.userId, this.workspaceId);
+ let run = await runModel.findByOperation(runOperationId);
+ for (let attempt = 0; !run?.plan?.length && attempt < PLAN_WAIT_ATTEMPTS; attempt++) {
+ await new Promise((resolve) => setTimeout(resolve, PLAN_WAIT_INTERVAL_MS));
+ run = await runModel.findByOperation(runOperationId);
}
- if (
- params.evidence.some(
- (item) =>
- [item.content, item.documentId, item.fileId].filter((value) => Boolean(value)).length !==
- 1,
- )
- ) {
+ if (!run?.plan?.length) {
return {
- content: 'Every evidence item must provide exactly one of content, documentId, or fileId.',
- error: 'INVALID_EVIDENCE',
+ content:
+ 'No Acceptance plan is attached to this run yet. If this Task is expected to have one, ' +
+ 'continue working and call listCriteria again before you finish.',
+ error: 'NO_ACCEPTANCE_PLAN',
success: false,
};
}
- const operation = await new AgentOperationModel(
+ const evidence = await new VerifyEvidenceModel(
this.db,
this.userId,
this.workspaceId,
- ).findById(this.operationId);
- if (!operation?.parentOperationId) return { error: 'NO_PARENT_OPERATION', success: false };
+ ).listByRun(run.id);
+ const submittedByItem = new Map<string, number>();
+ for (const row of evidence) {
+ submittedByItem.set(row.checkItemId, (submittedByItem.get(row.checkItemId) ?? 0) + 1);
+ }
+
+ const criteria: AcceptanceCriterionSummary[] = run.plan.map((item) => {
+ const declared = (item.verifierConfig as Record<string, unknown> | undefined)
+ ?.requiredEvidence;
+ return {
+ id: item.id,
+ index: item.index,
+ required: item.required,
+ ...(Array.isArray(declared)
+ ? { requiredEvidence: declared as Array<{ hint?: string; type: string }> }
+ : {}),
+ submittedEvidence: submittedByItem.get(item.id) ?? 0,
+ title: item.title,
+ };
+ });
+
+ // `content` is what the model actually reads: the context engine replaces a
+ // tool result with no readable content by a synthetic
+ // `{"error":"Tool call failed"}`, so returning only structured fields made
+ // this API look broken to the builder and pushed it off the plan-driven path.
+ const content = criteria
+ .map(
+ (item) =>
+ `- ${item.id} β€” ${item.title}${item.required ? ' (required)' : ''}` +
+ `${item.requiredEvidence?.length ? `, requires ${item.requiredEvidence.map((e) => e.type).join('/')}` : ''}` +
+ `${item.submittedEvidence > 0 ? `, ${item.submittedEvidence} evidence already submitted` : ''}`,
+ )
+ .join('\n');
+
+ return {
+ content: `Acceptance criteria for this run β€” pass an id as checkItemId to submitEvidence:\n${content}`,
+ criteria,
+ success: true,
+ };
+ };
+
+ submitEvidence = async (rawParams: SubmitAcceptanceEvidenceParams) => {
+ if (!this.operationId) return { error: 'NO_OPERATION', success: false };
+ if (!rawParams.checkItemId || !rawParams.evidence?.length) {
+ return { error: 'INVALID_ARGUMENTS', success: false };
+ }
+
+ // Models routinely pad the fields they are not using with `""` rather than
+ // omitting them. An empty string is absent, not a reference: left as-is it
+ // survives the `?? []` id collection below and fails the lookup, rejecting
+ // an otherwise valid text submission as UNKNOWN_FILE.
+ const params: SubmitAcceptanceEvidenceParams = {
+ ...rawParams,
+ evidence: rawParams.evidence.map((item) => ({
+ ...item,
+ content: item.content?.trim() ? item.content : undefined,
+ documentId: item.documentId?.trim() ? item.documentId : undefined,
+ fileId: item.fileId?.trim() ? item.fileId : undefined,
+ })),
+ };
+
+ // `content` is a caption, not a competing payload. Requiring exactly one of
+ // the three made a live builder that had captured a screenshot AND wanted to
+ // describe it get rejected, drop the fileId, and resubmit prose with the id
+ // written into the text β€” the exact text-only outcome this path exists to
+ // prevent. Only the two *references* are mutually exclusive.
+ const empty = params.evidence.find((item) => !item.content && !item.documentId && !item.fileId);
+ if (empty) {
+ return {
+ content: 'Every evidence item needs content, a documentId, or a fileId.',
+ error: 'INVALID_EVIDENCE',
+ success: false,
+ };
+ }
+ const ambiguous = params.evidence.find((item) => item.documentId && item.fileId);
+ if (ambiguous) {
+ return {
+ content:
+ 'An evidence item references either a documentId or a fileId, not both. ' +
+ 'Use `content` for any prose you want to attach alongside it.',
+ error: 'INVALID_EVIDENCE',
+ success: false,
+ };
+ }
+
+ // A visual type is a claim about an artifact a reviewer can open. Prose
+ // saying a screenshot was taken is not that claim's evidence β€” a live run
+ // submitted `{ type: 'screenshot', content: '…(see the screenshot file)' }`
+ // with no file, which renders on the acceptance as a visual check with
+ // nothing behind it: strictly worse than an honest text note.
+ const unbacked = params.evidence.find(
+ (item) => (item.type === 'screenshot' || item.type === 'video') && !item.fileId,
+ );
+ if (unbacked) {
+ return {
+ content:
+ `Evidence of type "${unbacked.type}" must reference a real artifact through fileId β€” ` +
+ 'inline content cannot stand in for one. Capture the artifact with a tool that ' +
+ 'returns a files.id, then cite that id. If you cannot produce one, submit what you ' +
+ 'actually observed as type "text" instead of claiming a visual artifact.',
+ error: 'UNBACKED_VISUAL_EVIDENCE',
+ success: false,
+ };
+ }
+
+ const runOperationId = await this.resolveRunOperationId();
+ if (!runOperationId) return { error: 'NO_OPERATION', success: false };
const run = await new VerifyRunModel(this.db, this.userId, this.workspaceId).findByOperation(
- operation.parentOperationId,
+ runOperationId,
);
const item = run?.plan?.find((candidate) => candidate.id === params.checkItemId);
if (!run || !item) return { error: 'UNKNOWN_CRITERION', success: false };
@@ -94,7 +234,7 @@ class AcceptanceEvidenceExecutionRuntime {
checkItemId: item.id,
checkItemIndex: item.index,
checkItemTitle: item.title,
- operationId: operation.parentOperationId,
+ operationId: runOperationId,
required: item.required,
verifierType: item.verifierType,
verifyRunId: run.id,
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/browser.ts b/apps/server/src/services/toolExecution/serverRuntimes/browser.ts
index 71be48daed6..a477adc8a9a 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/browser.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/browser.ts
@@ -1,9 +1,11 @@
import { BrowserIdentifier, BrowserManifest } from '@lobechat/builtin-tool-browser';
+import debug from 'debug';
import { deviceGateway } from '@/server/services/deviceGateway';
+import { FileService } from '@/server/services/file';
import { buildNoActiveDeviceResult, REMOTE_DEVICE_TOOL_IDENTIFIER } from './noActiveDevice';
-import { resolveRunWorkspaceId } from './resolveWorkspaceScope';
+import { resolveContentWorkspaceId, resolveRunWorkspaceId } from './resolveWorkspaceScope';
import { type ServerRuntimeRegistration } from './types';
/**
@@ -20,6 +22,86 @@ import { type ServerRuntimeRegistration } from './types';
* the run's identity in the args (mirroring how localSystem injects `cwd`); the
* device strips it back out before invoking the executor.
*/
+const log = debug('lobe-server:browser-runtime');
+
+/** `data:image/png;base64,…` β†’ the media type and the payload. */
+const DATA_URL_RE = /^data:(image\/[\w.+-]+);base64,(.+)$/;
+
+/** Filename extension per IANA media type, mirroring the heterogeneous uploader. */
+const IMAGE_EXT_BY_MEDIA_TYPE: Record<string, string> = {
+ 'image/gif': 'gif',
+ 'image/jpeg': 'jpg',
+ 'image/png': 'png',
+ 'image/webp': 'webp',
+};
+
+/**
+ * Turn the screenshot's inline `dataUrl` into a stored file, exposed on
+ * `state.images` as `{ fileId, mediaType, url }`.
+ *
+ * This is the same contract the heterogeneous pipeline already produces for a
+ * tool_result image (`AgentStreamPipeline.uploadResultImages` β†’
+ * `createFileStoreImageUploader`), and the one `MessageContent` reads to hand
+ * a vision model real `image_url` parts. Proxying the device's `dataUrl`
+ * verbatim left this runtime as the only image-producing tool with no file
+ * behind it: the model could not see its own screenshot, and nothing
+ * downstream β€” Acceptance evidence included β€” had an id to cite.
+ *
+ * The stored id is also named in `content`: `state` reaches the model as image
+ * parts, not as text, so a builder that has to cite the artifact (Acceptance
+ * evidence) would otherwise be able to see the screenshot without ever learning
+ * its id. It doubles as the only signal a non-vision model gets, since the
+ * device returns an empty `content` for this api.
+ *
+ * The file is created under the CONTENT workspace, not the gateway-addressing
+ * one: a workspace run routed to a personal device still writes workspace data,
+ * and some dispatch/resume paths never thread `workspaceId` into the tool
+ * context at all β€” so a raw `context.workspaceId` would file the evidence in
+ * personal scope where a workspace-scoped lookup cannot reach it.
+ *
+ * Best-effort by construction: the capture succeeded either way, so an upload
+ * failure degrades to the previous pass-through instead of failing the call.
+ * `dataUrl` is dropped once stored so the base64 never reaches the DB.
+ */
+const storeScreenshot = async (
+ result: { content?: string; state?: unknown; success?: boolean },
+ context: { agentId?: string; serverDB?: unknown; userId?: string; workspaceId?: string },
+) => {
+ const state = result.state as { dataUrl?: string } | undefined;
+ const match =
+ result.success !== false && typeof state?.dataUrl === 'string'
+ ? state.dataUrl.match(DATA_URL_RE)
+ : null;
+ if (!match || !context.serverDB || !context.userId) return result;
+
+ const [, mediaType, base64Data] = match;
+ try {
+ const workspaceId = await resolveContentWorkspaceId(context as never);
+ const fileService = new FileService(context.serverDB as never, context.userId, workspaceId);
+ const date = new Date().toISOString().slice(0, 10);
+ const ext = IMAGE_EXT_BY_MEDIA_TYPE[mediaType] ?? 'png';
+ const { fileId, url } = await fileService.uploadBase64(
+ base64Data,
+ `files/${date}/browser-screenshot-${Date.now()}.${ext}`,
+ { fileType: mediaType },
+ );
+
+ // `dataUrl` carried both the model's copy and the chat renderer's `src`.
+ // Dropping it (so the base64 never reaches the DB) must not blank the
+ // screenshot in chat, so the stored URL takes its place as the renderable
+ // field; the client executor path still supplies `dataUrl` directly.
+ const { dataUrl: _dropped, ...rest } = state!;
+ return {
+ ...result,
+ content: `Screenshot captured and stored as file ${fileId}. Cite that id when a tool asks for a fileId.`,
+ state: { ...rest, images: [{ fileId, mediaType, url }], url },
+ };
+ } catch (error) {
+ log('screenshot upload failed, passing the capture through inline: %O', error);
+ return result;
+ }
+};
+
export const browserRuntime: ServerRuntimeRegistration = {
factory: (context) => {
if (!context.userId) {
@@ -65,7 +147,7 @@ export const browserRuntime: ServerRuntimeRegistration = {
// are stripped device-side.
const finalArgs = { ...args, __agentId: context.agentId, __topicId: context.topicId };
- return deviceGateway.executeToolCall(
+ const result = await deviceGateway.executeToolCall(
{
deviceId: context.activeDeviceId!,
operationId: context.operationId,
@@ -79,6 +161,8 @@ export const browserRuntime: ServerRuntimeRegistration = {
},
context.executionTimeoutMs,
);
+
+ return api.name === 'screenshot' ? storeScreenshot(result, context) : result;
};
}
diff --git a/apps/server/src/services/verify/__tests__/lifecycleClaim.test.ts b/apps/server/src/services/verify/__tests__/lifecycleClaim.test.ts
index 142fe8856ff..f08dcde90f8 100644
--- a/apps/server/src/services/verify/__tests__/lifecycleClaim.test.ts
+++ b/apps/server/src/services/verify/__tests__/lifecycleClaim.test.ts
@@ -8,6 +8,7 @@ const {
claimEvidenceCollection,
claimVerifying,
execute,
+ evidenceListByRun,
findByOperation,
operationFindById,
finalizeVerifyRun,
@@ -17,6 +18,7 @@ const {
} = vi.hoisted(() => ({
claimEvidenceCollection: vi.fn(),
claimVerifying: vi.fn(),
+ evidenceListByRun: vi.fn(),
execute: vi.fn(),
finalizeVerifyRun: vi.fn(),
findByOperation: vi.fn(),
@@ -36,6 +38,9 @@ vi.mock('@/database/models/verifyRun', () => ({
vi.mock('@/database/models/agentOperation', () => ({
AgentOperationModel: vi.fn(() => ({ findById: operationFindById })),
}));
+vi.mock('@/database/models/verifyEvidence', () => ({
+ VerifyEvidenceModel: vi.fn(() => ({ listByRun: evidenceListByRun })),
+}));
vi.mock('@/database/models/document', () => ({ DocumentModel: vi.fn(() => ({})) }));
vi.mock('@/database/models/task', () => ({
TaskModel: vi.fn(() => ({
@@ -65,7 +70,7 @@ const params = { deliverable: 'done', goal: 'ship it', operationId: 'op-1' };
const confirmedRun = {
id: 'run-1',
- plan: [{ id: 'c1' }],
+ plan: [{ id: 'c1', required: true }],
planConfirmedAt: new Date(),
status: 'planned',
};
@@ -75,6 +80,7 @@ describe('runVerifyOnCompletion β€” verification claim', () => {
[
claimEvidenceCollection,
claimVerifying,
+ evidenceListByRun,
execute,
finalizeVerifyRun,
findByOperation,
@@ -86,6 +92,80 @@ describe('runVerifyOnCompletion β€” verification claim', () => {
findByOperation.mockResolvedValue(confirmedRun);
operationFindById.mockResolvedValue({ id: 'op-1', model: 'm', provider: 'p', taskId: null });
claimVerifying.mockResolvedValue(true);
+ evidenceListByRun.mockResolvedValue([]);
+ });
+
+ it('still collects when the builder covered only part of a multi-criterion plan', async () => {
+ // "any evidence row exists" would strand c2 at the structural gate with no
+ // chance to supply what it asks for.
+ findByOperation.mockResolvedValue({
+ ...confirmedRun,
+ plan: [
+ { id: 'c1', required: true },
+ { id: 'c2', required: true },
+ ],
+ });
+ operationFindById.mockResolvedValue({
+ agentId: 'builder',
+ id: 'op-1',
+ model: 'm',
+ provider: 'p',
+ taskId: 'task-1',
+ topicId: 'topic-1',
+ });
+ evidenceListByRun.mockResolvedValue([{ checkItemId: 'c1', type: 'text' }]);
+ claimEvidenceCollection.mockResolvedValue(true);
+
+ await runVerifyOnCompletion(db, 'u1', params);
+
+ expect(startEvidenceSubmission).toHaveBeenCalledTimes(1);
+ expect(execute).not.toHaveBeenCalled();
+ });
+
+ it('still collects when a criterion is missing a declared evidence type', async () => {
+ findByOperation.mockResolvedValue({
+ ...confirmedRun,
+ plan: [
+ {
+ id: 'c1',
+ required: true,
+ verifierConfig: { requiredEvidence: [{ type: 'screenshot' }] },
+ },
+ ],
+ });
+ operationFindById.mockResolvedValue({
+ agentId: 'builder',
+ id: 'op-1',
+ model: 'm',
+ provider: 'p',
+ taskId: 'task-1',
+ topicId: 'topic-1',
+ });
+ evidenceListByRun.mockResolvedValue([{ checkItemId: 'c1', type: 'text' }]);
+ claimEvidenceCollection.mockResolvedValue(true);
+
+ await runVerifyOnCompletion(db, 'u1', params);
+
+ expect(startEvidenceSubmission).toHaveBeenCalledTimes(1);
+ });
+
+ it('judges directly when the builder already submitted evidence inside the Task run', async () => {
+ operationFindById.mockResolvedValue({
+ agentId: 'builder',
+ id: 'op-1',
+ model: 'm',
+ provider: 'p',
+ taskId: 'task-1',
+ topicId: 'topic-1',
+ });
+ evidenceListByRun.mockResolvedValue([{ checkItemId: 'c1', type: 'screenshot' }]);
+
+ await runVerifyOnCompletion(db, 'u1', params);
+
+ expect(claimEvidenceCollection).not.toHaveBeenCalled();
+ expect(startEvidenceSubmission).not.toHaveBeenCalled();
+ expect(claimVerifying).toHaveBeenCalledTimes(1);
+ expect(execute).toHaveBeenCalledTimes(1);
});
it('starts builder evidence collection before judging a task-bound run', async () => {
diff --git a/apps/server/src/services/verify/lifecycle.ts b/apps/server/src/services/verify/lifecycle.ts
index b250fac40f6..9fbf4fdd2e0 100644
--- a/apps/server/src/services/verify/lifecycle.ts
+++ b/apps/server/src/services/verify/lifecycle.ts
@@ -4,6 +4,7 @@ import debug from 'debug';
import { AgentOperationModel } from '@/database/models/agentOperation';
import { DocumentModel } from '@/database/models/document';
import { TaskModel } from '@/database/models/task';
+import { VerifyEvidenceModel } from '@/database/models/verifyEvidence';
import { VerifyRunModel } from '@/database/models/verifyRun';
import type { LobeChatDatabase } from '@/database/type';
@@ -101,6 +102,57 @@ const executeVerifyLifecycle = async (
return;
}
+ // The builder now captures Acceptance evidence inside the main run. When it
+ // covered the whole plan, the post-run evidence turn has nothing left to
+ // collect β€” it mounts the evidence tool exclusively, so all it could add is
+ // a restatement of text already in the transcript, at the cost of a second
+ // agent run.
+ //
+ // Coverage is per required criterion, not "any row exists": a builder that
+ // evidenced one of three criteria has not finished collecting, and skipping
+ // on its first submission would strand the other two at the structural gate
+ // with no chance to supply what they ask for.
+ if (op.taskId && !evidenceSubmitted) {
+ const inRunEvidence = await new VerifyEvidenceModel(db, userId, workspaceId).listByRun(
+ run.id,
+ );
+ const byCheckItem = new Map<string, Set<string>>();
+ for (const row of inRunEvidence) {
+ const types = byCheckItem.get(row.checkItemId) ?? new Set<string>();
+ types.add(row.type);
+ byCheckItem.set(row.checkItemId, types);
+ }
+
+ const uncovered = run.plan.filter((item) => {
+ if (item.required === false) return false;
+ const captured = byCheckItem.get(item.id);
+ if (!captured?.size) return true;
+
+ // A criterion that names the artifacts it needs is only covered once
+ // each declared type is present.
+ const declared = (item.verifierConfig as { requiredEvidence?: { type: string }[] })
+ ?.requiredEvidence;
+ return Array.isArray(declared)
+ ? declared.some((required) => !captured.has(required.type))
+ : false;
+ });
+
+ if (inRunEvidence.length > 0 && uncovered.length === 0) {
+ log(
+ 'op %s covered every required criterion in-run (%d rows), skipping the evidence turn',
+ params.operationId,
+ inRunEvidence.length,
+ );
+ evidenceSubmitted = true;
+ } else if (inRunEvidence.length > 0) {
+ log(
+ 'op %s has partial in-run coverage (%d criteria still uncovered), running the evidence turn',
+ params.operationId,
+ uncovered.length,
+ );
+ }
+ }
+
if (op.taskId && !evidenceSubmitted) {
const evidenceClaimed = await new VerifyRunModel(
db,
diff --git a/packages/builtin-tool-acceptance-evidence/src/index.ts b/packages/builtin-tool-acceptance-evidence/src/index.ts
index ca7d4edce77..4ac10bfe06d 100644
--- a/packages/builtin-tool-acceptance-evidence/src/index.ts
+++ b/packages/builtin-tool-acceptance-evidence/src/index.ts
@@ -1,6 +1,7 @@
export { AcceptanceEvidenceIdentifier, AcceptanceEvidenceManifest } from './manifest';
export { systemPrompt } from './systemRole';
export {
+ type AcceptanceCriterionSummary,
AcceptanceEvidenceApiName,
type AcceptanceEvidenceType,
type SubmitAcceptanceEvidenceParams,
diff --git a/packages/builtin-tool-acceptance-evidence/src/manifest.ts b/packages/builtin-tool-acceptance-evidence/src/manifest.ts
index 441e613440e..e4a5b5f1b0c 100644
--- a/packages/builtin-tool-acceptance-evidence/src/manifest.ts
+++ b/packages/builtin-tool-acceptance-evidence/src/manifest.ts
@@ -9,12 +9,18 @@ export const AcceptanceEvidenceManifest: BuiltinToolManifest = {
api: [
{
description:
- 'Submit evidence produced by your completed work for one Acceptance criterion. This records evidence only; it does not decide the verdict.',
+ 'List the Acceptance criteria of the run you are working in, with the evidence already recorded for each. Call this first: criterion ids are minted when the run starts, so they cannot be named in your instructions.',
+ name: AcceptanceEvidenceApiName.listCriteria,
+ parameters: { properties: {}, type: 'object' },
+ },
+ {
+ description:
+ 'Submit evidence produced by your work for one Acceptance criterion. This records evidence only; it does not decide the verdict.',
name: AcceptanceEvidenceApiName.submitEvidence,
parameters: {
properties: {
checkItemId: {
- description: 'The exact criterion id from the evidence-submission instruction.',
+ description: 'A criterion id returned by listCriteria.',
type: 'string',
},
evidence: {
diff --git a/packages/builtin-tool-acceptance-evidence/src/systemRole.ts b/packages/builtin-tool-acceptance-evidence/src/systemRole.ts
index 2bd7d1c5413..47dd4f23ba7 100644
--- a/packages/builtin-tool-acceptance-evidence/src/systemRole.ts
+++ b/packages/builtin-tool-acceptance-evidence/src/systemRole.ts
@@ -1,11 +1,10 @@
-export const systemPrompt = `You are in the evidence-submission phase for work you just completed.
+export const systemPrompt = `You own the Acceptance evidence for the work you are doing.
-Your job is to cite concrete evidence already produced by your work for every Acceptance criterion. You are the builder, not the verifier:
-- Submit evidence with submitEvidence for each criterion id in the instruction.
+Call listCriteria to read the criteria of the current run, then submit evidence with submitEvidence as each criterion becomes provable. You are the builder, not the verifier:
+- Capture evidence from the real product surface while you work. A criterion with a visible surface is proved by a screenshot or recording; a text note is the fallback for what has no surface, not the default.
- Prefer precise command output, file paths, document ids, artifact file ids, screenshots, or concise factual notes.
- Use documentId only for an id from documents.id. Never pass an agent_documents.id binding id as documentId or fileId.
- If you only know an agent document binding id, call listDocuments and use the returned documentId field.
- Use fileId only for an id from files.id, such as an uploaded screenshot, video, or file artifact.
- Do not decide whether a criterion passes and do not invent evidence.
-- Use the conversation and artifacts from the completed task. Do not redo the task or start a new implementation.
- If evidence is missing, state that plainly in a note for that criterion.`;
diff --git a/packages/builtin-tool-acceptance-evidence/src/types.ts b/packages/builtin-tool-acceptance-evidence/src/types.ts
index 7ea447548bc..7956e853b52 100644
--- a/packages/builtin-tool-acceptance-evidence/src/types.ts
+++ b/packages/builtin-tool-acceptance-evidence/src/types.ts
@@ -1,4 +1,5 @@
export const AcceptanceEvidenceApiName = {
+ listCriteria: 'listCriteria',
submitEvidence: 'submitEvidence',
} as const;
@@ -14,3 +15,15 @@ export interface SubmitAcceptanceEvidenceParams {
type: AcceptanceEvidenceType;
}>;
}
+
+export interface AcceptanceCriterionSummary {
+ /** The `checkItemId` to pass back to `submitEvidence`. */
+ id: string;
+ index: number;
+ required: boolean;
+ /** Evidence types the criterion asks for, when it declares any. */
+ requiredEvidence?: Array<{ hint?: string; type: string }>;
+ /** Evidence already recorded for this criterion in the current run. */
+ submittedEvidence: number;
+ title: string;
+}
diff --git a/packages/builtin-tool-browser/src/client/Render/Screenshot.tsx b/packages/builtin-tool-browser/src/client/Render/Screenshot.tsx
index 2365b81005e..45690d53c70 100644
--- a/packages/builtin-tool-browser/src/client/Render/Screenshot.tsx
+++ b/packages/builtin-tool-browser/src/client/Render/Screenshot.tsx
@@ -3,19 +3,17 @@ import { Block, Image } from '@lobehub/ui';
import { memo } from 'react';
import type { BrowserScreenshotState } from '../../types';
+import { resolveScreenshotSrc } from './screenshotSrc';
-/** Screenshot: render the captured JPEG data URL inline for the user. */
+/** Screenshot: render the capture inline for the user. */
const Screenshot = memo<BuiltinRenderProps<unknown, BrowserScreenshotState, string>>(
({ pluginState }) => {
- if (!pluginState?.dataUrl) return null;
+ const src = resolveScreenshotSrc(pluginState);
+ if (!src) return null;
return (
<Block style={{ overflow: 'hidden', padding: 4 }} variant={'outlined'}>
- <Image
- alt={'Browser screenshot'}
- src={pluginState.dataUrl}
- style={{ borderRadius: 4, width: '100%' }}
- />
+ <Image alt={'Browser screenshot'} src={src} style={{ borderRadius: 4, width: '100%' }} />
</Block>
);
},
diff --git a/packages/builtin-tool-browser/src/client/Render/screenshotSrc.test.ts b/packages/builtin-tool-browser/src/client/Render/screenshotSrc.test.ts
new file mode 100644
index 00000000000..2b159e11aab
--- /dev/null
+++ b/packages/builtin-tool-browser/src/client/Render/screenshotSrc.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveScreenshotSrc } from './screenshotSrc';
+
+describe('resolveScreenshotSrc', () => {
+ it('uses the inline capture from the client executor', () => {
+ expect(resolveScreenshotSrc({ dataUrl: 'data:image/jpeg;base64,QUJD' })).toBe(
+ 'data:image/jpeg;base64,QUJD',
+ );
+ });
+
+ it('uses the stored capture from the server-proxied path', () => {
+ expect(resolveScreenshotSrc({ url: 'https://cdn.example.com/s.jpg' })).toBe(
+ 'https://cdn.example.com/s.jpg',
+ );
+ });
+
+ it('falls back to the first stored artifact', () => {
+ expect(
+ resolveScreenshotSrc({
+ images: [{ fileId: 'f1', mediaType: 'image/jpeg', url: 'https://cdn.example.com/a.jpg' }],
+ }),
+ ).toBe('https://cdn.example.com/a.jpg');
+ });
+
+ it('resolves nothing when no capture is present', () => {
+ expect(resolveScreenshotSrc({ height: 10, width: 10 })).toBeUndefined();
+ expect(resolveScreenshotSrc(undefined)).toBeUndefined();
+ });
+});
diff --git a/packages/builtin-tool-browser/src/client/Render/screenshotSrc.ts b/packages/builtin-tool-browser/src/client/Render/screenshotSrc.ts
new file mode 100644
index 00000000000..f9686dd4cda
--- /dev/null
+++ b/packages/builtin-tool-browser/src/client/Render/screenshotSrc.ts
@@ -0,0 +1,11 @@
+import type { BrowserScreenshotState } from '../../types';
+
+/**
+ * The image source for a capture, whichever shape produced it.
+ *
+ * The client executor returns the JPEG inline as `dataUrl`; the server-proxied
+ * device path stores the image and returns its URL instead, so the base64 never
+ * reaches the DB. Reading only `dataUrl` blanks every server-proxied capture.
+ */
+export const resolveScreenshotSrc = (state?: BrowserScreenshotState): string | undefined =>
+ state?.dataUrl || state?.url || state?.images?.[0]?.url;
diff --git a/packages/builtin-tool-browser/src/manifest.ts b/packages/builtin-tool-browser/src/manifest.ts
index 8a293535496..31880936dcb 100644
--- a/packages/builtin-tool-browser/src/manifest.ts
+++ b/packages/builtin-tool-browser/src/manifest.ts
@@ -108,7 +108,7 @@ export const BrowserManifest: BuiltinToolManifest = {
},
{
description:
- 'Capture a screenshot of the current page for the USER to see in chat. You cannot see the image yourself β€” use snapshot/readPage for perception.',
+ 'Capture a screenshot of the current page. The image is stored and returned to you as a file reference, and is also shown to the USER in chat. Use snapshot/readPage when you only need the page structure or text.',
name: BrowserApiName.screenshot,
parameters: {
properties: {},
diff --git a/packages/builtin-tool-browser/src/systemRole.ts b/packages/builtin-tool-browser/src/systemRole.ts
index 4d940902e28..5cc87bb65d2 100644
--- a/packages/builtin-tool-browser/src/systemRole.ts
+++ b/packages/builtin-tool-browser/src/systemRole.ts
@@ -9,6 +9,6 @@ Core workflow:
Notes:
- \`fill\` sets an input's value directly; pass \`submit: true\` to press Enter afterwards (search boxes, login forms).
-- \`screenshot\` renders a visual for the USER's chat β€” you cannot see it. Use \`snapshot\` / \`readPage\` for your own perception.
+- \`screenshot\` stores the capture as a file and returns it to you, and also renders it in the USER's chat. Use \`snapshot\` / \`readPage\` when the page structure or text is all you need.
- Prefer refs over coordinates. Coordinates are a fallback for canvas-like surfaces only.
- The browser shares the user's logged-in profile. Never visit pages or perform actions the user did not ask for, and never extract credentials or other sensitive data.`;
diff --git a/packages/builtin-tool-browser/src/types.ts b/packages/builtin-tool-browser/src/types.ts
index 3c8dbca0679..a67f545d441 100644
--- a/packages/builtin-tool-browser/src/types.ts
+++ b/packages/builtin-tool-browser/src/types.ts
@@ -27,8 +27,17 @@ export interface BrowserSnapshotState extends BrowserPageState {
export interface BrowserClickState extends BrowserPageState {}
export interface BrowserScreenshotState {
- dataUrl: string;
+ /**
+ * Inline capture, produced by the client executor. The server-proxied path
+ * stores the image instead and sets {@link BrowserScreenshotState.url}, so a
+ * consumer must accept either.
+ */
+ dataUrl?: string;
height?: number;
+ /** Stored artifacts, `{ fileId, mediaType, url }` β€” the shared tool-image contract. */
+ images?: { fileId: string; mediaType: string; url: string }[];
+ /** Accessible URL of the stored capture. */
+ url?: string;
width?: number;
}
diff --git a/packages/builtin-tool-browser/vitest.config.mts b/packages/builtin-tool-browser/vitest.config.mts
new file mode 100644
index 00000000000..4ac6027d578
--- /dev/null
+++ b/packages/builtin-tool-browser/vitest.config.mts
@@ -0,0 +1,7 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ environment: 'node',
+ },
+});
diff --git a/packages/device-gateway-client/src/http.test.ts b/packages/device-gateway-client/src/http.test.ts
index 5553c334833..f1b55794fa6 100644
--- a/packages/device-gateway-client/src/http.test.ts
+++ b/packages/device-gateway-client/src/http.test.ts
@@ -157,6 +157,46 @@ describe('GatewayHttpClient', () => {
});
});
+ it('surfaces the failure text when the device fails with empty content', async () => {
+ // `typeof '' === 'string'` used to short-circuit the error fallback, so a
+ // device api with no handler reached the model as an empty, successful-
+ // looking result β€” observed live as a builder calling `screenshot`
+ // fifteen times against a device with no browser handler.
+ mockFetch({
+ json: vi
+ .fn()
+ .mockResolvedValue({ content: '', error: 'Unknown tool API: navigate', success: false }),
+ ok: true,
+ });
+
+ const result = await client.executeToolCall(
+ { userId: 'user-1' },
+ { apiName: 'navigate', arguments: '{}', identifier: 'lobe-browser' },
+ );
+
+ expect(result).toEqual({
+ content: 'Unknown tool API: navigate',
+ error: 'Unknown tool API: navigate',
+ state: undefined,
+ success: false,
+ });
+ });
+
+ it('keeps a deliberate empty success result empty', async () => {
+ mockFetch({
+ json: vi.fn().mockResolvedValue({ content: '', success: true }),
+ ok: true,
+ });
+
+ const result = await client.executeToolCall(
+ { userId: 'user-1' },
+ { apiName: 'noop', arguments: '{}', identifier: 'test' },
+ );
+
+ expect(result.content).toBe('');
+ expect(result.success).toBe(true);
+ });
+
it('should preserve structured state alongside content', async () => {
// The wire envelope carries `state` separately from `content`. This is
// what makes `pluginState` work end-to-end for remote device tool calls.
diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.ts
index f1127215cc7..86630987fc9 100644
--- a/packages/device-gateway-client/src/http.ts
+++ b/packages/device-gateway-client/src/http.ts
@@ -184,21 +184,29 @@ export class GatewayHttpClient {
}
const data = await res.json();
+
+ // Device sends a typed envelope ({ content, state, success }). The legacy
+ // fallback used to JSON.stringify `data.content ?? data` β€” when content was
+ // missing it would stringify the *entire response body* including `success`
+ // and any other top-level fields, which leaked the structured payload into
+ // the LLM-facing content string. Only stringify the `content` field itself;
+ // never fall back to the whole body.
+ const deviceContent =
+ typeof data.content === 'string'
+ ? data.content
+ : data.content === undefined || data.content === null
+ ? ''
+ : JSON.stringify(data.content);
+
return {
- // Device sends a typed envelope ({ content, state, success }). The legacy
- // fallback used to JSON.stringify `data.content ?? data` β€” when content
- // was missing it would stringify the *entire response body* including
- // `success` and any other top-level fields, which leaked the structured
- // payload into the LLM-facing content string. Only stringify the
- // `content` field itself; never fall back to the whole body.
- content:
- typeof data.content === 'string'
- ? data.content
- : data.content !== undefined && data.content !== null
- ? JSON.stringify(data.content)
- : typeof data.error === 'string'
- ? data.error
- : '',
+ // A device that fails with nothing to say β€” an api it has no handler for,
+ // a handler that threw before writing output β€” reported `content: ''`,
+ // and `typeof '' === 'string'` short-circuited the error fallback below.
+ // The failure then reached the model as an empty, successful-looking
+ // result: observed live as a builder calling `screenshot` fifteen times
+ // against a device with no browser handler and reading nothing back each
+ // time. Every other failure path here puts the failure text in `content`.
+ content: deviceContent || (typeof data.error === 'string' ? data.error : ''),
error: data.error,
state: data.state,
success: data.success ?? true,
diff --git a/packages/prompts/src/prompts/task/index.test.ts b/packages/prompts/src/prompts/task/index.test.ts
index d735de4dacd..2928d76d10e 100644
--- a/packages/prompts/src/prompts/task/index.test.ts
+++ b/packages/prompts/src/prompts/task/index.test.ts
@@ -457,7 +457,34 @@ describe('buildTaskRunPrompt', () => {
expect(result).toContain('console is clean');
expect(result).toContain('include artifact paths, commands, and observed results');
expect(result).toContain('an independent verifier decides whether this Task is complete');
- expect(result).not.toContain('lh acceptance run result submit');
+ expect(result).toContain('Run the Acceptance inside this Task, not after it');
+ expect(result).toContain('lh acceptance install');
+ expect(result).toContain('lh acceptance run result submit');
+ expect(result).toContain('proved by a screenshot or recording');
+ // The portable skill is pulled to disk by CLI builders and is absent from
+ // `builtinSkills`, so it must never be named as an unconditional step.
+ expect(result).not.toContain('Use the `acceptance` skill to drive');
+ expect(result).toContain('must reference a real artifact by fileId');
+ });
+
+ it('should still instruct in-task acceptance when the policy has no criteria or requirement', () => {
+ const result = buildTaskRunPrompt(
+ {
+ task: {
+ id: 'task_root',
+ identifier: 'TASK-1',
+ instruction: 'ship the feature',
+ status: 'running',
+ verify: { criteria: [], enabled: true },
+ },
+ },
+ NOW,
+ );
+
+ expect(result).toContain('Verify β€” delivery acceptance');
+ expect(result).toContain('Run the Acceptance inside this Task, not after it');
+ expect(result).toContain('Criterion ids are minted when this run starts');
+ expect(result).toContain('lh verify plan state');
});
it('should omit the verify section when verify is disabled', () => {
diff --git a/packages/prompts/src/prompts/task/index.ts b/packages/prompts/src/prompts/task/index.ts
index 0b311da5e82..ef56821992a 100644
--- a/packages/prompts/src/prompts/task/index.ts
+++ b/packages/prompts/src/prompts/task/index.ts
@@ -691,7 +691,12 @@ export const buildTaskRunPrompt = (input: TaskRunPromptInput, now?: Date): strin
}
// Verify β€” delivery acceptance (builder self-evidence)
- if (task.verify?.enabled && (task.verify.criteria?.length || task.verify.requirement)) {
+ //
+ // Gated on `enabled` alone: every Task that carries an Acceptance runs it
+ // in-Task. A criteria-less Acceptance still materializes a plan at run start,
+ // and the builder reads those criterion ids at runtime β€” so having nothing to
+ // print here is not a reason to withhold the instruction.
+ if (task.verify?.enabled) {
taskLines.push('');
taskLines.push(
`Verify β€” delivery acceptance (maxIterations: ${task.verify.maxIterations || 3}):`,
@@ -709,11 +714,30 @@ export const buildTaskRunPrompt = (input: TaskRunPromptInput, now?: Date): strin
}
}
}
+ taskLines.push(
+ ' Run the Acceptance inside this Task, not after it: drive the real product surface and submit each artifact as soon as the criterion it proves is provable.',
+ );
+ taskLines.push(
+ ' Criterion ids are minted when this run starts, so they are not listed above. Read them at runtime with `listCriteria`, or `lh verify plan state "$LOBEHUB_OPERATION_ID" --json` if you have a shell.',
+ );
+ // Two builder shapes, two toolchains. The portable `acceptance` skill is
+ // pulled to disk by external CLI builders and is deliberately absent from
+ // `builtinSkills`, so naming it unconditionally hands the in-product agent
+ // an instruction it cannot act on.
+ taskLines.push(
+ ' With a shell: `lh acceptance install` gives you the `acceptance` skill, and `lh acceptance run result submit --operation "$LOBEHUB_OPERATION_ID" --item <checkItemId> --type screenshot --file <path>` uploads a captured artifact.',
+ );
+ taskLines.push(
+ ' Without a shell: drive the product with your own tools and cite artifacts by id through `submitEvidence`.',
+ );
+ taskLines.push(
+ ' A criterion with a visible surface is proved by a screenshot or recording, and `screenshot`/`video` evidence must reference a real artifact by fileId. Never label prose as a visual artifact: if you could not capture one, say what you observed as `text` and name the blocker.',
+ );
taskLines.push(
' Produce concrete evidence while you work, and include artifact paths, commands, and observed results in your final response.',
);
taskLines.push(
- ' Do not judge the Acceptance. A dedicated post-run phase will ask you to submit the evidence you produced; an independent verifier decides whether this Task is complete.',
+ ' Do not judge the Acceptance β€” submit evidence only; an independent verifier decides whether this Task is complete.',
);
}