Skip to content

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

✨ feat(goal): add the /goal loop end to end (#18005)

Arvin Xue8349e8ce271
diff --git a/apps/server/src/routers/lambda/acceptance.ts b/apps/server/src/routers/lambda/acceptance.ts
index 12cdabccc9f..5eb4798feb3 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 { AgentOperationModel } from '@/database/models/agentOperation';
import { TaskModel } from '@/database/models/task';
import { VerifyRunModel } from '@/database/models/verifyRun';
import { WorkspaceMemberModel } from '@/database/models/workspaceMember';
@@ -147,7 +148,19 @@ export const acceptanceRouter = router({
input.subjectType,
input.subjectId,
);
- return acceptance ?? null;
+ if (!acceptance) return null;
+
+ // `delivered` alone is ambiguous for the subject's status surface: a
+ // converged delivery waiting for sign-off and a failed one waiting for a
+ // decision both land there. The latest round's verdict is what tells
+ // them apart, so ship it with the aggregate instead of forcing callers
+ // to load the whole bundle for one field.
+ const latest = await ctx.acceptanceService.latestRound(acceptance.id);
+ return {
+ ...acceptance,
+ latestRunStatus: latest?.status ?? null,
+ latestRunUserDecision: latest?.userDecision ?? null,
+ };
}),
/**
@@ -340,6 +353,18 @@ export const acceptanceRouter = router({
};
const reportsByRun = new Map(reports.map((r) => [r.verifyRunId!, r]));
+ // What each round actually spent. Owner-only: cost is the author's
+ // operating detail, not something a shared link should expose.
+ // `isOwner` already implies a signed-in viewer; the explicit id check is
+ // what narrows it for the model, which is owner-scoped by construction.
+ const usageByOperation =
+ isOwner && ctx.userId
+ ? await new AgentOperationModel(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined)
+ .findUsageByOperations(
+ runs.flatMap((run) => (run.operationId ? [run.operationId] : [])),
+ )
+ .catch(() => new Map<string, { cost: number; tokens: number }>())
+ : new Map<string, { cost: number; tokens: number }>();
const rounds = runs.map((run) => {
// `origin` points at the author's private topic/agent — never hand it
// to a visitor holding nothing but the shared link.
@@ -362,7 +387,11 @@ export const acceptanceRouter = router({
},
};
}
- return { report: reportsByRun.get(run.id) ?? null, run: publicRun };
+ return {
+ report: reportsByRun.get(run.id) ?? null,
+ run: publicRun,
+ usage: (run.operationId ? usageByOperation.get(run.operationId) : undefined) ?? null,
+ };
});
const latestReport = [...rounds].reverse().find((r) => r.report)?.report ?? null;
diff --git a/apps/server/src/services/task/index.ts b/apps/server/src/services/task/index.ts
index 919d1f33dbc..33d9a5fe151 100644
--- a/apps/server/src/services/task/index.ts
+++ b/apps/server/src/services/task/index.ts
@@ -20,6 +20,7 @@ import { TaskModel } from '@/database/models/task';
import { TaskTopicModel } from '@/database/models/taskTopic';
import { TopicModel } from '@/database/models/topic';
import { UserModel } from '@/database/models/user';
+import { VerifyRunModel } from '@/database/models/verifyRun';
import type { LobeChatDatabase } from '@/database/type';
import { AiAgentService } from '../aiAgent';
@@ -777,6 +778,13 @@ export class TaskService {
const authorMap = await this.resolveAuthors(agentIds, userIds);
+ // Every run row answers "and did it pass?" on its own (with counts). Without this the
+ // activity feed lists rounds that all look alike, and the only way to learn
+ // a round's verdict is to leave for the acceptance page.
+ const verifyByOperation = await new VerifyRunModel(this.db, this.userId, this.workspaceId)
+ .findByOperations(topics.map((t) => t.operationId).filter((id): id is string => Boolean(id)))
+ .catch(() => new Map());
+
const creatorId = task.createdByAgentId ?? task.createdByUserId;
const createdActivity: TaskDetailActivity | null =
task.createdAt && creatorId
@@ -792,6 +800,7 @@ export class TaskService {
...topics.map((t) => {
const handoff = t.handoff as TaskTopicHandoff | null;
const topicAgentId = t.agentId ?? t.sourceTaskAssigneeAgentId ?? task.assigneeAgentId;
+ const verifyRun = t.operationId ? verifyByOperation.get(t.operationId) : undefined;
return {
author: topicAgentId ? authorMap.get(topicAgentId) : undefined,
completedAt: toISO(t.completedAt),
@@ -809,6 +818,20 @@ export class TaskService {
sourceTaskName: t.sourceTaskName,
time: toISO(t.createdAt),
title: handoff?.title || t.title || UNTITLED_TOPIC_TITLE,
+ // What opened this round. Without it the feed cannot distinguish a run
+ // the user started from one the goal loop / scheduler opened on its
+ // own — they render identically apart from `#seq`.
+ trigger: t.trigger ?? null,
+ verify: verifyRun
+ ? {
+ acceptanceId: verifyRun.acceptanceId,
+ passed: verifyRun.passed,
+ roundIndex: verifyRun.roundIndex,
+ runId: verifyRun.id,
+ status: verifyRun.status,
+ total: verifyRun.total,
+ }
+ : null,
type: 'topic' as const,
};
}),
diff --git a/apps/server/src/services/taskLifecycle/index.ts b/apps/server/src/services/taskLifecycle/index.ts
index 12d1b66665a..e6ae23b6b5f 100644
--- a/apps/server/src/services/taskLifecycle/index.ts
+++ b/apps/server/src/services/taskLifecycle/index.ts
@@ -193,7 +193,20 @@ export class TaskLifecycleService {
// 4. Synthesize a programmatic brief for the user (auto mode only).
// The agent-driven `createBrief` tool path stays the default until
// the GrowthBook flag flips. See for the rollout plan.
- if (getBriefMode(currentTask) === 'auto' && currentTask && topicId && lastAssistantContent) {
+ //
+ // Goal-loop rounds are deliberately silent. The outer loop can run many
+ // rounds before it converges, and a card per round buries the one moment
+ // that actually needs the user. The settle path owns those moments:
+ // `driveTaskFromVerify` raises "delivery ready for sign-off" when the
+ // loop succeeds and the budget-exhausted alert when it stops.
+ const isGoalLoopRound = !!currentTask && !!this.taskModel.getGoalConfig(currentTask);
+ if (
+ !isGoalLoopRound &&
+ getBriefMode(currentTask) === 'auto' &&
+ currentTask &&
+ topicId &&
+ lastAssistantContent
+ ) {
await this.synthesizeTopicBrief(
taskId,
taskIdentifier,
diff --git a/apps/server/src/services/taskRunner/buildTaskPrompt.ts b/apps/server/src/services/taskRunner/buildTaskPrompt.ts
index 18e31abb37c..fa4f6ba7f73 100644
--- a/apps/server/src/services/taskRunner/buildTaskPrompt.ts
+++ b/apps/server/src/services/taskRunner/buildTaskPrompt.ts
@@ -1,14 +1,81 @@
-import { buildTaskRunPrompt } from '@lobechat/prompts';
+import { buildTaskRunPrompt, type TaskRunPromptGoalLoop } from '@lobechat/prompts';
import type { TaskItem, TaskTopicHandoff, WorkspaceData } from '@lobechat/types';
+import { AcceptanceModel } from '@/database/models/acceptance';
import type { BriefModel } from '@/database/models/brief';
import type { TaskModel } from '@/database/models/task';
import type { TaskTopicModel } from '@/database/models/taskTopic';
+import { VerifyCheckResultModel } from '@/database/models/verifyCheckResult';
import { VerifyCriterionModel } from '@/database/models/verifyCriterion';
import { VerifyRubricModel } from '@/database/models/verifyRubric';
+import { VerifyRunModel } from '@/database/models/verifyRun';
import type { LobeChatDatabase } from '@/database/type';
import { extractFileIdsFromEditorData } from '@/server/services/file/extractFileIdsFromEditorData';
import { resolveAttachmentMetadata } from '@/server/services/file/resolveAttachments';
+import { resolveGoalRoundBudget } from '@/server/services/verify/goalBudget';
+
+/** Cap on unresolved checks carried into the next round's prompt. */
+const MAX_GOAL_FAILED_CHECKS = 8;
+
+/**
+ * For a goal task that already ran at least one round, collect what the next
+ * round must know: the previous round's unresolved checks (with the verifier's
+ * why/suggestion) and the user's reject comment, both read off the task's
+ * acceptance aggregate. Best-effort — any lookup failure degrades to the bare
+ * round counters so prompt building never blocks a run.
+ */
+const resolveGoalLoopContext = async (
+ task: TaskItem,
+ deps: BuildTaskPromptDeps,
+): Promise<TaskRunPromptGoalLoop | undefined> => {
+ const { db, taskModel, userId, workspaceId } = deps;
+ const goal = taskModel.getGoalConfig(task);
+ if (!goal || !task.totalTopics) return undefined;
+
+ const budget = resolveGoalRoundBudget(goal);
+ const context: TaskRunPromptGoalLoop = {
+ maxRounds: Number.isFinite(budget) ? budget : null,
+ round: (task.totalTopics || 0) + 1,
+ };
+
+ try {
+ const acceptance = await new AcceptanceModel(db, userId, workspaceId).findBySubject(
+ 'task',
+ task.id,
+ );
+ if (!acceptance) return context;
+
+ const runs = await new VerifyRunModel(db, userId, workspaceId).listByAcceptance(acceptance.id);
+ const last = runs.at(-1);
+ if (!last) return context;
+
+ if (last.userDecision === 'reject') {
+ const comment = (last.decisionDetail as { comment?: string } | null)?.comment;
+ if (comment) context.rejectComment = comment;
+ }
+
+ const plan = (last.plan ?? []) as Array<{ id: string; title: string }>;
+ const results = await new VerifyCheckResultModel(db, userId, workspaceId).listByRun(last.id);
+ const byItem = new Map(results.map((r) => [r.checkItemId, r]));
+ const failed = plan
+ .filter((item) => {
+ const r = byItem.get(item.id);
+ return (
+ !!r &&
+ r.status !== 'errored' &&
+ (r.status === 'failed' || r.verdict === 'failed' || r.verdict === 'uncertain')
+ );
+ })
+ .map((item) => {
+ const r = byItem.get(item.id);
+ return { title: item.title, why: r?.suggestion || r?.toulmin?.reasoning || undefined };
+ });
+ if (failed.length > 0) context.failedChecks = failed.slice(0, MAX_GOAL_FAILED_CHECKS);
+ return context;
+ } catch {
+ return context;
+ }
+};
export interface BuildTaskPromptDeps {
briefModel: BriefModel;
@@ -194,7 +261,10 @@ export async function buildTaskPrompt(
});
}
+ const goalLoop = await resolveGoalLoopContext(task, deps);
+
const prompt = buildTaskRunPrompt({
+ ...(goalLoop ? { goalLoop } : {}),
activities: {
briefs: briefs.map((b: any) => ({
createdAt: b.createdAt,
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts
index 73f44daaa76..6e769ea5f41 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/task.test.ts
@@ -3,6 +3,8 @@ import { describe, expect, it, vi } from 'vitest';
import { createTaskRuntime } from '../task';
+const verifyMocks = vi.hoisted(() => ({ createCriteriaFromDrafts: vi.fn() }));
+
vi.mock('@/server/routers/lambda/task', () => ({
taskRouter: { createCaller: () => ({}) },
}));
@@ -21,7 +23,114 @@ vi.mock('@/server/services/task', () => ({
TaskService: vi.fn(),
}));
+vi.mock('@/server/services/verify/planGenerator', () => ({
+ VerifyPlanGeneratorService: vi.fn().mockImplementation(() => verifyMocks),
+}));
+
describe('createTaskRuntime', () => {
+ describe('createGoal', () => {
+ it('leaves an omitted round budget unset so the default cap applies', async () => {
+ verifyMocks.createCriteriaFromDrafts.mockResolvedValueOnce(['criterion-1']);
+ const taskCaller = {
+ run: vi.fn().mockResolvedValue({ operationId: 'op-1', topicId: 'topic-1' }),
+ updateVerifyConfig: vi.fn().mockResolvedValue(undefined),
+ };
+ const taskModel = { updateTaskConfig: vi.fn().mockResolvedValue(undefined) };
+ const taskService = {
+ createTask: vi.fn().mockResolvedValue({
+ id: 'task-db-1',
+ identifier: 'T-1',
+ name: 'Ship homepage',
+ priority: 0,
+ status: 'backlog',
+ }),
+ };
+ const runtime = createTaskRuntime({
+ agentId: 'agt-1',
+ agentModel: { existsById: vi.fn().mockResolvedValue(true) } as any,
+ db: {} as any,
+ taskCaller: taskCaller as any,
+ taskModel: taskModel as any,
+ taskService: taskService as any,
+ topicId: 'origin-topic',
+ userId: 'user-1',
+ });
+
+ await runtime.createGoal({
+ criteria: [{ title: 'LCP under two seconds' }],
+ instruction: 'Make the homepage fast.',
+ name: 'Ship homepage',
+ });
+
+ // `null` means "uncapped"; coercing an omitted budget into it would let a
+ // failing goal spawn rounds forever.
+ const [, config] = taskModel.updateTaskConfig.mock.calls[0];
+ expect(config.goal.maxIterations).toBeUndefined();
+ });
+
+ it('creates, configures, and starts one verified task', async () => {
+ verifyMocks.createCriteriaFromDrafts.mockResolvedValueOnce(['criterion-1']);
+ const taskCaller = {
+ run: vi.fn().mockResolvedValue({ operationId: 'op-1', topicId: 'topic-1' }),
+ updateVerifyConfig: vi.fn().mockResolvedValue(undefined),
+ };
+ const taskModel = { updateTaskConfig: vi.fn().mockResolvedValue(undefined) };
+ const taskService = {
+ createTask: vi.fn().mockResolvedValue({
+ id: 'task-db-1',
+ identifier: 'T-1',
+ name: 'Ship homepage',
+ priority: 0,
+ status: 'backlog',
+ }),
+ };
+ const runtime = createTaskRuntime({
+ agentId: 'agt-1',
+ agentModel: { existsById: vi.fn().mockResolvedValue(true) } as any,
+ db: {} as any,
+ taskCaller: taskCaller as any,
+ taskModel: taskModel as any,
+ taskService: taskService as any,
+ topicId: 'origin-topic',
+ userId: 'user-1',
+ });
+
+ const result = await runtime.createGoal({
+ criteria: [{ title: 'LCP under two seconds' }],
+ instruction: 'Redesign and ship the homepage',
+ maxIterations: 3,
+ maxTotalCost: 12,
+ name: 'Ship homepage',
+ });
+
+ expect(result.success).toBe(true);
+ expect(verifyMocks.createCriteriaFromDrafts).toHaveBeenCalledWith([
+ expect.objectContaining({ onFail: 'auto_repair', required: true }),
+ ]);
+ expect(taskCaller.updateVerifyConfig).toHaveBeenCalledWith({
+ id: 'task-db-1',
+ verify: expect.objectContaining({
+ enabled: true,
+ maxIterations: 3,
+ verifyCriteriaIds: ['criterion-1'],
+ }),
+ });
+ expect(taskModel.updateTaskConfig).toHaveBeenCalledWith('task-db-1', {
+ goal: { maxIterations: 3, maxTotalCost: 12, originTopicId: 'origin-topic' },
+ });
+ expect(taskCaller.run).toHaveBeenCalledWith({ id: 'task-db-1' });
+ expect(taskModel.updateTaskConfig.mock.invocationCallOrder[0]).toBeLessThan(
+ taskCaller.updateVerifyConfig.mock.invocationCallOrder[0],
+ );
+ // The success branch is the only one carrying `state`; narrow to it so
+ // this asserts the shape rather than the union.
+ expect(result).toHaveProperty('state');
+ expect((result as { state: unknown }).state).toEqual(
+ expect.objectContaining({ identifier: 'T-1', success: true, taskId: 'task-db-1' }),
+ );
+ });
+ });
+
describe('task comments', () => {
it('adds a comment to the current task with agent attribution', async () => {
const taskCaller = {
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/task.ts b/apps/server/src/services/toolExecution/serverRuntimes/task.ts
index 769b7dbe2be..6b51c188b2d 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/task.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/task.ts
@@ -22,6 +22,7 @@ import { tasks } from '@/database/schemas';
import { appEnv } from '@/envs/app';
import { taskRouter } from '@/server/routers/lambda/task';
import { TaskService } from '@/server/services/task';
+import { VerifyPlanGeneratorService } from '@/server/services/verify/planGenerator';
import { type ServerRuntimeRegistration } from './types';
@@ -48,6 +49,7 @@ export interface TaskRuntimeDeps {
// Assistant message that carried the createTask tool call — the tool-call
// anchor, NOT the source user message. Recorded as `context.origin.messageId`.
assistantMessageId?: string;
+ db?: LobeChatDatabase;
// Pointers to the conversation that invoked the createTask tool. Recorded into
// `tasks.context.origin` so the task's handoff result can later be delivered
// back to this session. All optional — a task can be created
@@ -70,6 +72,8 @@ export interface TaskRuntimeDeps {
// Source tool result message id, when the runtime already has one.
toolMessageId?: string;
topicId?: string | null;
+ userId?: string;
+ workspaceId?: string;
}
export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
@@ -225,6 +229,105 @@ export const createTaskRuntime = (deps: TaskRuntimeDeps) => {
: rest;
},
+ createGoal: async (args: {
+ criteria: Array<{
+ description?: string;
+ instruction?: string;
+ onFail?: 'auto_repair' | 'manual';
+ required?: boolean;
+ title: string;
+ verifierConfig?: Record<string, unknown>;
+ verifierType?: 'agent' | 'llm' | 'program';
+ }>;
+ instruction: string;
+ maxIterations?: number | null;
+ maxTotalCost?: number | null;
+ name: string;
+ }) => {
+ if (!agentId) return { content: 'A goal needs the current agent.', success: false };
+ if (!deps.db || !deps.userId) {
+ return { content: 'Goal planning is unavailable in this runtime.', success: false };
+ }
+ const drafts = (args.criteria ?? []).filter((item) => item.title?.trim());
+ if (drafts.length === 0) {
+ return { content: 'A goal needs at least one acceptance criterion.', success: false };
+ }
+
+ const created = await createTaskImpl({
+ assigneeAgentId: agentId,
+ instruction: args.instruction,
+ name: args.name,
+ });
+ if (!created.success || !created.identifier || !created.taskId) return created;
+
+ try {
+ const verifyCriteriaIds = await new VerifyPlanGeneratorService(
+ deps.db,
+ deps.userId,
+ deps.workspaceId,
+ ).createCriteriaFromDrafts(
+ drafts.map((item) => ({
+ description: item.description,
+ instruction: item.verifierType === 'program' ? undefined : item.instruction,
+ onFail: item.onFail ?? 'auto_repair',
+ required: item.required ?? true,
+ title: item.title,
+ verifierConfig: item.verifierConfig,
+ verifierType: item.verifierType ?? 'agent',
+ })),
+ );
+ const maxIterations = Math.min(10, Math.max(2, args.maxIterations ?? 3));
+
+ // Both operations merge into tasks.config. Running them concurrently
+ // can lose either the goal marker or verify config to last-write-wins.
+ await taskModel().updateTaskConfig(created.taskId, {
+ goal: {
+ // `null` is the user's explicit "no cap"; `undefined` means they
+ // never chose, which must fall back to the documented default.
+ // Coercing the second into the first made an uncapped loop the
+ // default for every goal that omitted the field.
+ maxIterations: args.maxIterations,
+ maxTotalCost: args.maxTotalCost ?? null,
+ originTopicId: topicId ?? null,
+ },
+ });
+ await taskCaller().updateVerifyConfig({
+ id: created.taskId,
+ verify: {
+ enabled: true,
+ maxIterations,
+ requirement: args.name,
+ verifyCriteriaIds,
+ },
+ });
+
+ const run = await taskCaller().run({ id: created.taskId });
+ const operationId = (run as { operationId?: string }).operationId;
+ const runTopicId = (run as { topicId?: string }).topicId;
+
+ return {
+ content: `Goal task ${created.identifier} created and started with ${drafts.length} acceptance criteria.`,
+ state: {
+ identifier: created.identifier,
+ name: args.name,
+ operationId,
+ startedAt: new Date().toISOString(),
+ success: true,
+ taskId: created.taskId,
+ topicId: runTopicId,
+ },
+ success: true,
+ };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : 'Failed to start goal';
+ return {
+ content: `Goal task ${created.identifier} was created but could not be started: ${message}`,
+ state: { identifier: created.identifier, name: args.name, success: false },
+ success: false,
+ };
+ }
+ },
+
createTasks: async (args: { tasks: CreateTaskArgs[] }) => {
const items = Array.isArray(args.tasks) ? args.tasks : [];
if (items.length === 0) {
@@ -780,6 +883,9 @@ export const taskRuntime: ServerRuntimeRegistration = {
toolCallId,
toolMessageId: context.toolMessageId,
topicId,
+ db,
+ userId,
+ workspaceId,
// Initial personal-mode models cover the no-task-context case. Replaced
// before the first call when `taskId` is set.
agentModel: new AgentModel(db, userId),
@@ -797,6 +903,7 @@ export const taskRuntime: ServerRuntimeRegistration = {
// and still construct `ToolExecutionContext` without `workspaceId`.
const wsId = context.workspaceId ?? (await resolveWorkspaceId(db, taskId));
workspaceId = wsId;
+ deps.workspaceId = wsId;
deps.agentModel = new AgentModel(db, userId, wsId);
deps.taskModel = new TaskModel(db, userId, wsId);
deps.taskService = new TaskService(db, userId, wsId);
diff --git a/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts b/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts
index 1023ec0f91d..3781183fffd 100644
--- a/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts
+++ b/apps/server/src/services/verify/__tests__/acceptanceDecision.test.ts
@@ -37,6 +37,10 @@ vi.mock('@/database/models/task', () => ({
}));
vi.mock('@/database/models/topic', () => ({ TopicModel: vi.fn() }));
vi.mock('@/database/models/document', () => ({ DocumentModel: vi.fn() }));
+vi.mock('../goalLoop', () => ({
+ maybeContinueGoalLoop: vi.fn().mockResolvedValue('spawn-failed'),
+ syncGoalToolState: vi.fn(),
+}));
vi.mock('@/server/services/task', () => ({ TaskService: vi.fn() }));
const service = () => new AcceptanceService({} as any, 'user-1');
diff --git a/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts b/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts
index 1384a49e976..eb7bbe67d52 100644
--- a/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts
+++ b/apps/server/src/services/verify/__tests__/acceptanceLifecycle.test.ts
@@ -20,6 +20,10 @@ const mocks = vi.hoisted(() => ({
taskResolveVerifyConfig: vi.fn(),
}));
+vi.mock('../goalLoop', () => ({
+ maybeContinueGoalLoop: vi.fn().mockResolvedValue('spawn-failed'),
+ syncGoalToolState: vi.fn(),
+}));
vi.mock('../acceptanceService', () => ({
AcceptanceService: vi.fn(() => ({
acceptanceModel: { update: mocks.acceptanceUpdate },
diff --git a/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts b/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts
index ac44975fb14..650451030b2 100644
--- a/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts
+++ b/apps/server/src/services/verify/__tests__/driveTaskFromVerify.test.ts
@@ -12,32 +12,59 @@ vi.mock('../reporter', () => ({
const {
runFindByOperation,
+ runClaimTaskDrive,
runSetMetadata,
opFindById,
taskFindById,
+ taskGetGoalConfig,
taskUpdateStatus,
briefCreate,
serviceUpdateStatus,
statusRecompute,
deliverMock,
+ goalContinueMock,
+ goalSyncMock,
} = vi.hoisted(() => ({
briefCreate: vi.fn(),
deliverMock: vi.fn(),
+ goalContinueMock: vi.fn(),
+ goalSyncMock: vi.fn(),
opFindById: vi.fn(),
runFindByOperation: vi.fn(),
+ runClaimTaskDrive: vi.fn().mockResolvedValue(true),
runSetMetadata: vi.fn(),
serviceUpdateStatus: vi.fn(),
statusRecompute: vi.fn(),
taskFindById: vi.fn(),
+ taskGetGoalConfig: vi.fn(),
taskUpdateStatus: vi.fn(),
}));
+vi.mock('../goalLoop', () => ({
+ goalExhaustedBriefCopy: (task: any, outcome: string) => ({
+ summary: `budget exhausted (${outcome})`,
+ title: `${task.identifier} goal paused`,
+ }),
+ goalReadyForReviewBriefCopy: (task: any, acceptanceId?: string) => ({
+ actions: acceptanceId
+ ? [{ key: 'review', type: 'link', url: `/acceptance/${acceptanceId}` }]
+ : [],
+ summary: 'ready for your sign-off',
+ title: `${task.identifier} goal delivered`,
+ }),
+ maybeContinueGoalLoop: goalContinueMock,
+ resolveGoalRoundBudget: (goal: any) =>
+ goal.maxIterations === null ? Number.POSITIVE_INFINITY : (goal.maxIterations ?? 3),
+ syncGoalToolState: goalSyncMock,
+}));
+
vi.mock('../statusService', () => ({
VerifyStatusService: vi.fn(() => ({ recompute: statusRecompute })),
}));
vi.mock('@/database/models/verifyRun', () => ({
VerifyRunModel: vi.fn(() => ({
+ claimTaskDrive: runClaimTaskDrive,
findByOperation: runFindByOperation,
setMetadata: runSetMetadata,
})),
@@ -46,7 +73,11 @@ vi.mock('@/database/models/agentOperation', () => ({
AgentOperationModel: vi.fn(() => ({ findById: opFindById })),
}));
vi.mock('@/database/models/task', () => ({
- TaskModel: vi.fn(() => ({ findById: taskFindById, updateStatus: taskUpdateStatus })),
+ TaskModel: vi.fn(() => ({
+ findById: taskFindById,
+ getGoalConfig: taskGetGoalConfig,
+ updateStatus: taskUpdateStatus,
+ })),
}));
vi.mock('@/database/models/brief', () => ({
BriefModel: vi.fn(() => ({ create: briefCreate })),
@@ -65,16 +96,23 @@ const db = {} as any;
describe('driveTaskFromVerify', () => {
beforeEach(() => {
[
+ runClaimTaskDrive,
runFindByOperation,
runSetMetadata,
opFindById,
taskFindById,
+ taskGetGoalConfig,
taskUpdateStatus,
briefCreate,
serviceUpdateStatus,
statusRecompute,
deliverMock,
+ goalContinueMock,
+ goalSyncMock,
].forEach((m) => m.mockReset());
+ // The drive is claimed before any side effect; unclaimed means "someone
+ // else is driving this run", which every test here is not.
+ runClaimTaskDrive.mockResolvedValue(true);
opFindById.mockResolvedValue({ taskId: 'task-1', topicId: 'topic-done' });
taskFindById.mockResolvedValue({
assigneeAgentId: 'a1',
@@ -82,6 +120,7 @@ describe('driveTaskFromVerify', () => {
identifier: 'T-1',
status: 'running',
});
+ taskGetGoalConfig.mockReturnValue(undefined);
});
afterEach(() => vi.restoreAllMocks());
@@ -97,7 +136,7 @@ describe('driveTaskFromVerify', () => {
taskIdentifier: 'T-1',
topicId: 'topic-done',
});
- expect(runSetMetadata).toHaveBeenCalled();
+ expect(runClaimTaskDrive).toHaveBeenCalledWith('run-1');
});
it('passed → keeps a recurring task scheduled', async () => {
@@ -117,7 +156,7 @@ describe('driveTaskFromVerify', () => {
expect(deliverMock).toHaveBeenCalledWith(
expect.objectContaining({ reason: 'done', taskId: 'task-1' }),
);
- expect(runSetMetadata).toHaveBeenCalled();
+ expect(runClaimTaskDrive).toHaveBeenCalledWith('run-1');
});
it('settles the owning task when the passing verify run belongs to a repair child', async () => {
@@ -155,11 +194,16 @@ describe('driveTaskFromVerify', () => {
expect(statusRecompute.mock.calls).toEqual([['repair-op-1'], ['root-op']]);
});
- it('failed → urgent brief + pauses, delivers a failure creator callback', async () => {
+ it('failed → urgent brief + pauses with the reason on the task row', async () => {
runFindByOperation.mockResolvedValue({ id: 'run-1', metadata: null, status: 'failed' });
await driveTaskFromVerify(db, 'u1', 'op-1');
expect(briefCreate).toHaveBeenCalled();
- expect(taskUpdateStatus).toHaveBeenCalledWith('task-1', 'paused', { error: null });
+ // The reason must live on the task row, not only in a brief: the task
+ // detail feed deliberately excludes briefs, so a brief-only explanation is
+ // unreachable from the task page.
+ expect(taskUpdateStatus).toHaveBeenCalledWith('task-1', 'paused', {
+ error: 'Delivery did not pass verification.',
+ });
expect(serviceUpdateStatus).not.toHaveBeenCalled();
// Creator is told it failed verification (reason 'error'), not a passed result.
expect(deliverMock.mock.calls[0][0]).toMatchObject({ reason: 'error', taskId: 'task-1' });
@@ -170,7 +214,11 @@ describe('driveTaskFromVerify', () => {
await driveTaskFromVerify(db, 'u1', 'op-1');
// Paused for a human, but NOT completed — the delivery was never evaluated.
- expect(taskUpdateStatus).toHaveBeenCalledWith('task-1', 'paused', { error: null });
+ expect(taskUpdateStatus).toHaveBeenCalledWith(
+ 'task-1',
+ 'paused',
+ expect.objectContaining({ error: expect.stringContaining('could not run') }),
+ );
expect(serviceUpdateStatus).not.toHaveBeenCalled();
// The brief frames it as an internal verification error, not a rejected delivery.
@@ -216,4 +264,151 @@ describe('driveTaskFromVerify', () => {
await driveTaskFromVerify(db, 'u1', 'op-1');
expect(serviceUpdateStatus).not.toHaveBeenCalled();
});
+
+ describe('goal outer loop', () => {
+ const goalTask = {
+ assigneeAgentId: 'a1',
+ id: 'task-1',
+ identifier: 'T-1',
+ status: 'running',
+ totalTopics: 1,
+ };
+ const goal = { maxIterations: 3, maxTotalCost: null, originTopicId: 'origin-t' };
+
+ beforeEach(() => {
+ taskFindById.mockResolvedValue(goalTask);
+ taskGetGoalConfig.mockReturnValue(goal);
+ });
+
+ it('failed + budget left → spawns the next round silently (no brief, no pause, no callback)', async () => {
+ runFindByOperation.mockResolvedValue({
+ id: 'run-1',
+ metadata: { maxRepairRounds: 2 },
+ status: 'failed',
+ });
+ goalContinueMock.mockResolvedValue('continued');
+
+ await driveTaskFromVerify(db, 'u1', 'op-1');
+
+ expect(goalContinueMock).toHaveBeenCalledWith(
+ expect.objectContaining({ goal, task: goalTask }),
+ );
+ expect(briefCreate).not.toHaveBeenCalled();
+ expect(taskUpdateStatus).not.toHaveBeenCalled();
+ expect(deliverMock).not.toHaveBeenCalled();
+ // The claim both stamps the marker and proves we own this drive.
+ expect(runClaimTaskDrive).toHaveBeenCalledWith('run-1');
+ expect(goalSyncMock).toHaveBeenCalledWith(
+ expect.objectContaining({ state: expect.objectContaining({ phase: 'running' }) }),
+ );
+ });
+
+ it('does nothing when another callback already claimed the drive', async () => {
+ // Two verifier callbacks can settle together; only the claim winner acts.
+ runClaimTaskDrive.mockResolvedValue(false);
+
+ await driveTaskFromVerify({} as never, 'user-1', 'op-1');
+
+ expect(goalContinueMock).not.toHaveBeenCalled();
+ expect(taskUpdateStatus).not.toHaveBeenCalled();
+ expect(serviceUpdateStatus).not.toHaveBeenCalled();
+ expect(briefCreate).not.toHaveBeenCalled();
+ });
+
+ it('failed + budget exhausted → pauses with budget-specific brief copy', async () => {
+ runFindByOperation.mockResolvedValue({ id: 'run-1', metadata: null, status: 'failed' });
+ goalContinueMock.mockResolvedValue('exhausted-rounds');
+
+ await driveTaskFromVerify(db, 'u1', 'op-1');
+
+ // Reason on the row, not only in the brief — see the failed-branch test.
+ expect(taskUpdateStatus).toHaveBeenCalledWith('task-1', 'paused', {
+ error: 'budget exhausted (exhausted-rounds)',
+ });
+ const briefArg = briefCreate.mock.calls[0][0];
+ expect(briefArg.summary).toContain('budget exhausted (exhausted-rounds)');
+ expect(goalSyncMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ state: expect.objectContaining({ pausedReason: 'exhausted-rounds', phase: 'paused' }),
+ }),
+ );
+ });
+
+ it('failed + spawn failure → falls back to the regular pause + brief path', async () => {
+ runFindByOperation.mockResolvedValue({ id: 'run-1', metadata: null, status: 'failed' });
+ goalContinueMock.mockResolvedValue('spawn-failed');
+
+ await driveTaskFromVerify(db, 'u1', 'op-1');
+
+ expect(taskUpdateStatus).toHaveBeenCalledWith('task-1', 'paused', {
+ error: 'Delivery did not pass verification.',
+ });
+ expect(briefCreate.mock.calls[0][0].summary).toContain('did not pass');
+ });
+
+ it('errored → never loops (verification did not run), pauses like a non-goal task', async () => {
+ runFindByOperation.mockResolvedValue({ id: 'run-1', metadata: null, status: 'errored' });
+
+ await driveTaskFromVerify(db, 'u1', 'op-1');
+
+ expect(goalContinueMock).not.toHaveBeenCalled();
+ expect(taskUpdateStatus).toHaveBeenCalledWith(
+ 'task-1',
+ 'paused',
+ expect.objectContaining({ error: expect.stringContaining('could not run') }),
+ );
+ });
+
+ it('passed → parks for sign-off instead of completing (the verifier only recommends)', async () => {
+ runFindByOperation.mockResolvedValue({
+ acceptanceId: 'acc-9',
+ id: 'run-1',
+ metadata: null,
+ status: 'passed',
+ });
+
+ await driveTaskFromVerify(db, 'u1', 'op-1');
+
+ // The agent saying "done" is not the business fact — the human sign-off is.
+ expect(serviceUpdateStatus).not.toHaveBeenCalled();
+ // A converged goal and a goal that gave up both land on `paused`; only the
+ // reason on the row tells them apart in the UI.
+ expect(taskUpdateStatus).toHaveBeenCalledWith('task-1', 'paused', {
+ error: 'ready for your sign-off',
+ });
+ expect(goalSyncMock).toHaveBeenCalledWith(
+ expect.objectContaining({ state: expect.objectContaining({ phase: 'review' }) }),
+ );
+ });
+
+ it('passed → raises exactly one decision brief that links to the acceptance', async () => {
+ runFindByOperation.mockResolvedValue({
+ acceptanceId: 'acc-9',
+ id: 'run-1',
+ metadata: null,
+ status: 'passed',
+ });
+
+ await driveTaskFromVerify(db, 'u1', 'op-1');
+
+ expect(briefCreate).toHaveBeenCalledTimes(1);
+ const brief = briefCreate.mock.calls[0][0];
+ // `result` would be filed under "news" and its approve completes the task,
+ // bypassing the sign-off this branch exists to require.
+ expect(brief.type).toBe('decision');
+ expect(brief.actions).toEqual([
+ expect.objectContaining({ type: 'link', url: '/acceptance/acc-9' }),
+ ]);
+ });
+ });
+
+ it('non-goal task still completes on a passing verify (contract unchanged)', async () => {
+ taskGetGoalConfig.mockReturnValue(undefined);
+ runFindByOperation.mockResolvedValue({ id: 'run-1', metadata: null, status: 'passed' });
+
+ await driveTaskFromVerify(db, 'u1', 'op-1');
+
+ expect(serviceUpdateStatus).toHaveBeenCalledWith({ id: 'task-1', status: 'completed' });
+ expect(briefCreate).not.toHaveBeenCalled();
+ });
});
diff --git a/apps/server/src/services/verify/__tests__/goalLoop.test.ts b/apps/server/src/services/verify/__tests__/goalLoop.test.ts
new file mode 100644
index 00000000000..4e33d61ba0a
--- /dev/null
+++ b/apps/server/src/services/verify/__tests__/goalLoop.test.ts
@@ -0,0 +1,164 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { DEFAULT_GOAL_MAX_ROUNDS, resolveGoalRoundBudget } from '../goalBudget';
+import { maybeContinueGoalLoop, syncGoalToolState } from '../goalLoop';
+
+const { runTaskMock, sumCostMock, findToolMessageIdMock, updateToolMessageMock } = vi.hoisted(
+ () => ({
+ findToolMessageIdMock: vi.fn(),
+ runTaskMock: vi.fn(),
+ sumCostMock: vi.fn(),
+ updateToolMessageMock: vi.fn(),
+ }),
+);
+
+vi.mock('@/server/services/taskRunner', () => ({
+ TaskRunnerService: vi.fn(() => ({ runTask: runTaskMock })),
+}));
+vi.mock('@/database/models/agentOperation', () => ({
+ AgentOperationModel: vi.fn(() => ({ sumCostByTask: sumCostMock })),
+}));
+vi.mock('@/database/models/message', () => ({
+ MessageModel: vi.fn(() => ({
+ findToolMessageIdByToolCallId: findToolMessageIdMock,
+ updateToolMessage: updateToolMessageMock,
+ })),
+}));
+
+const db = {} as any;
+const baseTask = { id: 'task-1', identifier: 'T-1', totalTopics: 1 } as any;
+
+describe('resolveGoalRoundBudget', () => {
+ it('null → uncapped', () => {
+ expect(resolveGoalRoundBudget({ maxIterations: null })).toBe(Number.POSITIVE_INFINITY);
+ });
+ it('absent → default', () => {
+ expect(resolveGoalRoundBudget({})).toBe(DEFAULT_GOAL_MAX_ROUNDS);
+ });
+ it('numbers are floored at 2', () => {
+ expect(resolveGoalRoundBudget({ maxIterations: 1 })).toBe(2);
+ expect(resolveGoalRoundBudget({ maxIterations: 5 })).toBe(5);
+ });
+});
+
+describe('maybeContinueGoalLoop', () => {
+ beforeEach(() => {
+ [runTaskMock, sumCostMock].forEach((m) => m.mockReset());
+ });
+
+ it('spawns the next round with the goal trigger while budgets last', async () => {
+ runTaskMock.mockResolvedValue({});
+ const outcome = await maybeContinueGoalLoop({
+ db,
+ goal: { maxIterations: 3 },
+ task: baseTask,
+ userId: 'u1',
+ });
+ expect(outcome).toBe('continued');
+ expect(runTaskMock).toHaveBeenCalledWith({ taskId: 'task-1', trigger: 'goal' });
+ });
+
+ it('stops at the round budget', async () => {
+ const outcome = await maybeContinueGoalLoop({
+ db,
+ goal: { maxIterations: 3 },
+ task: { ...baseTask, totalTopics: 3 },
+ userId: 'u1',
+ });
+ expect(outcome).toBe('exhausted-rounds');
+ expect(runTaskMock).not.toHaveBeenCalled();
+ });
+
+ it('uncapped rounds (null) keep looping', async () => {
+ runTaskMock.mockResolvedValue({});
+ const outcome = await maybeContinueGoalLoop({
+ db,
+ goal: { maxIterations: null },
+ task: { ...baseTask, totalTopics: 42 },
+ userId: 'u1',
+ });
+ expect(outcome).toBe('continued');
+ });
+
+ it('stops when the cost budget is spent', async () => {
+ sumCostMock.mockResolvedValue(21.5);
+ const outcome = await maybeContinueGoalLoop({
+ db,
+ goal: { maxIterations: 5, maxTotalCost: 20 },
+ task: baseTask,
+ userId: 'u1',
+ });
+ expect(outcome).toBe('exhausted-cost');
+ expect(runTaskMock).not.toHaveBeenCalled();
+ });
+
+ it('ignores cost when no cost budget is set', async () => {
+ runTaskMock.mockResolvedValue({});
+ const outcome = await maybeContinueGoalLoop({
+ db,
+ goal: { maxIterations: 5, maxTotalCost: null },
+ task: baseTask,
+ userId: 'u1',
+ });
+ expect(outcome).toBe('continued');
+ expect(sumCostMock).not.toHaveBeenCalled();
+ });
+
+ it('degrades a spawn failure (e.g. CONFLICT: topic still running) to spawn-failed', async () => {
+ runTaskMock.mockRejectedValue(new Error('CONFLICT'));
+ const outcome = await maybeContinueGoalLoop({
+ db,
+ goal: { maxIterations: 3 },
+ task: baseTask,
+ userId: 'u1',
+ });
+ expect(outcome).toBe('spawn-failed');
+ });
+});
+
+describe('syncGoalToolState', () => {
+ beforeEach(() => {
+ [findToolMessageIdMock, updateToolMessageMock].forEach((m) => m.mockReset());
+ });
+
+ it('no origin toolCallId → silent no-op', async () => {
+ await syncGoalToolState({
+ db,
+ state: { phase: 'running' },
+ task: { ...baseTask, context: {} },
+ userId: 'u1',
+ });
+ expect(findToolMessageIdMock).not.toHaveBeenCalled();
+ });
+
+ it('pushes phase + counters onto the origin tool card', async () => {
+ findToolMessageIdMock.mockResolvedValue('msg-9');
+ await syncGoalToolState({
+ db,
+ state: { phase: 'paused', roundsRun: 3 },
+ task: { ...baseTask, context: { origin: { toolCallId: 'call-1' } } },
+ userId: 'u1',
+ });
+ expect(findToolMessageIdMock).toHaveBeenCalledWith('call-1');
+ expect(updateToolMessageMock).toHaveBeenCalledWith('msg-9', {
+ pluginState: expect.objectContaining({
+ goalPhase: 'paused',
+ phase: 'paused',
+ roundsRun: 3,
+ updatedAt: expect.any(String),
+ }),
+ });
+ });
+
+ it('missing tool card → no write, no throw', async () => {
+ findToolMessageIdMock.mockResolvedValue(null);
+ await syncGoalToolState({
+ db,
+ state: { phase: 'done' },
+ task: { ...baseTask, context: { origin: { toolCallId: 'call-1' } } },
+ userId: 'u1',
+ });
+ expect(updateToolMessageMock).not.toHaveBeenCalled();
+ });
+});
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 1d41801a817..cdb04cdfd1b 100644
--- a/apps/server/src/services/verify/__tests__/statusService.recompute.test.ts
+++ b/apps/server/src/services/verify/__tests__/statusService.recompute.test.ts
@@ -11,6 +11,10 @@ const { acceptanceRecomputeStatus, runFindByOperation, runUpdateStatus, resultLi
runUpdateStatus: vi.fn(),
}));
+vi.mock('../goalLoop', () => ({
+ maybeContinueGoalLoop: vi.fn().mockResolvedValue('spawn-failed'),
+ syncGoalToolState: vi.fn(),
+}));
vi.mock('../acceptanceService', () => ({
AcceptanceService: vi.fn(() => ({
recomputeStatus: acceptanceRecomputeStatus,
diff --git a/apps/server/src/services/verify/acceptanceService.ts b/apps/server/src/services/verify/acceptanceService.ts
index 5c614f9a6bb..a28964839c3 100644
--- a/apps/server/src/services/verify/acceptanceService.ts
+++ b/apps/server/src/services/verify/acceptanceService.ts
@@ -31,6 +31,7 @@ import type { LobeChatDatabase } from '@/database/type';
import { TaskService } from '@/server/services/task';
import { computeFalseFlags } from './feedbackService';
+import { maybeContinueGoalLoop, syncGoalToolState } from './goalLoop';
const log = debug('lobe-server:verify-acceptance');
@@ -535,6 +536,12 @@ export class AcceptanceService {
return status;
};
+ /** Latest round of an aggregate — the row `stampDecision` would write to. */
+ latestRound = async (acceptanceId: string) => {
+ const runs = await this.runModel.listByAcceptance(acceptanceId);
+ return runs.at(-1) ?? null;
+ };
+
/**
* The user accepts the delivery — the terminal business event (P-12). Stamps
* the decision on the current round, closes the aggregate, and best-effort
@@ -546,27 +553,86 @@ export class AcceptanceService {
await this.stampDecision(acceptanceId, 'accept', comment);
await this.acceptanceModel.updateStatus(acceptanceId, 'accepted');
- if (acceptance.subjectType === 'task') await this.completeTaskSubject(acceptance.subjectId);
+ if (acceptance.subjectType === 'task') {
+ await this.completeTaskSubject(acceptance.subjectId);
+ await this.syncGoalStateOnAccept(acceptance.subjectId);
+ }
return (await this.acceptanceModel.findById(acceptanceId))!;
};
+ /** Flip a goal task's origin card to its terminal "done" state. Best-effort. */
+ private syncGoalStateOnAccept = async (subjectId: string): Promise<void> => {
+ try {
+ const taskModel = new TaskModel(this.db, this.userId, this.workspaceId);
+ const task = await taskModel.findById(subjectId);
+ if (!task) return;
+ const goal = taskModel.getGoalConfig(task);
+ if (!goal) return;
+
+ await syncGoalToolState({
+ db: this.db,
+ state: { phase: 'done', roundsRun: task.totalTopics || 0 },
+ task,
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ });
+ } catch (error) {
+ log('syncGoalStateOnAccept failed (non-fatal): %O', error);
+ }
+ };
+
/**
* The user rejects the delivery. The comment is the re-tasking input: it is
* recorded on the round's decision detail, where the next repair/verify round
* picks it up. (Spawning the repair run itself is the runtime's job — for
* agent-bound rounds via the repair pipeline, for ingested rounds via the
* next `lh verify ingest-report`.)
+ *
+ * Goal tasks are the exception: a reject IS the "run another round" gesture,
+ * so the outer loop spawns the next task topic right here — the comment
+ * reaches the new round through the prompt builder, which reads it off this
+ * round's decision detail. Budgets still apply; when they ran out the reject
+ * only stamps state (the UI asks the user to raise the budget first).
*/
reject = async (acceptanceId: string, comment: string): Promise<AcceptanceItem> => {
- await this.requireDecidableAcceptance(acceptanceId);
+ const acceptance = await this.requireDecidableAcceptance(acceptanceId);
await this.stampDecision(acceptanceId, 'reject', comment);
await this.acceptanceModel.updateStatus(acceptanceId, 'rejected');
+ if (acceptance.subjectType === 'task') await this.spawnGoalRoundOnReject(acceptance.subjectId);
+
return (await this.acceptanceModel.findById(acceptanceId))!;
};
+ /**
+ * If the rejected subject is a goal task with budget left, start the next
+ * round (fresh topic). Best-effort: any failure leaves the acceptance in
+ * `rejected` — exactly where a non-goal reject would leave it.
+ */
+ private spawnGoalRoundOnReject = async (subjectId: string): Promise<void> => {
+ try {
+ const taskModel = new TaskModel(this.db, this.userId, this.workspaceId);
+ const task = await taskModel.findById(subjectId);
+ if (!task) return;
+
+ const goal = taskModel.getGoalConfig(task);
+ if (!goal) return;
+
+ const outcome = await maybeContinueGoalLoop({
+ db: this.db,
+ goal,
+ task,
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ });
+ log('reject on goal task %s → loop outcome: %s', task.identifier, outcome);
+ } catch (error) {
+ log('spawnGoalRoundOnReject failed (non-fatal): %O', error);
+ }
+ };
+
/**
* Record the user's verdict on one or more union checks (a group-level
* "accept all" is just many ids). Stamps `user_decision` +
diff --git a/apps/server/src/services/verify/goalBudget.ts b/apps/server/src/services/verify/goalBudget.ts
new file mode 100644
index 00000000000..1f62e8bbd64
--- /dev/null
+++ b/apps/server/src/services/verify/goalBudget.ts
@@ -0,0 +1,22 @@
+import type { TaskGoalConfig } from '@lobechat/types';
+
+/**
+ * Pure goal-budget helpers, dependency-free on purpose: both the outer loop
+ * (verify/goalLoop → TaskRunnerService) and the prompt builder
+ * (taskRunner/buildTaskPrompt) need them, and importing the loop service from
+ * the prompt builder would create a taskRunner ⇄ verify module cycle.
+ */
+
+/**
+ * Applied when the user left the round budget untouched. `null` in the config
+ * means the user explicitly opted out of a cap — that maps to Infinity, not to
+ * this default.
+ */
+export const DEFAULT_GOAL_MAX_ROUNDS = 3;
+
+/** Round budget: `null` = user opted out of a cap, absent = default. */
+export const resolveGoalRoundBudget = (goal: TaskGoalConfig): number => {
+ if (goal.maxIterations === null) return Number.POSITIVE_INFINITY;
+ if (typeof goal.maxIterations === 'number') return Math.max(2, goal.maxIterations);
+ return DEFAULT_GOAL_MAX_ROUNDS;
+};
diff --git a/apps/server/src/services/verify/goalLoop.ts b/apps/server/src/services/verify/goalLoop.ts
new file mode 100644
index 00000000000..9d0961ada85
--- /dev/null
+++ b/apps/server/src/services/verify/goalLoop.ts
@@ -0,0 +1,144 @@
+import type { BriefAction, TaskContext, TaskGoalConfig, TaskItem } from '@lobechat/types';
+import debug from 'debug';
+
+import { AgentOperationModel } from '@/database/models/agentOperation';
+import { MessageModel } from '@/database/models/message';
+import type { LobeChatDatabase } from '@/database/type';
+import { TaskRunnerService } from '@/server/services/taskRunner';
+
+import { resolveGoalRoundBudget } from './goalBudget';
+
+const log = debug('lobe-server:verify-goal-loop');
+
+export { DEFAULT_GOAL_MAX_ROUNDS, resolveGoalRoundBudget } from './goalBudget';
+
+export type GoalLoopOutcome = 'continued' | 'exhausted-cost' | 'exhausted-rounds' | 'spawn-failed';
+
+/**
+ * The goal outer loop: after a goal task's verify run settles as failed, spawn
+ * the next round (a fresh task topic) unless a budget ran out. Never throws —
+ * a spawn failure degrades to the caller's pause-and-notify path.
+ *
+ * The check-level auto-repair inner loop (same-topic re-run in repairService)
+ * has already been exhausted by the time a run settles as failed, so this is
+ * strictly the round-level loop.
+ */
+export const maybeContinueGoalLoop = async (params: {
+ db: LobeChatDatabase;
+ goal: TaskGoalConfig;
+ task: TaskItem;
+ userId: string;
+ workspaceId?: string;
+}): Promise<GoalLoopOutcome> => {
+ const { db, goal, task, userId, workspaceId } = params;
+
+ const roundsRun = task.totalTopics || 0;
+ const roundBudget = resolveGoalRoundBudget(goal);
+ if (roundsRun >= roundBudget) {
+ log('task %s exhausted round budget (%d/%s)', task.identifier, roundsRun, roundBudget);
+ return 'exhausted-rounds';
+ }
+
+ if (typeof goal.maxTotalCost === 'number') {
+ const spent = await new AgentOperationModel(db, userId, workspaceId).sumCostByTask(task.id);
+ if (spent >= goal.maxTotalCost) {
+ log('task %s exhausted cost budget ($%d >= $%d)', task.identifier, spent, goal.maxTotalCost);
+ return 'exhausted-cost';
+ }
+ }
+
+ try {
+ await new TaskRunnerService(db, userId, workspaceId).runTask({
+ taskId: task.id,
+ trigger: 'goal',
+ });
+ log('task %s → goal round %d spawned', task.identifier, roundsRun + 1);
+ return 'continued';
+ } catch (error) {
+ // CONFLICT (a topic is still running) or any spawn failure — the caller
+ // falls back to pause + brief so the loop can never crash the settle path.
+ log('task %s goal round spawn failed (non-fatal): %O', task.identifier, error);
+ return 'spawn-failed';
+ }
+};
+
+/** User-facing copy for the pause brief when a budget ran out. */
+export const goalExhaustedBriefCopy = (
+ task: TaskItem,
+ outcome: Extract<GoalLoopOutcome, 'exhausted-cost' | 'exhausted-rounds'>,
+ goal: TaskGoalConfig,
+): { summary: string; title: string } =>
+ outcome === 'exhausted-cost'
+ ? {
+ summary: `The goal did not pass verification and its cost budget ($${goal.maxTotalCost}) is used up. Adjust the plan or budget to restart the loop.`,
+ title: `${task.identifier} goal paused — cost budget exhausted`,
+ }
+ : {
+ summary: `The goal did not pass verification after ${task.totalTopics || 0} rounds (budget ${resolveGoalRoundBudget(goal)}). Adjust the plan or budget to restart the loop.`,
+ title: `${task.identifier} goal paused — round budget exhausted`,
+ };
+
+/**
+ * User-facing copy for the one brief a converged goal SHOULD raise: the loop is
+ * done iterating and the delivery is waiting on the user's sign-off.
+ *
+ * Per-round result briefs are suppressed for goal tasks (see
+ * `TaskLifecycleService.onTopicComplete`), so this is the moment the user is
+ * pulled back in — not once per round.
+ */
+export const goalReadyForReviewBriefCopy = (
+ task: TaskItem,
+ acceptanceId?: string,
+): { actions: BriefAction[]; summary: string; title: string } => ({
+ // A `decision` brief, not a `result` one, for two reasons: `result` briefs are
+ // filed unconditionally under "news" (nothing to do), and their approve button
+ // completes the task outright — which would bypass the very sign-off this
+ // change exists to require. The only action offered is a link to the
+ // acceptance page, so the button promises exactly what it does.
+ actions: acceptanceId
+ ? [
+ {
+ key: 'review',
+ label: '🔍 Review delivery',
+ type: 'link',
+ url: `/acceptance/${acceptanceId}`,
+ },
+ ]
+ : [],
+ summary: `The goal passed verification after ${task.totalTopics || 1} round(s) and is waiting for your sign-off. Review the checks, then accept or send it back.`,
+ title: `${task.identifier} goal delivered — ready for your review`,
+});
+
+/**
+ * Push the goal's latest phase onto the `createGoal` tool card in the origin
+ * conversation, keyed by the toolCallId recorded at creation time. Best-effort:
+ * a missing origin (task created outside a conversation) or a missing card is
+ * a silent no-op, and failures never propagate into the settle path.
+ */
+export const syncGoalToolState = async (params: {
+ db: LobeChatDatabase;
+ state: {
+ phase: 'done' | 'paused' | 'review' | 'running';
+ roundBudget?: number | null;
+ roundsRun?: number;
+ } & Record<string, unknown>;
+ task: TaskItem;
+ userId: string;
+ workspaceId?: string;
+}): Promise<void> => {
+ const { db, state, task, userId, workspaceId } = params;
+ const toolCallId = (task.context as TaskContext | undefined)?.origin?.toolCallId;
+ if (!toolCallId) return;
+
+ try {
+ const messageModel = new MessageModel(db, userId, workspaceId);
+ const toolMessageId = await messageModel.findToolMessageIdByToolCallId(toolCallId);
+ if (!toolMessageId) return;
+
+ await messageModel.updateToolMessage(toolMessageId, {
+ pluginState: { goalPhase: state.phase, ...state, updatedAt: new Date().toISOString() },
+ });
+ } catch (error) {
+ log('goal tool-state sync failed for task %s (non-fatal): %O', task.identifier, error);
+ }
+};
diff --git a/apps/server/src/services/verify/index.ts b/apps/server/src/services/verify/index.ts
index fa1dc0adddd..598ca7b9c75 100644
--- a/apps/server/src/services/verify/index.ts
+++ b/apps/server/src/services/verify/index.ts
@@ -18,6 +18,14 @@ export {
VerifyExecutorService,
} from './executor';
export { computeFalseFlags, VerifyFeedbackService } from './feedbackService';
+export { DEFAULT_GOAL_MAX_ROUNDS, resolveGoalRoundBudget } from './goalBudget';
+export {
+ goalExhaustedBriefCopy,
+ type GoalLoopOutcome,
+ goalReadyForReviewBriefCopy,
+ maybeContinueGoalLoop,
+ syncGoalToolState,
+} from './goalLoop';
export { runVerifyOnCompletion } from './lifecycle';
export { isHeterogeneousVerifyProvider, resolveVerifyModelConfig } from './modelConfig';
export { type GeneratePlanParams, VerifyPlanGeneratorService } from './planGenerator';
diff --git a/apps/server/src/services/verify/settle.ts b/apps/server/src/services/verify/settle.ts
index 79ceb549f16..47bedbb192c 100644
--- a/apps/server/src/services/verify/settle.ts
+++ b/apps/server/src/services/verify/settle.ts
@@ -9,6 +9,13 @@ import type { LobeChatDatabase } from '@/database/type';
import { TaskService } from '@/server/services/task';
import { TaskResultBridgeService } from '@/server/services/taskResultBridge';
+import {
+ goalExhaustedBriefCopy,
+ goalReadyForReviewBriefCopy,
+ maybeContinueGoalLoop,
+ resolveGoalRoundBudget,
+ syncGoalToolState,
+} from './goalLoop';
import { maybeAutoRepair } from './repairService';
import { VerifyReporterService } from './reporter';
import { VerifyStatusService } from './statusService';
@@ -84,6 +91,10 @@ export const driveTaskFromVerify = async (
// Only act on a terminally settled run (skip pending / verifying / repairing).
if (run?.status !== 'passed' && run?.status !== 'failed' && run?.status !== 'errored') return;
if ((run.metadata as { taskDrivenAt?: string } | null)?.taskDrivenAt) return; // already drove
+ // Cheap read above, authoritative claim here: concurrent verifier
+ // callbacks would otherwise both pass the read and both act — spawning two
+ // rounds, or one spawning while the other pauses the task it just started.
+ if (!(await runModel.claimTaskDrive(run.id))) return;
const operationModel = new AgentOperationModel(db, userId, workspaceId);
const op = await operationModel.findById(operationId);
@@ -94,20 +105,65 @@ export const driveTaskFromVerify = async (
const task = await taskModel.findById(taskOperation.taskId);
if (!task || TERMINAL_TASK_STATUS.has(task.status)) return; // task already settled
+ const goal = taskModel.getGoalConfig(task);
+
if (run.status === 'passed') {
- if (task.automationMode) {
- // Recurring tasks are parked back at `scheduled` and re-armed by the
- // task lifecycle. Verify accepts this run, not the lifetime schedule.
- log('verify passed → recurring task %s remains scheduled', taskOperation.taskId);
- } else {
- // Complete + cascade (checkpoint / sibling rollup / unlock downstream).
- // 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: taskOperation.taskId,
- status: 'completed',
+ if (goal) {
+ // A goal's loop converging is NOT the same business fact as the task
+ // being done: the verifier's `passed` is a recommendation, the human's
+ // sign-off is the terminal event (the acceptance lifecycle already
+ // models this as delivered → accepted). Completing the task here would
+ // claim "done" on the agent's own say-so and leave the acceptance
+ // waiting on a decision nobody is told to make.
+ //
+ // So: park the task for review and raise the ONE brief a goal should
+ // produce. `AcceptanceService.accept` completes the task (with the same
+ // cascade) once the user signs off.
+ // `paused` is the only status the task vocabulary has for "stopped,
+ // needs a human" — and the UI renders every paused task identically as
+ // 待审阅. Without a reason on the row, a converged goal waiting for
+ // sign-off and a goal that gave up look the same. Write the reason so
+ // the task page can tell them apart.
+ const review = goalReadyForReviewBriefCopy(task, run.acceptanceId ?? undefined);
+ await taskModel.updateStatus(taskOperation.taskId, 'paused', {
+ error: review.summary,
+ });
+ await new BriefModel(db, userId, workspaceId).create({
+ actions: review.actions,
+ agentId: task.assigneeAgentId || undefined,
+ priority: 'normal',
+ summary: review.summary,
+ taskId: taskOperation.taskId,
+ title: review.title,
+ trigger: 'task',
+ type: 'decision',
});
- log('verify passed → task %s completed', taskOperation.taskId);
+ await syncGoalToolState({
+ db,
+ state: { phase: 'review', roundsRun: task.totalTopics || 0 },
+ task,
+ userId,
+ workspaceId,
+ });
+ log('verify passed → goal task %s parked for sign-off', taskOperation.taskId);
+ } else {
+ // Non-goal tasks keep the existing contract: verify passing completes
+ // the task and cascades (checkpoint / sibling rollup / downstream
+ // unlock). Changing that for every verify-enabled task is a separate
+ // product decision, deliberately not bundled into the goal loop.
+ if (task.automationMode) {
+ // Recurring tasks are parked back at `scheduled` and re-armed by the
+ // task lifecycle. Verify accepts this run, not the lifetime schedule.
+ log('verify passed → recurring task %s remains scheduled', taskOperation.taskId);
+ } else {
+ // 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: taskOperation.taskId,
+ status: 'completed',
+ });
+ log('verify passed → task %s completed', taskOperation.taskId);
+ }
}
} else {
// Two non-pass outcomes, kept distinct so an infra error never reads as a
@@ -116,21 +172,73 @@ export const driveTaskFromVerify = async (
// - errored: the verifier could not run (infra) — the delivery was NOT
// evaluated, so we must not claim it "did not pass".
const isErrored = run.status === 'errored';
+
+ // Goal outer loop: a *failed* (judged) run on a goal task spawns the next
+ // round in a fresh topic while budgets last, instead of parking the task
+ // on the user. `errored` stays on the pause path — verification never ran,
+ // so looping would burn budget without new signal.
+ let exhausted: 'exhausted-cost' | 'exhausted-rounds' | undefined;
+ if (goal && !isErrored) {
+ const outcome = await maybeContinueGoalLoop({ db, goal, task, userId, workspaceId });
+ if (outcome === 'continued') {
+ await syncGoalToolState({
+ db,
+ state: {
+ phase: 'running',
+ roundBudget: goal.maxIterations === null ? null : resolveGoalRoundBudget(goal),
+ roundsRun: (task.totalTopics || 0) + 1,
+ },
+ task,
+ userId,
+ workspaceId,
+ });
+ // No brief, no pause, no creator callback — the loop continues
+ // silently until it converges or a budget runs out. The drive marker
+ // was already stamped by the claim above.
+ return;
+ }
+ if (outcome === 'exhausted-cost' || outcome === 'exhausted-rounds') exhausted = outcome;
+ // 'spawn-failed' falls through to the regular pause + brief path.
+ }
+
+ const exhaustedCopy =
+ exhausted && goal ? goalExhaustedBriefCopy(task, exhausted, goal) : null;
+ const pauseSummary =
+ exhaustedCopy?.summary ??
+ (isErrored
+ ? 'Verification could not run (internal error); the delivery was not evaluated.'
+ : 'Delivery did not pass verification.');
await new BriefModel(db, userId, workspaceId).create({
actions: DEFAULT_BRIEF_ACTIONS['error'],
agentId: task.assigneeAgentId || undefined,
priority: 'urgent',
- summary: isErrored
- ? 'Verification could not run (internal error); the delivery was not evaluated.'
- : 'Delivery did not pass verification.',
+ summary: pauseSummary,
taskId: taskOperation.taskId,
- title: isErrored
- ? `${task.identifier} verification errored`
- : `${task.identifier} failed verification`,
+ title:
+ exhaustedCopy?.title ??
+ (isErrored
+ ? `${task.identifier} verification errored`
+ : `${task.identifier} failed verification`),
trigger: 'task',
type: 'error',
});
- await taskModel.updateStatus(taskOperation.taskId, 'paused', { error: null });
+ // Same reasoning as the passed branch: the reason has to live on the task
+ // row, not only in a brief. The task detail feed deliberately excludes
+ // briefs, so a brief-only explanation is invisible from the task page.
+ await taskModel.updateStatus(taskOperation.taskId, 'paused', { error: pauseSummary });
+ if (goal) {
+ await syncGoalToolState({
+ db,
+ state: {
+ pausedReason: exhausted ?? (isErrored ? 'verify-errored' : 'verify-failed'),
+ phase: 'paused',
+ roundsRun: task.totalTopics || 0,
+ },
+ task,
+ userId,
+ workspaceId,
+ });
+ }
log(
isErrored
? 'verify errored → task %s paused + brief'
@@ -167,7 +275,7 @@ export const driveTaskFromVerify = async (
);
}
- await runModel.setMetadata(run.id, { taskDrivenAt: new Date().toISOString() });
+ // The drive marker was stamped by the claim at the top of this function.
} catch (error) {
log('driveTaskFromVerify failed for op %s (non-fatal): %O', operationId, error);
}
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 50108905982..839b82d160c 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1045,11 +1045,22 @@
"taskDetail.acceptance.goal": "Acceptance goal",
"taskDetail.acceptance.loadError": "Could not load delivery acceptance.",
"taskDetail.acceptance.multimodalLlm": "Multimodal LLM",
+ "taskDetail.acceptance.openReport": "Acceptance report",
"taskDetail.acceptance.requiredEvidence": "Required evidence",
"taskDetail.acceptance.retry": "Retry",
"taskDetail.acceptance.reviewError": "Could not save this review.",
"taskDetail.acceptance.title": "Delivery acceptance",
"taskDetail.acceptance.verifier": "Verification method",
+ "taskDetail.acceptanceState.accepted": "Accepted",
+ "taskDetail.acceptanceState.awaitingDecision": "Not passed — your call",
+ "taskDetail.acceptanceState.awaitingReview": "Awaiting your review",
+ "taskDetail.acceptanceState.awaitingVerification": "Awaiting verification",
+ "taskDetail.acceptanceState.closed": "Closed",
+ "taskDetail.acceptanceState.errored": "Verification errored",
+ "taskDetail.acceptanceState.hint": "Delivery acceptance — click to review",
+ "taskDetail.acceptanceState.rejected": "Sent back",
+ "taskDetail.acceptanceState.repairing": "Repairing",
+ "taskDetail.acceptanceState.verifying": "Verifying",
"taskDetail.activities": "Activities",
"taskDetail.activities.agentTag": "Agent",
"taskDetail.activities.fallback.brief": "posted a brief",
@@ -1080,6 +1091,14 @@
"taskDetail.deleteConfirm.content": "This action cannot be undone.",
"taskDetail.deleteConfirm.ok": "Delete",
"taskDetail.deleteConfirm.title": "Delete this task?",
+ "taskDetail.goalTimeline.hover.cost": "Cost",
+ "taskDetail.goalTimeline.hover.duration": "Duration",
+ "taskDetail.goalTimeline.hover.status": "Status",
+ "taskDetail.goalTimeline.hover.tokens": "Tokens",
+ "taskDetail.goalTimeline.hover.verdict": "Verdict",
+ "taskDetail.goalTimeline.round": "Round {{index}}",
+ "taskDetail.goalTimeline.rounds": "{{count}} rounds",
+ "taskDetail.goalTimeline.title": "Round progress",
"taskDetail.instruction": "Instruction",
"taskDetail.instructionPlaceholder": "Add task instruction...",
"taskDetail.latestActivity.brief": "Brief: {{title}}",
@@ -1129,10 +1148,22 @@
"taskDetail.runAll.skipped.blockedExternally": "{{count}} task(s) waiting on a blocker outside this batch — will run automatically when unblocked",
"taskDetail.runAll.skipped.ineligible": "{{count}} task(s) running or scheduled — skipped",
"taskDetail.runAll.title": "Run subtasks in dependency order",
+ "taskDetail.runCollapse": "Collapse run",
+ "taskDetail.runExpand": "Expand run",
"taskDetail.runFollowUp": "Ask a follow-up",
"taskDetail.runFollowUpPlaceholder": "Ask a follow-up about this run...",
"taskDetail.runNow": "Run now",
"taskDetail.runTask": "Run",
+ "taskDetail.runTrigger.goal": "Goal loop",
+ "taskDetail.runTrigger.heartbeat": "Heartbeat",
+ "taskDetail.runTrigger.schedule": "Scheduled",
+ "taskDetail.runVerify.checklist": "Acceptance checks",
+ "taskDetail.runVerify.errored": "Verification errored",
+ "taskDetail.runVerify.failed": "Not passed",
+ "taskDetail.runVerify.passed": "Passed",
+ "taskDetail.runVerify.pending": "Awaiting verification",
+ "taskDetail.runVerify.round": "Round {{index}}",
+ "taskDetail.runVerify.running": "Verifying",
"taskDetail.saveModelConfig": "Save",
"taskDetail.sendFollowUp": "Send follow up message",
"taskDetail.status.backlog": "Backlog",
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.json
index 932b5afd673..d42e6817a29 100644
--- a/locales/en-US/plugin.json
+++ b/locales/en-US/plugin.json
@@ -416,6 +416,7 @@
"builtins.lobe-skills.apiName.searchSkill": "Search Skills",
"builtins.lobe-skills.title": "Skills",
"builtins.lobe-task.apiName.addTaskComment": "Add comment",
+ "builtins.lobe-task.apiName.createGoal": "Start goal",
"builtins.lobe-task.apiName.createTask": "Create task",
"builtins.lobe-task.apiName.createTasks": "Create tasks",
"builtins.lobe-task.apiName.deleteTask": "Delete task",
@@ -445,6 +446,40 @@
"builtins.lobe-task.edit.unblocks": "unblocks",
"builtins.lobe-task.field.description": "Description",
"builtins.lobe-task.field.instruction": "Instruction",
+ "builtins.lobe-task.goal.add": "Add",
+ "builtins.lobe-task.goal.addCriterion": "Add acceptance criterion",
+ "builtins.lobe-task.goal.cancel": "Cancel",
+ "builtins.lobe-task.goal.costBudget": "Total cost budget",
+ "builtins.lobe-task.goal.criteria": "Acceptance criteria",
+ "builtins.lobe-task.goal.criterionTitle": "Title",
+ "builtins.lobe-task.goal.editCriterion": "Edit criterion C{{seq}}",
+ "builtins.lobe-task.goal.instruction": "Describe the exact pass conditions and required evidence",
+ "builtins.lobe-task.goal.judgePrompt": "Judge prompt",
+ "builtins.lobe-task.goal.optional": "Optional",
+ "builtins.lobe-task.goal.phase.accepted": "Accepted",
+ "builtins.lobe-task.goal.phase.awaitingDecision": "Not passed — your call",
+ "builtins.lobe-task.goal.phase.awaitingReview": "Awaiting your review",
+ "builtins.lobe-task.goal.phase.closed": "Closed",
+ "builtins.lobe-task.goal.phase.errored": "Verification errored",
+ "builtins.lobe-task.goal.phase.rejected": "Sent back",
+ "builtins.lobe-task.goal.phase.repairing": "Repairing",
+ "builtins.lobe-task.goal.phase.verifying": "Verifying",
+ "builtins.lobe-task.goal.required": "Required",
+ "builtins.lobe-task.goal.requiredHint": "Required — the goal cannot pass while this fails",
+ "builtins.lobe-task.goal.roundBudget": "Iteration budget",
+ "builtins.lobe-task.goal.roundsUnit": "rounds",
+ "builtins.lobe-task.goal.running": "Round 1 · running",
+ "builtins.lobe-task.goal.runningHint": "{{count}} checks will run automatically when this round completes",
+ "builtins.lobe-task.goal.save": "Save",
+ "builtins.lobe-task.goal.script": "Validation command or function",
+ "builtins.lobe-task.goal.sectionBudget": "Budget",
+ "builtins.lobe-task.goal.sectionInstruction": "Task instruction",
+ "builtins.lobe-task.goal.settledHint": "Click to open the acceptance",
+ "builtins.lobe-task.goal.uncapped": "Uncapped",
+ "builtins.lobe-task.goal.verifier.agent": "Agent verification",
+ "builtins.lobe-task.goal.verifier.llm": "Model judgement",
+ "builtins.lobe-task.goal.verifier.program": "Programmatic check",
+ "builtins.lobe-task.goal.verifierType": "Verification method",
"builtins.lobe-task.run.continueTopic": "continue topic",
"builtins.lobe-task.run.prompt": "Prompt",
"builtins.lobe-task.run.topic": "Topic",
diff --git a/locales/en-US/verify.json b/locales/en-US/verify.json
index be7f64abd86..46e7746b0cb 100644
--- a/locales/en-US/verify.json
+++ b/locales/en-US/verify.json
@@ -68,11 +68,13 @@
"acceptance.checks.iterated": "Iterated {{count}}×",
"acceptance.checks.iteratedHint": "The same acceptance concern evolved across {{count}} rounds; the last round stands. See the iteration history for the evolution.",
"acceptance.checks.iterationHistory": "Iteration history ({{count}} rounds)",
+ "acceptance.checks.judgeReason": "How this verdict was reached",
"acceptance.checks.notRequired": "Non-blocking",
"acceptance.checks.notRequiredHint": "required = false: failing this does not block acceptance.",
"acceptance.checks.rerun": "Verified {{count}} rounds",
"acceptance.checks.rerunHint": "The same check ran in {{count}} rounds; the last round stands.",
"acceptance.checks.title": "Acceptance checks",
+ "acceptance.checks.viewTrace": "View verification run",
"acceptance.detail.suggestion": "Suggestion",
"acceptance.error.description": "Check your connection and try loading this acceptance again.",
"acceptance.error.title": "Unable to load acceptance",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 38f97170f76..7e997a08584 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1045,11 +1045,22 @@
"taskDetail.acceptance.goal": "验收目标",
"taskDetail.acceptance.loadError": "交付验收加载失败。",
"taskDetail.acceptance.multimodalLlm": "多模态 LLM",
+ "taskDetail.acceptance.openReport": "验收报告",
"taskDetail.acceptance.requiredEvidence": "所需证据",
"taskDetail.acceptance.retry": "重试",
"taskDetail.acceptance.reviewError": "复核结果保存失败。",
"taskDetail.acceptance.title": "交付验收",
"taskDetail.acceptance.verifier": "验证方式",
+ "taskDetail.acceptanceState.accepted": "已验收",
+ "taskDetail.acceptanceState.awaitingDecision": "未通过 · 待你定夺",
+ "taskDetail.acceptanceState.awaitingReview": "待你验收",
+ "taskDetail.acceptanceState.awaitingVerification": "待验证",
+ "taskDetail.acceptanceState.closed": "已关闭",
+ "taskDetail.acceptanceState.errored": "验证出错",
+ "taskDetail.acceptanceState.hint": "交付验收 — 点击进入验收页",
+ "taskDetail.acceptanceState.rejected": "已打回",
+ "taskDetail.acceptanceState.repairing": "修复中",
+ "taskDetail.acceptanceState.verifying": "验证中",
"taskDetail.activities": "活动",
"taskDetail.activities.agentTag": "智能体",
"taskDetail.activities.fallback.brief": "发布了简要说明",
@@ -1080,6 +1091,14 @@
"taskDetail.deleteConfirm.content": "此操作不可撤销。",
"taskDetail.deleteConfirm.ok": "删除",
"taskDetail.deleteConfirm.title": "确认删除此任务?",
+ "taskDetail.goalTimeline.hover.cost": "成本",
+ "taskDetail.goalTimeline.hover.duration": "时长",
+ "taskDetail.goalTimeline.hover.status": "状态",
+ "taskDetail.goalTimeline.hover.tokens": "Token",
+ "taskDetail.goalTimeline.hover.verdict": "判定",
+ "taskDetail.goalTimeline.round": "第 {{index}} 轮",
+ "taskDetail.goalTimeline.rounds": "{{count}} 轮",
+ "taskDetail.goalTimeline.title": "轮次进展",
"taskDetail.instruction": "任务说明",
"taskDetail.instructionPlaceholder": "点击编辑任务说明…",
"taskDetail.latestActivity.brief": "简要:{{title}}",
@@ -1129,10 +1148,22 @@
"taskDetail.runAll.skipped.blockedExternally": "{{count}} 个任务被本批次外的依赖阻塞 —— 解除阻塞后将自动运行",
"taskDetail.runAll.skipped.ineligible": "{{count}} 个任务正在运行或已排期 —— 已跳过",
"taskDetail.runAll.title": "按依赖顺序运行子任务",
+ "taskDetail.runCollapse": "收起本轮",
+ "taskDetail.runExpand": "展开本轮",
"taskDetail.runFollowUp": "追问",
"taskDetail.runFollowUpPlaceholder": "对这次运行追问...",
"taskDetail.runNow": "立即运行",
"taskDetail.runTask": "运行",
+ "taskDetail.runTrigger.goal": "目标驱动",
+ "taskDetail.runTrigger.heartbeat": "心跳触发",
+ "taskDetail.runTrigger.schedule": "定时触发",
+ "taskDetail.runVerify.checklist": "验收检查项",
+ "taskDetail.runVerify.errored": "验证异常",
+ "taskDetail.runVerify.failed": "未通过",
+ "taskDetail.runVerify.passed": "已通过",
+ "taskDetail.runVerify.pending": "待验证",
+ "taskDetail.runVerify.round": "第 {{index}} 轮",
+ "taskDetail.runVerify.running": "验证中",
"taskDetail.saveModelConfig": "保存",
"taskDetail.sendFollowUp": "发送追加消息",
"taskDetail.status.backlog": "待办",
diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.json
index 1da14214b15..26d46c21814 100644
--- a/locales/zh-CN/plugin.json
+++ b/locales/zh-CN/plugin.json
@@ -416,6 +416,7 @@
"builtins.lobe-skills.apiName.searchSkill": "搜索技能",
"builtins.lobe-skills.title": "技能",
"builtins.lobe-task.apiName.addTaskComment": "添加评论",
+ "builtins.lobe-task.apiName.createGoal": "启动目标",
"builtins.lobe-task.apiName.createTask": "创建任务",
"builtins.lobe-task.apiName.createTasks": "批量创建任务",
"builtins.lobe-task.apiName.deleteTask": "删除任务",
@@ -445,6 +446,40 @@
"builtins.lobe-task.edit.unblocks": "移除依赖",
"builtins.lobe-task.field.description": "描述",
"builtins.lobe-task.field.instruction": "指令",
+ "builtins.lobe-task.goal.add": "添加",
+ "builtins.lobe-task.goal.addCriterion": "添加验收标准",
+ "builtins.lobe-task.goal.cancel": "取消",
+ "builtins.lobe-task.goal.costBudget": "总成本预算",
+ "builtins.lobe-task.goal.criteria": "验收标准",
+ "builtins.lobe-task.goal.criterionTitle": "标题",
+ "builtins.lobe-task.goal.editCriterion": "编辑验收标准 C{{seq}}",
+ "builtins.lobe-task.goal.instruction": "描述明确的通过条件和所需证据",
+ "builtins.lobe-task.goal.judgePrompt": "判定说明",
+ "builtins.lobe-task.goal.optional": "可选",
+ "builtins.lobe-task.goal.phase.accepted": "已验收",
+ "builtins.lobe-task.goal.phase.awaitingDecision": "未通过 · 待你定夺",
+ "builtins.lobe-task.goal.phase.awaitingReview": "待你验收",
+ "builtins.lobe-task.goal.phase.closed": "已关闭",
+ "builtins.lobe-task.goal.phase.errored": "验证异常",
+ "builtins.lobe-task.goal.phase.rejected": "已打回",
+ "builtins.lobe-task.goal.phase.repairing": "修复中",
+ "builtins.lobe-task.goal.phase.verifying": "验证中",
+ "builtins.lobe-task.goal.required": "必要",
+ "builtins.lobe-task.goal.requiredHint": "必要 — 此项不通过则目标无法达成",
+ "builtins.lobe-task.goal.roundBudget": "循环预算",
+ "builtins.lobe-task.goal.roundsUnit": "轮",
+ "builtins.lobe-task.goal.running": "第 1 轮 · 正在执行",
+ "builtins.lobe-task.goal.runningHint": "本轮完成后将自动验收 {{count}} 项标准",
+ "builtins.lobe-task.goal.save": "保存",
+ "builtins.lobe-task.goal.script": "验证脚本或函数",
+ "builtins.lobe-task.goal.sectionBudget": "预算",
+ "builtins.lobe-task.goal.sectionInstruction": "任务指令",
+ "builtins.lobe-task.goal.settledHint": "点击查看验收详情",
+ "builtins.lobe-task.goal.uncapped": "不限",
+ "builtins.lobe-task.goal.verifier.agent": "Agent 验收",
+ "builtins.lobe-task.goal.verifier.llm": "模型判定",
+ "builtins.lobe-task.goal.verifier.program": "程序检测",
+ "builtins.lobe-task.goal.verifierType": "验收方式",
"builtins.lobe-task.run.continueTopic": "继续话题",
"builtins.lobe-task.run.prompt": "附加提示",
"builtins.lobe-task.run.topic": "话题",
diff --git a/locales/zh-CN/verify.json b/locales/zh-CN/verify.json
index 2818310a061..e062e2a4d20 100644
--- a/locales/zh-CN/verify.json
+++ b/locales/zh-CN/verify.json
@@ -68,11 +68,13 @@
"acceptance.checks.iterated": "迭代 {{count}} 次",
"acceptance.checks.iteratedHint": "同一验收对象跨 {{count}} 轮迭代,以最后一轮为准;演进过程见「迭代历史」",
"acceptance.checks.iterationHistory": "迭代历史({{count}} 轮)",
+ "acceptance.checks.judgeReason": "判定依据",
"acceptance.checks.notRequired": "非阻断",
"acceptance.checks.notRequiredHint": "required = false:失败不阻止验收",
"acceptance.checks.rerun": "验证 {{count}} 轮",
"acceptance.checks.rerunHint": "同一检查项在 {{count}} 轮各验证一次,以最后一轮为准",
"acceptance.checks.title": "验收检查清单",
+ "acceptance.checks.viewTrace": "查看验证过程",
"acceptance.detail.suggestion": "建议",
"acceptance.error.description": "请检查网络连接后重试。",
"acceptance.error.title": "无法加载验收信息",
diff --git a/packages/builtin-tool-task/src/client/Inspector/CreateGoal/index.tsx b/packages/builtin-tool-task/src/client/Inspector/CreateGoal/index.tsx
new file mode 100644
index 00000000000..4ffc01e99d2
--- /dev/null
+++ b/packages/builtin-tool-task/src/client/Inspector/CreateGoal/index.tsx
@@ -0,0 +1,33 @@
+'use client';
+
+import type { BuiltinInspectorProps } from '@lobechat/types';
+import { cx } from 'antd-style';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { inspectorTextStyles, shinyTextStyles } from '@/styles';
+
+import type { CreateGoalParams, CreateGoalState } from '../../../types';
+
+const CreateGoalInspector = memo<BuiltinInspectorProps<CreateGoalParams, CreateGoalState>>(
+ ({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {
+ const { t } = useTranslation('plugin');
+ const name = args?.name || partialArgs?.name || pluginState?.name;
+
+ return (
+ <div
+ className={cx(
+ inspectorTextStyles.root,
+ (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,
+ )}
+ >
+ <span>{t('builtins.lobe-task.apiName.createGoal')}</span>
+ {name && <span> · {name}</span>}
+ </div>
+ );
+ },
+);
+
+CreateGoalInspector.displayName = 'CreateGoalInspector';
+
+export default CreateGoalInspector;
diff --git a/packages/builtin-tool-task/src/client/Inspector/index.ts b/packages/builtin-tool-task/src/client/Inspector/index.ts
index 4c4487bf4b2..1650cad098c 100644
--- a/packages/builtin-tool-task/src/client/Inspector/index.ts
+++ b/packages/builtin-tool-task/src/client/Inspector/index.ts
@@ -1,6 +1,7 @@
import type { BuiltinInspector } from '@lobechat/types';
import { TaskApiName } from '../../types';
+import CreateGoalInspector from './CreateGoal';
import { CreateTaskInspector } from './CreateTask';
import { CreateTasksInspector } from './CreateTasks';
import { DeleteTaskInspector } from './DeleteTask';
@@ -27,6 +28,7 @@ import { ViewTaskInspector } from './ViewTask';
export const TaskInspectors: Record<string, BuiltinInspector> = {
[TaskApiName.addTaskComment]: AddTaskCommentInspector as BuiltinInspector,
[TaskApiName.createTask]: CreateTaskInspector as BuiltinInspector,
+ [TaskApiName.createGoal]: CreateGoalInspector as BuiltinInspector,
[TaskApiName.createTasks]: CreateTasksInspector as BuiltinInspector,
[TaskApiName.deleteTask]: DeleteTaskInspector as BuiltinInspector,
[TaskApiName.deleteTaskComment]: DeleteTaskCommentInspector as BuiltinInspector,
@@ -41,6 +43,7 @@ export const TaskInspectors: Record<string, BuiltinInspector> = {
[TaskApiName.viewTask]: ViewTaskInspector as BuiltinInspector,
};
+export { default as CreateGoalInspector } from './CreateGoal';
export { CreateTaskInspector } from './CreateTask';
export { CreateTasksInspector } from './CreateTasks';
export { DeleteTaskInspector } from './DeleteTask';
diff --git a/packages/builtin-tool-task/src/client/Intervention/CreateGoal.tsx b/packages/builtin-tool-task/src/client/Intervention/CreateGoal.tsx
new file mode 100644
index 00000000000..5b4a2b2d1bb
--- /dev/null
+++ b/packages/builtin-tool-task/src/client/Intervention/CreateGoal.tsx
@@ -0,0 +1,389 @@
+'use client';
+
+import type { BuiltinInterventionProps } from '@lobechat/types';
+import {
+ ReactCodeblockPlugin,
+ ReactCodePlugin,
+ ReactHRPlugin,
+ ReactLinkPlugin,
+ ReactListPlugin,
+ ReactTablePlugin,
+} from '@lobehub/editor';
+import { Editor, useEditor } from '@lobehub/editor/react';
+import { ActionIcon, Block, Flexbox, Icon, Input, Text } from '@lobehub/ui';
+import { Button } from '@lobehub/ui/base-ui';
+import { InputNumber } from 'antd';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { ChevronRight, Pencil, Plus, Trash2 } from 'lucide-react';
+import { memo, useCallback, useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { CreateGoalParams, GoalCriterionDraft } from '../../types';
+import { openCriterionEditModal } from './CriterionEditModal';
+
+const styles = createStaticStyles(({ css }) => ({
+ criterion: css`
+ cursor: pointer;
+ padding-block: 7px;
+ padding-inline: 10px;
+
+ & + & {
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+ }
+
+ &:hover {
+ background: ${cssVar.colorFillQuaternary};
+ }
+ `,
+ header: css`
+ position: sticky;
+ z-index: 2;
+
+ /* Chrome measures sticky against the scroller's CONTENT box, so top: 0
+ would pin 8px below where the header actually rests (the root cancels
+ that padding) and shove it down. -8px makes the pinned and resting
+ positions identical — the title simply never moves. */
+ inset-block-start: -8px;
+
+ padding-block: 4px 2px;
+
+ background: ${cssVar.colorBgContainer};
+ `,
+ instructionEditor: css`
+ padding-block: 8px;
+ padding-inline: 12px;
+ border-radius: ${cssVar.borderRadiusLG};
+ background: ${cssVar.colorFillQuaternary};
+
+ /* The editor defaults to a document-reading 16px; inside a confirmation
+ card the instruction is one field among several, so it matches the
+ criteria rows rather than dwarfing them. */
+ &,
+ & * {
+ font-size: 13px;
+ line-height: 1.65;
+ }
+ `,
+ list: css`
+ overflow: hidden;
+ padding: 0;
+ `,
+ criterionTitle: css`
+ font-size: 13px;
+ `,
+ optional: css`
+ flex: none;
+
+ padding-block: 2px;
+ padding-inline: 7px;
+ border-radius: 6px;
+
+ font-size: 11px;
+ color: ${cssVar.colorTextSecondary};
+
+ background: ${cssVar.colorFillSecondary};
+ `,
+ /**
+ * Cancels the intervention scroller's own top padding. It has to sit on the
+ * card root, not on the sticky header: a sticky box is clamped to its
+ * containing block, so pulling the header alone just gets clamped back and
+ * leaves that strip for content to scroll through.
+ */
+ root: css`
+ margin-block-start: -8px;
+ `,
+ required: css`
+ flex: none;
+
+ padding-block: 2px;
+ padding-inline: 7px;
+ border-radius: 6px;
+
+ font-size: 11px;
+ color: ${cssVar.colorInfo};
+
+ background: ${cssVar.colorInfoBg};
+ `,
+ section: css`
+ padding-block: 8px;
+
+ & + & {
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+ }
+ `,
+ sectionHeader: css`
+ cursor: pointer;
+ user-select: none;
+ `,
+ sectionLabel: css`
+ font-size: 12px;
+ font-weight: 500;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ seq: css`
+ font-size: 11px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ titleInput: css`
+ padding-block: 2px;
+ padding-inline: 0;
+ font-size: 15px;
+ font-weight: 600;
+ `,
+}));
+
+interface SectionProps {
+ children: React.ReactNode;
+ extra?: React.ReactNode;
+ label: string;
+ onToggle: () => void;
+ open: boolean;
+}
+
+/**
+ * One collapsible module. The plan card is three distinct decisions (what to
+ * do, how to judge it, how much to spend) — each gets a header the user can
+ * fold away, instead of three flat blocks bleeding into each other.
+ */
+const Section = memo<SectionProps>(({ children, extra, label, onToggle, open }) => (
+ <Flexbox className={styles.section} gap={7}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.sectionHeader}
+ gap={6}
+ onClick={onToggle}
+ >
+ <Icon
+ color={cssVar.colorTextQuaternary}
+ icon={ChevronRight}
+ size={13}
+ style={{ transform: open ? 'rotate(90deg)' : 'none', transition: 'transform 0.2s' }}
+ />
+ <Text className={styles.sectionLabel}>{label}</Text>
+ {extra}
+ </Flexbox>
+ {open && children}
+ </Flexbox>
+));
+
+Section.displayName = 'CreateGoalSection';
+
+const CreateGoalIntervention = memo<BuiltinInterventionProps<CreateGoalParams>>(
+ ({ args, onArgsChange, registerBeforeApprove }) => {
+ const { t } = useTranslation('plugin');
+ const editor = useEditor();
+ const [openSections, setOpenSections] = useState({
+ budget: true,
+ criteria: true,
+ instruction: true,
+ });
+ const patch = (value: Partial<CreateGoalParams>) => onArgsChange?.({ ...args, ...value });
+ const openEditModal = (index: number) =>
+ openCriterionEditModal({
+ criterion: args.criteria[index],
+ onSubmit: (value) => updateCriterion(index, value),
+ seq: index + 1,
+ });
+ const updateCriterion = (index: number, value: Partial<GoalCriterionDraft>) =>
+ patch({
+ criteria: args.criteria.map((item, itemIndex) =>
+ itemIndex === index ? { ...item, ...value } : item,
+ ),
+ });
+ const toggleSection = (key: keyof typeof openSections) =>
+ setOpenSections((previous) => ({ ...previous, [key]: !previous[key] }));
+ // The instruction lives in the rich editor; args carry its persisted
+ // draft. The editor mounts once from the persisted value (a changing
+ // `content` prop would reset it mid-edit), while edits flow back through
+ // a debounced onArgsChange — the same DB-backed draft path every other
+ // field uses, so a refresh loses at most the debounce window. The
+ // before-approve flush closes even that window.
+ const [initialInstruction] = useState(args.instruction);
+ const persistTimerRef = useRef<ReturnType<typeof setTimeout>>(null);
+
+ const saveInstruction = useCallback(async () => {
+ if (persistTimerRef.current) clearTimeout(persistTimerRef.current);
+ if (!editor) return;
+ const markdown = String(editor.getDocument('markdown') ?? '');
+ await onArgsChange?.({ ...args, instruction: markdown });
+ }, [editor, onArgsChange, args]);
+ const saveInstructionRef = useRef(saveInstruction);
+ saveInstructionRef.current = saveInstruction;
+
+ const handleInstructionChange = useCallback(() => {
+ if (persistTimerRef.current) clearTimeout(persistTimerRef.current);
+ persistTimerRef.current = setTimeout(() => void saveInstructionRef.current(), 800);
+ }, []);
+
+ useEffect(
+ () => registerBeforeApprove?.('createGoal', () => saveInstructionRef.current()),
+ [registerBeforeApprove],
+ );
+
+ return (
+ <Flexbox className={styles.root}>
+ <Flexbox className={styles.header}>
+ <Input
+ className={styles.titleInput}
+ value={args.name}
+ variant={'borderless'}
+ onChange={(event) => patch({ name: event.target.value })}
+ />
+ </Flexbox>
+
+ <Section
+ label={t('builtins.lobe-task.goal.sectionInstruction')}
+ open={openSections.instruction}
+ onToggle={() => toggleSection('instruction')}
+ >
+ <Flexbox className={styles.instructionEditor}>
+ <Editor
+ content={initialInstruction}
+ editor={editor}
+ type={'markdown'}
+ plugins={[
+ ReactCodePlugin,
+ ReactCodeblockPlugin,
+ ReactHRPlugin,
+ ReactLinkPlugin,
+ ReactListPlugin,
+ ReactTablePlugin,
+ ]}
+ onTextChange={handleInstructionChange}
+ />
+ </Flexbox>
+ </Section>
+
+ <Section
+ label={t('builtins.lobe-task.goal.criteria')}
+ open={openSections.criteria}
+ extra={
+ <Text as={'span'} className={styles.seq}>
+ {args.criteria.length}
+ </Text>
+ }
+ onToggle={() => toggleSection('criteria')}
+ >
+ <Flexbox gap={7}>
+ <Block className={styles.list} variant={'outlined'}>
+ {args.criteria.map((criterion, index) => (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.criterion}
+ gap={8}
+ key={index}
+ onClick={() => openEditModal(index)}
+ >
+ <Text as={'span'} className={styles.seq}>
+ C{index + 1}
+ </Text>
+ {/* Read-only on purpose. A focusable input sitting in a dense
+ list is one stray click away from silently rewriting a
+ criterion; edits belong in the modal, where they are
+ deliberate and cancellable. */}
+ <Text ellipsis className={styles.criterionTitle} style={{ flex: 1 }}>
+ {criterion.title}
+ </Text>
+ <Button
+ className={(criterion.required ?? true) ? styles.required : styles.optional}
+ size={'small'}
+ type={'text'}
+ onClick={(event) => {
+ event.stopPropagation();
+ updateCriterion(index, { required: !(criterion.required ?? true) });
+ }}
+ >
+ {(criterion.required ?? true)
+ ? t('builtins.lobe-task.goal.required')
+ : t('builtins.lobe-task.goal.optional')}
+ </Button>
+ <ActionIcon
+ icon={Pencil}
+ size={'small'}
+ title={t('builtins.lobe-task.goal.editCriterion', { seq: index + 1 })}
+ onClick={(event) => {
+ event.stopPropagation();
+ openEditModal(index);
+ }}
+ />
+ <ActionIcon
+ icon={Trash2}
+ size={'small'}
+ onClick={(event) => {
+ event.stopPropagation();
+ patch({
+ criteria: args.criteria.filter((_, itemIndex) => itemIndex !== index),
+ });
+ }}
+ />
+ </Flexbox>
+ ))}
+ </Block>
+ <Flexbox horizontal>
+ <Button
+ icon={<Icon icon={Plus} />}
+ size={'small'}
+ type={'text'}
+ onClick={() =>
+ openCriterionEditModal({
+ criterion: {
+ onFail: 'auto_repair',
+ required: true,
+ title: '',
+ verifierType: 'agent',
+ },
+ isNew: true,
+ onSubmit: (value) => patch({ criteria: [...args.criteria, value] }),
+ seq: args.criteria.length + 1,
+ })
+ }
+ >
+ {t('builtins.lobe-task.goal.addCriterion')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ </Section>
+
+ <Section
+ label={t('builtins.lobe-task.goal.sectionBudget')}
+ open={openSections.budget}
+ onToggle={() => toggleSection('budget')}
+ >
+ <Flexbox horizontal gap={24}>
+ <Flexbox gap={4}>
+ <Text className={styles.seq}>{t('builtins.lobe-task.goal.roundBudget')}</Text>
+ <InputNumber
+ min={2}
+ size={'small'}
+ style={{ width: 120 }}
+ suffix={t('builtins.lobe-task.goal.roundsUnit')}
+ value={args.maxIterations ?? undefined}
+ variant={'filled'}
+ onChange={(value) => patch({ maxIterations: value })}
+ />
+ </Flexbox>
+ <Flexbox gap={4}>
+ <Text className={styles.seq}>{t('builtins.lobe-task.goal.costBudget')}</Text>
+ <InputNumber
+ min={0}
+ placeholder={t('builtins.lobe-task.goal.uncapped')}
+ prefix={'$'}
+ size={'small'}
+ style={{ width: 120 }}
+ value={args.maxTotalCost ?? undefined}
+ variant={'filled'}
+ onChange={(value) => patch({ maxTotalCost: value })}
+ />
+ </Flexbox>
+ </Flexbox>
+ </Section>
+ </Flexbox>
+ );
+ },
+);
+
+CreateGoalIntervention.displayName = 'CreateGoalIntervention';
+
+export default CreateGoalIntervention;
diff --git a/packages/builtin-tool-task/src/client/Intervention/CriterionEditModal.tsx b/packages/builtin-tool-task/src/client/Intervention/CriterionEditModal.tsx
new file mode 100644
index 00000000000..ab232255b9d
--- /dev/null
+++ b/packages/builtin-tool-task/src/client/Intervention/CriterionEditModal.tsx
@@ -0,0 +1,125 @@
+'use client';
+
+import { Flexbox, Input, Text, TextArea } from '@lobehub/ui';
+import {
+ Button,
+ createModal,
+ type ModalInstance,
+ Select,
+ Switch,
+ useModalContext,
+} from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { GoalCriterionDraft } from '../../types';
+
+interface CriterionEditContentProps {
+ criterion: GoalCriterionDraft;
+ /** Create flow: the criterion only exists once it is saved. */
+ isNew?: boolean;
+ onSubmit: (value: GoalCriterionDraft) => void;
+ seq: number;
+}
+
+/**
+ * A criterion's judge prompt is the thing the whole loop is scored against, so
+ * it gets a real editing surface rather than a row that grows a textarea in
+ * place — the same modal treatment the acceptance checklist already uses.
+ */
+const CriterionEditContent = memo<CriterionEditContentProps>(({ criterion, isNew, onSubmit }) => {
+ const { t: tp } = useTranslation('plugin');
+ const { close } = useModalContext();
+ const [draft, setDraft] = useState<GoalCriterionDraft>(criterion);
+ const verifierType = draft.verifierType ?? 'agent';
+ const isProgram = verifierType === 'program';
+
+ const patch = (value: Partial<GoalCriterionDraft>) =>
+ setDraft((previous) => ({ ...previous, ...value }));
+
+ const handleSave = () => {
+ if (!draft.title.trim()) return;
+ onSubmit({ ...draft, title: draft.title.trim() });
+ close();
+ };
+
+ return (
+ <Flexbox gap={16}>
+ <Flexbox gap={6}>
+ <Text fontSize={12} type={'secondary'}>
+ {tp('builtins.lobe-task.goal.criterionTitle')}
+ </Text>
+ <Input value={draft.title} onChange={(event) => patch({ title: event.target.value })} />
+ </Flexbox>
+
+ <Flexbox gap={6}>
+ <Text fontSize={12} type={'secondary'}>
+ {tp('builtins.lobe-task.goal.verifierType')}
+ </Text>
+ <Select
+ value={verifierType}
+ options={[
+ { label: tp('builtins.lobe-task.goal.verifier.agent'), value: 'agent' },
+ { label: tp('builtins.lobe-task.goal.verifier.llm'), value: 'llm' },
+ { label: tp('builtins.lobe-task.goal.verifier.program'), value: 'program' },
+ ]}
+ onChange={(value) => patch({ verifierType: value as GoalCriterionDraft['verifierType'] })}
+ />
+ </Flexbox>
+
+ <Flexbox gap={6}>
+ <Text fontSize={12} type={'secondary'}>
+ {isProgram
+ ? tp('builtins.lobe-task.goal.script')
+ : tp('builtins.lobe-task.goal.judgePrompt')}
+ </Text>
+ {isProgram ? (
+ <TextArea
+ autoSize={{ maxRows: 8, minRows: 3 }}
+ value={String(draft.verifierConfig?.command ?? '')}
+ onChange={(event) =>
+ patch({ verifierConfig: { ...draft.verifierConfig, command: event.target.value } })
+ }
+ />
+ ) : (
+ <TextArea
+ autoSize={{ maxRows: 10, minRows: 4 }}
+ placeholder={tp('builtins.lobe-task.goal.instruction')}
+ value={draft.instruction ?? ''}
+ onChange={(event) => patch({ instruction: event.target.value })}
+ />
+ )}
+ </Flexbox>
+
+ <Flexbox horizontal align={'center'} gap={10}>
+ <Switch
+ checked={draft.required ?? true}
+ size={'small'}
+ onChange={(checked) => patch({ required: checked })}
+ />
+ <Text fontSize={13}>{tp('builtins.lobe-task.goal.requiredHint')}</Text>
+ </Flexbox>
+
+ <Flexbox horizontal gap={8} justify={'flex-end'}>
+ <Button onClick={close}>{tp('builtins.lobe-task.goal.cancel')}</Button>
+ <Button disabled={!draft.title.trim()} type={'primary'} onClick={handleSave}>
+ {tp(isNew ? 'builtins.lobe-task.goal.add' : 'builtins.lobe-task.goal.save')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+CriterionEditContent.displayName = 'GoalCriterionEditContent';
+
+export const openCriterionEditModal = (props: CriterionEditContentProps): ModalInstance =>
+ createModal({
+ content: <CriterionEditContent {...props} />,
+ footer: null,
+ maskClosable: true,
+ title: props.isNew
+ ? t('builtins.lobe-task.goal.addCriterion', { ns: 'plugin' })
+ : t('builtins.lobe-task.goal.editCriterion', { ns: 'plugin', seq: props.seq }),
+ width: 'min(90vw, 560px)',
+ });
diff --git a/packages/builtin-tool-task/src/client/Intervention/index.ts b/packages/builtin-tool-task/src/client/Intervention/index.ts
new file mode 100644
index 00000000000..8ed16cbb568
--- /dev/null
+++ b/packages/builtin-tool-task/src/client/Intervention/index.ts
@@ -0,0 +1,8 @@
+import type { BuiltinIntervention } from '@lobechat/types';
+
+import { TaskApiName } from '../../types';
+import CreateGoalIntervention from './CreateGoal';
+
+export const TaskInterventions: Record<string, BuiltinIntervention> = {
+ [TaskApiName.createGoal]: CreateGoalIntervention as BuiltinIntervention,
+};
diff --git a/packages/builtin-tool-task/src/client/Render/CreateGoal/index.tsx b/packages/builtin-tool-task/src/client/Render/CreateGoal/index.tsx
new file mode 100644
index 00000000000..89e75340439
--- /dev/null
+++ b/packages/builtin-tool-task/src/client/Render/CreateGoal/index.tsx
@@ -0,0 +1,200 @@
+'use client';
+
+import type { BuiltinRenderProps } from '@lobechat/types';
+import { Flexbox, Icon, Text } from '@lobehub/ui';
+import { cssVar } from 'antd-style';
+import type { TFunction } from 'i18next';
+import {
+ AlertTriangle,
+ CheckCheck,
+ CircleSlash,
+ CircleX,
+ LoaderCircle,
+ RefreshCw,
+ RotateCcw,
+ Stamp,
+ Target,
+} from 'lucide-react';
+import { memo, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useAcceptanceBySubject } from '@/features/Verify';
+import { acceptanceOverviewPath } from '@/features/Verify/Acceptance/routes';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+
+import type { CreateGoalParams, CreateGoalState } from '../../../types';
+import { TaskResultCard } from '../shared';
+
+const formatElapsed = (milliseconds: number) => {
+ const seconds = Math.max(0, Math.floor(milliseconds / 1000));
+ const minutes = Math.floor(seconds / 60);
+ return `${minutes}:${String(seconds % 60).padStart(2, '0')}`;
+};
+
+/**
+ * How the goal's live state reads on the conversation card.
+ *
+ * `settled` marks the states where the loop has stopped moving on its own —
+ * they stop the timer and the spinner, and the row becomes a way into the
+ * acceptance, because from here the next move is the user's.
+ */
+const PHASE_META = {
+ accepted: { color: cssVar.colorSuccess, icon: CheckCheck, settled: true },
+ awaitingDecision: { color: cssVar.colorError, icon: AlertTriangle, settled: true },
+ awaitingReview: { color: cssVar.colorWarning, icon: Stamp, settled: true },
+ closed: { color: cssVar.colorTextTertiary, icon: CircleSlash, settled: true },
+ errored: { color: cssVar.colorError, icon: CircleX, settled: true },
+ rejected: { color: cssVar.colorError, icon: RotateCcw, settled: false },
+ repairing: { color: cssVar.colorWarning, icon: RefreshCw, settled: false },
+ running: { color: cssVar.colorInfo, icon: LoaderCircle, settled: false },
+ verifying: { color: cssVar.colorInfo, icon: LoaderCircle, settled: false },
+} as const;
+
+type PhaseKey = keyof typeof PHASE_META;
+
+/** Literal keys, so a renamed or missing phase label fails type-check. */
+const phaseLabel = (t: TFunction<'plugin'>, phase: PhaseKey): string => {
+ switch (phase) {
+ case 'accepted': {
+ return t('builtins.lobe-task.goal.phase.accepted');
+ }
+ case 'awaitingDecision': {
+ return t('builtins.lobe-task.goal.phase.awaitingDecision');
+ }
+ case 'awaitingReview': {
+ return t('builtins.lobe-task.goal.phase.awaitingReview');
+ }
+ case 'closed': {
+ return t('builtins.lobe-task.goal.phase.closed');
+ }
+ case 'errored': {
+ return t('builtins.lobe-task.goal.phase.errored');
+ }
+ case 'rejected': {
+ return t('builtins.lobe-task.goal.phase.rejected');
+ }
+ case 'repairing': {
+ return t('builtins.lobe-task.goal.phase.repairing');
+ }
+ case 'verifying': {
+ return t('builtins.lobe-task.goal.phase.verifying');
+ }
+ case 'running': {
+ return t('builtins.lobe-task.goal.running');
+ }
+ }
+};
+
+/**
+ * The card reads the acceptance aggregate directly instead of waiting for the
+ * loop to push a phase onto this tool message. A push can silently never
+ * arrive (it needs the task to remember which tool call spawned it); the
+ * aggregate is the same record the task page and the acceptance page read, so
+ * the conversation can never disagree with them.
+ */
+const resolvePhase = (status?: string, latestRunStatus?: string | null): PhaseKey => {
+ switch (status) {
+ case 'accepted': {
+ return 'accepted';
+ }
+ case 'closed': {
+ return 'closed';
+ }
+ case 'delivered': {
+ return latestRunStatus === 'passed' ? 'awaitingReview' : 'awaitingDecision';
+ }
+ case 'errored': {
+ return 'errored';
+ }
+ case 'rejected': {
+ return 'rejected';
+ }
+ case 'repairing': {
+ return 'repairing';
+ }
+ case 'verifying': {
+ return 'verifying';
+ }
+ // No aggregate yet, or one that only holds the plan: the round is still
+ // producing the delivery.
+ default: {
+ return 'running';
+ }
+ }
+};
+
+const CreateGoalRender = memo<BuiltinRenderProps<CreateGoalParams, CreateGoalState>>(
+ ({ args, pluginState }) => {
+ const { t } = useTranslation('plugin');
+ const navigate = useWorkspaceAwareNavigate();
+ const identifier = pluginState?.identifier;
+ const [now, setNow] = useState(() => Date.now());
+
+ const { data: acceptance, mutate } = useAcceptanceBySubject(
+ 'task',
+ pluginState?.taskId ?? null,
+ );
+ const phase = resolvePhase(acceptance?.status, acceptance?.latestRunStatus);
+ const meta = PHASE_META[phase];
+
+ // The elapsed clock and the poll share one timer: both exist only while the
+ // goal is still moving, and both stop the moment it settles.
+ useEffect(() => {
+ if (meta.settled) return;
+ const timer = window.setInterval(() => {
+ setNow(Date.now());
+ void mutate();
+ }, 1000);
+ return () => window.clearInterval(timer);
+ }, [meta.settled, mutate]);
+
+ if (!pluginState?.success || !identifier) return null;
+
+ const openAcceptance = acceptance
+ ? () => navigate(acceptanceOverviewPath(acceptance.id))
+ : undefined;
+
+ return (
+ <TaskResultCard
+ icon={Target}
+ iconColor={cssVar.colorTextSecondary}
+ identifier={identifier}
+ title={pluginState.name ?? args?.name}
+ >
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={8}
+ style={openAcceptance ? { cursor: 'pointer' } : undefined}
+ onClick={openAcceptance}
+ >
+ <Icon
+ color={meta.color}
+ icon={meta.icon}
+ size={15}
+ spin={phase === 'running' || phase === 'verifying' || phase === 'repairing'}
+ />
+ <Flexbox flex={1} gap={2}>
+ <Flexbox horizontal align={'center'} justify={'space-between'}>
+ <Text fontSize={13}>{phaseLabel(t, phase)}</Text>
+ {!meta.settled && (
+ <Text code fontSize={12} type={'secondary'}>
+ {formatElapsed(now - new Date(pluginState.startedAt ?? Date.now()).getTime())}
+ </Text>
+ )}
+ </Flexbox>
+ <Text fontSize={12} type={'secondary'}>
+ {meta.settled
+ ? t('builtins.lobe-task.goal.settledHint')
+ : t('builtins.lobe-task.goal.runningHint', { count: args?.criteria?.length ?? 0 })}
+ </Text>
+ </Flexbox>
+ </Flexbox>
+ </TaskResultCard>
+ );
+ },
+);
+
+CreateGoalRender.displayName = 'CreateGoalRender';
+
+export default CreateGoalRender;
diff --git a/packages/builtin-tool-task/src/client/Render/index.ts b/packages/builtin-tool-task/src/client/Render/index.ts
index 5267fa076d9..09081bcacae 100644
--- a/packages/builtin-tool-task/src/client/Render/index.ts
+++ b/packages/builtin-tool-task/src/client/Render/index.ts
@@ -1,6 +1,7 @@
import type { BuiltinRender } from '@lobechat/types';
import { TaskApiName } from '../../types';
+import CreateGoalRender from './CreateGoal';
import CreateTaskRender from './CreateTask';
import CreateTasksRender from './CreateTasks';
import EditTaskRender from './EditTask';
@@ -17,6 +18,7 @@ import SetTaskVerifyRender from './SetTaskVerify';
*/
export const TaskRenders: Record<string, BuiltinRender> = {
[TaskApiName.createTask]: CreateTaskRender as BuiltinRender,
+ [TaskApiName.createGoal]: CreateGoalRender as BuiltinRender,
[TaskApiName.createTasks]: CreateTasksRender as BuiltinRender,
[TaskApiName.editTask]: EditTaskRender as BuiltinRender,
[TaskApiName.runTask]: RunTaskRender as BuiltinRender,
@@ -24,6 +26,7 @@ export const TaskRenders: Record<string, BuiltinRender> = {
[TaskApiName.setTaskVerify]: SetTaskVerifyRender as BuiltinRender,
};
+export { default as CreateGoalRender } from './CreateGoal';
export { default as CreateTaskRender } from './CreateTask';
export { default as CreateTasksRender } from './CreateTasks';
export { default as EditTaskRender } from './EditTask';
diff --git a/packages/builtin-tool-task/src/client/executor/index.ts b/packages/builtin-tool-task/src/client/executor/index.ts
index 3244d695ecb..9dd95f00bac 100644
--- a/packages/builtin-tool-task/src/client/executor/index.ts
+++ b/packages/builtin-tool-task/src/client/executor/index.ts
@@ -21,6 +21,7 @@ import debug from 'debug';
import { getActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
import { taskService } from '@/services/task';
+import { verifyService } from '@/services/verify';
import { getChatStoreState } from '@/store/chat';
import { getTaskStoreState } from '@/store/task';
import { findSubtaskParentId } from '@/store/task/slices/detail/reducer';
@@ -58,6 +59,7 @@ const LIST_MUTATING_APIS = new Set<string>([
TaskApiName.runTasks,
TaskApiName.setTaskSchedule,
TaskApiName.updateTaskStatus,
+ TaskApiName.createGoal,
]);
const DETAIL_MUTATING_APIS = new Set<string>([
@@ -70,6 +72,7 @@ const DETAIL_MUTATING_APIS = new Set<string>([
TaskApiName.updateTaskComment,
TaskApiName.updateTaskStatus,
TaskApiName.viewTask,
+ TaskApiName.createGoal,
]);
const extractIdentifier = (params: unknown, result: BuiltinToolResult): string | undefined => {
@@ -264,6 +267,121 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
ctx?: BuiltinToolContext,
): Promise<BuiltinToolResult> => this.#createTask(params, ctx);
+ createGoal = async (
+ params: {
+ criteria: Array<{
+ description?: string;
+ instruction?: string;
+ onFail?: 'auto_repair' | 'manual';
+ required?: boolean;
+ title: string;
+ verifierConfig?: Record<string, unknown>;
+ verifierType?: 'agent' | 'llm' | 'program';
+ }>;
+ instruction: string;
+ maxIterations?: number | null;
+ maxTotalCost?: number | null;
+ name: string;
+ },
+ ctx?: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ if (!ctx?.agentId) {
+ return {
+ content: 'A goal needs the current agent as its assignee.',
+ error: { message: 'agentId is required', type: 'MissingAgent' },
+ success: false,
+ };
+ }
+
+ const criteria = (params.criteria ?? []).filter((item) => item.title?.trim());
+ if (criteria.length === 0) {
+ return {
+ content: 'A goal needs at least one acceptance criterion.',
+ error: { message: 'criteria array is empty', type: 'EmptyCriteria' },
+ success: false,
+ };
+ }
+
+ const created = await this.#createTask(
+ {
+ assigneeAgentId: ctx.agentId,
+ instruction: params.instruction,
+ name: params.name,
+ },
+ ctx,
+ );
+ const identifier = (created.state as { identifier?: string } | undefined)?.identifier;
+ const taskId = (created.state as { taskId?: string } | undefined)?.taskId;
+ if (!created.success || !identifier) return created;
+
+ try {
+ const verifyCriteriaIds = await verifyService.createCriteria(
+ criteria.map((item) => ({
+ description: item.description,
+ instruction: item.verifierType === 'program' ? undefined : item.instruction,
+ onFail: item.onFail ?? 'auto_repair',
+ required: item.required ?? true,
+ title: item.title,
+ verifierConfig: item.verifierConfig,
+ verifierType: item.verifierType ?? 'agent',
+ })),
+ );
+ const maxIterations = Math.min(10, Math.max(2, params.maxIterations ?? 3));
+
+ // Both APIs merge into tasks.config with a read-modify-write cycle. Keep
+ // them sequential so the verify write cannot overwrite the goal metadata.
+ await taskService.updateConfig(identifier, {
+ goal: {
+ // `null` is the user's explicit "no cap"; `undefined` means they
+ // never chose, which must fall back to the documented default.
+ // Coercing the second into the first made an uncapped loop the
+ // default for every goal that omitted the field.
+ maxIterations: params.maxIterations,
+ maxTotalCost: params.maxTotalCost ?? null,
+ originTopicId: ctx.topicId ?? null,
+ },
+ });
+ await taskService.updateVerifyConfig({
+ id: identifier,
+ verify: {
+ enabled: true,
+ maxIterations,
+ requirement: params.name,
+ verifyCriteriaIds,
+ },
+ });
+
+ const started = await this.runTask({ identifier }, ctx);
+ if (!started.success) return started;
+ const state = started.state as {
+ operationId?: string;
+ topicId?: string;
+ };
+
+ return {
+ content: `Goal task ${identifier} created and started with ${criteria.length} acceptance criteria.`,
+ state: {
+ identifier,
+ name: params.name,
+ operationId: state.operationId,
+ startedAt: new Date().toISOString(),
+ success: true,
+ taskId,
+ topicId: state.topicId,
+ },
+ success: true,
+ };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : 'Failed to start goal';
+ return {
+ content: `Goal task ${identifier} was created but could not be started: ${message}`,
+ error: { message, type: 'CreateGoalFailed' },
+ state: { identifier, name: params.name, success: false },
+ success: false,
+ };
+ }
+ };
+
createTasks = async (
params: { tasks: CreateTaskParams[] },
ctx?: BuiltinToolContext,
diff --git a/packages/builtin-tool-task/src/client/index.ts b/packages/builtin-tool-task/src/client/index.ts
index 4fe1d6c2d9f..22612e4c0f6 100644
--- a/packages/builtin-tool-task/src/client/index.ts
+++ b/packages/builtin-tool-task/src/client/index.ts
@@ -1,6 +1,7 @@
// Inspector components (customized tool call headers)
export {
AddTaskCommentInspector,
+ CreateGoalInspector,
CreateTaskInspector,
CreateTasksInspector,
DeleteTaskCommentInspector,
@@ -14,9 +15,11 @@ export {
UpdateTaskStatusInspector,
ViewTaskInspector,
} from './Inspector';
+export { TaskInterventions } from './Intervention';
// Render components (read-only snapshots)
export {
+ CreateGoalRender,
CreateTaskRender,
CreateTasksRender,
EditTaskRender,
diff --git a/packages/builtin-tool-task/src/manifest.ts b/packages/builtin-tool-task/src/manifest.ts
index 5093a3855ee..7c395057334 100644
--- a/packages/builtin-tool-task/src/manifest.ts
+++ b/packages/builtin-tool-task/src/manifest.ts
@@ -10,6 +10,52 @@ export const TaskIdentifier = 'lobe-task';
export const TaskManifest: BuiltinToolManifest = {
api: [
// ==================== Task CRUD ====================
+ {
+ description:
+ 'Create and immediately start a goal-driven task with an editable acceptance plan. Use this only when the user explicitly starts their request with /goal. The call pauses for confirmation; after approval it creates the task, persists the acceptance criteria, enables bounded automatic repair, and runs the current agent in a task topic.',
+ humanIntervention: 'required',
+ name: TaskApiName.createGoal,
+ parameters: {
+ properties: {
+ criteria: {
+ description:
+ 'Concrete acceptance criteria derived from every explicit user requirement.',
+ items: {
+ properties: {
+ description: { type: 'string' },
+ instruction: {
+ description: 'Detailed judging instruction. Omit for program checks.',
+ type: 'string',
+ },
+ onFail: { enum: ['auto_repair', 'manual'], type: 'string' },
+ required: { type: 'boolean' },
+ title: { type: 'string' },
+ verifierConfig: { type: 'object' },
+ verifierType: { enum: ['agent', 'llm', 'program'], type: 'string' },
+ },
+ required: ['title'],
+ type: 'object',
+ },
+ type: 'array',
+ },
+ instruction: { description: 'Detailed task direction and constraints.', type: 'string' },
+ maxIterations: {
+ description:
+ 'Maximum automatic execution/repair rounds. Default 3, minimum 2. Null means no user-specified cap.',
+ type: ['number', 'null'],
+ },
+ maxTotalCost: {
+ description: 'Optional total USD budget. Null means no user-specified cap.',
+ type: ['number', 'null'],
+ },
+ name: { description: 'Short task title.', type: 'string' },
+ },
+ required: ['name', 'instruction', 'criteria'],
+ type: 'object',
+ },
+ renderDisplayControl: 'expand',
+ work: { action: 'create', resourceType: 'task' },
+ },
{
description:
'Create a new task. Optionally attach it as a subtask by specifying parentIdentifier.',
diff --git a/packages/builtin-tool-task/src/systemRole.ts b/packages/builtin-tool-task/src/systemRole.ts
index 8f621701c09..9d914821492 100644
--- a/packages/builtin-tool-task/src/systemRole.ts
+++ b/packages/builtin-tool-task/src/systemRole.ts
@@ -1,5 +1,6 @@
export const systemPrompt = `You have access to Task management tools. Use them to:
+- **createGoal**: When — and only when — the user's message starts with \`/goal\`, turn the request into one editable goal plan and call createGoal before doing any substantive work. Use the current agent implicitly. Derive one concrete criterion per explicit requirement, default failed criteria to auto_repair, default maxIterations to 3, and omit maxTotalCost unless the user set one. The user confirms or edits the complete plan before the task starts. Do not call createTask/setTaskVerify/runTask separately for a /goal request
- **createTask**: Create a new task. Use parentIdentifier to make it a subtask
- **createTasks**: Create multiple tasks in one call. Prefer this when you are about to create more than one task in a row (e.g. all subtasks under one parent, or all chapters of an outline) — it cuts the number of tool calls and keeps the batch atomic from the user's perspective
- **listTasks**: List tasks. With no filters, defaults to top-level unfinished tasks of the current agent in normal agent conversations, or top-level unfinished tasks across all agents in task manager conversations. If you provide any filter, omitted filters are not applied implicitly
diff --git a/packages/builtin-tool-task/src/types.ts b/packages/builtin-tool-task/src/types.ts
index b08d228c424..a105079fbdc 100644
--- a/packages/builtin-tool-task/src/types.ts
+++ b/packages/builtin-tool-task/src/types.ts
@@ -7,6 +7,9 @@ export const TaskApiName = {
/** Create a new task, optionally as a subtask of another task */
createTask: 'createTask',
+ /** Confirm and start a goal-driven task with automatic delivery acceptance */
+ createGoal: 'createGoal',
+
/** Create multiple tasks in a single call (batched) */
createTasks: 'createTasks',
@@ -72,6 +75,36 @@ export interface CreateTaskState {
success: boolean;
}
+// ==================== createGoal ====================
+
+export interface GoalCriterionDraft {
+ description?: string;
+ instruction?: string;
+ onFail?: 'auto_repair' | 'manual';
+ required?: boolean;
+ title: string;
+ verifierConfig?: Record<string, unknown>;
+ verifierType?: 'agent' | 'llm' | 'program';
+}
+
+export interface CreateGoalParams {
+ criteria: GoalCriterionDraft[];
+ instruction: string;
+ maxIterations?: number | null;
+ maxTotalCost?: number | null;
+ name: string;
+}
+
+export interface CreateGoalState {
+ identifier?: string;
+ name?: string;
+ operationId?: string;
+ startedAt?: string;
+ success: boolean;
+ taskId?: string;
+ topicId?: string;
+}
+
// ==================== createTasks (batch) ====================
export interface CreateTasksParams {
diff --git a/packages/builtin-tools/src/register.ts b/packages/builtin-tools/src/register.ts
index 4fa6b88d413..1d639c71de9 100644
--- a/packages/builtin-tools/src/register.ts
+++ b/packages/builtin-tools/src/register.ts
@@ -125,7 +125,12 @@ import {
SkillsManifest,
SkillsRenders,
} from '@lobechat/builtin-tool-skills/client';
-import { TaskInspectors, TaskManifest, TaskRenders } from '@lobechat/builtin-tool-task/client';
+import {
+ TaskInspectors,
+ TaskInterventions,
+ TaskManifest,
+ TaskRenders,
+} from '@lobechat/builtin-tool-task/client';
import {
UserInteractionIdentifier,
UserInteractionInspectors,
@@ -317,6 +322,7 @@ export const registerBuiltinToolSurfaces = (): void => {
[LocalSystemIdentifier]: LocalSystemInterventions as Record<string, BuiltinIntervention>,
[MemoryManifest.identifier]: MemoryInterventions as Record<string, BuiltinIntervention>,
[MessageManifest.identifier]: MessageInterventions as Record<string, BuiltinIntervention>,
+ [TaskManifest.identifier]: TaskInterventions as Record<string, BuiltinIntervention>,
[UserInteractionIdentifier]: UserInteractionInterventions as Record<
string,
BuiltinIntervention
diff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.ts
index 226ef30c9f3..0686e6dc971 100644
--- a/packages/database/src/models/agentOperation.ts
+++ b/packages/database/src/models/agentOperation.ts
@@ -1,5 +1,5 @@
import type { VerifyRunStatus } from '@lobechat/types';
-import { and, eq, gte, isNotNull, or, sql } from 'drizzle-orm';
+import { and, eq, gte, inArray, isNotNull, or, sql } from 'drizzle-orm';
import { today } from '@/utils/time';
@@ -249,6 +249,55 @@ export class AgentOperationModel {
return row ?? null;
}
+ /**
+ * Total USD cost of every operation bound to a task — the goal outer loop's
+ * budget meter. Only root (task-bound) operations carry `taskId`, and each
+ * root's `totalCost` scalar already includes its direct children's rollup
+ * (see `persistCompletion`), so this sum covers verify / repair sub-runs
+ * without walking parent chains. Re-derived on every call — exact regardless
+ * of how many times a round settles.
+ */
+ async sumCostByTask(taskId: string): Promise<number> {
+ const [row] = await this.db
+ .select({ totalCost: sql<string | null>`sum(${agentOperations.totalCost})` })
+ .from(agentOperations)
+ .where(and(eq(agentOperations.taskId, taskId), this.ownership()));
+
+ const parsed = Number(row?.totalCost ?? 0);
+ return Number.isFinite(parsed) ? parsed : 0;
+ }
+
+ /**
+ * Per-operation cost and token totals for a set of runs, keyed by operation.
+ *
+ * Feeds the goal round rail's audit hover: a round's block should be able to
+ * say what it actually spent, and asking per round would be one query per
+ * block. Each root's `totalCost` already rolls up its direct children, so no
+ * parent-chain walk is needed here either.
+ */
+ async findUsageByOperations(
+ operationIds: string[],
+ ): Promise<Map<string, { cost: number; tokens: number }>> {
+ const ids = [...new Set(operationIds.filter(Boolean))];
+ if (ids.length === 0) return new Map();
+
+ const rows = await this.db
+ .select({
+ id: agentOperations.id,
+ totalCost: agentOperations.totalCost,
+ totalTokens: agentOperations.totalTokens,
+ })
+ .from(agentOperations)
+ .where(and(inArray(agentOperations.id, ids), this.ownership()));
+
+ return new Map(
+ rows.map((row) => [
+ row.id,
+ { cost: Number(row.totalCost ?? 0) || 0, tokens: Number(row.totalTokens ?? 0) || 0 },
+ ]),
+ );
+ }
+
/**
* Load an operation together with its direct child operations (`callSubAgent`
* children / isolated group members) — the (at most) two-layer operation
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index 5d9cb952dbf..cddb4adb5c5 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -2794,6 +2794,22 @@ export class MessageModel {
}));
};
+ /**
+ * Resolve the tool result message id for a toolCallId — the stable identifier
+ * the model emitted for the call. Lets server-side services push async state
+ * onto a tool card when all they hold is the call id recorded at creation
+ * time (e.g. the goal loop updating the `createGoal` card via
+ * `task.context.origin.toolCallId`).
+ */
+ findToolMessageIdByToolCallId = async (toolCallId: string): Promise<string | null> => {
+ const [row] = await this.db
+ .select({ id: messagePlugins.id })
+ .from(messagePlugins)
+ .where(and(eq(messagePlugins.toolCallId, toolCallId), this.pluginsOwnership()))
+ .limit(1);
+ return row?.id ?? null;
+ };
+
/**
* Update tool message with content, metadata, pluginState, and pluginError in a single transaction
* This prevents race conditions when updating multiple fields
diff --git a/packages/database/src/models/task.ts b/packages/database/src/models/task.ts
index 477acaa9c10..e88f07bb5e9 100644
--- a/packages/database/src/models/task.ts
+++ b/packages/database/src/models/task.ts
@@ -1,6 +1,7 @@
import type {
CheckpointConfig,
NewTask,
+ TaskGoalConfig,
TaskItem,
TaskVerifyConfig,
WorkspaceData,
@@ -755,6 +756,19 @@ export class TaskModel {
return this.updateTaskConfig(id, { review });
}
+ // ========== Goal Config ==========
+
+ /**
+ * Read this task's goal-loop config from `config.goal`. Presence marks a
+ * goal-driven task (created via the `createGoal` builtin tool) and enables
+ * the outer verify-driven round loop. No inheritance — a goal belongs to the
+ * exact task it was created on.
+ */
+ getGoalConfig(task: TaskItem): TaskGoalConfig | undefined {
+ const config = task.config as Record<string, any> | undefined;
+ return config?.goal ? (config.goal as TaskGoalConfig) : undefined;
+ }
+
// ========== Verify Config ==========
/**
diff --git a/packages/database/src/models/taskTopic.ts b/packages/database/src/models/taskTopic.ts
index adcae1d5b74..3dad00b4197 100644
--- a/packages/database/src/models/taskTopic.ts
+++ b/packages/database/src/models/taskTopic.ts
@@ -66,7 +66,7 @@ export class TaskTopicModel {
params: {
operationId?: string;
seq: number;
- trigger?: 'manual' | 'schedule' | 'heartbeat';
+ trigger?: 'manual' | 'schedule' | 'heartbeat' | 'goal';
},
): Promise<void> {
const visibility = await this.getTaskVisibility(taskId);
@@ -227,7 +227,7 @@ export class TaskTopicModel {
*/
async countByTask(
taskId: string,
- options?: { since?: Date; triggers?: Array<'manual' | 'schedule' | 'heartbeat'> },
+ options?: { since?: Date; triggers?: Array<'manual' | 'schedule' | 'heartbeat' | 'goal'> },
): Promise<number> {
const conditions = [eq(taskTopics.taskId, taskId), this.ownership()];
if (options?.since) conditions.push(gte(taskTopics.createdAt, options.since));
@@ -304,6 +304,7 @@ export class TaskTopicModel {
status: taskTopics.status,
title: topics.title,
topicId: taskTopics.topicId,
+ trigger: taskTopics.trigger,
})
.from(taskTopics)
.leftJoin(topics, eq(taskTopics.topicId, topics.id))
@@ -334,6 +335,7 @@ export class TaskTopicModel {
status: taskTopics.status,
title: topics.title,
topicId: taskTopics.topicId,
+ trigger: taskTopics.trigger,
})
.from(taskTopics)
.innerJoin(tasks, eq(taskTopics.taskId, tasks.id))
diff --git a/packages/database/src/models/verifyRun.ts b/packages/database/src/models/verifyRun.ts
index 9bff892a7ce..b304babba83 100644
--- a/packages/database/src/models/verifyRun.ts
+++ b/packages/database/src/models/verifyRun.ts
@@ -6,11 +6,11 @@ import type {
VerifyRunSource,
VerifyRunStatus,
} from '@lobechat/types';
-import { and, asc, desc, eq, ilike, isNull, lt, or, sql } from 'drizzle-orm';
+import { and, asc, desc, eq, ilike, inArray, isNull, lt, or, sql } from 'drizzle-orm';
import { agentOperations } from '../schemas/agentOperations';
import type { NewVerifyRun, VerifyRunItem } from '../schemas/verify';
-import { verifyRuns } from '../schemas/verify';
+import { verifyCheckResults, verifyRuns } from '../schemas/verify';
import type { LobeChatDatabase } from '../type';
import { isUuid } from '../utils/uuid';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
@@ -223,6 +223,59 @@ export class VerifyRunModel {
return { items, nextCursor };
};
+ /**
+ * The verification bound to each of several Agent Runs, keyed by operation.
+ * Feeds the task's activity list, where every run row needs to answer "and
+ * did it pass?" without one query per row.
+ */
+ findByOperations = async (
+ operationIds: string[],
+ ): Promise<
+ Map<
+ string,
+ Pick<VerifyRunItem, 'acceptanceId' | 'id' | 'roundIndex' | 'status'> & {
+ passed: number;
+ total: number;
+ }
+ >
+ > => {
+ const ids = [...new Set(operationIds.filter(Boolean))];
+ if (ids.length === 0) return new Map();
+
+ // Counts come from the same statement: a run row alone says pass/fail, but
+ // "4/4" is what makes a verdict inspectable at a glance, and fetching it
+ // per row would be one query per round.
+ const rows = await this.db
+ .select({
+ acceptanceId: verifyRuns.acceptanceId,
+ id: verifyRuns.id,
+ operationId: verifyRuns.operationId,
+ passed: sql<number>`count(*) filter (where ${verifyCheckResults.verdict} = 'passed')`,
+ roundIndex: verifyRuns.roundIndex,
+ status: verifyRuns.status,
+ total: sql<number>`count(${verifyCheckResults.id})`,
+ })
+ .from(verifyRuns)
+ .leftJoin(verifyCheckResults, eq(verifyCheckResults.verifyRunId, verifyRuns.id))
+ .where(and(inArray(verifyRuns.operationId, ids), this.ownership()))
+ .groupBy(
+ verifyRuns.id,
+ verifyRuns.acceptanceId,
+ verifyRuns.operationId,
+ verifyRuns.roundIndex,
+ verifyRuns.status,
+ );
+
+ return new Map(
+ rows
+ .filter((row): row is typeof row & { operationId: string } => Boolean(row.operationId))
+ .map(({ operationId, passed, total, ...run }) => [
+ operationId,
+ { ...run, passed: Number(passed), total: Number(total) },
+ ]),
+ );
+ };
+
/** Every round chained onto an acceptance aggregate, in round order. */
listByAcceptance = async (acceptanceId: string): Promise<VerifyRunItem[]> => {
return this.db.query.verifyRuns.findMany({
@@ -401,6 +454,39 @@ export class VerifyRunModel {
* stamp per-run knobs like the task's `maxRepairRounds` override, and to carry
* them onto a repair round's run so it derives the same cap.
*/
+ /**
+ * Claim the right to drive the task from this run, exactly once.
+ *
+ * The settle path reads `taskDrivenAt`, decides, and only then writes it —
+ * so two verifier callbacks landing together can both pass the read and both
+ * act (spawning two rounds, or one spawning while the other pauses the task
+ * it just started). The claim moves that decision into a single conditional
+ * UPDATE: the row is only stamped if nobody stamped it, and the loser learns
+ * it lost from the empty result.
+ *
+ * @returns true when this caller owns the drive, false when it was taken.
+ */
+ claimTaskDrive = async (runId: string): Promise<boolean> => {
+ const claimed = await this.db
+ .update(verifyRuns)
+ .set({
+ metadata: sql`coalesce(${verifyRuns.metadata}, '{}'::jsonb) || jsonb_build_object('taskDrivenAt', ${new Date().toISOString()}::text)`,
+ })
+ .where(
+ and(
+ eq(verifyRuns.id, runId),
+ // Null-testing a jsonb arrow expression in a WHERE clause takes the
+ // production engine down (XX000), so compare an extracted value
+ // against a sentinel instead — see the jsonbNullTest guard.
+ sql`coalesce(${verifyRuns.metadata} ->> 'taskDrivenAt', '') = ''`,
+ this.ownership(),
+ ),
+ )
+ .returning({ id: verifyRuns.id });
+
+ return claimed.length > 0;
+ };
+
setMetadata = async (runId: string, metadata: Record<string, unknown>): Promise<void> => {
await this.db
.update(verifyRuns)
diff --git a/packages/database/src/schemas/task.ts b/packages/database/src/schemas/task.ts
index 8d627756ea8..c3a67129c44 100644
--- a/packages/database/src/schemas/task.ts
+++ b/packages/database/src/schemas/task.ts
@@ -242,7 +242,7 @@ export const taskTopics = pgTable(
// 'schedule' (cron tick) or 'heartbeat' (interval tick). Null for legacy
// rows created before this column existed. Used so the maxExecutions quota
// counts only automation ticks, not manual runs.
- trigger: text('trigger').$type<'manual' | 'schedule' | 'heartbeat'>(),
+ trigger: text('trigger').$type<'manual' | 'schedule' | 'heartbeat' | 'goal'>(),
// Handoff (populated after topic completes via LLM summarization)
// { title, summary, keyFindings: string[], nextAction }
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 0bb95822536..bbf74257c41 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1256,11 +1256,30 @@ export default {
'taskDetail.acceptance.goal': 'Acceptance goal',
'taskDetail.acceptance.loadError': 'Could not load delivery acceptance.',
'taskDetail.acceptance.multimodalLlm': 'Multimodal LLM',
+ 'taskDetail.acceptance.openReport': 'Acceptance report',
'taskDetail.acceptance.retry': 'Retry',
'taskDetail.acceptance.requiredEvidence': 'Required evidence',
'taskDetail.acceptance.reviewError': 'Could not save this review.',
'taskDetail.acceptance.title': 'Delivery acceptance',
'taskDetail.acceptance.verifier': 'Verification method',
+ 'taskDetail.acceptanceState.accepted': 'Accepted',
+ 'taskDetail.acceptanceState.awaitingDecision': 'Not passed — your call',
+ 'taskDetail.acceptanceState.awaitingReview': 'Awaiting your review',
+ 'taskDetail.acceptanceState.awaitingVerification': 'Awaiting verification',
+ 'taskDetail.acceptanceState.closed': 'Closed',
+ 'taskDetail.acceptanceState.errored': 'Verification errored',
+ 'taskDetail.acceptanceState.hint': 'Delivery acceptance — click to review',
+ 'taskDetail.acceptanceState.rejected': 'Sent back',
+ 'taskDetail.acceptanceState.repairing': 'Repairing',
+ 'taskDetail.acceptanceState.verifying': 'Verifying',
+ 'taskDetail.goalTimeline.hover.cost': 'Cost',
+ 'taskDetail.goalTimeline.hover.duration': 'Duration',
+ 'taskDetail.goalTimeline.hover.status': 'Status',
+ 'taskDetail.goalTimeline.hover.tokens': 'Tokens',
+ 'taskDetail.goalTimeline.hover.verdict': 'Verdict',
+ 'taskDetail.goalTimeline.round': 'Round {{index}}',
+ 'taskDetail.goalTimeline.rounds': '{{count}} rounds',
+ 'taskDetail.goalTimeline.title': 'Round progress',
'taskDetail.activities': 'Activities',
'taskDetail.activitiesEmpty': 'No activity yet',
'taskDetail.artifacts': 'Artifacts',
@@ -1287,6 +1306,15 @@ export default {
'taskDetail.comment.save': 'Save',
'taskDetail.commentPlaceholder':
'Leave feedback to guide the agent — your comments shape the next run...',
+ 'taskDetail.runCollapse': 'Collapse run',
+ 'taskDetail.runVerify.checklist': 'Acceptance checks',
+ 'taskDetail.runVerify.errored': 'Verification errored',
+ 'taskDetail.runVerify.failed': 'Not passed',
+ 'taskDetail.runVerify.passed': 'Passed',
+ 'taskDetail.runVerify.pending': 'Awaiting verification',
+ 'taskDetail.runVerify.round': 'Round {{index}}',
+ 'taskDetail.runVerify.running': 'Verifying',
+ 'taskDetail.runExpand': 'Expand run',
'taskDetail.runFollowUp': 'Ask a follow-up',
'taskDetail.runFollowUpPlaceholder': 'Ask a follow-up about this run...',
'taskDetail.collapseReply': 'Collapse',
@@ -1370,6 +1398,9 @@ export default {
'taskDetail.topicMenu.stopConfirm.content':
'The current run will be canceled. Generated messages are kept and you can re-run the task later.',
'taskDetail.topicMenu.stopConfirm.title': 'Stop Run?',
+ 'taskDetail.runTrigger.goal': 'Goal loop',
+ 'taskDetail.runTrigger.heartbeat': 'Heartbeat',
+ 'taskDetail.runTrigger.schedule': 'Scheduled',
'taskDetail.topicSource': 'From {{identifier}}',
'taskDetail.updateFailed': 'Failed to update task',
'taskDetail.publishToWorkspace.menuLabel': 'Publish to Workspace',
diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.ts
index c56ecfe5004..523a1937a87 100644
--- a/packages/locales/src/default/plugin.ts
+++ b/packages/locales/src/default/plugin.ts
@@ -422,6 +422,7 @@ export default {
'builtins.lobe-skills.apiName.searchSkill': 'Search Skills',
'builtins.lobe-skills.title': 'Skills',
'builtins.lobe-task.apiName.createTask': 'Create task',
+ 'builtins.lobe-task.apiName.createGoal': 'Start goal',
'builtins.lobe-task.apiName.createTasks': 'Create tasks',
'builtins.lobe-task.apiName.addTaskComment': 'Add comment',
'builtins.lobe-task.apiName.deleteTask': 'Delete task',
@@ -435,6 +436,41 @@ export default {
'builtins.lobe-task.apiName.updateTaskComment': 'Update comment',
'builtins.lobe-task.apiName.updateTaskStatus': 'Update status',
'builtins.lobe-task.apiName.viewTask': 'View task',
+ 'builtins.lobe-task.goal.add': 'Add',
+ 'builtins.lobe-task.goal.addCriterion': 'Add acceptance criterion',
+ 'builtins.lobe-task.goal.costBudget': 'Total cost budget',
+ 'builtins.lobe-task.goal.criteria': 'Acceptance criteria',
+ 'builtins.lobe-task.goal.instruction': 'Describe the exact pass conditions and required evidence',
+ 'builtins.lobe-task.goal.optional': 'Optional',
+ 'builtins.lobe-task.goal.phase.accepted': 'Accepted',
+ 'builtins.lobe-task.goal.phase.awaitingDecision': 'Not passed — your call',
+ 'builtins.lobe-task.goal.phase.awaitingReview': 'Awaiting your review',
+ 'builtins.lobe-task.goal.phase.closed': 'Closed',
+ 'builtins.lobe-task.goal.phase.errored': 'Verification errored',
+ 'builtins.lobe-task.goal.phase.rejected': 'Sent back',
+ 'builtins.lobe-task.goal.phase.repairing': 'Repairing',
+ 'builtins.lobe-task.goal.phase.verifying': 'Verifying',
+ 'builtins.lobe-task.goal.required': 'Required',
+ 'builtins.lobe-task.goal.cancel': 'Cancel',
+ 'builtins.lobe-task.goal.criterionTitle': 'Title',
+ 'builtins.lobe-task.goal.editCriterion': 'Edit criterion C{{seq}}',
+ 'builtins.lobe-task.goal.judgePrompt': 'Judge prompt',
+ 'builtins.lobe-task.goal.requiredHint': 'Required — the goal cannot pass while this fails',
+ 'builtins.lobe-task.goal.roundBudget': 'Iteration budget',
+ 'builtins.lobe-task.goal.save': 'Save',
+ 'builtins.lobe-task.goal.verifier.agent': 'Agent verification',
+ 'builtins.lobe-task.goal.verifier.llm': 'Model judgement',
+ 'builtins.lobe-task.goal.verifier.program': 'Programmatic check',
+ 'builtins.lobe-task.goal.verifierType': 'Verification method',
+ 'builtins.lobe-task.goal.roundsUnit': 'rounds',
+ 'builtins.lobe-task.goal.sectionBudget': 'Budget',
+ 'builtins.lobe-task.goal.sectionInstruction': 'Task instruction',
+ 'builtins.lobe-task.goal.uncapped': 'Uncapped',
+ 'builtins.lobe-task.goal.running': 'Round 1 · running',
+ 'builtins.lobe-task.goal.runningHint':
+ '{{count}} checks will run automatically when this round completes',
+ 'builtins.lobe-task.goal.settledHint': 'Click to open the acceptance',
+ 'builtins.lobe-task.goal.script': 'Validation command or function',
'builtins.lobe-task.create.subtaskOf': 'Subtask of {{parent}}',
'builtins.lobe-task.createTasks.count': '{{count}} tasks',
'builtins.lobe-task.createTasks.failedCount': '{{count}} failed',
diff --git a/packages/locales/src/default/verify.ts b/packages/locales/src/default/verify.ts
index 055853d2f27..d83d279ec4c 100644
--- a/packages/locales/src/default/verify.ts
+++ b/packages/locales/src/default/verify.ts
@@ -47,6 +47,8 @@ export default {
'acceptance.checks.emptyFilter.ignored': 'No checks ignored',
'acceptance.checks.emptyFilter.needsFix': 'No checks marked for fixing',
'acceptance.checks.emptyFilter.pending': 'No checks left to review',
+ 'acceptance.checks.judgeReason': 'How this verdict was reached',
+ 'acceptance.checks.viewTrace': 'View verification run',
'acceptance.checks.finalRoundHint':
'The final result and evidence come from this round — click to locate it.',
'acceptance.checks.introduced': 'Added in round {{round}}',
diff --git a/packages/prompts/src/prompts/task/__snapshots__/index.test.ts.snap b/packages/prompts/src/prompts/task/__snapshots__/index.test.ts.snap
index 76ad05afb3e..6dbd81fe1d1 100644
--- a/packages/prompts/src/prompts/task/__snapshots__/index.test.ts.snap
+++ b/packages/prompts/src/prompts/task/__snapshots__/index.test.ts.snap
@@ -55,6 +55,7 @@ Review: (not configured)
Activities:
💬 19h ago Topic #1 制定大纲 ✓ completed tpc_001
+ ↳ summary: 完成大纲
📋 18h ago Brief [decision] 大纲完成 ✅ approve brief_001
💭 3h ago 👤 user 第5章后移,增加评测章节
💭 2h ago 🤖 agent 已调整大纲
@@ -73,8 +74,10 @@ Review: (not configured)
Activities:
💬 19h ago Topic #1 制定大纲 ✓ completed tpc_aaa
+ ↳ summary: 完成了大纲制定
📋 18h ago Brief [decision] 大纲完成 [urgent] ✅ approve brief_abc123
💬 18h ago Topic #2 修订大纲 ✓ completed tpc_bbb
+ ↳ summary: 修订了大纲并拆分子任务
📋 18h ago Brief [decision] 建议拆分第4章 [normal] brief_def456
</task>"
`;
diff --git a/packages/prompts/src/prompts/task/index.test.ts b/packages/prompts/src/prompts/task/index.test.ts
index 484c01efcd1..ee58c42b3fa 100644
--- a/packages/prompts/src/prompts/task/index.test.ts
+++ b/packages/prompts/src/prompts/task/index.test.ts
@@ -639,4 +639,84 @@ describe('buildTaskRunPrompt', () => {
expect(taskSection).toContain('👤 user');
expect(taskSection).toContain('🤖 agent');
});
+
+ it('renders the goal loop section with reject comment, failed checks and CLI hint', () => {
+ const result = buildTaskRunPrompt(
+ {
+ goalLoop: {
+ failedChecks: [
+ { title: 'LCP < 2s', why: 'measured 2.8s — preload hero image' },
+ { title: 'Lighthouse ≥ 90' },
+ ],
+ maxRounds: 3,
+ rejectComment: '真机 LCP 还是 2.4s,按真机口径再优化',
+ round: 2,
+ },
+ task: {
+ ...baseTask,
+ identifier: 'TASK-1',
+ instruction: '官网首页改版并上线',
+ name: '首页改版',
+ },
+ },
+ NOW,
+ );
+
+ expect(result).toContain('Goal loop — round 2 of 3');
+ // Reject comment outranks the failed checks.
+ expect(result.indexOf('真机 LCP 还是 2.4s')).toBeLessThan(result.indexOf('LCP < 2s'));
+ expect(result).toContain('1. LCP < 2s — measured 2.8s — preload hero image');
+ expect(result).toContain('2. Lighthouse ≥ 90');
+ expect(result).toContain('`lh task topic view TASK-1 <seq>`');
+ });
+
+ it('omits the round budget suffix for uncapped goals', () => {
+ const result = buildTaskRunPrompt(
+ {
+ goalLoop: { maxRounds: null, round: 5 },
+ task: { ...baseTask, identifier: 'TASK-1', instruction: '写书', name: '写一本书' },
+ },
+ NOW,
+ );
+
+ expect(result).toContain('Goal loop — round 5:');
+ expect(result).not.toContain('round 5 of');
+ });
+
+ it('expands full handoff for the two most recent rounds and keeps older ones title-only', () => {
+ const mkTopic = (seq: number, summary: string) => ({
+ createdAt: `2026-03-2${seq}T10:00:00Z`,
+ handoff: {
+ keyFindings: [`finding-${seq}`],
+ nextAction: `next-${seq}`,
+ summary,
+ title: `round ${seq}`,
+ },
+ id: `t${seq}`,
+ seq,
+ status: 'completed',
+ });
+ const result = buildTaskRunPrompt(
+ {
+ activities: {
+ topics: [
+ mkTopic(1, 'summary-one'),
+ mkTopic(2, 'summary-two'),
+ mkTopic(3, 'summary-three'),
+ ],
+ },
+ task: { ...baseTask, identifier: 'TASK-1', instruction: '写书', name: '写一本书' },
+ },
+ NOW,
+ );
+
+ // Recent two rounds carry the full handoff…
+ expect(result).toContain('↳ summary: summary-two');
+ expect(result).toContain('↳ summary: summary-three');
+ expect(result).toContain('↳ findings: finding-3');
+ expect(result).toContain('↳ next: next-3');
+ // …the oldest stays title-only.
+ expect(result).not.toContain('summary-one');
+ expect(result).toContain('round 1');
+ });
});
diff --git a/packages/prompts/src/prompts/task/index.ts b/packages/prompts/src/prompts/task/index.ts
index 01c9ba933f1..786d6cca1b9 100644
--- a/packages/prompts/src/prompts/task/index.ts
+++ b/packages/prompts/src/prompts/task/index.ts
@@ -397,6 +397,22 @@ export interface TaskRunPromptWorkspaceNode {
title?: string;
}
+/**
+ * Goal-loop context for a round spawned by the outer verify-driven loop: what
+ * the previous round left unresolved, so the new (fresh-context) topic can pick
+ * up without re-discovering everything.
+ */
+export interface TaskRunPromptGoalLoop {
+ /** Checks that did not pass in the previous round, with the verifier's why/suggestion. */
+ failedChecks?: Array<{ title: string; why?: string }>;
+ /** Round budget. Null/undefined = uncapped. */
+ maxRounds?: number | null;
+ /** The user's reject comment on the previous delivery — highest-priority input. */
+ rejectComment?: string;
+ /** 1-based index of the round this prompt is for. */
+ round?: number;
+}
+
export interface TaskRunPromptInput {
/** Activity data (all optional) */
activities?: {
@@ -407,6 +423,8 @@ export interface TaskRunPromptInput {
};
/** --prompt flag content */
extraPrompt?: string;
+ /** Present only for rounds spawned by the goal outer loop. */
+ goalLoop?: TaskRunPromptGoalLoop;
/** Parent task context (when current task is a subtask) */
parentTask?: {
identifier: string;
@@ -510,7 +528,7 @@ const briefIcon = (type: string): string => {
* 4. Original Task (instruction + description) — the base requirement
*/
export const buildTaskRunPrompt = (input: TaskRunPromptInput, now?: Date): string => {
- const { task, activities, extraPrompt, workspace, parentTask } = input;
+ const { task, activities, extraPrompt, goalLoop, workspace, parentTask } = input;
const sections: string[] = [];
// ── 1. High Priority Instruction ──
@@ -622,6 +640,30 @@ export const buildTaskRunPrompt = (input: TaskRunPromptInput, now?: Date): strin
);
}
+ // Goal loop — context handed over from the previous round of the outer loop
+ if (goalLoop) {
+ taskLines.push('');
+ const budget = typeof goalLoop.maxRounds === 'number' ? ` of ${goalLoop.maxRounds}` : '';
+ taskLines.push(
+ `Goal loop${goalLoop.round ? ` — round ${goalLoop.round}${budget}` : ''}: earlier rounds did not fully meet the acceptance criteria. Focus on closing the gaps below instead of redoing finished work.`,
+ );
+ if (goalLoop.rejectComment) {
+ taskLines.push(' User feedback on the last delivery (address this first):');
+ taskLines.push(` "${goalLoop.rejectComment}"`);
+ }
+ if (goalLoop.failedChecks && goalLoop.failedChecks.length > 0) {
+ taskLines.push(' Unresolved checks from the last round:');
+ for (const [i, check] of goalLoop.failedChecks.entries()) {
+ taskLines.push(` ${i + 1}. ${check.title}${check.why ? ` — ${check.why}` : ''}`);
+ }
+ }
+ taskLines.push(
+ ' To read a previous round in full, run: `lh task topic view ' +
+ task.identifier +
+ ' <seq>` (seq from the Activities list below).',
+ );
+ }
+
// Workspace
if (workspace && workspace.length > 0) {
const countNodes = (nodes: TaskRunPromptWorkspaceNode[]): number =>
@@ -656,13 +698,31 @@ export const buildTaskRunPrompt = (input: TaskRunPromptInput, now?: Date): strin
const timelineEntries: { text: string; time: number }[] = [];
if (activities?.topics) {
+ // Older rounds stay title-only to bound prompt size; the most recent ones
+ // carry their full handoff so the next round starts from real context
+ // instead of a bare title.
+ const detailedSeqs = new Set(
+ [...activities.topics]
+ .map((t) => t.seq ?? 0)
+ .sort((a, b) => b - a)
+ .slice(0, 2),
+ );
for (const t of activities.topics) {
const ago = timeAgo(t.createdAt, now);
const status = t.status || 'completed';
const title = t.title || t.handoff?.title || 'Untitled';
const idSuffix = t.id ? ` ${t.id}` : '';
+ const lines = [
+ ` 💬 ${ago} Topic #${t.seq || '?'} ${title} ${statusIcon(status)} ${status}${idSuffix}`,
+ ];
+ if (t.handoff && detailedSeqs.has(t.seq ?? 0)) {
+ if (t.handoff.summary) lines.push(` ↳ summary: ${t.handoff.summary}`);
+ if (t.handoff.keyFindings && t.handoff.keyFindings.length > 0)
+ lines.push(` ↳ findings: ${t.handoff.keyFindings.join('; ')}`);
+ if (t.handoff.nextAction) lines.push(` ↳ next: ${t.handoff.nextAction}`);
+ }
timelineEntries.push({
- text: ` 💬 ${ago} Topic #${t.seq || '?'} ${title} ${statusIcon(status)} ${status}${idSuffix}`,
+ text: lines.join('\n'),
time: new Date(t.createdAt).getTime(),
});
}
diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.ts
index 140bba12ac9..6d7ee8566ab 100644
--- a/packages/types/src/task/index.ts
+++ b/packages/types/src/task/index.ts
@@ -23,8 +23,10 @@ export type TaskAutomationMode = 'heartbeat' | 'schedule';
* scheduling state, nor count against the maxExecutions quota.
* - `schedule` — a cron `schedule` tick fired the run.
* - `heartbeat` — a heartbeat interval tick fired the run.
+ * - `goal` — the goal outer loop spawned this round after a failed verify.
+ * Like `manual`, it never counts against automation quotas.
*/
-export type TaskRunTrigger = 'manual' | 'schedule' | 'heartbeat';
+export type TaskRunTrigger = 'manual' | 'schedule' | 'heartbeat' | 'goal';
// ── Config types ──
@@ -51,6 +53,21 @@ export interface CheckpointConfig {
* config when present, otherwise the nearest ancestor's config in full (never a
* field-level merge). Resolved at runtime via `TaskModel.resolveVerifyConfig`.
*/
+/**
+ * Goal-driven loop config, persisted under `tasks.config.goal`. Written by the
+ * `createGoal` builtin tool; its presence marks the task as a goal task and
+ * enables the outer verify-driven round loop (a failed verify run spawns a new
+ * task topic instead of pausing, until a budget below runs out).
+ */
+export interface TaskGoalConfig {
+ /** Max execution rounds (task topics). Null = uncapped by the user. */
+ maxIterations?: number | null;
+ /** Total USD budget across all rounds and their verify runs. Null = uncapped. */
+ maxTotalCost?: number | null;
+ /** Conversation topic that spawned the goal — terminal callbacks post back here. */
+ originTopicId?: string | null;
+}
+
export interface TaskVerifyConfig {
/** Whether the verify gate runs on topic completion. */
enabled?: boolean;
@@ -421,8 +438,28 @@ export interface TaskDetailActivity {
time?: string;
title?: string;
topicId?: string | null;
+ /** Topic-only: what opened this round — `goal` marks a loop-spawned rerun. */
+ trigger?: TaskRunTrigger | null;
type: TaskActivityType;
userId?: string | null;
+ /**
+ * Topic-only: the verification bound to this run. Present as soon as a
+ * verify session exists — `status` is null while it is still being planned,
+ * so the row can say "verifying" before there is a verdict.
+ */
+ verify?: TaskRunVerifySummary | null;
+}
+
+export interface TaskRunVerifySummary {
+ /** The aggregate this round is chained onto — the link target. */
+ acceptanceId: string | null;
+ /** Checks that returned a passing verdict in this round. */
+ passed: number;
+ roundIndex: number | null;
+ runId: string;
+ status: string | null;
+ /** Checks this round produced a result for; 0 while the plan is unexecuted. */
+ total: number;
}
export interface TaskDetailData {
diff --git a/src/features/AgentTasks/AgentTaskDetail/GoalRoundPopover.test.ts b/src/features/AgentTasks/AgentTaskDetail/GoalRoundPopover.test.ts
new file mode 100644
index 00000000000..350de3ed71e
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskDetail/GoalRoundPopover.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from 'vitest';
+
+import { formatRoundCost, formatTokens } from './GoalRoundPopover';
+
+describe('formatRoundCost', () => {
+ it('avoids rendering a real sub-cent cost as $0.00', () => {
+ expect(formatRoundCost(0.004)).toBe('<$0.01');
+ });
+
+ it('keeps three decimals under a dollar and two above', () => {
+ expect(formatRoundCost(0.125)).toBe('$0.125');
+ expect(formatRoundCost(2.5)).toBe('$2.50');
+ });
+});
+
+describe('formatTokens', () => {
+ it('abbreviates thousands', () => {
+ expect(formatTokens(999)).toBe('999');
+ expect(formatTokens(15_400)).toBe('15.4k');
+ });
+});
diff --git a/src/features/AgentTasks/AgentTaskDetail/GoalRoundPopover.tsx b/src/features/AgentTasks/AgentTaskDetail/GoalRoundPopover.tsx
new file mode 100644
index 00000000000..b5e3da4b123
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskDetail/GoalRoundPopover.tsx
@@ -0,0 +1,116 @@
+'use client';
+
+import { Flexbox, Popover, Text } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { memo, type ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const styles = createStaticStyles(({ css }) => ({
+ label: css`
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ value: css`
+ font-size: 12px;
+ `,
+}));
+
+/** Cost is fractions of a cent per round — two decimals would read as "$0.00". */
+export const formatRoundCost = (cost: number): string =>
+ cost > 0 && cost < 0.01 ? `<$0.01` : `$${cost.toFixed(cost < 1 ? 3 : 2)}`;
+
+export const formatTokens = (tokens: number): string =>
+ tokens >= 1000 ? `${(tokens / 1000).toFixed(1)}k` : String(tokens);
+
+interface GoalRoundPopoverProps {
+ children: ReactNode;
+ duration: string;
+ index: number;
+ status?: string | null;
+ usage?: { cost: number; tokens: number } | null;
+ verdict?: string | null;
+}
+
+/**
+ * The audit view of one round.
+ *
+ * A block on the rail can only encode "how long" through its width; what it
+ * cost and how it was judged are exactly what an audit needs and exactly what
+ * a bar cannot say. Hover carries them without adding a second row of chrome
+ * to a component whose whole point is compactness.
+ */
+const GoalRoundPopover = memo<GoalRoundPopoverProps>(
+ ({ children, duration, index, status, usage, verdict }) => {
+ const { t } = useTranslation('chat');
+
+ const verdictLabel = (() => {
+ if (verdict === 'passed' || status === 'passed') return t('taskDetail.runVerify.passed');
+ if (verdict === 'failed' || status === 'failed') return t('taskDetail.runVerify.failed');
+ if (status === 'errored') return t('taskDetail.runVerify.errored');
+ if (status === 'running' || status === 'verifying') return t('taskDetail.runVerify.running');
+ if (status) return t('taskDetail.runVerify.pending');
+ return undefined;
+ })();
+
+ const rows: { label: string; value: string }[] = [
+ { label: t('taskDetail.goalTimeline.hover.duration'), value: duration },
+ // A verdict is the report's own word; `status` is the run's. Both are
+ // enum-ish and neither is user-facing copy, so map them rather than
+ // leaking a raw `passed` into a Chinese UI.
+ ...(verdictLabel
+ ? [{ label: t('taskDetail.goalTimeline.hover.verdict'), value: verdictLabel }]
+ : []),
+ // Absent for a round that never reported usage (still running, or an
+ // older row) — an audit should see nothing rather than a fabricated 0.
+ ...(usage?.cost
+ ? [
+ {
+ label: t('taskDetail.goalTimeline.hover.cost'),
+ value: formatRoundCost(usage.cost),
+ },
+ ]
+ : []),
+ ...(usage?.tokens
+ ? [
+ {
+ label: t('taskDetail.goalTimeline.hover.tokens'),
+ value: formatTokens(usage.tokens),
+ },
+ ]
+ : []),
+ ];
+
+ return (
+ <Popover
+ arrow={false}
+ placement={'top'}
+ trigger={'hover'}
+ content={
+ <Flexbox gap={6} style={{ minWidth: 140 }}>
+ <Text fontSize={13} weight={500}>
+ {t('taskDetail.goalTimeline.round', { index })}
+ </Text>
+ {rows.map((row) => (
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={16}
+ justify={'space-between'}
+ key={row.label}
+ >
+ <span className={styles.label}>{row.label}</span>
+ <span className={styles.value}>{row.value}</span>
+ </Flexbox>
+ ))}
+ </Flexbox>
+ }
+ >
+ {children}
+ </Popover>
+ );
+ },
+);
+
+GoalRoundPopover.displayName = 'GoalRoundPopover';
+
+export default GoalRoundPopover;
diff --git a/src/features/AgentTasks/AgentTaskDetail/GoalRoundTimeline.test.ts b/src/features/AgentTasks/AgentTaskDetail/GoalRoundTimeline.test.ts
new file mode 100644
index 00000000000..664587cedeb
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskDetail/GoalRoundTimeline.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ formatGoalDuration,
+ goalRoundEnd,
+ goalRoundWidth,
+ shouldShowGoalRoundTimeline,
+} from './GoalRoundTimeline';
+
+describe('formatGoalDuration', () => {
+ it('uses minutes before a full hour', () => {
+ expect(formatGoalDuration(3 * 60_000)).toBe('3m');
+ expect(formatGoalDuration(59 * 60_000)).toBe('59m');
+ });
+
+ it('uses hours before a full day', () => {
+ expect(formatGoalDuration(3_600_000)).toBe('1h');
+ expect(formatGoalDuration(23 * 3_600_000)).toBe('23h');
+ });
+
+ it('switches to days after 24 hours', () => {
+ expect(formatGoalDuration(34 * 3_600_000)).toBe('1.4d');
+ });
+});
+
+describe('shouldShowGoalRoundTimeline', () => {
+ it('hides progress until there is more than one round', () => {
+ expect(shouldShowGoalRoundTimeline(0)).toBe(false);
+ expect(shouldShowGoalRoundTimeline(1)).toBe(false);
+ expect(shouldShowGoalRoundTimeline(2)).toBe(true);
+ });
+});
+
+describe('goalRoundWidth', () => {
+ it('anchors the first round at the base width', () => {
+ expect(goalRoundWidth(60_000, 60_000)).toBe(28);
+ });
+
+ it('scales a longer round proportionally', () => {
+ expect(goalRoundWidth(180_000, 60_000)).toBe(84);
+ });
+
+ it('never renders narrower than the base or wider than the cap', () => {
+ expect(goalRoundWidth(1000, 60_000)).toBe(28);
+ expect(goalRoundWidth(60 * 60_000, 60_000)).toBe(160);
+ });
+
+ it('falls back to the base width for unusable durations', () => {
+ expect(goalRoundWidth(0, 60_000)).toBe(28);
+ expect(goalRoundWidth(60_000, 0)).toBe(28);
+ });
+});
+
+describe('goalRoundEnd', () => {
+ const now = new Date('2026-08-07T12:00:00Z').getTime();
+ const settledAt = '2026-08-05T12:00:00Z';
+
+ it('stops a settled round at its own timestamp, not the clock', () => {
+ // Reopening the task two days later must not bill those days to the round.
+ expect(goalRoundEnd({ status: 'passed', updatedAt: settledAt }, now)).toBe(
+ new Date(settledAt).getTime(),
+ );
+ expect(goalRoundEnd({ status: 'failed', updatedAt: settledAt }, now)).toBe(
+ new Date(settledAt).getTime(),
+ );
+ });
+
+ it('runs an in-flight round up to now', () => {
+ expect(goalRoundEnd({ status: 'running', updatedAt: settledAt }, now)).toBe(now);
+ expect(goalRoundEnd({ status: 'verifying', updatedAt: settledAt }, now)).toBe(now);
+ });
+
+ it('falls back to now when the settled timestamp is missing or unusable', () => {
+ expect(goalRoundEnd({ status: 'passed' }, now)).toBe(now);
+ expect(goalRoundEnd({ status: 'passed', updatedAt: 'not-a-date' }, now)).toBe(now);
+ });
+});
diff --git a/src/features/AgentTasks/AgentTaskDetail/GoalRoundTimeline.tsx b/src/features/AgentTasks/AgentTaskDetail/GoalRoundTimeline.tsx
new file mode 100644
index 00000000000..98638606d06
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskDetail/GoalRoundTimeline.tsx
@@ -0,0 +1,187 @@
+'use client';
+
+import { Flexbox, Text } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import GoalRoundPopover from './GoalRoundPopover';
+
+interface GoalRound {
+ report: { verdict?: string | null } | null;
+ run: {
+ createdAt: Date | string;
+ id?: string;
+ roundIndex?: number | null;
+ status?: string | null;
+ /** Last write to the row — the closest thing to "when this round ended". */
+ updatedAt?: Date | string | null;
+ };
+ /** Owner-only: what the round spent. Absent for shared links and old rows. */
+ usage?: { cost: number; tokens: number } | null;
+}
+
+const styles = createStaticStyles(({ css }) => ({
+ dot: css`
+ position: absolute;
+ inset-block-end: -2px;
+ inset-inline-end: -2px;
+
+ width: 7px;
+ height: 7px;
+ border: 2px solid ${cssVar.colorBgContainer};
+ border-radius: 50%;
+
+ background: ${cssVar.colorError};
+ `,
+ rail: css`
+ display: flex;
+ flex-wrap: wrap;
+ gap: 5px;
+ align-items: center;
+
+ min-width: 0;
+ `,
+ round: css`
+ cursor: pointer;
+
+ position: relative;
+
+ height: 11px;
+ border-radius: 4px;
+
+ background: ${cssVar.colorInfoBgHover};
+
+ transition:
+ transform 0.15s,
+ filter 0.15s;
+
+ &[data-active='true'] {
+ background: ${cssVar.colorInfo};
+ }
+
+ /* Grow vertically and brighten — never horizontally: width is what encodes
+ the round's duration, so stretching it on hover would lie about the data. */
+ &:hover {
+ transform: scaleY(1.45);
+ filter: brightness(1.25);
+ }
+ `,
+ total: css`
+ flex: none;
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+}));
+
+export const formatGoalDuration = (milliseconds: number) => {
+ const minutes = milliseconds / 60_000;
+ if (minutes < 60) return `${Math.max(1, Math.round(minutes))}m`;
+ const hours = milliseconds / 3_600_000;
+ if (hours < 24) return `${Math.round(hours)}h`;
+ return `${Number((hours / 24).toFixed(1))}d`;
+};
+
+export const shouldShowGoalRoundTimeline = (roundCount: number) => roundCount > 1;
+
+const SETTLED_RUN_STATUSES = new Set(['passed', 'failed', 'errored']);
+
+export const isSettledRound = (status?: string | null): boolean =>
+ Boolean(status && SETTLED_RUN_STATUSES.has(status));
+
+/**
+ * When a round stopped.
+ *
+ * A settled round must not keep measuring against the clock: reopening the
+ * task days later would otherwise bill those idle days to the last round and
+ * stretch its bar accordingly. Only a round still in flight runs up to now.
+ */
+export const goalRoundEnd = (
+ run: { status?: string | null; updatedAt?: Date | string | null },
+ now: number,
+): number => {
+ if (!isSettledRound(run.status) || !run.updatedAt) return now;
+ const settled = new Date(run.updatedAt).getTime();
+ return Number.isFinite(settled) ? settled : now;
+};
+
+/** Narrowest a round can render and still read as a block rather than a tick. */
+const ROUND_BASE_WIDTH = 28;
+/** Beyond this a long round would push the rail past the panel. */
+const ROUND_MAX_WIDTH = 160;
+
+/**
+ * Round width tracks how long the round actually took, anchored on the first
+ * round's duration. Stretching every round to fill the panel made two rounds
+ * of wildly different lengths look identical — and made two rounds look like a
+ * full bar, as if the budget were spent.
+ */
+export const goalRoundWidth = (durationMs: number, baseMs: number): number => {
+ if (!Number.isFinite(durationMs) || durationMs <= 0 || baseMs <= 0) return ROUND_BASE_WIDTH;
+ const scaled = ROUND_BASE_WIDTH * (durationMs / baseMs);
+ return Math.round(Math.min(ROUND_MAX_WIDTH, Math.max(ROUND_BASE_WIDTH, scaled)));
+};
+
+const GoalRoundTimeline = memo<{ rounds?: GoalRound[] }>(({ rounds = [] }) => {
+ const { t } = useTranslation('chat');
+ if (!shouldShowGoalRoundTimeline(rounds.length)) return null;
+
+ const now = Date.now();
+ const start = new Date(rounds[0].run.createdAt).getTime();
+
+ // Each round spans until the next one opens; the last one until it settled,
+ // or until now while it is still running.
+ const durations = rounds.map(({ run }, index) => {
+ const from = new Date(run.createdAt).getTime();
+ const to =
+ index + 1 < rounds.length
+ ? new Date(rounds[index + 1].run.createdAt).getTime()
+ : goalRoundEnd(run, now);
+ return Math.max(1, to - from);
+ });
+ const base = durations[0];
+ // Total ends where the last round ends, for the same reason.
+ const elapsed = Math.max(1, goalRoundEnd(rounds.at(-1)!.run, now) - start);
+
+ return (
+ <Flexbox gap={8}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('taskDetail.goalTimeline.title')}
+ </Text>
+ <div className={styles.rail}>
+ {rounds.map(({ report, run, usage }, index) => (
+ <GoalRoundPopover
+ duration={formatGoalDuration(durations[index])}
+ index={run.roundIndex ?? index + 1}
+ key={`${run.roundIndex ?? index}-${new Date(run.createdAt).getTime()}`}
+ status={run.status}
+ usage={usage}
+ verdict={report?.verdict}
+ >
+ <div
+ className={styles.round}
+ data-active={run.status === 'running' || index === rounds.length - 1}
+ data-goal-round={run.roundIndex ?? index + 1}
+ style={{ width: goalRoundWidth(durations[index], base) }}
+ >
+ {/* An agent-verified round may carry no report at all, so the
+ run's own status is the more reliable failure signal. */}
+ {(report?.verdict === 'failed' || run.status === 'failed') && (
+ <span className={styles.dot} />
+ )}
+ </div>
+ </GoalRoundPopover>
+ ))}
+ {/* Reads as the rail's own caption, right where the rounds end. */}
+ <span className={styles.total}>
+ {t('taskDetail.goalTimeline.rounds', { count: rounds.length })} ·{' '}
+ {formatGoalDuration(elapsed)}
+ </span>
+ </div>
+ </Flexbox>
+ );
+});
+
+GoalRoundTimeline.displayName = 'GoalRoundTimeline';
+
+export default GoalRoundTimeline;
diff --git a/src/features/AgentTasks/AgentTaskDetail/RunVerifyDetail.tsx b/src/features/AgentTasks/AgentTaskDetail/RunVerifyDetail.tsx
new file mode 100644
index 00000000000..b318318c131
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskDetail/RunVerifyDetail.tsx
@@ -0,0 +1,90 @@
+'use client';
+
+import { Flexbox, Icon, Text } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { CircleCheck, CircleDashed, CircleX } from 'lucide-react';
+import { memo, type ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useVerifyResults } from '@/features/Verify';
+
+const styles = createStaticStyles(({ css }) => ({
+ check: css`
+ padding-block: 6px;
+ padding-inline: 10px;
+
+ & + & {
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+ }
+ `,
+ list: css`
+ overflow: hidden;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+ `,
+ reason: css`
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ `,
+}));
+
+const verdictIcon = (verdict: string | null) => {
+ if (verdict === 'passed') return { color: cssVar.colorSuccess, icon: CircleCheck };
+ if (verdict) return { color: cssVar.colorError, icon: CircleX };
+ return { color: cssVar.colorTextQuaternary, icon: CircleDashed };
+};
+
+/**
+ * The per-check breakdown behind a run's verdict, fetched only once the run is
+ * expanded — a collapsed feed of many rounds should not pull every round's
+ * results just to show a tag.
+ */
+const RunVerifyDetail = memo<{
+ /** The run's verdict tag, which follows the list once it is open. */
+ extra?: ReactNode;
+ operationId?: string | null;
+}>(({ extra, operationId }) => {
+ const { t } = useTranslation('chat');
+ const { data: results } = useVerifyResults(operationId ?? null);
+
+ if (!results?.length) return null;
+
+ return (
+ <Flexbox gap={6}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('taskDetail.runVerify.checklist')}
+ </Text>
+ {extra}
+ </Flexbox>
+ <Flexbox className={styles.list}>
+ {results.map((result) => {
+ const meta = verdictIcon(result.verdict);
+ // An LLM judge's reasoning IS its product; a programmatic check
+ // usually has none, and then the verdict alone is the whole story.
+ const reasoning = (result.toulmin as { reasoning?: string } | null)?.reasoning;
+
+ return (
+ <Flexbox className={styles.check} gap={4} key={result.id}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Icon color={meta.color} icon={meta.icon} size={14} style={{ flex: 'none' }} />
+ <Text ellipsis fontSize={13} style={{ flex: 1, minWidth: 0 }}>
+ {result.checkItemTitle}
+ </Text>
+ </Flexbox>
+ {reasoning && (
+ <Text className={styles.reason} style={{ whiteSpace: 'pre-wrap' }}>
+ {reasoning}
+ </Text>
+ )}
+ </Flexbox>
+ );
+ })}
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+RunVerifyDetail.displayName = 'RunVerifyDetail';
+
+export default RunVerifyDetail;
diff --git a/src/features/AgentTasks/AgentTaskDetail/RunVerifyTag.test.ts b/src/features/AgentTasks/AgentTaskDetail/RunVerifyTag.test.ts
new file mode 100644
index 00000000000..9ebb3902453
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskDetail/RunVerifyTag.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveVerdict } from './RunVerifyTag';
+
+describe('resolveVerdict', () => {
+ it('maps a run to the verdict it actually reached', () => {
+ expect(resolveVerdict('passed')).toBe('passed');
+ expect(resolveVerdict('failed')).toBe('failed');
+ expect(resolveVerdict('errored')).toBe('errored');
+ });
+
+ it('treats an in-flight verification as running', () => {
+ expect(resolveVerdict('running')).toBe('running');
+ expect(resolveVerdict('verifying')).toBe('running');
+ });
+
+ it('does not claim a verdict for a run that has not been checked yet', () => {
+ // A planned session has a checklist but no result; saying "verifying"
+ // there would claim work that has not started.
+ expect(resolveVerdict('planned')).toBe('pending');
+ expect(resolveVerdict(null)).toBe('pending');
+ });
+});
diff --git a/src/features/AgentTasks/AgentTaskDetail/RunVerifyTag.tsx b/src/features/AgentTasks/AgentTaskDetail/RunVerifyTag.tsx
new file mode 100644
index 00000000000..fd144d8edb3
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskDetail/RunVerifyTag.tsx
@@ -0,0 +1,105 @@
+'use client';
+
+import type { TaskRunVerifySummary } from '@lobechat/types';
+import { Icon, Tag } from '@lobehub/ui';
+import { cssVar } from 'antd-style';
+import { CircleCheck, CircleDashed, CircleX, Loader2, TriangleAlert } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useChatStore } from '@/store/chat';
+import { useGlobalStore } from '@/store/global';
+
+/**
+ * A run row's verification verdict.
+ *
+ * Every round in a goal loop looks alike in the feed — same title, same agent,
+ * different outcome. Without this the only way to learn whether a round passed
+ * is to leave the task and read the acceptance, which is exactly the trip this
+ * tag saves.
+ */
+const VERDICT_META = {
+ errored: { color: cssVar.colorError, icon: TriangleAlert, labelKey: 'errored' },
+ failed: { color: cssVar.colorError, icon: CircleX, labelKey: 'failed' },
+ passed: { color: cssVar.colorSuccess, icon: CircleCheck, labelKey: 'passed' },
+ pending: { color: cssVar.colorTextTertiary, icon: CircleDashed, labelKey: 'pending' },
+ running: { color: cssVar.colorInfo, icon: Loader2, labelKey: 'running', spin: true },
+} as const;
+
+type VerdictKey = keyof typeof VERDICT_META;
+
+export const resolveVerdict = (status: string | null): VerdictKey => {
+ switch (status) {
+ case 'errored': {
+ return 'errored';
+ }
+ case 'failed': {
+ return 'failed';
+ }
+ case 'passed': {
+ return 'passed';
+ }
+ case 'running':
+ case 'verifying': {
+ return 'running';
+ }
+ // A verify session exists but has not produced a verdict — planned, or
+ // waiting on the run it verifies.
+ default: {
+ return 'pending';
+ }
+ }
+};
+
+interface RunVerifyTagProps {
+ verify?: TaskRunVerifySummary | null;
+}
+
+const RunVerifyTag = memo<RunVerifyTagProps>(({ verify }) => {
+ const { t } = useTranslation('chat');
+ // Every surface that renders a run row (task detail, and task detail inside
+ // the portal) mounts a portal host, so the verdict opens beside the run
+ // rather than replacing the page the reader is comparing rounds on.
+ const openAcceptance = useChatStore((state) => state.openAcceptance);
+ const showTaskAgentPanel = useGlobalStore((state) => state.toggleTaskAgentPanel);
+
+ // Runs with no verification configured keep the row they have today.
+ if (!verify) return null;
+
+ const verdict = resolveVerdict(verify.status);
+ const meta = VERDICT_META[verdict];
+ const round =
+ verify.roundIndex == null
+ ? undefined
+ : t('taskDetail.runVerify.round', { index: verify.roundIndex });
+ const label = t(`taskDetail.runVerify.${meta.labelKey}` as const);
+ // "4/4" is what makes the verdict inspectable; a bare "passed" hides how much
+ // was actually checked. Only shown once the round produced results.
+ const counts = verify.total > 0 ? `${verify.passed}/${verify.total}` : undefined;
+
+ return (
+ <Tag
+ size={'small'}
+ style={{ cursor: verify.acceptanceId ? 'pointer' : undefined, flexShrink: 0 }}
+ title={round ? `${round} · ${label}` : label}
+ icon={
+ <Icon color={meta.color} icon={meta.icon} size={12} spin={'spin' in meta && meta.spin} />
+ }
+ onClick={
+ verify.acceptanceId
+ ? (event) => {
+ event.stopPropagation();
+ showTaskAgentPanel(true);
+ openAcceptance(verify.acceptanceId!);
+ }
+ : undefined
+ }
+ >
+ {counts ? `${counts} ${label}` : label}
+ </Tag>
+ );
+});
+
+RunVerifyTag.displayName = 'RunVerifyTag';
+
+export default RunVerifyTag;
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.test.tsx
index 342e2d289cb..c0dc78bc9bb 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.test.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.test.tsx
@@ -1,13 +1,17 @@
/**
* @vitest-environment happy-dom
*/
-import { fireEvent, render, screen } from '@testing-library/react';
+import { fireEvent, render as rtlRender, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
+import { MemoryRouter } from 'react-router';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { PendingAcceptanceCheckList } from './PendingAcceptanceCheckList';
import TaskAcceptance from './TaskAcceptance';
+// The section links out to the acceptance report, so it needs router context.
+const render = (ui: ReactNode) => rtlRender(<MemoryRouter>{ui}</MemoryRouter>);
+
const mocks = vi.hoisted(() => ({
acceptanceSubject: null as null | { id: string },
bundle: undefined as
@@ -22,8 +26,11 @@ const mocks = vi.hoisted(() => ({
}>;
isOwner: boolean;
},
+ currentPortalView: null as null | string,
mutateBundle: vi.fn(),
mutateSubject: vi.fn(),
+ navigate: vi.fn(),
+ openAcceptance: vi.fn(),
openAcceptanceCheck: vi.fn(),
subjectArgs: [] as unknown[],
toggleTaskAgentPanel: vi.fn(),
@@ -56,6 +63,10 @@ vi.mock('@lobehub/ui/base-ui', () => ({
),
}));
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => mocks.navigate,
+}));
+
vi.mock('antd', () => ({
App: { useApp: () => ({ message: { error: vi.fn() } }) },
}));
@@ -119,11 +130,14 @@ vi.mock('@/services/verify', () => ({
vi.mock('@/store/chat', () => ({
useChatStore: (selector: (state: Record<string, unknown>) => unknown) =>
- selector({ openAcceptanceCheck: mocks.openAcceptanceCheck }),
+ selector({
+ openAcceptance: mocks.openAcceptance,
+ openAcceptanceCheck: mocks.openAcceptanceCheck,
+ }),
}));
vi.mock('@/store/chat/selectors', () => ({
- chatPortalSelectors: { currentViewType: () => null },
+ chatPortalSelectors: { currentViewType: () => mocks.currentPortalView },
}));
vi.mock('@/store/chat/slices/portal/initialState', () => ({
@@ -153,6 +167,7 @@ describe('TaskAcceptance', () => {
vi.clearAllMocks();
mocks.acceptanceSubject = null;
mocks.bundle = undefined;
+ mocks.currentPortalView = null;
});
it('renders the configured criteria in the same slot before an acceptance aggregate exists', () => {
@@ -202,7 +217,8 @@ describe('TaskAcceptance', () => {
expect(screen.getByText('Check 11')).toBeInTheDocument();
});
- it('keeps a small checklist flat and opens the selected check in the Acceptance portal', () => {
+ it('opens the selected check and expands its Acceptance panel from Task detail', () => {
+ mocks.currentPortalView = 'taskDetail';
mocks.acceptanceSubject = { id: 'acceptance-1' };
mocks.bundle = {
acceptance: { id: 'acceptance-1', requirement: 'Everything is verifiable.' },
@@ -224,6 +240,21 @@ describe('TaskAcceptance', () => {
expect(mocks.openAcceptanceCheck).toHaveBeenCalledWith('acceptance-1', 'c1');
});
+ it('opens the acceptance report in the panel rather than navigating away', () => {
+ mocks.acceptanceSubject = { id: 'acceptance-1' };
+ mocks.bundle = {
+ acceptance: { id: 'acceptance-1', requirement: 'Everything is verifiable.' },
+ checks: [{ category: 'Setup', id: 'c1', seq: 1, title: 'Create task' }],
+ isOwner: true,
+ };
+
+ render(<TaskAcceptance />);
+
+ fireEvent.click(screen.getByText('taskDetail.acceptance.openReport'));
+ expect(mocks.toggleTaskAgentPanel).toHaveBeenCalledWith(true);
+ expect(mocks.openAcceptance).toHaveBeenCalledWith('acceptance-1');
+ });
+
it('groups a checklist with more than 10 checks', () => {
mocks.acceptanceSubject = { id: 'acceptance-1' };
mocks.bundle = {
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.tsx
index 34be45672e8..a9015033371 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.tsx
@@ -3,7 +3,13 @@
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 } from 'lucide-react';
+import {
+ ChevronRight,
+ ChevronsDownUp,
+ ChevronsUpDown,
+ ExternalLink,
+ RotateCcw,
+} from 'lucide-react';
import { memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -17,12 +23,11 @@ import {
useAcceptanceBySubject,
} from '@/features/Verify';
import { useChatStore } from '@/store/chat';
-import { chatPortalSelectors } from '@/store/chat/selectors';
-import { PortalViewType } from '@/store/chat/slices/portal/initialState';
import { useGlobalStore } from '@/store/global';
import { useTaskStore } from '@/store/task';
import { taskDetailSelectors } from '@/store/task/selectors';
+import GoalRoundTimeline from './GoalRoundTimeline';
import { resolveTaskAcceptanceRequirement } from './resolveTaskAcceptanceProjection';
import { TaskAcceptanceHeader } from './TaskAcceptanceHeader';
import TaskVerifyConfig from './TaskVerifyConfig';
@@ -127,8 +132,8 @@ CompactCheckRow.displayName = 'TaskAcceptanceCompactCheckRow';
const TaskAcceptance = memo(() => {
const { t } = useTranslation(['chat', 'verify']);
+ const openAcceptance = useChatStore((state) => state.openAcceptance);
const openAcceptanceCheck = useChatStore((state) => state.openAcceptanceCheck);
- const currentPortalView = useChatStore(chatPortalSelectors.currentViewType);
const showTaskAgentPanel = useGlobalStore((state) => state.toggleTaskAgentPanel);
const taskDatabaseId = useTaskStore(taskDetailSelectors.activeTaskDatabaseId);
const verify = useTaskStore(taskDetailSelectors.activeTaskVerifyConfig);
@@ -156,6 +161,18 @@ const TaskAcceptance = memo(() => {
verify?.requirement,
bundle?.acceptance.requirement,
);
+ const openCheck = (acceptanceId: string, checkId: string) => {
+ showTaskAgentPanel(true);
+ openAcceptanceCheck(acceptanceId, checkId);
+ };
+
+ // Same destination as a check, one level up: the report belongs in the panel
+ // beside the task, not on a page that replaces it.
+ const openReport = (acceptanceId: string) => {
+ showTaskAgentPanel(true);
+ openAcceptance(acceptanceId);
+ };
+
const grouped = shouldGroupChecks(checks.length);
const groups = useMemo(
() =>
@@ -174,7 +191,22 @@ const TaskAcceptance = memo(() => {
const header = (
<TaskAcceptanceHeader
count={checks.length}
+ // The section shows the rounds and the checklist; the report is the full
+ // record behind them — reachable from the block it belongs to, instead
+ // of only from the status row at the top of the page.
isOpen={sectionExpanded}
+ extra={
+ acceptanceSubject && (
+ <Button
+ icon={<Icon icon={ExternalLink} />}
+ size={'small'}
+ type={'text'}
+ onClick={() => openReport(acceptanceSubject.id)}
+ >
+ {t('taskDetail.acceptance.openReport')}
+ </Button>
+ )
+ }
onToggle={() => setSectionExpanded((expanded) => !expanded)}
/>
);
@@ -199,6 +231,7 @@ const TaskAcceptance = memo(() => {
{bundleError && <AcceptanceError onRetry={() => void mutateBundle()} />}
{bundle && (
<>
+ <GoalRoundTimeline rounds={bundle.rounds} />
{requirement && (
<Flexbox gap={6}>
<Text fontSize={12} type={'secondary'}>
@@ -269,12 +302,7 @@ const TaskAcceptance = memo(() => {
<CompactCheckRow
check={check}
key={check.id}
- onOpen={() => {
- if (currentPortalView !== PortalViewType.TaskDetail) {
- showTaskAgentPanel(true);
- }
- openAcceptanceCheck(bundle.acceptance.id, check.id);
- }}
+ onOpen={() => openCheck(bundle.acceptance.id, check.id)}
/>
))}
</Flexbox>
@@ -284,12 +312,7 @@ const TaskAcceptance = memo(() => {
<CompactCheckRow
check={check}
key={check.id}
- onOpen={() => {
- if (currentPortalView !== PortalViewType.TaskDetail) {
- showTaskAgentPanel(true);
- }
- openAcceptanceCheck(bundle.acceptance.id, check.id);
- }}
+ onOpen={() => openCheck(bundle.acceptance.id, check.id)}
/>
))}
</Block>
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskAcceptanceHeader.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptanceHeader.tsx
index 669f36bd3b7..65ecb8908c4 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskAcceptanceHeader.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptanceHeader.tsx
@@ -1,25 +1,27 @@
'use client';
-import { Block, Icon, Tag, Text } from '@lobehub/ui';
+import { Block, Flexbox, Icon, Tag, Text } from '@lobehub/ui';
import { cssVar } from 'antd-style';
import { ShieldCheck } from 'lucide-react';
-import { memo } from 'react';
+import { memo, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import AccordionArrowIcon from '../shared/AccordionArrowIcon';
interface TaskAcceptanceHeaderProps {
count?: number;
+ /** Section-level action (e.g. open the full report), outside the toggle. */
+ extra?: ReactNode;
isOpen: boolean;
onToggle: () => void;
}
/** Canonical Task detail header shared by acceptance definition and result modes. */
export const TaskAcceptanceHeader = memo<TaskAcceptanceHeaderProps>(
- ({ count, isOpen, onToggle }) => {
+ ({ count, extra, isOpen, onToggle }) => {
const { t } = useTranslation('chat');
- return (
+ const toggle = (
<Block
clickable
horizontal
@@ -39,6 +41,17 @@ export const TaskAcceptanceHeader = memo<TaskAcceptanceHeaderProps>(
<AccordionArrowIcon isOpen={isOpen} style={{ color: cssVar.colorTextDescription }} />
</Block>
);
+
+ if (!extra) return toggle;
+
+ return (
+ <Flexbox horizontal align={'center'} justify={'space-between'}>
+ {toggle}
+ {/* Lives outside the toggle: opening the report should not also fold
+ the section the user is reading. */}
+ <Flexbox onClick={(event) => event.stopPropagation()}>{extra}</Flexbox>
+ </Flexbox>
+ );
},
);
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskAcceptanceStateRow.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptanceStateRow.tsx
new file mode 100644
index 00000000000..1cd67cb58b0
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptanceStateRow.tsx
@@ -0,0 +1,133 @@
+'use client';
+
+import { Block, Icon, Text } from '@lobehub/ui';
+import { cssVar } from 'antd-style';
+import {
+ AlertTriangle,
+ CheckCheck,
+ CircleDashed,
+ CircleSlash,
+ CircleX,
+ Loader2,
+ RefreshCw,
+ RotateCcw,
+ Stamp,
+} from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useAcceptanceBySubject } from '@/features/Verify';
+import { acceptanceOverviewPath } from '@/features/Verify/Acceptance/routes';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useTaskStore } from '@/store/task';
+import { taskDetailSelectors } from '@/store/task/selectors';
+
+/**
+ * The human layer of the task's two-layer state.
+ *
+ * `task.status` answers "should the system keep spending compute" and stays an
+ * editable scheduling control. Whether the delivery is ACCEPTED is a separate
+ * question with its own lifecycle — this read-only row expresses it in the same
+ * top-right block, instead of a floating banner or a badge buried in the
+ * acceptance section. Clicking it goes to where the decision is made.
+ *
+ * `delivered` alone cannot be rendered honestly: a converged delivery and a
+ * budget-exhausted one both land there. The latest round's verdict (shipped
+ * with the subject payload) tells them apart.
+ */
+const STATE_META = {
+ accepted: { color: cssVar.colorSuccess, icon: CheckCheck, labelKey: 'accepted' },
+ awaitingVerification: {
+ color: cssVar.colorTextTertiary,
+ icon: CircleDashed,
+ labelKey: 'awaitingVerification',
+ },
+ awaitingDecision: { color: cssVar.colorError, icon: AlertTriangle, labelKey: 'awaitingDecision' },
+ awaitingReview: { color: cssVar.colorWarning, icon: Stamp, labelKey: 'awaitingReview' },
+ closed: { color: cssVar.colorTextTertiary, icon: CircleSlash, labelKey: 'closed' },
+ errored: { color: cssVar.colorError, icon: CircleX, labelKey: 'errored' },
+ rejected: { color: cssVar.colorError, icon: RotateCcw, labelKey: 'rejected' },
+ repairing: { color: cssVar.colorWarning, icon: RefreshCw, labelKey: 'repairing', spin: true },
+ verifying: { color: cssVar.colorInfo, icon: Loader2, labelKey: 'verifying', spin: true },
+} as const;
+
+type StateKey = keyof typeof STATE_META;
+
+const resolveState = (status: string, latestRunStatus?: string | null): StateKey | undefined => {
+ switch (status) {
+ case 'accepted': {
+ return 'accepted';
+ }
+ case 'closed': {
+ return 'closed';
+ }
+ case 'delivered': {
+ return latestRunStatus === 'passed' ? 'awaitingReview' : 'awaitingDecision';
+ }
+ case 'errored': {
+ return 'errored';
+ }
+ // The checklist existing is not the same as it being checked. While the
+ // round is still producing the delivery, nothing is under verification —
+ // saying "verifying" here claims work that hasn't started.
+ case 'pending':
+ case 'planned': {
+ return 'awaitingVerification';
+ }
+ case 'verifying': {
+ return 'verifying';
+ }
+ case 'rejected': {
+ return 'rejected';
+ }
+ case 'repairing': {
+ return 'repairing';
+ }
+ default: {
+ return undefined;
+ }
+ }
+};
+
+const TaskAcceptanceStateRow = memo(() => {
+ const { t } = useTranslation('chat');
+ const navigate = useWorkspaceAwareNavigate();
+ const taskDatabaseId = useTaskStore(taskDetailSelectors.activeTaskDatabaseId);
+ const { data: acceptance } = useAcceptanceBySubject('task', taskDatabaseId ?? null);
+
+ // No aggregate yet (verify not configured / never ran) — the row simply
+ // doesn't exist. Ordinary tasks keep the exact block they have today.
+ if (!acceptance) return null;
+
+ const state = resolveState(acceptance.status, acceptance.latestRunStatus);
+ if (!state) return null;
+
+ const meta = STATE_META[state];
+
+ return (
+ <Block
+ clickable
+ horizontal
+ align={'center'}
+ gap={10}
+ paddingBlock={4}
+ paddingInline={8}
+ title={t('taskDetail.acceptanceState.hint')}
+ variant={'borderless'}
+ onClick={() => navigate(acceptanceOverviewPath(acceptance.id))}
+ >
+ <Icon
+ color={meta.color}
+ icon={meta.icon}
+ size={16}
+ spin={'spin' in meta && meta.spin}
+ style={{ flex: 'none' }}
+ />
+ <Text weight={500}>{t(`taskDetail.acceptanceState.${meta.labelKey}`)}</Text>
+ </Block>
+ );
+});
+
+TaskAcceptanceStateRow.displayName = 'TaskAcceptanceStateRow';
+
+export default TaskAcceptanceStateRow;
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskActivities.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskActivities.tsx
index b6939698066..599ecfdf6d4 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskActivities.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskActivities.tsx
@@ -167,26 +167,37 @@ const TaskActivities = memo(() => {
<Flexbox gap={12} paddingBlock={12} paddingInline={12}>
{activeTaskId && <CommentInput taskId={activeTaskId} />}
{items.length > 0 ? (
- items.map(({ activity, brief, key }) => {
- if (brief) {
- return (
- <TaskBriefCard
- brief={brief}
- key={key}
- onAfterAddComment={refreshActiveTask}
- onAfterDelete={refreshActiveTask}
- onAfterResolve={refreshActiveTask}
- />
- );
- }
- if (activity.type === 'topic') {
- return <TopicCard activity={activity} key={key} />;
- }
- if (activity.type === 'comment') {
- return <CommentCard activity={activity} key={key} />;
- }
- return <ActivityRow activity={activity} key={key} />;
- })
+ // A goal loop can produce many rounds; only the newest run opens by
+ // default so the latest result is not buried under older ones.
+ (() => {
+ const firstTopicKey = items.find(({ activity }) => activity.type === 'topic')?.key;
+ return items.map(({ activity, brief, key }) => {
+ if (brief) {
+ return (
+ <TaskBriefCard
+ brief={brief}
+ key={key}
+ onAfterAddComment={refreshActiveTask}
+ onAfterDelete={refreshActiveTask}
+ onAfterResolve={refreshActiveTask}
+ />
+ );
+ }
+ if (activity.type === 'topic') {
+ return (
+ <TopicCard
+ activity={activity}
+ defaultExpanded={key === firstTopicKey}
+ key={key}
+ />
+ );
+ }
+ if (activity.type === 'comment') {
+ return <CommentCard activity={activity} key={key} />;
+ }
+ return <ActivityRow activity={activity} key={key} />;
+ });
+ })()
) : (
<Empty
description={t('taskDetail.activitiesEmpty')}
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskProperties.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskProperties.tsx
index d3baa0ec9ff..66d77f48c89 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskProperties.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskProperties.tsx
@@ -9,6 +9,7 @@ import { taskDetailSelectors } from '@/store/task/selectors';
import TaskPriorityTag from '../features/TaskPriorityTag';
import TaskStatusTag from '../features/TaskStatusTag';
import TaskTriggerTag from '../features/TaskTriggerTag';
+import TaskAcceptanceStateRow from './TaskAcceptanceStateRow';
import TaskScheduleConfig from './TaskScheduleConfig';
interface StatusMeta {
@@ -70,6 +71,10 @@ const TaskProperties = memo(() => {
</Block>
</TaskStatusTag>
+ {/* The human layer: whether the delivery is accepted. Read-only here —
+ the decision itself is made on the acceptance page this links to. */}
+ <TaskAcceptanceStateRow />
+
<TaskPriorityTag priority={priority} taskIdentifier={taskId}>
<Block
clickable
diff --git a/src/features/AgentTasks/AgentTaskDetail/TopicCard.tsx b/src/features/AgentTasks/AgentTaskDetail/TopicCard.tsx
index 2135d7c1746..92ef36926c6 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TopicCard.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TopicCard.tsx
@@ -13,11 +13,21 @@ import {
} from '@lobehub/ui';
import { confirmModal } from '@lobehub/ui/base-ui';
import { cssVar } from 'antd-style';
-import { CircleDot, CircleStop, Copy, ExternalLink, MoreHorizontal, SquarePen } from 'lucide-react';
+import {
+ ChevronDown,
+ ChevronRight,
+ CircleDot,
+ CircleStop,
+ Copy,
+ ExternalLink,
+ MoreHorizontal,
+ SquarePen,
+} from 'lucide-react';
import { memo, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import CollapsibleContent from '@/components/CollapsibleContent';
+import { DEFAULT_AVATAR } from '@/const/meta';
import AgentProfilePopup from '@/features/AgentProfileCard/AgentProfilePopup';
import { useActivityTime } from '@/hooks/useActivityTime';
import { usePermission } from '@/hooks/usePermission';
@@ -26,6 +36,8 @@ import { taskDetailSelectors } from '@/store/task/selectors';
import { styles } from '../shared/style';
import RunReplyEditor from './RunReplyEditor';
+import RunVerifyDetail from './RunVerifyDetail';
+import RunVerifyTag from './RunVerifyTag';
import TopicStatusIcon from './TopicStatusIcon';
const formatDuration = (ms: number): string => {
@@ -54,10 +66,17 @@ const RunContent = memo<{ content: string }>(({ content }) => (
interface TopicCardProps {
activity: TaskDetailActivity;
+ /**
+ * Whether the run body starts open. A goal loop can produce many rounds, and
+ * an all-expanded feed buries the newest result under older ones — the list
+ * opens only the latest and collapses the rest.
+ */
+ defaultExpanded?: boolean;
}
-const TopicCard = memo<TopicCardProps>(({ activity }) => {
+const TopicCard = memo<TopicCardProps>(({ activity, defaultExpanded = true }) => {
const { t } = useTranslation('chat');
+ const [bodyExpanded, setBodyExpanded] = useState(defaultExpanded);
const openTopicDrawer = useTaskStore((s) => s.openTopicDrawer);
const cancelTopic = useTaskStore((s) => s.cancelTopic);
const addComment = useTaskStore((s) => s.addComment);
@@ -71,6 +90,12 @@ const TopicCard = memo<TopicCardProps>(({ activity }) => {
// active task.
const runTaskId = activity.sourceTaskId ?? activeTaskId;
const canFollowUp = canEditTask && !!runTaskId;
+ const hasBody = Boolean(
+ activity.summary || activity.content || canFollowUp || activity.verify?.total,
+ );
+ // A verdict with no results behind it has nothing to move down to, so it
+ // stays in the header no matter what the body is doing.
+ const verifyDetailOpen = bodyExpanded && Boolean(activity.verify?.total);
const finalDuration =
!isRunning && activity.time && activity.completedAt
@@ -162,13 +187,17 @@ const TopicCard = memo<TopicCardProps>(({ activity }) => {
const isAgent = activity.author?.type === 'agent';
- const avatarNode = activity.author?.avatar ? (
- <Avatar avatar={activity.author.avatar} size={24} />
- ) : (
- <div className={styles.activityAvatar}>
- <CircleDot size={12} />
- </div>
- );
+ // An agent that simply never set an avatar is still an agent — it gets the
+ // same default face it wears everywhere else, not a placeholder dot. The dot
+ // stays for rows with no author at all.
+ const avatarNode =
+ activity.author?.avatar || isAgent ? (
+ <Avatar avatar={activity.author?.avatar || DEFAULT_AVATAR} size={24} />
+ ) : (
+ <div className={styles.activityAvatar}>
+ <CircleDot size={12} />
+ </div>
+ );
return (
<Block
@@ -211,11 +240,25 @@ const TopicCard = memo<TopicCardProps>(({ activity }) => {
#{activity.seq}
</Text>
)}
+ {/* Only mark machine-opened rounds: a `manual` tag on every row the
+ user started themselves is noise, absence already means manual. */}
+ {activity.trigger && activity.trigger !== 'manual' && (
+ <Tag
+ size={'small'}
+ style={{ flexShrink: 0 }}
+ title={t(`taskDetail.runTrigger.${activity.trigger}` as const)}
+ >
+ {t(`taskDetail.runTrigger.${activity.trigger}` as const)}
+ </Tag>
+ )}
{durationText && (
<Text fontSize={12} style={{ flexShrink: 0 }} type={'secondary'}>
· {durationText}
</Text>
)}
+ {/* The verdict rides the header only while the run is folded; once
+ open it moves down to sit on the checklist that justifies it. */}
+ {!verifyDetailOpen && <RunVerifyTag verify={activity.verify} />}
</Flexbox>
<Flexbox horizontal align={'center'} flex={'none'} gap={8}>
@@ -224,6 +267,16 @@ const TopicCard = memo<TopicCardProps>(({ activity }) => {
{startedAt}
</Text>
)}
+ {hasBody && (
+ <Flexbox onClick={stopPropagation}>
+ <ActionIcon
+ icon={bodyExpanded ? ChevronDown : ChevronRight}
+ size={'small'}
+ title={t(bodyExpanded ? 'taskDetail.runCollapse' : 'taskDetail.runExpand')}
+ onClick={() => setBodyExpanded((open) => !open)}
+ />
+ </Flexbox>
+ )}
<Flexbox onClick={stopPropagation}>
<DropdownMenu items={menuItems}>
<ActionIcon icon={MoreHorizontal} size={'small'} />
@@ -232,7 +285,7 @@ const TopicCard = memo<TopicCardProps>(({ activity }) => {
</Flexbox>
</Flexbox>
- {(activity.summary || activity.content || canFollowUp) && (
+ {hasBody && bodyExpanded && (
<Flexbox gap={8} paddingInline={4}>
{activity.summary && (
<Text
@@ -243,6 +296,16 @@ const TopicCard = memo<TopicCardProps>(({ activity }) => {
</Text>
)}
{activity.content && <RunContent content={activity.content} />}
+ {/* The verdict's evidence, next to the delivery it judged — reading
+ one should never require leaving for the acceptance page. */}
+ {activity.verify && (
+ <Flexbox onClick={stopPropagation}>
+ <RunVerifyDetail
+ extra={<RunVerifyTag verify={activity.verify} />}
+ operationId={activity.operationId}
+ />
+ </Flexbox>
+ )}
{canFollowUp &&
(commenting ? (
<Flexbox onClick={stopPropagation}>
diff --git a/src/features/Conversation/InterventionBar/style.ts b/src/features/Conversation/InterventionBar/style.ts
index feee640a00d..fee25e9bc6b 100644
--- a/src/features/Conversation/InterventionBar/style.ts
+++ b/src/features/Conversation/InterventionBar/style.ts
@@ -15,10 +15,13 @@ export const styles = createStaticStyles(({ css, cssVar }) => ({
margin-block-end: 12px;
`,
content: css`
- overflow-y: auto;
+ /* ChatInput's maxHeight owns the vertical scrolling; an overflow:auto here
+ never scrolls itself but still severs position:sticky inside intervention
+ bodies from that real scroll container. */
+ overflow-y: visible;
flex: 1;
min-height: 0;
- padding-block: 6px 8px;
+ padding-block: 0 8px;
`,
tab: css`
cursor: pointer;
diff --git a/src/features/DevPanel/RenderGallery/fixtures/index.ts b/src/features/DevPanel/RenderGallery/fixtures/index.ts
index 9644150ad5e..02126fd6662 100644
--- a/src/features/DevPanel/RenderGallery/fixtures/index.ts
+++ b/src/features/DevPanel/RenderGallery/fixtures/index.ts
@@ -25,6 +25,7 @@ import lobeNotebook from './lobe-notebook';
import lobePageAgent from './lobe-page-agent';
import lobeSkillStore from './lobe-skill-store';
import lobeSkills from './lobe-skills';
+import lobeTask from './lobe-task';
import lobeUserInteraction from './lobe-user-interaction';
import lobeUserMemory from './lobe-user-memory';
import lobeWebBrowsing from './lobe-web-browsing';
@@ -98,6 +99,7 @@ const toolsetModules: ToolsetFixtureModule[] = [
lobePageAgent,
lobeSkillStore,
lobeSkills,
+ lobeTask,
lobeUserInteraction,
lobeUserMemory,
lobeWebBrowsing,
diff --git a/src/features/DevPanel/RenderGallery/fixtures/lobe-task.ts b/src/features/DevPanel/RenderGallery/fixtures/lobe-task.ts
new file mode 100644
index 00000000000..50d10a19644
--- /dev/null
+++ b/src/features/DevPanel/RenderGallery/fixtures/lobe-task.ts
@@ -0,0 +1,60 @@
+'use client';
+
+import { defineFixtures, variants } from './_helpers';
+
+const goalArgs = {
+ criteria: [
+ {
+ instruction: '确认移动端首页最大内容绘制时间低于 2 秒。',
+ onFail: 'auto_repair',
+ required: true,
+ title: '移动端 LCP < 2s',
+ verifierType: 'agent',
+ },
+ {
+ instruction: '确认首页已经切换到新的品牌视觉和文案。',
+ onFail: 'auto_repair',
+ required: true,
+ title: '新版品牌首页已上线',
+ verifierType: 'agent',
+ },
+ {
+ instruction: '检查桌面端与移动端关键入口均可访问,且不存在阻断错误。',
+ onFail: 'auto_repair',
+ required: true,
+ title: '关键路径无回归',
+ verifierType: 'agent',
+ },
+ ],
+ instruction:
+ '完成官网首页品牌改版并上线;以移动端 LCP 小于 2 秒为核心指标,同时验证关键访问路径。',
+ maxIterations: 3,
+ name: '官网首页改版并上线,LCP < 2s',
+};
+
+export default defineFixtures({
+ identifier: 'lobe-task',
+ fixtures: {
+ createGoal: variants([
+ {
+ args: goalArgs,
+ description: '完整的可编辑目标计划,用于 Intervention 状态。',
+ label: '计划确认',
+ },
+ {
+ args: goalArgs,
+ description: '用户确认计划后,任务进入第一轮执行。',
+ label: '第 1 轮运行中',
+ pluginState: {
+ identifier: 'T-482',
+ name: goalArgs.name,
+ operationId: 'goal-demo-operation',
+ startedAt: new Date(Date.now() - (39 * 60 + 12) * 1000).toISOString(),
+ success: true,
+ taskId: 'task-goal-demo',
+ topicId: 'topic-goal-demo',
+ },
+ },
+ ]),
+ },
+});
diff --git a/src/features/Portal/AcceptanceCheck/Body.tsx b/src/features/Portal/AcceptanceCheck/Body.tsx
index d59e89bfd92..a05e5890df4 100644
--- a/src/features/Portal/AcceptanceCheck/Body.tsx
+++ b/src/features/Portal/AcceptanceCheck/Body.tsx
@@ -17,6 +17,7 @@ import {
import { verifyService } from '@/services/verify';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
+import { useTaskStore } from '@/store/task';
const styles = createStaticStyles(({ css }) => ({
body: css`
@@ -32,6 +33,8 @@ const styles = createStaticStyles(({ css }) => ({
const Body = memo(() => {
const { t } = useTranslation(['chat', 'verify']);
+ // Task detail (and Home) mount the drawer this opens into.
+ const openTopicDrawer = useTaskStore((s) => s.openTopicDrawer);
const portal = useChatStore(chatPortalSelectors.acceptanceCheckPortal);
const openAcceptance = useChatStore((state) => state.openAcceptance);
@@ -39,6 +42,19 @@ const Body = memo(() => {
const [reviewPending, setReviewPending] = useState(false);
const check = data?.checks.find((item) => item.id === portal?.checkId);
+ /**
+ * An agent judge's argument IS its run, so the trace is the reviewable form
+ * of its verdict. The button was already rendered here but received no
+ * handler, which made it a dead click.
+ */
+ const openVerifierTrace = async (verifierOperationId: string) => {
+ const resolved = await verifyService.getVerifierThread(verifierOperationId);
+ if (!resolved?.topicId) return;
+ openTopicDrawer(resolved.topicId, {
+ title: t('acceptance.checks.viewTrace', { ns: 'verify' }),
+ });
+ };
+
const handleReview = async (input: CheckReviewInput): Promise<boolean> => {
if (!data) return false;
@@ -117,6 +133,7 @@ const Body = memo(() => {
canReview={data.isOwner}
check={check}
reviewPending={reviewPending}
+ onOpenTrace={openVerifierTrace}
onReview={handleReview}
onRound={() => openAcceptance(data.acceptance.id)}
/>
diff --git a/src/features/Portal/AcceptanceCheck/Title.tsx b/src/features/Portal/AcceptanceCheck/Title.tsx
index 1ffc32e1af0..0c293ebc144 100644
--- a/src/features/Portal/AcceptanceCheck/Title.tsx
+++ b/src/features/Portal/AcceptanceCheck/Title.tsx
@@ -1,10 +1,24 @@
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
+import { useAcceptanceBundle } from '@/features/Verify';
+import { useChatStore } from '@/store/chat';
+import { chatPortalSelectors } from '@/store/chat/selectors';
+
+/**
+ * The panel already says it is a check; repeating "check detail" in the title
+ * spends the one line that could say WHICH check — the only thing a reader
+ * with several panels open needs to tell them apart.
+ */
const Title = memo(() => {
const { t } = useTranslation('chat');
+ const portal = useChatStore(chatPortalSelectors.acceptanceCheckPortal);
+ const { data } = useAcceptanceBundle(portal?.acceptanceId ?? null);
+ const check = data?.checks.find((item) => item.id === portal?.checkId);
+
+ if (!check) return t('taskDetail.acceptance.detailTitle');
- return t('taskDetail.acceptance.detailTitle');
+ return check.seq ? `C${check.seq} · ${check.title}` : check.title;
});
Title.displayName = 'AcceptanceCheckPortalTitle';
diff --git a/src/features/Verify/Acceptance/CheckList.tsx b/src/features/Verify/Acceptance/CheckList.tsx
index d0ea7798b8f..b884428b3a9 100644
--- a/src/features/Verify/Acceptance/CheckList.tsx
+++ b/src/features/Verify/Acceptance/CheckList.tsx
@@ -33,6 +33,7 @@ import {
MessageSquareX,
PartyPopper,
Repeat,
+ Route,
XCircle,
} from 'lucide-react';
import { Fragment, memo, useState } from 'react';
@@ -180,12 +181,6 @@ const styles = createStaticStyles(({ css }) => ({
background: ${cssVar.colorFillSecondary};
}
`,
- descClamp: css`
- overflow: hidden;
- display: -webkit-box;
- -webkit-box-orient: vertical;
- -webkit-line-clamp: 2;
- `,
evidenceImage: css`
overflow: hidden;
@@ -791,347 +786,358 @@ const CheckRow = memo<{
expanded: boolean;
onReview: (input: CheckReviewInput) => Promise<boolean>;
onRound?: (round: number) => void;
+ /** Open an agent judge's verification run (its trace IS the argument). */
+ onOpenTrace?: (verifierOperationId: string) => void | Promise<void>;
onToggle: () => void;
reviewPending: boolean;
-}>(({ canReview, check, detailMode, expanded, onReview, onRound, onToggle, reviewPending }) => {
- const { t } = useTranslation('verify');
- // The judging narrative stays collapsed: level one is title + evidence.
- const [historyOpen, setHistoryOpen] = useState(false);
- 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);
-
- const reviewState = userReviewState(check);
- // The decision is stamped on the check's result row — a never-executed
- // check has no evidence to judge, so it exposes no review actions.
- const reviewable = canReview && Boolean(check.result);
- const activeReview =
- check.userReview && !check.userReview.stale
- ? check.reviews.at(-1) // the standing verdict is always the newest entry
- : undefined;
- const historyReviews = check.reviews.filter((entry) => entry !== activeReview);
- const evidenceById = collectEvidenceById(check);
- const hasHistory = check.revisions > 1 || historyReviews.length > 0;
-
- const openReject = () =>
- openCheckRejectModal({
- checkTitle: `C${check.seq} · ${check.title}`,
- draftKey: check.id,
- evidence: check.evidence
- .filter((item) => isAnnotatable(item))
- .map((item) => ({ fileUrl: item.fileUrl!, id: item.id })),
- initialComment: reviewComment,
- onConfirm: async ({ annotations, comment, fileIds }) => {
- const ok = await onReview({
- action: 'reject',
- annotations: annotations.length > 0 ? annotations : undefined,
- checkItemIds: [check.id],
- comment: comment || undefined,
- fileIds: fileIds.length > 0 ? fileIds : undefined,
- });
- if (ok) setReviewComment('');
- return ok;
- },
- });
-
- // Accepting settles the check — the row folds itself away once the write
- // lands, so the reviewer's eye moves on to what still needs judgment.
- const handleAccept = async (event: { stopPropagation: () => void }) => {
- event.stopPropagation();
- setAccepting(true);
- 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);
- const ok = await onReview({ action: 'ignore', checkItemIds: [check.id] });
- setIgnoring(false);
- if (ok && expanded) onToggle();
- };
-
- // The user's standing verdict owns the head slot: a reject replaces the
- // verifier's mark outright (that check IS sent back, whatever the verifier
- // said); passed + user-accepted merges into the double-check receipt.
- const headIcon =
- reviewState === 'rejected'
- ? MessageSquareX
- : reviewState === 'ignored'
- ? Ban
- : check.state === 'passed' && reviewState === 'accepted'
- ? CheckCheck
- : meta.icon;
- const headColor =
- reviewState === 'rejected'
- ? cssVar.colorError
- : reviewState === 'ignored'
- ? cssVar.colorTextQuaternary
- : meta.color;
-
- const headIconNode = (
- <Icon
- color={headColor}
- icon={headIcon}
- size={16}
- style={{ alignSelf: 'flex-start', flex: 'none', marginBlockStart: 3 }}
- />
- );
+}>(
+ ({
+ canReview,
+ check,
+ detailMode,
+ expanded,
+ onOpenTrace,
+ onReview,
+ onRound,
+ onToggle,
+ reviewPending,
+ }) => {
+ const { t } = useTranslation('verify');
+ // The judging narrative stays collapsed: level one is title + evidence.
+ const [historyOpen, setHistoryOpen] = useState(false);
+ 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);
+
+ const reviewState = userReviewState(check);
+ // The decision is stamped on the check's result row — a never-executed
+ // check has no evidence to judge, so it exposes no review actions.
+ const reviewable = canReview && Boolean(check.result);
+ const activeReview =
+ check.userReview && !check.userReview.stale
+ ? check.reviews.at(-1) // the standing verdict is always the newest entry
+ : undefined;
+ const historyReviews = check.reviews.filter((entry) => entry !== activeReview);
+ const evidenceById = collectEvidenceById(check);
+ const hasHistory = check.revisions > 1 || historyReviews.length > 0;
+
+ const openReject = () =>
+ openCheckRejectModal({
+ checkTitle: `C${check.seq} · ${check.title}`,
+ draftKey: check.id,
+ evidence: check.evidence
+ .filter((item) => isAnnotatable(item))
+ .map((item) => ({ fileUrl: item.fileUrl!, id: item.id })),
+ initialComment: reviewComment,
+ onConfirm: async ({ annotations, comment, fileIds }) => {
+ const ok = await onReview({
+ action: 'reject',
+ annotations: annotations.length > 0 ? annotations : undefined,
+ checkItemIds: [check.id],
+ comment: comment || undefined,
+ fileIds: fileIds.length > 0 ? fileIds : undefined,
+ });
+ if (ok) setReviewComment('');
+ return ok;
+ },
+ });
+
+ // Accepting settles the check — the row folds itself away once the write
+ // lands, so the reviewer's eye moves on to what still needs judgment.
+ const handleAccept = async (event: { stopPropagation: () => void }) => {
+ event.stopPropagation();
+ setAccepting(true);
+ 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);
+ const ok = await onReview({ action: 'ignore', checkItemIds: [check.id] });
+ setIgnoring(false);
+ if (ok && expanded) onToggle();
+ };
+
+ // The user's standing verdict owns the head slot: a reject replaces the
+ // verifier's mark outright (that check IS sent back, whatever the verifier
+ // said); passed + user-accepted merges into the double-check receipt.
+ const headIcon =
+ reviewState === 'rejected'
+ ? MessageSquareX
+ : reviewState === 'ignored'
+ ? Ban
+ : check.state === 'passed' && reviewState === 'accepted'
+ ? CheckCheck
+ : meta.icon;
+ const headColor =
+ reviewState === 'rejected'
+ ? cssVar.colorError
+ : reviewState === 'ignored'
+ ? cssVar.colorTextQuaternary
+ : meta.color;
+
+ const headIconNode = (
+ <Icon
+ color={headColor}
+ icon={headIcon}
+ size={16}
+ style={{ alignSelf: 'flex-start', flex: 'none', marginBlockStart: 3 }}
+ />
+ );
- return (
- <Flexbox className={detailMode ? undefined : styles.row} data-check-row={check.id}>
- {!detailMode && (
- <Flexbox
- horizontal
- align={'flex-start'}
- className={styles.rowHeader}
- data-expanded={expanded ? '' : undefined}
- gap={10}
- onClick={onToggle}
- >
- {reviewState === 'rejected' ? (
- <Tooltip title={t('acceptance.review.rejectedHint')}>{headIconNode}</Tooltip>
- ) : (
- headIconNode
- )}
- <Tooltip
- title={seqCopied ? t('acceptance.checks.copied') : t('acceptance.checks.copySeq')}
- >
- <span
- className={cx(styles.seqChip, styles.seqChipClickable)}
- onClick={(event) => {
- event.stopPropagation();
- void copyToClipboard(`C${check.seq}`);
- setSeqCopied(true);
- setTimeout(() => setSeqCopied(false), 1500);
- }}
- >
- C{check.seq}
- </span>
- </Tooltip>
+ return (
+ <Flexbox className={detailMode ? undefined : styles.row} data-check-row={check.id}>
+ {!detailMode && (
<Flexbox
horizontal
- align={'center'}
- flex={1}
- gap={8}
- style={{ minWidth: 0 }}
- wrap={expanded ? 'wrap' : 'nowrap'}
+ align={'flex-start'}
+ className={styles.rowHeader}
+ data-expanded={expanded ? '' : undefined}
+ gap={10}
+ onClick={onToggle}
>
- <Text
- className={expanded ? undefined : styles.titleEllipsis}
- style={{ fontSize: 13, minWidth: 0 }}
- >
- {check.title}
- </Text>
- {!check.required && (
- <Tooltip title={t('acceptance.checks.notRequiredHint')}>
- <Tag size={'small'}>{t('acceptance.checks.notRequired')}</Tag>
- </Tooltip>
+ {reviewState === 'rejected' ? (
+ <Tooltip title={t('acceptance.review.rejectedHint')}>{headIconNode}</Tooltip>
+ ) : (
+ headIconNode
)}
- {/* The verdict pair travels WITH the title, not adrift at the row's
- far right: the claim you judge and the judgement you give land in
- one glance, so a long checklist needs no eye round-trip across the
- row (and no mis-click onto a neighbour's buttons). */}
- {reviewable && reviewState === 'pending' && (
- <Flexbox
- horizontal
- align={'center'}
- className={cx(styles.rowActions, 'acceptance-row-actions')}
- gap={2}
- style={{
- // The accept spinner must stay visible after the pointer leaves.
- ...(accepting ? { opacity: 1 } : undefined),
- flex: 'none',
+ <Tooltip
+ title={seqCopied ? t('acceptance.checks.copied') : t('acceptance.checks.copySeq')}
+ >
+ <span
+ className={cx(styles.seqChip, styles.seqChipClickable)}
+ onClick={(event) => {
+ event.stopPropagation();
+ void copyToClipboard(`C${check.seq}`);
+ setSeqCopied(true);
+ setTimeout(() => setSeqCopied(false), 1500);
}}
>
- <ActionIcon
- disabled={reviewPending && !accepting}
- icon={Check}
- loading={accepting}
- size={'small'}
- title={t('acceptance.review.accept')}
- onClick={handleAccept}
- />
- <ActionIcon
- disabled={reviewPending && !ignoring}
- icon={Ban}
- loading={ignoring}
- size={'small'}
- title={t('acceptance.review.ignore')}
- onClick={handleIgnore}
- />
- <ActionIcon
- disabled={reviewPending}
- icon={MessageSquareX}
- size={'small'}
- title={t('acceptance.review.reject')}
- onClick={(event) => {
- event.stopPropagation();
- openReject();
- }}
- />
- </Flexbox>
- )}
- </Flexbox>
- <Flexbox
- horizontal
- align={'center'}
- className={cx(styles.rowMeta, 'acceptance-row-meta')}
- gap={6}
- >
- {/* An accept on a NON-passed verdict can't merge into the head icon
- (the failed/uncertain mark must stay visible) — mark it here. */}
- {reviewState === 'accepted' && check.state !== 'passed' && (
- <Tooltip
- title={t('acceptance.review.acceptedNote', {
- time: dayjs(check.userReview!.createdAt).format('MM-DD HH:mm'),
- })}
+ C{check.seq}
+ </span>
+ </Tooltip>
+ <Flexbox
+ horizontal
+ align={'center'}
+ flex={1}
+ gap={8}
+ style={{ minWidth: 0 }}
+ wrap={expanded ? 'wrap' : 'nowrap'}
+ >
+ <Text
+ className={expanded ? undefined : styles.titleEllipsis}
+ style={{ fontSize: 13, minWidth: 0 }}
>
- <Icon color={cssVar.colorTextQuaternary} icon={BadgeCheck} size={14} />
- </Tooltip>
- )}
- {visualization && <VisualizationDeltaBadge manifest={visualization} />}
- {EVIDENCE_BADGES.map(({ icon, key, labelKey }) =>
- counts[key] ? (
- <Tooltip key={key} title={t(labelKey, { count: counts[key] })}>
- <Flexbox
- horizontal
- align={'center'}
- gap={3}
- style={{ color: cssVar.colorTextTertiary, fontSize: 11 }}
- >
- <Icon icon={icon} size={13} />
- {counts[key] > 1 ? counts[key] : null}
- </Flexbox>
+ {check.title}
+ </Text>
+ {!check.required && (
+ <Tooltip title={t('acceptance.checks.notRequiredHint')}>
+ <Tag size={'small'}>{t('acceptance.checks.notRequired')}</Tag>
</Tooltip>
- ) : null,
- )}
- {/* The iteration mark stays compact — [↻ N]; the words (verified N
- rounds · introduced in round X) live in its tooltip. Clicking
- jumps to the round the concern first appeared in. */}
- {onRound && check.revisions > 1 && (
- <Tooltip
- title={[
- check.titleChanged
- ? t('acceptance.checks.iterated', { count: check.revisions })
- : t('acceptance.checks.rerun', { count: check.revisions }),
- check.resultRound !== undefined &&
- check.resultRound !== null &&
- check.introducedAtRound !== check.resultRound
- ? t('acceptance.checks.introduced', { round: check.introducedAtRound })
- : null,
- ]
- .filter(Boolean)
- .join(' · ')}
- >
- <span
- className={cx(styles.chip, styles.chipClickable)}
- onClick={(event) => {
- event.stopPropagation();
- onRound(check.introducedAtRound);
- }}
- >
- <Icon icon={Repeat} size={10} /> {check.revisions}
- </span>
- </Tooltip>
- )}
- {onRound && check.resultRound !== undefined && check.resultRound !== null && (
- <Tooltip title={t('acceptance.checks.finalRoundHint')}>
- <span
- className={cx(styles.chip, styles.chipClickable)}
- onClick={(event) => {
- event.stopPropagation();
- onRound(check.resultRound!);
+ )}
+ {/* The verdict pair travels WITH the title, not adrift at the row's
+ far right: the claim you judge and the judgement you give land in
+ one glance, so a long checklist needs no eye round-trip across the
+ row (and no mis-click onto a neighbour's buttons). */}
+ {reviewable && reviewState === 'pending' && (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={cx(styles.rowActions, 'acceptance-row-actions')}
+ gap={2}
+ style={{
+ // The accept spinner must stay visible after the pointer leaves.
+ ...(accepting ? { opacity: 1 } : undefined),
+ flex: 'none',
}}
>
- {t('acceptance.round', { round: check.resultRound })}
- </span>
- </Tooltip>
- )}
- </Flexbox>
- <Flexbox align={'center'} height={22}>
- <Icon
- color={cssVar.colorTextQuaternary}
- icon={ChevronRight}
- size={14}
- style={{
- transform: expanded ? 'rotate(90deg)' : 'none',
- transition: 'transform 0.2s',
- }}
- />
- </Flexbox>
- </Flexbox>
- )}
-
- {expanded && (
- <Flexbox
- gap={10}
- paddingBlock={detailMode ? 0 : '0 14px'}
- paddingInline={detailMode ? 0 : 16}
- >
- {check.result?.toulmin?.evidence && (
- <Text className={styles.descClamp} fontSize={12} type={'secondary'}>
- {check.result.toulmin.evidence}
- </Text>
- )}
- {visualization && <VisualizationRenderer manifest={visualization} />}
- <EvidenceList evidence={check.evidence} />
-
- {check.state === 'not_executed' && (
+ <ActionIcon
+ disabled={reviewPending && !accepting}
+ icon={Check}
+ loading={accepting}
+ size={'small'}
+ title={t('acceptance.review.accept')}
+ onClick={handleAccept}
+ />
+ <ActionIcon
+ disabled={reviewPending && !ignoring}
+ icon={Ban}
+ loading={ignoring}
+ size={'small'}
+ title={t('acceptance.review.ignore')}
+ onClick={handleIgnore}
+ />
+ <ActionIcon
+ disabled={reviewPending}
+ icon={MessageSquareX}
+ size={'small'}
+ title={t('acceptance.review.reject')}
+ onClick={(event) => {
+ event.stopPropagation();
+ openReject();
+ }}
+ />
+ </Flexbox>
+ )}
+ </Flexbox>
<Flexbox
horizontal
align={'center'}
- gap={8}
- paddingBlock={8}
- paddingInline={10}
- style={{
- background: cssVar.colorFillQuaternary,
- borderRadius: cssVar.borderRadius,
- width: '100%',
- }}
+ className={cx(styles.rowMeta, 'acceptance-row-meta')}
+ gap={6}
>
+ {/* An accept on a NON-passed verdict can't merge into the head icon
+ (the failed/uncertain mark must stay visible) — mark it here. */}
+ {reviewState === 'accepted' && check.state !== 'passed' && (
+ <Tooltip
+ title={t('acceptance.review.acceptedNote', {
+ time: dayjs(check.userReview!.createdAt).format('MM-DD HH:mm'),
+ })}
+ >
+ <Icon color={cssVar.colorTextQuaternary} icon={BadgeCheck} size={14} />
+ </Tooltip>
+ )}
+ {visualization && <VisualizationDeltaBadge manifest={visualization} />}
+ {EVIDENCE_BADGES.map(({ icon, key, labelKey }) =>
+ counts[key] ? (
+ <Tooltip key={key} title={t(labelKey, { count: counts[key] })}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={3}
+ style={{ color: cssVar.colorTextTertiary, fontSize: 11 }}
+ >
+ <Icon icon={icon} size={13} />
+ {counts[key] > 1 ? counts[key] : null}
+ </Flexbox>
+ </Tooltip>
+ ) : null,
+ )}
+ {/* The iteration mark stays compact — [↻ N]; the words (verified N
+ rounds · introduced in round X) live in its tooltip. Clicking
+ jumps to the round the concern first appeared in. */}
+ {onRound && check.revisions > 1 && (
+ <Tooltip
+ title={[
+ check.titleChanged
+ ? t('acceptance.checks.iterated', { count: check.revisions })
+ : t('acceptance.checks.rerun', { count: check.revisions }),
+ check.resultRound !== undefined &&
+ check.resultRound !== null &&
+ check.introducedAtRound !== check.resultRound
+ ? t('acceptance.checks.introduced', { round: check.introducedAtRound })
+ : null,
+ ]
+ .filter(Boolean)
+ .join(' · ')}
+ >
+ <span
+ className={cx(styles.chip, styles.chipClickable)}
+ onClick={(event) => {
+ event.stopPropagation();
+ onRound(check.introducedAtRound);
+ }}
+ >
+ <Icon icon={Repeat} size={10} /> {check.revisions}
+ </span>
+ </Tooltip>
+ )}
+ {onRound && check.resultRound !== undefined && check.resultRound !== null && (
+ <Tooltip title={t('acceptance.checks.finalRoundHint')}>
+ <span
+ className={cx(styles.chip, styles.chipClickable)}
+ onClick={(event) => {
+ event.stopPropagation();
+ onRound(check.resultRound!);
+ }}
+ >
+ {t('acceptance.round', { round: check.resultRound })}
+ </span>
+ </Tooltip>
+ )}
+ </Flexbox>
+ <Flexbox align={'center'} height={22}>
<Icon
color={cssVar.colorTextQuaternary}
- icon={CircleDashed}
- size={15}
- style={{ flex: 'none' }}
+ icon={ChevronRight}
+ size={14}
+ style={{
+ transform: expanded ? 'rotate(90deg)' : 'none',
+ transition: 'transform 0.2s',
+ }}
/>
- <Text fontSize={12} type={'secondary'}>
- {t('acceptance.focus.verifierDescription.notExecuted')}
- </Text>
</Flexbox>
- )}
+ </Flexbox>
+ )}
- {/* An executed check with zero artifacts must SAY so — a silent blank
- under the verdict reads as a rendering bug, not as a fact. Filled
- so it reads as a status, never as more description text. */}
- {check.state !== 'not_executed' &&
- check.result &&
- !hasRenderableEvidence(check.evidence.length, visualization) && (
+ {expanded && (
+ <Flexbox
+ gap={10}
+ paddingBlock={detailMode ? 0 : '0 14px'}
+ paddingInline={detailMode ? 0 : 16}
+ >
+ {/* The verifier's account of what it saw. Clamping it to two lines
+ hid the middle of the argument behind an ellipsis with no way to
+ open it — in a detail view there is nothing to preview. */}
+ {check.result?.toulmin?.evidence && (
+ <Text fontSize={12} style={{ whiteSpace: 'pre-wrap' }} type={'secondary'}>
+ {check.result.toulmin.evidence}
+ </Text>
+ )}
+ {/* An agent judge's argument is its run, not a paragraph — link the
+ trace instead of trying to summarize it inline. `onOpenTrace`
+ gates the render, not just the click: a caller that forgets to
+ pass it would otherwise get a button whose optional call silently
+ does nothing — exactly how this shipped dead in the portal. */}
+ {check.planItem?.verifierType === 'agent' &&
+ check.result?.verifierOperationId &&
+ onOpenTrace && (
+ <Flexbox horizontal>
+ <Button
+ icon={<Icon icon={Route} />}
+ size={'small'}
+ type={'text'}
+ onClick={(event) => {
+ event.stopPropagation();
+ void onOpenTrace(check.result!.verifierOperationId!);
+ }}
+ >
+ {t('acceptance.checks.viewTrace')}
+ </Button>
+ </Flexbox>
+ )}
+ {visualization && <VisualizationRenderer manifest={visualization} />}
+ <EvidenceList evidence={check.evidence} />
+
+ {check.state === 'not_executed' && (
<Flexbox
- paddingBlock={6}
+ horizontal
+ align={'center'}
+ gap={8}
+ paddingBlock={8}
paddingInline={10}
style={{
background: cssVar.colorFillQuaternary,
@@ -1139,39 +1145,69 @@ const CheckRow = memo<{
width: '100%',
}}
>
+ <Icon
+ color={cssVar.colorTextQuaternary}
+ icon={CircleDashed}
+ size={15}
+ style={{ flex: 'none' }}
+ />
<Text fontSize={12} type={'secondary'}>
- {t('acceptance.evidence.empty')}
+ {t('acceptance.focus.verifierDescription.notExecuted')}
</Text>
</Flexbox>
)}
- {/* The user's standing feedback hangs right under the evidence it
+ {/* The verifier's record slot. An LLM judge's whole product IS its
+ reasoning, so when it exists it IS the record shown here — in the
+ same slot the empty-evidence note otherwise occupies (the two are
+ the same statement: "here is what the verifier left behind"). An
+ executed check with neither still SAYS so — a silent blank under
+ the verdict reads as a rendering bug, not as a fact. */}
+ {check.state !== 'not_executed' &&
+ check.result &&
+ (check.result.toulmin?.reasoning ? (
+ <Flexbox
+ gap={4}
+ paddingBlock={8}
+ paddingInline={10}
+ style={{
+ background: cssVar.colorFillQuaternary,
+ borderRadius: cssVar.borderRadius,
+ width: '100%',
+ }}
+ >
+ <Text fontSize={11} type={'secondary'}>
+ {t('acceptance.checks.judgeReason')}
+ </Text>
+ <Text fontSize={12} style={{ whiteSpace: 'pre-wrap' }}>
+ {check.result.toulmin.reasoning}
+ </Text>
+ </Flexbox>
+ ) : !hasRenderableEvidence(check.evidence.length, visualization) ? (
+ <Flexbox
+ paddingBlock={6}
+ paddingInline={10}
+ style={{
+ background: cssVar.colorFillQuaternary,
+ borderRadius: cssVar.borderRadius,
+ width: '100%',
+ }}
+ >
+ <Text fontSize={12} type={'secondary'}>
+ {t('acceptance.evidence.empty')}
+ </Text>
+ </Flexbox>
+ ) : null)}
+
+ {/* The user's standing feedback hangs right under the evidence it
judges. BOTH verdicts keep an undo path — a mis-click is the most
likely way either happens, and a send-back the user didn't mean
otherwise costs a whole repair round to walk back. */}
- {activeReview &&
- (activeReview.action === 'accept' ? (
- <Flexbox horizontal align={'center'} gap={8}>
- <AcceptedNote review={activeReview} />
- {reviewable && (
- <Button
- disabled={reviewPending}
- size={'small'}
- type={'text'}
- onClick={(event) => {
- event.stopPropagation();
- openReject();
- }}
- >
- {t('acceptance.review.revertToReject')}
- </Button>
- )}
- </Flexbox>
- ) : activeReview.action === 'ignore' ? (
- <Flexbox horizontal align={'center'} gap={8}>
- <IgnoredNote review={activeReview} />
- {reviewable && (
- <>
+ {activeReview &&
+ (activeReview.action === 'accept' ? (
+ <Flexbox horizontal align={'center'} gap={8}>
+ <AcceptedNote review={activeReview} />
+ {reviewable && (
<Button
disabled={reviewPending}
size={'small'}
@@ -1183,155 +1219,179 @@ const CheckRow = memo<{
>
{t('acceptance.review.revertToReject')}
</Button>
+ )}
+ </Flexbox>
+ ) : activeReview.action === 'ignore' ? (
+ <Flexbox horizontal align={'center'} gap={8}>
+ <IgnoredNote review={activeReview} />
+ {reviewable && (
+ <>
+ <Button
+ disabled={reviewPending}
+ size={'small'}
+ type={'text'}
+ onClick={(event) => {
+ event.stopPropagation();
+ openReject();
+ }}
+ >
+ {t('acceptance.review.revertToReject')}
+ </Button>
+ <Button
+ disabled={reviewPending && !accepting}
+ loading={accepting}
+ size={'small'}
+ type={'text'}
+ onClick={handleAccept}
+ >
+ {t('acceptance.review.revertToAccept')}
+ </Button>
+ </>
+ )}
+ </Flexbox>
+ ) : (
+ <Flexbox gap={6}>
+ <FeedbackCard evidenceById={evidenceById} review={activeReview} />
+ {/* The mirror of the accept escape: take the send-back back.
+ A fresh accept supersedes the reject, so the check leaves
+ 待修复 and the feedback drops out of the next round's input. */}
+ {reviewable && (
+ <Flexbox horizontal>
+ <Button
+ disabled={reviewPending && !accepting}
+ loading={accepting}
+ size={'small'}
+ type={'text'}
+ onClick={handleAccept}
+ >
+ {t('acceptance.review.revertToAccept')}
+ </Button>
+ </Flexbox>
+ )}
+ </Flexbox>
+ ))}
+
+ {/* Confirm (plain filled) anchors the right edge; reject is the
+ quiet text escape next to it. */}
+ {reviewable &&
+ !activeReview &&
+ (detailMode ? (
+ <Flexbox gap={10} style={{ marginBlockStart: 6 }}>
+ {hasAnnotatableEvidence(check) && (
<Button
- disabled={reviewPending && !accepting}
- loading={accepting}
- size={'small'}
+ icon={<Icon icon={Images} />}
+ style={{ alignSelf: 'flex-start' }}
type={'text'}
- onClick={handleAccept}
+ onClick={(event) => {
+ event.stopPropagation();
+ openReject();
+ }}
>
- {t('acceptance.review.revertToAccept')}
+ {t('acceptance.review.annotate')}
</Button>
- </>
- )}
- </Flexbox>
- ) : (
- <Flexbox gap={6}>
- <FeedbackCard evidenceById={evidenceById} review={activeReview} />
- {/* The mirror of the accept escape: take the send-back back.
- A fresh accept supersedes the reject, so the check leaves
- 待修复 and the feedback drops out of the next round's input. */}
- {reviewable && (
- <Flexbox horizontal>
+ )}
+ <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={'small'}
- type={'text'}
+ size={'large'}
+ style={{ flex: 1 }}
+ type={'fill'}
onClick={handleAccept}
>
- {t('acceptance.review.revertToAccept')}
+ {t('acceptance.review.accept')}
</Button>
</Flexbox>
- )}
- </Flexbox>
- ))}
-
- {/* Confirm (plain filled) anchors the right edge; reject is the
- quiet text escape next to it. */}
- {reviewable &&
- !activeReview &&
- (detailMode ? (
- <Flexbox gap={10} style={{ marginBlockStart: 6 }}>
- {hasAnnotatableEvidence(check) && (
+ </Flexbox>
+ ) : (
+ <Flexbox horizontal gap={4} justify={'flex-end'}>
<Button
- icon={<Icon icon={Images} />}
- style={{ alignSelf: 'flex-start' }}
+ 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.annotate')}
- </Button>
- )}
- <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 }}
+ size={'small'}
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)}>
- <Icon
- icon={ChevronRight}
- size={12}
- style={{
- transform: historyOpen ? 'rotate(90deg)' : 'none',
- transition: 'transform 0.2s',
- }}
+ {hasHistory && (
+ <span
+ className={styles.historyToggle}
+ onClick={() => setHistoryOpen((open) => !open)}
+ >
+ <Icon
+ icon={ChevronRight}
+ size={12}
+ style={{
+ transform: historyOpen ? 'rotate(90deg)' : 'none',
+ transition: 'transform 0.2s',
+ }}
+ />
+ {t('acceptance.checks.iterationHistory', { count: check.revisions })}
+ </span>
+ )}
+ {historyOpen && hasHistory && (
+ <IterationTimeline
+ check={check}
+ evidenceById={evidenceById}
+ historyReviews={historyReviews}
+ onRound={onRound}
/>
- {t('acceptance.checks.iterationHistory', { count: check.revisions })}
- </span>
- )}
- {historyOpen && hasHistory && (
- <IterationTimeline
- check={check}
- evidenceById={evidenceById}
- historyReviews={historyReviews}
- onRound={onRound}
- />
- )}
- </Flexbox>
- )}
- </Flexbox>
- );
-});
+ )}
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+ },
+);
interface FocusedCheckDetailsProps {
canReview: boolean;
check: AcceptanceCheck;
+ /** Open an agent judge's verification run (its trace IS the argument). */
+ onOpenTrace?: (verifierOperationId: string) => void | Promise<void>;
onReview: (input: CheckReviewInput) => Promise<boolean>;
onRound?: (round: number) => void;
reviewPending: boolean;
@@ -1339,13 +1399,14 @@ interface FocusedCheckDetailsProps {
/** Full check content for the dedicated second-level acceptance workspace. */
export const FocusedCheckDetails = memo<FocusedCheckDetailsProps>(
- ({ canReview, check, onReview, onRound, reviewPending }) => (
+ ({ canReview, check, onOpenTrace, onReview, onRound, reviewPending }) => (
<CheckRow
detailMode
expanded
canReview={canReview}
check={check}
reviewPending={reviewPending}
+ onOpenTrace={onOpenTrace}
onReview={onReview}
onRound={onRound}
onToggle={() => {}}
@@ -1425,6 +1486,8 @@ interface CheckListProps {
groupFeedback: AcceptanceGroupFeedback[];
/** Record group-scoped feedback; resolves true when the write landed. */
onGroupFeedback: (category: string, comment: string, fileIds: string[]) => Promise<boolean>;
+ /** Open an agent judge's verification run (its trace IS the argument). */
+ onOpenTrace?: (verifierOperationId: string) => void | Promise<void>;
/** Record the user's verdict; resolves true when the write landed. */
onReview: (input: CheckReviewInput) => Promise<boolean>;
onRound?: (round: number) => void;
@@ -1448,6 +1511,7 @@ const CheckList = memo<CheckListProps>(
groupFeedback,
onGroupFeedback,
onReview,
+ onOpenTrace,
onRound,
onToggleGroup,
onToggleGroupItems,
@@ -1535,6 +1599,7 @@ const CheckList = memo<CheckListProps>(
expanded={expanded.has(check.id)}
key={check.id}
reviewPending={reviewPending}
+ onOpenTrace={onOpenTrace}
onReview={onReview}
onRound={onRound}
onToggle={() => onToggleItem(check.id)}
@@ -1772,6 +1837,7 @@ const CheckList = memo<CheckListProps>(
expanded={expanded.has(check.id)}
key={check.id}
reviewPending={reviewPending}
+ onOpenTrace={onOpenTrace}
onReview={onReview}
onRound={onRound}
onToggle={() => onToggleItem(check.id)}
diff --git a/src/features/Verify/Acceptance/LedgerPanel.tsx b/src/features/Verify/Acceptance/LedgerPanel.tsx
index 7586093af95..e7edf3de1a5 100644
--- a/src/features/Verify/Acceptance/LedgerPanel.tsx
+++ b/src/features/Verify/Acceptance/LedgerPanel.tsx
@@ -12,6 +12,7 @@ import {
Loader2,
PanelRightClose,
RefreshCw,
+ RotateCcw,
} from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -139,24 +140,41 @@ const LedgerPanel = memo<LedgerPanelProps>(
const accepted = rv?.accepted ?? 0;
const allAccepted = total > 0 && accepted >= total;
+ // A round the user sent back is a distinct outcome, not "still
+ // pending" — without this it renders identically to an unreviewed
+ // round, so the ledger cannot show which round triggered a rerun.
+ const rejected = round.run.userDecision === 'reject';
+
const stateColor = runningMeta
? runningMeta.color
- : allAccepted
- ? cssVar.colorSuccess
- : cssVar.colorTextTertiary;
- const stateIcon = runningMeta ? runningMeta.icon : allAccepted ? CheckCircle2 : Circle;
+ : rejected
+ ? cssVar.colorError
+ : allAccepted
+ ? cssVar.colorSuccess
+ : cssVar.colorTextTertiary;
+ const stateIcon = runningMeta
+ ? runningMeta.icon
+ : rejected
+ ? RotateCcw
+ : allAccepted
+ ? CheckCircle2
+ : Circle;
const stateLabel = runningMeta
? t(`acceptance.roundStatus.${runStatus}` as 'acceptance.roundStatus.verifying', {
defaultValue: runStatus,
})
- : allAccepted
- ? t('acceptance.ledger.accepted')
- : t('acceptance.ledger.pending');
+ : rejected
+ ? t('acceptance.status.rejected')
+ : allAccepted
+ ? t('acceptance.ledger.accepted')
+ : t('acceptance.ledger.pending');
// Acceptance-framed stats: how many of THIS round's checks are signed
- // off (accepted/total), or all still awaiting.
- const stats =
- running || total === 0
+ // off (accepted/total), or all still awaiting. A rejected round shows
+ // the reason instead — it is the input that seeded the next round.
+ const stats = rejected
+ ? round.run.decisionDetail?.comment || t('acceptance.banner.rejectedHint')
+ : running || total === 0
? null
: accepted > 0
? t('acceptance.ledger.acceptedStats', { accepted, total })
diff --git a/src/features/Verify/Acceptance/index.tsx b/src/features/Verify/Acceptance/index.tsx
index 830ab026b9c..18fa1364696 100644
--- a/src/features/Verify/Acceptance/index.tsx
+++ b/src/features/Verify/Acceptance/index.tsx
@@ -433,6 +433,23 @@ const AcceptancePage = memo<AcceptancePageProps>(
setTopicPanelOpen(true);
setLedgerExpand(true);
}, [data, openTopicDrawer]);
+
+ /**
+ * An agent judge argues by running, not by writing a paragraph — so the
+ * reviewable form of its verdict is its own conversation. Resolve the
+ * verifier operation to its topic and open the same drawer used for the
+ * origin run.
+ */
+ const openVerifierTrace = useCallback(
+ async (verifierOperationId: string) => {
+ const resolved = await verifyService.getVerifierThread(verifierOperationId);
+ const topicId = resolved?.topicId;
+ if (!topicId) return;
+ openTopicDrawer(topicId, { title: t('acceptance.checks.viewTrace') });
+ setTopicPanelOpen(true);
+ },
+ [openTopicDrawer, t],
+ );
const [reportRound, setReportRound] = useState<AcceptanceRound | null>(null);
// `?r=<roundIndex>` deep-links one round's full report — a durable
// per-round snapshot URL (standalone page only; the portal embed rides the
@@ -1787,6 +1804,7 @@ const AcceptancePage = memo<AcceptancePageProps>(
reviewPending={pending}
round={roundFilter}
onGroupFeedback={handleGroupFeedback}
+ onOpenTrace={openVerifierTrace}
onReview={handleReview}
onRound={historyNavigation}
onToggleGroup={handleToggleGroup}
diff --git a/src/features/Verify/hooks.test.ts b/src/features/Verify/hooks.test.ts
index 4cecfdbf147..75efa2dffe7 100644
--- a/src/features/Verify/hooks.test.ts
+++ b/src/features/Verify/hooks.test.ts
@@ -72,10 +72,15 @@ describe('Verify data hooks', () => {
expect(getAcceptanceBySubject).toHaveBeenCalledWith('task', 'T-231');
});
- it('polls while a task has no acceptance and stops after one is created', () => {
+ it('polls fastest before an acceptance exists, then keeps it live until it settles', () => {
expect(getAcceptanceBySubjectRefreshInterval(undefined)).toBe(2000);
expect(getAcceptanceBySubjectRefreshInterval(null)).toBe(2000);
- expect(getAcceptanceBySubjectRefreshInterval({ id: 'acceptance-1' })).toBe(0);
+ // A task page left open through a goal loop would otherwise keep rendering
+ // whatever state it first saw, all the way through delivery.
+ expect(getAcceptanceBySubjectRefreshInterval({ id: 'a1', status: 'verifying' })).toBe(5000);
+ expect(getAcceptanceBySubjectRefreshInterval({ id: 'a1', status: 'delivered' })).toBe(5000);
+ expect(getAcceptanceBySubjectRefreshInterval({ id: 'a1', status: 'accepted' })).toBe(0);
+ expect(getAcceptanceBySubjectRefreshInterval({ id: 'a1', status: 'closed' })).toBe(0);
});
it('does not request rubrics while rubric authoring is inactive', async () => {
diff --git a/src/features/Verify/hooks.ts b/src/features/Verify/hooks.ts
index 623439b62b4..ba6821cf7bf 100644
--- a/src/features/Verify/hooks.ts
+++ b/src/features/Verify/hooks.ts
@@ -25,8 +25,21 @@ const ACCEPTANCE_BUNDLE_SWR_CONFIG = {
revalidateOnReconnect: true,
} as const;
-export const getAcceptanceBySubjectRefreshInterval = (acceptance: unknown) =>
- acceptance ? 0 : 2000;
+/**
+ * Poll until the aggregate exists AND stops moving.
+ *
+ * Discovery was the only case handled before, so a task page left open during
+ * a goal loop kept rendering whatever state it first saw — "awaiting
+ * verification" straight through verifying, delivery and acceptance — until a
+ * focus or remount happened to refetch.
+ */
+const TERMINAL_ACCEPTANCE_STATUSES = new Set(['accepted', 'closed']);
+
+export const getAcceptanceBySubjectRefreshInterval = (acceptance: unknown) => {
+ if (!acceptance) return 2000;
+ const status = (acceptance as { status?: string }).status;
+ return status && TERMINAL_ACCEPTANCE_STATUSES.has(status) ? 0 : 5000;
+};
/** Plan + rollup status for one Agent Run. Pass null operationId to skip. */
export const useVerifyState = (operationId: string | null) =>
diff --git a/src/routes/(main)/agent/task/[taskId]/index.tsx b/src/routes/(main)/agent/task/[taskId]/index.tsx
index 14da82760b3..bf1e9d38b08 100644
--- a/src/routes/(main)/agent/task/[taskId]/index.tsx
+++ b/src/routes/(main)/agent/task/[taskId]/index.tsx
@@ -1,16 +1,28 @@
'use client';
+import { Flexbox } from '@lobehub/ui';
import { memo } from 'react';
import { useParams } from 'react-router';
import { TaskDetailPage } from '@/features/AgentTasks';
+import ChatPortal from '@/routes/(main)/agent/features/Portal';
const AgentTaskDetailRoute = memo(() => {
const { taskId } = useParams<{ taskId?: string }>();
if (!taskId) return null;
- return <TaskDetailPage showTaskAgentPanelToggle={false} taskId={taskId} />;
+ return (
+ <Flexbox horizontal flex={1} height={'100%'} style={{ minHeight: 0 }} width={'100%'}>
+ <Flexbox flex={1} style={{ minWidth: 0 }}>
+ <TaskDetailPage showTaskAgentPanelToggle={false} taskId={taskId} />
+ </Flexbox>
+ {/* Task detail opens acceptance checks in the portal. This route sits
+ beside the (chat) subtree that normally mounts one, so without its own
+ host every check click pushed a view nothing rendered — a dead click. */}
+ <ChatPortal />
+ </Flexbox>
+ );
});
export default AgentTaskDetailRoute;