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: converge task acceptance lifecycle (#17631)

Arvin Xu83503b5f1d08
diff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.md
index 7224c796522..ebeb175f122 100644
--- a/.agents/acceptance/common-mistakes.md
+++ b/.agents/acceptance/common-mistakes.md
@@ -253,3 +253,13 @@ full incident narratives and old Case numbers for earlier cross-references.
**What it breaks**: the direct summary no longer matches the compact coding-agent pattern the user expects, and the action occupies persistent visual weight despite being needed only on inspection.
**Correct approach**: place additions/deletions directly below the single-file title, reveal “View changes” on row hover or keyboard focus, and keep it visible while the diff is open so the reverse action remains discoverable.
+
+## Task Acceptance continuity must be proven with one Task
+
+**Wrong approach**: compare the configured criteria of one Task with the completed Acceptance of another Task, then treat a larger cross-round union as a current-data defect.
+
+**Why it's wrong**: two Tasks can legitimately have different goals and item counts, while Acceptance intentionally retains checks introduced by later rounds as part of the auditable delivery history.
+
+**What it breaks**: evidence appears to show an unexplained 6→7 mutation and two different goals, and a legitimate seventh cross-round check can be incorrectly hidden.
+
+**Correct approach**: capture definition and result states from the same Task, keep the full Acceptance check union visible, and keep the Task verify requirement synchronized with the aggregate goal.
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.md
index 21d0b79884e..e1df8d8e2e3 100644
--- a/.agents/acceptance/probe-mock-patterns.md
+++ b/.agents/acceptance/probe-mock-patterns.md
@@ -64,6 +64,22 @@ HttpOnly, so an empty `document.cookie` does not establish signed-out state.
## Project-specific recipes
+### Task CLI polling with seeded API-key auth
+
+**Situation:** A local acceptance run is driven through `lh task run` with the
+seeded `LOBEHUB_CLI_API_KEY`, and the test needs to observe the asynchronous
+repair lifecycle.
+
+**Doesn't work:** `lh task run <id> --follow` switches to `/webapi/*`, which
+requires OIDC and rejects API-key auth after the task has already started.
+Likewise, `lh acceptance view task:T-N` does not currently resolve a task
+identifier to its internal subject id.
+
+**Works:** Start the task without `--follow`, poll with `lh task view T-N`, and
+query the aggregate with `lh acceptance view task:<internal-task-id>`. The start
+response and task activity expose the operation and topic ids; the Acceptance
+bundle exposes the repair round and final rollup.
+
### Message-attached heterogeneous-agent errors
Inject a temporary assistant message through
diff --git a/apps/server/src/routers/lambda/acceptance.ts b/apps/server/src/routers/lambda/acceptance.ts
index cce6f77b3cd..a85cebfb5f4 100644
--- a/apps/server/src/routers/lambda/acceptance.ts
+++ b/apps/server/src/routers/lambda/acceptance.ts
@@ -12,6 +12,7 @@ import {
requireWorkspaceRoleWhenScoped,
wsCompatProcedure,
} from '@/business/server/trpc-middlewares/workspaceAuth';
+import { TaskModel } from '@/database/models/task';
import { VerifyRunModel } from '@/database/models/verifyRun';
import { WorkspaceMemberModel } from '@/database/models/workspaceMember';
import type { AcceptanceItem } from '@/database/schemas/verify';
@@ -206,6 +207,14 @@ export const acceptanceRouter = router({
await ctx.acceptanceService.acceptanceModel.update(aggregate.id, {
requirement: input.requirement,
});
+ // A Task acceptance is instantiated from tasks.config.verify. Mirror
+ // edits back to that source so the next run cannot restore an older goal.
+ if (input.subjectType === 'task') {
+ const taskModel = new TaskModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);
+ const task = await taskModel.resolve(input.subjectId);
+ if (!task) throw new Error('Task not found in the current workspace');
+ await taskModel.updateVerifyConfig(task.id, { requirement: input.requirement });
+ }
return { id: aggregate.id, requirement: input.requirement };
} catch (error) {
throw new TRPCError({
diff --git a/apps/server/src/routers/lambda/verify.ts b/apps/server/src/routers/lambda/verify.ts
index 3ff32b99817..c8e246e37b3 100644
--- a/apps/server/src/routers/lambda/verify.ts
+++ b/apps/server/src/routers/lambda/verify.ts
@@ -347,6 +347,10 @@ export const verifyRouter = router({
return ctx.criterionModel.delete(input.id);
}),
+ forkRubricCriteria: verifyWriteProcedure
+ .input(z.object({ ids: z.array(z.string()) }))
+ .mutation(async ({ ctx, input }) => ctx.criterionModel.forkRubricCriteria(input.ids)),
+
listCriteria: verifyProcedure.query(async ({ ctx }) => ctx.criterionModel.query()),
updateCriterion: verifyWriteProcedure
diff --git a/apps/server/src/services/task/index.ts b/apps/server/src/services/task/index.ts
index 25eed726907..8c023d6c009 100644
--- a/apps/server/src/services/task/index.ts
+++ b/apps/server/src/services/task/index.ts
@@ -809,6 +809,7 @@ export class TaskService {
timeout: task.heartbeatTimeout,
}
: undefined,
+ id: task.id,
identifier: task.identifier,
instruction: task.instruction,
name: task.name,
diff --git a/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts b/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts
new file mode 100644
index 00000000000..c28669aae52
--- /dev/null
+++ b/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts
@@ -0,0 +1,128 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { instantiateVerifyPlanOnStart } from '../planInstantiation';
+import { createRepairRunner } from '../repairService';
+
+const mocks = vi.hoisted(() => ({
+ acceptanceAttachRun: vi.fn(),
+ acceptanceEnsureForSubject: vi.fn(),
+ acceptanceUpdate: vi.fn(),
+ agentExec: vi.fn(),
+ confirmPlan: vi.fn(),
+ ensureForOperation: vi.fn(),
+ generateDraftPlan: vi.fn(),
+ operationFindById: vi.fn(),
+ runFindByOperation: vi.fn(),
+ setMetadata: vi.fn(),
+ setPlan: vi.fn(),
+ taskFindById: vi.fn(),
+ taskResolveVerifyConfig: vi.fn(),
+}));
+
+vi.mock('../acceptanceService', () => ({
+ AcceptanceService: vi.fn(() => ({
+ acceptanceModel: { update: mocks.acceptanceUpdate },
+ attachRun: mocks.acceptanceAttachRun,
+ ensureForSubject: mocks.acceptanceEnsureForSubject,
+ })),
+}));
+
+vi.mock('../planGenerator', () => ({
+ VerifyPlanGeneratorService: vi.fn(() => ({
+ generateDraftPlan: mocks.generateDraftPlan,
+ })),
+}));
+
+vi.mock('@/database/models/task', () => ({
+ TaskModel: vi.fn(() => ({
+ findById: mocks.taskFindById,
+ resolveVerifyConfig: mocks.taskResolveVerifyConfig,
+ })),
+}));
+
+vi.mock('@/database/models/verifyRun', () => ({
+ VerifyRunModel: vi.fn(() => ({
+ confirmPlan: mocks.confirmPlan,
+ ensureForOperation: mocks.ensureForOperation,
+ findByOperation: mocks.runFindByOperation,
+ setMetadata: mocks.setMetadata,
+ setPlan: mocks.setPlan,
+ })),
+}));
+
+vi.mock('@/database/models/agentOperation', () => ({
+ AgentOperationModel: vi.fn(() => ({ findById: mocks.operationFindById })),
+}));
+
+vi.mock('@/server/services/aiAgent', () => ({
+ AiAgentService: vi.fn(() => ({ execAgent: mocks.agentExec })),
+}));
+
+const db = {} as any;
+const plan = [{ id: 'check-1', required: true }];
+
+describe('Verify acceptance lifecycle', () => {
+ beforeEach(() => {
+ Object.values(mocks).forEach((mock) => mock.mockReset());
+ });
+
+ it('creates and attaches the task acceptance when its verify plan is confirmed', async () => {
+ mocks.taskResolveVerifyConfig.mockResolvedValue({
+ enabled: true,
+ requirement: 'The novel is complete and coherent',
+ });
+ mocks.taskFindById.mockResolvedValue({
+ instruction: 'Write a science-fiction novel',
+ name: 'Novel',
+ });
+ mocks.runFindByOperation
+ .mockResolvedValueOnce(null)
+ .mockResolvedValueOnce({ id: 'run-1', plan });
+ mocks.acceptanceEnsureForSubject.mockResolvedValue({ id: 'acceptance-1' });
+
+ await instantiateVerifyPlanOnStart(
+ db,
+ 'user-1',
+ { operationId: 'operation-1', taskId: 'task-1' },
+ 'workspace-1',
+ );
+
+ expect(mocks.acceptanceEnsureForSubject).toHaveBeenCalledWith('task', 'task-1', {
+ requirement: 'The novel is complete and coherent',
+ });
+ expect(mocks.acceptanceUpdate).toHaveBeenCalledWith('acceptance-1', {
+ requirement: 'The novel is complete and coherent',
+ });
+ expect(mocks.acceptanceAttachRun).toHaveBeenCalledWith('run-1', 'acceptance-1');
+ });
+
+ it('attaches an auto-repair verify run as the next round of the same acceptance', async () => {
+ mocks.operationFindById.mockResolvedValue({ parentOperationId: null });
+ mocks.agentExec.mockResolvedValue({ operationId: 'repair-operation' });
+ mocks.runFindByOperation.mockResolvedValue({
+ acceptanceId: 'acceptance-1',
+ id: 'source-run',
+ metadata: { maxRepairRounds: 2 },
+ plan,
+ });
+ mocks.ensureForOperation.mockResolvedValue({ id: 'repair-run' });
+
+ const runner = createRepairRunner({
+ agentId: 'agent-1',
+ db,
+ maxRepairRounds: 2,
+ topicId: 'topic-1',
+ userId: 'user-1',
+ workspaceId: 'workspace-1',
+ });
+ const result = await runner!({
+ failedItemIds: ['check-1'],
+ instruction: 'Fix the failed check',
+ operationId: 'source-operation',
+ });
+
+ expect(result).toEqual({ repairOperationId: 'repair-operation' });
+ expect(mocks.acceptanceAttachRun).toHaveBeenCalledWith('repair-run', 'acceptance-1');
+ });
+});
diff --git a/apps/server/src/services/verify/__tests__/acceptanceUnion.test.ts b/apps/server/src/services/verify/__tests__/acceptanceUnion.test.ts
index 0d3f58b1e43..2caa63dd2c6 100644
--- a/apps/server/src/services/verify/__tests__/acceptanceUnion.test.ts
+++ b/apps/server/src/services/verify/__tests__/acceptanceUnion.test.ts
@@ -56,6 +56,29 @@ describe('buildAcceptanceCheckUnion', () => {
]);
});
+ it('joins different run-local item ids through their stable source criterion', () => {
+ const rows = buildAcceptanceCheckUnion([
+ {
+ results: [result('run-1-item', 'failed')],
+ run: run('r1', 1, [
+ planItem('run-1-item', { sourceCriterionId: 'criterion-1', title: 'Stable check' }),
+ ]),
+ },
+ {
+ results: [result('run-2-item', 'passed')],
+ run: run('r2', 2, [
+ planItem('run-2-item', { sourceCriterionId: 'criterion-1', title: 'Stable check' }),
+ ]),
+ },
+ ]);
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0].id).toBe('criterion-1');
+ expect(rows[0].state).toBe('passed');
+ expect(rows[0].fixed).toBe(true);
+ expect(rows[0].history.map((entry) => entry.roundIndex)).toEqual([1, 2]);
+ });
+
it('marks an item planned later but never re-run as carried forward', () => {
const plan = [planItem('prefs')];
const rows = buildAcceptanceCheckUnion([
diff --git a/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts b/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts
index 5aeae0c11b8..3eab4e685a4 100644
--- a/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts
+++ b/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts
@@ -1,7 +1,14 @@
// @vitest-environment node
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { driveTaskFromVerify } from '../settle';
+import { driveTaskFromVerify, finalizeVerifyRun } from '../settle';
+
+vi.mock('../repairService', () => ({
+ maybeAutoRepair: vi.fn(),
+}));
+vi.mock('../reporter', () => ({
+ VerifyReporterService: vi.fn(() => ({ generateReport: vi.fn() })),
+}));
const {
runFindByOperation,
@@ -11,6 +18,7 @@ const {
taskUpdateStatus,
briefCreate,
serviceUpdateStatus,
+ statusRecompute,
deliverMock,
} = vi.hoisted(() => ({
briefCreate: vi.fn(),
@@ -19,10 +27,15 @@ const {
runFindByOperation: vi.fn(),
runSetMetadata: vi.fn(),
serviceUpdateStatus: vi.fn(),
+ statusRecompute: vi.fn(),
taskFindById: vi.fn(),
taskUpdateStatus: vi.fn(),
}));
+vi.mock('../statusService', () => ({
+ VerifyStatusService: vi.fn(() => ({ recompute: statusRecompute })),
+}));
+
vi.mock('@/database/models/verifyRun', () => ({
VerifyRunModel: vi.fn(() => ({
findByOperation: runFindByOperation,
@@ -59,6 +72,7 @@ describe('driveTaskFromVerify', () => {
taskUpdateStatus,
briefCreate,
serviceUpdateStatus,
+ statusRecompute,
deliverMock,
].forEach((m) => m.mockReset());
opFindById.mockResolvedValue({ taskId: 'task-1', topicId: 'topic-done' });
@@ -86,6 +100,41 @@ describe('driveTaskFromVerify', () => {
expect(runSetMetadata).toHaveBeenCalled();
});
+ it('settles the owning task when the passing verify run belongs to a repair child', async () => {
+ runFindByOperation.mockResolvedValue({ id: 'repair-run', metadata: null, status: 'passed' });
+ opFindById.mockImplementation(async (id: string) =>
+ id === 'repair-op'
+ ? { parentOperationId: 'root-op', taskId: null, topicId: 'topic-repair' }
+ : { parentOperationId: null, taskId: 'task-1', topicId: 'topic-original' },
+ );
+
+ await driveTaskFromVerify(db, 'u1', 'repair-op');
+
+ expect(serviceUpdateStatus).toHaveBeenCalledWith({ id: 'task-1', status: 'completed' });
+ expect(deliverMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ operationId: 'repair-op',
+ taskId: 'task-1',
+ topicId: 'topic-repair',
+ }),
+ );
+ });
+
+ it('collapses every ancestor round out of repairing when a multi-repair child settles', async () => {
+ runFindByOperation.mockResolvedValue({ id: 'repair-run', metadata: null, status: 'passed' });
+ opFindById.mockImplementation(async (id: string) =>
+ id === 'repair-op-2'
+ ? { parentOperationId: 'repair-op-1', taskId: null, topicId: 'topic-repair' }
+ : id === 'repair-op-1'
+ ? { parentOperationId: 'root-op', taskId: null, topicId: 'topic-repair' }
+ : { parentOperationId: null, taskId: 'task-1', topicId: 'topic-original' },
+ );
+
+ await finalizeVerifyRun(db, 'u1', 'repair-op-2', {});
+
+ expect(statusRecompute.mock.calls).toEqual([['repair-op-1'], ['root-op']]);
+ });
+
it('failed → urgent brief + pauses, delivers a failure creator callback', async () => {
runFindByOperation.mockResolvedValue({ id: 'run-1', metadata: null, status: 'failed' });
await driveTaskFromVerify(db, 'u1', 'op-1');
diff --git a/apps/server/src/services/verify/__tests__/executor.test.ts b/apps/server/src/services/verify/__tests__/executor.test.ts
new file mode 100644
index 00000000000..cd640bd02c9
--- /dev/null
+++ b/apps/server/src/services/verify/__tests__/executor.test.ts
@@ -0,0 +1,88 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { VerifyExecutorService } from '../executor';
+
+const mocks = vi.hoisted(() => ({
+ evidenceListByRun: vi.fn(),
+ resultCreateMany: vi.fn(),
+ resultListByRun: vi.fn(),
+ resultUpdateByCheckItem: vi.fn(),
+ runEnsureForOperation: vi.fn(),
+ statusMarkVerifying: vi.fn(),
+ statusRecompute: vi.fn(),
+}));
+
+vi.mock('@/database/models/document', () => ({
+ DocumentModel: vi.fn(() => ({ findById: vi.fn() })),
+}));
+vi.mock('@/database/models/verifyEvidence', () => ({
+ VerifyEvidenceModel: vi.fn(() => ({ listByRun: mocks.evidenceListByRun })),
+}));
+vi.mock('@/database/models/verifyCheckResult', () => ({
+ VerifyCheckResultModel: vi.fn(() => ({
+ createMany: mocks.resultCreateMany,
+ listByRun: mocks.resultListByRun,
+ updateByCheckItem: mocks.resultUpdateByCheckItem,
+ })),
+}));
+vi.mock('@/database/models/verifyRun', () => ({
+ VerifyRunModel: vi.fn(() => ({ ensureForOperation: mocks.runEnsureForOperation })),
+}));
+vi.mock('../statusService', () => ({
+ VerifyStatusService: vi.fn(() => ({
+ markVerifying: mocks.statusMarkVerifying,
+ recompute: mocks.statusRecompute,
+ })),
+}));
+
+describe('VerifyExecutorService', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.evidenceListByRun.mockResolvedValue([]);
+ mocks.resultCreateMany.mockResolvedValue(undefined);
+ mocks.resultListByRun
+ .mockResolvedValueOnce([])
+ .mockResolvedValue([{ checkItemId: 'word-count', status: 'pending' }]);
+ mocks.resultUpdateByCheckItem.mockResolvedValue(undefined);
+ mocks.statusMarkVerifying.mockResolvedValue(undefined);
+ mocks.statusRecompute.mockResolvedValue('verifying');
+ });
+
+ it('runs a program criterion through the verifier-agent fallback', async () => {
+ mocks.runEnsureForOperation.mockResolvedValue({
+ id: 'run-1',
+ plan: [
+ {
+ id: 'word-count',
+ index: 0,
+ required: true,
+ title: '字数达标',
+ verifierType: 'program',
+ },
+ ],
+ planConfirmedAt: new Date(),
+ });
+ const runVerifierAgent = vi.fn().mockResolvedValue({ verifierOperationId: 'verifier-op-1' });
+
+ await new VerifyExecutorService({} as never, 'user-1').execute({
+ deliverable: 'story',
+ goal: 'write a story',
+ modelConfig: { model: 'model', provider: 'provider' },
+ operationId: 'builder-op-1',
+ runVerifierAgent,
+ });
+
+ expect(runVerifierAgent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ checkItem: expect.objectContaining({ id: 'word-count', verifierType: 'program' }),
+ operationId: 'builder-op-1',
+ }),
+ );
+ expect(mocks.resultUpdateByCheckItem).toHaveBeenCalledWith(
+ 'run-1',
+ 'word-count',
+ expect.objectContaining({ status: 'running', verifierOperationId: 'verifier-op-1' }),
+ );
+ });
+});
diff --git a/apps/server/src/services/verify/__tests__/holisticPlan.test.ts b/apps/server/src/services/verify/__tests__/holisticPlan.test.ts
index 0d7250948a1..043b10763e0 100644
--- a/apps/server/src/services/verify/__tests__/holisticPlan.test.ts
+++ b/apps/server/src/services/verify/__tests__/holisticPlan.test.ts
@@ -94,6 +94,7 @@ describe('generateDraftPlan — holistic fallback', () => {
const plan = lastPlan();
expect(plan).toHaveLength(1);
+ expect(plan[0].id).toBe('c1');
expect(plan[0].title).toBe('Crit 1');
expect(plan[0].verifierType).toBe('llm');
});
diff --git a/apps/server/src/services/verify/__tests__/reporter.test.ts b/apps/server/src/services/verify/__tests__/reporter.test.ts
index 027054e1c01..45879621691 100644
--- a/apps/server/src/services/verify/__tests__/reporter.test.ts
+++ b/apps/server/src/services/verify/__tests__/reporter.test.ts
@@ -28,8 +28,10 @@ describe('rollupVerdict', () => {
expect(
rollupVerdict([r({}), r({ required: false, status: 'failed', verdict: 'failed' })]),
).toBe('passed');
- // skipped required items are not "unresolved"
- expect(rollupVerdict([r({ status: 'skipped', verdict: null })])).toBe('passed');
+ });
+
+ it('keeps a skipped required item unresolved', () => {
+ expect(rollupVerdict([r({ status: 'skipped', verdict: null })])).toBe('uncertain');
});
});
diff --git a/apps/server/src/services/verify/__tests__/statusService.recompute.test.ts b/apps/server/src/services/verify/__tests__/statusService.recompute.test.ts
index fc3dc4cfd5c..1d41801a817 100644
--- a/apps/server/src/services/verify/__tests__/statusService.recompute.test.ts
+++ b/apps/server/src/services/verify/__tests__/statusService.recompute.test.ts
@@ -3,10 +3,18 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { VerifyStatusService } from '../statusService';
-const { runFindByOperation, runUpdateStatus, resultListByRun } = vi.hoisted(() => ({
- resultListByRun: vi.fn(),
- runFindByOperation: vi.fn(),
- runUpdateStatus: vi.fn(),
+const { acceptanceRecomputeStatus, runFindByOperation, runUpdateStatus, resultListByRun } =
+ vi.hoisted(() => ({
+ acceptanceRecomputeStatus: vi.fn(),
+ resultListByRun: vi.fn(),
+ runFindByOperation: vi.fn(),
+ runUpdateStatus: vi.fn(),
+ }));
+
+vi.mock('../acceptanceService', () => ({
+ AcceptanceService: vi.fn(() => ({
+ recomputeStatus: acceptanceRecomputeStatus,
+ })),
}));
vi.mock('@/database/models/verifyRun', () => ({
@@ -22,7 +30,8 @@ vi.mock('@/database/models/verifyCheckResult', () => ({
const db = {} as any;
// One confirmed run whose plan is the given required check items.
-const runWith = (items: { id: string }[]) => ({
+const runWith = (items: { id: string }[], acceptanceId?: string) => ({
+ acceptanceId,
id: 'run-1',
plan: items.map((i) => ({ ...i, required: true })),
planConfirmedAt: new Date(),
@@ -31,7 +40,9 @@ const runWith = (items: { id: string }[]) => ({
describe('VerifyStatusService.recompute — errored rollup', () => {
beforeEach(() => {
- [runFindByOperation, runUpdateStatus, resultListByRun].forEach((m) => m.mockReset());
+ [acceptanceRecomputeStatus, runFindByOperation, runUpdateStatus, resultListByRun].forEach((m) =>
+ m.mockReset(),
+ );
});
it('an errored required check (none failed) rolls up to `errored`, not `failed`', async () => {
@@ -44,6 +55,25 @@ describe('VerifyStatusService.recompute — errored rollup', () => {
expect(runUpdateStatus).toHaveBeenCalledWith('run-1', 'errored');
});
+ it('a skipped required check rolls up to `errored` instead of passing', async () => {
+ runFindByOperation.mockResolvedValue(runWith([{ id: 'c1' }]));
+ resultListByRun.mockResolvedValue([{ checkItemId: 'c1', status: 'skipped', verdict: null }]);
+
+ const status = await new VerifyStatusService(db, 'u1').recompute('op-1');
+
+ expect(status).toBe('errored');
+ expect(runUpdateStatus).toHaveBeenCalledWith('run-1', 'errored');
+ });
+
+ it('updates the attached acceptance when the verify rollup changes', async () => {
+ runFindByOperation.mockResolvedValue(runWith([{ id: 'c1' }], 'acceptance-1'));
+ resultListByRun.mockResolvedValue([{ checkItemId: 'c1', status: 'passed', verdict: 'passed' }]);
+
+ await new VerifyStatusService(db, 'u1').recompute('op-1');
+
+ expect(acceptanceRecomputeStatus).toHaveBeenCalledWith('acceptance-1');
+ });
+
it('a genuine failure dominates an errored check (delivery still gates)', async () => {
runFindByOperation.mockResolvedValue(runWith([{ id: 'c1' }, { id: 'c2' }]));
resultListByRun.mockResolvedValue([
diff --git a/apps/server/src/services/verify/acceptanceService.ts b/apps/server/src/services/verify/acceptanceService.ts
index 687afff1b96..ec159986404 100644
--- a/apps/server/src/services/verify/acceptanceService.ts
+++ b/apps/server/src/services/verify/acceptanceService.ts
@@ -170,20 +170,25 @@ export const buildAcceptanceCheckUnion = (rounds: RoundInput[]): AcceptanceCheck
const roundIndex = run.roundIndex ?? 0;
const plan = (run.plan ?? []) as VerifyCheckItem[];
const planById = new Map(plan.map((item) => [item.id, item]));
+ const logicalIdByCheckItemId = new Map(
+ plan.map((item) => [item.id, item.sourceCriterionId ?? item.id]),
+ );
for (const item of plan) {
- const row = ensureRow(item.id, roundIndex);
+ const logicalId = item.sourceCriterionId ?? item.id;
+ const row = ensureRow(logicalId, roundIndex);
// The latest snapshot wins: repair rounds may refine method/expected.
row.planItem = item;
row.title = item.title;
row.required = item.required;
row.category = item.category ?? row.category;
row.surface = itemSurface(item) ?? row.surface;
- lastPlannedRound.set(item.id, roundIndex);
+ lastPlannedRound.set(logicalId, roundIndex);
}
for (const result of results) {
- const row = ensureRow(result.checkItemId, roundIndex);
+ const logicalId = logicalIdByCheckItemId.get(result.checkItemId) ?? result.checkItemId;
+ const row = ensureRow(logicalId, roundIndex);
const state = resultState(result);
// The title THIS round used — the current round's snapshot, not the final one.
const roundTitle =
@@ -207,7 +212,7 @@ export const buildAcceptanceCheckUnion = (rounds: RoundInput[]): AcceptanceCheck
// order so a chain (C replaced by B replaced by A) collapses fully into A.
const foldOrder = [...rows.values()].sort((a, b) => a.introducedAtRound - b.introducedAtRound);
for (const row of foldOrder) {
- const supersedes = row.planItem?.supersedes ?? [];
+ const supersedes = (row.planItem?.supersedes ?? []).map((id) => rows.get(id)?.id ?? id);
for (const oldId of supersedes) {
const old = rows.get(oldId);
if (!old || old === row) continue;
diff --git a/apps/server/src/services/verify/executor.ts b/apps/server/src/services/verify/executor.ts
index 49a98e0e696..961bad9feb5 100644
--- a/apps/server/src/services/verify/executor.ts
+++ b/apps/server/src/services/verify/executor.ts
@@ -56,7 +56,7 @@ export interface ExecuteVerifyParams {
goal: string;
modelConfig: { model: string; provider: string };
operationId: string;
- /** Runs `agent`-type checks as verifier sub-agents; agent items skip when absent. */
+ /** Runs agent checks and program checks without a native runner as verifier sub-agents. */
runVerifierAgent?: VerifierAgentRunner;
}
@@ -153,10 +153,11 @@ export class VerifyExecutorService {
const agentItems = gated.filter((i) => i.verifierType === 'agent');
const programItems = gated.filter((i) => i.verifierType === 'program');
- // The three verifier kinds are independent — run them concurrently. LLM items
- // are judged in one batched call; each agent item spawns its own sub-agent.
+ // The verifier kinds are independent — run them concurrently. Program checks
+ // currently use the verifier agent as an evidence-producing fallback until a
+ // sandboxed native program runner is available.
await Promise.all([
- this.runProgramItems(verifyRunId, programItems),
+ this.runProgramItems(params, verifyRunId, programItems, evidenceByItem),
this.runLlmItems(params, verifyRunId, llmItems, evidenceByItem),
...agentItems.map((item) =>
this.runAgentItem(params, verifyRunId, item, evidenceByItem.get(item.id) ?? []),
@@ -216,13 +217,29 @@ export class VerifyExecutorService {
return gapIds;
}
- /** Program verifiers are a v1 placeholder (no shell environment) — mark skipped. */
- private async runProgramItems(verifyRunId: string, items: VerifyCheckItem[]): Promise<void> {
+ /** Execute program checks through the verifier agent until a native runner exists. */
+ private async runProgramItems(
+ params: ExecuteVerifyParams,
+ verifyRunId: string,
+ items: VerifyCheckItem[],
+ evidenceByItem: EvidenceByItem,
+ ): Promise<void> {
+ if (params.runVerifierAgent) {
+ await Promise.all(
+ items.map((item) =>
+ this.runAgentItem(params, verifyRunId, item, evidenceByItem.get(item.id) ?? []),
+ ),
+ );
+ return;
+ }
+
for (const item of items) {
await this.resultModel.updateByCheckItem(verifyRunId, item.id, {
completedAt: new Date(),
- status: 'skipped',
- toulmin: { limitation: 'Program verifier is not executed in v1.' },
+ status: item.required ? 'errored' : 'skipped',
+ toulmin: {
+ limitation: 'Program verifier requires a native runner or verifier-agent fallback.',
+ },
});
}
}
@@ -257,7 +274,7 @@ export class VerifyExecutorService {
if (!params.runVerifierAgent) {
await this.resultModel.updateByCheckItem(verifyRunId, item.id, {
completedAt: new Date(),
- status: 'skipped',
+ status: item.required ? 'errored' : 'skipped',
toulmin: { limitation: 'Agent verifier requires runtime context; not run here.' },
});
return;
diff --git a/apps/server/src/services/verify/planGenerator.ts b/apps/server/src/services/verify/planGenerator.ts
index 5ae6034bb99..b231ed104df 100644
--- a/apps/server/src/services/verify/planGenerator.ts
+++ b/apps/server/src/services/verify/planGenerator.ts
@@ -96,7 +96,10 @@ const criterionToCheckItem = (
): VerifyCheckItem => ({
description: criterion.description ?? undefined,
documentId: criterion.documentId ?? undefined,
- id: randomUUID(),
+ // A criterion is the stable logical acceptance check. Reuse its id for every
+ // run snapshot so independent task re-runs converge onto one Acceptance row;
+ // the verify run still scopes each immutable snapshot and result.
+ id: criterion.id,
index,
onFail: criterion.onFail,
required: criterion.required,
@@ -200,7 +203,7 @@ export class VerifyPlanGeneratorService {
items.push({
description: draft.description,
documentId,
- id: randomUUID(),
+ id: criterion.id,
index,
onFail,
required,
diff --git a/apps/server/src/services/verify/planInstantiation.ts b/apps/server/src/services/verify/planInstantiation.ts
index 60a33494bba..0a3ecbc92fb 100644
--- a/apps/server/src/services/verify/planInstantiation.ts
+++ b/apps/server/src/services/verify/planInstantiation.ts
@@ -4,6 +4,7 @@ import { TaskModel } from '@/database/models/task';
import { VerifyRunModel } from '@/database/models/verifyRun';
import type { LobeChatDatabase } from '@/database/type';
+import { AcceptanceService } from './acceptanceService';
import { VerifyPlanGeneratorService } from './planGenerator';
const log = debug('lobe-server:verify-plan-instantiation');
@@ -82,10 +83,27 @@ export const instantiateVerifyPlanOnStart = async (
await runModel.setMetadata(run.id, { maxRepairRounds: verifyConfig.maxIterations });
}
await runModel.confirmPlan(run.id);
+
+ // A task verification round belongs to its business-level Acceptance from
+ // the moment the plan is confirmed. This lets the task surface show live
+ // planned/verifying/repairing progress instead of waiting for an external
+ // ingest command to create the aggregate after verification has finished.
+ const acceptanceService = new AcceptanceService(db, userId, workspaceId);
+ const acceptance = await acceptanceService.ensureForSubject('task', params.taskId, {
+ requirement: verifyConfig.requirement?.trim() || goal,
+ });
+ // Task verify config is the source that produced this plan. Keep the
+ // aggregate goal in lockstep when a later run changes that source.
+ await acceptanceService.acceptanceModel.update(acceptance.id, {
+ requirement: verifyConfig.requirement?.trim() || goal,
+ });
+ await acceptanceService.attachRun(run.id, acceptance.id);
+
log(
- 'instantiated + confirmed verify plan for op %s (%d items)',
+ 'instantiated + confirmed verify plan for op %s (%d items), acceptance %s',
params.operationId,
run.plan.length,
+ acceptance.id,
);
}
} catch (error) {
diff --git a/apps/server/src/services/verify/repairService.ts b/apps/server/src/services/verify/repairService.ts
index 1b0d8cc4836..28ad891e17d 100644
--- a/apps/server/src/services/verify/repairService.ts
+++ b/apps/server/src/services/verify/repairService.ts
@@ -11,6 +11,7 @@ import type { VerifyCheckResultItem } from '@/database/schemas/verify';
import type { LobeChatDatabase } from '@/database/type';
import { AiAgentService } from '@/server/services/aiAgent';
+import { AcceptanceService } from './acceptanceService';
import { VerifyStatusService } from './statusService';
const log = debug('lobe-server:verify-repair');
@@ -134,6 +135,16 @@ export const createRepairRunner = (params: {
// instead of falling back to the rubric/default.
if (sourceRun?.metadata) await runModel.setMetadata(repairRun.id, sourceRun.metadata);
await runModel.confirmPlan(repairRun.id);
+
+ // A repair is the next immutable round of the same business acceptance,
+ // not an unrelated verification session. Attach it before it settles so
+ // the aggregate immediately advances from "repairing" to the live round.
+ if (sourceRun?.acceptanceId) {
+ await new AcceptanceService(db, userId, workspaceId).attachRun(
+ repairRun.id,
+ sourceRun.acceptanceId,
+ );
+ }
}
log('repair op %s → %s (round %d)', operationId, repairOperationId, round + 1);
diff --git a/apps/server/src/services/verify/reportRollup.ts b/apps/server/src/services/verify/reportRollup.ts
index adec97fe4fd..28ff2dd0059 100644
--- a/apps/server/src/services/verify/reportRollup.ts
+++ b/apps/server/src/services/verify/reportRollup.ts
@@ -17,15 +17,14 @@ export interface ReportStats {
export const rollupVerdict = (results: VerifyCheckResultItem[]): VerifyVerdict => {
const required = results.filter((r) => r.required);
const failed = (r: VerifyCheckResultItem) => r.status === 'failed' || r.verdict === 'failed';
- const unresolved = (r: VerifyCheckResultItem) =>
- r.verdict === 'uncertain' || (!r.verdict && r.status !== 'skipped');
+ const unresolved = (r: VerifyCheckResultItem) => r.verdict === 'uncertain' || !r.verdict;
if (required.some(failed)) return 'failed';
if (required.some(unresolved)) return 'uncertain';
return 'passed';
};
-/** Verdict tallies for the report's statistics snapshot (pending/skipped → total only). */
+/** Verdict tallies for the report's statistics snapshot (unresolved → total only). */
export const countStats = (results: VerifyCheckResultItem[]): ReportStats => ({
failed: results.filter((r) => r.verdict === 'failed').length,
passed: results.filter((r) => r.verdict === 'passed').length,
diff --git a/apps/server/src/services/verify/settle.ts b/apps/server/src/services/verify/settle.ts
index f9749f49ad2..863b4e97282 100644
--- a/apps/server/src/services/verify/settle.ts
+++ b/apps/server/src/services/verify/settle.ts
@@ -11,10 +11,50 @@ import { TaskResultBridgeService } from '@/server/services/taskResultBridge';
import { maybeAutoRepair } from './repairService';
import { VerifyReporterService } from './reporter';
+import { VerifyStatusService } from './statusService';
const log = debug('lobe-server:verify-settle');
const TERMINAL_TASK_STATUS = new Set(['canceled', 'completed', 'failed']);
+const MAX_OPERATION_ANCESTORS = 32;
+
+/**
+ * Repair operations are descendants of the task's original operation and do
+ * not necessarily repeat `taskId` on every child row. Walk the bounded parent
+ * chain so the final repair verdict still settles the owning task.
+ */
+const resolveTaskOperation = async (operationModel: AgentOperationModel, operationId: string) => {
+ let current = await operationModel.findById(operationId);
+ let depth = 0;
+
+ while (current && !current.taskId && current.parentOperationId && depth < 10) {
+ current = await operationModel.findById(current.parentOperationId);
+ depth += 1;
+ }
+
+ return current?.taskId ? current : null;
+};
+
+/** Collapse every transient `repairing` marker left along a bounded repair chain. */
+export const recomputeRepairAncestors = async (
+ operationModel: AgentOperationModel,
+ statusService: VerifyStatusService,
+ operationId: string,
+) => {
+ const visited = new Set<string>();
+ let current = await operationModel.findById(operationId);
+ let depth = 0;
+
+ while (current?.parentOperationId && depth < MAX_OPERATION_ANCESTORS) {
+ const parentOperationId = current.parentOperationId;
+ if (visited.has(parentOperationId)) break;
+ visited.add(parentOperationId);
+
+ await statusService.recompute(parentOperationId);
+ current = await operationModel.findById(parentOperationId);
+ depth += 1;
+ }
+};
interface ReportContext {
deliverable: string;
@@ -45,11 +85,13 @@ export const driveTaskFromVerify = async (
if (run?.status !== 'passed' && run?.status !== 'failed' && run?.status !== 'errored') return;
if ((run.metadata as { taskDrivenAt?: string } | null)?.taskDrivenAt) return; // already drove
- const op = await new AgentOperationModel(db, userId, workspaceId).findById(operationId);
- if (!op?.taskId) return; // not a task-bound run — nothing to drive
+ const operationModel = new AgentOperationModel(db, userId, workspaceId);
+ const op = await operationModel.findById(operationId);
+ const taskOperation = await resolveTaskOperation(operationModel, operationId);
+ if (!op || !taskOperation?.taskId) return; // not a task-bound run — nothing to drive
const taskModel = new TaskModel(db, userId, workspaceId);
- const task = await taskModel.findById(op.taskId);
+ const task = await taskModel.findById(taskOperation.taskId);
if (!task || TERMINAL_TASK_STATUS.has(task.status)) return; // task already settled
if (run.status === 'passed') {
@@ -57,10 +99,10 @@ export const driveTaskFromVerify = async (
// The verify → TaskService → aiAgent → agentRuntime completion → verify
// cycle is safe statically since every use is call-time (inside this fn).
await new TaskService(db, userId, workspaceId).updateStatus({
- id: op.taskId,
+ id: taskOperation.taskId,
status: 'completed',
});
- log('verify passed → task %s completed', op.taskId);
+ log('verify passed → task %s completed', taskOperation.taskId);
} else {
// Two non-pass outcomes, kept distinct so an infra error never reads as a
// rejected delivery:
@@ -75,19 +117,19 @@ export const driveTaskFromVerify = async (
summary: isErrored
? 'Verification could not run (internal error); the delivery was not evaluated.'
: 'Delivery did not pass verification.',
- taskId: op.taskId,
+ taskId: taskOperation.taskId,
title: isErrored
? `${task.identifier} verification errored`
: `${task.identifier} failed verification`,
trigger: 'task',
type: 'error',
});
- await taskModel.updateStatus(op.taskId, 'paused', { error: null });
+ await taskModel.updateStatus(taskOperation.taskId, 'paused', { error: null });
log(
isErrored
? 'verify errored → task %s paused + brief'
: 'verify failed → task %s paused + brief',
- op.taskId,
+ taskOperation.taskId,
);
}
@@ -106,13 +148,17 @@ export const driveTaskFromVerify = async (
await new TaskResultBridgeService(db, userId, workspaceId).deliver({
operationId,
reason: run.status === 'passed' ? 'done' : 'error',
- taskId: op.taskId,
+ taskId: taskOperation.taskId,
taskIdentifier: task.identifier,
topicId: op.topicId ?? undefined,
...(errorMessage && { errorMessage }),
});
} catch (error) {
- log('verify-settle creator callback failed for task %s (non-fatal): %O', op.taskId, error);
+ log(
+ 'verify-settle creator callback failed for task %s (non-fatal): %O',
+ taskOperation.taskId,
+ error,
+ );
}
await runModel.setMetadata(run.id, { taskDrivenAt: new Date().toISOString() });
@@ -154,5 +200,14 @@ export const finalizeVerifyRun = async (
});
}
+ // The repaired child is now the active/final round. Every failed ancestor may
+ // have been stamped `repairing`, so collapse the complete bounded chain back
+ // to the verdict derived from each round's own results.
+ await recomputeRepairAncestors(
+ new AgentOperationModel(db, userId, workspaceId),
+ new VerifyStatusService(db, userId, workspaceId),
+ operationId,
+ );
+
await driveTaskFromVerify(db, userId, operationId, workspaceId);
};
diff --git a/apps/server/src/services/verify/statusService.ts b/apps/server/src/services/verify/statusService.ts
index 55084e68345..80690ce4992 100644
--- a/apps/server/src/services/verify/statusService.ts
+++ b/apps/server/src/services/verify/statusService.ts
@@ -5,6 +5,8 @@ import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';
import { VerifyRunModel } from '@/database/models/verifyRun';
import type { LobeChatDatabase } from '@/database/type';
+import { AcceptanceService } from './acceptanceService';
+
const log = debug('lobe-server:verify-status');
/**
@@ -14,10 +16,16 @@ const log = debug('lobe-server:verify-status');
* sessions by their bound Agent Run (`operationId`) for the agent pipeline.
*/
export class VerifyStatusService {
+ private readonly db: LobeChatDatabase;
private readonly runModel: VerifyRunModel;
private readonly resultModel: VerifyCheckResultModel;
+ private readonly userId: string;
+ private readonly workspaceId?: string;
constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ this.db = db;
+ this.userId = userId;
+ this.workspaceId = workspaceId;
this.runModel = new VerifyRunModel(db, userId, workspaceId);
this.resultModel = new VerifyCheckResultModel(db, userId, workspaceId);
}
@@ -30,8 +38,8 @@ export class VerifyStatusService {
* - else any required result errored (verifier couldn't run) → `errored`
* - otherwise → `passed`
* A genuine `failed` dominates an `errored` (the delivery has a real problem to
- * fix, so it should still gate + repair). `skipped` results (e.g. v1 program
- * placeholders) are pass-through.
+ * fix, so it should still gate + repair). A required `skipped` result is an
+ * execution gap and rolls up as `errored`; only optional checks may skip.
*/
async recompute(operationId: string): Promise<VerifyRunStatus | null> {
const run = await this.runModel.findByOperation(operationId);
@@ -60,7 +68,7 @@ export class VerifyStatusService {
continue;
}
if (result.status === 'failed' || result.verdict === 'failed') anyFailed = true;
- else if (result.status === 'errored') anyErrored = true;
+ else if (result.status === 'errored' || result.status === 'skipped') anyErrored = true;
}
const status: VerifyRunStatus = anyPending
@@ -73,6 +81,11 @@ export class VerifyStatusService {
if (status !== run.status) {
await this.runModel.updateStatus(run.id, status);
+ if (run.acceptanceId) {
+ await new AcceptanceService(this.db, this.userId, this.workspaceId).recomputeStatus(
+ run.acceptanceId,
+ );
+ }
log('rollup op %s (run %s) → %s', operationId, run.id, status);
}
@@ -100,5 +113,10 @@ export class VerifyStatusService {
return;
}
await this.runModel.updateStatus(run.id, status);
+ if (run.acceptanceId) {
+ await new AcceptanceService(this.db, this.userId, this.workspaceId).recomputeStatus(
+ run.acceptanceId,
+ );
+ }
}
}
diff --git a/locales/en-US/verify.json b/locales/en-US/verify.json
index 212a0dcdafd..2fd49a2000b 100644
--- a/locales/en-US/verify.json
+++ b/locales/en-US/verify.json
@@ -126,7 +126,7 @@
"acceptance.group.ignoredCount": "{{count}} ignored",
"acceptance.group.passRatio": "{{passed}}/{{total}} passed",
"acceptance.group.rejectedCount": "{{count}} sent back",
- "acceptance.group.uncategorized": "Other requirements",
+ "acceptance.group.uncategorized": "Ungrouped",
"acceptance.history.jump": "Round {{round}} — click to locate it in the ledger",
"acceptance.latestSummary": "Latest report summary",
"acceptance.ledger.accepted": "Accepted",
@@ -159,6 +159,7 @@
"acceptance.review.attachLimit": "Up to {{count}} screenshots.",
"acceptance.review.attachTooLarge": "The image is too large (10MB max).",
"acceptance.review.confirmReject": "Submit feedback",
+ "acceptance.review.detailPlaceholder": "Leave a comment for this check. It will be submitted with your decision…",
"acceptance.review.feedbackLabel": "Feedback",
"acceptance.review.fullscreen": "Annotate fullscreen",
"acceptance.review.fullscreenDone": "Done annotating",
diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.json
index 1af129a3d0b..7369d52b567 100644
--- a/locales/zh-CN/verify.json
+++ b/locales/zh-CN/verify.json
@@ -126,7 +126,7 @@
"acceptance.group.ignoredCount": "{{count}} 已忽略",
"acceptance.group.passRatio": "{{passed}}/{{total}} 通过",
"acceptance.group.rejectedCount": "{{count}} 已打回",
- "acceptance.group.uncategorized": "其他需求",
+ "acceptance.group.uncategorized": "未分组",
"acceptance.history.jump": "第 {{round}} 轮——点击在轮次审计中定位",
"acceptance.latestSummary": "最新报告摘要",
"acceptance.ledger.accepted": "已验收",
@@ -159,6 +159,7 @@
"acceptance.review.attachLimit": "最多添加 {{count}} 张截图。",
"acceptance.review.attachTooLarge": "图片过大(最大 10MB)。",
"acceptance.review.confirmReject": "提交反馈",
+ "acceptance.review.detailPlaceholder": "留下对该检查项的评论,提交审核决定时会一并发送…",
"acceptance.review.feedbackLabel": "反馈",
"acceptance.review.fullscreen": "全屏标注",
"acceptance.review.fullscreenDone": "完成标注",
diff --git a/packages/database/src/models/__tests__/verifyCriterion.test.ts b/packages/database/src/models/__tests__/verifyCriterion.test.ts
index d2082db546f..1756d6c9cef 100644
--- a/packages/database/src/models/__tests__/verifyCriterion.test.ts
+++ b/packages/database/src/models/__tests__/verifyCriterion.test.ts
@@ -2,7 +2,13 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../core/getTestDB';
-import { users, verifyCriteria } from '../../schemas';
+import {
+ users,
+ verifyCriteria,
+ verifyRubricCriteria,
+ verifyRubrics,
+ workspaces,
+} from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { VerifyCriterionModel } from '../verifyCriterion';
@@ -17,6 +23,8 @@ beforeEach(async () => {
});
afterEach(async () => {
+ await serverDB.delete(verifyRubricCriteria);
+ await serverDB.delete(verifyRubrics);
await serverDB.delete(verifyCriteria);
await serverDB.delete(users);
});
@@ -62,6 +70,65 @@ describe('VerifyCriterionModel', () => {
expect(resolved.map((r) => r.id).sort()).toEqual([a.id, b.id].sort());
});
+ it('forks rubric criteria while preserving task-local criterion identities', async () => {
+ const model = new VerifyCriterionModel(serverDB, userId);
+ const shared = await model.create({ title: 'shared', verifierType: 'llm' });
+ const local = await model.create({ title: 'local', verifierType: 'agent' });
+ const [rubric] = await serverDB
+ .insert(verifyRubrics)
+ .values({ title: 'template', userId })
+ .returning();
+ await serverDB.insert(verifyRubricCriteria).values({
+ criterionId: shared.id,
+ rubricId: rubric.id,
+ userId,
+ });
+
+ const [forkedId, localId] = await model.forkRubricCriteria([shared.id, local.id]);
+
+ expect(forkedId).not.toBe(shared.id);
+ expect(localId).toBe(local.id);
+ expect(await model.findById(forkedId)).toMatchObject({
+ title: shared.title,
+ verifierType: shared.verifierType,
+ });
+
+ await model.update(forkedId, { title: 'task edit' });
+ expect(await model.findById(shared.id)).toMatchObject({ title: 'shared' });
+ });
+
+ it('forks a workspace rubric criterion authored by another member', async () => {
+ const workspaceId = 'verify-criterion-workspace';
+ await serverDB.insert(workspaces).values({
+ id: workspaceId,
+ name: 'Verify workspace',
+ primaryOwnerId: otherUserId,
+ slug: workspaceId,
+ });
+ const author = new VerifyCriterionModel(serverDB, otherUserId, workspaceId);
+ const editor = new VerifyCriterionModel(serverDB, userId, workspaceId);
+ const shared = await author.create({ title: 'workspace shared', verifierType: 'llm' });
+ const [rubric] = await serverDB
+ .insert(verifyRubrics)
+ .values({ title: 'workspace template', userId: otherUserId, workspaceId })
+ .returning();
+ await serverDB.insert(verifyRubricCriteria).values({
+ criterionId: shared.id,
+ rubricId: rubric.id,
+ userId: otherUserId,
+ workspaceId,
+ });
+
+ const [forkedId] = await editor.forkRubricCriteria([shared.id]);
+
+ expect(forkedId).not.toBe(shared.id);
+ expect(await editor.findById(forkedId)).toMatchObject({
+ title: 'workspace shared',
+ userId,
+ workspaceId,
+ });
+ });
+
it('updates and deletes', async () => {
const model = new VerifyCriterionModel(serverDB, userId);
const c = await model.create({ title: 'old', verifierType: 'llm' });
diff --git a/packages/database/src/models/verifyCriterion.ts b/packages/database/src/models/verifyCriterion.ts
index 7eaa7b54589..bde9c10c887 100644
--- a/packages/database/src/models/verifyCriterion.ts
+++ b/packages/database/src/models/verifyCriterion.ts
@@ -1,7 +1,7 @@
import { and, desc, eq, inArray } from 'drizzle-orm';
import type { NewVerifyCriterion, VerifyCriterionItem } from '../schemas/verify';
-import { verifyCriteria } from '../schemas/verify';
+import { verifyCriteria, verifyRubricCriteria } from '../schemas/verify';
import type { LobeChatDatabase } from '../type';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
@@ -59,6 +59,64 @@ export class VerifyCriterionModel {
.where(and(inArray(verifyCriteria.id, ids), this.ownership()));
};
+ /**
+ * Give a task private copies of criteria that are still mounted on a reusable
+ * rubric. Older task configs could point at the rubric rows directly; editing
+ * those rows would silently rewrite the template for every future task.
+ *
+ * Returned ids preserve the input order. Criteria that are already task-local
+ * keep their identity, while rubric-owned criteria are cloned in one transaction.
+ */
+ forkRubricCriteria = async (ids: string[]): Promise<string[]> => {
+ if (ids.length === 0) return [];
+
+ return this.db.transaction(async (tx) => {
+ const criteria = await tx
+ .select()
+ .from(verifyCriteria)
+ .where(and(inArray(verifyCriteria.id, ids), this.ownership()));
+ const criteriaById = new Map(criteria.map((criterion) => [criterion.id, criterion]));
+
+ const rubricLinks = await tx
+ .select({ criterionId: verifyRubricCriteria.criterionId })
+ .from(verifyRubricCriteria)
+ .where(
+ and(
+ inArray(verifyRubricCriteria.criterionId, ids),
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ verifyRubricCriteria,
+ ),
+ ),
+ );
+ const sharedIds = new Set(rubricLinks.map(({ criterionId }) => criterionId));
+ const sharedCriteria = ids
+ .filter((id, index) => sharedIds.has(id) && ids.indexOf(id) === index)
+ .map((id) => criteriaById.get(id))
+ .filter((criterion): criterion is VerifyCriterionItem => Boolean(criterion));
+
+ if (sharedCriteria.length === 0) return ids;
+
+ const clones = await tx
+ .insert(verifyCriteria)
+ .values(
+ sharedCriteria.map(
+ ({ createdAt: _createdAt, id: _id, updatedAt: _updatedAt, ...criterion }) =>
+ buildWorkspacePayload(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ criterion,
+ ),
+ ),
+ )
+ .returning({ id: verifyCriteria.id });
+ const forkedById = new Map(
+ sharedCriteria.map((criterion, index) => [criterion.id, clones[index].id]),
+ );
+
+ return ids.map((id) => forkedById.get(id) ?? id);
+ });
+ };
+
update = async (id: string, value: Partial<Omit<VerifyCriterionItem, 'id' | 'userId'>>) => {
return this.db
.update(verifyCriteria)
diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.ts
index efd90434f34..c5461104254 100644
--- a/packages/locales/src/default/verify.ts
+++ b/packages/locales/src/default/verify.ts
@@ -148,7 +148,7 @@ export default {
'acceptance.group.feedbackTitle': 'Group feedback',
'acceptance.group.passRatio': '{{passed}}/{{total}} passed',
'acceptance.group.rejectedCount': '{{count}} sent back',
- 'acceptance.group.uncategorized': 'Other requirements',
+ 'acceptance.group.uncategorized': 'Ungrouped',
'acceptance.history.jump': 'Round {{round}} — click to locate it in the ledger',
'acceptance.latestSummary': 'Latest report summary',
'acceptance.ledger.accepted': 'Accepted',
@@ -181,6 +181,8 @@ export default {
'acceptance.review.attachLimit': 'Up to {{count}} screenshots.',
'acceptance.review.attachTooLarge': 'The image is too large (10MB max).',
'acceptance.review.confirmReject': 'Submit feedback',
+ 'acceptance.review.detailPlaceholder':
+ 'Leave a comment for this check. It will be submitted with your decision…',
'acceptance.review.feedbackLabel': 'Feedback',
'acceptance.review.fullscreen': 'Annotate fullscreen',
'acceptance.review.fullscreenDone': 'Done annotating',
diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.ts
index a5792f6a082..d8c56bfb263 100644
--- a/packages/types/src/task/index.ts
+++ b/packages/types/src/task/index.ts
@@ -441,6 +441,8 @@ export interface TaskDetailData {
lastAt?: string | null;
timeout?: number | null;
};
+ /** Stable database identity used by subject-bound aggregates such as Acceptance. */
+ id?: string;
identifier: string;
instruction: string;
name?: string | null;
diff --git a/src/features/AgentTasks/AgentTaskDetail/PendingAcceptanceCheckList.tsx b/src/features/AgentTasks/AgentTaskDetail/PendingAcceptanceCheckList.tsx
new file mode 100644
index 00000000000..bc2589bc6f9
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskDetail/PendingAcceptanceCheckList.tsx
@@ -0,0 +1,90 @@
+'use client';
+
+import { Block, Flexbox, Icon, Text } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { CircleDashed } from 'lucide-react';
+import { memo } from 'react';
+
+const styles = createStaticStyles(({ css }) => ({
+ groupHeader: css`
+ padding-block: 9px;
+ padding-inline: 12px;
+ `,
+ list: css`
+ overflow: hidden;
+ width: 100%;
+ padding: 0;
+ `,
+ row: css`
+ cursor: pointer;
+ padding-block: 10px;
+ padding-inline: 12px;
+
+ & + & {
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+ }
+
+ &:hover {
+ background: ${cssVar.colorFillQuaternary};
+ }
+ `,
+ seq: css`
+ flex: none;
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+}));
+
+export interface PendingAcceptanceCheckItem {
+ id: string;
+ title: string;
+}
+
+interface PendingAcceptanceCheckListProps {
+ groupLabel: string;
+ items: PendingAcceptanceCheckItem[];
+ onOpen: (item: PendingAcceptanceCheckItem) => void;
+}
+
+/** The pre-run projection of Acceptance checks: same list grammar, pending verdicts. */
+export const PendingAcceptanceCheckList = memo<PendingAcceptanceCheckListProps>(
+ ({ groupLabel, items, onOpen }) => (
+ <Block className={styles.list} variant={'outlined'}>
+ <Flexbox horizontal align={'center'} className={styles.groupHeader} gap={8}>
+ <Text fontSize={12}>{groupLabel}</Text>
+ <Text fontSize={11} type={'secondary'}>
+ {items.length}
+ </Text>
+ </Flexbox>
+ {items.map((item, index) => (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.row}
+ data-task-acceptance-criterion={item.id}
+ gap={10}
+ key={item.id}
+ role={'button'}
+ tabIndex={0}
+ onClick={() => onOpen(item)}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter' || event.key === ' ') onOpen(item);
+ }}
+ >
+ <Icon
+ color={cssVar.colorTextQuaternary}
+ icon={CircleDashed}
+ size={16}
+ style={{ flex: 'none' }}
+ />
+ <span className={styles.seq}>C{index + 1}</span>
+ <Text ellipsis style={{ flex: 1, minWidth: 0 }}>
+ {item.title}
+ </Text>
+ </Flexbox>
+ ))}
+ </Block>
+ ),
+);
+
+PendingAcceptanceCheckList.displayName = 'PendingAcceptanceCheckList';
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.test.tsx
index 7e6a09f019c..6ab98541d78 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.test.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.test.tsx
@@ -5,6 +5,7 @@ import { fireEvent, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { PendingAcceptanceCheckList } from './PendingAcceptanceCheckList';
import TaskAcceptance from './TaskAcceptance';
const mocks = vi.hoisted(() => ({
@@ -24,6 +25,7 @@ const mocks = vi.hoisted(() => ({
mutateBundle: vi.fn(),
mutateSubject: vi.fn(),
openAcceptanceCheck: vi.fn(),
+ subjectArgs: [] as unknown[],
toggleTaskAgentPanel: vi.fn(),
}));
@@ -71,6 +73,7 @@ vi.mock('antd-style', () => ({
}),
cssVar: {
colorTextDescription: '#999',
+ colorTextQuaternary: '#aaa',
colorTextSecondary: '#666',
},
}));
@@ -98,11 +101,15 @@ vi.mock('@/features/Verify', () => ({
isLoading: false,
mutate: mocks.mutateBundle,
}),
- useAcceptanceBySubject: () => ({
- data: mocks.acceptanceSubject,
- error: undefined,
- mutate: mocks.mutateSubject,
- }),
+ useAcceptanceBySubject: (...args: unknown[]) => {
+ mocks.subjectArgs = args;
+ return {
+ data: mocks.acceptanceSubject,
+ error: undefined,
+ isLoading: false,
+ mutate: mocks.mutateSubject,
+ };
+ },
}));
vi.mock('@/services/verify', () => ({
@@ -129,10 +136,16 @@ vi.mock('@/store/global', () => ({
vi.mock('@/store/task', () => ({
useTaskStore: (selector: (state: Record<string, unknown>) => unknown) =>
- selector({ activeTaskId: 'T-231' }),
+ selector({
+ activeTaskId: 'T-231',
+ taskDetailMap: { 'T-231': { id: 'task-database-231', identifier: 'T-231' } },
+ }),
}));
vi.mock('../shared/AccordionArrowIcon', () => ({ default: () => <span>arrow</span> }));
+vi.mock('./TaskVerifyConfig', () => ({
+ default: () => <div data-testid="task-acceptance-criteria">criteria</div>,
+}));
describe('TaskAcceptance', () => {
beforeEach(() => {
@@ -141,10 +154,35 @@ describe('TaskAcceptance', () => {
mocks.bundle = undefined;
});
- it('stays absent when the task has no acceptance aggregate', () => {
- const { container } = render(<TaskAcceptance />);
+ it('renders the configured criteria in the same slot before an acceptance aggregate exists', () => {
+ render(<TaskAcceptance />);
+
+ expect(screen.getByTestId('task-acceptance-criteria')).toBeInTheDocument();
+ expect(mocks.subjectArgs).toEqual(['task', 'task-database-231']);
+ });
- expect(container).toBeEmptyDOMElement();
+ it('renders pending criteria with the Acceptance check row grammar', () => {
+ const onOpen = vi.fn();
+
+ render(
+ <PendingAcceptanceCheckList
+ groupLabel={'Ungrouped'}
+ items={[
+ { id: 'criterion-1', title: 'Word count' },
+ { id: 'criterion-2', title: 'Markdown structure' },
+ ]}
+ onOpen={onOpen}
+ />,
+ );
+
+ expect(screen.getByText('Ungrouped')).toBeInTheDocument();
+ expect(screen.getByText('C1')).toBeInTheDocument();
+ expect(screen.getByText('C2')).toBeInTheDocument();
+ expect(screen.queryByText('Agent')).not.toBeInTheDocument();
+ expect(screen.queryByText('Required')).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByText('Word count'));
+ expect(onOpen).toHaveBeenCalledWith({ id: 'criterion-1', title: 'Word count' });
});
it('renders grouped checks and opens the selected check in the Acceptance portal', () => {
@@ -160,10 +198,28 @@ describe('TaskAcceptance', () => {
render(<TaskAcceptance />);
+ expect(screen.queryByTestId('task-acceptance-criteria')).not.toBeInTheDocument();
expect(screen.getByText('Setup')).toBeInTheDocument();
expect(screen.getByText('Result')).toBeInTheDocument();
fireEvent.click(screen.getByText('Create task'));
expect(mocks.toggleTaskAgentPanel).toHaveBeenCalledWith(true);
expect(mocks.openAcceptanceCheck).toHaveBeenCalledWith('acceptance-1', 'c1');
});
+
+ it('keeps the Acceptance cross-round union visible in Task detail', () => {
+ mocks.acceptanceSubject = { id: 'acceptance-1' };
+ mocks.bundle = {
+ acceptance: { id: 'acceptance-1', requirement: 'Everything is verifiable.' },
+ checks: [
+ { category: 'Current', id: 'c1', seq: 1, title: 'Current check' },
+ { category: 'Historical', id: 'old', seq: 2, title: 'Removed check' },
+ ],
+ isOwner: true,
+ };
+
+ render(<TaskAcceptance />);
+
+ expect(screen.getByText('Current check')).toBeInTheDocument();
+ expect(screen.getByText('Removed check')).toBeInTheDocument();
+ });
});
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.tsx
index c360ade612f..a5465cf7db8 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.tsx
@@ -1,9 +1,9 @@
'use client';
-import { ActionIcon, Block, Flexbox, Icon, Tag, Text } from '@lobehub/ui';
+import { ActionIcon, Block, Flexbox, Icon, Text } from '@lobehub/ui';
import { Button } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
-import { ChevronRight, ChevronsDownUp, ChevronsUpDown, RotateCcw, ShieldCheck } from 'lucide-react';
+import { ChevronRight, ChevronsDownUp, ChevronsUpDown, RotateCcw } from 'lucide-react';
import { memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -22,7 +22,9 @@ import { useGlobalStore } from '@/store/global';
import { useTaskStore } from '@/store/task';
import { taskDetailSelectors } from '@/store/task/selectors';
-import AccordionArrowIcon from '../shared/AccordionArrowIcon';
+import { resolveTaskAcceptanceRequirement } from './resolveTaskAcceptanceProjection';
+import { TaskAcceptanceHeader } from './TaskAcceptanceHeader';
+import TaskVerifyConfig from './TaskVerifyConfig';
const styles = createStaticStyles(({ css }) => ({
body: css`
@@ -127,15 +129,17 @@ const TaskAcceptance = memo(() => {
const openAcceptanceCheck = useChatStore((state) => state.openAcceptanceCheck);
const currentPortalView = useChatStore(chatPortalSelectors.currentViewType);
const showTaskAgentPanel = useGlobalStore((state) => state.toggleTaskAgentPanel);
- const taskId = useTaskStore(taskDetailSelectors.activeTaskId);
+ const taskDatabaseId = useTaskStore(taskDetailSelectors.activeTaskDatabaseId);
+ const verify = useTaskStore(taskDetailSelectors.activeTaskVerifyConfig);
const [sectionExpanded, setSectionExpanded] = useState(true);
const [collapsedGroups, setCollapsedGroups] = useState<Set<string>>(() => new Set());
const {
data: acceptanceSubject,
error: subjectError,
+ isLoading: subjectLoading,
mutate: mutateSubject,
- } = useAcceptanceBySubject('task', taskId ?? null);
+ } = useAcceptanceBySubject('task', taskDatabaseId ?? null);
const {
data: bundle,
error: bundleError,
@@ -143,7 +147,14 @@ const TaskAcceptance = memo(() => {
mutate: mutateBundle,
} = useAcceptanceBundle(acceptanceSubject?.id ?? null);
+ // Task detail intentionally renders the Acceptance's cross-round union. The
+ // count may grow when later rounds introduce checks; that history is part of
+ // the delivery record rather than a mismatch with the original configuration.
const checks = useMemo(() => bundle?.checks ?? [], [bundle?.checks]);
+ const requirement = resolveTaskAcceptanceRequirement(
+ verify?.requirement,
+ bundle?.acceptance.requirement,
+ );
const groups = useMemo(
() => groupChecks(checks, t('acceptance.group.uncategorized', { ns: 'verify' })),
[checks, t],
@@ -151,33 +162,24 @@ const TaskAcceptance = memo(() => {
const groupKeys = groups.map((group) => group.key);
const allGroupsCollapsed =
groupKeys.length > 0 && groupKeys.every((key) => collapsedGroups.has(key));
- if (!acceptanceSubject && !subjectError) return null;
+ if (subjectLoading) return <NeuralNetworkLoading size={28} />;
+ // Before the first Acceptance round exists, the configured criteria ARE the
+ // delivery acceptance. Keep them in this single slot; once a round exists,
+ // replace the definitions with their live/result projection below.
+ if (!acceptanceSubject && !subjectError) return <TaskVerifyConfig />;
- const renderHeader = () => (
- <Block
- clickable
- horizontal
- align={'center'}
- gap={8}
- paddingBlock={4}
- paddingInline={8}
- style={{ cursor: 'pointer', width: 'fit-content' }}
- variant={'borderless'}
- onClick={() => setSectionExpanded((expanded) => !expanded)}
- >
- <Icon color={cssVar.colorTextDescription} icon={ShieldCheck} size={16} />
- <Text color={cssVar.colorTextSecondary} fontSize={13} weight={500}>
- {t('taskDetail.acceptance.title')}
- </Text>
- {checks.length > 0 && <Tag size={'small'}>{checks.length}</Tag>}
- <AccordionArrowIcon isOpen={sectionExpanded} style={{ color: cssVar.colorTextDescription }} />
- </Block>
+ const header = (
+ <TaskAcceptanceHeader
+ count={checks.length}
+ isOpen={sectionExpanded}
+ onToggle={() => setSectionExpanded((expanded) => !expanded)}
+ />
);
if (subjectError) {
return (
<Flexbox gap={8}>
- {renderHeader()}
+ {header}
<Flexbox className={styles.body}>
<AcceptanceError onRetry={() => void mutateSubject()} />
</Flexbox>
@@ -187,19 +189,19 @@ const TaskAcceptance = memo(() => {
return (
<Flexbox gap={8}>
- {renderHeader()}
+ {header}
{sectionExpanded && (
<Flexbox className={styles.body} gap={14}>
{bundleLoading && <NeuralNetworkLoading size={28} />}
{bundleError && <AcceptanceError onRetry={() => void mutateBundle()} />}
{bundle && (
<>
- {bundle.acceptance.requirement && (
+ {requirement && (
<Flexbox gap={6}>
<Text fontSize={12} type={'secondary'}>
{t('taskDetail.acceptance.goal')}
</Text>
- <Text>{bundle.acceptance.requirement}</Text>
+ <Text>{requirement}</Text>
</Flexbox>
)}
<Flexbox gap={7}>
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskAcceptanceHeader.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptanceHeader.tsx
new file mode 100644
index 00000000000..669f36bd3b7
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptanceHeader.tsx
@@ -0,0 +1,45 @@
+'use client';
+
+import { Block, Icon, Tag, Text } from '@lobehub/ui';
+import { cssVar } from 'antd-style';
+import { ShieldCheck } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AccordionArrowIcon from '../shared/AccordionArrowIcon';
+
+interface TaskAcceptanceHeaderProps {
+ count?: number;
+ isOpen: boolean;
+ onToggle: () => void;
+}
+
+/** Canonical Task detail header shared by acceptance definition and result modes. */
+export const TaskAcceptanceHeader = memo<TaskAcceptanceHeaderProps>(
+ ({ count, isOpen, onToggle }) => {
+ const { t } = useTranslation('chat');
+
+ return (
+ <Block
+ clickable
+ horizontal
+ align={'center'}
+ gap={8}
+ paddingBlock={4}
+ paddingInline={8}
+ style={{ cursor: 'pointer', width: 'fit-content' }}
+ variant={'borderless'}
+ onClick={onToggle}
+ >
+ <Icon color={cssVar.colorTextDescription} icon={ShieldCheck} size={16} />
+ <Text color={cssVar.colorTextSecondary} fontSize={13} weight={500}>
+ {t('taskDetail.acceptance.title')}
+ </Text>
+ {Boolean(count) && <Tag size={'small'}>{count}</Tag>}
+ <AccordionArrowIcon isOpen={isOpen} style={{ color: cssVar.colorTextDescription }} />
+ </Block>
+ );
+ },
+);
+
+TaskAcceptanceHeader.displayName = 'TaskAcceptanceHeader';
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailSections.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailSections.tsx
index a8689747076..d0be53f768b 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailSections.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailSections.tsx
@@ -12,7 +12,6 @@ import TaskModelConfig from './TaskModelConfig';
import TaskParentBar from './TaskParentBar';
import TaskProperties from './TaskProperties';
import TaskSubtasks from './TaskSubtasks';
-import TaskVerifyConfig from './TaskVerifyConfig';
/**
* The scrollable body sections of a task detail, shared by the full-page
@@ -39,7 +38,6 @@ const TaskDetailSections = memo(() => {
</Flexbox>
<Flexbox gap={24} style={{ paddingBottom: 120 }}>
<TaskInstruction />
- <TaskVerifyConfig />
<TaskAcceptance />
<TaskSubtasks />
<TaskArtifacts />
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskVerifyConfig.test.ts b/src/features/AgentTasks/AgentTaskDetail/TaskVerifyConfig.test.ts
new file mode 100644
index 00000000000..bdb2ce870b7
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskVerifyConfig.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from 'vitest';
+
+import { toTemplateCriterionDrafts } from './TaskVerifyConfig';
+
+describe('toTemplateCriterionDrafts', () => {
+ it('removes task-local identities when snapshotting criteria for a reusable rubric', () => {
+ expect(
+ toTemplateCriterionDrafts([
+ {
+ criterionId: 'task-criterion-1',
+ id: 'draft-1',
+ required: true,
+ title: ' Preserve the delivery contract ',
+ verifierType: 'llm',
+ },
+ ]),
+ ).toEqual([
+ {
+ required: true,
+ title: 'Preserve the delivery contract',
+ verifierType: 'llm',
+ },
+ ]);
+ });
+});
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskVerifyConfig.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskVerifyConfig.tsx
index febd4060d63..c396423354c 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskVerifyConfig.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskVerifyConfig.tsx
@@ -3,6 +3,7 @@
import {
ActionIcon,
Block,
+ Drawer,
type DropdownItem,
DropdownMenu,
Flexbox,
@@ -12,7 +13,7 @@ import {
Text,
TextArea,
} from '@lobehub/ui';
-import { Button, Select, Switch } from '@lobehub/ui/base-ui';
+import { Button, Checkbox, Select } from '@lobehub/ui/base-ui';
import { App } from 'antd';
import { createStaticStyles, cssVar } from 'antd-style';
import {
@@ -30,6 +31,7 @@ import { useTranslation } from 'react-i18next';
import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
import { openVerifyCriterionModal } from '@/features/AgentTasks/AgentTaskDetail/VerifyCriterionModal';
+import { VerifyCriterionEditor } from '@/features/AgentTasks/AgentTaskDetail/VerifyCriterionModal/VerifyCriterionForm';
import { useRubrics } from '@/features/Verify/hooks';
import { usePermission } from '@/hooks/usePermission';
import { type VerifyCriterionDraft, verifyService } from '@/services/verify';
@@ -38,7 +40,9 @@ import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';
import { useTaskStore } from '@/store/task';
import { taskDetailSelectors } from '@/store/task/selectors';
+import { PendingAcceptanceCheckList } from './PendingAcceptanceCheckList';
import { resolveTaskAcceptanceGoal } from './resolveTaskAcceptanceGoal';
+import { TaskAcceptanceHeader } from './TaskAcceptanceHeader';
const SAVE_DEBOUNCE_MS = 600;
@@ -53,15 +57,23 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
width: 100%;
`,
row: css`
- padding-block: 8px;
- padding-inline: 8px;
+ cursor: pointer;
+ padding-block: 10px;
+ padding-inline: 12px;
+
+ & + & {
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+ }
+
+ &:hover {
+ background: ${cssVar.colorFillQuaternary};
+ }
`,
rowTitle: css`
flex: 1;
`,
section: css`
- padding: 16px;
- border-radius: 12px;
+ padding-inline: 12px;
`,
subtitle: css`
color: ${cssVar.colorTextSecondary};
@@ -70,6 +82,8 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
/** Working item: a draft plus a stable client id, so reorder/edit is jitter-free. */
interface DraftItem extends VerifyCriterionDraft {
+ /** Persisted logical identity. Kept across edits so Acceptance can join later runs. */
+ criterionId?: string;
/** Stable client-side id for list keys + dnd; not the persisted criterion id. */
id: string;
}
@@ -77,10 +91,23 @@ interface DraftItem extends VerifyCriterionDraft {
let idSeq = 0;
const nextUid = () => `vc_${Date.now().toString(36)}_${(idSeq += 1)}`;
-const toDraftItem = (draft: VerifyCriterionDraft): DraftItem => ({ ...draft, id: nextUid() });
+const toDraftItem = (draft: VerifyCriterionDraft, criterionId?: string): DraftItem => ({
+ ...draft,
+ criterionId,
+ id: nextUid(),
+});
+
+/** Snapshot task-owned criteria into independent rows before mounting them on a reusable rubric. */
+export const toTemplateCriterionDrafts = (drafts: DraftItem[]): VerifyCriterionDraft[] =>
+ drafts
+ .filter((draft) => draft.title.trim().length > 0)
+ .map(({ criterionId: _criterionId, id: _id, ...draft }) => ({
+ ...draft,
+ title: draft.title.trim(),
+ }));
const TaskVerifyConfig = memo(() => {
- const { t } = useTranslation('chat');
+ const { t } = useTranslation(['chat', 'verify']);
const { message } = App.useApp();
const { allowed: canEditTask } = usePermission('create_content');
@@ -129,9 +156,11 @@ const TaskVerifyConfig = memo(() => {
// Configured view defaults to a read-only preview; structural editing (reorder,
// delete, add, requirement rewrite) is revealed only after clicking "Edit".
const [editing, setEditing] = useState(false);
+ const [selectedCriterionId, setSelectedCriterionId] = useState<string | null>(null);
// Hydrate the working list once per task from the persisted criterion ids.
const hydratedTaskRef = useRef<string | null>(null);
+ const criterionIdsRef = useRef(new Map<string, string>());
useEffect(() => {
if (!taskId) return;
if (hydratedTaskRef.current === taskId) return;
@@ -139,6 +168,7 @@ const TaskVerifyConfig = memo(() => {
setRequirement(verify?.requirement ?? '');
setEnabled(verify?.enabled !== false);
setShowTemplatePicker(false);
+ criterionIdsRef.current.clear();
const ids = verify?.verifyCriteriaIds ?? [];
if (ids.length === 0) {
@@ -155,24 +185,27 @@ const TaskVerifyConfig = memo(() => {
.map((id) => byId.get(id))
.filter((c): c is NonNullable<typeof c> => Boolean(c))
.map((c) =>
- toDraftItem({
- description: c.description ?? undefined,
- documentId: c.documentId,
- required: c.required,
- title: c.title,
- verifierConfig: c.verifierConfig ?? undefined,
- verifierType: c.verifierType,
- }),
+ toDraftItem(
+ {
+ description: c.description ?? undefined,
+ documentId: c.documentId,
+ required: c.required,
+ title: c.title,
+ verifierConfig: c.verifierConfig ?? undefined,
+ verifierType: c.verifierType,
+ },
+ c.id,
+ ),
);
+ criterionIdsRef.current = new Map(
+ ordered.flatMap((draft) => (draft.criterionId ? [[draft.id, draft.criterionId]] : [])),
+ );
setDrafts(ordered);
})
.finally(() => setHydrated(true));
}, [taskId, verify?.verifyCriteriaIds, verify?.requirement, verify?.enabled]);
// ---- debounced persistence ----
- // v1 simplification: every save re-creates fresh criterion rows (full replace).
- // We deliberately do NOT diff/dedupe against existing criteria — order of the
- // returned ids is the display order, which keeps drag-reorder trivially correct.
const saveTimerRef = useRef<ReturnType<typeof setTimeout>>(undefined);
// Latest not-yet-flushed payload; the debounce timer (or unmount flush) reads it.
const pendingRef = useRef<{
@@ -180,33 +213,94 @@ const TaskVerifyConfig = memo(() => {
enabled: boolean;
requirement: string;
} | null>(null);
+ const savingRef = useRef(false);
const doSave = useCallback(async () => {
- const payload = pendingRef.current;
- pendingRef.current = null;
- if (!taskId || !payload) return;
+ if (!taskId || savingRef.current) return;
+ savingRef.current = true;
try {
- const cleaned = payload.drafts.filter((d) => d.title.trim().length > 0);
- const requirement = payload.requirement.trim() || null;
- if (cleaned.length === 0) {
- // Removing all criteria clears the gate → back to the empty state.
+ while (pendingRef.current) {
+ const payload = pendingRef.current;
+ pendingRef.current = null;
+ const cleaned = payload.drafts
+ .filter((d) => d.title.trim().length > 0)
+ .map((draft) => ({
+ ...draft,
+ criterionId: criterionIdsRef.current.get(draft.id) ?? draft.criterionId,
+ }));
+ const requirement = payload.requirement.trim() || null;
+ if (cleaned.length === 0) {
+ await useTaskStore.getState().updateVerifyConfig(taskId, {
+ enabled: payload.enabled,
+ requirement,
+ verifyCriteriaIds: null,
+ });
+ continue;
+ }
+
+ const existing = cleaned.filter((draft): draft is DraftItem & { criterionId: string } =>
+ Boolean(draft.criterionId),
+ );
+ const localIds = await verifyService.forkRubricCriteria(
+ existing.map(({ criterionId }) => criterionId),
+ );
+ existing.forEach((draft, index) => {
+ draft.criterionId = localIds[index];
+ criterionIdsRef.current.set(draft.id, localIds[index]);
+ });
+ await Promise.all(
+ existing.map(
+ ({
+ criterionId,
+ description,
+ documentId,
+ required,
+ title,
+ verifierConfig,
+ verifierType,
+ }) =>
+ verifyService.updateCriterion(criterionId, {
+ description: description ?? null,
+ documentId: documentId ?? null,
+ required,
+ title: title.trim(),
+ verifierConfig,
+ verifierType,
+ }),
+ ),
+ );
+
+ const additions = cleaned.filter((draft) => !draft.criterionId);
+ const createdIds =
+ additions.length === 0
+ ? []
+ : await verifyService.createCriteria(
+ additions.map(({ criterionId: _criterionId, id: _id, ...draft }) => ({
+ ...draft,
+ title: draft.title.trim(),
+ })),
+ );
+ additions.forEach((draft, index) => {
+ draft.criterionId = createdIds[index];
+ criterionIdsRef.current.set(draft.id, createdIds[index]);
+ });
+ const ids = cleaned.map(({ criterionId }) => criterionId!);
await useTaskStore.getState().updateVerifyConfig(taskId, {
enabled: payload.enabled,
requirement,
- verifyCriteriaIds: null,
+ verifyCriteriaIds: ids,
});
- return;
+ setDrafts((current) =>
+ current.map((draft) => ({
+ ...draft,
+ criterionId: criterionIdsRef.current.get(draft.id) ?? draft.criterionId,
+ })),
+ );
}
- const ids = await verifyService.createCriteria(
- cleaned.map(({ id: _id, ...draft }) => ({ ...draft, title: draft.title.trim() })),
- );
- await useTaskStore.getState().updateVerifyConfig(taskId, {
- enabled: payload.enabled,
- requirement,
- verifyCriteriaIds: ids,
- });
} catch (e) {
console.error('[TaskVerifyConfig] Failed to save:', e);
+ } finally {
+ savingRef.current = false;
}
}, [taskId]);
@@ -303,17 +397,11 @@ const TaskVerifyConfig = memo(() => {
});
}, [drafts, commit]);
- // Open the per-criterion detail editor; title/notes/verifier/required all live here.
- const openCriterionDetail = useCallback(
- (item: DraftItem) => {
- openVerifyCriterionModal({
- initial: item,
- onDelete: () => handleRemove(item.id),
- onSubmit: (next) => commit(drafts.map((d) => (d.id === item.id ? { ...d, ...next } : d))),
- });
- },
- [drafts, commit, handleRemove],
- );
+ // Open the per-criterion detail editor in the same right-side reading position
+ // used by a completed Acceptance check.
+ const openCriterionDetail = useCallback((item: DraftItem) => {
+ setSelectedCriterionId(item.id);
+ }, []);
const handlePickTemplate = useCallback(
async (rubricId: string) => {
@@ -361,16 +449,22 @@ const TaskVerifyConfig = memo(() => {
if (persistedIds.length === 0) return;
try {
const title = (requirement.trim() || t('verifyConfig.empty.title')).slice(0, 60);
+ // A rubric is a reusable snapshot, not another owner of the task's mutable
+ // criterion rows. Clone the current definitions so later task edits cannot
+ // silently rewrite this template or another task instantiated from it.
+ const templateCriterionIds = await verifyService.createCriteria(
+ toTemplateCriterionDrafts(drafts),
+ );
const rubric = await verifyService.createRubric({ title });
await verifyService.setRubricCriteria(
rubric.id,
- persistedIds.map((criterionId) => ({ criterionId })),
+ templateCriterionIds.map((criterionId) => ({ criterionId })),
);
message.success(t('verifyConfig.saveAsTemplateSuccess'));
} catch (e) {
console.error('[TaskVerifyConfig] save as template failed:', e);
}
- }, [verify?.verifyCriteriaIds, requirement, t, message]);
+ }, [drafts, verify?.verifyCriteriaIds, requirement, t, message]);
const rubricOptions = useMemo(
() => (rubrics ?? []).map((r) => ({ label: r.title, value: r.id })),
@@ -543,20 +637,22 @@ const TaskVerifyConfig = memo(() => {
);
return (
- <Block className={styles.section} variant={'outlined'}>
+ <Flexbox className={styles.section}>
<Flexbox gap={12}>
- {/* header: title + enable + edit toggle */}
+ {/* Definition and result modes share one title contract. Mode-specific
+ controls stay on the right without changing the information hierarchy. */}
<Flexbox horizontal align={'center'} justify={'space-between'}>
- <Flexbox horizontal align={'center'} gap={8}>
- <Icon icon={ShieldCheck} size={18} />
- <Text weight={600}>{t('verifyConfig.empty.title')}</Text>
- </Flexbox>
+ <TaskAcceptanceHeader isOpen count={drafts.length} onToggle={() => setExpanded(false)} />
<Flexbox horizontal align={'center'} gap={4}>
- <Switch checked={enabled} onChange={handleToggleEnabled} />
+ <Checkbox
+ aria-label={t('verifyConfig.enable')}
+ checked={enabled}
+ size={16}
+ onChange={handleToggleEnabled}
+ />
<Button size={'small'} type={'text'} onClick={() => setEditing((v) => !v)}>
{editing ? t('verifyConfig.done') : t('verifyConfig.edit')}
</Button>
- <ActionIcon icon={ChevronUp} size={'small'} onClick={() => setExpanded(false)} />
</Flexbox>
</Flexbox>
@@ -564,7 +660,7 @@ const TaskVerifyConfig = memo(() => {
<Flexbox gap={6}>
<Flexbox horizontal align={'center'} justify={'space-between'}>
<Text className={styles.subtitle} fontSize={12}>
- {t('verifyConfig.requirementLabel')}
+ {t('taskDetail.acceptance.goal')}
</Text>
{editing ? (
<Button
@@ -593,7 +689,8 @@ const TaskVerifyConfig = memo(() => {
)}
</Flexbox>
- {/* criteria list: static rows in preview, drag-reorderable rows in edit mode */}
+ {/* Editing keeps ordering controls, while the normal reading state mirrors
+ the canonical Acceptance grouped check list. */}
{editing ? (
<SortableList
className={styles.list}
@@ -624,23 +721,17 @@ const TaskVerifyConfig = memo(() => {
onChange={handleSortEnd}
/>
) : (
- <Flexbox gap={4}>
- {drafts.map((item) => (
- <Block
- clickable
- horizontal
- align={'center'}
- className={styles.row}
- gap={8}
- key={item.id}
- variant={'filled'}
- onClick={() => openCriterionDetail(item)}
- >
- {renderCriterionMeta(item)}
- <Icon className={styles.subtitle} icon={ChevronRight} size={16} />
- </Block>
- ))}
- </Flexbox>
+ <PendingAcceptanceCheckList
+ groupLabel={t('acceptance.group.uncategorized', { ns: 'verify' })}
+ items={drafts.map((item) => ({
+ id: item.id,
+ title: item.title || t('verifyConfig.criterionTitlePlaceholder'),
+ }))}
+ onOpen={(selected) => {
+ const item = drafts.find((draft) => draft.id === selected.id);
+ if (item) openCriterionDetail(item);
+ }}
+ />
)}
{/* footer actions: only meaningful in edit mode */}
@@ -660,7 +751,32 @@ const TaskVerifyConfig = memo(() => {
</Flexbox>
) : null}
</Flexbox>
- </Block>
+ <Drawer
+ destroyOnHidden
+ open={Boolean(selectedCriterionId)}
+ placement={'right'}
+ styles={{ body: { padding: 0 } }}
+ title={t('verifyConfig.detail.title')}
+ width={'min(92vw, 440px)'}
+ onClose={() => setSelectedCriterionId(null)}
+ >
+ {drafts
+ .filter((item) => item.id === selectedCriterionId)
+ .map((item) => (
+ <VerifyCriterionEditor
+ initial={item}
+ key={item.id}
+ onClose={() => setSelectedCriterionId(null)}
+ onDelete={() => handleRemove(item.id)}
+ onSubmit={(next) =>
+ commit(
+ drafts.map((draft) => (draft.id === item.id ? { ...draft, ...next } : draft)),
+ )
+ }
+ />
+ ))}
+ </Drawer>
+ </Flexbox>
);
});
diff --git a/src/features/AgentTasks/AgentTaskDetail/VerifyCriterionModal/VerifyCriterionForm.tsx b/src/features/AgentTasks/AgentTaskDetail/VerifyCriterionModal/VerifyCriterionForm.tsx
index 9d56c7a062a..e1236d128bc 100644
--- a/src/features/AgentTasks/AgentTaskDetail/VerifyCriterionModal/VerifyCriterionForm.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/VerifyCriterionModal/VerifyCriterionForm.tsx
@@ -8,17 +8,22 @@ import { useTranslation } from 'react-i18next';
import type { VerifyCriterionDraft } from '@/services/verify';
-interface VerifyCriterionFormProps {
+interface VerifyCriterionEditorProps {
initial: VerifyCriterionDraft;
+ onClose: () => void;
/** Omitted when the criterion is brand-new and not yet committed. */
onDelete?: () => void;
onSubmit: (next: VerifyCriterionDraft) => void;
}
-/** Per-criterion editor body: the only place title/notes/verifier/required are edited. */
-const VerifyCriterionForm = ({ initial, onDelete, onSubmit }: VerifyCriterionFormProps) => {
+/** Shared editor body for modal and right-side drawer criterion details. */
+export const VerifyCriterionEditor = ({
+ initial,
+ onClose,
+ onDelete,
+ onSubmit,
+}: VerifyCriterionEditorProps) => {
const { t } = useTranslation('chat');
- const { close } = useModalContext();
const [title, setTitle] = useState(initial.title ?? '');
const [description, setDescription] = useState(initial.description ?? '');
@@ -44,7 +49,7 @@ const VerifyCriterionForm = ({ initial, onDelete, onSubmit }: VerifyCriterionFor
title: trimmed,
verifierType,
});
- close();
+ onClose();
};
return (
@@ -104,7 +109,7 @@ const VerifyCriterionForm = ({ initial, onDelete, onSubmit }: VerifyCriterionFor
type={'text'}
onClick={() => {
onDelete();
- close();
+ onClose();
}}
>
{t('verifyConfig.removeCriterion')}
@@ -113,7 +118,7 @@ const VerifyCriterionForm = ({ initial, onDelete, onSubmit }: VerifyCriterionFor
<span />
)}
<Flexbox horizontal gap={8}>
- <Button onClick={close}>{t('verifyConfig.cancel')}</Button>
+ <Button onClick={onClose}>{t('verifyConfig.cancel')}</Button>
<Button disabled={!title.trim()} type={'primary'} onClick={handleSave}>
{t('verifyConfig.save')}
</Button>
@@ -123,4 +128,13 @@ const VerifyCriterionForm = ({ initial, onDelete, onSubmit }: VerifyCriterionFor
);
};
+interface VerifyCriterionFormProps extends Omit<VerifyCriterionEditorProps, 'onClose'> {}
+
+/** Modal adapter retained for the manual-add flow. */
+const VerifyCriterionForm = (props: VerifyCriterionFormProps) => {
+ const { close } = useModalContext();
+
+ return <VerifyCriterionEditor {...props} onClose={close} />;
+};
+
export default VerifyCriterionForm;
diff --git a/src/features/AgentTasks/AgentTaskDetail/resolveTaskAcceptanceProjection.test.ts b/src/features/AgentTasks/AgentTaskDetail/resolveTaskAcceptanceProjection.test.ts
new file mode 100644
index 00000000000..01a4795144d
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskDetail/resolveTaskAcceptanceProjection.test.ts
@@ -0,0 +1,12 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveTaskAcceptanceRequirement } from './resolveTaskAcceptanceProjection';
+
+describe('resolveTaskAcceptanceProjection', () => {
+ it('uses the Task-configured requirement before the aggregate snapshot', () => {
+ expect(
+ resolveTaskAcceptanceRequirement(' Current task goal ', 'Historical aggregate goal'),
+ ).toBe('Current task goal');
+ expect(resolveTaskAcceptanceRequirement(' ', ' Aggregate goal ')).toBe('Aggregate goal');
+ });
+});
diff --git a/src/features/AgentTasks/AgentTaskDetail/resolveTaskAcceptanceProjection.ts b/src/features/AgentTasks/AgentTaskDetail/resolveTaskAcceptanceProjection.ts
new file mode 100644
index 00000000000..86108adf5cf
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskDetail/resolveTaskAcceptanceProjection.ts
@@ -0,0 +1,5 @@
+/** Task configuration is the source used to instantiate the next Acceptance round. */
+export const resolveTaskAcceptanceRequirement = (
+ configuredRequirement: string | null | undefined,
+ aggregateRequirement: string | null | undefined,
+) => configuredRequirement?.trim() || aggregateRequirement?.trim() || '';
diff --git a/src/features/Portal/AcceptanceCheck/Body.test.tsx b/src/features/Portal/AcceptanceCheck/Body.test.tsx
index 4f450f4dd75..7b9f7ae7804 100644
--- a/src/features/Portal/AcceptanceCheck/Body.test.tsx
+++ b/src/features/Portal/AcceptanceCheck/Body.test.tsx
@@ -13,10 +13,12 @@ vi.mock('@lobehub/ui', () => ({
Center: ({ children }: { children: ReactNode }) => <div>{children}</div>,
Empty: () => <div />,
Flexbox: ({ children, className }: { children: ReactNode; className?: string }) => (
- <div className={className} data-testid={'detail-surface'}>
+ <div className={className} data-testid={className ? 'detail-surface' : undefined}>
{children}
</div>
),
+ Icon: () => <span data-testid={'check-state-icon'} />,
+ Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,
}));
vi.mock('@lobehub/ui/base-ui', () => ({
@@ -51,11 +53,12 @@ vi.mock('@/store/chat/selectors', () => ({
}));
vi.mock('@/features/Verify', () => ({
+ checkHeadMeta: () => ({ color: 'green', icon: () => null }),
FocusedCheckDetails: () => <div data-testid={'check-details'} />,
useAcceptanceBundle: () => ({
data: {
acceptance: { id: 'acc-1' },
- checks: [{ id: 'check-1' }],
+ checks: [{ id: 'check-1', seq: 3, title: 'The result keeps its title' }],
isOwner: true,
},
error: mocks.bundleError,
@@ -80,6 +83,13 @@ describe('AcceptanceCheck Portal Body', () => {
expect(surface.querySelector('[class*="block"]')).toBeNull();
});
+ it('keeps the selected check identity visible above its details', () => {
+ render(<Body />);
+
+ expect(screen.getByText('C3 · The result keeps its title')).toBeInTheDocument();
+ expect(screen.getByTestId('check-state-icon')).toBeInTheDocument();
+ });
+
it('offers an in-place retry when loading the selected check fails', () => {
mocks.bundleError = new Error('network failed');
diff --git a/src/features/Portal/AcceptanceCheck/Body.tsx b/src/features/Portal/AcceptanceCheck/Body.tsx
index 61d1884e9b9..c48d11cf19b 100644
--- a/src/features/Portal/AcceptanceCheck/Body.tsx
+++ b/src/features/Portal/AcceptanceCheck/Body.tsx
@@ -1,6 +1,6 @@
'use client';
-import { Center, Empty, Flexbox } from '@lobehub/ui';
+import { Center, Empty, Flexbox, Icon, Text } from '@lobehub/ui';
import { Button } from '@lobehub/ui/base-ui';
import { App } from 'antd';
import { createStaticStyles } from 'antd-style';
@@ -8,7 +8,12 @@ import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
-import { type CheckReviewInput, FocusedCheckDetails, useAcceptanceBundle } from '@/features/Verify';
+import {
+ checkHeadMeta,
+ type CheckReviewInput,
+ FocusedCheckDetails,
+ useAcceptanceBundle,
+} from '@/features/Verify';
import { verifyService } from '@/services/verify';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
@@ -67,8 +72,16 @@ const Body = memo(() => {
);
}
+ const checkMeta = checkHeadMeta(check);
+
return (
- <Flexbox className={styles.body}>
+ <Flexbox className={styles.body} gap={16}>
+ <Flexbox horizontal align={'center'} gap={10}>
+ <Icon color={checkMeta.color} icon={checkMeta.icon} size={18} style={{ flex: 'none' }} />
+ <Text fontSize={16} weight={600}>
+ C{check.seq} · {check.title}
+ </Text>
+ </Flexbox>
<FocusedCheckDetails
canReview={data.isOwner}
check={check}
diff --git a/src/features/Portal/Mobile.tsx b/src/features/Portal/Mobile.tsx
index 2fb54cbee19..d4e8af89069 100644
--- a/src/features/Portal/Mobile.tsx
+++ b/src/features/Portal/Mobile.tsx
@@ -15,12 +15,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
container: css`
background: linear-gradient(${cssVar.colorBgElevated}, ${cssVar.colorBgContainer}) !important;
`,
- modal: css`
- & > div {
- height: 95dvh;
- max-height: 95dvh;
- }
- `,
}));
const MobilePortal = () => {
@@ -47,7 +41,7 @@ const MobilePortal = () => {
<ImperativeModal
allowFullscreen
destroyOnHidden
- className={cx(styles.modal, isPortalThread && styles.container)}
+ className={cx(isPortalThread && styles.container)}
footer={null}
height={'95%'}
open={showMobilePortal}
diff --git a/src/features/Verify/Acceptance/CheckList.tsx b/src/features/Verify/Acceptance/CheckList.tsx
index 789c32203b9..36e4fb7fa84 100644
--- a/src/features/Verify/Acceptance/CheckList.tsx
+++ b/src/features/Verify/Acceptance/CheckList.tsx
@@ -10,6 +10,7 @@ import {
Image,
Tag,
Text,
+ TextArea,
Tooltip,
} from '@lobehub/ui';
import { Button } from '@lobehub/ui/base-ui';
@@ -770,6 +771,8 @@ const CheckRow = memo<{
const [seqCopied, setSeqCopied] = useState(false);
const [accepting, setAccepting] = useState(false);
const [ignoring, setIgnoring] = useState(false);
+ const [rejecting, setRejecting] = useState(false);
+ const [reviewComment, setReviewComment] = useState('');
const meta = STATE_META[check.state];
const counts = evidenceCounts(check.evidence);
const visualization = readVisualizationManifest(check.result?.metadata);
@@ -808,11 +811,27 @@ const CheckRow = memo<{
const handleAccept = async (event: { stopPropagation: () => void }) => {
event.stopPropagation();
setAccepting(true);
- const ok = await onReview({ action: 'accept', checkItemIds: [check.id] });
+ const comment = reviewComment.trim();
+ const ok = await onReview({
+ action: 'accept',
+ checkItemIds: [check.id],
+ comment: comment || undefined,
+ });
setAccepting(false);
+ if (ok) setReviewComment('');
if (ok && expanded) onToggle();
};
+ const handleReject = async (event: { stopPropagation: () => void }) => {
+ event.stopPropagation();
+ const comment = reviewComment.trim();
+ if (!comment) return;
+ setRejecting(true);
+ const ok = await onReview({ action: 'reject', checkItemIds: [check.id], comment });
+ setRejecting(false);
+ if (ok) setReviewComment('');
+ };
+
const handleIgnore = async (event: { stopPropagation: () => void }) => {
event.stopPropagation();
setIgnoring(true);
@@ -1167,40 +1186,75 @@ const CheckRow = memo<{
{/* Confirm (plain filled) anchors the right edge; reject is the
quiet text escape next to it. */}
- {reviewable && !activeReview && (
- <Flexbox horizontal gap={4} justify={'flex-end'}>
- <Button
- disabled={reviewPending && !ignoring}
- loading={ignoring}
- size={'small'}
- type={'text'}
- onClick={handleIgnore}
- >
- {t('acceptance.review.ignore')}
- </Button>
- <Button
- disabled={reviewPending}
- size={'small'}
- type={'text'}
- onClick={(event) => {
- event.stopPropagation();
- openReject();
- }}
- >
- {t('acceptance.review.reject')}
- </Button>
- <Button
- disabled={reviewPending && !accepting}
- icon={<Icon icon={Check} />}
- loading={accepting}
- size={'small'}
- type={'fill'}
- onClick={handleAccept}
- >
- {t('acceptance.review.accept')}
- </Button>
- </Flexbox>
- )}
+ {reviewable &&
+ !activeReview &&
+ (detailMode ? (
+ <Flexbox gap={10} style={{ marginBlockStart: 6 }}>
+ <TextArea
+ autoSize={{ maxRows: 8, minRows: 3 }}
+ placeholder={t('acceptance.review.detailPlaceholder')}
+ value={reviewComment}
+ onChange={(event) => setReviewComment(event.target.value)}
+ />
+ <Flexbox horizontal gap={8}>
+ <Button
+ block
+ disabled={reviewPending || !reviewComment.trim()}
+ loading={rejecting}
+ size={'large'}
+ style={{ flex: 1 }}
+ onClick={handleReject}
+ >
+ {t('acceptance.review.reject')}
+ </Button>
+ <Button
+ block
+ disabled={reviewPending && !accepting}
+ icon={<Icon icon={Check} />}
+ loading={accepting}
+ size={'large'}
+ style={{ flex: 1 }}
+ type={'fill'}
+ onClick={handleAccept}
+ >
+ {t('acceptance.review.accept')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ ) : (
+ <Flexbox horizontal gap={4} justify={'flex-end'}>
+ <Button
+ disabled={reviewPending && !ignoring}
+ loading={ignoring}
+ size={'small'}
+ type={'text'}
+ onClick={handleIgnore}
+ >
+ {t('acceptance.review.ignore')}
+ </Button>
+ <Button
+ disabled={reviewPending}
+ size={'small'}
+ type={'text'}
+ onClick={(event) => {
+ event.stopPropagation();
+ openReject();
+ }}
+ >
+ {t('acceptance.review.reject')}
+ </Button>
+ <Button
+ disabled={reviewPending && !accepting}
+ icon={<Icon icon={Check} />}
+ loading={accepting}
+ size={'small'}
+ type={'fill'}
+ onClick={handleAccept}
+ >
+ {t('acceptance.review.accept')}
+ </Button>
+ </Flexbox>
+ ))}
{hasHistory && (
<span className={styles.historyToggle} onClick={() => setHistoryOpen((open) => !open)}>
diff --git a/src/features/Verify/hooks.test.ts b/src/features/Verify/hooks.test.ts
index 91aa33a26d0..4cecfdbf147 100644
--- a/src/features/Verify/hooks.test.ts
+++ b/src/features/Verify/hooks.test.ts
@@ -8,6 +8,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { verifyService } from '@/services/verify';
import {
+ getAcceptanceBySubjectRefreshInterval,
useAcceptanceBySubject,
useRubrics,
useVerifyReportBundle,
@@ -71,6 +72,12 @@ describe('Verify data hooks', () => {
expect(getAcceptanceBySubject).toHaveBeenCalledWith('task', 'T-231');
});
+ it('polls while a task has no acceptance and stops after one is created', () => {
+ expect(getAcceptanceBySubjectRefreshInterval(undefined)).toBe(2000);
+ expect(getAcceptanceBySubjectRefreshInterval(null)).toBe(2000);
+ expect(getAcceptanceBySubjectRefreshInterval({ id: 'acceptance-1' })).toBe(0);
+ });
+
it('does not request rubrics while rubric authoring is inactive', async () => {
const listRubrics = vi.spyOn(verifyService, 'listRubrics').mockResolvedValue([]);
diff --git a/src/features/Verify/hooks.ts b/src/features/Verify/hooks.ts
index 40015ce1071..623439b62b4 100644
--- a/src/features/Verify/hooks.ts
+++ b/src/features/Verify/hooks.ts
@@ -25,6 +25,9 @@ const ACCEPTANCE_BUNDLE_SWR_CONFIG = {
revalidateOnReconnect: true,
} as const;
+export const getAcceptanceBySubjectRefreshInterval = (acceptance: unknown) =>
+ acceptance ? 0 : 2000;
+
/** Plan + rollup status for one Agent Run. Pass null operationId to skip. */
export const useVerifyState = (operationId: string | null) =>
useClientDataSWR(operationId ? verifyKeys.state(operationId) : null, () =>
@@ -61,7 +64,13 @@ export const useAcceptanceBySubject = (
useClientDataSWR(
subjectId ? verifyKeys.acceptanceBySubject(subjectType, subjectId) : null,
() => verifyService.getAcceptanceBySubject(subjectType, subjectId!),
- ACCEPTANCE_BUNDLE_SWR_CONFIG,
+ {
+ ...ACCEPTANCE_BUNDLE_SWR_CONFIG,
+ // A task can mount before its first Verify Run creates the aggregate.
+ // Discover that server-side transition without requiring focus/reload,
+ // then stop polling as soon as the Acceptance exists.
+ refreshInterval: getAcceptanceBySubjectRefreshInterval,
+ },
);
/** The caller's recent acceptance aggregates (with subject headers) — the list panel. */
diff --git a/src/services/verify.ts b/src/services/verify.ts
index 098f8cc6c1a..cd356971009 100644
--- a/src/services/verify.ts
+++ b/src/services/verify.ts
@@ -317,6 +317,10 @@ export class VerifyService {
createCriterion = (input: CreateCriterionInput): Promise<VerifyCriterionItem> =>
lambdaClient.verify.createCriterion.mutate(input) as Promise<VerifyCriterionItem>;
+ /** Copy legacy rubric-backed criteria before a task edits them. */
+ forkRubricCriteria = (ids: string[]): Promise<string[]> =>
+ lambdaClient.verify.forkRubricCriteria.mutate({ ids }) as Promise<string[]>;
+
updateCriterion = (id: string, value: UpdateCriterionValue): Promise<unknown> =>
lambdaClient.verify.updateCriterion.mutate({ id, value });
diff --git a/src/store/task/selectors/detailSelectors.ts b/src/store/task/selectors/detailSelectors.ts
index d3d7d30b46a..a527ff18a98 100644
--- a/src/store/task/selectors/detailSelectors.ts
+++ b/src/store/task/selectors/detailSelectors.ts
@@ -9,6 +9,8 @@ const activeTaskId = (s: TaskStoreState) => s.activeTaskId;
const activeTaskDetail = (s: TaskStoreState): TaskDetailData | undefined =>
s.activeTaskId ? s.taskDetailMap[s.activeTaskId] : undefined;
+const activeTaskDatabaseId = (s: TaskStoreState) => activeTaskDetail(s)?.id;
+
const taskDetailById = (id: string) => (s: TaskStoreState) => s.taskDetailMap[id];
const isTaskDetailLoading = (s: TaskStoreState): boolean =>
@@ -125,6 +127,7 @@ export const taskDetailSelectors = {
activeTaskAutomationMode,
activeTaskCheckpoint,
activeTaskCreatedByUserId,
+ activeTaskDatabaseId,
activeTaskModel,
activeTaskDependencies,
activeTaskDescription,