🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(goal): Delivery tab for finished Goals with a wrap-up storyline (#20189)
Arvin Xudb7196e715c2
diff --git a/apps/cli/src/commands/goal.test.ts b/apps/cli/src/commands/goal.test.tsindex 4d0f1296c0c..9f3508fdfe6 100644--- a/apps/cli/src/commands/goal.test.ts+++ b/apps/cli/src/commands/goal.test.ts@@ -13,6 +13,8 @@ const { mockClient } = vi.hoisted(() => ({delete: { mutate: vi.fn() },submitPlan: { mutate: vi.fn() },submitOperationPlan: { mutate: vi.fn() },+ submitOperationReport: { mutate: vi.fn() },+ submitReport: { mutate: vi.fn() },graph: { query: vi.fn() },setBudget: { mutate: vi.fn() },supervision: { query: vi.fn() },@@ -104,6 +106,55 @@ describe('goal plan authentication', () => {);});+describe('goal report authentication', () => {+ afterEach(() => {+ vi.unstubAllEnvs();+ vi.mocked(console.log).mockRestore();+ });++ it.each(['hetero-operation', undefined])(+ 'routes %s credentials to the appropriate report endpoint',+ async (purpose) => {+ vi.clearAllMocks();+ vi.stubEnv(+ 'LOBEHUB_JWT',+ purpose+ ? `header.${Buffer.from(JSON.stringify({ purpose })).toString('base64url')}.signature`+ : undefined,+ );+ vi.stubEnv('LOBEHUB_OPERATION_ID', 'op-wrapup');+ vi.spyOn(console, 'log').mockImplementation(() => {});+ mockClient.goal.submitReport.mutate.mockResolvedValue({ data: {} });+ mockClient.goal.submitOperationReport.mutate.mockResolvedValue({ data: {} });+ await createProgram().parseAsync([+ 'node',+ 'test',+ 'goal',+ 'report',+ 'goal-1',+ '--metadata-file',+ 'report.json',+ '--content-file',+ 'report.md',+ ]);+ const [selected, other] =+ purpose === 'hetero-operation'+ ? [mockClient.goal.submitOperationReport, mockClient.goal.submitReport]+ : [mockClient.goal.submitReport, mockClient.goal.submitOperationReport];+ // The mocked readFile returns the same text for both files.+ expect(selected.mutate).toHaveBeenCalledWith({+ id: 'goal-1',+ operationId: 'op-wrapup',+ report: {+ content: JSON.stringify({ action: 'verify', reason: 'Ready' }),+ metadata: { action: 'verify', reason: 'Ready' },+ },+ });+ expect(other.mutate).not.toHaveBeenCalled();+ },+ );+});+describe('goal run command', () => {beforeEach(() => {vi.clearAllMocks();diff --git a/apps/cli/src/commands/goal.ts b/apps/cli/src/commands/goal.tsindex 4cb2ffd4854..41fa7c76ca3 100644--- a/apps/cli/src/commands/goal.ts+++ b/apps/cli/src/commands/goal.ts@@ -217,6 +217,40 @@ export function registerGoalCommand(program: Command) {},);+ goal+ .command('report <id>')+ .description("Submit this Goal's wrap-up report from its wrap-up run")+ .requiredOption(+ '--metadata-file <path>',+ 'JSON: headline, deliverableWorkId, chapters, mainline, nextSteps, graphCursor',+ )+ .requiredOption('--content-file <path>', 'The full written report in markdown')+ .option('--operation <id>', 'Defaults to LOBEHUB_OPERATION_ID')+ .option('--json', 'Output JSON')+ .action(+ async (+ id: string,+ options: { contentFile: string; json?: boolean; metadataFile: string; operation?: string },+ ) => {+ const operationId = options.operation ?? process.env.LOBEHUB_OPERATION_ID;+ if (!operationId) throw new Error('Current wrap-up operation ID required');+ const client = await getTrpcClient();+ const endpoint = hasOperationToken()+ ? client.goal.submitOperationReport+ : client.goal.submitReport;+ const result = await endpoint.mutate({+ id,+ operationId,+ report: {+ content: await readFile(options.contentFile, 'utf8'),+ metadata: JSON.parse(await readFile(options.metadataFile, 'utf8')),+ },+ });+ if (options.json) outputJson(result.data);+ else console.log('Goal report recorded.');+ },+ );+goal.command('create <title>').option(diff --git a/apps/server/src/routers/lambda/__tests__/acceptance.reject.test.ts b/apps/server/src/routers/lambda/__tests__/acceptance.reject.test.tsindex 2afc5286b8d..a261b889904 100644--- a/apps/server/src/routers/lambda/__tests__/acceptance.reject.test.ts+++ b/apps/server/src/routers/lambda/__tests__/acceptance.reject.test.ts@@ -10,6 +10,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type * as RbacPermissionModule from '@/business/server/trpc-middlewares/rbacPermission';import type * as AcceptanceModelModule from '@/database/models/acceptance';import type * as GoalModelModule from '@/database/models/goal';+import type * as GoalServiceModule from '@/server/services/goal';import { acceptanceRouter } from '../acceptance';import { cleanupTestUser, createTestContext, createTestUser } from './integration/setup';@@ -59,6 +60,20 @@ vi.mock('@/database/models/goal', async (importOriginal) => {}return { ...actual, GoalModel };});+const mockReopenForChanges = vi.fn();+vi.mock('@/server/services/goal', async (importOriginal) => {+ const actual = await importOriginal<typeof GoalServiceModule>();+ return {+ ...actual,+ GoalService: vi.fn().mockImplementation(function () {+ return { reopenForChanges: mockReopenForChanges };+ }),+ };+});+const mockScheduleGoalAdvance = vi.fn();+vi.mock('@/server/services/goal/scheduler', () => ({+ scheduleGoalAdvance: (...args: unknown[]) => mockScheduleGoalAdvance(...args),+}));vi.mock('@/database/models/acceptance', async (importOriginal) => {const actual = await importOriginal<typeof AcceptanceModelModule>();class AcceptanceModel extends actual.AcceptanceModel {@@ -108,6 +123,8 @@ describe('acceptanceRouter reject', () => {afterEach(async () => {mockExecAgent.mockReset();+ mockReopenForChanges.mockReset();+ mockScheduleGoalAdvance.mockReset();flags.denyMessageCreate = false;flags.failRepairingStamp = false;flags.goalOwnsTask = false;@@ -224,6 +241,41 @@ describe('acceptanceRouter reject', () => {expect(mockExecAgent).not.toHaveBeenCalled();});+ it('reopens the Goal a rejected Goal-level acceptance ended, and queues its rework', async () => {+ await serverDB+ .update(acceptances)+ .set({ subjectId: 'task_goal_acceptance', subjectType: 'task' })+ .where(eq(acceptances.id, acceptanceId));+ flags.goalOwnsTask = true;+ mockReopenForChanges.mockResolvedValue('goal_1');++ const caller = acceptanceRouter.createCaller(createTestContext(userId));+ const result = await caller.reject({ comment: 'Add a day-one agenda', id: acceptanceId });++ expect(result.repairDispatch).toEqual({ dispatched: false, reason: 'goal_coordinator' });+ expect(mockReopenForChanges).toHaveBeenCalledWith(+ 'task_goal_acceptance',+ 'Add a day-one agenda',+ );+ expect(mockScheduleGoalAdvance).toHaveBeenCalledWith(+ expect.objectContaining({ goalId: 'goal_1', trigger: 'decide', userId }),+ );+ });++ it('does not queue an advance when the Goal was not reopened', async () => {+ await serverDB+ .update(acceptances)+ .set({ subjectId: 'task_goal', subjectType: 'task' })+ .where(eq(acceptances.id, acceptanceId));+ flags.goalOwnsTask = true;+ mockReopenForChanges.mockResolvedValue(undefined);++ const caller = acceptanceRouter.createCaller(createTestContext(userId));+ await caller.reject({ comment: 'Rework the draft', id: acceptanceId });++ expect(mockScheduleGoalAdvance).not.toHaveBeenCalled();+ });+it('still reports the dispatch when the repairing stamp fails after the run started', async () => {const { agentId, topicId } = await seedTopic();await seedOrigin({ topicId });diff --git a/apps/server/src/routers/lambda/_helpers/acceptanceRepairDispatch.ts b/apps/server/src/routers/lambda/_helpers/acceptanceRepairDispatch.tsindex 0501f3fad63..ab2782efdc7 100644--- a/apps/server/src/routers/lambda/_helpers/acceptanceRepairDispatch.ts+++ b/apps/server/src/routers/lambda/_helpers/acceptanceRepairDispatch.ts@@ -6,6 +6,8 @@ import { GoalModel } from '@/database/models/goal';import { TopicModel } from '@/database/models/topic';import type { AcceptanceItem } from '@/database/schemas/verify';import type { LobeChatDatabase } from '@/database/type';+import { GoalService } from '@/server/services/goal';+import { scheduleGoalAdvance } from '@/server/services/goal/scheduler';import type { AcceptanceService } from '@/server/services/verify';import { agentNotifyRouter } from '../agentNotify';@@ -66,12 +68,27 @@ export const dispatchAcceptanceRepair = async (// rejected round through the prompt builder and claims the task. A plain// run in the old topic would race it into a second, unaccounted attempt.if (acceptance.subjectType === 'task') {- const goal = await new GoalModel(- ctx.serverDB,- acceptance.userId,- acceptance.workspaceId ?? undefined,- ).findByGraphTask(acceptance.subjectId);- if (goal) return { dispatched: false, reason: 'goal_coordinator' };+ const workspaceId = acceptance.workspaceId ?? undefined;+ const goal = await new GoalModel(ctx.serverDB, acceptance.userId, workspaceId).findByGraphTask(+ acceptance.subjectId,+ );+ if (goal) {+ // The Goal-level acceptance passing is what ended the Goal: sending it+ // back reopens the Goal so the coordinator has a next attempt to start.+ const reopened = await new GoalService(+ ctx.serverDB,+ acceptance.userId,+ workspaceId,+ ).reopenForChanges(acceptance.subjectId, rejectComment);+ if (reopened)+ await scheduleGoalAdvance({+ goalId: reopened,+ trigger: 'decide',+ userId: acceptance.userId,+ workspaceId,+ });+ return { dispatched: false, reason: 'goal_coordinator' };+ }}const origin = await service.findRepairOrigin(acceptance.id);diff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.tsindex d1cd34b39c8..f30ceac3399 100644--- a/apps/server/src/routers/lambda/goal.ts+++ b/apps/server/src/routers/lambda/goal.ts@@ -15,6 +15,7 @@ import {DEFAULT_MANAGER_MAX_TURNS,managerTurnsSpent,} from '@/server/services/goal/recoveryPolicy';+import { GoalReportStore, type SubmitGoalReportInput } from '@/server/services/goal/reportStore';import { scheduleGoalAdvance } from '@/server/services/goal/scheduler';import {HeteroOperationPrincipalError,@@ -41,6 +42,18 @@ const goalProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>);const goalWriteProcedure = goalProcedure.use(withScopedPermission('agent:update'));const idInput = z.object({ id: z.string() });+/**+ * A wrap-up report submitted from a run. The metadata passes through as a+ * record: `GoalReportStore.submit` parses it with the report schema and checks+ * every reference against the Goal graph.+ */+const reportInput = idInput.extend({+ operationId: z.string().min(1),+ report: z.object({+ content: z.string(),+ metadata: z.record(z.string(), z.unknown()),+ }),+});/** Everything a goal is created from except who owns it. */const conversationGoalInput = z.object({@@ -190,6 +203,50 @@ export const goalRouter = router({});return { data, success: true };}),+ // The wrap-up report of a heterogeneous agent's run: server tools never reach+ // a device run, so its report arrives through the CLI instead of the tool.+ submitOperationReport: heteroAuthedProcedure+ .use(serverDatabase)+ .input(reportInput)+ .mutation(async ({ ctx, input }) => {+ if (ctx.heteroAuthKind !== 'operation' || !ctx.heteroOperation) {+ throw new TRPCError({+ code: 'UNAUTHORIZED',+ message: 'An operation-bound token is required',+ });+ }+ let principal;+ try {+ principal = await resolveActiveHeteroOperationPrincipal({+ capability: 'hetero:ingest',+ claims: ctx.heteroOperation,+ db: ctx.serverDB,+ operationId: input.operationId,+ });+ } catch (error) {+ if (!(error instanceof HeteroOperationPrincipalError)) throw error;+ throw new TRPCError({+ cause: error,+ code:+ error.status === 401 ? 'UNAUTHORIZED' : error.status === 409 ? 'CONFLICT' : 'FORBIDDEN',+ message: error.message,+ });+ }+ const data = await new GoalReportStore(+ ctx.serverDB,+ principal.userId,+ principal.workspaceId,+ ).submitFromOperation(input.id, input.report as SubmitGoalReportInput, input.operationId);+ return { data, success: true };+ }),+ submitReport: goalWriteProcedure.input(reportInput).mutation(async ({ ctx, input }) => {+ const data = await new GoalReportStore(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ ).submitFromOperation(input.id, input.report as SubmitGoalReportInput, input.operationId);+ return { data, success: true };+ }),submitPlan: goalWriteProcedure.input(idInput.extend({diff --git a/apps/server/src/services/goal/decideNextMove.ts b/apps/server/src/services/goal/decideNextMove.tsindex aae1d60f7d9..f5bbdeacd18 100644--- a/apps/server/src/services/goal/decideNextMove.ts+++ b/apps/server/src/services/goal/decideNextMove.ts@@ -20,6 +20,8 @@ import type {} from '@lobechat/types';import { toMetricScale } from '@lobechat/types';+import { isGoalReportNode } from './report';+export { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';/** Reason strings the recovery paths key off, written by the settle path. */@@ -27,6 +29,15 @@ export { LEASE_EXPIRED_ERROR, VERIFICATION_ERRORED_ERROR, VERIFICATION_FAILED_ERexport const TERMINAL_NODE_STATUSES = new Set(['resolved', 'rejected', 'retired']);+/**+ * A Task node the coordinator decides on. The wrap-up report node is a Task too,+ * but it runs after the Goal-level acceptance has ended and never takes part in+ * the Goal's status: its failure or timeout must not open a gate, occupy a slot+ * or keep a Goal from being judged.+ */+export const isCoordinatedTask = (node: Pick<GoalGraphNode, 'kind' | 'title'>) =>+ node.kind === 'task' && !isGoalReportNode(node);+/*** Whether a paused Task lost its run rather than failed it: the coordinator* reclaimed an expired lease, or the gateway watchdog abandoned a silent run.@@ -57,7 +68,7 @@ export const selectFrontier = (graph: GoalGraphSnapshot): FrontierSelection => {);const eligible = graph.nodes- .filter((node) => node.kind === 'task' && !TERMINAL_NODE_STATUSES.has(node.status))+ .filter((node) => isCoordinatedTask(node) && !TERMINAL_NODE_STATUSES.has(node.status)).map((node) => ({blockedBy: graph.edges.filter(@@ -175,7 +186,7 @@ export const compareMetric = (*/export const needsMetricCriteria = (graph: GoalGraphSnapshot): boolean => {if (!graph.goal.config?.acceptance?.metrics?.length) return false;- const taskNodes = graph.nodes.filter((node) => node.kind === 'task');+ const taskNodes = graph.nodes.filter(isCoordinatedTask);return taskNodes.length > 0 && taskNodes.every((node) => TERMINAL_NODE_STATUSES.has(node.status));};@@ -284,7 +295,7 @@ export const decideNextMove = ({// re-picked every tick, and reported `waiting_external`, which ends the// advance before anything behind it is even considered.const inFlight = graph.nodes.filter(- (node) => node.kind === 'task' && isInFlight(tasksById.get(node.taskId ?? '')),+ (node) => isCoordinatedTask(node) && isInFlight(tasksById.get(node.taskId ?? '')),).length;let parked = false;@@ -397,7 +408,7 @@ const decideWithoutFrontier = (metricCriteria?: GoalMetricCriteriaState,): GoalMove => {const base = { candidates };- const taskNodes = graph.nodes.filter((node) => node.kind === 'task');+ const taskNodes = graph.nodes.filter(isCoordinatedTask);// A goal with no tasks at all has not been planned yet — decompose it into// explorable directions before anything runs, instead of parking it.diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.tsindex a31d0081cf8..ba21c03ca13 100644--- a/apps/server/src/services/goal/index.test.ts+++ b/apps/server/src/services/goal/index.test.ts@@ -2932,6 +2932,88 @@ describe('GoalService', () => {expect((await service.graph(graph.goal.id)).goal.status).toBe('failed');});+ it('offers retry, abandon and fail on a failed terminal acceptance; abandon cancels the Goal', async () => {+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config: { recovery: { maxAttemptsPerTask: 1 } },+ requirement: 'Return three verified supplier quotes.',+ title: 'Abandoned terminal acceptance',+ tasks: ['Complete full Goal acceptance'],+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.update(created.taskId!, { totalTopics: 1 });+ await taskModel.updateStatus(created.taskId!, 'paused', {+ error: 'Delivery did not pass verification.',+ });+ await service.tick(graph.goal.id);+ const gated = await service.graph(graph.goal.id);++ expect(gated.decisions[0].options?.map((option) => option.id)).toEqual([+ 'retry',+ 'retire',+ 'fail',+ ]);+ await service.decide(graph.goal.id, gated.decisions[0].id, 'retire');++ const after = await service.graph(graph.goal.id);+ expect(after.goal.status).toBe('canceled');+ expect(after.nodes.find((node) => node.taskId === created.taskId)?.status).toBe('retired');+ });++ it('reopens an achieved Goal when its owner requests changes, and reworks the acceptance', async () => {+ vi.spyOn(TaskRunnerService.prototype, 'runTask').mockResolvedValue({} as never);+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ requirement: 'A one-page onboarding checklist',+ title: 'Reworked delivery',+ tasks: ['Draft the checklist'],+ });+ const work = await service.tick(graph.goal.id);+ await taskModel.updateStatus(work.taskId!, 'completed');+ await service.tick(graph.goal.id);+ await service.tick(graph.goal.id);+ const acceptance = await service.tick(graph.goal.id);+ await taskModel.updateStatus(acceptance.taskId!, 'completed');+ await service.tick(graph.goal.id);+ expect((await service.tick(graph.goal.id)).outcome).toBe('achieved');++ const reopened = await service.reopenForChanges(acceptance.taskId!, 'Add a day-one agenda');++ expect(reopened).toBe(graph.goal.id);+ const after = await service.graph(graph.goal.id);+ expect(after.goal.status).toBe('running');+ expect(after.goal.completedAt).toBeNull();+ expect(after.goal.config?.changeRequest).toMatchObject({+ comment: 'Add a day-one agenda',+ taskId: acceptance.taskId,+ });+ expect(after.nodes.find((node) => node.taskId === acceptance.taskId)?.status).toBe('active');+ expect((await taskModel.findById(acceptance.taskId!))?.status).toBe('backlog');++ // The coordinator dispatches the rework instead of reading the Goal as done.+ const rework = await service.tick(graph.goal.id);+ expect(rework.message).toMatch(/^Started task /);+ expect(TaskRunnerService.prototype.runTask).toHaveBeenLastCalledWith(+ expect.objectContaining({ taskId: acceptance.taskId }),+ );+ });++ it('does not reopen a Goal the owner already ended', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({+ requirement: 'A one-page onboarding checklist',+ title: 'Ended delivery',+ tasks: ['Complete full Goal acceptance'],+ });+ const created = await service.tick(graph.goal.id);+ await new GoalModel(serverDB, userId).updateStatus(graph.goal.id, 'canceled');++ expect(await service.reopenForChanges(created.taskId!, 'Too late')).toBeUndefined();+ expect((await service.graph(graph.goal.id)).goal.status).toBe('canceled');+ });+it('respects a manually paused responsible task without rerunning it', async () => {const service = new GoalService(serverDB, userId);const taskModel = new TaskModel(serverDB, userId);diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.tsindex 9bcb6229e27..fcbb64920e7 100644--- a/apps/server/src/services/goal/index.ts+++ b/apps/server/src/services/goal/index.ts@@ -74,6 +74,9 @@ import {resolveTaskMaxSteps,VERIFY_SETTLE_GRACE_MS,} from './recoveryPolicy';+import { isGoalReportNode, withoutGoalReport } from './report';+import { GoalReportService } from './reportService';+import { GoalReportStore } from './reportStore';import { GoalSupervisorService } from './supervisor';import { claimGoalTask } from './taskClaim';import { TaskRecoveryCoordinator } from './taskRecoveryCoordinator';@@ -92,6 +95,18 @@ import {} from './understanding';const TASK_NODE_CLAIM_TTL_MS = 5 * 60 * 1000;+/**+ * Tick outcomes after which the Goal-level acceptance may have just ended: the+ * Goal was achieved, failed or canceled, or parked on a gate (an acceptance+ * whose attempts ran out opens one). Every other outcome skips the check.+ */+const REPORT_CHECK_OUTCOMES = new Set<GoalTickResult['outcome']>([+ 'achieved',+ 'failed',+ 'waiting_human',+]);+/** A Goal whose delivery the owner can still send back for rework. */+const REOPENABLE_GOAL_STATUSES = new Set(['achieved', 'running']);const TASK_DESCRIPTION_MAX_LENGTH = 255;/** Advisory-lock namespace for goal dispatch. `0x676f_6469` is ASCII `godi`. */const GOAL_DISPATCH_LOCK_NAMESPACE = 0x67_6f_64_69;@@ -683,14 +698,15 @@ export class GoalService {graph = async (goalId: string) => {const graph = await this.requireGraph(goalId);- const [runHeartbeats, deliveredAt, acceptances, assignees, spend] = await Promise.all([+ const [runHeartbeats, deliveredAt, acceptances, assignees, spend, report] = await Promise.all([this.collectRunHeartbeats(graph),this.collectDeliveredAt(graph),this.collectAcceptances(graph),this.collectAssignees(graph),this.resolveSpend(graph),+ new GoalReportStore(this.db, this.userId, this.workspaceId).state(graph),]);- return { ...graph, acceptances, assignees, deliveredAt, runHeartbeats, spend };+ return { ...graph, acceptances, assignees, deliveredAt, report, runHeartbeats, spend };};/**@@ -1219,7 +1235,11 @@ export class GoalService {const graph = await this.requireGraph(goalId);const unfinishedNodes = graph.nodes.filter(- (node) => node.kind === 'task' && node.taskId && !TERMINAL_NODE_STATUSES.has(node.status),+ (node) =>+ node.kind === 'task' &&+ !isGoalReportNode(node) &&+ node.taskId &&+ !TERMINAL_NODE_STATUSES.has(node.status),);const unfinishedNodeIds = new Set(unfinishedNodes.map((node) => node.id));const unfinishedTaskIds = unfinishedNodes.flatMap((node) => (node.taskId ? [node.taskId] : []));@@ -1378,7 +1398,10 @@ export class GoalService {if (stoppedByExploration &&before.nodes.filter(- (node) => node.kind === 'task' && node.title !== GOAL_ACCEPTANCE_TASK_TITLE,+ (node) =>+ node.kind === 'task' &&+ node.title !== GOAL_ACCEPTANCE_TASK_TITLE &&+ !isGoalReportNode(node),).length >= (goal.config?.exploration?.maxExperiments ?? 0))return goal;@@ -1445,17 +1468,65 @@ export class GoalService {await this.graphModel.updateNodeStatus(goalId, source.id, 'retired', resolution);}}- const terminalAcceptanceFailed =- source?.title === GOAL_ACCEPTANCE_TASK_TITLE &&- (optionId === 'retire' || optionId === 'fail');+ // Ending the terminal acceptance ends the Goal: `fail` is a verdict that+ // the Goal failed, `retire` abandons it without one.+ const terminalAcceptance = source?.title === GOAL_ACCEPTANCE_TASK_TITLE;+ const nextStatus =+ terminalAcceptance && optionId === 'fail'+ ? 'failed'+ : terminalAcceptance && optionId === 'retire'+ ? 'canceled'+ : 'running';await this.transitionStatus(graph.goal,- terminalAcceptanceFailed ? 'failed' : 'running',+ nextStatus,`decision "${decision.question}" resolved: ${optionId}`,);return resolved;};+ /**+ * The owner sent the Goal's delivery back (提出修改 on the Goal-level+ * acceptance). The acceptance passing is what ended the Goal, so without a+ * reopen the coordinator reads it as still achieved and nothing reworks it.+ * The acceptance Task goes back to the queue — its next attempt reads the+ * rejected round's comment through the prompt builder — and the Goal runs+ * again. When that attempt is accepted the Goal is achieved anew, and the+ * wrap-up writes a new report version for the new result.+ *+ * Returns the reopened Goal id, or undefined when `taskId` is not a settled+ * Goal-level acceptance of a Goal that can still be reworked; a stopped Goal+ * is continued from its result, not reopened by a sign-off.+ */+ reopenForChanges = async (taskId: string, comment?: string): Promise<string | undefined> => {+ const goal = await this.goalModel.findByGraphTask(taskId);+ if (!goal || !REOPENABLE_GOAL_STATUSES.has(goal.status)) return undefined;+ const graph = await this.requireGraph(goal.id);+ const node = graph.nodes.find(+ (candidate) =>+ candidate.kind === 'task' &&+ candidate.taskId === taskId &&+ candidate.title === GOAL_ACCEPTANCE_TASK_TITLE,+ );+ if (node?.status !== 'resolved') return undefined;++ const reason = comment ? `Changes requested: ${comment}` : 'Changes requested';+ await this.taskModel.updateStatus(taskId, 'backlog', { error: null });+ await this.graphModel.updateNodeStatus(goal.id, node.id, 'active', reason);+ await this.goalModel.update(goal.id, {+ config: {+ ...graph.goal.config,+ changeRequest: {+ ...(comment ? { comment } : {}),+ requestedAt: new Date().toISOString(),+ taskId,+ },+ },+ });+ await this.transitionStatus(graph.goal, 'running', reason, 'user');+ return goal.id;+ };+/*** Answer a goal's clarification round in one go. Each answer resolves like a* single `decide`; the caller schedules one advance afterwards, so the@@ -1546,8 +1617,30 @@ export class GoalService {* runtime's event array.*/tick = async (goalId: string, options?: GoalTickOptions): Promise<GoalTickResult> => {+ const result = await this.tickOnce(goalId, options);+ if (REPORT_CHECK_OUTCOMES.has(result.outcome)) await this.dispatchGoalReport(goalId);+ return result;+ };++ /**+ * The wrap-up branch. Runs after the move rather than as one: it only fires+ * once the Goal-level acceptance has ended, and whatever happens to it — a+ * dispatch that throws, a run that fails or times out — must not change the+ * outcome the coordinator just reported or the Goal's status.+ */+ private dispatchGoalReport = async (goalId: string) => {+ try {+ await new GoalReportService(this.db, this.userId, this.workspaceId).dispatchIfDue(goalId);+ } catch (error) {+ console.error('[GoalService] wrap-up report dispatch failed:', error);+ }+ };++ private tickOnce = async (goalId: string, options?: GoalTickOptions): Promise<GoalTickResult> => {const at = Date.now();- const graph = await this.requireGraph(goalId);+ // The coordinator never sees the wrap-up report node: it runs after the+ // Goal-level acceptance and does not take part in the Goal's status.+ const graph = withoutGoalReport(await this.requireGraph(goalId));if (graph.goal.config?.manager) {// The system's own planner leads whenever the Goal has one: a main Agent is// the fallback for problems that planner cannot express, not a replacement@@ -2997,6 +3090,9 @@ export class GoalService {options: terminalAcceptance? [{ id: 'retry', label: 'Retry goal acceptance' },+ // Drop the acceptance Task and end the Goal without a verdict —+ // unlike `fail`, which records that the Goal was judged failed.+ { id: 'retire', label: 'Abandon goal acceptance' },{ id: 'fail', label: 'Fail goal' },]: [@@ -3004,7 +3100,7 @@ export class GoalService {{ id: 'retire', label: 'Retire task' },],question: terminalAcceptance- ? `${reason}. Retry Goal acceptance or fail this Goal?`+ ? `${reason}. Retry Goal acceptance, abandon it, or fail this Goal?`: `${reason}. Retry or retire this task node?`,recommendedOptionId: 'retry',requestedUserId: this.userId,diff --git a/apps/server/src/services/goal/report.test.ts b/apps/server/src/services/goal/report.test.tsnew file mode 100644index 00000000000..fcc9b74f41a--- /dev/null+++ b/apps/server/src/services/goal/report.test.ts@@ -0,0 +1,531 @@+import { GOAL_ACCEPTANCE_TASK_TITLE, GOAL_REPORT_TASK_TITLE } from '@lobechat/const/goal';+import type {+ GoalGraphDecision,+ GoalGraphEdge,+ GoalGraphNode,+ GoalGraphSnapshot,+ GoalReportMetadata,+ TaskItem,+} from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { decideNextMove, selectFrontier } from './decideNextMove';+import {+ buildGoalReportInstruction,+ buildGoalReportSkeleton,+ decideGoalReport,+ validateGoalReport,+} from './report';++const node = (id: string, overrides: Partial<GoalGraphNode> = {}): GoalGraphNode =>+ ({+ createdAt: new Date(1000),+ description: null,+ id,+ kind: 'task',+ priority: 0,+ resolvedAt: null,+ status: 'proposed',+ taskId: null,+ title: id,+ updatedAt: new Date(1000),+ ...overrides,+ }) as GoalGraphNode;++const edge = (+ sourceNodeId: string,+ kind: GoalGraphEdge['kind'],+ targetNodeId: string,+): GoalGraphEdge =>+ ({+ createdAt: new Date(1000),+ id: `${sourceNodeId}-${kind}-${targetNodeId}`,+ kind,+ sourceNodeId,+ targetNodeId,+ }) as GoalGraphEdge;++const gate = (id: string, nodeId: string, overrides: Partial<GoalGraphDecision> = {}) =>+ ({+ createdAt: new Date(5000),+ id,+ nodeId,+ question: 'Retry Goal acceptance or fail this Goal?',+ resolvedOptionId: null,+ status: 'pending',+ ...overrides,+ }) as GoalGraphDecision;++const graph = (overrides: Partial<GoalGraphSnapshot> = {}): GoalGraphSnapshot =>+ ({+ decisions: [],+ edges: [],+ events: [],+ goal: {+ config: {},+ id: 'goal_1',+ requirement: 'Ship it',+ status: 'running',+ title: 'G',+ updatedAt: new Date(1000),+ },+ nodes: [],+ workVersions: [],+ ...overrides,+ }) as GoalGraphSnapshot;++const acceptance = (overrides: Partial<GoalGraphNode> = {}) =>+ node('acc', { title: GOAL_ACCEPTANCE_TASK_TITLE, ...overrides });++describe('decideGoalReport', () => {+ it('does not dispatch while Goal-level acceptance has not ended', () => {+ for (const status of ['proposed', 'active', 'waiting'] as const) {+ expect(+ decideGoalReport(+ graph({ nodes: [node('t1', { status: 'resolved' }), acceptance({ status })] }),+ ),+ ).toEqual({ dispatch: false, reason: 'Goal-level acceptance has not ended' });+ }+ // Every Task resolved but acceptance not even created yet.+ expect(decideGoalReport(graph({ nodes: [node('t1', { status: 'resolved' })] })).dispatch).toBe(+ false,+ );+ });++ it('does not dispatch on a verification failure that still has attempts left', () => {+ // A rejection with attempts left is retried automatically: no gate, node stays active.+ const snapshot = graph({ nodes: [acceptance({ status: 'active' })] });+ expect(decideGoalReport(snapshot).dispatch).toBe(false);+ });++ it('dispatches once when acceptance passed', () => {+ const resolvedAt = new Date(7000);+ const snapshot = graph({+ goal: { ...graph().goal, status: 'achieved' },+ nodes: [node('t1', { status: 'resolved' }), acceptance({ resolvedAt, status: 'resolved' })],+ });+ const first = decideGoalReport(snapshot);+ expect(first).toEqual({+ dispatch: true,+ key: `accepted:acc:${resolvedAt.getTime()}`,+ trigger: 'accepted',+ });++ const dispatched = graph({+ ...snapshot,+ goal: {+ ...snapshot.goal,+ config: {+ report: {+ acceptanceKey: (first as { key: string }).key,+ dispatchedAt: new Date().toISOString(),+ nodeId: 'report',+ trigger: 'accepted',+ },+ },+ },+ });+ expect(decideGoalReport(dispatched).dispatch).toBe(false);+ });++ it('dispatches again when changes were requested and acceptance passed again', () => {+ const snapshot = graph({+ goal: {+ ...graph().goal,+ config: {+ report: {+ acceptanceKey: 'accepted:acc:7000',+ dispatchedAt: new Date().toISOString(),+ nodeId: 'report',+ trigger: 'accepted',+ },+ },+ status: 'achieved',+ },+ nodes: [acceptance({ resolvedAt: new Date(9000), status: 'resolved' })],+ });+ expect(decideGoalReport(snapshot)).toMatchObject({+ dispatch: true,+ key: 'accepted:acc:9000',+ });+ });++ it('does not treat a resolved acceptance as ended while new work is open', () => {+ const snapshot = graph({+ nodes: [acceptance({ status: 'resolved' }), node('fix', { status: 'active' })],+ });+ expect(decideGoalReport(snapshot).dispatch).toBe(false);+ });++ it('dispatches once when acceptance failed with its attempts spent', () => {+ const snapshot = graph({+ decisions: [gate('gate_1', 'decision')],+ edges: [edge('acc', 'leads_to', 'decision')],+ goal: { ...graph().goal, status: 'review' },+ nodes: [acceptance({ status: 'waiting' }), node('decision', { kind: 'decision' })],+ });+ expect(decideGoalReport(snapshot)).toEqual({+ dispatch: true,+ key: 'acceptance_failed:gate_1',+ trigger: 'acceptance_failed',+ });++ // Answering the gate with `fail` ends the Goal, but it is the same result.+ const failed = graph({+ ...snapshot,+ decisions: [gate('gate_1', 'decision', { resolvedOptionId: 'fail', status: 'resolved' })],+ goal: {+ ...snapshot.goal,+ config: {+ report: {+ acceptanceKey: 'acceptance_failed:gate_1',+ dispatchedAt: new Date().toISOString(),+ nodeId: 'report',+ trigger: 'acceptance_failed',+ },+ },+ status: 'failed',+ },+ nodes: [acceptance({ status: 'retired' }), node('decision', { kind: 'decision' })],+ });+ expect(decideGoalReport(failed).dispatch).toBe(false);++ // Answering it with `retry` puts acceptance back in progress: nothing to report.+ const retried = graph({+ ...snapshot,+ decisions: [gate('gate_1', 'decision', { resolvedOptionId: 'retry', status: 'resolved' })],+ goal: { ...snapshot.goal, status: 'running' },+ nodes: [acceptance({ status: 'active' }), node('decision', { kind: 'decision' })],+ });+ expect(decideGoalReport(retried).dispatch).toBe(false);+ });++ it('dispatches once when the Goal is failed or canceled', () => {+ for (const status of ['failed', 'canceled'] as const) {+ const snapshot = graph({+ events: [+ {+ createdAt: new Date(8000),+ entityId: 'goal_1',+ entityType: 'goal',+ eventType: 'rejected',+ id: `evt_${status}`,+ } as GoalGraphSnapshot['events'][number],+ ],+ goal: { ...graph().goal, status },+ nodes: [node('t1', { status: 'active' })],+ });+ const decision = decideGoalReport(snapshot);+ expect(decision).toEqual({+ dispatch: true,+ key: `goal_${status}:evt_${status}`,+ trigger: status === 'failed' ? 'goal_failed' : 'goal_canceled',+ });+ expect(+ decideGoalReport(+ graph({+ ...snapshot,+ goal: {+ ...snapshot.goal,+ config: {+ report: {+ acceptanceKey: (decision as { key: string }).key,+ dispatchedAt: new Date().toISOString(),+ nodeId: 'report',+ trigger: 'goal_failed',+ },+ },+ },+ }),+ ).dispatch,+ ).toBe(false);+ }+ });+});++describe('the wrap-up node does not take part in the Goal status', () => {+ const reportNode = node('report', {+ status: 'active',+ taskId: 'task_report',+ title: GOAL_REPORT_TASK_TITLE,+ });++ it('a failed wrap-up Task opens no gate and does not block acceptance', () => {+ const snapshot = graph({+ nodes: [node('t1', { status: 'resolved' }), reportNode],+ });+ const move = decideNextMove({+ concurrency: 1,+ frontier: selectFrontier(snapshot),+ graph: snapshot,+ tasksById: new Map([+ [+ 'task_report',+ { error: 'boom', id: 'task_report', identifier: 'T-9', status: 'paused' } as TaskItem,+ ],+ ]),+ });+ expect(move.branch).toBe('terminal_acceptance');+ expect(move.outcome).toBe('advanced');+ });++ it('a running wrap-up Task holds no concurrency slot and never becomes the frontier', () => {+ const snapshot = graph({ nodes: [node('t1'), reportNode] });+ const frontier = selectFrontier(snapshot);+ expect(frontier.candidates.map((candidate) => candidate.nodeId)).toEqual(['t1']);+ const move = decideNextMove({+ concurrency: 1,+ frontier,+ graph: snapshot,+ tasksById: new Map([+ ['task_report', { id: 'task_report', identifier: 'T-9', status: 'running' } as TaskItem],+ ]),+ });+ expect(move).toMatchObject({ branch: 'create_task', chosenNodeId: 't1' });+ });+});++describe('buildGoalReportSkeleton', () => {+ // problem → t1 (resolved) → t2 (resolved, depends on t1) → acc (depends on t2)+ // t1b: an earlier protocol revised by t2; t0: a retired direction off t1.+ const snapshot = graph({+ edges: [+ edge('t2', 'depends_on', 't1'),+ edge('acc', 'depends_on', 't2'),+ edge('t1', 'produces', 'f1'),+ edge('t2', 'produces', 'f2'),+ edge('t2', 'revises', 't1b'),+ edge('t0', 'depends_on', 't1'),+ ],+ events: [+ { createdAt: new Date(1), id: 'evt_old' },+ { createdAt: new Date(9), id: 'evt_new' },+ ] as GoalGraphSnapshot['events'],+ nodes: [+ node('problem', { kind: 'problem', status: 'resolved' }),+ node('t1', { createdAt: new Date(1), status: 'resolved' }),+ node('f1', { kind: 'finding', status: 'resolved' }),+ node('t1b', { createdAt: new Date(2), status: 'resolved' }),+ node('t0', { createdAt: new Date(3), status: 'retired' }),+ node('t2', { createdAt: new Date(4), status: 'resolved' }),+ node('f2', { kind: 'finding', status: 'resolved' }),+ acceptance({ createdAt: new Date(5), status: 'resolved' }),+ node('report', { title: GOAL_REPORT_TASK_TITLE }),+ ],+ workVersions: [+ {+ createdAt: new Date(6),+ id: 'l1',+ nodeId: 't2',+ relation: 'produced',+ work: { title: 'Final doc', type: 'document', workId: 'work_doc' },+ workVersionId: 'wv_doc',+ },+ ] as GoalGraphSnapshot['workVersions'],+ });++ it('traces the main path back from the deliverable and hangs detours under their fork', () => {+ const skeleton = buildGoalReportSkeleton(snapshot);+ expect(skeleton.mainPath.map((item) => item.id)).toEqual(['t1', 't2', 'acc']);+ expect(skeleton.mainPath.find((item) => item.id === 't2')).toMatchObject({+ findingIds: ['f2'],+ workVersionIds: ['wv_doc'],+ });+ expect(skeleton.detours).toEqual([+ expect.objectContaining({+ forkNodeId: 't2',+ id: 't1b',+ signal: 'superseded by t2 (revises)',+ }),+ expect.objectContaining({ forkNodeId: 't1', id: 't0', signal: 'retired' }),+ ]);+ expect(skeleton.deliverable).toMatchObject({ workId: 'work_doc', workVersionId: 'wv_doc' });+ expect(skeleton.graphCursor).toBe('evt_new');+ // The candidate mainline stops at the path: detours and the wrap-up node stay off it.+ expect(skeleton.mainline.nodeIds).toEqual(['problem', 't1', 'f1', 't2', 'f2', 'acc']);+ expect(skeleton.mainline.edges.map((item) => item.id)).toEqual([+ 't2-depends_on-t1',+ 'acc-depends_on-t2',+ 't1-produces-f1',+ 't2-produces-f2',+ ]);+ });++ it('asks for chapters, detour reasons and lessons, next steps and a submission', () => {+ const text = buildGoalReportInstruction(snapshot, 'accepted', {+ kind: 'tool',+ toolName: 'lobe-goal-report.submitGoalReport',+ });+ expect(text).toContain('Candidate main path');+ expect(text).toContain('t1b [task, resolved] t1b · superseded by t2 (revises) · fork: t2');+ expect(text).toContain('Goal-level acceptance passed');+ expect(text).toContain('Graph cursor: evt_new');+ expect(text).toContain('Call lobe-goal-report.submitGoalReport once');+ expect(text).toContain('reason it was abandoned and the lesson');+ expect(text).not.toContain('report [task');+ expect(text).toContain('Candidate mainline');+ expect(text).toContain('- edge t2-depends_on-t1: t2 -[depends_on]-> t1');+ expect(text).toContain('Mark the mainline');+ expect(text).toContain('headline, deliverableWorkId, chapters, mainline, nextSteps');+ });++ /**+ * Regression: a heterogeneous wrap-up agent (Claude Code, Codex) never+ * receives server tools, so an instruction that only named the report tool+ * left it with no way to submit — no report could ever be stored.+ */+ it('tells a heterogeneous wrap-up agent to submit through the lh CLI', () => {+ const text = buildGoalReportInstruction(snapshot, 'accepted', { kind: 'cli' });+ expect(text).toContain(+ `lh goal report ${snapshot.goal.id} --metadata-file <json> --content-file <md>`,+ );+ expect(text).toContain(`lh goal show ${snapshot.goal.id} --json`);+ expect(text).not.toContain('submitGoalReport');+ });++ describe('validateGoalReport', () => {+ const valid: GoalReportMetadata = {+ chapters: [+ {+ detours: [+ { kind: 'superseded', lesson: 'L', nodeIds: ['t1b'], reason: 'R', title: 'Old' },+ { kind: 'dead_end', lesson: 'L', nodeIds: ['t0'], reason: 'R', title: 'Dead' },+ ],+ findingIds: ['f1', 'f2'],+ narrative: 'N',+ nodeIds: ['t1', 't2'],+ title: 'C1',+ workVersionIds: ['wv_doc'],+ },+ {+ detours: [],+ findingIds: [],+ narrative: 'N',+ nodeIds: ['acc'],+ title: 'C2',+ workVersionIds: [],+ },+ ],+ deliverableWorkId: 'work_doc',+ graphCursor: 'evt_new',+ headline: 'H',+ mainline: {+ edgeIds: ['t2-depends_on-t1', 'acc-depends_on-t2', 't2-produces-f2'],+ nodeIds: ['problem', 't1', 't2', 'f2', 'acc'],+ },+ nextSteps: [{ nodeIds: ['t2'], reason: 'R', title: 'Next' }],+ };++ it('accepts references that belong to the Goal', () => {+ expect(+ validateGoalReport(snapshot, valid, { eventIds: new Set(['evt_old', 'evt_new']) }),+ ).toEqual([]);+ });++ it('rejects foreign ids, unresolved main-path nodes and fake detours', () => {+ const errors = validateGoalReport(+ snapshot,+ {+ ...valid,+ chapters: [+ {+ ...valid.chapters[0],+ detours: [+ { kind: 'dead_end', lesson: 'L', nodeIds: ['t2'], reason: 'R', title: 'Not dead' },+ ],+ findingIds: ['t1', 'f_other'],+ nodeIds: ['t0', 'n_other', 'report'],+ workVersionIds: ['wv_other'],+ },+ ],+ deliverableWorkId: 'work_other',+ graphCursor: 'evt_other',+ nextSteps: [{ nodeIds: ['n_other'], reason: 'R', title: 'Next' }],+ },+ { eventIds: new Set(['evt_new']) },+ );+ expect(errors).toEqual([+ 'chapters[0].nodeIds: t0 is retired; main-path nodes must be resolved',+ 'chapters[0].nodeIds: n_other is not a node of this Goal',+ 'chapters[0].nodeIds: report is not a node of this Goal',+ 'chapters[0].findingIds: t1 is not a finding of this Goal',+ 'chapters[0].findingIds: f_other is not a finding of this Goal',+ 'chapters[0].workVersionIds: wv_other is not a Work version linked to this Goal',+ 'chapters[0].detours[0].nodeIds: t2 is resolved and not superseded by revises/contradicts',+ 'nextSteps[0].nodeIds: n_other is not a node of this Goal',+ 'chapters[0].nodeIds: t0 is not on the mainline',+ 'chapters[0].detours[0].nodeIds: t2 is on the mainline; a detour cannot be',+ 'mainline.nodeIds: t1 is on the mainline but no chapter tells it',+ 'mainline.nodeIds: t2 is on the mainline but no chapter tells it',+ 'mainline.nodeIds: acc is on the mainline but no chapter tells it',+ 'deliverableWorkId: work_other is not a Work linked to this Goal',+ 'graphCursor: evt_other is not an event of this Goal',+ ]);+ });++ describe('mainline', () => {+ const check = (mainline: GoalReportMetadata['mainline']) =>+ validateGoalReport(snapshot, { ...valid, mainline });++ it('is required on a new submission', () => {+ expect(check(undefined)).toEqual([+ 'mainline: required — mark the nodes and edges of the path that led to the result',+ ]);+ });++ it('keeps only resolved nodes of this Goal, of a kind that can carry the story', () => {+ expect(+ check({+ edgeIds: [],+ nodeIds: ['t1', 't2', 'acc', 't0', 'n_other', 'report', 'gate_node'],+ }),+ ).toEqual([+ 'mainline.nodeIds: t0 is retired; mainline nodes must be resolved',+ 'mainline.nodeIds: n_other is not a node of this Goal',+ 'mainline.nodeIds: report is not a node of this Goal',+ 'mainline.nodeIds: gate_node is not a node of this Goal',+ 'chapters[0].detours[1].nodeIds: t0 is on the mainline; a detour cannot be',+ ]);++ const withDecision = graph({+ ...snapshot,+ nodes: [...snapshot.nodes, node('d1', { kind: 'decision', status: 'resolved' })],+ });+ expect(+ validateGoalReport(withDecision, {+ ...valid,+ mainline: { edgeIds: [], nodeIds: ['t1', 't2', 'acc', 'd1'] },+ }),+ ).toEqual([+ 'mainline.nodeIds: d1 is a decision; only problem, task, experiment and finding nodes can be on the mainline',+ ]);+ });++ it('keeps only edges of this Goal whose both ends are on the mainline', () => {+ expect(+ check({+ edgeIds: ['t2-depends_on-t1', 't0-depends_on-t1', 't2-revises-t1b', 'e_other'],+ nodeIds: ['t1', 't2', 'acc'],+ }),+ ).toEqual([+ 'mainline.edgeIds: t0-depends_on-t1 connects t0, which is not a mainline node',+ 'mainline.edgeIds: t2-revises-t1b connects t1b, which is not a mainline node',+ 'mainline.edgeIds: e_other is not an edge of this Goal',+ ]);+ });++ it('must be the same path the chapters tell', () => {+ expect(+ validateGoalReport(snapshot, {+ ...valid,+ chapters: [valid.chapters[0]],+ mainline: { edgeIds: [], nodeIds: ['t2', 'acc'] },+ }),+ ).toEqual([+ 'chapters[0].nodeIds: t1 is not on the mainline',+ 'mainline.nodeIds: acc is on the mainline but no chapter tells it',+ ]);+ });+ });+ });+});diff --git a/apps/server/src/services/goal/report.ts b/apps/server/src/services/goal/report.tsnew file mode 100644index 00000000000..43a3fb7b378--- /dev/null+++ b/apps/server/src/services/goal/report.ts@@ -0,0 +1,590 @@+import { GOAL_ACCEPTANCE_TASK_TITLE, GOAL_REPORT_TASK_TITLE } from '@lobechat/const/goal';+import type {+ GoalEdgeKind,+ GoalGraphNode,+ GoalGraphSnapshot,+ GoalReportMetadata,+ GoalReportTrigger,+} from '@lobechat/types';++/**+ * The wrap-up branch of the Goal coordinator: once the Goal-level acceptance+ * has ended, a wrap-up agent turns the graph into a storyline. Everything here+ * is a pure function of the graph so the dispatch rule, the skeleton handed to+ * the agent and the checks on what it submits can be tested without IO.+ */++export const isGoalReportNode = (node: Pick<GoalGraphNode, 'kind' | 'title'>) =>+ node.kind === 'task' && node.title === GOAL_REPORT_TASK_TITLE;++/**+ * The graph as the coordinator should see it: without the wrap-up node, its+ * edges and its Work links. The wrap-up never takes part in deciding the Goal's+ * status — a failed or timed-out report must not open a gate or keep a Goal+ * from finishing — so every decision path reads this view.+ */+export const withoutGoalReport = <T extends GoalGraphSnapshot>(graph: T): T => {+ const hidden = new Set(graph.nodes.filter(isGoalReportNode).map((node) => node.id));+ if (hidden.size === 0) return graph;+ return {+ ...graph,+ edges: graph.edges.filter(+ (edge) => !hidden.has(edge.sourceNodeId) && !hidden.has(edge.targetNodeId),+ ),+ nodes: graph.nodes.filter((node) => !hidden.has(node.id)),+ workVersions: graph.workVersions.filter((link) => !hidden.has(link.nodeId)),+ };+};++const acceptanceNodeOf = (graph: GoalGraphSnapshot) =>+ graph.nodes.find((node) => node.kind === 'task' && node.title === GOAL_ACCEPTANCE_TASK_TITLE);++const IN_PROGRESS_STATUSES = new Set(['proposed', 'active', 'waiting']);++export interface AcceptanceResult {+ /** Stable identity of this acceptance result: one wrap-up per key. */+ key: string;+ trigger: GoalReportTrigger;+}++/**+ * The acceptance result the Goal currently rests on, or undefined while the+ * Goal-level acceptance has not ended.+ *+ * - accepted — the acceptance node resolved and no other work is open.+ * - acceptance_failed — the acceptance was rejected with its attempts spent: the+ * gate it opened (pending, or answered `fail`/`retire`).+ * - goal_failed/canceled — the Goal itself ended without such a result.+ *+ * Each key names the event that produced it (resolution instant, gate id, goal+ * status event), so a Goal that is sent back for changes and accepted again+ * yields a new key — and a new report version — while re-reading the same+ * result never dispatches twice.+ */+export const resolveAcceptanceResult = (graph: GoalGraphSnapshot): AcceptanceResult | undefined => {+ const view = withoutGoalReport(graph);+ const acceptance = acceptanceNodeOf(view);++ if (acceptance) {+ const otherWorkOpen = view.nodes.some(+ (node) =>+ node.kind === 'task' && node.id !== acceptance.id && IN_PROGRESS_STATUSES.has(node.status),+ );+ if (acceptance.status === 'resolved' && !otherWorkOpen) {+ const at = acceptance.resolvedAt ?? acceptance.updatedAt;+ return { key: `accepted:${acceptance.id}:${new Date(at).getTime()}`, trigger: 'accepted' };+ }++ const gateNodeIds = new Set(+ view.edges+ .filter((edge) => edge.kind === 'leads_to' && edge.sourceNodeId === acceptance.id)+ .map((edge) => edge.targetNodeId),+ );+ const gate = view.decisions+ .filter((decision) => gateNodeIds.has(decision.nodeId))+ .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())[0];+ if (+ gate &&+ (gate.status === 'pending' ||+ (gate.status === 'resolved' &&+ (gate.resolvedOptionId === 'fail' || gate.resolvedOptionId === 'retire')))+ ) {+ return { key: `acceptance_failed:${gate.id}`, trigger: 'acceptance_failed' };+ }+ }++ if (graph.goal.status === 'failed' || graph.goal.status === 'canceled') {+ // A person may end a Goal mid-acceptance; the acceptance will not finish+ // after that, so the Goal's own end is the result the report is written for.+ const ended = graph.events.find(+ (event) =>+ event.entityType === 'goal' &&+ event.entityId === graph.goal.id &&+ event.eventType === 'rejected',+ );+ // Keyed by the status event, never by `goal.updatedAt`: recording the+ // dispatch receipt on the goal row moves that, which would read as a new+ // result on the next tick and dispatch again.+ return {+ key: `goal_${graph.goal.status}:${ended?.id ?? 'ended'}`,+ trigger: graph.goal.status === 'failed' ? 'goal_failed' : 'goal_canceled',+ };+ }++ return undefined;+};++export type GoalReportDecision =+ { dispatch: false; reason: string } | ({ dispatch: true } & AcceptanceResult);++/**+ * Whether the coordinator should dispatch a wrap-up run now. Never before the+ * Goal-level acceptance has ended, and once per acceptance result.+ */+export const decideGoalReport = (graph: GoalGraphSnapshot): GoalReportDecision => {+ const result = resolveAcceptanceResult(graph);+ if (!result) return { dispatch: false, reason: 'Goal-level acceptance has not ended' };+ if (graph.goal.config?.report?.acceptanceKey === result.key)+ return { dispatch: false, reason: 'A wrap-up was already dispatched for this result' };+ return { dispatch: true, ...result };+};++// ---------------------------------------------------------------------------+// Skeleton+// ---------------------------------------------------------------------------++const PATH_EDGE_KINDS = new Set<GoalEdgeKind>(['depends_on', 'derived_from']);+const SUPERSEDING_EDGE_KINDS = new Set<GoalEdgeKind>(['revises', 'contradicts']);+const DEAD_STATUSES = new Set(['rejected', 'retired']);+const STORY_KINDS = new Set(['task', 'experiment', 'finding']);++export interface GoalReportSkeletonNode {+ findingIds: string[];+ id: string;+ kind: GoalGraphNode['kind'];+ status: GoalGraphNode['status'];+ title: string;+ workVersionIds: string[];+}++export interface GoalReportSkeletonDetour {+ /** Node on the main path this detour branched from, when one could be found. */+ forkNodeId?: string;+ id: string;+ kind: GoalGraphNode['kind'];+ /** Why the skeleton flags it: the node's own status, or the node that superseded it. */+ signal: string;+ status: GoalGraphNode['status'];+ title: string;+}++export interface GoalReportSkeleton {+ acceptance: {+ finding?: string;+ gate?: { question: string; resolution?: string | null; status: string };+ nodeId?: string;+ status?: string;+ };+ deliverable?: { title: string | null; type: string; workId: string; workVersionId: string };+ detours: GoalReportSkeletonDetour[];+ graphCursor?: string;+ /** Candidate mainline mark: the resolved root question, main-path nodes and their findings, and the edges among them. */+ mainline: {+ edges: { id: string; kind: GoalEdgeKind; source: string; target: string }[];+ nodeIds: string[];+ };+ mainPath: GoalReportSkeletonNode[];+}++/** Nodes superseded by another through `revises` / `contradicts`, mapped to their successor. */+const supersededBy = (graph: GoalGraphSnapshot) => {+ const map = new Map<string, string>();+ for (const edge of graph.edges) {+ if (SUPERSEDING_EDGE_KINDS.has(edge.kind)) map.set(edge.targetNodeId, edge.sourceNodeId);+ }+ return map;+};++/**+ * The deterministic part of the story, handed to the wrap-up agent as a+ * starting point: the candidate main path traced back from the final+ * deliverable, and the candidate detours hung under the fork they left from.+ * The agent decides chapters, names, narrative and which detours matter.+ */+export const buildGoalReportSkeleton = (source: GoalGraphSnapshot): GoalReportSkeleton => {+ const graph = withoutGoalReport(source);+ const byId = new Map(graph.nodes.map((node) => [node.id, node]));+ const acceptance = acceptanceNodeOf(graph);++ const produced = graph.workVersions.filter(+ (link) => link.relation === 'produced' && link.work && link.work.type !== 'task',+ );+ const newest = <T extends { createdAt: Date }>(items: T[]) =>+ [...items].sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())[0];+ const deliverableLink =+ newest(produced.filter((link) => link.nodeId === acceptance?.id)) ?? newest(produced);++ // Walk back from the node that closed the Goal (or produced its deliverable).+ const starts = [acceptance?.id, deliverableLink?.nodeId].filter(Boolean) as string[];+ if (starts.length === 0) {+ starts.push(+ ...graph.nodes+ .filter((node) => node.kind === 'task' && node.status === 'resolved')+ .map((node) => node.id),+ );+ }+ const visited = new Set<string>();+ const queue = [...starts];+ while (queue.length > 0) {+ const id = queue.shift()!;+ if (visited.has(id)) continue;+ visited.add(id);+ for (const edge of graph.edges) {+ if (edge.sourceNodeId === id && (PATH_EDGE_KINDS.has(edge.kind) || edge.kind === 'produces'))+ queue.push(edge.targetNodeId);+ if (edge.targetNodeId === id && edge.kind === 'produces') queue.push(edge.sourceNodeId);+ }+ }++ const superseded = supersededBy(graph);+ const onMainPath = (node: GoalGraphNode) =>+ visited.has(node.id) &&+ node.status === 'resolved' &&+ STORY_KINDS.has(node.kind) &&+ !superseded.has(node.id);++ const byCreation = (a: GoalGraphNode, b: GoalGraphNode) =>+ new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();++ const mainNodes = graph.nodes.filter(onMainPath).sort(byCreation);+ const mainIds = new Set(mainNodes.map((node) => node.id));+ const findingsOf = (id: string) =>+ graph.edges+ .filter((edge) => edge.sourceNodeId === id && edge.kind === 'produces')+ .map((edge) => edge.targetNodeId)+ .filter((target) => byId.get(target)?.kind === 'finding');++ const mainPath = mainNodes+ .filter((node) => node.kind !== 'finding')+ .map((node) => ({+ findingIds: findingsOf(node.id),+ id: node.id,+ kind: node.kind,+ status: node.status,+ title: node.title,+ workVersionIds: graph.workVersions+ .filter((link) => link.nodeId === node.id)+ .map((link) => link.workVersionId),+ }));++ const forkOf = (node: GoalGraphNode): string | undefined => {+ const successor = superseded.get(node.id);+ if (successor && mainIds.has(successor)) return successor;+ const upstream = graph.edges.find(+ (edge) =>+ edge.sourceNodeId === node.id &&+ PATH_EDGE_KINDS.has(edge.kind) &&+ mainIds.has(edge.targetNodeId),+ );+ if (upstream) return upstream.targetNodeId;+ const container = graph.edges.find(+ (edge) => edge.kind === 'contains' && edge.targetNodeId === node.id,+ );+ return container?.sourceNodeId;+ };++ const detours = graph.nodes+ .filter(+ (node) =>+ STORY_KINDS.has(node.kind) &&+ !mainIds.has(node.id) &&+ (DEAD_STATUSES.has(node.status) || superseded.has(node.id)),+ )+ .sort(byCreation)+ .map((node) => {+ const successor = superseded.get(node.id);+ return {+ forkNodeId: forkOf(node),+ id: node.id,+ kind: node.kind,+ signal: successor+ ? `superseded by ${successor} (${graph.edges.find((edge) => edge.sourceNodeId === successor && edge.targetNodeId === node.id)?.kind})`+ : node.status,+ status: node.status,+ title: node.title,+ };+ });++ const mainlineIds = new Set([+ ...graph.nodes+ .filter((node) => node.kind === 'problem' && node.status === 'resolved')+ .map((node) => node.id),+ ...mainNodes.map((node) => node.id),+ ]);+ const mainline = {+ edges: graph.edges+ .filter((edge) => mainlineIds.has(edge.sourceNodeId) && mainlineIds.has(edge.targetNodeId))+ .map((edge) => ({+ id: edge.id,+ kind: edge.kind,+ source: edge.sourceNodeId,+ target: edge.targetNodeId,+ })),+ nodeIds: graph.nodes.filter((node) => mainlineIds.has(node.id)).map((node) => node.id),+ };++ const gateNodeIds = new Set(+ graph.edges+ .filter((edge) => edge.kind === 'leads_to' && edge.sourceNodeId === acceptance?.id)+ .map((edge) => edge.targetNodeId),+ );+ const gate = graph.decisions+ .filter((decision) => gateNodeIds.has(decision.nodeId))+ .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())[0];+ const acceptanceFinding = acceptance+ ? findingsOf(acceptance.id)+ .map((id) => byId.get(id))+ .find(Boolean)+ : undefined;++ const newestEvent = [...source.events].sort(+ (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),+ )[0];++ return {+ acceptance: {+ finding: acceptanceFinding+ ? [acceptanceFinding.title, acceptanceFinding.description].filter(Boolean).join(' — ')+ : undefined,+ gate: gate+ ? { question: gate.question, resolution: gate.resolution, status: gate.status }+ : undefined,+ nodeId: acceptance?.id,+ status: acceptance?.status,+ },+ deliverable: deliverableLink?.work+ ? {+ title: deliverableLink.work.title,+ type: deliverableLink.work.type,+ workId: deliverableLink.work.workId,+ workVersionId: deliverableLink.workVersionId,+ }+ : undefined,+ detours,+ graphCursor: newestEvent?.id,+ mainPath,+ mainline,+ };+};++const TRIGGER_LABEL: Record<GoalReportTrigger, string> = {+ acceptance_failed: 'Goal-level acceptance ended without passing (attempts spent or rejected)',+ accepted: 'Goal-level acceptance passed',+ goal_canceled: 'The Goal was canceled',+ goal_failed: 'The Goal was marked failed',+};++/** The wrap-up agent's instruction: the skeleton plus what it must produce. */+/**+ * How the wrap-up agent submits. An ordinary agent gets the report tool; a+ * heterogeneous agent (Claude Code, Codex…) runs on a device where server tools+ * are not wired in, so it submits through the `lh` CLI instead — the same way+ * a heterogeneous main Agent submits its plan.+ */+export type GoalReportSubmission = { kind: 'cli' } | { kind: 'tool'; toolName: string };++export const buildGoalReportInstruction = (+ graph: GoalGraphSnapshot,+ trigger: GoalReportTrigger,+ submission: GoalReportSubmission,+): string => {+ const skeleton = buildGoalReportSkeleton(graph);+ const line = (node: { id: string; kind: string; status: string; title: string }) =>+ `${node.id} [${node.kind}, ${node.status}] ${node.title}`;++ return [+ `Write the wrap-up report of the Goal "${graph.goal.title}" (goalId: ${graph.goal.id}).`,+ `Why now: ${TRIGGER_LABEL[trigger]}. Goal status: ${graph.goal.status}.`,+ graph.goal.requirement ? `Goal requirement:\n${graph.goal.requirement}` : undefined,+ [+ 'Acceptance result summary:',+ `- acceptance node: ${skeleton.acceptance.nodeId ?? 'none'} (${skeleton.acceptance.status ?? 'not created'})`,+ skeleton.acceptance.finding+ ? `- acceptance conclusion: ${skeleton.acceptance.finding}`+ : undefined,+ skeleton.acceptance.gate+ ? `- acceptance gate (${skeleton.acceptance.gate.status}): ${skeleton.acceptance.gate.question}${skeleton.acceptance.gate.resolution ? ` → ${skeleton.acceptance.gate.resolution}` : ''}`+ : undefined,+ ]+ .filter(Boolean)+ .join('\n'),+ skeleton.deliverable+ ? `Final deliverable: Work ${skeleton.deliverable.workId} (${skeleton.deliverable.type}) "${skeleton.deliverable.title ?? ''}", version ${skeleton.deliverable.workVersionId}`+ : 'Final deliverable: none linked to the graph.',+ [+ 'Candidate main path (traced back from the final deliverable along produces / depends_on / derived_from, oldest first):',+ ...skeleton.mainPath.map(+ (node) =>+ `- ${line(node)}${node.findingIds.length ? ` · findings: ${node.findingIds.join(', ')}` : ''}${node.workVersionIds.length ? ` · work versions: ${node.workVersionIds.join(', ')}` : ''}`,+ ),+ ].join('\n'),+ [+ 'Candidate detours (rejected / retired / superseded), under the fork they left from:',+ ...(skeleton.detours.length+ ? skeleton.detours.map(+ (node) => `- ${line(node)} · ${node.signal} · fork: ${node.forkNodeId ?? 'unknown'}`,+ )+ : ['- none']),+ ].join('\n'),+ [+ 'Candidate mainline (nodes and the edges among them; the exploration map highlights exactly what you mark):',+ `- nodeIds: ${skeleton.mainline.nodeIds.join(', ') || 'none'}`,+ ...skeleton.mainline.edges.map(+ (edge) => `- edge ${edge.id}: ${edge.source} -[${edge.kind}]-> ${edge.target}`,+ ),+ ].join('\n'),+ `Graph cursor: ${skeleton.graphCursor ?? 'none'}`,+ [+ 'What to do:',+ submission.kind === 'cli'+ ? `1. Inspect the Goal, its findings and deliverables as needed (\`lh goal show ${graph.goal.id} --json\`). The skeleton is a starting point, not the answer.`+ : '1. Inspect the Goal, its findings and deliverables as needed. The skeleton is a starting point, not the answer.',+ '2. Split the main path into a few chapters. Give each a title and a narrative of what was tried, what was learned and what it produced; reference its nodeIds (resolved main-path nodes only), findingIds and workVersionIds.',+ '3. Decide which detours are worth telling. For each one attach it to the chapter it forked from, with kind (dead_end | superseded | retry), the reason it was abandoned and the lesson it taught. Leave out detours that teach nothing.',+ '4. Write nextSteps: what remains or should come next, each with a reason.',+ '5. Write a one-sentence headline, and set deliverableWorkId when there is a final deliverable.',+ '6. Mark the mainline: the path that actually led to the result. mainline.nodeIds are the resolved tasks on the correct path (plus, when useful, the resolved root problem and the findings that carried the answer forward); mainline.edgeIds are the edges of this Goal that connect two of those nodes. Detour nodes are never on the mainline. The chapters must tell exactly this path: every chapter nodeId is a mainline node, and every mainline task appears in a chapter.',+ '7. Do NOT restate acceptance verdicts or user decisions as data; the page reads those from their own records. Narrate around them.',+ submission.kind === 'cli'+ ? `8. Write the metadata (headline, deliverableWorkId, chapters, mainline, nextSteps, graphCursor) as JSON to a file, and the full written report in markdown, built from that same metadata, to another file. Submit both once with \`lh goal report ${graph.goal.id} --metadata-file <json> --content-file <md>\`. If it rejects a reference, fix the file and submit again.`+ : `8. Call ${submission.toolName} once with goalId, the metadata (headline, deliverableWorkId, chapters, mainline, nextSteps, graphCursor) and content: the full written report in markdown, built from that same metadata. If it rejects a reference, fix it and call again.`,+ ].join('\n'),+ ]+ .filter(Boolean)+ .join('\n\n');+};++// ---------------------------------------------------------------------------+// Validation of a submitted report+// ---------------------------------------------------------------------------++/**+ * Every reference in a submitted report must belong to this Goal, main-path+ * nodes must be resolved, and a detour must really be one: rejected, retired,+ * or superseded through `revises` / `contradicts`. Returns every problem found+ * so the agent can fix them in one pass.+ */+export const validateGoalReport = (+ source: GoalGraphSnapshot,+ metadata: GoalReportMetadata,+ options: { eventIds?: Set<string> } = {},+): string[] => {+ const graph = withoutGoalReport(source);+ const byId = new Map(graph.nodes.map((node) => [node.id, node]));+ const workVersionIds = new Set(graph.workVersions.map((link) => link.workVersionId));+ const workIds = new Set(+ graph.workVersions.flatMap((link) => (link.work ? [link.work.workId] : [])),+ );+ const superseded = supersededBy(graph);+ const errors: string[] = [];++ metadata.chapters.forEach((chapter, index) => {+ const at = `chapters[${index}]`;+ for (const id of chapter.nodeIds) {+ const node = byId.get(id);+ if (!node) errors.push(`${at}.nodeIds: ${id} is not a node of this Goal`);+ else if (node.status !== 'resolved')+ errors.push(`${at}.nodeIds: ${id} is ${node.status}; main-path nodes must be resolved`);+ }+ for (const id of chapter.findingIds) {+ const node = byId.get(id);+ if (!node || node.kind !== 'finding')+ errors.push(`${at}.findingIds: ${id} is not a finding of this Goal`);+ }+ for (const id of chapter.workVersionIds) {+ if (!workVersionIds.has(id))+ errors.push(`${at}.workVersionIds: ${id} is not a Work version linked to this Goal`);+ }+ chapter.detours.forEach((detour, detourIndex) => {+ for (const id of detour.nodeIds) {+ const node = byId.get(id);+ if (!node) {+ errors.push(`${at}.detours[${detourIndex}].nodeIds: ${id} is not a node of this Goal`);+ } else if (!DEAD_STATUSES.has(node.status) && !superseded.has(id)) {+ errors.push(+ `${at}.detours[${detourIndex}].nodeIds: ${id} is ${node.status} and not superseded by revises/contradicts`,+ );+ }+ }+ });+ });++ metadata.nextSteps.forEach((step, index) => {+ for (const id of step.nodeIds ?? []) {+ if (!byId.has(id))+ errors.push(`nextSteps[${index}].nodeIds: ${id} is not a node of this Goal`);+ }+ });++ errors.push(...validateMainline(graph, metadata));++ if (metadata.deliverableWorkId && !workIds.has(metadata.deliverableWorkId))+ errors.push(+ `deliverableWorkId: ${metadata.deliverableWorkId} is not a Work linked to this Goal`,+ );++ if (options.eventIds && !options.eventIds.has(metadata.graphCursor))+ errors.push(`graphCursor: ${metadata.graphCursor} is not an event of this Goal`);++ return errors;+};++const MAINLINE_KINDS = new Set(['problem', 'task', 'experiment', 'finding']);+/** Mainline nodes a chapter must tell; the root question and findings ride along without one. */+const CHAPTERED_KINDS = new Set(['task', 'experiment']);++/**+ * The mainline must be a real path through this Goal: resolved nodes only, edges+ * of this Goal whose both ends are on it, and the same path the chapters tell —+ * so the highlighted map and the storyline can never disagree.+ */+const validateMainline = (graph: GoalGraphSnapshot, metadata: GoalReportMetadata): string[] => {+ const { mainline } = metadata;+ if (!mainline)+ return ['mainline: required — mark the nodes and edges of the path that led to the result'];++ const byId = new Map(graph.nodes.map((node) => [node.id, node]));+ const edgeById = new Map(graph.edges.map((edge) => [edge.id, edge]));+ const onMainline = new Set(mainline.nodeIds);+ const errors: string[] = [];++ for (const id of mainline.nodeIds) {+ const node = byId.get(id);+ if (!node) errors.push(`mainline.nodeIds: ${id} is not a node of this Goal`);+ else if (!MAINLINE_KINDS.has(node.kind))+ errors.push(+ `mainline.nodeIds: ${id} is a ${node.kind}; only problem, task, experiment and finding nodes can be on the mainline`,+ );+ else if (node.status !== 'resolved')+ errors.push(`mainline.nodeIds: ${id} is ${node.status}; mainline nodes must be resolved`);+ }++ for (const id of mainline.edgeIds) {+ const edge = edgeById.get(id);+ if (!edge) {+ errors.push(`mainline.edgeIds: ${id} is not an edge of this Goal`);+ continue;+ }+ const outside = [edge.sourceNodeId, edge.targetNodeId].filter((end) => !onMainline.has(end));+ if (outside.length > 0)+ errors.push(+ `mainline.edgeIds: ${id} connects ${outside.join(', ')}, which is not a mainline node`,+ );+ }++ const chaptered = new Set<string>();+ metadata.chapters.forEach((chapter, index) => {+ for (const id of chapter.nodeIds) {+ chaptered.add(id);+ if (byId.has(id) && !onMainline.has(id))+ errors.push(`chapters[${index}].nodeIds: ${id} is not on the mainline`);+ }+ chapter.detours.forEach((detour, detourIndex) => {+ for (const id of detour.nodeIds) {+ if (onMainline.has(id))+ errors.push(+ `chapters[${index}].detours[${detourIndex}].nodeIds: ${id} is on the mainline; a detour cannot be`,+ );+ }+ });+ });++ for (const id of mainline.nodeIds) {+ const node = byId.get(id);+ // An invalid mainline node was already reported above; asking to tell it too is noise.+ if (node?.status === 'resolved' && CHAPTERED_KINDS.has(node.kind) && !chaptered.has(id))+ errors.push(`mainline.nodeIds: ${id} is on the mainline but no chapter tells it`);+ }++ return errors;+};diff --git a/apps/server/src/services/goal/reportService.test.ts b/apps/server/src/services/goal/reportService.test.tsnew file mode 100644index 00000000000..d7b6ea3c494--- /dev/null+++ b/apps/server/src/services/goal/reportService.test.ts@@ -0,0 +1,401 @@+// @vitest-environment node+import { GOAL_REPORT_TASK_TITLE } from '@lobechat/const/goal';+import type { GoalReportMetadata } from '@lobechat/types';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { AgentOperationModel } from '@/database/models/agentOperation';+import { TaskModel } from '@/database/models/task';+import { TaskTopicModel } from '@/database/models/taskTopic';+import { WorkModel } from '@/database/models/work';+import {+ acceptances,+ agentOperations,+ agents,+ goalEdges,+ goalEvents,+ goalNodeDecisions,+ goalNodes,+ goalNodeWorkVersions,+ goals,+ tasks,+ taskTopics,+ topics,+ users,+ works,+ workVersions,+} from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++import { TaskRunnerService } from '../taskRunner';+import { GoalService } from './index';+import { GoalReportStore } from './reportStore';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'goal-report-test-user';++let runTask: ReturnType<typeof vi.spyOn>;++beforeEach(async () => {+ await serverDB.insert(users).values({ id: userId }).onConflictDoNothing();+ let seq = 0;+ runTask = vi+ .spyOn(TaskRunnerService.prototype, 'runTask')+ .mockImplementation(async ({ taskId }) => {+ seq += 1;+ const topicId = `tpc_report_${seq}`;+ await serverDB.insert(topics).values({ id: topicId, userId }).onConflictDoNothing();+ await new TaskModel(serverDB, userId).updateStatus(taskId, 'running');+ await new TaskTopicModel(serverDB, userId).add(taskId, topicId, {+ operationId: `op_report_${seq}`,+ seq,+ });+ return { operationId: `op_report_${seq}`, taskId, topicId } as any;+ });+});++afterEach(async () => {+ vi.restoreAllMocks();+ await serverDB.delete(goalNodeWorkVersions);+ await serverDB.delete(goalNodeDecisions);+ await serverDB.delete(goalEdges);+ await serverDB.delete(goalEvents);+ await serverDB.delete(goalNodes);+ await serverDB.delete(goals);+ await serverDB.delete(workVersions);+ await serverDB.delete(works);+ await serverDB.delete(acceptances);+ await serverDB.delete(agentOperations);+ await serverDB.delete(taskTopics);+ await serverDB.delete(topics);+ await serverDB.delete(tasks);+ await serverDB.delete(agents);+ await serverDB.delete(users);+});++/** Drive a one-Task goal to the point where Goal-level acceptance is running. */+const runToAcceptance = async (service: GoalService, config?: object) => {+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ config,+ requirement: 'Deliver a verified report',+ tasks: ['Build the thing'],+ title: 'Report goal',+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'completed');+ await service.tick(graph.goal.id); // consume → finding+ await service.tick(graph.goal.id); // create acceptance node+ const acceptance = await service.tick(graph.goal.id); // bind acceptance task+ return { acceptanceTaskId: acceptance.taskId!, goalId: graph.goal.id, taskModel };+};++const reportTaskRuns = () =>+ runTask.mock.calls.filter(([params]: any) =>+ params.additionalPluginIds?.includes('lobe-goal-report'),+ );++describe('GoalService wrap-up branch', () => {+ it('does not dispatch before Goal-level acceptance has ended', async () => {+ const service = new GoalService(serverDB, userId);+ const { goalId } = await runToAcceptance(service);++ // Acceptance Task exists but has not finished: tick a few more times.+ await service.tick(goalId);+ await service.tick(goalId);++ const graph = await service.graph(goalId);+ expect(graph.nodes.some((node) => node.title === GOAL_REPORT_TASK_TITLE)).toBe(false);+ expect(graph.report).toBeUndefined();+ expect(reportTaskRuns()).toHaveLength(0);+ });++ it('dispatches once after acceptance passes, and shows it as running', async () => {+ const service = new GoalService(serverDB, userId);+ const { acceptanceTaskId, goalId, taskModel } = await runToAcceptance(service);+ await taskModel.updateStatus(acceptanceTaskId, 'completed');+ await service.tick(goalId); // consume acceptance+ expect(await service.tick(goalId)).toMatchObject({ outcome: 'achieved' });++ // Re-ticking the achieved goal must not dispatch again.+ await service.tick(goalId);+ await service.tick(goalId);++ expect(reportTaskRuns()).toHaveLength(1);+ const graph = await service.graph(goalId);+ expect(graph.goal.status).toBe('achieved');+ const reportNode = graph.nodes.find((node) => node.title === GOAL_REPORT_TASK_TITLE)!;+ expect(reportNode).toMatchObject({ kind: 'task', status: 'active' });+ expect(graph.report).toMatchObject({+ dispatch: { nodeId: reportNode.id, taskId: reportNode.taskId, trigger: 'accepted' },+ status: 'running',+ });+ const reportTask = await taskModel.findById(reportNode.taskId!);+ expect(reportTask?.instruction).toContain('Candidate main path');+ expect(reportTask?.instruction).toContain('Goal-level acceptance passed');+ });++ it('dispatches once when acceptance failed with its attempts spent, not again on fail', async () => {+ const service = new GoalService(serverDB, userId);+ const { acceptanceTaskId, goalId, taskModel } = await runToAcceptance(service, {+ recovery: { maxAttemptsPerTask: 1 },+ });+ await taskModel.update(acceptanceTaskId, { totalTopics: 1 });+ await taskModel.updateStatus(acceptanceTaskId, 'paused', {+ error: 'Delivery did not pass verification.',+ });+ expect(await service.tick(goalId)).toMatchObject({ outcome: 'waiting_human' });+ await service.tick(goalId);+ expect(reportTaskRuns()).toHaveLength(1);+ expect((await service.graph(goalId)).report?.dispatch.trigger).toBe('acceptance_failed');++ const gate = (await service.graph(goalId)).decisions.find((d) => d.status === 'pending')!;+ await service.decide(goalId, gate.id, 'fail', 'Out of attempts');+ expect(await service.tick(goalId)).toMatchObject({ outcome: 'failed' });+ expect(reportTaskRuns()).toHaveLength(1);+ });++ it('dispatches once when the Goal is canceled', async () => {+ const service = new GoalService(serverDB, userId);+ const { goalId } = await runToAcceptance(service);+ await serverDB.update(goals).set({ status: 'canceled' }).where(eq(goals.id, goalId));++ await service.tick(goalId);+ await service.tick(goalId);++ expect(reportTaskRuns()).toHaveLength(1);+ const graph = await service.graph(goalId);+ expect(graph.goal.status).toBe('canceled');+ expect(graph.report?.dispatch.trigger).toBe('goal_canceled');+ });++ it('re-dispatches the same wrap-up Task when acceptance ends again after changes', async () => {+ const service = new GoalService(serverDB, userId);+ const { acceptanceTaskId, goalId, taskModel } = await runToAcceptance(service);+ await taskModel.updateStatus(acceptanceTaskId, 'completed');+ await service.tick(goalId);+ await service.tick(goalId);+ const first = (await service.graph(goalId)).report!.dispatch;++ // "Request changes": acceptance reopened, fixed, and accepted again.+ const acceptanceNode = (await service.graph(goalId)).nodes.find(+ (node) => node.taskId === acceptanceTaskId,+ )!;+ await serverDB+ .update(goalNodes)+ .set({ resolvedAt: new Date(Date.now() + 60_000), status: 'resolved' })+ .where(eq(goalNodes.id, acceptanceNode.id));+ await service.tick(goalId);++ const second = (await service.graph(goalId)).report!.dispatch;+ expect(reportTaskRuns()).toHaveLength(2);+ expect(second.acceptanceKey).not.toBe(first.acceptanceKey);+ expect(second.taskId).toBe(first.taskId);+ });++ /**+ * Regression: a heterogeneous wrap-up agent never receives server tools, so an+ * instruction naming only the report tool could never be followed.+ */+ it('tells a heterogeneous wrap-up agent to submit through the CLI', async () => {+ await serverDB.insert(agents).values({+ agencyConfig: { heterogeneousProvider: { type: 'claude-code' } } as any,+ id: 'agt_report_hetero',+ userId,+ });+ const service = new GoalService(serverDB, userId);+ const { acceptanceTaskId, goalId, taskModel } = await runToAcceptance(service, {+ taskAgentId: 'agt_report_hetero',+ });+ await taskModel.updateStatus(acceptanceTaskId, 'completed');+ await service.tick(goalId);+ await service.tick(goalId);++ const [{ taskId }] = reportTaskRuns().map(([params]: any) => params);+ const task = await taskModel.findById(taskId);+ expect(task?.assigneeAgentId).toBe('agt_report_hetero');+ expect(task?.instruction).toContain(`lh goal report ${goalId}`);+ expect(task?.instruction).not.toContain('submitGoalReport');+ });++ it('a failed wrap-up leaves the Goal status alone and reads as failed', async () => {+ runTask.mockRejectedValue(new Error('agent unavailable'));+ const service = new GoalService(serverDB, userId);+ const { acceptanceTaskId, goalId, taskModel } = await runToAcceptance(service);+ await taskModel.updateStatus(acceptanceTaskId, 'completed');+ await service.tick(goalId);+ expect(await service.tick(goalId)).toMatchObject({ outcome: 'achieved' });++ const graph = await service.graph(goalId);+ expect(graph.goal.status).toBe('achieved');+ expect(graph.report).toMatchObject({+ dispatch: { error: 'agent unavailable' },+ status: 'failed',+ });+ // The receipt still names the bound Task, so the page can point at it.+ expect(graph.report?.dispatch.taskId).toBe(+ graph.nodes.find((node) => node.title === GOAL_REPORT_TASK_TITLE)?.taskId,+ );+ expect(graph.report?.dispatch.taskId).toBeTruthy();+ });+});++describe('GoalReportStore.submit', () => {+ const setup = async () => {+ const service = new GoalService(serverDB, userId);+ const { acceptanceTaskId, goalId, taskModel } = await runToAcceptance(service);+ await taskModel.updateStatus(acceptanceTaskId, 'completed');+ await service.tick(goalId);+ await service.tick(goalId);+ const graph = await service.graph(goalId);+ const reportNode = graph.nodes.find((node) => node.title === GOAL_REPORT_TASK_TITLE)!;+ const buildNode = graph.nodes.find((node) => node.title === 'Build the thing')!;+ const finding = graph.nodes.find((node) => node.kind === 'finding')!;+ const topic = (await new TaskTopicModel(serverDB, userId).findByTaskId(reportNode.taskId!))[0];+ const metadata: GoalReportMetadata = {+ chapters: [+ {+ detours: [],+ findingIds: [finding.id],+ narrative: 'Built it and it held up under acceptance.',+ nodeIds: [buildNode.id],+ title: 'Building',+ workVersionIds: [],+ },+ ],+ graphCursor: graph.events[0].id,+ headline: 'Delivered a verified report',+ mainline: { edgeIds: [], nodeIds: [buildNode.id] },+ nextSteps: [{ reason: 'Nothing blocks it', title: 'Ship' }],+ };+ return { buildNode, goalId, metadata, reportNode, service, topicId: topic.topicId! };+ };++ it('rejects references that do not belong to the Goal and stores nothing', async () => {+ const { goalId, metadata, reportNode, service, topicId } = await setup();+ const reports = new GoalReportStore(serverDB, userId);++ await expect(+ reports.submit(+ goalId,+ {+ content: '# Report',+ metadata: {+ ...metadata,+ chapters: [{ ...metadata.chapters[0], nodeIds: ['gnode_elsewhere'] }],+ },+ },+ { topicId },+ ),+ ).rejects.toThrow('chapters[0].nodeIds: gnode_elsewhere is not a node of this Goal');++ // The wrap-up node is hidden from the story, so it can never be on the mainline.+ await expect(+ reports.submit(+ goalId,+ {+ content: '# Report',+ metadata: {+ ...metadata,+ mainline: { edgeIds: ['gedge_elsewhere'], nodeIds: [reportNode.id] },+ },+ },+ { topicId },+ ),+ ).rejects.toThrow('mainline.edgeIds: gedge_elsewhere is not an edge of this Goal');++ await expect(+ reports.submit(+ goalId,+ { content: '# Report', metadata: { ...metadata, mainline: undefined } },+ { topicId },+ ),+ ).rejects.toThrow('mainline: required');++ await expect(+ reports.submit(goalId, { content: '# Report', metadata }, { topicId: 'tpc_other' }),+ ).rejects.toThrow('not the wrap-up run');++ expect(await new WorkModel(serverDB, userId).findLatestGoalReport(goalId)).toBeUndefined();+ expect((await service.graph(goalId)).report?.status).toBe('running');+ });++ it('accepts a report from an operation of the wrap-up run and refuses any other run', async () => {+ const { goalId, metadata, topicId } = await setup();+ const reports = new GoalReportStore(serverDB, userId);+ const operations = new AgentOperationModel(serverDB, userId);+ await operations.recordStart({ operationId: 'op_cli_wrapup', topicId });+ await serverDB.insert(topics).values({ id: 'tpc_elsewhere', userId });+ await operations.recordStart({ operationId: 'op_cli_elsewhere', topicId: 'tpc_elsewhere' });++ await expect(+ reports.submitFromOperation(goalId, { content: '# Report', metadata }, 'op_cli_elsewhere'),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ await expect(+ reports.submitFromOperation(goalId, { content: '# Report', metadata }, 'op_missing'),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ const stored = await reports.submitFromOperation(+ goalId,+ { content: '# Report', metadata },+ 'op_cli_wrapup',+ );+ expect(stored.version).toBe(1);+ });++ it('stores metadata and content separately, appending a version per submission', async () => {+ const { goalId, metadata, reportNode, service, topicId } = await setup();+ const reports = new GoalReportStore(serverDB, userId);++ const first = await reports.submit(+ goalId,+ { content: '# Report v1\n\nBuilt it.', metadata },+ { operationId: 'op_report_1', topicId },+ );+ const second = await reports.submit(+ goalId,+ { content: '# Report v2', metadata: { ...metadata, headline: 'Second pass' } },+ { operationId: 'op_report_1', topicId },+ );+ expect(first.version).toBe(1);+ expect(second.version).toBe(2);+ expect(second.workId).toBe(first.workId);++ const [work] = await serverDB.select().from(works).where(eq(works.id, first.workId));+ expect(work).toMatchObject({+ resourceId: goalId,+ resourceType: 'goal_report',+ type: 'goal_report',+ });+ const rows = await serverDB+ .select()+ .from(workVersions)+ .where(eq(workVersions.workId, first.workId))+ .orderBy(workVersions.version);+ expect(rows.map((row) => row.content)).toEqual(['# Report v1\n\nBuilt it.', '# Report v2']);+ expect(rows[0].metadata).toEqual({ goalReport: metadata });+ expect(rows[1].metadata?.goalReport?.headline).toBe('Second pass');+ expect(rows[1].metadata?.goalReport?.mainline).toEqual(metadata.mainline);++ const graph = await service.graph(goalId);+ expect(graph.report).toMatchObject({+ latest: { content: '# Report v2', metadata: { headline: 'Second pass' }, version: 2 },+ status: 'completed',+ });+ expect(graph.nodes.find((node) => node.id === reportNode.id)?.status).toBe('resolved');+ expect(graph.workVersions).toContainEqual(+ expect.objectContaining({+ nodeId: reportNode.id,+ relation: 'produced',+ workVersionId: second.workVersionId,+ }),+ );+ // Report links are invisible to the generic Work lists.+ expect(+ await new WorkModel(serverDB, userId).listByWorkspace({ includeFileWorks: true }),+ ).toMatchObject({+ items: expect.not.arrayContaining([expect.objectContaining({ type: 'goal_report' })]),+ });+ });+});diff --git a/apps/server/src/services/goal/reportService.ts b/apps/server/src/services/goal/reportService.tsnew file mode 100644index 00000000000..e3c28c07b49--- /dev/null+++ b/apps/server/src/services/goal/reportService.ts@@ -0,0 +1,217 @@+import { GoalReportApiName, GoalReportIdentifier } from '@lobechat/builtin-tool-goal/report';+import { isHeterogeneousAgentModelId } from '@lobechat/const';+import {+ GOAL_ACCEPTANCE_TASK_TITLE,+ GOAL_COORDINATOR_ACTOR_ID,+ GOAL_REPORT_TASK_TITLE,+} from '@lobechat/const/goal';+import type { GoalGraphSnapshot, GoalReportDispatch, GoalReportTrigger } from '@lobechat/types';++import { AgentModel } from '@/database/models/agent';+import { GoalModel } from '@/database/models/goal';+import { GoalGraphModel } from '@/database/models/goalGraph';+import { TaskModel } from '@/database/models/task';+import { TaskTopicModel } from '@/database/models/taskTopic';+import type { LobeChatDatabase } from '@/database/type';++import { TaskService } from '../task';+import { TaskRunnerService } from '../taskRunner';+import { buildGoalReportInstruction, decideGoalReport } from './report';++const REPORT_MAX_STEPS = 40;+const TASK_DESCRIPTION_MAX_LENGTH = 255;++export class GoalReportService {+ private readonly coordinatorGraph: GoalGraphModel;+ private readonly taskModel: TaskModel;+ private readonly taskTopicModel: TaskTopicModel;++ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,+ ) {+ this.coordinatorGraph = new GoalGraphModel(db, userId, workspaceId, {+ id: GOAL_COORDINATOR_ACTOR_ID,+ type: 'system',+ });+ this.taskModel = new TaskModel(db, userId, workspaceId);+ this.taskTopicModel = new TaskTopicModel(db, userId, workspaceId);+ }++ // -------------------------------------------------------------------------+ // Dispatch+ // -------------------------------------------------------------------------++ /**+ * Dispatch the wrap-up run when the Goal-level acceptance has ended and no+ * wrap-up was dispatched for that result yet.+ *+ * Best-effort by contract: the wrap-up never takes part in the Goal's status,+ * so a failure here is recorded on the dispatch receipt and swallowed.+ */+ dispatchIfDue = async (goalId: string): Promise<GoalReportDispatch | undefined> => {+ const graph = await this.coordinatorGraph.getGraph(goalId);+ if (!graph) return undefined;+ const decision = decideGoalReport(graph);+ if (!decision.dispatch) return undefined;++ // Claim the result under the goal row lock, so two coordinators reading the+ // same ended acceptance dispatch exactly one wrap-up.+ const claimed = await this.db.transaction(async (tx) => {+ const model = new GoalModel(tx, this.userId, this.workspaceId);+ const goal = await model.lockById(goalId);+ if (!goal || goal.config?.report?.acceptanceKey === decision.key) return undefined;++ const writer = new GoalGraphModel(tx, this.userId, this.workspaceId, {+ id: GOAL_COORDINATOR_ACTOR_ID,+ type: 'system',+ });+ const created = await writer.createNodeOnce(goalId, {+ description:+ 'Wrap-up: turn the finished Goal graph into a chaptered storyline and a written report. Does not affect the Goal status.',+ kind: 'task',+ priority: -2,+ status: 'proposed',+ title: GOAL_REPORT_TASK_TITLE,+ });+ if (!created) return undefined;+ if (created.created) {+ const acceptance = graph.nodes.find(+ (node) => node.kind === 'task' && node.title === GOAL_ACCEPTANCE_TASK_TITLE,+ );+ if (acceptance)+ await writer.createEdge(goalId, created.node.id, acceptance.id, 'depends_on');+ }++ const dispatch: GoalReportDispatch = {+ acceptanceKey: decision.key,+ dispatchedAt: new Date().toISOString(),+ nodeId: created.node.id,+ taskId: created.node.taskId ?? undefined,+ trigger: decision.trigger,+ };+ await model.update(goalId, { config: { ...goal.config, report: dispatch } });+ return dispatch;+ });+ if (!claimed) return undefined;++ try {+ const started = await this.startRun(graph, claimed, decision.trigger);+ return this.recordDispatch(goalId, claimed.acceptanceKey, started);+ } catch (error) {+ console.error('[GoalReportService] wrap-up dispatch failed:', error);+ return this.recordDispatch(goalId, claimed.acceptanceKey, {+ error: error instanceof Error ? error.message : String(error),+ });+ }+ };++ private startRun = async (+ graph: GoalGraphSnapshot,+ dispatch: GoalReportDispatch,+ trigger: GoalReportTrigger,+ ): Promise<Partial<GoalReportDispatch>> => {+ const goalId = graph.goal.id;+ // A re-run keeps whoever the Task is already assigned to.+ const assigneeAgentId = dispatch.taskId+ ? ((await this.taskModel.findById(dispatch.taskId))?.assigneeAgentId ?? undefined)+ : await this.resolveAssignee(graph);+ const instruction = buildGoalReportInstruction(+ graph,+ trigger,+ (await this.isHeterogeneousAgent(assigneeAgentId))+ ? { kind: 'cli' }+ : {+ kind: 'tool',+ toolName: `${GoalReportIdentifier}.${GoalReportApiName.submitGoalReport}`,+ },+ );++ let taskId = dispatch.taskId;+ if (taskId) {+ // A new acceptance result: rewrite the same Task for the new skeleton and+ // run it again, which appends a report version instead of a second Task.+ for (const topic of await this.taskTopicModel.findRunningByTaskIds([taskId])) {+ if (topic.topicId)+ await new TaskService(this.db, this.userId, this.workspaceId)+ .cancelTopic(topic.topicId)+ .catch(() => {});+ }+ await this.taskModel.update(taskId, { error: null, instruction, status: 'backlog' });+ } else {+ const task = await new TaskService(this.db, this.userId, this.workspaceId).createTask({+ assigneeAgentId,+ config: { checkpoint: { topic: { after: false } } },+ description: `Wrap-up report of ${graph.goal.title}`.slice(0, TASK_DESCRIPTION_MAX_LENGTH),+ instruction,+ name: GOAL_REPORT_TASK_TITLE,+ projectId: graph.goal.projectId ?? undefined,+ });+ const bound = await this.coordinatorGraph.bindTask(goalId, dispatch.nodeId, task.id);+ if (!bound) {+ await this.taskModel.delete(task.id);+ throw new Error('Wrap-up node was bound by another coordinator');+ }+ taskId = task.id;+ // Kept on the receipt before the run starts, so a run that fails to start+ // still names the Task the page can point at.+ await this.recordDispatch(goalId, dispatch.acceptanceKey, { taskId });+ }+ await this.coordinatorGraph.updateNodeStatus(+ goalId,+ dispatch.nodeId,+ 'active',+ `Writing the Goal report (${trigger})`,+ );++ const run = await new TaskRunnerService(this.db, this.userId, this.workspaceId).runTask({+ additionalPluginIds: [GoalReportIdentifier],+ maxSteps: REPORT_MAX_STEPS,+ taskId,+ trigger: 'goal',+ });+ return { operationId: run.operationId, taskId };+ };++ /** The goal agent narrates its own Goal; the executor is the fallback. */+ private resolveAssignee = async (graph: GoalGraphSnapshot) => {+ const agentModel = new AgentModel(this.db, this.userId, this.workspaceId);+ for (const id of [graph.goal.agentId, graph.goal.config?.taskAgentId]) {+ if (id && (await agentModel.existsById(id))) return id;+ }+ return undefined;+ };++ /**+ * Heterogeneous agents run on a device and never receive server tools such as+ * the report tool, so their wrap-up submits through the `lh` CLI. Same test+ * the agent runtime uses to route a run to the device.+ */+ private isHeterogeneousAgent = async (agentId?: string) => {+ if (!agentId) return false;+ const agent = await new AgentModel(this.db, this.userId, this.workspaceId).getAgentConfigById(+ agentId,+ );+ return (+ !!agent?.agencyConfig?.heterogeneousProvider?.type ||+ (!!agent?.model && isHeterogeneousAgentModelId(agent.model))+ );+ };++ private recordDispatch = async (+ goalId: string,+ acceptanceKey: string,+ patch: Partial<GoalReportDispatch>,+ ) =>+ this.db.transaction(async (tx) => {+ const model = new GoalModel(tx, this.userId, this.workspaceId);+ const goal = await model.lockById(goalId);+ const current = goal?.config?.report;+ // A newer result may have claimed the receipt meanwhile; leave it alone.+ if (!goal || !current || current.acceptanceKey !== acceptanceKey) return current;+ const report = { ...current, ...patch };+ await model.update(goalId, { config: { ...goal.config, report } });+ return report;+ });+}diff --git a/apps/server/src/services/goal/reportStore.ts b/apps/server/src/services/goal/reportStore.tsnew file mode 100644index 00000000000..9708e4e7a27--- /dev/null+++ b/apps/server/src/services/goal/reportStore.ts@@ -0,0 +1,222 @@+import { GoalReportApiName, GoalReportIdentifier } from '@lobechat/builtin-tool-goal/report';+import { GOAL_COORDINATOR_ACTOR_ID } from '@lobechat/const/goal';+import type {+ GoalGraphSnapshot,+ GoalReportDispatch,+ GoalReportMetadata,+ GoalReportState,+} from '@lobechat/types';+import { GoalReportMetadataSchema } from '@lobechat/types';+import { TRPCError } from '@trpc/server';+import { eq } from 'drizzle-orm';++import { AgentOperationModel } from '@/database/models/agentOperation';+import { GoalGraphModel } from '@/database/models/goalGraph';+import { TaskModel } from '@/database/models/task';+import { TaskTopicModel } from '@/database/models/taskTopic';+import { WorkModel } from '@/database/models/work';+import { goalEvents } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++import { validateGoalReport } from './report';++/**+ * How long a wrap-up run may go without submitting before the page stops+ * showing it as in progress. The Goal itself never waits on it.+ */+export const GOAL_REPORT_TIMEOUT_MS = 60 * 60 * 1000;++export interface SubmitGoalReportInput {+ content: string;+ metadata: Omit<GoalReportMetadata, 'graphCursor'> & { graphCursor?: string };+}++export interface GoalReportCaller {+ agentId?: string | null;+ operationId?: string | null;+ toolCallId?: string | null;+ topicId?: string | null;+}++/**+ * Writes and reads of the Goal report. Kept free of the task runner (and so of+ * the agent runtime) because the wrap-up agent's tool runtime imports it: the+ * runtime registry sits under the agent runtime, and importing back up into it+ * would be a cycle.+ */+export class GoalReportStore {+ private readonly coordinatorGraph: GoalGraphModel;+ private readonly operationModel: AgentOperationModel;+ private readonly taskModel: TaskModel;+ private readonly taskTopicModel: TaskTopicModel;+ private readonly workModel: WorkModel;++ constructor(+ private readonly db: LobeChatDatabase,+ userId: string,+ workspaceId?: string,+ ) {+ this.coordinatorGraph = new GoalGraphModel(db, userId, workspaceId, {+ id: GOAL_COORDINATOR_ACTOR_ID,+ type: 'system',+ });+ this.operationModel = new AgentOperationModel(db, userId, workspaceId);+ this.taskModel = new TaskModel(db, userId, workspaceId);+ this.taskTopicModel = new TaskTopicModel(db, userId, workspaceId);+ this.workModel = new WorkModel(db, userId, workspaceId);+ }++ // -------------------------------------------------------------------------+ // Submission+ // -------------------------------------------------------------------------++ /**+ * Submit on behalf of a running operation — the CLI path a heterogeneous+ * wrap-up agent takes, since server tools never reach a device run. The+ * operation is looked up with the caller's own ownership, and its topic must+ * be a run of this Goal's wrap-up Task, exactly as for the tool.+ */+ submitFromOperation = async (+ goalId: string,+ input: SubmitGoalReportInput,+ operationId: string,+ ) => {+ const operation = await this.operationModel.findOwnOperationById(operationId);+ if (!operation) throw new TRPCError({ code: 'NOT_FOUND', message: 'Operation not found' });+ return this.submit(goalId, input, {+ agentId: operation.agentId,+ operationId: operation.id,+ topicId: operation.topicId,+ });+ };++ /**+ * Validate and store one report version.+ *+ * When `caller` is given (the tool path), it must be a run of this Goal's+ * wrap-up Task — no other conversation can rewrite a Goal's report.+ */+ submit = async (goalId: string, input: SubmitGoalReportInput, caller?: GoalReportCaller) => {+ const graph = await this.coordinatorGraph.getGraph(goalId);+ if (!graph) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ const dispatch = graph.goal.config?.report;+ if (!dispatch)+ throw new TRPCError({+ code: 'PRECONDITION_FAILED',+ message: 'No wrap-up was dispatched for this Goal',+ });++ if (caller) {+ const runs = dispatch.taskId ? await this.taskTopicModel.findByTaskId(dispatch.taskId) : [];+ if (!caller.topicId || !runs.some((run) => run.topicId === caller.topicId))+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'This conversation is not the wrap-up run of this Goal',+ });+ }++ const eventRows = await this.db+ .select({ createdAt: goalEvents.createdAt, id: goalEvents.id })+ .from(goalEvents)+ .where(eq(goalEvents.goalId, goalId));+ const eventIds = new Set(eventRows.map((row) => row.id));+ const newestEvent = eventRows.sort(+ (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),+ )[0];++ const parsed = GoalReportMetadataSchema.safeParse({+ ...input.metadata,+ graphCursor: input.metadata.graphCursor ?? newestEvent?.id,+ });+ if (!parsed.success)+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: `Invalid report: ${parsed.error.issues+ .map((issue) => `${issue.path.join('.')}: ${issue.message}`)+ .join('; ')}`,+ });+ const content = input.content.trim();+ if (!content)+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Invalid report: content is empty' });++ const errors = validateGoalReport(graph, parsed.data, { eventIds });+ if (errors.length > 0)+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: `Invalid report references:\n${errors.join('\n')}`,+ });++ const work = await this.workModel.registerGoalReport({+ agentId: caller?.agentId,+ content,+ goalId,+ metadata: parsed.data,+ rootOperationId: caller?.operationId,+ title: `Goal report: ${graph.goal.title}`,+ toolCallId: caller?.toolCallId,+ toolIdentifier: GoalReportIdentifier,+ toolName: GoalReportApiName.submitGoalReport,+ topicId: caller?.topicId,+ });+ if (work.currentVersionId) {+ await this.coordinatorGraph.attachWorkVersion(+ goalId,+ dispatch.nodeId,+ work.currentVersionId,+ 'produced',+ );+ }+ await this.coordinatorGraph.updateNodeStatus(+ goalId,+ dispatch.nodeId,+ 'resolved',+ 'Goal report submitted',+ );+ const latest = await this.workModel.findLatestGoalReport(goalId);+ return { version: latest?.version, workId: work.id, workVersionId: work.currentVersionId };+ };++ // -------------------------------------------------------------------------+ // Read+ // -------------------------------------------------------------------------++ /** The wrap-up state for a graph read: in progress, completed or failed. */+ state = async (graph: GoalGraphSnapshot): Promise<GoalReportState | undefined> => {+ const dispatch = graph.goal.config?.report;+ if (!dispatch) return undefined;++ const latestRow = await this.workModel.findLatestGoalReport(graph.goal.id);+ const parsed = latestRow+ ? GoalReportMetadataSchema.safeParse(latestRow.metadata?.goalReport)+ : undefined;+ const latest =+ latestRow && parsed?.success+ ? {+ content: latestRow.content,+ createdAt: latestRow.createdAt,+ metadata: parsed.data,+ version: latestRow.version,+ workId: latestRow.workId,+ workVersionId: latestRow.workVersionId,+ }+ : undefined;++ return { dispatch, latest, status: await this.resolveStatus(dispatch, latest?.createdAt) };+ };++ private resolveStatus = async (+ dispatch: GoalReportDispatch,+ latestAt?: Date,+ ): Promise<GoalReportState['status']> => {+ const dispatchedAt = new Date(dispatch.dispatchedAt).getTime();+ if (latestAt && new Date(latestAt).getTime() >= dispatchedAt) return 'completed';+ if (dispatch.error) return 'failed';+ if (Date.now() - dispatchedAt > GOAL_REPORT_TIMEOUT_MS) return 'failed';+ if (!dispatch.taskId) return 'running';+ const task = await this.taskModel.findById(dispatch.taskId);+ if (!task) return 'failed';+ // The run ended — completed, failed, paused on an error — without a report.+ if (['completed', 'failed', 'canceled', 'paused'].includes(task.status)) return 'failed';+ return 'running';+ };+}diff --git a/apps/server/src/services/goal/reportTools.ts b/apps/server/src/services/goal/reportTools.tsnew file mode 100644index 00000000000..b102a47d42c--- /dev/null+++ b/apps/server/src/services/goal/reportTools.ts@@ -0,0 +1,91 @@+import type {+ ReadGoalGraphParams,+ SubmitGoalReportParams,+} from '@lobechat/builtin-tool-goal/report';++import { GoalGraphModel } from '@/database/models/goalGraph';+import type { ToolExecutionContext } from '@/server/services/toolExecution/types';++import { withoutGoalReport } from './report';+import { GoalReportStore } from './reportStore';++const DESCRIPTION_PREVIEW = 600;++/** The wrap-up agent's tools. Every call is bound to the server-created wrap-up run. */+export class GoalReportTools {+ constructor(+ private readonly context: Pick<+ ToolExecutionContext,+ 'agentId' | 'operationId' | 'serverDB' | 'toolCallId' | 'topicId' | 'userId' | 'workspaceId'+ >,+ ) {}++ private run = async (action: () => Promise<unknown>) => {+ try {+ return { content: JSON.stringify(await action()), success: true };+ } catch (error) {+ console.error('[goal:report:tool] call failed', error);+ return {+ content: error instanceof Error ? error.message : 'Goal report tool failed',+ success: false,+ };+ }+ };++ readGoalGraph = (params: ReadGoalGraphParams) =>+ this.run(async () => {+ const { serverDB, userId, workspaceId } = this.context;+ const graph = await new GoalGraphModel(serverDB!, userId!, workspaceId).getGraph(+ params.goalId,+ );+ if (!graph) throw new Error('Goal not found');+ const view = withoutGoalReport(graph);+ return {+ decisions: view.decisions.map((decision) => ({+ id: decision.id,+ nodeId: decision.nodeId,+ question: decision.question,+ resolution: decision.resolution,+ resolvedOptionId: decision.resolvedOptionId,+ status: decision.status,+ })),+ edges: view.edges.map((edge) => ({+ kind: edge.kind,+ source: edge.sourceNodeId,+ target: edge.targetNodeId,+ })),+ goal: {+ id: view.goal.id,+ requirement: view.goal.requirement,+ status: view.goal.status,+ title: view.goal.title,+ },+ nodes: view.nodes.map((node) => ({+ description: node.description?.slice(0, DESCRIPTION_PREVIEW) ?? null,+ id: node.id,+ kind: node.kind,+ status: node.status,+ title: node.title,+ })),+ workVersions: view.workVersions.map((link) => ({+ nodeId: link.nodeId,+ relation: link.relation,+ title: link.work?.title ?? null,+ type: link.work?.type ?? null,+ workId: link.work?.workId ?? null,+ workVersionId: link.workVersionId,+ })),+ };+ });++ submitGoalReport = ({ content, goalId, ...metadata }: SubmitGoalReportParams) =>+ this.run(async () => {+ const { agentId, operationId, serverDB, toolCallId, topicId, userId, workspaceId } =+ this.context;+ return new GoalReportStore(serverDB!, userId!, workspaceId).submit(+ goalId,+ { content, metadata },+ { agentId, operationId, toolCallId, topicId: topicId ?? null },+ );+ });+}diff --git a/apps/server/src/services/taskRunner/buildTaskPrompt.test.ts b/apps/server/src/services/taskRunner/buildTaskPrompt.test.tsindex 632c0f78646..1cd65a07300 100644--- a/apps/server/src/services/taskRunner/buildTaskPrompt.test.ts+++ b/apps/server/src/services/taskRunner/buildTaskPrompt.test.ts@@ -92,6 +92,48 @@ describe('buildTaskPrompt Goal loop context', () => {});});+describe('buildTaskPrompt owner change request', () => {+ it('keeps the owner reject comment when the rework already opened a new round', async () => {+ const taskModel = new TaskModel(db, userId);+ const task = await taskModel.create({ instruction: 'Complete full Goal acceptance' });+ await taskModel.update(task.id, { totalTopics: 2 });+ const goal = await new GoalModel(db, userId).create({+ subjectType: 'standalone',+ title: 'Reworked delivery',+ });+ const graphModel = new GoalGraphModel(db, userId);+ const taskNode = await graphModel.createNode(goal.id, {+ kind: 'task',+ title: 'Complete full Goal acceptance',+ });+ await graphModel.bindTask(goal.id, taskNode!.id, task.id);+ const acceptance = await new AcceptanceModel(db, userId).create({+ subjectId: task.id,+ subjectType: 'task',+ });+ const runModel = new VerifyRunModel(db, userId);+ const rejected = await runModel.create({ acceptanceId: acceptance.id, roundIndex: 1 });+ await runModel.setDecision(rejected.id, 'reject', {+ comment: 'Add a day-one agenda',+ decidedAt: new Date().toISOString(),+ decidedBy: userId,+ });+ // The rework's first attempt planned its own round, then failed to run.+ await runModel.create({ acceptanceId: acceptance.id, roundIndex: 2 });++ const result = await buildTaskPrompt((await taskModel.findById(task.id))!, {+ briefModel: new BriefModel(db, userId),+ db,+ taskModel,+ taskTopicModel: new TaskTopicModel(db, userId),+ userId,+ });++ expect(result.prompt).toContain('Review feedback on the last delivery');+ expect(result.prompt).toContain('"Add a day-one agenda"');+ });+});+describe('buildTaskPrompt delivery acceptance', () => {const buildFor = async (taskId: string) => {const taskModel = new TaskModel(db, userId);diff --git a/apps/server/src/services/taskRunner/buildTaskPrompt.ts b/apps/server/src/services/taskRunner/buildTaskPrompt.tsindex 42ec75205e2..8bcf205395f 100644--- a/apps/server/src/services/taskRunner/buildTaskPrompt.ts+++ b/apps/server/src/services/taskRunner/buildTaskPrompt.ts@@ -51,8 +51,12 @@ const resolveGoalLoopContext = async (const last = runs.at(-1);if (!last) return context;- if (last.userDecision === 'reject') {- const comment = (last.decisionDetail as { comment?: string } | null)?.comment;+ // The owner's latest verdict is the instruction until they give another.+ // A rework's own rounds carry no decision, so a retry after its first+ // attempt failed must still read the comment the owner sent it back with.+ const decided = runs.findLast((run) => !!run.userDecision);+ if (decided?.userDecision === 'reject') {+ const comment = (decided.decisionDetail as { comment?: string } | null)?.comment;if (comment) context.rejectComment = comment;}diff --git a/apps/server/src/services/taskRunner/index.ts b/apps/server/src/services/taskRunner/index.tsindex 0f0180f0cec..ba202b527ca 100644--- a/apps/server/src/services/taskRunner/index.ts+++ b/apps/server/src/services/taskRunner/index.ts@@ -20,6 +20,8 @@ import { buildTaskPrompt } from './buildTaskPrompt';const log = debug('task-runner');export interface RunTaskParams {+ /** Extra builtin tools this run mounts beside the Task skill, e.g. the Goal report tool. */+ additionalPluginIds?: string[];continueTopicId?: string;extraPrompt?: string;/** Optional per-operation cap. Omitted means the agent runtime remains uncapped. */@@ -70,6 +72,7 @@ export class TaskRunnerService {async runTask(params: RunTaskParams): Promise<RunTaskResult> {const {+ additionalPluginIds,taskId: idOrIdentifier,continueTopicId,extraPrompt,@@ -208,6 +211,7 @@ export class TaskRunnerService {// turn, which mounts this tool exclusively and therefore can only ever// restate text it already wrote.if (acceptanceEnabled) pluginIds.push(AcceptanceEvidenceIdentifier);+ if (additionalPluginIds) pluginIds.push(...additionalPluginIds);const taskConfig = (task.config ?? {}) as Record<string, unknown>;diff --git a/apps/server/src/services/toolExecution/serverRuntimes/goalReport.ts b/apps/server/src/services/toolExecution/serverRuntimes/goalReport.tsnew file mode 100644index 00000000000..50bf27e9a35--- /dev/null+++ b/apps/server/src/services/toolExecution/serverRuntimes/goalReport.ts@@ -0,0 +1,14 @@+import { GoalReportIdentifier } from '@lobechat/builtin-tool-goal/report';++import { GoalReportTools } from '@/server/services/goal/reportTools';++import type { ServerRuntimeRegistration } from './types';++export const goalReportRuntime: ServerRuntimeRegistration = {+ identifier: GoalReportIdentifier,+ factory: (context) => {+ if (!context.serverDB || !context.userId)+ throw new Error('Goal report database context required');+ return new GoalReportTools(context);+ },+};diff --git a/apps/server/src/services/toolExecution/serverRuntimes/index.ts b/apps/server/src/services/toolExecution/serverRuntimes/index.tsindex d5b2ef17d7f..52543754f2e 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/index.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/index.ts@@ -25,6 +25,7 @@ import { calculatorRuntime } from './calculator';import { cloudSandboxRuntime } from './cloudSandbox';import { credsRuntime } from './creds';import { goalRuntime } from './goal';+import { goalReportRuntime } from './goalReport';import { goalSupervisorRuntime } from './goalSupervisor';import { groupAgentBuilderRuntime } from './groupAgentBuilder';import { groupManagementRuntime } from './groupManagement';@@ -92,6 +93,7 @@ registerRuntimes([groupAgentBuilderRuntime,groupManagementRuntime,goalRuntime,+ goalReportRuntime,goalSupervisorRuntime,imageGenerationRuntime,videoGenerationRuntime,diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex dcb218203a1..df0ded7c461 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -641,19 +641,20 @@"goalProcess.gate.reason.costBudgetExhausted": "The goal cost budget is used up","goalProcess.gate.reason.goalAcceptanceFailed": "Goal-level acceptance did not pass","goalProcess.gate.reason.recoveryFailed": "Automatic recovery could not start the next attempt",+ "goalProcess.gate.reason.runError": "The run stopped with an error ({{code}})","goalProcess.gate.reason.verifyFailed": "Task {{id}} did not pass verification","goalProcess.gate.reason.verifyInternalError": "Verification could not run (internal error); this delivery was not evaluated","goalProcess.gate.recommended": "recommended","goalProcess.gate.title.clarifyGoal": "Clarify the goal before work starts","goalProcess.gate.title.goalAcceptance": "Decide the goal acceptance outcome","goalProcess.gate.title.recoverTask": "Decide what happens to the failed task",- "goalProcess.goalAcceptance.review": "Review delivery",- "goalProcess.goalAcceptance.state.accepted": "Accepted",- "goalProcess.goalAcceptance.state.awaitingAcceptance": "Awaiting your acceptance",- "goalProcess.goalAcceptance.viewFull": "Read full report",+ "goalProcess.graph.bridgeHops_one": "via {{count}} step not shown",+ "goalProcess.graph.bridgeHops_other": "via {{count}} steps not shown","goalProcess.graph.exitFullscreen": "Exit fullscreen","goalProcess.graph.fullscreen": "Fullscreen","goalProcess.graph.legend.hide": "Hide this kind on the map",+ "goalProcess.graph.legend.mainline": "Mainline",+ "goalProcess.graph.legend.mainlineHint": "The path the wrap-up report marked as the one that led to the result","goalProcess.graph.legend.show": "Show this kind on the map","goalProcess.graph.title": "Exploration map","goalProcess.graph.view.all": "Full map",@@ -788,6 +789,110 @@"goalProcess.portal.title": "Goal","goalProcess.requirementPlaceholder": "Describe what counts as done…","goalProcess.requirementSaveFailed": "Failed to save the requirement — it will retry on your next edit",+ "goalProcess.result.changes.comment": "Your feedback",+ "goalProcess.result.changes.revising": "You asked for changes. The Agent is reworking the delivery and will send it for acceptance again.",+ "goalProcess.result.continueSeed.deliverable": "Delivered: {{title}}",+ "goalProcess.result.continueSeed.intro": "Continue from the result of the Goal \"{{title}}\".",+ "goalProcess.result.continueSeed.open": "Still open:",+ "goalProcess.result.continueSeed.requirement": "Original requirement:",+ "goalProcess.result.continueSeed.title": "Continue: {{title}}",+ "goalProcess.result.criteria.document": "Evidence document",+ "goalProcess.result.criteria.empty": "This Goal has no structured acceptance criteria.",+ "goalProcess.result.criteria.evidenceCount": "{{count}} evidence",+ "goalProcess.result.criteria.state.failed": "Not met",+ "goalProcess.result.criteria.state.passed": "Met",+ "goalProcess.result.criteria.state.unjudged": "Not judged",+ "goalProcess.result.criteria.title": "Acceptance criteria",+ "goalProcess.result.criteria.unjudgedHint": "The latest acceptance round did not judge this criterion.",+ "goalProcess.result.decisions.empty": "Nothing on this Goal needed your call.",+ "goalProcess.result.decisions.title": "Decisions you made",+ "goalProcess.result.deliverables.cited": "Cited as acceptance evidence: {{criteria}}",+ "goalProcess.result.deliverables.citedCount": "Cited by {{count}} acceptance criteria",+ "goalProcess.result.deliverables.clearFilter": "Clear search and filter",+ "goalProcess.result.deliverables.empty.description": "This Goal left nothing you can open here. Its tasks may have written results only to a local path or into the conversation — check each task’s output on the Process tab.",+ "goalProcess.result.deliverables.empty.title": "No persisted deliverables",+ "goalProcess.result.deliverables.filter.all": "All",+ "goalProcess.result.deliverables.filter.document": "Documents",+ "goalProcess.result.deliverables.filter.external": "Links",+ "goalProcess.result.deliverables.filter.file": "Files",+ "goalProcess.result.deliverables.noMatch": "No deliverables match “{{query}}”",+ "goalProcess.result.deliverables.noMatchType": "No deliverables of this type",+ "goalProcess.result.deliverables.otherTasks": "Other tasks",+ "goalProcess.result.deliverables.primary": "Main deliverable",+ "goalProcess.result.deliverables.producedBy": "By “{{title}}”",+ "goalProcess.result.deliverables.reader.cited": "Cited by acceptance",+ "goalProcess.result.deliverables.reader.close": "Close (Esc)",+ "goalProcess.result.deliverables.reader.download": "Download",+ "goalProcess.result.deliverables.reader.label": "Deliverable reader",+ "goalProcess.result.deliverables.reader.next": "Next (→)",+ "goalProcess.result.deliverables.reader.noPreview": "No online preview",+ "goalProcess.result.deliverables.reader.noUrl": "No download address was saved for this item.",+ "goalProcess.result.deliverables.reader.openLink": "Open in new window",+ "goalProcess.result.deliverables.reader.prev": "Previous (←)",+ "goalProcess.result.deliverables.reader.supports": "Supports: {{criteria}}",+ "goalProcess.result.deliverables.reader.unavailable": "This document cannot be opened here.",+ "goalProcess.result.deliverables.reader.uncited": "Not cited",+ "goalProcess.result.deliverables.search": "Search deliverables",+ "goalProcess.result.deliverables.titleWithCount": "Deliverables · {{count}}",+ "goalProcess.result.deliverables.uncited": "Not cited by acceptance evidence",+ "goalProcess.result.deliverables.viewAll": "Review all {{count}}",+ "goalProcess.result.gate.error": "Could not save the decision. Try again.",+ "goalProcess.result.gate.prompt": "Check which criteria were not met below, then retry or end the Goal.",+ "goalProcess.result.gate.revising": "You chose to retry. The Agent is revising the result; it will be accepted again when done.",+ "goalProcess.result.requirement": "Original requirement",+ "goalProcess.result.scale.cost": "Spent {{cost}}",+ "goalProcess.result.scale.criteria": "{{met}}/{{total}} criteria met",+ "goalProcess.result.scale.duration": "Took {{duration}}",+ "goalProcess.result.scale.tasks": "{{count}} tasks",+ "goalProcess.result.signOff.accept": "Accept delivery",+ "goalProcess.result.signOff.acceptConfirm.content": "The Goal closes as delivered; everything it produced stays available.",+ "goalProcess.result.signOff.acceptConfirm.title": "Accept this delivery?",+ "goalProcess.result.signOff.acceptConfirm.unmet": "{{count}} criteria are not met yet; accepting takes the result as it is.",+ "goalProcess.result.signOff.accepted": "You accepted this delivery.",+ "goalProcess.result.signOff.cancel": "Cancel",+ "goalProcess.result.signOff.changes.description": "Your feedback goes back to the Agent. It keeps working on this Goal and hands you a new result to accept.",+ "goalProcess.result.signOff.changes.placeholder": "What should change? Be specific — the Agent works from this.",+ "goalProcess.result.signOff.changes.required": "Write what should change before sending.",+ "goalProcess.result.signOff.changes.sent": "Sent back to the Agent",+ "goalProcess.result.signOff.changes.submit": "Send to Agent",+ "goalProcess.result.signOff.changes.title": "Request changes",+ "goalProcess.result.signOff.changesRequested": "Changes requested — your feedback is back with the Agent.",+ "goalProcess.result.signOff.error": "Could not save the sign-off. Try again.",+ "goalProcess.result.signOff.prompt": "Review the delivery, then accept it or ask for changes.",+ "goalProcess.result.signOff.requestChanges": "Request changes",+ "goalProcess.result.signOff.stopped": "The Goal stopped before it was done — this is what it left behind. Pick it up from here.",+ "goalProcess.result.signOff.unavailable": "There is no Goal-level acceptance to sign off.",+ "goalProcess.result.status.awaitingDecision": "Acceptance not passed · your call",+ "goalProcess.result.status.awaitingSignOff": "Achieved · awaiting your sign-off",+ "goalProcess.result.status.partial": "Not achieved · partial result",+ "goalProcess.result.status.revising": "Revising",+ "goalProcess.result.status.signedOff": "Signed off",+ "goalProcess.result.story.chapterMissing": "This chapter is no longer in the report — it may have been rewritten.",+ "goalProcess.result.story.detourKind.dead_end": "Dead end",+ "goalProcess.result.story.detourKind.retry": "Retried",+ "goalProcess.result.story.detourKind.superseded": "Superseded",+ "goalProcess.result.story.detourOpen": "Click to open this chapter’s local map",+ "goalProcess.result.story.detourTag": "Detour",+ "goalProcess.result.story.detours_one": "{{count}} detour",+ "goalProcess.result.story.detours_other": "{{count}} detours",+ "goalProcess.result.story.lesson": "Lesson",+ "goalProcess.result.story.mapHint": "This chapter’s main path and the detours off it. Detours and the lines into them are orange and dashed; the node a detour forked from is shown even when another chapter covers it. Click a node for its details.",+ "goalProcess.result.story.mapTitle": "Local map",+ "goalProcess.result.story.pending": "Organizing the exploration",+ "goalProcess.result.story.pendingHint": "The wrap-up agent is turning this run into chapters. They will replace this section on their own when ready.",+ "goalProcess.result.story.readReport": "Read full report",+ "goalProcess.result.story.reportEmpty": "This report has no full text.",+ "goalProcess.result.story.reportTitle": "Goal report",+ "goalProcess.result.story.unavailable": "The report is not available yet.",+ "goalProcess.result.trail.shownAbove": "Shown above",+ "goalProcess.result.trail.title": "Exploration",+ "goalProcess.result.trail.unattributed": "Other conclusions",+ "goalProcess.result.unfinished.abandoned": "Dropped tasks",+ "goalProcess.result.unfinished.continue": "Continue from this result",+ "goalProcess.result.unfinished.empty": "Nothing is left open.",+ "goalProcess.result.unfinished.nextSteps": "Suggested next steps",+ "goalProcess.result.unfinished.title": "Not done / next steps",+ "goalProcess.result.unfinished.unmetCriteria": "Unmet criteria","goalProcess.resume": "Resume","goalProcess.running.elapsed": "Running {{duration}}","goalProcess.stale.description": "No heartbeat for {{duration}}. The next advance marks this attempt lost and starts a fresh one — it does not count as a failure.",@@ -798,6 +903,8 @@"goalProcess.summary.retired": "Retired · {{count}} attempts","goalProcess.summary.running": "Running · attempt {{index}}","goalProcess.summary.waiting": "{{count}} attempts did not pass — needs your decision",+ "goalProcess.tabs.process": "Execution",+ "goalProcess.tabs.result": "Delivery","goalProcess.tag.done": "Done","goalProcess.tag.lost": "Lost","goalProcess.tag.needsDecision": "Needs your decision",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 04b384836aa..0638d0fab82 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -641,19 +641,20 @@"goalProcess.gate.reason.costBudgetExhausted": "目标的成本预算已用完","goalProcess.gate.reason.goalAcceptanceFailed": "目标整体验收未通过","goalProcess.gate.reason.recoveryFailed": "自动恢复未能启动下一次尝试",+ "goalProcess.gate.reason.runError": "任务运行出错({{code}})","goalProcess.gate.reason.verifyFailed": "任务 {{id}} 未通过验证","goalProcess.gate.reason.verifyInternalError": "验证未能运行(内部错误),这次交付没有被评估","goalProcess.gate.recommended": "推荐","goalProcess.gate.title.clarifyGoal": "开工前先确认目标","goalProcess.gate.title.goalAcceptance": "决定目标验收的去向","goalProcess.gate.title.recoverTask": "决定失败任务的去向",- "goalProcess.goalAcceptance.review": "去验收",- "goalProcess.goalAcceptance.state.accepted": "已验收",- "goalProcess.goalAcceptance.state.awaitingAcceptance": "待你验收",- "goalProcess.goalAcceptance.viewFull": "查看全文",+ "goalProcess.graph.bridgeHops_one": "中间隔 {{count}} 步未显示",+ "goalProcess.graph.bridgeHops_other": "中间隔 {{count}} 步未显示","goalProcess.graph.exitFullscreen": "退出全屏","goalProcess.graph.fullscreen": "全屏","goalProcess.graph.legend.hide": "在图中隐藏这类节点",+ "goalProcess.graph.legend.mainline": "主线",+ "goalProcess.graph.legend.mainlineHint": "收尾报告标记的、真正通向结果的路径","goalProcess.graph.legend.show": "在图中显示这类节点","goalProcess.graph.title": "探索图","goalProcess.graph.view.all": "全图",@@ -788,6 +789,110 @@"goalProcess.portal.title": "目标","goalProcess.requirementPlaceholder": "描述怎样才算达成这个目标…","goalProcess.requirementSaveFailed": "验收要求保存失败,下次编辑时会自动重试",+ "goalProcess.result.changes.comment": "你的修改意见",+ "goalProcess.result.changes.revising": "你提出了修改,Agent 正在返工,改完后会重新验收。",+ "goalProcess.result.continueSeed.deliverable": "已交付:{{title}}",+ "goalProcess.result.continueSeed.intro": "基于目标「{{title}}」的成果继续。",+ "goalProcess.result.continueSeed.open": "仍未完成:",+ "goalProcess.result.continueSeed.requirement": "原始要求:",+ "goalProcess.result.continueSeed.title": "继续:{{title}}",+ "goalProcess.result.criteria.document": "证据文档",+ "goalProcess.result.criteria.empty": "这个目标没有结构化的验收标准。",+ "goalProcess.result.criteria.evidenceCount": "{{count}} 项证据",+ "goalProcess.result.criteria.state.failed": "未达成",+ "goalProcess.result.criteria.state.passed": "达成",+ "goalProcess.result.criteria.state.unjudged": "未判定",+ "goalProcess.result.criteria.title": "验收标准",+ "goalProcess.result.criteria.unjudgedHint": "最新一轮验收没有判定这条标准。",+ "goalProcess.result.decisions.empty": "这个目标没有需要你拍板的决定。",+ "goalProcess.result.decisions.title": "你做过的决定",+ "goalProcess.result.deliverables.cited": "被验收证据引用:{{criteria}}",+ "goalProcess.result.deliverables.citedCount": "被 {{count}} 条验收标准引用",+ "goalProcess.result.deliverables.clearFilter": "清除搜索和筛选",+ "goalProcess.result.deliverables.empty.description": "这个目标没有留下可在这里打开的交付物。任务可能只把结果写在了本地路径或对话里,可在「执行过程」里查看各任务的输出。",+ "goalProcess.result.deliverables.empty.title": "没有持久化的交付物",+ "goalProcess.result.deliverables.filter.all": "全部",+ "goalProcess.result.deliverables.filter.document": "文档",+ "goalProcess.result.deliverables.filter.external": "链接",+ "goalProcess.result.deliverables.filter.file": "文件",+ "goalProcess.result.deliverables.noMatch": "没有匹配「{{query}}」的交付物",+ "goalProcess.result.deliverables.noMatchType": "没有这种类型的交付物",+ "goalProcess.result.deliverables.otherTasks": "其他任务",+ "goalProcess.result.deliverables.primary": "主交付物",+ "goalProcess.result.deliverables.producedBy": "由「{{title}}」产出",+ "goalProcess.result.deliverables.reader.cited": "验收已引用",+ "goalProcess.result.deliverables.reader.close": "关闭(Esc)",+ "goalProcess.result.deliverables.reader.download": "下载",+ "goalProcess.result.deliverables.reader.label": "交付物阅读模式",+ "goalProcess.result.deliverables.reader.next": "下一份(→)",+ "goalProcess.result.deliverables.reader.noPreview": "不支持在线预览",+ "goalProcess.result.deliverables.reader.noUrl": "这一项没有保存可下载的地址。",+ "goalProcess.result.deliverables.reader.openLink": "在新窗口打开",+ "goalProcess.result.deliverables.reader.prev": "上一份(←)",+ "goalProcess.result.deliverables.reader.supports": "支撑:{{criteria}}",+ "goalProcess.result.deliverables.reader.unavailable": "这份文档无法在这里打开。",+ "goalProcess.result.deliverables.reader.uncited": "未被引用",+ "goalProcess.result.deliverables.search": "搜索交付物",+ "goalProcess.result.deliverables.titleWithCount": "交付物 · {{count}}",+ "goalProcess.result.deliverables.uncited": "未被验收证据引用",+ "goalProcess.result.deliverables.viewAll": "逐一查看全部 {{count}} 项",+ "goalProcess.result.gate.error": "决定没有保存成功,请重试。",+ "goalProcess.result.gate.prompt": "先看下方哪些标准没有达成,再决定重试还是结束目标。",+ "goalProcess.result.gate.revising": "你选择了重试,Agent 正在修改,改完后会重新验收。",+ "goalProcess.result.requirement": "原始要求",+ "goalProcess.result.scale.cost": "花费 {{cost}}",+ "goalProcess.result.scale.criteria": "标准达成 {{met}}/{{total}}",+ "goalProcess.result.scale.duration": "用时 {{duration}}",+ "goalProcess.result.scale.tasks": "{{count}} 个任务",+ "goalProcess.result.signOff.accept": "接受交付",+ "goalProcess.result.signOff.acceptConfirm.content": "目标将以已交付结束,产出仍可随时查看。",+ "goalProcess.result.signOff.acceptConfirm.title": "接受这份交付?",+ "goalProcess.result.signOff.acceptConfirm.unmet": "还有 {{count}} 条标准未达成,接受即按现状收下。",+ "goalProcess.result.signOff.accepted": "你已接受这份交付。",+ "goalProcess.result.signOff.cancel": "取消",+ "goalProcess.result.signOff.changes.description": "你的意见会交回 Agent,由它继续修改这个目标,完成后重新交给你验收。",+ "goalProcess.result.signOff.changes.placeholder": "需要改什么?请写具体,Agent 会按这段意见修改。",+ "goalProcess.result.signOff.changes.required": "请先写下需要修改的地方。",+ "goalProcess.result.signOff.changes.sent": "已交回 Agent",+ "goalProcess.result.signOff.changes.submit": "交回 Agent",+ "goalProcess.result.signOff.changes.title": "提出修改",+ "goalProcess.result.signOff.changesRequested": "已提出修改,意见已交回 Agent 继续处理。",+ "goalProcess.result.signOff.error": "签收未能保存,请重试。",+ "goalProcess.result.signOff.prompt": "看完交付后,接受或提出修改。",+ "goalProcess.result.signOff.requestChanges": "提出修改",+ "goalProcess.result.signOff.stopped": "目标没有完成就停止了,这里是它留下的成果,可以从这里接着做。",+ "goalProcess.result.signOff.unavailable": "没有可签收的整体验收。",+ "goalProcess.result.status.awaitingDecision": "验收未通过 · 等你决定",+ "goalProcess.result.status.awaitingSignOff": "已达成 · 等你验收",+ "goalProcess.result.status.partial": "未达成 · 部分成果",+ "goalProcess.result.status.revising": "修改中",+ "goalProcess.result.status.signedOff": "已签收",+ "goalProcess.result.story.chapterMissing": "报告里已经没有这一章,可能被重新整理过。",+ "goalProcess.result.story.detourKind.dead_end": "死路",+ "goalProcess.result.story.detourKind.retry": "重试",+ "goalProcess.result.story.detourKind.superseded": "被取代",+ "goalProcess.result.story.detourOpen": "点击打开这一章的局部探索图",+ "goalProcess.result.story.detourTag": "弯路",+ "goalProcess.result.story.detours_one": "绕了 {{count}} 次弯路",+ "goalProcess.result.story.detours_other": "绕了 {{count}} 次弯路",+ "goalProcess.result.story.lesson": "收获",+ "goalProcess.result.story.mapHint": "这一章的主路径和走岔的节点:走岔的节点和通往它们的连线是橙色虚线;弯路分出来的上游节点即使属于别的章节也会显示。点击节点查看详情。",+ "goalProcess.result.story.mapTitle": "局部探索图",+ "goalProcess.result.story.pending": "正在整理探索过程",+ "goalProcess.result.story.pendingHint": "收尾 Agent 正在把这次目标的过程整理成章节,完成后会自动替换这里。",+ "goalProcess.result.story.readReport": "阅读完整报告",+ "goalProcess.result.story.reportEmpty": "这份报告没有正文。",+ "goalProcess.result.story.reportTitle": "目标报告",+ "goalProcess.result.story.unavailable": "报告暂时不可用。",+ "goalProcess.result.trail.shownAbove": "即上方正文",+ "goalProcess.result.trail.title": "探索过程",+ "goalProcess.result.trail.unattributed": "其他结论",+ "goalProcess.result.unfinished.abandoned": "放弃的任务",+ "goalProcess.result.unfinished.continue": "基于成果继续",+ "goalProcess.result.unfinished.empty": "没有遗留的事项。",+ "goalProcess.result.unfinished.nextSteps": "建议的下一步",+ "goalProcess.result.unfinished.title": "没有完成 / 下一步",+ "goalProcess.result.unfinished.unmetCriteria": "未达成的标准","goalProcess.resume": "继续","goalProcess.running.elapsed": "已运行 {{duration}}","goalProcess.stale.description": "已 {{duration}} 没有心跳。下一次推进会把这次尝试标为失联并重开一次,不计失败次数。",@@ -798,6 +903,8 @@"goalProcess.summary.retired": "已放弃 · {{count}} 次尝试","goalProcess.summary.running": "进行中 · 第 {{index}} 次尝试","goalProcess.summary.waiting": "{{count}} 次尝试都没通过,等你决定",+ "goalProcess.tabs.process": "执行过程",+ "goalProcess.tabs.result": "结果交付","goalProcess.tag.done": "完成","goalProcess.tag.lost": "失联","goalProcess.tag.needsDecision": "等你决定",diff --git a/packages/builtin-tool-goal/package.json b/packages/builtin-tool-goal/package.jsonindex 140ad30e465..a5248235762 100644--- a/packages/builtin-tool-goal/package.json+++ b/packages/builtin-tool-goal/package.json@@ -6,6 +6,7 @@".": "./src/index.ts","./client": "./src/client/index.ts","./client/executor": "./src/client/executor/index.ts",+ "./report": "./src/report.ts","./supervisor": "./src/supervisor.ts"},"main": "./src/index.ts",diff --git a/packages/builtin-tool-goal/src/index.ts b/packages/builtin-tool-goal/src/index.tsindex 35d2a379a88..07af3f92ba8 100644--- a/packages/builtin-tool-goal/src/index.ts+++ b/packages/builtin-tool-goal/src/index.ts@@ -7,6 +7,7 @@ export {} from './createGoalInput';export { isGoalPrompt, stripGoalCommand } from './goalPrompt';export { GoalIdentifier, GoalManifest } from './manifest';+export * from './report';export * from './supervisor';export { systemPrompt } from './systemRole';export * from './types';diff --git a/packages/builtin-tool-goal/src/report.ts b/packages/builtin-tool-goal/src/report.tsnew file mode 100644index 00000000000..3db708daba7--- /dev/null+++ b/packages/builtin-tool-goal/src/report.ts@@ -0,0 +1,120 @@+import type { BuiltinToolManifest, GoalReportMetadata } from '@lobechat/types';++export const GoalReportIdentifier = 'lobe-goal-report';+export const GoalReportApiName = {+ readGoalGraph: 'readGoalGraph',+ submitGoalReport: 'submitGoalReport',+} as const;++export interface ReadGoalGraphParams {+ goalId: string;+}++export interface SubmitGoalReportParams extends Omit<GoalReportMetadata, 'graphCursor'> {+ /** The full written report, in markdown, built from the same storyline. */+ content: string;+ goalId: string;+ /** The graph cursor from the skeleton; the newest Goal event when omitted. */+ graphCursor?: string;+}++const ids = { items: { type: 'string' }, type: 'array' };++export const GoalReportManifest: BuiltinToolManifest = {+ api: [+ {+ description:+ 'Read the Goal graph this report is about: every node with its kind, status and description, the edges between them, decision gates and the Work versions linked to each node. Use it to check what the skeleton in your instruction points at.',+ name: GoalReportApiName.readGoalGraph,+ parameters: {+ additionalProperties: false,+ properties: { goalId: { type: 'string' } },+ required: ['goalId'],+ type: 'object',+ },+ },+ {+ description:+ 'Submit the Goal wrap-up report. The storyline (headline, chapters with their main-path nodes, findings and Work versions, detours with reason and lesson, next steps) is stored as structured metadata and `content` as the full markdown report; each call appends a new report version. The mainline marks the nodes and edges of the path that led to the result; chapters tell exactly that path. Every id must belong to this Goal: chapter and mainline nodeIds must be resolved, mainline edges must join two mainline nodes, detour nodeIds must be rejected, retired or superseded (revises / contradicts). A rejected call lists every invalid reference — fix them and call again.',+ name: GoalReportApiName.submitGoalReport,+ parameters: {+ additionalProperties: false,+ properties: {+ chapters: {+ items: {+ additionalProperties: false,+ properties: {+ detours: {+ items: {+ additionalProperties: false,+ properties: {+ kind: { enum: ['dead_end', 'superseded', 'retry'], type: 'string' },+ lesson: { type: 'string' },+ nodeIds: ids,+ reason: { type: 'string' },+ title: { type: 'string' },+ },+ required: ['title', 'reason', 'lesson', 'nodeIds', 'kind'],+ type: 'object',+ },+ type: 'array',+ },+ findingIds: ids,+ narrative: { type: 'string' },+ nodeIds: ids,+ title: { type: 'string' },+ workVersionIds: ids,+ },+ required: ['title', 'narrative', 'nodeIds'],+ type: 'object',+ },+ type: 'array',+ },+ content: {+ description: 'The full written report in markdown, built from the metadata above.',+ type: 'string',+ },+ deliverableWorkId: { type: 'string' },+ goalId: { type: 'string' },+ graphCursor: {+ description: 'The graph cursor given in the instruction.',+ type: 'string',+ },+ headline: { description: 'One sentence: what the Goal delivered.', type: 'string' },+ mainline: {+ additionalProperties: false,+ description:+ 'The path that led to the result, highlighted on the exploration map. nodeIds: the resolved tasks on it (optionally the resolved root problem and the findings that carried the answer); edgeIds: edges of this Goal whose both ends are mainline nodes. Chapters must tell exactly these tasks.',+ properties: { edgeIds: ids, nodeIds: ids },+ required: ['nodeIds', 'edgeIds'],+ type: 'object',+ },+ nextSteps: {+ items: {+ additionalProperties: false,+ properties: {+ nodeIds: ids,+ reason: { type: 'string' },+ title: { type: 'string' },+ },+ required: ['title', 'reason'],+ type: 'object',+ },+ type: 'array',+ },+ },+ required: ['goalId', 'headline', 'chapters', 'mainline', 'nextSteps', 'content'],+ type: 'object',+ },+ },+ ],+ identifier: GoalReportIdentifier,+ meta: {+ avatar: '🎯',+ description: 'Submit the Goal wrap-up report storyline',+ title: 'Goal report',+ },+ systemRole:+ 'You are writing the wrap-up report of a finished Goal. Use readGoalGraph to inspect it. Only submitGoalReport records the report; a prose answer does not. Reference only ids that appear in the Goal graph.',+ type: 'builtin',+};diff --git a/packages/builtin-tools/src/identifiers.ts b/packages/builtin-tools/src/identifiers.tsindex d3971fa4a6f..ef08025895f 100644--- a/packages/builtin-tools/src/identifiers.ts+++ b/packages/builtin-tools/src/identifiers.ts@@ -15,7 +15,11 @@ import { BrowserManifest } from '@lobechat/builtin-tool-browser';import { CalculatorManifest } from '@lobechat/builtin-tool-calculator/manifest';import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';import { CredsManifest } from '@lobechat/builtin-tool-creds';-import { GoalManifest, GoalSupervisorManifest } from '@lobechat/builtin-tool-goal';+import {+ GoalManifest,+ GoalReportManifest,+ GoalSupervisorManifest,+} from '@lobechat/builtin-tool-goal';import { GroupAgentBuilderManifest } from '@lobechat/builtin-tool-group-agent-builder';import { GroupManagementManifest } from '@lobechat/builtin-tool-group-management';import { ImageGenerationManifest } from '@lobechat/builtin-tool-image-generation';@@ -49,6 +53,7 @@ export const builtinToolIdentifiers: string[] = [GroupManagementManifest.identifier,GoalManifest.identifier,GoalSupervisorManifest.identifier,+ GoalReportManifest.identifier,ImageGenerationManifest.identifier,VideoGenerationManifest.identifier,KnowledgeBaseManifest.identifier,diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.tsindex a1542caf619..ab3da6edd82 100644--- a/packages/builtin-tools/src/index.ts+++ b/packages/builtin-tools/src/index.ts@@ -22,7 +22,11 @@ import { BrowserManifest } from '@lobechat/builtin-tool-browser';import { CalculatorManifest } from '@lobechat/builtin-tool-calculator/manifest';import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';import { CredsManifest } from '@lobechat/builtin-tool-creds';-import { GoalManifest, GoalSupervisorManifest } from '@lobechat/builtin-tool-goal';+import {+ GoalManifest,+ GoalReportManifest,+ GoalSupervisorManifest,+} from '@lobechat/builtin-tool-goal';import { GroupAgentBuilderManifest } from '@lobechat/builtin-tool-group-agent-builder';import { GroupManagementManifest } from '@lobechat/builtin-tool-group-management';import { ImageGenerationManifest } from '@lobechat/builtin-tool-image-generation';@@ -536,6 +540,13 @@ const builtinToolRegistry: LobeBuiltinTool[] = [manifest: GoalSupervisorManifest,type: 'builtin',},+ {+ discoverable: false,+ hidden: true,+ identifier: GoalReportManifest.identifier,+ manifest: GoalReportManifest,+ type: 'builtin',+ },{discoverable: false,hidden: true,diff --git a/packages/const/src/goal.ts b/packages/const/src/goal.tsindex 169fae96ccd..0ae2f9d5c11 100644--- a/packages/const/src/goal.ts+++ b/packages/const/src/goal.ts@@ -110,3 +110,12 @@ export const VERIFICATION_UNJUDGEABLE_ERROR =*/export const ACCEPTANCE_REVIEW_ERRORED_ERROR ='Acceptance review could not run; the delivery passed its verifiers but was never reviewed.';++/**+ * Fixed title of the wrap-up Task the coordinator dispatches once the+ * Goal-level acceptance has ended (passed, failed / exhausted, or the Goal was+ * failed / canceled). It writes the Goal report storyline. Stored in English as+ * data; clients recognize it by this title. It never takes part in deciding the+ * Goal's status — the coordinator ignores it when choosing its next move.+ */+export const GOAL_REPORT_TASK_TITLE = 'Write the Goal report';diff --git a/packages/database/src/models/__tests__/goalGraph.test.ts b/packages/database/src/models/__tests__/goalGraph.test.tsindex e1044517c62..d9a5e403582 100644--- a/packages/database/src/models/__tests__/goalGraph.test.ts+++ b/packages/database/src/models/__tests__/goalGraph.test.ts@@ -4,7 +4,7 @@ import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';-import { agents, goalNodes, goals, users, workspaces } from '../../schemas';+import { agents, goalNodes, goals, topics, users, workspaces } from '../../schemas';import type { LobeChatDatabase } from '../../type';import { GoalModel } from '../goal';import { GoalGraphModel } from '../goalGraph';@@ -230,6 +230,39 @@ describe('GoalGraphModel', () => {expect(links?.[0].work).toMatchObject({ type: 'task', workId: work!.id });});+ it('hydrates what a file deliverable needs to be downloaded and cited', async () => {+ // The result page's reader shows a file's format and size on its download+ // card, and matches acceptance evidence to the file by its file-store id.+ await serverDB.insert(topics).values({ id: 'goal-graph-file-topic', userId });+ const goal = await goalModel.create({ subjectType: 'standalone', title: 'File goal' });+ const node = await graphModel.createNode(goal.id, { kind: 'task', title: 'Export sheet' });+ const work = await new WorkModel(serverDB, userId).registerFile({+ filePath: '/mnt/data/pricing.xlsx',+ metadata: {+ fileId: 'file-pricing',+ filePath: '/mnt/data/pricing.xlsx',+ fileSize: 4096,+ fileUrl: 'https://cdn.example.com/pricing.xlsx',+ mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',+ },+ title: 'pricing.xlsx',+ toolIdentifier: 'goal-test',+ toolName: 'writeFile',+ topicId: 'goal-graph-file-topic',+ userId,+ });+ await graphModel.attachWorkVersion(goal.id, node!.id, work.currentVersionId!, 'produced');++ const links = (await graphModel.getGraph(goal.id))?.workVersions;+ expect(links?.[0].work).toMatchObject({+ fileId: 'file-pricing',+ fileSize: 4096,+ fileUrl: 'https://cdn.example.com/pricing.xlsx',+ mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',+ type: 'file',+ });+ });+it('hydrates a linked Work only for a viewer allowed to see it', async () => {// A workspace goal is readable by every member (`goals` has no visibility// column), but a Work is owner-scoped. Hydrating the link without the Workdiff --git a/packages/database/src/models/goalGraph.ts b/packages/database/src/models/goalGraph.tsindex 069460c94ab..5742ebc1a3f 100644--- a/packages/database/src/models/goalGraph.ts+++ b/packages/database/src/models/goalGraph.ts@@ -219,6 +219,9 @@ export class GoalGraphModel {workId: row.workId,...(row.metadata?.agentDocumentId ? { agentDocumentId: row.metadata.agentDocumentId } : {}),...(row.metadata?.fileUrl ? { fileUrl: row.metadata.fileUrl } : {}),+ ...(row.metadata?.fileId ? { fileId: row.metadata.fileId } : {}),+ ...(typeof row.metadata?.fileSize === 'number' ? { fileSize: row.metadata.fileSize } : {}),+ ...(row.metadata?.mimeType ? { mimeType: row.metadata.mimeType } : {}),});}return display;diff --git a/packages/database/src/models/work/goalReport.ts b/packages/database/src/models/work/goalReport.tsnew file mode 100644index 00000000000..dd6b90fefd5--- /dev/null+++ b/packages/database/src/models/work/goalReport.ts@@ -0,0 +1,83 @@+import type { GoalReportMetadata, WorkItem } from '@lobechat/types';+import { and, desc, eq } from 'drizzle-orm';++import { works, workVersions } from '../../schemas/work';+import { type WorkContext, workOwnership } from './context';+import { truncateSummaryText, type WorkTypeAdapter, type WorkVersionEventParams } from './internal';+import { registerWorkVersion } from './writes';++export interface RegisterGoalReportWorkParams extends Omit<WorkVersionEventParams, 'changeType'> {+ /** The full written report, as markdown. */+ content: string;+ goalId: string;+ metadata: GoalReportMetadata;+ title: string;+}++/**+ * One `goal_report` Work per Goal (keyed by the goal id); every submission+ * appends a version. The structured storyline goes to the version's metadata,+ * the full report to its content.+ */+export const registerGoalReportWork = (+ ctx: WorkContext,+ params: RegisterGoalReportWorkParams,+): Promise<WorkItem> => {+ const { content, goalId, metadata, title, ...event } = params;+ return registerWorkVersion(+ ctx,+ {+ resourceId: goalId,+ resourceType: 'goal_report',+ type: 'goal_report',+ userId: ctx.userId,+ // Goals carry no visibility of their own: every member of the workspace+ // reads the goal, so its report follows the goal rather than the author.+ visibility: ctx.workspaceId ? 'public' : 'private',+ },+ { ...event, changeType: 'updated' },+ () => ({+ display: {+ content,+ description: truncateSummaryText(metadata.headline),+ identifier: null,+ status: null,+ title,+ url: null,+ },+ metadata: { goalReport: metadata },+ }),+ );+};++/** Newest report version of a Goal, or undefined when none was submitted. */+export const findLatestGoalReportVersion = async (ctx: WorkContext, goalId: string) => {+ const [row] = await ctx.db+ .select({+ content: workVersions.content,+ createdAt: workVersions.createdAt,+ metadata: workVersions.metadata,+ version: workVersions.version,+ workId: works.id,+ workVersionId: workVersions.id,+ })+ .from(workVersions)+ .innerJoin(works, and(eq(workVersions.workId, works.id), workOwnership(ctx)))+ .where(and(eq(works.resourceType, 'goal_report'), eq(works.resourceId, goalId)))+ .orderBy(desc(workVersions.version))+ .limit(1);+ return row;+};++/**+ * Goal reports are read through the goal graph, never the generic Work lists:+ * shipped clients have no descriptor for the type, and a report without its+ * goal has nothing to open. The adapter exists so the registry stays total.+ */+export const goalReportWorkAdapter: WorkTypeAdapter = {+ listConversationRows: async () => [],+ listVersionEvents: async () => [],+ mapCurrentRow: () => {+ throw new Error('goal_report Works are not listed');+ },+};diff --git a/packages/database/src/models/work/index.ts b/packages/database/src/models/work/index.tsindex 85459e3c1fe..7e834ea11ca 100644--- a/packages/database/src/models/work/index.ts+++ b/packages/database/src/models/work/index.ts@@ -20,6 +20,11 @@ import { registerDocumentWork } from './document';import { registerExternalWork } from './external';import { findFileWorkVersionByToolCall, registerFileWork } from './file';import { normalizeGithubShellToolResult, normalizeGithubToolResult } from './githubToolResult';+import {+ findLatestGoalReportVersion,+ registerGoalReportWork,+ type RegisterGoalReportWorkParams,+} from './goalReport';import { normalizeLinearToolResult } from './linearToolResult';import * as queries from './queries';import { registerTaskWork } from './task';@@ -76,6 +81,11 @@ export class WorkModel {registerFile = (params: RegisterFileWorkParams): Promise<WorkItem> =>registerFileWork(this.ctx, params);+ registerGoalReport = (params: RegisterGoalReportWorkParams): Promise<WorkItem> =>+ registerGoalReportWork(this.ctx, params);++ findLatestGoalReport = (goalId: string) => findLatestGoalReportVersion(this.ctx, goalId);+/*** Existence probe for a file Work's one-version-per-operation dedup key, so* the server consumer can skip a redundant export/upload on a retry. Seediff --git a/packages/database/src/models/work/registry.ts b/packages/database/src/models/work/registry.tsindex ef8b4162c8b..82e78310c95 100644--- a/packages/database/src/models/work/registry.ts+++ b/packages/database/src/models/work/registry.ts@@ -3,6 +3,7 @@ import type { WorkType } from '@lobechat/types';import { documentWorkAdapter } from './document';import { externalWorkAdapter } from './external';import { fileWorkAdapter } from './file';+import { goalReportWorkAdapter } from './goalReport';import type { WorkTypeAdapter } from './internal';import { taskWorkAdapter } from './task';@@ -16,13 +17,21 @@ export const WORK_TYPE_ADAPTERS = {document: documentWorkAdapter,external: externalWorkAdapter,file: fileWorkAdapter,+ goal_report: goalReportWorkAdapter,task: taskWorkAdapter,} satisfies Record<WorkType, WorkTypeAdapter>;-export const WORK_TYPES = Object.keys(WORK_TYPE_ADAPTERS) as WorkType[];+/** Work types read only through their owner (the goal graph), never through Work lists. */+const UNLISTED_WORK_TYPES = new Set<WorkType>(['goal_report']);++export const WORK_TYPES = (Object.keys(WORK_TYPE_ADAPTERS) as WorkType[]).filter(+ (type) => !UNLISTED_WORK_TYPES.has(type),+);/** Type-erased adapter list for uniform iteration in the aggregate queries. */-export const workTypeAdapters = Object.values(WORK_TYPE_ADAPTERS) as WorkTypeAdapter[];+export const workTypeAdapters = WORK_TYPES.map(+ (type) => WORK_TYPE_ADAPTERS[type],+) as WorkTypeAdapter[];/*** Work types gated behind an explicit client opt-in on the read path. `file` wasdiff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 3d0a1af2af5..c8177b4efef 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -2082,10 +2082,6 @@ export default {'goalProcess.acceptance.delivered': 'Awaiting your call','goalProcess.acceptance.errored': 'Verification error','goalProcess.acceptance.rejected': 'Rejected',- 'goalProcess.goalAcceptance.state.accepted': 'Accepted',- 'goalProcess.goalAcceptance.state.awaitingAcceptance': 'Awaiting your acceptance',- 'goalProcess.goalAcceptance.viewFull': 'Read full report',- 'goalProcess.goalAcceptance.review': 'Review delivery','goalProcess.tag.verifying': 'Verifying','goalProcess.tag.lost': 'Lost','goalProcess.tag.done': 'Done',@@ -2108,6 +2104,7 @@ export default {'goalProcess.gate.reason.attemptBudgetExhausted': 'The attempt budget for this work is used up','goalProcess.gate.reason.costBudgetExhausted': 'The goal cost budget is used up','goalProcess.gate.reason.recoveryFailed': 'Automatic recovery could not start the next attempt',+ 'goalProcess.gate.reason.runError': 'The run stopped with an error ({{code}})','goalProcess.gate.recommended': 'recommended','goalProcess.gate.noteLabel': 'Extra guidance','goalProcess.gate.notePlaceholder': 'Optional — goes into the next attempt instructions',@@ -2129,10 +2126,135 @@ export default {'goalProcess.graph.view.all': 'Full map','goalProcess.graph.fullscreen': 'Fullscreen','goalProcess.graph.exitFullscreen': 'Exit fullscreen',+ 'goalProcess.graph.bridgeHops_one': 'via {{count}} step not shown',+ 'goalProcess.graph.bridgeHops_other': 'via {{count}} steps not shown','goalProcess.linked.open': 'Open goal progress','goalProcess.portal.openPage': 'Open goal page','goalProcess.portal.title': 'Goal',+ 'goalProcess.result.changes.comment': 'Your feedback',+ 'goalProcess.result.changes.revising':+ 'You asked for changes. The Agent is reworking the delivery and will send it for acceptance again.',+ 'goalProcess.result.continueSeed.deliverable': 'Delivered: {{title}}',+ 'goalProcess.result.continueSeed.intro': 'Continue from the result of the Goal "{{title}}".',+ 'goalProcess.result.continueSeed.open': 'Still open:',+ 'goalProcess.result.continueSeed.requirement': 'Original requirement:',+ 'goalProcess.result.continueSeed.title': 'Continue: {{title}}',+ 'goalProcess.result.criteria.document': 'Evidence document',+ 'goalProcess.result.criteria.empty': 'This Goal has no structured acceptance criteria.',+ 'goalProcess.result.criteria.evidenceCount': '{{count}} evidence',+ 'goalProcess.result.criteria.state.failed': 'Not met',+ 'goalProcess.result.criteria.state.passed': 'Met',+ 'goalProcess.result.criteria.state.unjudged': 'Not judged',+ 'goalProcess.result.criteria.title': 'Acceptance criteria',+ 'goalProcess.result.criteria.unjudgedHint':+ 'The latest acceptance round did not judge this criterion.',+ 'goalProcess.result.deliverables.cited': 'Cited as acceptance evidence: {{criteria}}',+ 'goalProcess.result.deliverables.citedCount': 'Cited by {{count}} acceptance criteria',+ 'goalProcess.result.deliverables.clearFilter': 'Clear search and filter',+ 'goalProcess.result.deliverables.empty.description':+ 'This Goal left nothing you can open here. Its tasks may have written results only to a local path or into the conversation — check each task’s output on the Process tab.',+ 'goalProcess.result.deliverables.empty.title': 'No persisted deliverables',+ 'goalProcess.result.deliverables.filter.all': 'All',+ 'goalProcess.result.deliverables.filter.document': 'Documents',+ 'goalProcess.result.deliverables.filter.external': 'Links',+ 'goalProcess.result.deliverables.filter.file': 'Files',+ 'goalProcess.result.deliverables.noMatch': 'No deliverables match “{{query}}”',+ 'goalProcess.result.deliverables.noMatchType': 'No deliverables of this type',+ 'goalProcess.result.deliverables.otherTasks': 'Other tasks',+ 'goalProcess.result.deliverables.primary': 'Main deliverable',+ 'goalProcess.result.deliverables.producedBy': 'By “{{title}}”',+ 'goalProcess.result.deliverables.reader.cited': 'Cited by acceptance',+ 'goalProcess.result.deliverables.reader.close': 'Close (Esc)',+ 'goalProcess.result.deliverables.reader.download': 'Download',+ 'goalProcess.result.deliverables.reader.label': 'Deliverable reader',+ 'goalProcess.result.deliverables.reader.next': 'Next (→)',+ 'goalProcess.result.deliverables.reader.noPreview': 'No online preview',+ 'goalProcess.result.deliverables.reader.noUrl': 'No download address was saved for this item.',+ 'goalProcess.result.deliverables.reader.openLink': 'Open in new window',+ 'goalProcess.result.deliverables.reader.prev': 'Previous (←)',+ 'goalProcess.result.deliverables.reader.supports': 'Supports: {{criteria}}',+ 'goalProcess.result.deliverables.reader.uncited': 'Not cited',+ 'goalProcess.result.deliverables.reader.unavailable': 'This document cannot be opened here.',+ 'goalProcess.result.deliverables.search': 'Search deliverables',+ 'goalProcess.result.deliverables.titleWithCount': 'Deliverables · {{count}}',+ 'goalProcess.result.deliverables.uncited': 'Not cited by acceptance evidence',+ 'goalProcess.result.deliverables.viewAll': 'Review all {{count}}',+ 'goalProcess.result.decisions.empty': 'Nothing on this Goal needed your call.',+ 'goalProcess.result.decisions.title': 'Decisions you made',+ 'goalProcess.result.gate.error': 'Could not save the decision. Try again.',+ 'goalProcess.result.gate.prompt':+ 'Check which criteria were not met below, then retry or end the Goal.',+ 'goalProcess.result.gate.revising':+ 'You chose to retry. The Agent is revising the result; it will be accepted again when done.',+ 'goalProcess.result.requirement': 'Original requirement',+ 'goalProcess.result.scale.cost': 'Spent {{cost}}',+ 'goalProcess.result.scale.criteria': '{{met}}/{{total}} criteria met',+ 'goalProcess.result.scale.duration': 'Took {{duration}}',+ 'goalProcess.result.scale.tasks': '{{count}} tasks',+ 'goalProcess.result.signOff.accept': 'Accept delivery',+ 'goalProcess.result.signOff.acceptConfirm.content':+ 'The Goal closes as delivered; everything it produced stays available.',+ 'goalProcess.result.signOff.acceptConfirm.title': 'Accept this delivery?',+ 'goalProcess.result.signOff.acceptConfirm.unmet':+ '{{count}} criteria are not met yet; accepting takes the result as it is.',+ 'goalProcess.result.signOff.accepted': 'You accepted this delivery.',+ 'goalProcess.result.signOff.cancel': 'Cancel',+ 'goalProcess.result.signOff.changes.description':+ 'Your feedback goes back to the Agent. It keeps working on this Goal and hands you a new result to accept.',+ 'goalProcess.result.signOff.changes.placeholder':+ 'What should change? Be specific — the Agent works from this.',+ 'goalProcess.result.signOff.changes.required': 'Write what should change before sending.',+ 'goalProcess.result.signOff.changes.sent': 'Sent back to the Agent',+ 'goalProcess.result.signOff.changes.submit': 'Send to Agent',+ 'goalProcess.result.signOff.changes.title': 'Request changes',+ 'goalProcess.result.signOff.changesRequested':+ 'Changes requested — your feedback is back with the Agent.',+ 'goalProcess.result.signOff.error': 'Could not save the sign-off. Try again.',+ 'goalProcess.result.signOff.prompt': 'Review the delivery, then accept it or ask for changes.',+ 'goalProcess.result.signOff.requestChanges': 'Request changes',+ 'goalProcess.result.signOff.stopped':+ 'The Goal stopped before it was done — this is what it left behind. Pick it up from here.',+ 'goalProcess.result.signOff.unavailable': 'There is no Goal-level acceptance to sign off.',+ 'goalProcess.result.status.awaitingDecision': 'Acceptance not passed · your call',+ 'goalProcess.result.status.awaitingSignOff': 'Achieved · awaiting your sign-off',+ 'goalProcess.result.status.partial': 'Not achieved · partial result',+ 'goalProcess.result.status.revising': 'Revising',+ 'goalProcess.result.status.signedOff': 'Signed off',+ 'goalProcess.result.unfinished.abandoned': 'Dropped tasks',+ 'goalProcess.result.unfinished.continue': 'Continue from this result',+ 'goalProcess.result.unfinished.empty': 'Nothing is left open.',+ 'goalProcess.result.unfinished.nextSteps': 'Suggested next steps',+ 'goalProcess.result.unfinished.title': 'Not done / next steps',+ 'goalProcess.result.unfinished.unmetCriteria': 'Unmet criteria',+ 'goalProcess.result.story.chapterMissing':+ 'This chapter is no longer in the report — it may have been rewritten.',+ 'goalProcess.result.story.detourKind.dead_end': 'Dead end',+ 'goalProcess.result.story.detourKind.retry': 'Retried',+ 'goalProcess.result.story.detourKind.superseded': 'Superseded',+ 'goalProcess.result.story.detourOpen': 'Click to open this chapter’s local map',+ 'goalProcess.result.story.detourTag': 'Detour',+ 'goalProcess.result.story.detours_one': '{{count}} detour',+ 'goalProcess.result.story.detours_other': '{{count}} detours',+ 'goalProcess.result.story.lesson': 'Lesson',+ 'goalProcess.result.story.mapHint':+ 'This chapter’s main path and the detours off it. Detours and the lines into them are orange and dashed; the node a detour forked from is shown even when another chapter covers it. Click a node for its details.',+ 'goalProcess.result.story.mapTitle': 'Local map',+ 'goalProcess.result.story.pending': 'Organizing the exploration',+ 'goalProcess.result.story.pendingHint':+ 'The wrap-up agent is turning this run into chapters. They will replace this section on their own when ready.',+ 'goalProcess.result.story.readReport': 'Read full report',+ 'goalProcess.result.story.reportEmpty': 'This report has no full text.',+ 'goalProcess.result.story.reportTitle': 'Goal report',+ 'goalProcess.result.story.unavailable': 'The report is not available yet.',+ 'goalProcess.result.trail.shownAbove': 'Shown above',+ 'goalProcess.result.trail.title': 'Exploration',+ 'goalProcess.result.trail.unattributed': 'Other conclusions',+ 'goalProcess.tabs.process': 'Execution',+ 'goalProcess.tabs.result': 'Delivery','goalProcess.graph.legend.hide': 'Hide this kind on the map',+ 'goalProcess.graph.legend.mainline': 'Mainline',+ 'goalProcess.graph.legend.mainlineHint':+ 'The path the wrap-up report marked as the one that led to the result','goalProcess.graph.legend.show': 'Show this kind on the map','goalProcess.edge.investigates': 'investigates','goalProcess.edge.produces': 'produces',diff --git a/packages/types/src/goal.ts b/packages/types/src/goal.tsindex 57f840241c1..0f7e47cf361 100644--- a/packages/types/src/goal.ts+++ b/packages/types/src/goal.ts@@ -1,3 +1,4 @@+import type { GoalReportDispatch, GoalReportState } from './goalReport';import type { InitialGoalOverviewContext } from './stepContext';import type { AcceptanceStatus } from './verify';import type { WorkType } from './work';@@ -262,6 +263,18 @@ export interface GoalManagerState {turns: number;}+/**+ * The owner's 提出修改 on a delivered Goal: rejecting the Goal-level acceptance+ * reopens the Goal, and this is what the rework answers to.+ */+export interface GoalChangeRequest {+ /** The owner's feedback, which also reaches the next attempt's prompt. */+ comment?: string;+ requestedAt: string;+ /** The Goal-level acceptance Task sent back for rework. */+ taskId: string;+}+/*** How well the coordinator understands what the user wants, as of the last* decomposition. Derived from the concrete unknowns the planner reported rather@@ -280,6 +293,11 @@ export interface GoalUnderstanding {export interface GoalConfig {acceptance?: GoalAcceptancePolicy;+ /**+ * The owner's latest request for changes. Kept after the rework lands: the+ * result page reads it as 修改中 only while the Goal is open again.+ */+ changeRequest?: GoalChangeRequest;exploration?: GoalExplorationConfig;manager?: GoalManagerPolicy;@@ -298,6 +316,8 @@ export interface GoalConfig {/** Retained after release to distinguish lease-aware retries from legacy planners. */planningProtocol?: 'lease-v1';recovery?: GoalRecoveryPolicy;+ /** Coordinator-owned receipt of the latest wrap-up report dispatch. */+ report?: GoalReportDispatch;schedule?: GoalSchedulePolicy;supervision?: GoalSupervisionPolicy;/** Durable supervisor topic and bounded incident ledger. */@@ -315,7 +335,7 @@ export interface GoalConfig {/** Creation accepts planning options, never a runtime receipt. */export type GoalCreateConfig = Omit<GoalConfig,- 'managerState' | 'supervisorState' | 'understanding'+ 'managerState' | 'report' | 'supervisorState' | 'understanding'>;/**@@ -493,9 +513,15 @@ export interface GoalGraphWorkVersionDisplay {* route resolves {@link resourceId}.*/agentDocumentId?: string;+ /** File-store identity of a `file` Work — what acceptance evidence cites it by. */+ fileId?: string;+ /** Size in bytes of a `file` Work, when it was persisted. */+ fileSize?: number;/** Durable download target of a `file` Work, which keeps it out of `url`. */fileUrl?: string;identifier: string | null;+ /** MIME type of a `file` Work, when it was persisted. */+ mimeType?: string;/** Canonical resource identity — the document id an in-app link addresses. */resourceId: string | null;status: string | null;@@ -538,6 +564,12 @@ export interface GoalGraphSnapshot {events: GoalGraphEvent[];goal: GoalItem;nodes: GoalGraphNode[];+ /**+ * The wrap-up report: whether it is being written, done or failed, and the+ * newest submitted version. Absent until the Goal-level acceptance has ended+ * and a wrap-up was dispatched.+ */+ report?: GoalReportState;/*** Live heartbeat per active task node id: the `agent_operations.updatedAt`* of the run behind it. The runtime refreshes that lease every ~90s, whilediff --git a/packages/types/src/goalReport.ts b/packages/types/src/goalReport.tsnew file mode 100644index 00000000000..677da1552fb--- /dev/null+++ b/packages/types/src/goalReport.ts@@ -0,0 +1,117 @@+import { z } from 'zod';++/**+ * The structured storyline of a finished Goal, written by the wrap-up agent+ * once the Goal-level acceptance has ended.+ *+ * Only narrative and references live here. Whether a criterion passed and what+ * a person decided are NOT copied in: the page reads those from the verify+ * records and `goal_node_decisions`, so the report can never disagree with them.+ */+const idList = z.array(z.string().trim().min(1)).max(200);++export const goalReportDetourKinds = ['dead_end', 'superseded', 'retry'] as const;+export type GoalReportDetourKind = (typeof goalReportDetourKinds)[number];++export const GoalReportDetourSchema = z+ .object({+ kind: z.enum(goalReportDetourKinds),+ lesson: z.string().trim().min(1).max(2000),+ nodeIds: idList.min(1),+ reason: z.string().trim().min(1).max(2000),+ title: z.string().trim().min(1).max(200),+ })+ .strict();+export type GoalReportDetour = z.infer<typeof GoalReportDetourSchema>;++export const GoalReportChapterSchema = z+ .object({+ detours: z.array(GoalReportDetourSchema).max(20).default([]),+ findingIds: idList.default([]),+ narrative: z.string().trim().min(1).max(8000),+ nodeIds: idList.default([]),+ title: z.string().trim().min(1).max(200),+ workVersionIds: idList.default([]),+ })+ .strict();+export type GoalReportChapter = z.infer<typeof GoalReportChapterSchema>;++export const GoalReportNextStepSchema = z+ .object({+ nodeIds: idList.optional(),+ reason: z.string().trim().min(1).max(2000),+ title: z.string().trim().min(1).max(200),+ })+ .strict();+export type GoalReportNextStep = z.infer<typeof GoalReportNextStepSchema>;++/**+ * The path that actually carried the Goal to its result, marked by the wrap-up+ * agent: the resolved nodes on it and the edges between them. It lives on the+ * report version rather than on `goal_nodes`, so a rewritten storyline replaces+ * it whole and no stale mark outlives the story that drew it.+ */+export const GoalReportMainlineSchema = z+ .object({+ edgeIds: idList.default([]),+ nodeIds: idList.min(1),+ })+ .strict();+export type GoalReportMainline = z.infer<typeof GoalReportMainlineSchema>;++export const GoalReportMetadataSchema = z+ .object({+ chapters: z.array(GoalReportChapterSchema).min(1).max(30),+ deliverableWorkId: z.string().trim().min(1).optional(),+ /** The newest `goal_events.id` the report was written against. */+ graphCursor: z.string().trim().min(1),+ headline: z.string().trim().min(1).max(500),+ /** Optional only so versions written before it existed still parse; a new submission must carry it. */+ mainline: GoalReportMainlineSchema.optional(),+ nextSteps: z.array(GoalReportNextStepSchema).max(20).default([]),+ })+ .strict();+export type GoalReportMetadata = z.infer<typeof GoalReportMetadataSchema>;++/**+ * Where the Goal's wrap-up stands, as the page needs it:+ *+ * - `running` — a report run is in flight for the latest acceptance result.+ * - `completed` — a report version was submitted for the latest acceptance result.+ * - `failed` — the run ended, failed or timed out without a report. The Goal's+ * own status is unaffected; the page falls back to its derived view.+ */+export type GoalReportStatus = 'completed' | 'failed' | 'running';++/** Which acceptance result a wrap-up run was dispatched for. */+export type GoalReportTrigger = 'accepted' | 'acceptance_failed' | 'goal_canceled' | 'goal_failed';++/** Coordinator-owned receipt of the latest wrap-up dispatch, kept on `goal.config.report`. */+export interface GoalReportDispatch {+ /** Stable identity of the acceptance result; one dispatch per key. */+ acceptanceKey: string;+ dispatchedAt: string;+ /** Why the run could not be started, when it could not. */+ error?: string;+ nodeId: string;+ operationId?: string;+ taskId?: string;+ trigger: GoalReportTrigger;+}++export interface GoalReportVersion {+ content: string | null;+ createdAt: Date;+ metadata: GoalReportMetadata;+ version: number;+ workId: string;+ workVersionId: string;+}++/** The wrap-up state a goal graph read carries. */+export interface GoalReportState {+ dispatch: GoalReportDispatch;+ /** Newest report version, whichever acceptance result it was written for. */+ latest?: GoalReportVersion;+ status: GoalReportStatus;+}diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex 2091d4ce5d3..366cf40bb72 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -32,6 +32,7 @@ export * from './followUpAction';export * from './ftsSearch';export * from './generation';export * from './goal';+export * from './goalReport';export * from './heteroSessionImport';export * from './home';export * from './hotkey';diff --git a/packages/types/src/work.ts b/packages/types/src/work.tsindex b1a8a65bf18..7f19f530085 100644--- a/packages/types/src/work.ts+++ b/packages/types/src/work.ts@@ -1,11 +1,20 @@+import type { GoalReportMetadata } from './goalReport';import type { TaskStatus } from './task';-export type WorkType = 'document' | 'external' | 'file' | 'task';+/**+ * `goal_report` is the wrap-up report of a Goal: one Work per goal, a new+ * version per acceptance result. It is read through the goal graph, not the+ * generic Work lists.+ */+export type WorkType = 'document' | 'external' | 'file' | 'goal_report' | 'task';+/** Work types the generic Work lists return; a `goal_report` is read through its goal. */+export type ListedWorkType = Exclude<WorkType, 'goal_report'>;export type LinearWorkResourceType = 'linear_document' | 'linear_issue';export type GithubWorkResourceType = 'github_issue' | 'github_pull_request';/** Every resource type backed by the unified `external` Work type. */export type ExternalWorkResourceType = GithubWorkResourceType | LinearWorkResourceType;-export type WorkResourceType = 'document' | ExternalWorkResourceType | 'file' | 'task';+export type WorkResourceType =+ 'document' | ExternalWorkResourceType | 'file' | 'goal_report' | 'task';export type WorkVisibility = 'private' | 'public';/*** How a version changed the Work. Not derivable from `version === 1`: updating@@ -75,6 +84,8 @@ export interface WorkVersionMetadata {fileSize?: number;/** `file` Work — durable, fetchable URL of the persisted file. */fileUrl?: string;+ /** `goal_report` Work — the structured storyline; the full report is the version's `content`. */+ goalReport?: GoalReportMetadata;/** `file` Work — lines added by this version's edit (0 when the source tool reports none). */linesAdded?: number;/** `file` Work — lines deleted by this version's edit (0 when the source tool reports none). */diff --git a/src/features/AgentGoals/ProcessControl/DeliverableReader.tsx b/src/features/AgentGoals/ProcessControl/DeliverableReader.tsxnew file mode 100644index 00000000000..9e548294ce3--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/DeliverableReader.tsx@@ -0,0 +1,427 @@+'use client';++import { formatSize } from '@lobechat/utils/format';+import { Center, Flexbox, Icon, Markdown, useAppElement } from '@lobehub/ui';+import { ActionIcon, Button, Skeleton, Tag, Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { ArrowLeft, ArrowRight, Download, ExternalLink, X } from 'lucide-react';+import { useEffect, useRef } from 'react';+import { createPortal } from 'react-dom';+import { useTranslation } from 'react-i18next';++import { isSafeExternalUrl } from '@/features/Work/descriptors';+import { useActivityTime } from '@/hooks/useActivityTime';+import { useClientDataSWR } from '@/libs/swr';+import { portalKeys } from '@/libs/swr/keys';+import { documentService } from '@/services/document';++import type { DeliverableItem } from './deliverableList';+import {+ CitationMark,+ deliverableIconOf,+ deliverableTitleOf,+ fileFormatOf,+ isImageArtifact,+} from './deliverableVisuals';++/**+ * Full-screen reading mode for a Goal's deliverables: the list on the left,+ * the current one wide on the right, ←/→ to page through them in order and Esc+ * to return to the result page. Each kind shows what reading it means — a+ * document renders its text, a file offers its download, an external resource+ * offers to open it.+ */++const styles = createStaticStyles(({ css }) => ({+ body: css`+ overflow: auto;+ flex: 1;++ min-height: 0;+ padding-block: 32px 64px;+ padding-inline: 48px;+ `,+ card: css`+ width: 100%;+ max-width: 640px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadiusLG};++ background: ${cssVar.colorBgContainer};+ `,+ doc: css`+ width: 100%;+ max-width: 760px;+ margin-inline: auto;+ `,+ header: css`+ flex: none;+ padding-block: 12px;+ padding-inline: 24px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};+ `,+ image: css`+ max-width: 100%;+ max-height: 60vh;+ border-radius: ${cssVar.borderRadius};+ object-fit: contain;+ `,+ item: css`+ cursor: pointer;++ display: flex;+ gap: 10px;+ align-items: center;++ width: 100%;+ padding-block: 8px;+ padding-inline: 10px;+ border: none;+ border-radius: ${cssVar.borderRadius};++ text-align: start;++ background: none;++ &:hover {+ background: ${cssVar.colorFillTertiary};+ }++ &:focus-visible {+ outline: 2px solid ${cssVar.colorPrimary};+ outline-offset: -2px;+ }+ `,+ itemActive: css`+ background: ${cssVar.colorFillSecondary};++ &:hover {+ background: ${cssVar.colorFillSecondary};+ }+ `,+ overlay: css`+ position: fixed;+ z-index: 1000;+ inset: 0;++ display: flex;+ flex-direction: row;++ background: ${cssVar.colorBgLayout};++ &:focus {+ outline: none;+ }+ `,+ sidebar: css`+ overflow: auto;+ flex: none;++ width: 320px;+ padding: 12px;+ border-inline-end: 1px solid ${cssVar.colorBorderSecondary};+ `,+}));++const SidebarItem = ({+ active,+ item,+ onClick,+}: {+ active: boolean;+ item: DeliverableItem;+ onClick: () => void;+}) => {+ const { t } = useTranslation('chat');+ const { text, title } = useActivityTime(item.artifact.createdAt);++ return (+ <button+ aria-current={active || undefined}+ className={cx(styles.item, active && styles.itemActive)}+ type={'button'}+ onClick={onClick}+ >+ <Icon color={cssVar.colorTextSecondary} icon={deliverableIconOf(item.artifact)} size={16} />+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>+ <Text ellipsis fontSize={13} weight={500}>+ {deliverableTitleOf(item.artifact, t('goalProcess.deliverables.untitled'))}+ </Text>+ <Text ellipsis fontSize={12} title={title} type={'secondary'}>+ {[item.producerTitle, text].filter(Boolean).join(' · ')}+ </Text>+ </Flexbox>+ <CitationMark item={item} />+ </button>+ );+};++const DocumentBody = ({ documentId }: { documentId: string }) => {+ const { data: document, isLoading } = useClientDataSWR(+ portalKeys.documentHeader(documentId),+ () => documentService.getDocumentById(documentId),+ );++ if (isLoading)+ return (+ <Flexbox className={styles.doc} data-testid={'deliverable-reader-loading'} gap={12}>+ <Skeleton height={28} radius={4} width={'50%'} />+ <Skeleton height={14} radius={4} />+ <Skeleton height={14} radius={4} />+ <Skeleton height={14} radius={4} width={'70%'} />+ </Flexbox>+ );++ return (+ <div className={styles.doc} data-testid={'deliverable-reader-document'}>+ <Markdown variant={'chat'}>{document?.content ?? ''}</Markdown>+ </div>+ );+};++const Body = ({ item }: { item: DeliverableItem }) => {+ const { t } = useTranslation('chat');+ const { artifact } = item;+ const title = deliverableTitleOf(artifact, t('goalProcess.deliverables.untitled'));+ const url = isSafeExternalUrl(artifact.url) ? artifact.url : undefined;++ if (artifact.type === 'document')+ return artifact.resourceId ? (+ <DocumentBody documentId={artifact.resourceId} key={artifact.resourceId} />+ ) : (+ <Center>+ <Text type={'secondary'}>{t('goalProcess.result.deliverables.reader.unavailable')}</Text>+ </Center>+ );++ if (artifact.type === 'external')+ return (+ <Center>+ <Center+ className={styles.card}+ data-testid={'deliverable-reader-link'}+ gap={12}+ padding={32}+ >+ <Icon icon={deliverableIconOf(artifact)} size={28} />+ <Text fontSize={15} weight={600}>+ {title}+ </Text>+ {url ? (+ <>+ <Text ellipsis fontSize={13} style={{ maxWidth: 520 }} type={'secondary'}>+ {url}+ </Text>+ <Button href={url} icon={ExternalLink} rel={'noopener noreferrer'} target={'_blank'}>+ {t('goalProcess.result.deliverables.reader.openLink')}+ </Button>+ </>+ ) : (+ <Text fontSize={13} type={'secondary'}>+ {t('goalProcess.result.deliverables.reader.noUrl')}+ </Text>+ )}+ </Center>+ </Center>+ );++ const meta = [+ fileFormatOf(artifact),+ artifact.fileSize !== undefined && formatSize(artifact.fileSize),+ !isImageArtifact(artifact) && t('goalProcess.result.deliverables.reader.noPreview'),+ ].filter(Boolean);++ return (+ <Center>+ <Center className={styles.card} data-testid={'deliverable-reader-file'} gap={12} padding={32}>+ {url && isImageArtifact(artifact) ? (+ <img alt={title} className={styles.image} src={url} />+ ) : (+ <Icon icon={deliverableIconOf(artifact)} size={28} />+ )}+ <Text fontSize={15} weight={600}>+ {title}+ </Text>+ {meta.length > 0 && (+ <Text fontSize={13} type={'secondary'}>+ {meta.join(' · ')}+ </Text>+ )}+ {url ? (+ <Button download href={url} icon={Download} rel={'noopener noreferrer'} target={'_blank'}>+ {t('goalProcess.result.deliverables.reader.download')}+ </Button>+ ) : (+ <Text fontSize={13} type={'secondary'}>+ {t('goalProcess.result.deliverables.reader.noUrl')}+ </Text>+ )}+ </Center>+ </Center>+ );+};++const Header = ({+ index,+ item,+ onIndexChange,+ total,+}: {+ index: number;+ item: DeliverableItem;+ onIndexChange: (index: number) => void;+ total: number;+}) => {+ const { t } = useTranslation('chat');+ const { text, title } = useActivityTime(item.artifact.createdAt);+ const cited = item.citedBy.length > 0;++ return (+ <Flexbox horizontal align={'center'} className={styles.header} gap={16}>+ <Flexbox flex={1} gap={4} style={{ minWidth: 0 }}>+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>+ <Text ellipsis data-testid={'deliverable-reader-title'} fontSize={15} weight={600}>+ {deliverableTitleOf(item.artifact, t('goalProcess.deliverables.untitled'))}+ </Text>+ {item.primary && <Tag color={'blue'}>{t('goalProcess.result.deliverables.primary')}</Tag>}+ <Tag color={cited ? 'success' : undefined}>+ {cited+ ? t('goalProcess.result.deliverables.reader.cited')+ : t('goalProcess.result.deliverables.reader.uncited')}+ </Tag>+ </Flexbox>+ <Text ellipsis fontSize={12} title={title} type={'secondary'}>+ {[+ item.producerTitle &&+ t('goalProcess.result.deliverables.producedBy', { title: item.producerTitle }),+ text,+ cited &&+ t('goalProcess.result.deliverables.reader.supports', {+ criteria: item.citedBy.map((criterion) => criterion.title).join(';'),+ }),+ ]+ .filter(Boolean)+ .join(' · ')}+ </Text>+ </Flexbox>+ <Text data-testid={'deliverable-reader-position'} fontSize={13} type={'secondary'}>+ {`${index + 1} / ${total}`}+ </Text>+ <ActionIcon+ disabled={index === 0}+ icon={ArrowLeft}+ title={t('goalProcess.result.deliverables.reader.prev')}+ onClick={() => onIndexChange(index - 1)}+ />+ <ActionIcon+ disabled={index === total - 1}+ icon={ArrowRight}+ title={t('goalProcess.result.deliverables.reader.next')}+ onClick={() => onIndexChange(index + 1)}+ />+ </Flexbox>+ );+};++interface DeliverableReaderProps {+ index: number;+ items: DeliverableItem[];+ onClose: () => void;+ onIndexChange: (index: number) => void;+}++const DeliverableReader = ({ index, items, onClose, onIndexChange }: DeliverableReaderProps) => {+ const { t } = useTranslation('chat');+ // Portal into the themed app root: the theme's CSS variables live there, and+ // a node mounted straight on <body> renders without them.+ const appElement = useAppElement();+ const overlayRef = useRef<HTMLDivElement>(null);+ const sidebarRef = useRef<HTMLDivElement>(null);+ const current = items[Math.min(index, items.length - 1)];++ // Keep the current item in view as ←/→ walk past the fold.+ useEffect(() => {+ sidebarRef.current+ ?.querySelector('[aria-current="true"]')+ ?.scrollIntoView({ block: 'nearest' });+ }, [index]);++ // Take focus on open so the keys reach the reader, and hand it back to+ // whatever opened it on close.+ useEffect(() => {+ const opener = document.activeElement as HTMLElement | null;+ overlayRef.current?.focus();+ return () => opener?.focus?.();+ }, []);++ useEffect(() => {+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return;+ const target = event.target as HTMLElement | null;+ if (target?.closest('input, textarea, [contenteditable="true"]')) return;+ if (event.key === 'Escape') {+ event.preventDefault();+ onClose();+ } else if (event.key === 'ArrowRight' && index < items.length - 1) {+ event.preventDefault();+ onIndexChange(index + 1);+ } else if (event.key === 'ArrowLeft' && index > 0) {+ event.preventDefault();+ onIndexChange(index - 1);+ }+ };+ window.addEventListener('keydown', onKeyDown);+ return () => window.removeEventListener('keydown', onKeyDown);+ }, [index, items.length, onClose, onIndexChange]);++ if (!current) return null;++ return createPortal(+ <div+ aria-label={t('goalProcess.result.deliverables.reader.label')}+ aria-modal={true}+ className={styles.overlay}+ data-testid={'deliverable-reader'}+ ref={overlayRef}+ role={'dialog'}+ tabIndex={-1}+ >+ <Flexbox className={styles.sidebar} gap={4} ref={sidebarRef}>+ <Flexbox+ horizontal+ align={'center'}+ justify={'space-between'}+ paddingBlock={4}+ paddingInline={10}+ >+ <Text weight={600}>+ {t('goalProcess.result.deliverables.titleWithCount', { count: items.length })}+ </Text>+ <ActionIcon+ icon={X}+ size={'small'}+ title={t('goalProcess.result.deliverables.reader.close')}+ onClick={onClose}+ />+ </Flexbox>+ {items.map((item, itemIndex) => (+ <SidebarItem+ active={itemIndex === index}+ item={item}+ key={item.artifact.workVersionId}+ onClick={() => onIndexChange(itemIndex)}+ />+ ))}+ </Flexbox>+ <Flexbox flex={1} style={{ minWidth: 0 }}>+ <Header index={index} item={current} total={items.length} onIndexChange={onIndexChange} />+ <div className={styles.body}>+ <Body item={current} key={current.artifact.workVersionId} />+ </div>+ </Flexbox>+ </div>,+ appElement ?? document.body,+ );+};++export default DeliverableReader;diff --git a/src/features/AgentGoals/ProcessControl/Frontier.tsx b/src/features/AgentGoals/ProcessControl/Frontier.tsxindex c369cb4a9f4..68ede89b9a8 100644--- a/src/features/AgentGoals/ProcessControl/Frontier.tsx+++ b/src/features/AgentGoals/ProcessControl/Frontier.tsx@@ -21,10 +21,8 @@ import {coordinatorGateReason,coordinatorNodeTitleKey,coordinatorReasonCopy,- isGoalAcceptanceTask,viewGateKind,} from './coordinatorCopy';-import { GoalFinalAcceptance } from './GoalAcceptanceCard';import type { FrontierItem, GoalGraphView, GoalNodeView } from './goalGraphViewModel';import { useElapsed } from './useElapsed';@@ -128,7 +126,7 @@ interface FrontierProps {}/** Server option ids are stable; their labels are English strings from the coordinator. */-const useOptionLabel = () => {+export const useGateOptionLabel = () => {const { t } = useTranslation('chat');return (option: GoalDecisionOption) => {switch (option.id) {@@ -344,7 +342,7 @@ const FrontierRow = memo<{subject?: GoalNodeView;}>(({ actions, canEdit, item, numbers, onSelect, subject }) => {const { t } = useTranslation('chat');- const optionLabel = useOptionLabel();+ const optionLabel = useGateOptionLabel();const [note, setNote] = useState('');const { view } = item;const { node } = view;@@ -510,12 +508,6 @@ const Frontier = memo<FrontierProps>(({ actions, canEdit, graph, onSelect, planngraph.nodes.filter((view) => view.seq !== undefined).map((view) => [view.node.id, view.seq!]),);const achieved = graph.goal.status === 'achieved';- // Once the Goal's final acceptance finished, its acceptance document is what- // the owner reads next, so it takes the task list's place (the component- // keeps the list until the latest round is confirmed passed).- const finalAcceptanceView = graph.nodes.find(- (view) => isGoalAcceptanceTask(view) && view.node.status === 'resolved' && !!view.acceptance,- );// A goal's clarification round is asked as one form, not one gate row per// question. Someone who cannot answer still sees the questions as rows.const clarifyItems = canEdit@@ -550,92 +542,88 @@ const Frontier = memo<FrontierProps>(({ actions, canEdit, graph, onSelect, plann{canEdit && <AddTaskButton onAdd={actions.addTask} />}</Flexbox>- <GoalFinalAcceptance graph={graph} view={finalAcceptanceView}>- <div className={styles.list}>- <Block gap={0} padding={2} variant={'borderless'}>- {graph.frontier.length === 0 &&- (planning ? (- <Flexbox horizontal align={'center'} gap={10} padding={12}>- <RunningGlyph size={16} />- <Flexbox gap={2}>- <Text weight={500}>{t('goalProcess.planning.title')}</Text>- <Text fontSize={12} type={'secondary'}>- {t('goalProcess.planning.description')}- </Text>- </Flexbox>- </Flexbox>- ) : (- <Flexbox gap={2} padding={12}>- <Text weight={500}>- {achieved- ? t('goalProcess.frontier.achievedTitle')- : t('goalProcess.frontier.emptyTitle')}- </Text>- <Text fontSize={12} type={'secondary'}>- {achieved- ? t('goalProcess.frontier.achievedDescription')- : t('goalProcess.frontier.emptyDescription')}- </Text>- </Flexbox>- ))}- {pendingClarifications.length > 0 && (- // Filled so the one thing blocking the goal stands apart from the- // task rows around it.- <Block gap={12} padding={12} variant={'filled'}>+ <div className={styles.list}>+ <Block gap={0} padding={2} variant={'borderless'}>+ {graph.frontier.length === 0 &&+ (planning ? (+ <Flexbox horizontal align={'center'} gap={10} padding={12}>+ <RunningGlyph size={16} /><Flexbox gap={2}>- <Text weight={500}>{t('goalProcess.clarify.title')}</Text>+ <Text weight={500}>{t('goalProcess.planning.title')}</Text><Text fontSize={12} type={'secondary'}>- {t('goalProcess.clarify.description')}+ {t('goalProcess.planning.description')}</Text></Flexbox>- <GoalClarification goalId={graph.goal.id} pending={pendingClarifications} />- </Block>- )}- {rows.map((item, index) => (- <Fragment key={item.key}>- {(index > 0 || pendingClarifications.length > 0) && (- <Divider dashed style={{ margin: 0 }} />- )}- <FrontierRow- actions={actions}- canEdit={canEdit}- item={item}- numbers={numbers}- subject={- item.view.gateSubjectId ? graph.byId[item.view.gateSubjectId] : undefined- }- onSelect={onSelect}- />- </Fragment>+ </Flexbox>+ ) : (+ <Flexbox gap={2} padding={12}>+ <Text weight={500}>+ {achieved+ ? t('goalProcess.frontier.achievedTitle')+ : t('goalProcess.frontier.emptyTitle')}+ </Text>+ <Text fontSize={12} type={'secondary'}>+ {achieved+ ? t('goalProcess.frontier.achievedDescription')+ : t('goalProcess.frontier.emptyDescription')}+ </Text>+ </Flexbox>))}- </Block>- {graph.blocked.length > 0 && (- <>- <Divider dashed style={{ margin: 0 }} />- <div className={styles.blockedHead} onClick={() => setShowBlocked(!showBlocked)}>- <Icon icon={showBlocked ? ChevronDown : ChevronRight} size={12} />- <span>{t('goalProcess.frontier.blocked', { count: graph.blocked.length })}</span>- </div>- {showBlocked && (- <Block gap={0} padding={2} variant={'borderless'}>- {graph.blocked.map((view, index) => (- <Fragment key={view.node.id}>- {index > 0 && <Divider dashed style={{ margin: 0 }} />}- <FrontierRow- actions={actions}- canEdit={canEdit}- item={{ key: view.node.id, kind: 'ready', rank: 3, view }}- numbers={numbers}- onSelect={onSelect}- />- </Fragment>- ))}- </Block>- )}- </>+ {pendingClarifications.length > 0 && (+ // Filled so the one thing blocking the goal stands apart from the+ // task rows around it.+ <Block gap={12} padding={12} variant={'filled'}>+ <Flexbox gap={2}>+ <Text weight={500}>{t('goalProcess.clarify.title')}</Text>+ <Text fontSize={12} type={'secondary'}>+ {t('goalProcess.clarify.description')}+ </Text>+ </Flexbox>+ <GoalClarification goalId={graph.goal.id} pending={pendingClarifications} />+ </Block>)}- </div>- </GoalFinalAcceptance>+ {rows.map((item, index) => (+ <Fragment key={item.key}>+ {(index > 0 || pendingClarifications.length > 0) && (+ <Divider dashed style={{ margin: 0 }} />+ )}+ <FrontierRow+ actions={actions}+ canEdit={canEdit}+ item={item}+ numbers={numbers}+ subject={item.view.gateSubjectId ? graph.byId[item.view.gateSubjectId] : undefined}+ onSelect={onSelect}+ />+ </Fragment>+ ))}+ </Block>+ {graph.blocked.length > 0 && (+ <>+ <Divider dashed style={{ margin: 0 }} />+ <div className={styles.blockedHead} onClick={() => setShowBlocked(!showBlocked)}>+ <Icon icon={showBlocked ? ChevronDown : ChevronRight} size={12} />+ <span>{t('goalProcess.frontier.blocked', { count: graph.blocked.length })}</span>+ </div>+ {showBlocked && (+ <Block gap={0} padding={2} variant={'borderless'}>+ {graph.blocked.map((view, index) => (+ <Fragment key={view.node.id}>+ {index > 0 && <Divider dashed style={{ margin: 0 }} />}+ <FrontierRow+ actions={actions}+ canEdit={canEdit}+ item={{ key: view.node.id, kind: 'ready', rank: 3, view }}+ numbers={numbers}+ onSelect={onSelect}+ />+ </Fragment>+ ))}+ </Block>+ )}+ </>+ )}+ </div></Flexbox>);});diff --git a/src/features/AgentGoals/ProcessControl/GoalAcceptanceCard.tsx b/src/features/AgentGoals/ProcessControl/GoalAcceptanceCard.tsxdeleted file mode 100644index 72240766935..00000000000--- a/src/features/AgentGoals/ProcessControl/GoalAcceptanceCard.tsx+++ /dev/null@@ -1,181 +0,0 @@-'use client';--import { Flexbox, Icon, Markdown } from '@lobehub/ui';-import { Button, Tag, Text } from '@lobehub/ui/base-ui';-import { createStaticStyles, cssVar } from 'antd-style';-import { FileText } from 'lucide-react';-import type { MouseEvent, ReactNode } from 'react';-import { useTranslation } from 'react-i18next';--import { useAcceptanceBundle } from '@/features/Acceptance/hooks';-import { useClientDataSWR } from '@/libs/swr';-import { portalKeys } from '@/libs/swr/keys';-import { documentService } from '@/services/document';-import { useChatStore } from '@/store/chat';--import {- goalAcceptanceState,- isFinalAcceptanceReady,- latestRunStatus,- pickFinalDeliverable,-} from './goalAcceptanceReport';-import type { GoalGraphView, GoalNodeView } from './goalGraphViewModel';--/**- * The Goal's final deliverable, in place of the task list.- *- * Once every task ran through and the final acceptance passed, nothing is left- * to advance: what the owner wants to read is what the Goal produced. So the- * list gives way to that product — the document the work wrote, its title and a- * preview of its content — and the full document opens in the side Portal, like- * every other drill-down here. Neither the acceptance report nor the synthesized- * finding stands in for it: both are about the product, not the product.- *- * Until that point (see `isFinalAcceptanceReady`), or when the Goal produced no- * document, the list stays exactly as it was.- */--const styles = createStaticStyles(({ css }) => ({- document: css`- cursor: pointer;-- display: flex;- flex-direction: column;- gap: 10px;-- width: 100%;- padding-block: 16px;- padding-inline: 18px;- border: 1px solid ${cssVar.colorBorderSecondary};- border-radius: ${cssVar.borderRadius};-- text-align: start;-- background: ${cssVar.colorBgContainer};-- &:hover {- border-color: ${cssVar.colorBorder};- }-- &:focus-visible {- outline: 2px solid ${cssVar.colorPrimary};- outline-offset: -2px;- }- `,- preview: css`- overflow: hidden;- max-height: 320px;-- mask-image: linear-gradient(to bottom, #000 75%, transparent);- `,-}));--interface GoalFinalAcceptanceProps {- /** The task list, shown until the Goal's final deliverable can replace it. */- children: ReactNode;- graph: GoalGraphView;- /** The Goal's resolved final acceptance task, when there is one. */- view?: GoalNodeView;-}--// The tag and the button are their own actions, not "open the document".-const stop = (event: MouseEvent) => event.stopPropagation();--const FinalDeliverable = ({- acceptance,- children,- graph,- view,-}: GoalFinalAcceptanceProps & {- acceptance: NonNullable<GoalNodeView['acceptance']>;- view: GoalNodeView;-}) => {- const { t } = useTranslation('chat');- const openAcceptance = useChatStore((s) => s.openAcceptance);- const openDocument = useChatStore((s) => s.openDocument);-- const { data } = useAcceptanceBundle(acceptance.id);- const state = goalAcceptanceState(acceptance.status, latestRunStatus(data?.rounds ?? []));- const ready = !!data && isFinalAcceptanceReady(view.node.status, state);- const deliverable = ready ? pickFinalDeliverable(graph.artifacts, view.node.id) : undefined;-- // The graph carries only the document id; its content is read for the preview.- const { data: document } = useClientDataSWR(- deliverable ? portalKeys.documentHeader(deliverable.documentId) : null,- () => documentService.getDocumentById(deliverable!.documentId),- );-- if (!deliverable) return <>{children}</>;-- const open = () => openDocument(deliverable.documentId, deliverable.agentDocumentId);- const producer = graph.byId[deliverable.nodeId]?.node.title;-- return (- <Flexbox gap={10}>- <div- className={styles.document}- role={'button'}- tabIndex={0}- onClick={open}- onKeyDown={(event) => {- if (event.key !== 'Enter' && event.key !== ' ') return;- event.preventDefault();- open();- }}- >- <Flexbox horizontal align={'center'} gap={8}>- <Icon color={cssVar.colorTextSecondary} icon={FileText} size={16} />- <Text ellipsis fontSize={15} style={{ flex: 1, minWidth: 0 }} weight={600}>- {document?.title || deliverable.title || t('goalProcess.deliverables.untitled')}- </Text>- <Tag- color={state === 'accepted' ? 'success' : 'warning'}- size={'small'}- style={{ cursor: 'pointer' }}- onClick={(event) => {- stop(event);- openAcceptance(acceptance.id);- }}- >- {t(- state === 'accepted'- ? 'goalProcess.goalAcceptance.state.accepted'- : 'goalProcess.goalAcceptance.state.awaitingAcceptance',- )}- </Tag>- </Flexbox>- {!!producer && (- <Text fontSize={12} type={'secondary'}>- {t('goalProcess.deliverables.from', { title: producer })}- </Text>- )}- {!!document?.content && (- <div className={styles.preview}>- <Markdown fontSize={13} variant={'chat'}>- {document.content}- </Markdown>- </div>- )}- <Text fontSize={12} type={'secondary'}>- {t('goalProcess.goalAcceptance.viewFull')}- </Text>- </div>- {state === 'awaitingAcceptance' && (- <Flexbox horizontal>- <Button size={'small'} type={'primary'} onClick={() => openAcceptance(acceptance.id)}>- {t('goalProcess.goalAcceptance.review')}- </Button>- </Flexbox>- )}- </Flexbox>- );-};--export const GoalFinalAcceptance = ({ children, graph, view }: GoalFinalAcceptanceProps) => {- if (!view?.acceptance) return <>{children}</>;- return (- <FinalDeliverable acceptance={view.acceptance} graph={graph} view={view}>- {children}- </FinalDeliverable>- );-};diff --git a/src/features/AgentGoals/ProcessControl/GoalCriteriaResults.tsx b/src/features/AgentGoals/ProcessControl/GoalCriteriaResults.tsxnew file mode 100644index 00000000000..b70673e4f61--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/GoalCriteriaResults.tsx@@ -0,0 +1,303 @@+'use client';++import { Flexbox, Icon, Image, Markdown } from '@lobehub/ui';+import { Skeleton, Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import {+ ChevronRight,+ CircleCheck,+ CircleDashed,+ CircleX,+ FileText,+ Paperclip,+} from 'lucide-react';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncError from '@/components/AsyncError';+import { useChatStore } from '@/store/chat';++import { SectionTitle } from './GoalResultFollowUps';+import type { CriterionOutcome, CriterionOutcomeState, EvidenceLike } from './goalResultState';++/**+ * 验收标准 × 结果 — each criterion the Goal was accepted against, next to what+ * the latest acceptance round found: met or not, one line of what the evidence+ * showed, and why when it was not. A row opens into its evidence — screenshots,+ * written evidence, the documents it cites — in place, without framing the+ * content in another card.+ */++const styles = createStaticStyles(({ css }) => ({+ arrow: css`+ flex: none;+ color: ${cssVar.colorTextQuaternary};+ transition: transform 0.2s;+ `,+ arrowOpen: css`+ transform: rotate(90deg);+ `,+ evidence: css`+ padding-block: 0 12px;+ padding-inline: 28px 0;+ `,+ item: css`+ &:not(:last-child) {+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};+ }+ `,+ reason: css`+ color: ${cssVar.colorError};+ `,+ row: css`+ width: 100%;+ padding-block: 10px;+ padding-inline: 0;+ border: none;++ text-align: start;++ background: none;+ `,+ rowOpenable: css`+ cursor: pointer;++ &:hover {+ background: ${cssVar.colorFillQuaternary};+ }++ &:focus-visible {+ outline: 2px solid ${cssVar.colorPrimary};+ outline-offset: -2px;+ }+ `,+ docLink: css`+ cursor: pointer;++ width: fit-content;+ padding: 0;+ border: none;++ color: ${cssVar.colorPrimary};++ background: none;++ &:hover {+ text-decoration: underline;+ }+ `,+}));++const STATE_ICON: Record<CriterionOutcomeState, typeof CircleCheck> = {+ failed: CircleX,+ passed: CircleCheck,+ unjudged: CircleDashed,+};++const STATE_COLOR: Record<CriterionOutcomeState, string> = {+ failed: cssVar.colorError,+ passed: cssVar.colorSuccess,+ unjudged: cssVar.colorTextQuaternary,+};++const IMAGE_TYPES = new Set(['screenshot', 'gif']);++const EvidenceItem = ({ item }: { item: EvidenceLike }) => {+ const { t } = useTranslation('chat');+ const openDocument = useChatStore((s) => s.openDocument);+ const caption = item.description || item.fileName;++ if (IMAGE_TYPES.has(item.type) && item.fileUrl)+ return (+ <Flexbox gap={4}>+ <Image+ preview+ alt={caption ?? item.type}+ loading={'lazy'}+ src={item.fileUrl}+ style={{ maxHeight: 360, objectFit: 'contain', width: '100%' }}+ variant={'borderless'}+ />+ {caption && (+ <Text fontSize={12} type={'secondary'}>+ {caption}+ </Text>+ )}+ </Flexbox>+ );++ if (item.type === 'video' && item.fileUrl)+ return <video controls src={item.fileUrl} style={{ display: 'block', width: '100%' }} />;++ if (item.content)+ return (+ <Flexbox gap={4}>+ {caption && (+ <Text fontSize={12} type={'secondary'}>+ {caption}+ </Text>+ )}+ <Markdown fontSize={13} variant={'chat'}>+ {item.content}+ </Markdown>+ </Flexbox>+ );++ if (item.documentId)+ return (+ <Flexbox horizontal align={'center'} gap={6}>+ <Icon color={cssVar.colorTextTertiary} icon={FileText} size={14} />+ <button+ className={styles.docLink}+ type={'button'}+ onClick={() => openDocument(item.documentId!)}+ >+ {caption || t('goalProcess.result.criteria.document')}+ </button>+ </Flexbox>+ );++ if (item.fileUrl)+ return (+ <Flexbox horizontal align={'center'} gap={6}>+ <Icon color={cssVar.colorTextTertiary} icon={Paperclip} size={14} />+ <a href={item.fileUrl} rel={'noopener noreferrer'} target={'_blank'}>+ {caption || item.type}+ </a>+ </Flexbox>+ );++ return caption ? (+ <Text fontSize={13} type={'secondary'}>+ {caption}+ </Text>+ ) : null;+};++const CriterionRow = ({ index, outcome }: { index: number; outcome: CriterionOutcome }) => {+ const { t } = useTranslation('chat');+ const [open, setOpen] = useState(false);+ const { criterion, evidence, reason, state, summary } = outcome;+ const openable = evidence.length > 0;+ const color = STATE_COLOR[state];++ return (+ <div className={styles.item} data-criterion-id={criterion.id} data-criterion-state={state}>+ <Flexbox+ horizontal+ align={'flex-start'}+ as={openable ? 'button' : 'div'}+ className={cx(styles.row, openable && styles.rowOpenable)}+ gap={10}+ {...(openable ? { onClick: () => setOpen(!open), type: 'button' as const } : {})}+ >+ <Icon+ color={color}+ icon={STATE_ICON[state]}+ size={18}+ style={{ flex: 'none', marginBlockStart: 1 }}+ />+ <Flexbox flex={1} gap={3} style={{ minWidth: 0 }}>+ <Flexbox horizontal align={'baseline'} gap={8}>+ <Text style={{ flex: 1, minWidth: 0, wordBreak: 'break-word' }} weight={500}>+ {index + 1}. {criterion.title}+ </Text>+ <Text fontSize={12} style={{ color, flex: 'none' }} weight={500}>+ {t(`goalProcess.result.criteria.state.${state}`)}+ </Text>+ </Flexbox>+ {summary && (+ <Text fontSize={13} style={{ wordBreak: 'break-word' }} type={'secondary'}>+ {summary}+ </Text>+ )}+ {state === 'failed' && reason && (+ <Text className={styles.reason} fontSize={13} style={{ wordBreak: 'break-word' }}>+ {reason}+ </Text>+ )}+ {state === 'unjudged' && (+ <Text fontSize={13} type={'secondary'}>+ {reason ?? t('goalProcess.result.criteria.unjudgedHint')}+ </Text>+ )}+ </Flexbox>+ {openable && (+ <Flexbox+ horizontal+ align={'center'}+ gap={4}+ style={{ flex: 'none', marginBlockStart: 2 }}+ >+ <Text fontSize={12} type={'secondary'}>+ {t('goalProcess.result.criteria.evidenceCount', { count: evidence.length })}+ </Text>+ <Icon+ className={cx(styles.arrow, open && styles.arrowOpen)}+ icon={ChevronRight}+ size={14}+ />+ </Flexbox>+ )}+ </Flexbox>+ {open && (+ <Flexbox className={styles.evidence} gap={12}>+ {evidence.map((item) => (+ <EvidenceItem item={item} key={item.id} />+ ))}+ </Flexbox>+ )}+ </div>+ );+};++interface GoalCriteriaResultsProps {+ /** The acceptance or criteria read failed: its outcomes are not a result. */+ error?: unknown;+ loading: boolean;+ onRetry?: () => void;+ outcomes: CriterionOutcome[];+}++const GoalCriteriaResults = ({ error, loading, onRetry, outcomes }: GoalCriteriaResultsProps) => {+ const { t } = useTranslation('chat');+ const met = outcomes.filter((outcome) => outcome.state === 'passed').length;++ return (+ <Flexbox gap={8}>+ <SectionTitle+ extra={+ !error &&+ outcomes.length > 0 && (+ <Text fontSize={13} type={'secondary'}>+ {t('goalProcess.result.scale.criteria', { met, total: outcomes.length })}+ </Text>+ )+ }+ >+ {t('goalProcess.result.criteria.title')}+ </SectionTitle>+ {error ? (+ <AsyncError error={error} variant={'block'} onRetry={onRetry} />+ ) : loading ? (+ <Flexbox gap={10}>+ <Skeleton height={18} radius={4} />+ <Skeleton height={18} radius={4} />+ <Skeleton height={18} radius={4} width={'70%'} />+ </Flexbox>+ ) : outcomes.length === 0 ? (+ <Text fontSize={13} type={'secondary'}>+ {t('goalProcess.result.criteria.empty')}+ </Text>+ ) : (+ <Flexbox>+ {outcomes.map((outcome, index) => (+ <CriterionRow index={index} key={outcome.criterion.id} outcome={outcome} />+ ))}+ </Flexbox>+ )}+ </Flexbox>+ );+};++export default GoalCriteriaResults;diff --git a/src/features/AgentGoals/ProcessControl/GoalResult.tsx b/src/features/AgentGoals/ProcessControl/GoalResult.tsxnew file mode 100644index 00000000000..1ee246bd324--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/GoalResult.tsx@@ -0,0 +1,96 @@+'use client';++import { Flexbox, Markdown } from '@lobehub/ui';+import { Skeleton } from '@lobehub/ui/base-ui';+import { Divider } from 'antd';++import { useClientDataSWR } from '@/libs/swr';+import { portalKeys } from '@/libs/swr/keys';+import { documentService } from '@/services/document';++import { pickFinalDeliverable } from './goalAcceptanceReport';+import GoalCriteriaResults from './GoalCriteriaResults';+import type { GoalGraphView } from './goalGraphViewModel';+import { GoalDecisionsMade, GoalUnfinished, useContinueFromResult } from './GoalResultFollowUps';+import GoalResultHeader from './GoalResultHeader';+import { findFinalAcceptanceView } from './goalResultState';+import ResultDeliverables from './ResultDeliverables';+import ResultTrail from './ResultTrail';+import { useGoalResultData } from './useGoalResultData';++/**+ * 结果交付 — what a finished Goal hands over, on its own tab.+ *+ * Layered for a reviewer who reads top-down: the first screen says where the+ * result stands, what was asked, how big the run was, and carries the sign-off.+ * Every deliverable follows in one place, with a reader to page through them.+ * Then each acceptance criterion against what the latest acceptance round+ * found, the decisions the owner made along the way, and what is still open.+ * The document the work wrote follows, read like a page rather than a card,+ * and under it the trail of how that result was reached. How the Goal ran+ * (tasks, map, activity) lives on the 执行过程 tab.+ */++const FinalDocument = ({ documentId }: { documentId: string }) => {+ // The graph carries only the document id; its content is read for the page.+ const { data: document, isLoading } = useClientDataSWR(+ portalKeys.documentHeader(documentId),+ () => documentService.getDocumentById(documentId),+ );++ if (isLoading)+ return (+ <Flexbox gap={10}>+ <Skeleton height={24} radius={4} width={'40%'} />+ <Skeleton height={14} radius={4} />+ <Skeleton height={14} radius={4} />+ <Skeleton height={14} radius={4} width={'70%'} />+ </Flexbox>+ );++ return <Markdown variant={'chat'}>{document?.content ?? ''}</Markdown>;+};++interface GoalResultProps {+ graph: GoalGraphView;+ onSelect: (nodeId: string) => void;+}++const GoalResult = ({ graph, onSelect }: GoalResultProps) => {+ const acceptanceNodeId = findFinalAcceptanceView(graph)?.node.id ?? '';+ const deliverable = pickFinalDeliverable(graph.artifacts, acceptanceNodeId);+ const data = useGoalResultData(graph);+ const continueFromResult = useContinueFromResult(graph, data.outcomes);++ return (+ <Flexbox gap={8}>+ <Flexbox gap={32}>+ <GoalResultHeader data={data} graph={graph} onContinue={continueFromResult} />+ <ResultDeliverables+ graph={graph}+ loading={data.isLoading}+ outcomes={data.outcomes}+ primaryResourceId={deliverable?.documentId}+ />+ <GoalCriteriaResults+ error={data.error}+ loading={data.isLoading}+ outcomes={data.outcomes}+ onRetry={data.retry}+ />+ <GoalDecisionsMade graph={graph} />+ <GoalUnfinished graph={graph} outcomes={data.outcomes} onContinue={continueFromResult} />+ </Flexbox>+ <Divider style={{ marginBlock: 24 }} />+ {deliverable && (+ <>+ <FinalDocument documentId={deliverable.documentId} />+ <Divider style={{ marginBlock: 24 }} />+ </>+ )}+ <ResultTrail documentId={deliverable?.documentId} graph={graph} onSelect={onSelect} />+ </Flexbox>+ );+};++export default GoalResult;diff --git a/src/features/AgentGoals/ProcessControl/GoalResultFollowUps.tsx b/src/features/AgentGoals/ProcessControl/GoalResultFollowUps.tsxnew file mode 100644index 00000000000..e6244dddd24--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/GoalResultFollowUps.tsx@@ -0,0 +1,326 @@+'use client';++import { Flexbox, Icon } from '@lobehub/ui';+import { Button, Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { ArrowRight, CircleSlash, Flag, MessageCircleQuestion, XCircle } from 'lucide-react';+import { type ReactNode, useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useActivityTime } from '@/hooks/useActivityTime';++import { createGoalModal } from '../CreateGoalModal';+import {+ coordinatorGateKind,+ coordinatorGateReason,+ coordinatorReasonCopy,+ gateTitleKey,+} from './coordinatorCopy';+import { pickFinalDeliverable } from './goalAcceptanceReport';+import type { GoalGraphView } from './goalGraphViewModel';+import {+ buildAbandonedNodes,+ buildUserDecisions,+ type CriterionOutcome,+ findFinalAcceptanceView,+ type UserDecisionView,+} from './goalResultState';++/**+ * 你做过的决定 and 没有完成 / 下一步 — what the owner already shaped, and what+ * is still open. Both read only recorded data: decisions from+ * `goal_node_decisions`, unmet criteria from the latest acceptance round,+ * dropped tasks from the graph; the report's next steps are appended when a+ * wrap-up storyline exists, never required.+ */++const styles = createStaticStyles(({ css }) => ({+ item: css`+ padding-block: 10px;++ &:not(:last-child) {+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};+ }+ `,+ time: css`+ flex: none;+ min-width: 60px;+ text-align: end;+ `,+}));++export const SectionTitle = ({ children, extra }: { children: ReactNode; extra?: ReactNode }) => (+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>+ <Text fontSize={16} weight={600}>+ {children}+ </Text>+ {extra}+ </Flexbox>+);++const DecisionTime = ({ at }: { at: Date }) => {+ const { text, title } = useActivityTime(at);+ return (+ <Text className={styles.time} fontSize={12} title={title} type={'secondary'}>+ {text}+ </Text>+ );+};++/**+ * A decision in the owner's language. Coordinator gates are stored as English+ * templates ("… Retry or retire this task node?") with stable option ids; a+ * recognized gate reads as its localized title, the task it was about and the+ * localized reason. Any other decision keeps the wording it was asked in.+ */+const useDecisionCopy = (graph: GoalGraphView) => {+ const { t } = useTranslation('chat');++ return (view: UserDecisionView) => {+ const { decision } = view;+ const kind = coordinatorGateKind(decision);+ if (!kind) return { choice: view.choice, question: view.question };++ const subjectId = graph.byId[decision.nodeId]?.gateSubjectId;+ const subject = subjectId ? graph.byId[subjectId]?.node.title : undefined;+ const rawReason = coordinatorGateReason(decision.question);+ const reasonCopy = coordinatorReasonCopy(rawReason);+ const optionId = decision.resolvedOptionId;+ const choice =+ optionId === 'retry' || optionId === 'retire' || optionId === 'fail'+ ? t(`goalProcess.gate.option.${optionId}`)+ : view.choice;++ return {+ choice,+ detail: reasonCopy ? t(reasonCopy.key as any, reasonCopy.params) : rawReason,+ question: subject+ ? `${t(gateTitleKey(kind) as any)} · ${subject}`+ : t(gateTitleKey(kind) as any),+ };+ };+};++const DecisionItem = ({+ copy,+ view,+}: {+ copy: { choice?: string; detail?: string; question: string };+ view: UserDecisionView;+}) => (+ <Flexbox horizontal className={styles.item} gap={12}>+ <Icon+ color={cssVar.colorTextTertiary}+ icon={MessageCircleQuestion}+ size={16}+ style={{ flex: 'none', marginBlockStart: 2 }}+ />+ <Flexbox flex={1} gap={4} style={{ minWidth: 0 }}>+ <Text style={{ wordBreak: 'break-word' }}>{copy.question}</Text>+ {copy.detail && (+ <Text fontSize={13} style={{ wordBreak: 'break-word' }} type={'secondary'}>+ {copy.detail}+ </Text>+ )}+ {copy.choice && (+ <Flexbox horizontal align={'flex-start'} gap={6}>+ <Icon+ color={cssVar.colorPrimary}+ icon={ArrowRight}+ size={14}+ style={{ flex: 'none', marginBlockStart: 3 }}+ />+ <Text style={{ wordBreak: 'break-word' }} weight={500}>+ {copy.choice}+ </Text>+ </Flexbox>+ )}+ </Flexbox>+ {view.resolvedAt && <DecisionTime at={view.resolvedAt} />}+ </Flexbox>+);++export const GoalDecisionsMade = ({ graph }: { graph: GoalGraphView }) => {+ const { t } = useTranslation('chat');+ const decisions = buildUserDecisions(graph.decisions);+ const copyOf = useDecisionCopy(graph);++ return (+ <Flexbox gap={8}>+ <SectionTitle>{t('goalProcess.result.decisions.title')}</SectionTitle>+ {decisions.length === 0 ? (+ <Text fontSize={13} type={'secondary'}>+ {t('goalProcess.result.decisions.empty')}+ </Text>+ ) : (+ <Flexbox>+ {decisions.map((view) => (+ <DecisionItem copy={copyOf(view)} key={view.decision.id} view={view} />+ ))}+ </Flexbox>+ )}+ </Flexbox>+ );+};++/**+ * 基于成果继续 — a new Goal seeded with this one's requirement, what it+ * delivered and what is still open. The create flow still lets the owner+ * rewrite all of it before anything runs.+ */+export const useContinueFromResult = (graph: GoalGraphView, outcomes: CriterionOutcome[]) => {+ const { t } = useTranslation('chat');+ const navigate = useWorkspaceAwareNavigate();++ return useCallback(() => {+ const { goal } = graph;+ const deliverable = pickFinalDeliverable(+ graph.artifacts,+ findFinalAcceptanceView(graph)?.node.id ?? '',+ );+ const open = [+ ...outcomes+ .filter((outcome) => outcome.state !== 'passed')+ .map((outcome) =>+ outcome.reason+ ? `${outcome.criterion.title}: ${outcome.reason}`+ : outcome.criterion.title,+ ),+ ...buildAbandonedNodes(graph).map(({ reason, view }) =>+ reason ? `${view.node.title}: ${reason}` : view.node.title,+ ),+ ];+ const requirement = [+ t('goalProcess.result.continueSeed.intro', { title: goal.title }),+ deliverable?.title &&+ t('goalProcess.result.continueSeed.deliverable', { title: deliverable.title }),+ goal.requirement &&+ `${t('goalProcess.result.continueSeed.requirement')}\n${goal.requirement}`,+ open.length > 0 &&+ `${t('goalProcess.result.continueSeed.open')}\n${open.map((line) => `- ${line}`).join('\n')}`,+ ]+ .filter(Boolean)+ .join('\n\n');++ createGoalModal({+ agentId: goal.agentId ?? undefined,+ initialRequirement: requirement,+ initialTitle: t('goalProcess.result.continueSeed.title', { title: goal.title }),+ onCreated: (created) => {+ const ownerId = created.agentId ?? goal.agentId;+ navigate(ownerId ? `/agent/${ownerId}/goal/${created.goalId}` : `/goal/${created.goalId}`);+ },+ projectId: goal.projectId ?? undefined,+ });+ }, [graph, navigate, outcomes, t]);+};++const OpenItem = ({+ detail,+ icon,+ title,+ tone,+}: {+ detail?: string;+ icon: typeof Flag;+ title: string;+ tone: string;+}) => (+ <Flexbox horizontal className={styles.item} gap={12}>+ <Icon color={tone} icon={icon} size={16} style={{ flex: 'none', marginBlockStart: 2 }} />+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>+ <Text style={{ wordBreak: 'break-word' }} weight={500}>+ {title}+ </Text>+ {detail && (+ <Text fontSize={13} style={{ wordBreak: 'break-word' }} type={'secondary'}>+ {detail}+ </Text>+ )}+ </Flexbox>+ </Flexbox>+);++const OpenGroup = ({ children, label }: { children: ReactNode; label: string }) => (+ <Flexbox gap={2}>+ <Text fontSize={12} type={'secondary'} weight={500}>+ {label}+ </Text>+ <Flexbox>{children}</Flexbox>+ </Flexbox>+);++export const GoalUnfinished = ({+ graph,+ onContinue,+ outcomes,+}: {+ graph: GoalGraphView;+ onContinue: () => void;+ outcomes: CriterionOutcome[];+}) => {+ const { t } = useTranslation('chat');+ const unmet = outcomes.filter((outcome) => outcome.state === 'failed');+ const abandoned = buildAbandonedNodes(graph);+ const nextSteps = graph.report?.latest?.metadata.nextSteps ?? [];+ const empty = unmet.length === 0 && abandoned.length === 0 && nextSteps.length === 0;++ return (+ <Flexbox gap={12}>+ <SectionTitle+ extra={+ <Button icon={ArrowRight} size={'small'} onClick={onContinue}>+ {t('goalProcess.result.unfinished.continue')}+ </Button>+ }+ >+ {t('goalProcess.result.unfinished.title')}+ </SectionTitle>+ {empty && (+ <Text fontSize={13} type={'secondary'}>+ {t('goalProcess.result.unfinished.empty')}+ </Text>+ )}+ {unmet.length > 0 && (+ <OpenGroup label={t('goalProcess.result.unfinished.unmetCriteria')}>+ {unmet.map((outcome) => (+ <OpenItem+ detail={outcome.reason}+ icon={XCircle}+ key={outcome.criterion.id}+ title={outcome.criterion.title}+ tone={cssVar.colorError}+ />+ ))}+ </OpenGroup>+ )}+ {abandoned.length > 0 && (+ <OpenGroup label={t('goalProcess.result.unfinished.abandoned')}>+ {abandoned.map(({ reason, view }) => (+ <OpenItem+ detail={reason}+ icon={CircleSlash}+ key={view.node.id}+ title={view.node.title}+ tone={cssVar.colorTextTertiary}+ />+ ))}+ </OpenGroup>+ )}+ {nextSteps.length > 0 && (+ <OpenGroup label={t('goalProcess.result.unfinished.nextSteps')}>+ {nextSteps.map((step) => (+ <OpenItem+ detail={step.reason}+ icon={Flag}+ key={step.title}+ title={step.title}+ tone={cssVar.colorPrimary}+ />+ ))}+ </OpenGroup>+ )}+ </Flexbox>+ );+};diff --git a/src/features/AgentGoals/ProcessControl/GoalResultHeader.tsx b/src/features/AgentGoals/ProcessControl/GoalResultHeader.tsxnew file mode 100644index 00000000000..4e4dde3ef79--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/GoalResultHeader.tsx@@ -0,0 +1,368 @@+'use client';++import type { GoalGraphDecision } from '@lobechat/types';+import { Flexbox, Icon, Markdown, TextArea, Tooltip } from '@lobehub/ui';+import { Button, confirmModal, Text, toast } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import {+ ArrowRight,+ BadgeCheck,+ CircleAlert,+ CircleCheck,+ CircleX,+ RefreshCw,+ Undo2,+} from 'lucide-react';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncError from '@/components/AsyncError';+import CollapsibleContent from '@/components/CollapsibleContent';+import { usePermission } from '@/hooks/usePermission';+import { verifyService } from '@/services/verify';+import { useGoalStore } from '@/store/goal';++import { formatSpan, formatUsd } from '../goalPresentation';+import { coordinatorGateReason, coordinatorReasonCopy } from './coordinatorCopy';+import { useGateOptionLabel } from './Frontier';+import type { GoalGraphView } from './goalGraphViewModel';+import {+ countGoalTasks,+ deriveGoalResultStatus,+ deriveSignOffState,+ findGoalAcceptanceGate,+ findOpenChangeRequest,+ type GoalAcceptanceGate,+ type GoalResultStatus,+ type GoalSignOffState,+} from './goalResultState';+import { openRequestChangesModal } from './RequestChangesModal';+import type { GoalResultData } from './useGoalResultData';++/**+ * The first screen of a finished Goal: where it stands, the one-line result+ * (only when the wrap-up report wrote one), what was asked, how big the run+ * was, and the one action it waits on — signing off the delivery. Sign-off is+ * the Goal-level acceptance's own accept / reject, so the acceptance page and+ * this strip can never disagree.+ */++const styles = createStaticStyles(({ css }) => ({+ strip: css`+ padding-block: 10px;+ padding-inline: 14px;+ border-radius: ${cssVar.borderRadiusLG};+ background: ${cssVar.colorFillQuaternary};+ `,+}));++const STATUS_ICON: Record<GoalResultStatus, typeof CircleCheck> = {+ awaitingDecision: CircleX,+ awaitingSignOff: CircleCheck,+ partial: CircleAlert,+ revising: RefreshCw,+ signedOff: BadgeCheck,+};++const STATUS_COLOR: Record<GoalResultStatus, string> = {+ awaitingDecision: cssVar.colorError,+ awaitingSignOff: cssVar.colorSuccess,+ partial: cssVar.colorWarning,+ revising: cssVar.colorInfo,+ signedOff: cssVar.colorPrimary,+};++const SIGN_OFF_TEXT: Record<GoalSignOffState, string> = {+ accepted: 'goalProcess.result.signOff.accepted',+ changesRequested: 'goalProcess.result.signOff.changesRequested',+ open: 'goalProcess.result.signOff.prompt',+ stopped: 'goalProcess.result.signOff.stopped',+ unavailable: 'goalProcess.result.signOff.unavailable',+};++interface SignOffStripProps {+ data: GoalResultData;+ gate?: GoalAcceptanceGate['kind'];+ goalId: string;+ goalStatus: string;+ onContinue: () => void;+ partial: boolean;+}++const SignOffStrip = ({+ data,+ gate,+ goalId,+ goalStatus,+ onContinue,+ partial,+}: SignOffStripProps) => {+ const { t } = useTranslation('chat');+ const refreshGoalGraph = useGoalStore((s) => s.refreshGoalGraph);+ const { acceptanceId, acceptanceStatus, canReview, mutateAcceptance, outcomes } = data;+ const state = deriveSignOffState(acceptanceStatus, goalStatus, gate);+ const unmet = outcomes.filter((outcome) => outcome.state !== 'passed').length;++ const settle = async (action: () => Promise<unknown>) => {+ try {+ await action();+ await Promise.all([mutateAcceptance(), refreshGoalGraph(goalId)]);+ return true;+ } catch (error) {+ console.error('[goal:sign-off]', error);+ toast.error(t('goalProcess.result.signOff.error'));+ return false;+ }+ };++ const accept = () =>+ confirmModal({+ cancelText: t('goalProcess.result.signOff.cancel'),+ content:+ unmet > 0+ ? `${t('goalProcess.result.signOff.acceptConfirm.content')} ${t(+ 'goalProcess.result.signOff.acceptConfirm.unmet',+ { count: unmet },+ )}`+ : t('goalProcess.result.signOff.acceptConfirm.content'),+ okText: t('goalProcess.result.signOff.accept'),+ onOk: async () => {+ await settle(() => verifyService.acceptDelivery(acceptanceId!));+ },+ title: t('goalProcess.result.signOff.acceptConfirm.title'),+ });++ const requestChanges = () =>+ openRequestChangesModal({+ onConfirm: async (comment) => {+ const sent = await settle(() => verifyService.rejectDelivery(acceptanceId!, comment));+ if (sent) toast.success(t('goalProcess.result.signOff.changes.sent'));+ return sent;+ },+ });++ const actionable = state === 'open' && !!acceptanceId && canReview;++ // Without the bundle the page cannot tell whether a sign-off is possible;+ // say so and offer a retry rather than silently dropping the actions.+ if (data.error && state === 'open')+ return (+ <Flexbox className={styles.strip} data-sign-off-state={'error'}>+ <AsyncError error={data.error} variant={'inline'} onRetry={data.retry} />+ </Flexbox>+ );++ return (+ <Flexbox+ horizontal+ align={'center'}+ className={styles.strip}+ data-sign-off-state={state}+ gap={12}+ justify={'space-between'}+ wrap={'wrap'}+ >+ <Text style={{ flex: 1, minWidth: 200 }} type={state === 'open' ? undefined : 'secondary'}>+ {t(SIGN_OFF_TEXT[state] as any)}+ </Text>+ <Flexbox horizontal gap={8}>+ {actionable && (+ <>+ <Button icon={Undo2} onClick={requestChanges}>+ {t('goalProcess.result.signOff.requestChanges')}+ </Button>+ <Button icon={CircleCheck} type={'primary'} onClick={accept}>+ {t('goalProcess.result.signOff.accept')}+ </Button>+ </>+ )}+ {/* A stopped Goal has nothing further to sign; its way forward is to+ pick the work up again. */}+ {!actionable && partial && (+ <Button icon={ArrowRight} onClick={onContinue}>+ {t('goalProcess.result.unfinished.continue')}+ </Button>+ )}+ </Flexbox>+ </Flexbox>+ );+};++interface DecisionStripProps {+ decision: GoalGraphDecision;+ goalId: string;+ onDecided: () => Promise<unknown>;+}++/**+ * The Goal-level acceptance ended unmet and the coordinator opened a gate on+ * it. The owner decides here, beside the criteria that failed, instead of+ * hunting for the gate on the 执行过程 tab — same options, same endpoint.+ */+const DecisionStrip = ({ decision, goalId, onDecided }: DecisionStripProps) => {+ const { t } = useTranslation('chat');+ const decideGoal = useGoalStore((s) => s.decideGoal);+ const { allowed: canEdit } = usePermission('create_content');+ const optionLabel = useGateOptionLabel();+ const [note, setNote] = useState('');+ const [deciding, setDeciding] = useState<string>();++ const rawReason = coordinatorGateReason(decision.question);+ const reasonCopy = coordinatorReasonCopy(rawReason);+ const reason = reasonCopy ? t(reasonCopy.key as any, reasonCopy.params) : rawReason;++ const decide = async (optionId: string) => {+ setDeciding(optionId);+ try {+ await decideGoal(goalId, {+ decisionId: decision.id,+ optionId,+ resolution: note.trim() || undefined,+ });+ await onDecided();+ } catch (error) {+ console.error('[goal:result-decision]', error);+ toast.error(t('goalProcess.result.gate.error'));+ } finally {+ setDeciding(undefined);+ }+ };++ return (+ <Flexbox className={styles.strip} data-goal-result-gate={decision.id} gap={12}>+ <Flexbox gap={4}>+ {reason && <Text weight={500}>{reason}</Text>}+ <Text type={'secondary'}>{t('goalProcess.result.gate.prompt')}</Text>+ </Flexbox>+ {canEdit && (+ <>+ <TextArea+ autoSize={{ maxRows: 3, minRows: 1 }}+ placeholder={t('goalProcess.gate.notePlaceholder')}+ value={note}+ onChange={(event) => setNote(event.target.value)}+ />+ <Flexbox horizontal gap={8} wrap={'wrap'}>+ {decision.options?.map((option) => (+ <Tooltip key={option.id} title={option.description}>+ <Button+ danger={option.id === 'fail'}+ disabled={!!deciding && deciding !== option.id}+ loading={deciding === option.id}+ type={option.id === decision.recommendedOptionId ? 'primary' : 'default'}+ onClick={() => decide(option.id)}+ >+ {optionLabel(option)}+ </Button>+ </Tooltip>+ ))}+ </Flexbox>+ </>+ )}+ </Flexbox>+ );+};++interface GoalResultHeaderProps {+ data: GoalResultData;+ graph: GoalGraphView;+ onContinue: () => void;+}++const GoalResultHeader = ({ data, graph, onContinue }: GoalResultHeaderProps) => {+ const { t } = useTranslation('chat');+ const { goal } = graph;+ const { outcomes } = data;+ const met = outcomes.filter((outcome) => outcome.state === 'passed').length;+ const gate = findGoalAcceptanceGate(graph);+ const changeRequest = findOpenChangeRequest(graph);+ const status = deriveGoalResultStatus({+ acceptanceStatus: data.acceptanceStatus,+ changesRequested: !!changeRequest,+ gate: gate?.kind,+ goalStatus: goal.status,+ unmetCriteria: outcomes.filter((outcome) => outcome.state === 'failed').length,+ });+ const headline = graph.report?.latest?.metadata.headline;++ const scale = [+ outcomes.length > 0 && t('goalProcess.result.scale.criteria', { met, total: outcomes.length }),+ t('goalProcess.result.scale.tasks', { count: countGoalTasks(graph) }),+ goal.startedAt &&+ t('goalProcess.result.scale.duration', {+ duration: formatSpan(+ (goal.completedAt ?? goal.updatedAt).getTime() - goal.startedAt.getTime(),+ ),+ }),+ graph.spend && t('goalProcess.result.scale.cost', { cost: formatUsd(graph.spend.totalCost) }),+ ].filter(Boolean);++ return (+ <Flexbox data-goal-result-status={status} gap={14}>+ <Flexbox horizontal align={'center'} gap={8}>+ <Icon color={STATUS_COLOR[status]} icon={STATUS_ICON[status]} size={18} />+ <Text fontSize={14} style={{ color: STATUS_COLOR[status] }} weight={600}>+ {t(`goalProcess.result.status.${status}`)}+ </Text>+ </Flexbox>+ {headline && (+ <Text fontSize={20} style={{ lineHeight: 1.4 }} weight={600}>+ {headline}+ </Text>+ )}+ {goal.requirement && (+ <Flexbox gap={4}>+ <Text fontSize={12} type={'secondary'} weight={500}>+ {t('goalProcess.result.requirement')}+ </Text>+ <CollapsibleContent maxHeight={120}>+ <Markdown fontSize={14} variant={'chat'}>+ {goal.requirement}+ </Markdown>+ </CollapsibleContent>+ </Flexbox>+ )}+ <Text fontSize={13} type={'secondary'}>+ {scale.join(' · ')}+ </Text>+ {status === 'awaitingDecision' && gate?.kind === 'pending' ? (+ <DecisionStrip+ decision={gate.decision}+ goalId={goal.id}+ onDecided={data.mutateAcceptance}+ />+ ) : status === 'revising' ? (+ // Nothing to sign while the rework runs: the strip says what the Agent+ // is answering to instead of offering accept / request changes again.+ <Flexbox className={styles.strip} data-sign-off-state={'revising'} gap={6}>+ <Text type={'secondary'}>+ {t(+ changeRequest+ ? 'goalProcess.result.changes.revising'+ : 'goalProcess.result.gate.revising',+ )}+ </Text>+ {changeRequest?.comment && (+ <Flexbox data-goal-change-request gap={2}>+ <Text fontSize={12} type={'secondary'} weight={500}>+ {t('goalProcess.result.changes.comment')}+ </Text>+ <Text style={{ whiteSpace: 'pre-wrap' }}>{changeRequest.comment}</Text>+ </Flexbox>+ )}+ </Flexbox>+ ) : (+ <SignOffStrip+ data={data}+ gate={gate?.kind}+ goalId={goal.id}+ goalStatus={goal.status}+ partial={status === 'partial'}+ onContinue={onContinue}+ />+ )}+ </Flexbox>+ );+};++export default GoalResultHeader;diff --git a/src/features/AgentGoals/ProcessControl/GoalResultTabs.tsx b/src/features/AgentGoals/ProcessControl/GoalResultTabs.tsxnew file mode 100644index 00000000000..82b5f716a7a--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/GoalResultTabs.tsx@@ -0,0 +1,55 @@+'use client';++import { Flexbox } from '@lobehub/ui';+import { Tabs } from '@lobehub/ui/base-ui';+import type { ReactNode } from 'react';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import type { GoalGraphView } from './goalGraphViewModel';+import GoalResult from './GoalResult';+import { hasGoalResult } from './goalResultState';++/**+ * A finished Goal opens on what it delivered; how it got there moves to a+ * second tab. A Goal still in flight has no result to hand over, so it keeps+ * the single process view with no tabs at all.+ *+ * Hosts key this by goal id, so switching goals starts back on the result.+ */++type GoalTab = 'process' | 'result';++interface GoalResultTabsProps {+ graph: GoalGraphView;+ onSelect: (nodeId: string) => void;+ /** The 执行过程 content — the whole process view the host already renders. */+ process: ReactNode;+}++const GoalResultTabs = ({ graph, onSelect, process }: GoalResultTabsProps) => {+ const { t } = useTranslation('chat');+ const [tab, setTab] = useState<GoalTab>('result');++ if (!hasGoalResult(graph)) return <>{process}</>;++ return (+ <Flexbox gap={20}>+ <Tabs+ activeKey={tab}+ style={{ marginInline: -6 }}+ variant={'square'}+ items={[+ { key: 'result', label: t('goalProcess.tabs.result') },+ { key: 'process', label: t('goalProcess.tabs.process') },+ ]}+ onChange={(key) => setTab(key as GoalTab)}+ />+ {/* Only the active tab mounts: the exploration map measures its box on+ mount and would lay out against a hidden panel. */}+ {tab === 'result' ? <GoalResult graph={graph} onSelect={onSelect} /> : process}+ </Flexbox>+ );+};++export default GoalResultTabs;diff --git a/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx b/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsxindex 03f0451b268..e7ef268e95c 100644--- a/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx+++ b/src/features/AgentGoals/ProcessControl/Graph/GraphNode.tsx@@ -28,8 +28,12 @@ import { experimentStatusVisual } from './experimentStatus';export interface GraphNodeData extends Record<string, unknown> {dim: boolean;+ /** Called out by the host — a detour on a report chapter's local map. */+ highlighted?: boolean;isGate: boolean;kind?: GoalGraphNodeKind;+ /** On the path the wrap-up report marked as the one that led to the result. */+ mainline?: boolean;memberCount?: number;running: boolean;selected: boolean;@@ -82,6 +86,11 @@ const styles = createStaticStyles(({ css }) => ({ghost: css`border-style: dashed;`,+ highlighted: css`+ border-color: ${cssVar.colorWarning};+ border-style: dashed;+ box-shadow: 0 0 0 3px ${cssVar.colorWarningBg};+ `,ghostBar: css`height: 8px;border-radius: 4px;@@ -165,6 +174,11 @@ const styles = createStaticStyles(({ css }) => ({font-variant-numeric: tabular-nums;color: ${cssVar.colorTextTertiary};`,+ /* A ring, not a fill: the kind tint and the state chip must stay readable. */+ mainline: css`+ border-color: ${cssVar.colorPrimary};+ box-shadow: 0 0 0 1px ${cssVar.colorPrimary};+ `,selected: css`border-color: ${cssVar.colorPrimaryBorder};`,@@ -264,7 +278,7 @@ RunningClock.displayName = 'GoalGraphRunningClock';const GraphNodeView = memo<NodeProps>(({ data }) => {const { t } = useTranslation('chat');const nodeData = data as GraphNodeData;- const { dim, isGate, running, selected, stale, subtitle, view } = nodeData;+ const { dim, highlighted, isGate, mainline, running, selected, stale, subtitle, view } = nodeData;const { node } = view;const chip = useStateChip(nodeData);const kind = nodeData.kind ?? node.kind;@@ -283,18 +297,26 @@ const GraphNodeView = memo<NodeProps>(({ data }) => {type={'target'}/><div+ data-mainline={mainline || undefined}className={cx(styles.card,isGate && styles.gate,stale && styles.stale,dim && styles.dim,+ highlighted && styles.highlighted,selected && styles.selected,+ mainline && styles.mainline,)}>{/* Status reads first: its own top row, left-aligned, with the runningclock riding right behind it (review: bottom placements read poorly). */}- {(chip || view.humanTouches.length > 0) && (+ {(chip || highlighted || view.humanTouches.length > 0) && (<div className={styles.statusRow}>+ {highlighted && (+ <span className={styles.chipText} style={{ color: cssVar.colorWarningText }}>+ {t('goalProcess.result.story.detourTag')}+ </span>+ )}{kind === 'experiment' && (<span className={styles.chipText} style={{ color: palette.line }}>{t('goalExperiment.number', { number: view.seq })}diff --git a/src/features/AgentGoals/ProcessControl/Graph/chapterMap.test.ts b/src/features/AgentGoals/ProcessControl/Graph/chapterMap.test.tsnew file mode 100644index 00000000000..c09274e22ff--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/Graph/chapterMap.test.ts@@ -0,0 +1,187 @@+import type { GoalEdgeKind, GoalGraphEdge, GoalReportState } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import type { GoalGraphView, GoalNodeView } from '../goalGraphViewModel';+import { chapterMap } from './chapterMap';+import { edgeTone, resolveMainline } from './mainline';++type Link = [id: string, kind: GoalEdgeKind, source: string, target: string];++const graphOf = (+ nodes: Record<string, 'problem' | 'task' | 'finding' | 'experiment'>,+ links: Link[],+ mainline?: { edgeIds: string[]; nodeIds: string[] },+): GoalGraphView => {+ const views = Object.entries(nodes).map(+ ([id, kind]) => ({ node: { id, kind, status: 'resolved' } }) as unknown as GoalNodeView,+ );+ return {+ blocked: [],+ byId: Object.fromEntries(views.map((view) => [view.node.id, view])),+ edges: links.map(+ ([id, kind, sourceNodeId, targetNodeId]) =>+ ({ id, kind, sourceNodeId, targetNodeId }) as GoalGraphEdge,+ ),+ frontier: [],+ nodes: views,+ report: mainline+ ? ({+ latest: {+ metadata: { chapters: [], graphCursor: 'e', headline: 'H', mainline, nextSteps: [] },+ },+ status: 'completed',+ } as unknown as GoalReportState)+ : undefined,+ } as unknown as GoalGraphView;+};++const edgeIds = (map: ReturnType<typeof chapterMap>) => map.graph.edges.map((edge) => edge.id);+const nodeIds = (map: ReturnType<typeof chapterMap>) => map.graph.nodes.map((v) => v.node.id);++describe('chapterMap', () => {+ it('keeps every relation between the chapter’s own nodes', () => {+ const graph = graphOf(+ { a: 'task', b: 'task', c: 'task', d: 'task', e: 'task', f: 'finding', g: 'task' },+ [+ ['e-dep', 'depends_on', 'b', 'a'],+ ['e-der', 'derived_from', 'c', 'b'],+ ['e-rev', 'revises', 'd', 'c'],+ ['e-con', 'contradicts', 'f', 'd'],+ ['e-pro', 'produces', 'e', 'f'],+ ['e-dec', 'decomposes', 'a', 'e'],+ ['e-out', 'depends_on', 'g', 'a'],+ ],+ );++ const map = chapterMap(graph, ['a', 'b', 'c', 'd', 'e', 'f']);++ expect(edgeIds(map)).toEqual(['e-dep', 'e-der', 'e-rev', 'e-con', 'e-pro', 'e-dec']);+ expect(map.bridges).toEqual([]);+ expect([...map.contextIds]).toEqual([]);+ });++ it('shows the question a detour forked from when the chapter does not list it', () => {+ // p decomposes into the mainline task and the dead end: neither links to the other.+ const graph = graphOf(+ { dead: 'task', main: 'task', p: 'problem' },+ [+ ['p-main', 'decomposes', 'p', 'main'],+ ['p-dead', 'decomposes', 'p', 'dead'],+ ],+ { edgeIds: ['p-main'], nodeIds: ['main'] },+ );++ const map = chapterMap(graph, ['main', 'dead']);++ expect([...map.contextIds]).toEqual(['p']);+ expect(nodeIds(map).sort()).toEqual(['dead', 'main', 'p']);+ expect(edgeIds(map)).toEqual(['p-main', 'p-dead']);+ expect(map.bridges).toEqual([]);+ });++ it('draws one schematic link when the fork is further than one node away', () => {+ const graph = graphOf(+ { main: 'task', mid1: 'task', mid2: 'task', retry: 'task' },+ [+ ['d1', 'derived_from', 'mid1', 'main'],+ ['d2', 'derived_from', 'mid2', 'mid1'],+ ['d3', 'derived_from', 'retry', 'mid2'],+ ],+ { edgeIds: [], nodeIds: ['main'] },+ );++ const map = chapterMap(graph, ['main', 'retry']);++ expect(map.bridges).toEqual([{ hops: 2, sourceNodeId: 'main', targetNodeId: 'retry' }]);+ expect([...map.contextIds]).toEqual([]);+ expect(nodeIds(map).sort()).toEqual(['main', 'retry']);+ });++ it('anchors on the part holding the mainline, whatever order the chapter lists', () => {+ const graph = graphOf(+ { dead: 'task', main: 'task', p: 'problem', side: 'finding' },+ [+ ['p-main', 'decomposes', 'p', 'main'],+ ['p-dead', 'decomposes', 'p', 'dead'],+ ['dead-side', 'produces', 'dead', 'side'],+ ],+ { edgeIds: [], nodeIds: ['main'] },+ );++ const map = chapterMap(graph, ['dead', 'side', 'main']);++ expect([...map.contextIds]).toEqual(['p']);+ expect(edgeIds(map).sort()).toEqual(['dead-side', 'p-dead', 'p-main']);+ });++ it('joins every stray part, not only the first', () => {+ const graph = graphOf(+ { a: 'task', b: 'task', main: 'task', p: 'problem' },+ [+ ['p-main', 'decomposes', 'p', 'main'],+ ['p-a', 'decomposes', 'p', 'a'],+ ['p-b', 'decomposes', 'p', 'b'],+ ],+ { edgeIds: [], nodeIds: ['main'] },+ );++ const map = chapterMap(graph, ['main', 'a', 'b']);++ expect([...map.contextIds]).toEqual(['p']);+ expect(edgeIds(map)).toEqual(['p-main', 'p-a', 'p-b']);+ });++ it('leaves a part with no route to the rest alone, and ignores containment', () => {+ const graph = graphOf(+ { alone: 'task', main: 'task', x: 'experiment' },+ [+ ['x-main', 'contains', 'x', 'main'],+ ['x-alone', 'contains', 'x', 'alone'],+ ],+ { edgeIds: [], nodeIds: ['main'] },+ );++ const map = chapterMap(graph, ['main', 'alone']);++ expect(map.bridges).toEqual([]);+ expect([...map.contextIds]).toEqual([]);+ expect(edgeIds(map)).toEqual([]);+ });++ it('drops chapter references the graph no longer carries', () => {+ const graph = graphOf({ a: 'task' }, []);+ expect(nodeIds(chapterMap(graph, ['a', 'gone']))).toEqual(['a']);+ });+});++describe('edgeTone', () => {+ const graph = graphOf({ dead: 'task', main: 'task', p: 'problem' }, [], {+ edgeIds: ['p-main'],+ nodeIds: ['p', 'main'],+ });+ const mainline = resolveMainline(graph);+ const isMainlineCard = (id: string) => mainline!.nodeIds.has(id);+ const detours = new Set(['dead']);++ it('keeps the mainline line highlighted', () => {+ const edge = { id: 'p-main', sourceNodeId: 'p', targetNodeId: 'main' };+ expect(edgeTone(mainline, edge, isMainlineCard, detours)).toBe('mainline');+ });++ it('draws the line into a detour in the detour style instead of muting it', () => {+ const edge = { id: 'p-dead', sourceNodeId: 'p', targetNodeId: 'dead' };+ expect(edgeTone(mainline, edge, isMainlineCard, detours)).toBe('detour');+ expect(edgeTone(mainline, edge, isMainlineCard)).toBe('muted');+ });++ it('styles a schematic bridge into a detour the same way', () => {+ const bridge = { bridge: true, id: 'b', sourceNodeId: 'main', targetNodeId: 'dead' };+ expect(edgeTone(mainline, bridge, isMainlineCard, detours)).toBe('detour');+ });++ it('calls out a detour even without a marked mainline', () => {+ const edge = { id: 'x', sourceNodeId: 'main', targetNodeId: 'dead' };+ expect(edgeTone(undefined, edge, () => false, detours)).toBe('detour');+ expect(edgeTone(undefined, edge, () => false)).toBeUndefined();+ });+});diff --git a/src/features/AgentGoals/ProcessControl/Graph/chapterMap.ts b/src/features/AgentGoals/ProcessControl/Graph/chapterMap.tsnew file mode 100644index 00000000000..4981f0e45ca--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/Graph/chapterMap.ts@@ -0,0 +1,115 @@+import { type GoalGraphView, scopeGraphView } from '../goalGraphViewModel';+import type { GraphBridge } from './layout';+import { resolveMainline } from './mainline';++/**+ * A report chapter's local map: the chapter's nodes, every edge between them,+ * and whatever it takes to show where each detour forked off.+ */+export interface ChapterMap {+ /**+ * Schematic links for a stray part that reaches the rest only through a+ * longer chain of nodes left off the map. `hops` counts the nodes skipped.+ */+ bridges: GraphBridge[];+ /** Nodes outside the chapter, added only because the fork happens there. */+ contextIds: ReadonlySet<string>;+ graph: GoalGraphView;+}++const componentsOf = (+ ids: ReadonlySet<string>,+ links: { sourceNodeId: string; targetNodeId: string }[],+): Set<string>[] => {+ const parent = new Map([...ids].map((id) => [id, id]));+ const find = (id: string): string => {+ const up = parent.get(id)!;+ if (up === id) return id;+ const root = find(up);+ parent.set(id, root);+ return root;+ };+ for (const link of links)+ if (ids.has(link.sourceNodeId) && ids.has(link.targetNodeId))+ parent.set(find(link.sourceNodeId), find(link.targetNodeId));+ const groups = new Map<string, Set<string>>();+ for (const id of ids) {+ const root = find(id);+ groups.set(root, (groups.get(root) ?? new Set()).add(id));+ }+ return [...groups.values()];+};++/**+ * Narrowing the goal graph to a chapter keeps only edges with both ends inside+ * it, and a detour usually forks from a node the chapter does not list — the+ * question both paths decompose from, or the task a retry continued. Left at+ * that, the map is loose cards with no way to tell where the stray path began.+ *+ * So the part holding the mainline (else the chapter's first node) is the+ * anchor, and every other part is joined to it by its shortest route through+ * the goal graph: one node in between is shown as the fork itself; a longer+ * route is drawn as one schematic link, anchor side first.+ */+export const chapterMap = (graph: GoalGraphView, nodeIds: readonly string[]): ChapterMap => {+ const links = graph.edges.filter(+ (edge) =>+ edge.kind !== 'contains' &&+ !!graph.byId[edge.sourceNodeId] &&+ !!graph.byId[edge.targetNodeId],+ );+ const neighbours = new Map<string, string[]>();+ for (const { sourceNodeId, targetNodeId } of links) {+ neighbours.set(sourceNodeId, [...(neighbours.get(sourceNodeId) ?? []), targetNodeId]);+ neighbours.set(targetNodeId, [...(neighbours.get(targetNodeId) ?? []), sourceNodeId]);+ }++ const chapterIds = nodeIds.filter((id) => graph.byId[id]);+ const members = new Set(chapterIds);+ const contextIds = new Set<string>();+ const bridges: GraphBridge[] = [];+ const mainline = resolveMainline(graph);++ // Every pass joins at least one part to the anchor, so this ends.+ for (;;) {+ const parts = componentsOf(members, [...links, ...bridges]);+ if (parts.length <= 1) break;+ const anchor =+ parts.find((part) => [...part].some((id) => mainline?.nodeIds.has(id))) ??+ parts.find((part) => part.has(chapterIds[0])) ??+ parts[0];++ const previous = new Map<string, string | undefined>([...anchor].map((id) => [id, undefined]));+ const queue = [...anchor];+ let reached: string | undefined;+ while (queue.length > 0 && !reached) {+ const current = queue.shift()!;+ for (const next of neighbours.get(current) ?? []) {+ if (previous.has(next)) continue;+ previous.set(next, current);+ if (members.has(next)) {+ reached = next;+ break;+ }+ queue.push(next);+ }+ }+ // What is left has no route to the anchor at all; nothing honest to draw.+ if (!reached) break;++ const between: string[] = [];+ let step = previous.get(reached);+ while (step && !anchor.has(step)) {+ between.push(step);+ step = previous.get(step);+ }+ if (between.length === 1) {+ contextIds.add(between[0]);+ members.add(between[0]);+ } else {+ bridges.push({ hops: between.length, sourceNodeId: step!, targetNodeId: reached });+ }+ }++ return { bridges, contextIds, graph: scopeGraphView(graph, members) };+};diff --git a/src/features/AgentGoals/ProcessControl/Graph/index.tsx b/src/features/AgentGoals/ProcessControl/Graph/index.tsxindex 933971c4ac8..035146a337a 100644--- a/src/features/AgentGoals/ProcessControl/Graph/index.tsx+++ b/src/features/AgentGoals/ProcessControl/Graph/index.tsx@@ -32,14 +32,20 @@ import { useChatStore } from '@/store/chat';import { chatPortalSelectors } from '@/store/chat/selectors';import { type GoalGraphNodeKind, graphNodeKind, graphNodeLabel } from '../../Experiments/model';-import { type GoalGraphView, type GoalNodeView, isRunningNode } from '../goalGraphViewModel';+import {+ type GoalGraphView,+ type GoalNodeView,+ isRunningNode,+ scopeGraphView,+} from '../goalGraphViewModel';import { KindDot } from '../shared';import { edgeDirection } from './edgeRouting';import ExperimentGroup, { type ExperimentGroupData } from './ExperimentGroup';import ExplorationEdge from './ExplorationEdge';import { explorationMap } from './explorationMap';import GraphNodeView, { GhostNodeView, type GraphNodeData } from './GraphNode';-import { hideKinds, layoutGraph, NODE_WIDTH } from './layout';+import { type GraphBridge, hideKinds, layoutGraph, NODE_WIDTH } from './layout';+import { type EdgeTone, edgeTone, isNodeDimmed, nodeEmphasis, resolveMainline } from './mainline';import { type MeasuredSizes, mergeMeasuredSizes } from './measuredSizes';import { revealCenter } from './revealNode';import { useExplorationNavigation } from './useExplorationNavigation';@@ -80,11 +86,34 @@ const styles = createStaticStyles(({ css }) => ({stroke-dasharray: 5 4;}+ /* The wrap-up report's mainline: the path reads as one bold line, and+ everything off it steps back. Selection still lights a muted edge. */+ .react-flow__edge.goal-mainline .react-flow__edge-path {+ stroke: ${cssVar.colorPrimary};+ stroke-width: 2.5;+ }++ /* A chapter map's detours: the line into a stray card reads in the same+ orange dash as the card's own frame. */+ .react-flow__edge.goal-detour .react-flow__edge-path {+ stroke: ${cssVar.colorWarning};+ stroke-dasharray: 6 4;+ stroke-width: 1.75;+ }++ .react-flow__edge.goal-muted:not(.goal-hot) {+ opacity: 0.3;+ }+.react-flow__edge.goal-hot .react-flow__edge-path {stroke: ${cssVar.colorPrimary};stroke-width: 1.75;}+ .react-flow__edge.goal-mainline.goal-hot .react-flow__edge-path {+ stroke-width: 2.5;+ }+.react-flow__edge-textbg {fill: ${cssVar.colorBgLayout};}@@ -121,6 +150,17 @@ const styles = createStaticStyles(({ css }) => ({`,/* A hidden kind stays in the legend as a dimmed toggle — the way back mustbe exactly where the way in was. */+ /** Not a kind filter: it names the bold line and ring the mainline is drawn with. */+ legendMainline: css`+ cursor: default;+ color: ${cssVar.colorText};+ `,+ legendMainlineSwatch: css`+ width: 14px;+ height: 3px;+ border-radius: 2px;+ background: ${cssVar.colorPrimary};+ `,legendOff: css`opacity: 0.35;@@ -182,6 +222,11 @@ const styles = createStaticStyles(({ css }) => ({}));interface GraphProps {+ /**+ * Schematic links the host adds for a route through nodes it left off the+ * map — a report chapter joining a detour to where it forked.+ */+ bridges?: GraphBridge[];/** Header actions after the legend — e.g. a host without fullscreen links out to the goal page. */extra?: ReactNode;/**@@ -192,6 +237,8 @@ interface GraphProps {*/fullscreen?: boolean;graph: GoalGraphView;+ /** Nodes to call out on the map — a chapter's detours in the report's local map. */+ highlightedIds?: ReadonlySet<string>;onFullscreenChange?: (fullscreen: boolean) => void;onSelect: (nodeId: string) => void;/** The coordinator is still decomposing: show ghost task cards under the problem. */@@ -287,7 +334,10 @@ const GHOST_RANK_GAP = 56;const GHOST_HEIGHT = 88;const Canvas = memo<- Pick<GraphProps, 'graph' | 'onSelect' | 'planning' | 'selectedId'> & {+ Pick<+ GraphProps,+ 'bridges' | 'graph' | 'highlightedIds' | 'onSelect' | 'planning' | 'selectedId'+ > & {className: string;fullscreen: boolean;hiddenKinds: ReadonlySet<GoalGraphNodeKind>;@@ -301,10 +351,12 @@ const Canvas = memo<}>(({+ bridges: hostBridges,className,fullscreen,graph,hiddenKinds,+ highlightedIds,onSelect,planning,refitKey,@@ -353,10 +405,14 @@ const Canvas = memo<: graph.nodes.map((item) => item.node).filter((node) => view === 'all' || stageNodeIds(graph).has(node.id));- const { bridges, visibleIds } = useMemo(- () => hideKinds(baseNodes, graph.edges, hiddenKinds),- [baseNodes, graph.edges, hiddenKinds],- );+ const { bridges, visibleIds } = useMemo(() => {+ const hidden = hideKinds(baseNodes, graph.edges, hiddenKinds);+ const shown = (hostBridges ?? []).filter(+ (bridge) =>+ hidden.visibleIds.has(bridge.sourceNodeId) && hidden.visibleIds.has(bridge.targetNodeId),+ );+ return { ...hidden, bridges: [...hidden.bridges, ...shown] };+ }, [baseNodes, graph.edges, hiddenKinds, hostBridges]);// A card's height follows its content — a long title wraps to four lines —// so the per-kind estimate stacked the next rank into the cards above it.// The first pass lays out on the estimate; once React Flow has measured the@@ -418,6 +474,18 @@ const Canvas = memo<[ghosts],);+ const mainline = useMemo(() => resolveMainline(graph), [graph]);+ const emphasisById = useMemo(() => {+ const result = new Map<string, ReturnType<typeof nodeEmphasis>>();+ if (!mainline) return result;+ const shape = { nodes: graph.nodes.map((view) => view.node), edges: graph.edges };+ for (const node of baseNodes) {+ const members = node.kind === 'experiment' ? experimentMembers(shape, node.id, false) : [];+ result.set(node.id, nodeEmphasis(mainline, node, members));+ }+ return result;+ }, [mainline, graph, baseNodes]);+const flowNodes: FlowNode[] = useMemo(() =>baseNodes@@ -426,10 +494,19 @@ const Canvas = memo<const item = graph.byId[node.id];const box = positions[item.node.id];const isGate = item.node.kind === 'decision' && item.node.status === 'waiting';+ const emphasis = emphasisById.get(item.node.id);+ const highlighted = highlightedIds?.has(item.node.id) ?? false;const data: GraphNodeData = {// Not started and still blocked — it is context, not the story.- dim: item.node.status === 'proposed' && item.blockers.length > 0,+ // Once the report marked a mainline, everything off it is context too.+ dim: isNodeDimmed({+ blocked: item.node.status === 'proposed' && item.blockers.length > 0,+ emphasis,+ highlighted,+ }),+ highlighted,isGate,+ mainline: emphasis === 'mainline',memberCount: experimentMembers({ nodes: graph.nodes.map((view) => view.node), edges: graph.edges },item.node.id,@@ -481,6 +558,7 @@ const Canvas = memo<[graph,baseNodes,+ highlightedIds,visibleIds,positions,selectedId,@@ -493,6 +571,7 @@ const Canvas = memo<hasExperiments,map.parents,measuredSizes,+ emphasisById,],);@@ -503,6 +582,13 @@ const Canvas = memo<type: MarkerType.ArrowClosed,width: 12,};+ const mainlineMarker = { ...marker, color: cssVar.colorPrimary };+ const detourMarker = { ...marker, color: cssVar.colorWarning };+ const isMainlineCard = (id: string) => emphasisById.get(id) === 'mainline';+ const toneOf = (edge: Parameters<typeof edgeTone>[1]) =>+ edgeTone(mainline, edge, isMainlineCard, highlightedIds);+ const markerOf = (tone: EdgeTone) =>+ tone === 'mainline' ? mainlineMarker : tone === 'detour' ? detourMarker : marker;const lanes = new Map<string, number>();const direct = (hasExperiments ? map.edges : graph.edges).filter((edge) => visibleIds.has(edge.sourceNodeId) && visibleIds.has(edge.targetNodeId))@@ -512,11 +598,13 @@ const Canvas = memo<const lane = lanes.get(pair) ?? 0;lanes.set(pair, lane + 1);const hot = selectedId === edge.sourceNodeId || selectedId === edge.targetNodeId;+ const tone = toneOf(edge);return {className: cx((edge.kind === 'depends_on' || ('projected' in edge && edge.projected === true)) &&'goal-dep',hot && 'goal-hot',+ tone && `goal-${tone}`,),id: edge.id,label:@@ -526,7 +614,7 @@ const Canvas = memo<}): edgeLabel(edge.kind),labelShowBg: true,- markerEnd: marker,+ markerEnd: markerOf(tone),source,target,type: hasExperiments ? 'exploration' : 'default',@@ -534,21 +622,41 @@ const Canvas = memo<} satisfies FlowEdge;});// A bridge stands in for a chain through hidden nodes: dashed like other- // indirect relations, and unlabeled — any word would claim a relation the- // hidden hop may not have.+ // indirect relations, and never named — any relation word would claim+ // something the hidden hop may not have. Only how far it skips is said.const bridged = bridges.map((bridge) => {const hot = selectedId === bridge.sourceNodeId || selectedId === bridge.targetNodeId;+ const id = `bridge:${bridge.sourceNodeId}:${bridge.targetNodeId}`;+ const tone = toneOf({ ...bridge, bridge: true, id });return {- className: cx('goal-dep', hot && 'goal-hot'),- id: `bridge:${bridge.sourceNodeId}:${bridge.targetNodeId}`,- markerEnd: marker,+ className: cx('goal-dep', hot && 'goal-hot', tone && `goal-${tone}`),+ id,+ ...(bridge.hops+ ? {+ label: t('goalProcess.graph.bridgeHops', { count: bridge.hops }),+ labelShowBg: true,+ }+ : {}),+ markerEnd: markerOf(tone),source: bridge.sourceNodeId,target: bridge.targetNodeId,type: 'default',} satisfies FlowEdge;});return [...direct, ...bridged];- }, [graph, visibleIds, bridges, selectedId, edgeLabel, hasExperiments, map.edges, t]);+ }, [+ graph,+ visibleIds,+ bridges,+ selectedId,+ edgeLabel,+ hasExperiments,+ map.edges,+ t,+ mainline,+ emphasisById,+ highlightedIds,+ ]);const ghostFlowEdges: FlowEdge[] = useMemo(() =>@@ -688,13 +796,7 @@ const Graph = memo<GraphProps>(({ extra, fullscreen = false, onFullscreenChange,const { collapsed, scopeId } = navigation;const scopeIds = new Set(navigation.nodes.map((node) => node.id));const scopedGraph: GoalGraphView = scopeId- ? {- ...props.graph,- nodes: props.graph.nodes.filter((item) => scopeIds.has(item.node.id)),- edges: navigation.edges,- frontier: props.graph.frontier.filter((item) => scopeIds.has(item.view.node.id)),- blocked: props.graph.blocked.filter((item) => scopeIds.has(item.node.id)),- }+ ? scopeGraphView(props.graph, scopeIds, navigation.edges): props.graph;const openNode = useChatStore((s) => s.openGoalNode);const [preferredView, setView] = useState<GraphViewMode>('stage');@@ -799,8 +901,21 @@ const Graph = memo<GraphProps>(({ extra, fullscreen = false, onFullscreenChange,{!fullscreen && toggle}</>);+ const hasMainline = !!resolveMainline(props.graph);const legend = (<Flexbox horizontal align={'center'} className={styles.legend} gap={10}>+ {hasMainline && (+ <Flexbox+ horizontal+ align={'center'}+ className={styles.legendMainline}+ gap={4}+ title={t('goalProcess.graph.legend.mainlineHint')}+ >+ <span className={styles.legendMainlineSwatch} />+ <span>{t('goalProcess.graph.legend.mainline')}</span>+ </Flexbox>+ )}{(['problem',diff --git a/src/features/AgentGoals/ProcessControl/Graph/layout.ts b/src/features/AgentGoals/ProcessControl/Graph/layout.tsindex 185d7a4d485..2cd48612a3b 100644--- a/src/features/AgentGoals/ProcessControl/Graph/layout.ts+++ b/src/features/AgentGoals/ProcessControl/Graph/layout.ts@@ -69,6 +69,8 @@ export interface LayoutBox {/** A synthetic edge standing in for a ranked chain that runs through hidden nodes. */export interface GraphBridge {+ /** How many nodes left off the map the link stands in for, when the host knows. */+ hops?: number;sourceNodeId: string;targetNodeId: string;}diff --git a/src/features/AgentGoals/ProcessControl/Graph/mainline.test.ts b/src/features/AgentGoals/ProcessControl/Graph/mainline.test.tsnew file mode 100644index 00000000000..908bf67e9f5--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/Graph/mainline.test.ts@@ -0,0 +1,114 @@+import type { GoalReportState } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import type { GoalGraphView } from '../goalGraphViewModel';+import { edgeEmphasis, isNodeDimmed, nodeEmphasis, resolveMainline } from './mainline';++const graphWith = (+ mainline: { edgeIds: string[]; nodeIds: string[] } | undefined,+ nodeIds = ['p', 't1', 't2', 't3', 'x1'],+) =>+ ({+ byId: Object.fromEntries(nodeIds.map((id) => [id, { node: { id } }])),+ report: {+ latest: {+ metadata: { chapters: [], graphCursor: 'e', headline: 'H', mainline, nextSteps: [] },+ },+ status: 'completed',+ } as unknown as GoalReportState,+ }) as unknown as Pick<GoalGraphView, 'byId' | 'report'>;++describe('resolveMainline', () => {+ it('reads the mark from the newest report version', () => {+ const mainline = resolveMainline(graphWith({ edgeIds: ['e1'], nodeIds: ['t1', 't2'] }));+ expect([...mainline!.nodeIds]).toEqual(['t1', 't2']);+ expect([...mainline!.edgeIds]).toEqual(['e1']);+ });++ it('leaves the map as it was without a report or a mark', () => {+ expect(resolveMainline({ byId: {}, report: undefined } as any)).toBeUndefined();+ expect(resolveMainline(graphWith(undefined))).toBeUndefined();+ });++ it('drops nodes gone from the graph, and does not mute a map whose whole mainline is gone', () => {+ expect([+ ...resolveMainline(graphWith({ edgeIds: [], nodeIds: ['t1', 'gone'] }))!.nodeIds,+ ]).toEqual(['t1']);+ expect(resolveMainline(graphWith({ edgeIds: [], nodeIds: ['gone'] }))).toBeUndefined();+ });+});++describe('nodeEmphasis', () => {+ const mainline = resolveMainline(graphWith({ edgeIds: ['e1'], nodeIds: ['t1', 't2'] }));++ it('highlights marked nodes and mutes the rest', () => {+ expect(nodeEmphasis(mainline, { id: 't1', kind: 'task' })).toBe('mainline');+ expect(nodeEmphasis(mainline, { id: 't3', kind: 'task' })).toBe('muted');+ expect(nodeEmphasis(mainline, { id: 'f9', kind: 'finding' })).toBe('muted');+ });++ it('keeps the root question readable', () => {+ expect(nodeEmphasis(mainline, { id: 'p', kind: 'problem' })).toBeUndefined();+ });++ it('highlights a collapsed experiment whose members are on the mainline', () => {+ expect(nodeEmphasis(mainline, { id: 'x1', kind: 'experiment' }, ['t2'])).toBe('mainline');+ expect(nodeEmphasis(mainline, { id: 'x1', kind: 'experiment' }, ['t3'])).toBe('muted');+ });++ it('changes nothing when no mainline was marked', () => {+ expect(nodeEmphasis(undefined, { id: 't3', kind: 'task' })).toBeUndefined();+ });+});++describe('edgeEmphasis', () => {+ const mainline = resolveMainline(graphWith({ edgeIds: ['e1'], nodeIds: ['t1', 't2'] }));+ const isCard = (id: string) => mainline!.nodeIds.has(id);++ it('highlights only the marked edges, projected ones included by their goal edge id', () => {+ expect(+ edgeEmphasis(mainline, { id: 'e1', sourceNodeId: 'x1', targetNodeId: 't1' }, isCard),+ ).toBe('mainline');+ // Both ends on the mainline is not enough for a real edge: the report chose which to mark.+ expect(+ edgeEmphasis(mainline, { id: 'e2', sourceNodeId: 't1', targetNodeId: 't2' }, isCard),+ ).toBe('muted');+ });++ it('highlights a bridge through hidden kinds when both of its cards are on the mainline', () => {+ expect(+ edgeEmphasis(+ mainline,+ { bridge: true, id: 'bridge:t1:t2', sourceNodeId: 't1', targetNodeId: 't2' },+ isCard,+ ),+ ).toBe('mainline');+ expect(+ edgeEmphasis(+ mainline,+ { bridge: true, id: 'bridge:t1:t3', sourceNodeId: 't1', targetNodeId: 't3' },+ isCard,+ ),+ ).toBe('muted');+ });++ it('changes nothing when no mainline was marked', () => {+ expect(+ edgeEmphasis(undefined, { id: 'e1', sourceNodeId: 't1', targetNodeId: 't2' }, () => false),+ ).toBeUndefined();+ });+});++describe('isNodeDimmed', () => {+ it('mutes cards off the mainline and blocked cards', () => {+ expect(isNodeDimmed({ blocked: false, emphasis: 'muted', highlighted: false })).toBe(true);+ expect(isNodeDimmed({ blocked: true, emphasis: undefined, highlighted: false })).toBe(true);+ expect(isNodeDimmed({ blocked: false, emphasis: 'mainline', highlighted: false })).toBe(false);+ expect(isNodeDimmed({ blocked: false, emphasis: undefined, highlighted: false })).toBe(false);+ });++ it('keeps a highlighted detour readable even though it is off the mainline', () => {+ // A chapter's local map calls its detours out; the mainline mark must not fade them.+ expect(isNodeDimmed({ blocked: false, emphasis: 'muted', highlighted: true })).toBe(false);+ });+});diff --git a/src/features/AgentGoals/ProcessControl/Graph/mainline.ts b/src/features/AgentGoals/ProcessControl/Graph/mainline.tsnew file mode 100644index 00000000000..ed8865cd3f3--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/Graph/mainline.ts@@ -0,0 +1,98 @@+import type { GoalGraphNode } from '@lobechat/types';++import type { GoalGraphView } from '../goalGraphViewModel';++/**+ * The mainline the wrap-up report marked: the path that actually carried the+ * Goal to its result. It rides on the newest report version, so a rewritten+ * storyline redraws it and a Goal without a report keeps the plain map.+ */+export interface Mainline {+ edgeIds: ReadonlySet<string>;+ nodeIds: ReadonlySet<string>;+}++/** How a card or a line reads against the mainline; `undefined` leaves it as it was. */+export type MainlineEmphasis = 'mainline' | 'muted' | undefined;++export const resolveMainline = (+ graph: Pick<GoalGraphView, 'byId' | 'report'>,+): Mainline | undefined => {+ const mark = graph.report?.latest?.metadata.mainline;+ if (!mark) return undefined;+ // A node deleted since the report was written must not leave the whole map muted.+ const nodeIds = new Set(mark.nodeIds.filter((id) => graph.byId[id]));+ if (nodeIds.size === 0) return undefined;+ return { edgeIds: new Set(mark.edgeIds), nodeIds };+};++/**+ * A card is on the mainline when it was marked, or when it is an experiment+ * whose members were — collapsed, the experiment stands in for them. The root+ * question is the anchor every path starts from, so it is never muted.+ */+export const nodeEmphasis = (+ mainline: Mainline | undefined,+ node: Pick<GoalGraphNode, 'id' | 'kind'>,+ members: Iterable<string> = [],+): MainlineEmphasis => {+ if (!mainline) return undefined;+ if (mainline.nodeIds.has(node.id)) return 'mainline';+ for (const member of members) if (mainline.nodeIds.has(member)) return 'mainline';+ if (node.kind === 'problem') return undefined;+ return 'muted';+};++/**+ * Whether a card steps back on the map: still blocked before it started, or+ * off a marked mainline — unless the host is calling it out on purpose (a+ * chapter's detour on the report's local map), which must stay readable.+ */+export const isNodeDimmed = ({+ blocked,+ emphasis,+ highlighted,+}: {+ blocked: boolean;+ emphasis: MainlineEmphasis;+ highlighted: boolean;+}): boolean => blocked || (emphasis === 'muted' && !highlighted);++/**+ * A goal edge is on the mainline when the report marked it — a projected edge+ * keeps its goal edge id, so it follows its original. A bridge drawn through+ * hidden kinds has no id of its own: it is on the mainline when both of the+ * cards it joins are.+ */+export const edgeEmphasis = (+ mainline: Mainline | undefined,+ edge: { bridge?: boolean; id: string; sourceNodeId: string; targetNodeId: string },+ isMainlineCard: (id: string) => boolean,+): MainlineEmphasis => {+ if (!mainline) return undefined;+ const on = edge.bridge+ ? isMainlineCard(edge.sourceNodeId) && isMainlineCard(edge.targetNodeId)+ : mainline.edgeIds.has(edge.id);+ return on ? 'mainline' : 'muted';+};++/** How a line is drawn: {@link MainlineEmphasis}, or part of a called-out detour. */+export type EdgeTone = MainlineEmphasis | 'detour';++/**+ * The mainline keeps its own line. Any other line touching a card the host+ * calls out — a chapter's detour — is part of that detour, and reads as one+ * instead of stepping back with the rest of the off-mainline map.+ */+export const edgeTone = (+ mainline: Mainline | undefined,+ edge: Parameters<typeof edgeEmphasis>[1],+ isMainlineCard: (id: string) => boolean,+ highlightedIds: ReadonlySet<string> = new Set(),+): EdgeTone => {+ const emphasis = edgeEmphasis(mainline, edge, isMainlineCard);+ if (emphasis === 'mainline') return emphasis;+ if (highlightedIds.has(edge.sourceNodeId) || highlightedIds.has(edge.targetNodeId))+ return 'detour';+ return emphasis;+};diff --git a/src/features/AgentGoals/ProcessControl/RequestChangesModal.tsx b/src/features/AgentGoals/ProcessControl/RequestChangesModal.tsxnew file mode 100644index 00000000000..8673265f04e--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/RequestChangesModal.tsx@@ -0,0 +1,83 @@+'use client';++import { Flexbox, TextArea } from '@lobehub/ui';+import {+ Button,+ createModal,+ type ModalInstance,+ Text,+ useModalContext,+} from '@lobehub/ui/base-ui';+import { cssVar } from 'antd-style';+import { t } from 'i18next';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++/**+ * 提出修改 on a Goal's delivery. Unlike the acceptance page's reject, the+ * feedback is required: it is the only instruction the Agent gets for the+ * next round, and an empty "please change it" hands over nothing to act on.+ */++interface RequestChangesContentProps {+ /** Send the feedback; resolve true to close. */+ onConfirm: (comment: string) => Promise<boolean>;+}++const RequestChangesContent = ({ onConfirm }: RequestChangesContentProps) => {+ const { t } = useTranslation('chat');+ const { close } = useModalContext();+ const [comment, setComment] = useState('');+ const [touched, setTouched] = useState(false);+ const [loading, setLoading] = useState(false);+ const empty = comment.trim().length === 0;++ const submit = async () => {+ setTouched(true);+ if (empty) return;+ setLoading(true);+ try {+ if (await onConfirm(comment.trim())) close();+ } finally {+ setLoading(false);+ }+ };++ return (+ <Flexbox gap={12}>+ <Text fontSize={13} type={'secondary'}>+ {t('goalProcess.result.signOff.changes.description')}+ </Text>+ <TextArea+ autoFocus+ autoSize={{ maxRows: 8, minRows: 4 }}+ placeholder={t('goalProcess.result.signOff.changes.placeholder')}+ status={touched && empty ? 'error' : undefined}+ value={comment}+ onChange={(event) => setComment(event.target.value)}+ />+ {touched && empty && (+ <Text fontSize={12} style={{ color: cssVar.colorError }}>+ {t('goalProcess.result.signOff.changes.required')}+ </Text>+ )}+ <Flexbox horizontal gap={8} justify={'flex-end'}>+ <Button disabled={loading} onClick={close}>+ {t('goalProcess.result.signOff.cancel')}+ </Button>+ <Button loading={loading} type={'primary'} onClick={submit}>+ {t('goalProcess.result.signOff.changes.submit')}+ </Button>+ </Flexbox>+ </Flexbox>+ );+};++export const openRequestChangesModal = (props: RequestChangesContentProps): ModalInstance =>+ createModal({+ content: <RequestChangesContent {...props} />,+ footer: null,+ maskClosable: true,+ title: t('goalProcess.result.signOff.changes.title', { ns: 'chat' }),+ width: 'min(90vw, 520px)',+ });diff --git a/src/features/AgentGoals/ProcessControl/ResultDeliverables.tsx b/src/features/AgentGoals/ProcessControl/ResultDeliverables.tsxnew file mode 100644index 00000000000..3feccf31955--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/ResultDeliverables.tsx@@ -0,0 +1,418 @@+'use client';++import { Center, Flexbox, Icon, Markdown } from '@lobehub/ui';+import { ActionIcon, Button, Input, Segmented, Skeleton, Tag, Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { ArrowRight, PackageOpen, SearchIcon, SearchX, X } from 'lucide-react';+import { useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useActivityTime } from '@/hooks/useActivityTime';+import { useClientDataSWR } from '@/libs/swr';+import { portalKeys } from '@/libs/swr/keys';+import { documentService } from '@/services/document';++import {+ buildDeliverables,+ type DeliverableItem,+ type DeliverableType,+ deliverableTypeCounts,+ filterDeliverables,+ groupDeliverables,+ MANY_DELIVERABLES,+} from './deliverableList';+import DeliverableReader from './DeliverableReader';+import { CitationMark, deliverableIconOf, deliverableTitleOf } from './deliverableVisuals';+import type { GoalGraphView } from './goalGraphViewModel';+import { SectionTitle } from './GoalResultFollowUps';+import type { CriterionOutcome } from './goalResultState';++/**+ * 交付物 on the 结果交付 tab — everything the Goal persisted, in one place.+ *+ * The main deliverable (the document the work wrote) leads as a card with the+ * start of its text; every other artifact is a row naming the task that+ * produced it, when, and whether acceptance evidence cites it. A long list+ * grows the tools a long list needs — grouping by task, a type filter and+ * search — and a short one stays a plain list. Any row, or 逐一查看, opens the+ * full-screen reader to page through them in order.+ */++const styles = createStaticStyles(({ css }) => ({+ card: css`+ overflow: hidden;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadiusLG};+ background: ${cssVar.colorBgContainer};+ `,+ excerpt: css`+ pointer-events: none;+ overflow: hidden;+ max-height: 148px;++ mask-image: linear-gradient(to bottom, #000 55%, transparent);+ `,+ groupTitle: css`+ padding-block: 12px 4px;+ padding-inline: 12px;+ `,+ primary: css`+ cursor: pointer;++ display: flex;+ flex-direction: column;+ gap: 12px;++ width: 100%;+ padding: 16px;+ border: none;++ text-align: start;++ background: none;++ &:hover {+ background: ${cssVar.colorFillQuaternary};+ }++ &:focus-visible {+ outline: 2px solid ${cssVar.colorPrimary};+ outline-offset: -2px;+ }+ `,+ row: css`+ cursor: pointer;++ display: flex;+ gap: 12px;+ align-items: center;++ width: 100%;+ padding-block: 10px;+ padding-inline: 12px;+ border: none;++ text-align: start;++ background: none;++ &:hover {+ background: ${cssVar.colorFillQuaternary};+ }++ &:focus-visible {+ outline: 2px solid ${cssVar.colorPrimary};+ outline-offset: -2px;+ }+ `,+}));++const ProducerAndTime = ({ item }: { item: DeliverableItem }) => {+ const { t } = useTranslation('chat');+ const { text, title } = useActivityTime(item.artifact.createdAt);+ return (+ <Text ellipsis fontSize={12} title={title} type={'secondary'}>+ {[+ item.producerTitle &&+ t('goalProcess.result.deliverables.producedBy', { title: item.producerTitle }),+ text,+ ]+ .filter(Boolean)+ .join(' · ')}+ </Text>+ );+};++const DeliverableRow = ({ item, onOpen }: { item: DeliverableItem; onOpen: () => void }) => {+ const { t } = useTranslation('chat');+ return (+ <button+ className={styles.row}+ data-testid={'goal-deliverable-row'}+ type={'button'}+ onClick={onOpen}+ >+ <Icon color={cssVar.colorTextSecondary} icon={deliverableIconOf(item.artifact)} size={18} />+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>+ <Text ellipsis weight={500}>+ {deliverableTitleOf(item.artifact, t('goalProcess.deliverables.untitled'))}+ </Text>+ <ProducerAndTime item={item} />+ </Flexbox>+ <CitationMark item={item} />+ </button>+ );+};++const PrimaryExcerpt = ({ documentId }: { documentId: string }) => {+ const { data: document, isLoading } = useClientDataSWR(+ portalKeys.documentHeader(documentId),+ () => documentService.getDocumentById(documentId),+ );+ if (isLoading)+ return (+ <Flexbox gap={8}>+ <Skeleton height={14} radius={4} />+ <Skeleton height={14} radius={4} width={'80%'} />+ <Skeleton height={14} radius={4} width={'60%'} />+ </Flexbox>+ );+ // The card already names the document; its own leading H1 would repeat it.+ const excerpt = document?.content?.replace(/^\s*#\s[^\n]*\n+/, '');+ if (!excerpt) return null;+ return (+ <div aria-hidden className={styles.excerpt}>+ <Markdown fontSize={13} variant={'chat'}>+ {excerpt}+ </Markdown>+ </div>+ );+};++const PrimaryCard = ({+ item,+ loading,+ onOpen,+}: {+ item: DeliverableItem;+ loading: boolean;+ onOpen: () => void;+}) => {+ const { t } = useTranslation('chat');+ const { text, title } = useActivityTime(item.artifact.createdAt);+ return (+ <div className={styles.card}>+ <button+ className={styles.primary}+ data-testid={'goal-deliverable-primary'}+ type={'button'}+ onClick={onOpen}+ >+ <Flexbox horizontal align={'center'} gap={8}>+ <Tag color={'blue'}>{t('goalProcess.result.deliverables.primary')}</Tag>+ <Text ellipsis fontSize={15} weight={600}>+ {deliverableTitleOf(item.artifact, t('goalProcess.deliverables.untitled'))}+ </Text>+ </Flexbox>+ {item.artifact.resourceId && <PrimaryExcerpt documentId={item.artifact.resourceId} />}+ <Text fontSize={12} title={title} type={'secondary'}>+ {[+ item.producerTitle &&+ t('goalProcess.result.deliverables.producedBy', { title: item.producerTitle }),+ text,+ loading+ ? undefined+ : item.citedBy.length > 0+ ? t('goalProcess.result.deliverables.citedCount', { count: item.citedBy.length })+ : t('goalProcess.result.deliverables.uncited'),+ ]+ .filter(Boolean)+ .join(' · ')}+ </Text>+ </button>+ </div>+ );+};++const LoadingRows = () => (+ <Flexbox className={styles.card} data-testid={'goal-deliverables-loading'} gap={14} padding={16}>+ {[0, 1, 2].map((key) => (+ <Flexbox horizontal align={'center'} gap={12} key={key}>+ <Skeleton height={18} radius={4} width={18} />+ <Flexbox flex={1} gap={6}>+ <Skeleton height={14} radius={4} width={'45%'} />+ <Skeleton height={12} radius={4} width={'30%'} />+ </Flexbox>+ </Flexbox>+ ))}+ </Flexbox>+);++const EmptyState = () => {+ const { t } = useTranslation('chat');+ return (+ <Center className={styles.card} data-testid={'goal-deliverables-empty'} gap={8} padding={32}>+ <Icon color={cssVar.colorTextQuaternary} icon={PackageOpen} size={28} />+ <Text weight={600}>{t('goalProcess.result.deliverables.empty.title')}</Text>+ <Text align={'center'} fontSize={13} style={{ maxWidth: 420 }} type={'secondary'}>+ {t('goalProcess.result.deliverables.empty.description')}+ </Text>+ </Center>+ );+};++const TYPE_ORDER = ['document', 'file', 'external'] as const;++interface ResultDeliverablesProps {+ graph: GoalGraphView;+ /** Citation marks read the acceptance bundle; until it lands they are unknown. */+ loading: boolean;+ outcomes: CriterionOutcome[];+ primaryResourceId?: string;+}++const ResultDeliverables = ({+ graph,+ loading,+ outcomes,+ primaryResourceId,+}: ResultDeliverablesProps) => {+ const { t } = useTranslation('chat');+ const [readerIndex, setReaderIndex] = useState<number>();+ const [type, setType] = useState<DeliverableType | 'all'>('all');+ const [query, setQuery] = useState('');++ const items = useMemo(+ () =>+ buildDeliverables({+ artifacts: graph.artifacts,+ outcomes,+ primaryResourceId,+ titleOf: (nodeId) => graph.byId[nodeId]?.node.title,+ }),+ [graph.artifacts, graph.byId, outcomes, primaryResourceId],+ );++ const primary = items[0]?.primary ? items[0] : undefined;+ const rest = primary ? items.slice(1) : items;+ const many = rest.length >= MANY_DELIVERABLES;+ const visible = many ? filterDeliverables(rest, { query, type }) : rest;+ const groups = many ? groupDeliverables(visible) : [{ items: visible }];+ const counts = deliverableTypeCounts(rest);+ const open = (item: DeliverableItem) => setReaderIndex(items.indexOf(item));++ const title = (+ <SectionTitle+ extra={+ items.length > 0 && (+ <Button icon={ArrowRight} size={'small'} onClick={() => setReaderIndex(0)}>+ {t('goalProcess.result.deliverables.viewAll', { count: items.length })}+ </Button>+ )+ }+ >+ {items.length > 0+ ? t('goalProcess.result.deliverables.titleWithCount', { count: items.length })+ : t('goalProcess.deliverables.title')}+ </SectionTitle>+ );++ if (items.length === 0)+ return (+ <Flexbox gap={12}>+ {title}+ <EmptyState />+ </Flexbox>+ );++ return (+ <Flexbox data-testid={'goal-result-deliverables'} gap={12}>+ {title}+ {primary && <PrimaryCard item={primary} loading={loading} onOpen={() => open(primary)} />}+ {many && (+ <Flexbox horizontal align={'center'} gap={12} wrap={'wrap'}>+ <Segmented+ size={'small'}+ value={type}+ options={[+ {+ label: `${t('goalProcess.result.deliverables.filter.all')} ${rest.length}`,+ value: 'all',+ },+ ...TYPE_ORDER.filter((key) => counts.has(key)).map((key) => ({+ label: `${t(`goalProcess.result.deliverables.filter.${key}` as const)} ${counts.get(key)}`,+ value: key,+ })),+ ]}+ onChange={(value) => setType(value as DeliverableType | 'all')}+ />+ <Input+ aria-label={t('goalProcess.result.deliverables.search')}+ data-testid={'goal-deliverables-search'}+ placeholder={t('goalProcess.result.deliverables.search')}+ prefix={<Icon icon={SearchIcon} size={14} />}+ size={'small'}+ style={{ width: 240 }}+ value={query}+ suffix={+ query && (+ <ActionIcon+ icon={X}+ size={'small'}+ title={t('goalProcess.result.deliverables.clearFilter')}+ onClick={() => setQuery('')}+ />+ )+ }+ onChange={(event) => setQuery(event.target.value)}+ />+ </Flexbox>+ )}+ {loading ? (+ <LoadingRows />+ ) : visible.length === 0 ? (+ rest.length > 0 && (+ <Center+ className={styles.card}+ data-testid={'goal-deliverables-no-match'}+ gap={8}+ padding={24}+ >+ <Icon color={cssVar.colorTextQuaternary} icon={SearchX} size={24} />+ <Text weight={500}>+ {query.trim()+ ? t('goalProcess.result.deliverables.noMatch', { query: query.trim() })+ : t('goalProcess.result.deliverables.noMatchType')}+ </Text>+ <Button+ size={'small'}+ type={'text'}+ onClick={() => {+ setQuery('');+ setType('all');+ }}+ >+ {t('goalProcess.result.deliverables.clearFilter')}+ </Button>+ </Center>+ )+ ) : (+ rest.length > 0 && (+ <Flexbox className={styles.card} paddingBlock={4}>+ {groups.map((group) => (+ <Flexbox key={group.nodeId ?? 'rest'}>+ {groups.length > 1 && (+ <Text+ className={styles.groupTitle}+ data-testid={'goal-deliverables-group'}+ fontSize={12}+ type={'secondary'}+ >+ {`${group.title ?? t('goalProcess.result.deliverables.otherTasks')} · ${group.items.length}`}+ </Text>+ )}+ {group.items.map((item) => (+ <DeliverableRow+ item={item}+ key={item.artifact.workVersionId}+ onOpen={() => open(item)}+ />+ ))}+ </Flexbox>+ ))}+ </Flexbox>+ )+ )}+ {readerIndex !== undefined && (+ <DeliverableReader+ index={readerIndex}+ items={items}+ onClose={() => setReaderIndex(undefined)}+ onIndexChange={setReaderIndex}+ />+ )}+ </Flexbox>+ );+};++export default ResultDeliverables;diff --git a/src/features/AgentGoals/ProcessControl/ResultTrail.test.tsx b/src/features/AgentGoals/ProcessControl/ResultTrail.test.tsxnew file mode 100644index 00000000000..2edea68681b--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/ResultTrail.test.tsx@@ -0,0 +1,187 @@+/**+ * @vitest-environment happy-dom+ */+import { GOAL_REPORT_TASK_TITLE } from '@lobechat/const/goal';+import type { GoalReportMetadata, GoalReportState } from '@lobechat/types';+import { fireEvent, render, screen } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { GoalGraphView, GoalNodeView } from './goalGraphViewModel';+import ResultTrail from './ResultTrail';++const chatState = vi.hoisted(() => ({+ openDocument: vi.fn(),+ openGoalReport: vi.fn(),+ openGoalReportChapter: vi.fn(),+}));++vi.mock('@/store/chat', () => ({+ useChatStore: (selector: (state: typeof chatState) => unknown) => selector(chatState),+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, options?: { count?: number }) =>+ options?.count === undefined ? key : `${key}:${options.count}`,+ }),+}));++vi.mock('@lobehub/ui', async (importOriginal) => {+ const actual = await importOriginal<Record<string, unknown>>();+ return {+ ...actual,+ Markdown: ({ children }: { children: string }) => <div>{children}</div>,+ Tooltip: ({ children, title }: { children: React.ReactNode; title: React.ReactNode }) => (+ <>+ {children}+ <div data-testid={'tooltip'}>{title}</div>+ </>+ ),+ };+});++const at = (minutes: number) => new Date(Date.UTC(2026, 8, 28, 0, minutes));++const view = (id: string, kind: string, minutes: number, extra: object = {}) =>+ ({+ attempts: [],+ node: {+ createdAt: at(minutes),+ id,+ kind,+ resolvedAt: at(minutes),+ status: 'resolved',+ title: id,+ updatedAt: at(minutes),+ },+ ...extra,+ }) as unknown as GoalNodeView;++const taskA = view('Collect sources', 'task', 1);+const wrapUp = view('wrap', 'task', 9);+(wrapUp.node as { title: string }).title = GOAL_REPORT_TASK_TITLE;+const finding = view('Sources agree', 'finding', 2, { producedBy: taskA.node });+const deadEnd = view('Scrape old API', 'task', 3);++const deliverable = {+ createdAt: at(4),+ identifier: null,+ nodeId: 'Collect sources',+ resourceId: 'docs_1',+ title: 'Source list',+ type: 'document',+ url: null,+ workId: 'wk-1',+ workVersionId: 'v-1',+};++const metadata = {+ chapters: [+ {+ detours: [+ {+ kind: 'dead_end',+ lesson: 'Check the API first',+ nodeIds: ['Scrape old API'],+ reason: 'The old API was retired',+ title: 'Scraping the old API',+ },+ ],+ findingIds: ['Sources agree'],+ narrative: 'We began by gathering every source.',+ nodeIds: ['Collect sources'],+ title: 'Gathering the sources',+ workVersionIds: ['v-1'],+ },+ ],+ graphCursor: 'evt-1',+ headline: 'Shipped the brief',+ nextSteps: [],+} satisfies GoalReportMetadata;++const graph = (report?: Partial<GoalReportState>): GoalGraphView =>+ ({+ artifacts: [deliverable],+ byId: {+ 'Collect sources': taskA,+ 'Scrape old API': deadEnd,+ 'Sources agree': finding,+ 'wrap': wrapUp,+ },+ findings: [finding],+ goal: { id: 'goal-1', status: 'achieved' },+ nodes: [taskA, deadEnd, finding, wrapUp],+ report: report && {+ dispatch: { acceptanceKey: 'k', dispatchedAt: '', nodeId: 'wrap', trigger: 'accepted' },+ status: 'completed',+ ...report,+ },+ }) as unknown as GoalGraphView;++const latest = {+ content: '# Full report',+ createdAt: at(10),+ metadata,+ version: 1,+ workId: 'wk-report',+ workVersionId: 'v-report',+};++beforeEach(() => {+ vi.clearAllMocks();+});++describe('ResultTrail', () => {+ /**+ * The 探索过程 section follows the wrap-up run as the graph poll brings each+ * snapshot: organizing → storyline, with no reload in between; and back to+ * the derived trail when the run fails.+ */+ it('switches from the organizing state to the storyline as the report lands', () => {+ const { rerender } = render(+ <ResultTrail graph={graph({ status: 'running' })} onSelect={vi.fn()} />,+ );++ expect(screen.getByText('goalProcess.result.story.pending')).toBeTruthy();+ expect(screen.queryByText('Collect sources')).toBeNull();++ rerender(<ResultTrail graph={graph({ latest, status: 'completed' })} onSelect={vi.fn()} />);++ expect(screen.queryByText('goalProcess.result.story.pending')).toBeNull();+ expect(screen.getByText('Gathering the sources')).toBeTruthy();+ expect(screen.getByText('We began by gathering every source.')).toBeTruthy();+ // The chapter's conclusion and deliverable are its list items.+ expect(screen.getByText('Sources agree')).toBeTruthy();+ expect(screen.getByText('Source list')).toBeTruthy();+ });++ it('shows the detour hint with its reason and opens the chapter map', () => {+ render(<ResultTrail graph={graph({ latest, status: 'completed' })} onSelect={vi.fn()} />);++ const hint = screen.getByRole('button', { name: /goalProcess.result.story.detours:1/ });+ expect(screen.getByTestId('tooltip').textContent).toContain('The old API was retired');++ fireEvent.click(hint);+ expect(chatState.openGoalReportChapter).toHaveBeenCalledWith('goal-1', 0);+ });++ it('opens the full report beside the page', () => {+ render(<ResultTrail graph={graph({ latest, status: 'completed' })} onSelect={vi.fn()} />);++ fireEvent.click(screen.getByRole('button', { name: /goalProcess.result.story.readReport/ }));+ expect(chatState.openGoalReport).toHaveBeenCalledWith('goal-1');+ });++ it('falls back to the derived trail when the wrap-up failed or never ran', () => {+ for (const snapshot of [graph({ status: 'failed' }), graph()]) {+ const { unmount } = render(<ResultTrail graph={snapshot} onSelect={vi.fn()} />);++ expect(screen.queryByText('goalProcess.result.story.pending')).toBeNull();+ expect(screen.queryByText('Gathering the sources')).toBeNull();+ // The derived step is the task itself; the wrap-up Task is not a step.+ expect(screen.getByText('Collect sources')).toBeTruthy();+ expect(screen.queryByText(GOAL_REPORT_TASK_TITLE)).toBeNull();+ unmount();+ }+ });+});diff --git a/src/features/AgentGoals/ProcessControl/ResultTrail.tsx b/src/features/AgentGoals/ProcessControl/ResultTrail.tsxnew file mode 100644index 00000000000..8dc899d6b80--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/ResultTrail.tsx@@ -0,0 +1,655 @@+'use client';++import { Flexbox, Icon, Markdown, Tooltip } from '@lobehub/ui';+import { Button, Skeleton, Spin, Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import {+ BookOpen,+ ChevronRight,+ ExternalLink,+ FileDown,+ FileText,+ GitBranch,+ type LucideIcon,+} from 'lucide-react';+import { type ReactNode, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useActivityTime } from '@/hooks/useActivityTime';+import { useChatStore } from '@/store/chat';+import { shinyTextStyles } from '@/styles';++import { coordinatorNodeTitleKey } from './coordinatorCopy';+import { openTargetOf, useOpenGoalArtifact } from './Deliverables';+import type { GoalArtifactView, GoalGraphView, GoalNodeView } from './goalGraphViewModel';+import {+ buildResultTrail,+ buildStoryChapters,+ resultTrailSource,+ type ResultTrailStep,+ type StoryChapterView,+} from './goalResultState';+import { type MainlineEmphasis, nodeEmphasis, resolveMainline } from './Graph/mainline';+import { KIND_COLOR, KIND_ICON } from './shared';++/**+ * 探索过程 — the audit trail under the delivered document.+ *+ * Read top-down, one layer at a time: the document above is the answer; each+ * stage here is a piece of the way there with the conclusions it reached and+ * the files it wrote; a conclusion expands into its evidence.+ *+ * Once the wrap-up agent has written the Goal report, the stages are its+ * chapters — titled, narrated, and honest about the detours taken, each of+ * which opens the chapter's local map beside the page. While that report is+ * being written the section says so; without one (or when the run failed) it+ * falls back to the trail `buildResultTrail` derives per task.+ */++const styles = createStaticStyles(({ css }) => ({+ arrow: css`+ flex: none;+ color: ${cssVar.colorTextQuaternary};+ transition: transform 0.2s;+ `,+ arrowOpen: css`+ transform: rotate(90deg);+ `,+ /** Aligned with the item title: tile (32) + gap (12) + row padding (12). */+ evidence: css`+ padding-block: 0 12px;+ padding-inline: 56px 12px;+ `,+ /** One stage's outputs, framed as a single list like the frontier's. */+ list: css`+ overflow: hidden;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadius};+ background: ${cssVar.colorBgContainer};++ /* Outranks the row's own "border: none", which would otherwise erase it. */+ & > :not(:first-child) {+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};+ }+ `,+ row: css`+ width: 100%;+ padding-block: 10px;+ padding-inline: 12px;+ border: none;++ text-align: start;++ background: none;+ `,+ rowOpenable: css`+ cursor: pointer;++ &:hover {+ background: ${cssVar.colorFillQuaternary};+ }++ &:focus-visible {+ outline: 2px solid ${cssVar.colorPrimary};+ outline-offset: -2px;+ }+ `,+ /** The rail ties the numbered stages into one sequence. */+ rail: css`+ position: relative;+ flex: none;+ width: 24px;++ &::after {+ content: '';++ position: absolute;+ inset-block: 30px 0;+ inset-inline-start: 11px;++ width: 1px;++ background: ${cssVar.colorBorderSecondary};+ }+ `,+ railLast: css`+ &::after {+ display: none;+ }+ `,+ stageNumber: css`+ display: flex;+ align-items: center;+ justify-content: center;++ width: 24px;+ height: 24px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: 50%;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;+ color: ${cssVar.colorTextSecondary};++ background: ${cssVar.colorBgContainer};+ `,+ /** Same colour as the mainline on the exploration map, so the two read as one path. */+ stageMainline: css`+ border-color: ${cssVar.colorPrimary};+ color: ${cssVar.colorPrimary};+ `,+ mainlineTag: css`+ flex: none;+ font-size: 12px;+ color: ${cssVar.colorPrimary};+ `,+ stepMuted: css`+ opacity: 0.55;+ `,+ detour: css`+ cursor: pointer;++ display: inline-flex;+ flex: none;+ gap: 4px;+ align-items: center;++ padding-block: 2px;+ padding-inline: 8px;+ border: 1px dashed ${cssVar.colorWarningBorder};+ border-radius: 999px;++ font-size: 12px;+ color: ${cssVar.colorWarningText};++ background: ${cssVar.colorWarningBg};++ &:hover {+ border-style: solid;+ }++ &:focus-visible {+ outline: 2px solid ${cssVar.colorPrimary};+ outline-offset: 2px;+ }+ `,+ narrative: css`+ color: ${cssVar.colorTextSecondary};+ `,+ stageTitle: css`+ cursor: pointer;++ &:hover {+ color: ${cssVar.colorPrimary};+ }+ `,+ tile: css`+ display: flex;+ flex: none;+ align-items: center;+ justify-content: center;++ width: 32px;+ height: 32px;+ border-radius: ${cssVar.borderRadius};+ `,+ time: css`+ flex: none;+ min-width: 60px;+ text-align: end;+ `,+}));++/** First line of a finding's evidence, as the item's one-line summary. */+const summaryOf = (description?: string | null) =>+ description+ ?.split('\n')+ .map((line) => line.replace(/^[#>*\-\s]+/, '').trim())+ .find(Boolean);++const TrailItem = ({+ icon,+ meta,+ onClick,+ subtitle,+ title,+ tone,+ trailing,+}: {+ icon: LucideIcon;+ meta?: ReactNode;+ onClick?: () => void;+ subtitle?: ReactNode;+ title: ReactNode;+ tone: { line: string; soft: string };+ trailing?: ReactNode;+}) => (+ <Flexbox+ horizontal+ align={'center'}+ as={onClick ? 'button' : 'div'}+ className={cx(styles.row, onClick && styles.rowOpenable)}+ gap={12}+ {...(onClick ? { onClick, type: 'button' as const } : {})}+ >+ <span className={styles.tile} style={{ background: tone.soft }}>+ <Icon color={tone.line} icon={icon} size={16} />+ </span>+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>+ <Text ellipsis weight={500}>+ {title}+ </Text>+ {subtitle && (+ <Text ellipsis fontSize={12} type={'secondary'}>+ {subtitle}+ </Text>+ )}+ </Flexbox>+ {meta}+ {trailing}+ </Flexbox>+);++const TrailFinding = ({ view }: { view: GoalNodeView }) => {+ const { t } = useTranslation('chat');+ const [open, setOpen] = useState(false);+ const description = view.node.description;+ const summary = summaryOf(description);++ return (+ <div>+ <TrailItem+ icon={KIND_ICON.finding}+ title={view.node.title}+ tone={KIND_COLOR.finding}+ // Expanded, the evidence below already says what the summary said.+ subtitle={+ open+ ? undefined+ : summary+ ? `${t('goalProcess.kind.finding')} · ${summary}`+ : t('goalProcess.kind.finding')+ }+ trailing={+ description ? (+ <Icon+ className={cx(styles.arrow, open && styles.arrowOpen)}+ icon={ChevronRight}+ size={14}+ />+ ) : undefined+ }+ onClick={description ? () => setOpen(!open) : undefined}+ />+ {open && description && (+ <div className={styles.evidence}>+ <Markdown fontSize={13} variant={'chat'}>+ {description}+ </Markdown>+ </div>+ )}+ </div>+ );+};++const ARTIFACT_TONE = { line: cssVar.colorTextSecondary, soft: cssVar.colorFillTertiary };++const TrailArtifact = ({+ artifact,+ isDocument,+ onOpen,+}: {+ artifact: GoalArtifactView;+ /** The document already shown in full above — pointed at, not reopened. */+ isDocument: boolean;+ onOpen: (artifact: GoalArtifactView) => void;+}) => {+ const { t } = useTranslation('chat');+ const { text, title } = useActivityTime(artifact.createdAt);+ const openable = !isDocument && !!openTargetOf(artifact);+ const icon =+ artifact.type === 'document' ? FileText : artifact.type === 'file' ? FileDown : ExternalLink;++ return (+ <TrailItem+ icon={icon}+ title={artifact.title || artifact.identifier || t('goalProcess.deliverables.untitled')}+ tone={ARTIFACT_TONE}+ meta={+ <Text className={styles.time} fontSize={12} title={title} type={'secondary'}>+ {text}+ </Text>+ }+ subtitle={+ isDocument+ ? `${t('goalProcess.deliverables.title')} · ${t('goalProcess.result.trail.shownAbove')}`+ : t('goalProcess.deliverables.title')+ }+ onClick={openable ? () => onOpen(artifact) : undefined}+ />+ );+};++const StepTime = ({ view }: { view: GoalNodeView }) => {+ const { text, title } = useActivityTime(view.node.resolvedAt ?? view.node.updatedAt);+ return (+ <Text className={styles.time} fontSize={12} title={title} type={'secondary'}>+ {text}+ </Text>+ );+};++/** One stage of the section: the rail, its number, a header and what it holds. */+const Stage = ({+ children,+ emphasis,+ header,+ index,+ last,+}: {+ children?: ReactNode;+ /** How the stage reads against the report's mainline, as on the exploration map. */+ emphasis?: MainlineEmphasis;+ header: ReactNode;+ index: number;+ last: boolean;+}) => (+ <Flexbox horizontal className={cx(emphasis === 'muted' && styles.stepMuted)} gap={12}>+ <div className={cx(styles.rail, last && styles.railLast)}>+ <span className={cx(styles.stageNumber, emphasis === 'mainline' && styles.stageMainline)}>+ {index + 1}+ </span>+ </div>+ <Flexbox flex={1} gap={10} paddingBlock={'2px 24px'} style={{ minWidth: 0 }}>+ <Flexbox horizontal align={'center'} gap={8} style={{ minHeight: 24 }}>+ {header}+ </Flexbox>+ {children}+ </Flexbox>+ </Flexbox>+);++const TrailStep = ({+ documentId,+ emphasis,+ index,+ last,+ onOpenArtifact,+ onSelect,+ step,+}: {+ documentId?: string;+ emphasis: MainlineEmphasis;+ index: number;+ last: boolean;+ onOpenArtifact: (artifact: GoalArtifactView) => void;+ onSelect: (nodeId: string) => void;+ step: ResultTrailStep;+}) => {+ const { t } = useTranslation('chat');+ const { view } = step;+ const titleKey = view ? coordinatorNodeTitleKey(view) : undefined;+ const title = view+ ? titleKey+ ? t(titleKey as any)+ : view.node.title+ : t('goalProcess.result.trail.unattributed');++ return (+ <Stage+ emphasis={emphasis}+ index={index}+ last={last}+ header={+ <>+ {view ? (+ // The run itself is the deepest layer: open it for the full account.+ <Text+ ellipsis+ className={styles.stageTitle}+ style={{ flex: 1, minWidth: 0 }}+ weight={600}+ onClick={() => onSelect(view.node.id)}+ >+ {title}+ </Text>+ ) : (+ <Text style={{ flex: 1, minWidth: 0 }} type={'secondary'} weight={600}>+ {title}+ </Text>+ )}+ {emphasis === 'mainline' && (+ <span className={styles.mainlineTag}>{t('goalProcess.graph.legend.mainline')}</span>+ )}+ {view && <StepTime view={view} />}+ </>+ }+ >+ <div className={styles.list}>+ {step.findings.map((finding) => (+ <TrailFinding key={finding.node.id} view={finding} />+ ))}+ {step.artifacts.map((artifact) => (+ <TrailArtifact+ artifact={artifact}+ isDocument={!!documentId && artifact.resourceId === documentId}+ key={artifact.workVersionId}+ onOpen={onOpenArtifact}+ />+ ))}+ </div>+ </Stage>+ );+};++const DetourHint = ({+ chapter,+ onOpen,+}: {+ chapter: StoryChapterView['chapter'];+ onOpen: () => void;+}) => {+ const { t } = useTranslation('chat');+ const count = chapter.detours.length;++ return (+ <Tooltip+ title={+ <Flexbox gap={6} style={{ maxWidth: 360 }}>+ {chapter.detours.map((detour, index) => (+ <div key={index}>+ <b>{detour.title}</b>+ {`:${detour.reason}`}+ </div>+ ))}+ <Text fontSize={12} style={{ color: 'inherit', opacity: 0.7 }}>+ {t('goalProcess.result.story.detourOpen')}+ </Text>+ </Flexbox>+ }+ >+ <button className={styles.detour} type={'button'} onClick={onOpen}>+ <Icon icon={GitBranch} size={12} />+ {t('goalProcess.result.story.detours', { count })}+ </button>+ </Tooltip>+ );+};++const StoryChapter = ({+ documentId,+ goalId,+ last,+ onOpenArtifact,+ view,+}: {+ documentId?: string;+ goalId: string;+ last: boolean;+ onOpenArtifact: (artifact: GoalArtifactView) => void;+ view: StoryChapterView;+}) => {+ const openChapter = useChatStore((s) => s.openGoalReportChapter);+ const { chapter } = view;+ const hasItems = view.findings.length > 0 || view.artifacts.length > 0;++ return (+ <Stage+ index={view.index}+ last={last}+ header={+ <>+ <Text ellipsis style={{ flex: 1, minWidth: 0 }} weight={600}>+ {chapter.title}+ </Text>+ {chapter.detours.length > 0 && (+ <DetourHint chapter={chapter} onOpen={() => openChapter(goalId, view.index)} />+ )}+ </>+ }+ >+ <Markdown className={styles.narrative} fontSize={14} variant={'chat'}>+ {chapter.narrative}+ </Markdown>+ {hasItems && (+ <div className={styles.list}>+ {view.findings.map((finding) => (+ <TrailFinding key={finding.node.id} view={finding} />+ ))}+ {view.artifacts.map((artifact) => (+ <TrailArtifact+ artifact={artifact}+ isDocument={!!documentId && artifact.resourceId === documentId}+ key={artifact.workVersionId}+ onOpen={onOpenArtifact}+ />+ ))}+ </div>+ )}+ </Stage>+ );+};++/**+ * The wrap-up agent is still writing. Shaped like the chapters that will+ * replace it — rail, number, a title over its narrative — so nothing jumps when+ * the graph poll brings the storyline in.+ */+const TrailPending = () => {+ const { t } = useTranslation('chat');++ return (+ <Flexbox gap={16}>+ <Flexbox horizontal align={'center'} gap={8} role={'status'}>+ <Spin size={'small'} variant={'network'} />+ <Text className={shinyTextStyles.shinyText} weight={500}>+ {t('goalProcess.result.story.pending')}+ </Text>+ </Flexbox>+ <Text fontSize={12} type={'secondary'}>+ {t('goalProcess.result.story.pendingHint')}+ </Text>+ <Flexbox aria-hidden gap={0}>+ {[0, 1].map((index) => (+ <Stage+ header={<Skeleton height={16} radius={4} width={index === 0 ? '36%' : '28%'} />}+ index={index}+ key={index}+ last={index === 1}+ >+ <Flexbox gap={8}>+ <Skeleton height={14} radius={4} />+ <Skeleton height={14} radius={4} width={'72%'} />+ </Flexbox>+ </Stage>+ ))}+ </Flexbox>+ </Flexbox>+ );+};++interface ResultTrailProps {+ /** The delivered document already rendered above the trail. */+ documentId?: string;+ graph: GoalGraphView;+ onSelect: (nodeId: string) => void;+}++const ResultTrail = ({ documentId, graph, onSelect }: ResultTrailProps) => {+ const { t } = useTranslation('chat');+ const openArtifact = useOpenGoalArtifact();+ const openReport = useChatStore((s) => s.openGoalReport);+ const source = resultTrailSource(graph);+ const title = (+ <Text fontSize={16} weight={600}>+ {t('goalProcess.result.trail.title')}+ </Text>+ );++ if (source.kind === 'pending')+ return (+ <Flexbox gap={16}>+ {title}+ <TrailPending />+ </Flexbox>+ );++ if (source.kind === 'story') {+ const chapters = buildStoryChapters(graph, source.metadata);+ return (+ <Flexbox gap={16}>+ <Flexbox horizontal align={'center'} gap={12} justify={'space-between'}>+ {title}+ {source.report.content?.trim() && (+ <Button+ icon={<Icon icon={BookOpen} />}+ size={'small'}+ onClick={() => openReport(graph.goal.id)}+ >+ {t('goalProcess.result.story.readReport')}+ </Button>+ )}+ </Flexbox>+ <Flexbox gap={0}>+ {chapters.map((chapter, index) => (+ <StoryChapter+ documentId={documentId}+ goalId={graph.goal.id}+ key={index}+ last={index === chapters.length - 1}+ view={chapter}+ onOpenArtifact={openArtifact}+ />+ ))}+ </Flexbox>+ </Flexbox>+ );+ }++ const steps = buildResultTrail(graph);+ if (steps.length === 0) return null;+ // The steps the report's mainline runs through wear the same mark as on the map.+ const mainline = resolveMainline(graph);++ return (+ <Flexbox gap={16}>+ {title}+ <Flexbox gap={0}>+ {steps.map((step, index) => (+ <TrailStep+ documentId={documentId}+ emphasis={step.view ? nodeEmphasis(mainline, step.view.node) : undefined}+ index={index}+ key={step.key}+ last={index === steps.length - 1}+ step={step}+ onOpenArtifact={openArtifact}+ onSelect={onSelect}+ />+ ))}+ </Flexbox>+ </Flexbox>+ );+};++export default ResultTrail;diff --git a/src/features/AgentGoals/ProcessControl/coordinatorCopy.test.ts b/src/features/AgentGoals/ProcessControl/coordinatorCopy.test.tsindex ba440db7e21..5a433888949 100644--- a/src/features/AgentGoals/ProcessControl/coordinatorCopy.test.ts+++ b/src/features/AgentGoals/ProcessControl/coordinatorCopy.test.ts@@ -12,6 +12,8 @@ describe('coordinatorGateKind', () => {it('recognizes the coordinator gate shapes and nothing else', () => {expect(coordinatorGateKind(decision(['retry', 'retire']))).toBe('recoverTask');expect(coordinatorGateKind(decision(['retry', 'fail']))).toBe('goalAcceptance');+ // The terminal acceptance gate also offers abandoning it.+ expect(coordinatorGateKind(decision(['retry', 'retire', 'fail']))).toBe('goalAcceptance');expect(coordinatorGateKind(decision(['option-1', 'assume', 'answer']))).toBe('clarifyGoal');expect(coordinatorGateKind(decision(['approve', 'reject']))).toBeUndefined();expect(coordinatorGateKind(undefined)).toBeUndefined();@@ -62,6 +64,11 @@ describe('coordinatorGateReason', () => {'Goal-level acceptance did not pass. Retry Goal acceptance or fail this Goal?',),).toBe('Goal-level acceptance did not pass');+ expect(+ coordinatorGateReason(+ 'Goal-level acceptance did not pass. Retry Goal acceptance, abandon it, or fail this Goal?',+ ),+ ).toBe('Goal-level acceptance did not pass');});it('returns non-template questions verbatim', () => {@@ -93,6 +100,14 @@ describe('coordinatorReasonCopy', () => {});});+ it('wraps a bare runtime error type in a localized sentence', () => {+ expect(coordinatorReasonCopy('InvalidProviderAPIKey')).toEqual({+ key: 'goalProcess.gate.reason.runError',+ params: { code: 'InvalidProviderAPIKey' },+ });+ expect(coordinatorReasonCopy('Timeout')).toBeUndefined();+ });+it('passes unknown reasons through as undefined so the raw text renders', () => {expect(coordinatorReasonCopy('some future reason')).toBeUndefined();expect(coordinatorReasonCopy(undefined)).toBeUndefined();diff --git a/src/features/AgentGoals/ProcessControl/coordinatorCopy.ts b/src/features/AgentGoals/ProcessControl/coordinatorCopy.tsindex 5b0413365dd..affa45309d5 100644--- a/src/features/AgentGoals/ProcessControl/coordinatorCopy.ts+++ b/src/features/AgentGoals/ProcessControl/coordinatorCopy.ts@@ -25,8 +25,10 @@ export const coordinatorGateKind = (decision?: GoalGraphDecision | null,): CoordinatorGateKind | undefined => {const ids = idsOf(decision);- if (ids.has('retry') && ids.has('retire')) return 'recoverTask';+ // `fail` only ever appears on the terminal acceptance gate, which may also+ // offer `retire` — check it first.if (ids.has('retry') && ids.has('fail')) return 'goalAcceptance';+ if (ids.has('retry') && ids.has('retire')) return 'recoverTask';if (ids.has(GOAL_CLARIFICATION_OPTION.assume) && ids.has(GOAL_CLARIFICATION_OPTION.answer))return 'clarifyGoal';return undefined;@@ -60,6 +62,7 @@ export const coordinatorNodeTitleKey = (view: GoalNodeView): string | undefinedconst QUESTION_TAILS = [/\.?\s*Retry or retire this task node\?$/,/\.?\s*Retry Goal acceptance or fail this Goal\?$/,+ /\.?\s*Retry Goal acceptance, abandon it, or fail this Goal\?$/,];export const coordinatorGateReason = (question?: string | null): string | undefined => {@@ -105,6 +108,14 @@ const REASON_PATTERNS: Array<{pattern:/^Automatic recovery could not (start the next attempt|restart an abandoned operation)$/,},+ {+ // A run that failed outright leaves its runtime error type as the reason+ // (e.g. `InvalidProviderAPIKey`). The code stays visible for support; the+ // sentence around it is the user's language.+ key: 'goalProcess.gate.reason.runError',+ param: 'code',+ pattern: /^([A-Z][a-z0-9]+[A-Z][A-Za-z0-9]*)$/,+ },];export const coordinatorReasonCopy = (reason?: string | null): LocalizedCopyRef | undefined => {diff --git a/src/features/AgentGoals/ProcessControl/deliverableList.test.ts b/src/features/AgentGoals/ProcessControl/deliverableList.test.tsnew file mode 100644index 00000000000..f6fbe1fb2b5--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/deliverableList.test.ts@@ -0,0 +1,151 @@+import { describe, expect, it } from 'vitest';++import {+ buildDeliverables,+ dedupeArtifacts,+ evidenceCites,+ filterDeliverables,+ groupDeliverables,+} from './deliverableList';+import type { GoalArtifactView } from './goalGraphViewModel';+import type { CriterionOutcome } from './goalResultState';++let seq = 0;+const artifact = (patch: Partial<GoalArtifactView> = {}): GoalArtifactView => {+ seq += 1;+ return {+ createdAt: new Date(2026, 8, 1, 0, seq),+ identifier: null,+ nodeId: 'n1',+ relation: 'produced',+ resourceId: null,+ title: `item ${seq}`,+ type: 'document',+ url: null,+ workId: `w${seq}`,+ workVersionId: `v${seq}`,+ ...patch,+ };+};++const outcome = (id: string, evidence: CriterionOutcome['evidence']): CriterionOutcome => ({+ criterion: { id, title: `criterion ${id}` },+ evidence,+ state: 'passed',+});++const titles: Record<string, string> = { n1: '整理定价', n2: '采集截图', n3: '写报告', n4: '访谈' };+const titleOf = (nodeId: string) => titles[nodeId];++describe('dedupeArtifacts', () => {+ it('keeps one row per version, under the node that produced it', () => {+ const produced = artifact({ nodeId: 'n1', workVersionId: 'same' });+ const input = artifact({ nodeId: 'n2', relation: 'input', workVersionId: 'same' });++ expect(dedupeArtifacts([input, produced])).toEqual([produced]);+ expect(dedupeArtifacts([produced, input])).toEqual([produced]);+ });+});++describe('evidenceCites', () => {+ it('matches a document by id, a file by file id or url, and a link by url in the text', () => {+ const doc = artifact({ resourceId: 'docs_1', type: 'document' });+ const file = artifact({ fileId: 'file_1', type: 'file', url: 'https://cdn/x.zip' });+ const link = artifact({ type: 'external', url: 'https://tana.inc/pricing' });++ expect(evidenceCites(doc, { documentId: 'docs_1', id: 'e', type: 'markdown' })).toBe(true);+ expect(evidenceCites(doc, { documentId: 'docs_2', id: 'e', type: 'markdown' })).toBe(false);+ expect(evidenceCites(file, { fileId: 'file_1', id: 'e', type: 'screenshot' })).toBe(true);+ expect(evidenceCites(file, { fileUrl: 'https://cdn/x.zip', id: 'e', type: 'file' })).toBe(true);+ expect(+ evidenceCites(link, { content: 'see https://tana.inc/pricing', id: 'e', type: 'text' }),+ ).toBe(true);+ expect(evidenceCites(link, { content: 'nothing', id: 'e', type: 'text' })).toBe(false);+ });+});++describe('buildDeliverables', () => {+ it('leads with the main deliverable and lists which criteria cite each item', () => {+ const report = artifact({ nodeId: 'n3', resourceId: 'docs_report' });+ const sheet = artifact({ fileId: 'file_sheet', nodeId: 'n1', type: 'file' });+ const items = buildDeliverables({+ artifacts: [sheet, report],+ outcomes: [+ outcome('c1', [{ documentId: 'docs_report', id: 'e1', type: 'markdown' }]),+ outcome('c2', [+ { documentId: 'docs_report', id: 'e2', type: 'markdown' },+ { fileId: 'file_sheet', id: 'e3', type: 'file' },+ ]),+ ],+ primaryResourceId: 'docs_report',+ titleOf,+ });++ expect(items.map((item) => [item.artifact.workVersionId, item.primary])).toEqual([+ [report.workVersionId, true],+ [sheet.workVersionId, false],+ ]);+ expect(items[0].citedBy.map((c) => c.id)).toEqual(['c1', 'c2']);+ expect(items[1].citedBy.map((c) => c.id)).toEqual(['c2']);+ expect(items[0].producerTitle).toBe('写报告');+ });+});++describe('filterDeliverables', () => {+ const items = buildDeliverables({+ artifacts: [+ artifact({ nodeId: 'n1', title: '定价对比表.xlsx', type: 'file' }),+ artifact({ nodeId: 'n1', title: 'Tana 定价公告', type: 'external' }),+ artifact({ nodeId: 'n2', title: 'Tana-pricing.png', type: 'file' }),+ artifact({ nodeId: 'n4', title: '访谈纪要', type: 'document' }),+ ],+ outcomes: [],+ titleOf,+ });++ it('narrows by type', () => {+ expect(filterDeliverables(items, { query: '', type: 'file' })).toHaveLength(2);+ });++ it('searches title and producing task, case-insensitively', () => {+ expect(+ filterDeliverables(items, { query: 'tana', type: 'all' }).map((i) => i.artifact.title),+ ).toEqual(['Tana-pricing.png', 'Tana 定价公告']);+ expect(filterDeliverables(items, { query: '采集', type: 'all' })).toHaveLength(1);+ expect(filterDeliverables(items, { query: '飞书', type: 'all' })).toEqual([]);+ });+});++describe('groupDeliverables', () => {+ it('groups by producing task and folds single-item tasks into one trailing group', () => {+ const items = buildDeliverables({+ artifacts: [+ artifact({ nodeId: 'n1' }),+ artifact({ nodeId: 'n1' }),+ artifact({ nodeId: 'n2' }),+ artifact({ nodeId: 'n2' }),+ artifact({ nodeId: 'n2' }),+ artifact({ nodeId: 'n3' }),+ artifact({ nodeId: 'n4' }),+ ],+ outcomes: [],+ titleOf,+ });++ const groups = groupDeliverables(items);+ expect(groups.map((group) => [group.title, group.items.length])).toEqual([+ ['采集截图', 3],+ ['整理定价', 2],+ [undefined, 2],+ ]);+ });++ it('stays flat when there is nothing to separate', () => {+ const items = buildDeliverables({+ artifacts: [artifact({ nodeId: 'n1' }), artifact({ nodeId: 'n2' })],+ outcomes: [],+ titleOf,+ });+ expect(groupDeliverables(items)).toEqual([{ items }]);+ });+});diff --git a/src/features/AgentGoals/ProcessControl/deliverableList.ts b/src/features/AgentGoals/ProcessControl/deliverableList.tsnew file mode 100644index 00000000000..c2ab2d5b34b--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/deliverableList.ts@@ -0,0 +1,143 @@+import type { GoalArtifactView } from './goalGraphViewModel';+import type { CriterionLike, CriterionOutcome, EvidenceLike } from './goalResultState';++/**+ * The 结果交付 page's deliverables area, as data: every artifact the Goal+ * persisted, once, with who produced it and which acceptance criteria cite it+ * as evidence. The main deliverable leads; the rest follow newest first.+ *+ * Kept pure so the grouping, filtering and citation rules are testable apart+ * from the list and the reader that render them.+ */++export type DeliverableType = GoalArtifactView['type'];++export interface DeliverableItem {+ artifact: GoalArtifactView;+ /** Criteria whose latest-round evidence points at this artifact. */+ citedBy: CriterionLike[];+ primary: boolean;+ producerTitle?: string;+}++export interface DeliverableGroup {+ items: DeliverableItem[];+ /** The producing task node; `undefined` for the merged 其他任务 group. */+ nodeId?: string;+ title?: string;+}++/** From how many non-primary deliverables the list offers grouping, filters and search. */+export const MANY_DELIVERABLES = 6;++const RELATION_RANK: Record<string, number> = { produced: 0 };++/**+ * One row per Work version. A version is linked to every node that touched it+ * — the task that `produced` it and each task that took it as `input` — and a+ * goal-level list must name it once, under the task that made it.+ */+export const dedupeArtifacts = (artifacts: GoalArtifactView[]): GoalArtifactView[] => {+ const byVersion = new Map<string, GoalArtifactView>();+ for (const artifact of artifacts) {+ const seen = byVersion.get(artifact.workVersionId);+ if (+ !seen ||+ (RELATION_RANK[artifact.relation ?? ''] ?? 1) < (RELATION_RANK[seen.relation ?? ''] ?? 1)+ )+ byVersion.set(artifact.workVersionId, artifact);+ }+ return [...byVersion.values()].sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());+};++/**+ * Whether one piece of acceptance evidence points at the artifact: a cited+ * document by id, an uploaded file by file-store id or url, and anything with a+ * url by that url appearing in written evidence.+ */+export const evidenceCites = (artifact: GoalArtifactView, evidence: EvidenceLike): boolean => {+ if (artifact.type === 'document' && artifact.resourceId && evidence.documentId)+ return evidence.documentId === artifact.resourceId;+ if (artifact.fileId && evidence.fileId === artifact.fileId) return true;+ if (!artifact.url) return false;+ return evidence.fileUrl === artifact.url || !!evidence.content?.includes(artifact.url);+};++export const buildDeliverables = ({+ artifacts,+ outcomes,+ primaryResourceId,+ titleOf,+}: {+ artifacts: GoalArtifactView[];+ outcomes: CriterionOutcome[];+ /** The main deliverable's document id — see `pickFinalDeliverable`. */+ primaryResourceId?: string;+ titleOf: (nodeId: string) => string | undefined;+}): DeliverableItem[] => {+ const items = dedupeArtifacts(artifacts).map((artifact) => ({+ artifact,+ citedBy: outcomes+ .filter((outcome) => outcome.evidence.some((item) => evidenceCites(artifact, item)))+ .map((outcome) => outcome.criterion),+ primary:+ !!primaryResourceId &&+ artifact.type === 'document' &&+ artifact.resourceId === primaryResourceId,+ producerTitle: titleOf(artifact.nodeId),+ }));++ // The same document can carry several versions; only the newest is primary.+ const primaryIndex = items.findIndex((item) => item.primary);+ return [+ ...(primaryIndex >= 0 ? [items[primaryIndex]] : []),+ ...items+ .filter((_, index) => index !== primaryIndex)+ .map((item) => (item.primary ? { ...item, primary: false } : item)),+ ];+};++export const deliverableTypeCounts = (items: DeliverableItem[]) => {+ const counts = new Map<DeliverableType, number>();+ for (const { artifact } of items) counts.set(artifact.type, (counts.get(artifact.type) ?? 0) + 1);+ return counts;+};++export const filterDeliverables = (+ items: DeliverableItem[],+ { query, type }: { query: string; type: DeliverableType | 'all' },+): DeliverableItem[] => {+ const needle = query.trim().toLowerCase();+ return items.filter(({ artifact, producerTitle }) => {+ if (type !== 'all' && artifact.type !== type) return false;+ if (!needle) return true;+ return [artifact.title, artifact.identifier, producerTitle].some((text) =>+ text?.toLowerCase().includes(needle),+ );+ });+};++/**+ * Groups by the producing task, newest group first. A task that produced a+ * single deliverable gets no group of its own — a column of one-row groups is+ * noise, not structure — so those rows share one trailing 其他任务 group. When+ * nothing is left to separate (a single group), the list stays flat.+ */+export const groupDeliverables = (items: DeliverableItem[]): DeliverableGroup[] => {+ const byNode = new Map<string, DeliverableItem[]>();+ for (const item of items)+ byNode.set(item.artifact.nodeId, [...(byNode.get(item.artifact.nodeId) ?? []), item]);++ const groups: DeliverableGroup[] = [];+ const rest: DeliverableItem[] = [];+ for (const [nodeId, members] of byNode) {+ if (members.length < 2) {+ rest.push(...members);+ continue;+ }+ groups.push({ items: members, nodeId, title: members[0].producerTitle });+ }+ if (rest.length > 0) groups.push({ items: rest });++ return groups.length > 1 ? groups : [{ items }];+};diff --git a/src/features/AgentGoals/ProcessControl/deliverableVisuals.tsx b/src/features/AgentGoals/ProcessControl/deliverableVisuals.tsxnew file mode 100644index 00000000000..cb0f3d505a8--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/deliverableVisuals.tsx@@ -0,0 +1,79 @@+'use client';++import { Icon } from '@lobehub/ui';+import { Tooltip } from '@lobehub/ui/base-ui';+import { cssVar } from 'antd-style';+import {+ CircleCheck,+ CircleDashed,+ File,+ FileArchive,+ FileImage,+ FileSpreadsheet,+ FileText,+ Link2,+} from 'lucide-react';+import { useTranslation } from 'react-i18next';++import type { DeliverableItem } from './deliverableList';+import type { GoalArtifactView } from './goalGraphViewModel';++const extensionOf = (artifact: GoalArtifactView) =>+ (artifact.title || artifact.identifier || '').match(/\.([\da-z]+)$/i)?.[1]?.toLowerCase();++/** The short format label a file card shows — `ZIP`, `PNG`, `XLSX`… */+export const fileFormatOf = (artifact: GoalArtifactView): string | undefined =>+ extensionOf(artifact)?.toUpperCase() ?? artifact.mimeType?.split('/')[1]?.toUpperCase();++export const isImageArtifact = (artifact: GoalArtifactView) =>+ artifact.type === 'file' &&+ (artifact.mimeType?.startsWith('image/') ||+ ['gif', 'jpeg', 'jpg', 'png', 'svg', 'webp'].includes(extensionOf(artifact) ?? ''));++/** What kind of thing the row is, told by its icon before its title is read. */+export const deliverableIconOf = (artifact: GoalArtifactView) => {+ if (artifact.type === 'document') return FileText;+ if (artifact.type === 'external') return Link2;+ if (isImageArtifact(artifact)) return FileImage;+ const ext = extensionOf(artifact);+ if (['7z', 'gz', 'rar', 'tar', 'tgz', 'zip'].includes(ext ?? '')) return FileArchive;+ if (['csv', 'tsv', 'xls', 'xlsx'].includes(ext ?? '')) return FileSpreadsheet;+ return File;+};++/**+ * Whether acceptance evidence cites the deliverable: a filled check when it+ * backs at least one criterion (named in the tooltip), a dashed ring when no+ * evidence points at it. Both carry an accessible label — the icon alone is+ * not the message.+ */+export const CitationMark = ({ item }: { item: DeliverableItem }) => {+ const { t } = useTranslation('chat');+ const cited = item.citedBy.length > 0;+ const label = cited+ ? t('goalProcess.result.deliverables.cited', {+ criteria: item.citedBy.map((criterion) => criterion.title).join(';'),+ })+ : t('goalProcess.result.deliverables.uncited');++ return (+ <Tooltip title={label}>+ <span+ aria-label={label}+ data-cited={cited}+ data-testid={'goal-deliverable-citation'}+ role={'img'}+ style={{ display: 'inline-flex', flex: 'none' }}+ >+ <Icon+ color={cited ? cssVar.colorSuccess : cssVar.colorTextQuaternary}+ icon={cited ? CircleCheck : CircleDashed}+ size={16}+ />+ </span>+ </Tooltip>+ );+};++export const deliverableTitleOf = (artifact: GoalArtifactView, untitled: string) =>+ artifact.title || artifact.identifier || untitled;diff --git a/src/features/AgentGoals/ProcessControl/goalAcceptanceReport.test.ts b/src/features/AgentGoals/ProcessControl/goalAcceptanceReport.test.tsindex 44ad438e3d8..d4a975059de 100644--- a/src/features/AgentGoals/ProcessControl/goalAcceptanceReport.test.ts+++ b/src/features/AgentGoals/ProcessControl/goalAcceptanceReport.test.ts@@ -1,50 +1,6 @@import { describe, expect, it } from 'vitest';-import {- goalAcceptanceState,- isFinalAcceptanceReady,- latestRunStatus,- pickFinalDeliverable,-} from './goalAcceptanceReport';--describe('goalAcceptanceState', () => {- /**- * Regression: the terminal acceptance only ever showed a small "待你确认" chip,- * which read the same for a Goal awaiting sign-off and one that failed.- */- it('tells a passed delivery awaiting sign-off from one that needs a decision', () => {- expect(goalAcceptanceState('delivered', 'passed')).toBe('awaitingAcceptance');- expect(goalAcceptanceState('delivered', 'failed')).toBe('awaitingDecision');- expect(goalAcceptanceState('delivered', undefined)).toBe('awaitingDecision');- });-- it('maps the running and settled statuses', () => {- expect(goalAcceptanceState('verifying')).toBe('inProgress');- expect(goalAcceptanceState('repairing')).toBe('inProgress');- expect(goalAcceptanceState('planned')).toBe('inProgress');- expect(goalAcceptanceState('accepted')).toBe('accepted');- expect(goalAcceptanceState('rejected')).toBe('rejected');- expect(goalAcceptanceState('errored')).toBe('errored');- expect(goalAcceptanceState('closed')).toBeUndefined();- });-});--describe('isFinalAcceptanceReady', () => {- /**- * Regression: the report view showed on an acceptance that was still lost and- * retrying, next to a ledger of failed attempts. It belongs only to a Goal- * whose final acceptance finished and waits on sign-off.- */- it('shows the report only once the acceptance task finished and passed', () => {- expect(isFinalAcceptanceReady('resolved', 'awaitingAcceptance')).toBe(true);- expect(isFinalAcceptanceReady('resolved', 'accepted')).toBe(true);- expect(isFinalAcceptanceReady('active', 'awaitingAcceptance')).toBe(false);- expect(isFinalAcceptanceReady('waiting', 'awaitingDecision')).toBe(false);- expect(isFinalAcceptanceReady('resolved', 'awaitingDecision')).toBe(false);- expect(isFinalAcceptanceReady('resolved', 'inProgress')).toBe(false);- expect(isFinalAcceptanceReady('resolved', undefined)).toBe(false);- });-});+import { pickFinalDeliverable } from './goalAcceptanceReport';describe('pickFinalDeliverable', () => {const artifact = (@@ -107,16 +63,3 @@ describe('pickFinalDeliverable', () => {).toBeUndefined();});});--describe('latestRunStatus', () => {- it('reads the newest round', () => {- expect(- latestRunStatus([- { run: { status: 'failed' } },- { run: { status: 'failed' } },- { run: { status: 'repairing' } },- ]),- ).toBe('repairing');- expect(latestRunStatus([])).toBeUndefined();- });-});diff --git a/src/features/AgentGoals/ProcessControl/goalAcceptanceReport.ts b/src/features/AgentGoals/ProcessControl/goalAcceptanceReport.tsindex 4abc0cc2241..c19ebea938c 100644--- a/src/features/AgentGoals/ProcessControl/goalAcceptanceReport.ts+++ b/src/features/AgentGoals/ProcessControl/goalAcceptanceReport.ts@@ -1,53 +1,3 @@-/**- * What the terminal Goal acceptance means to the person who owns the Goal.- *- * `delivered` alone cannot be rendered honestly: a round that passed and is- * waiting for sign-off lands there, and so does one that ran out of rounds- * without passing. The latest round's status tells them apart.- */-export type GoalAcceptanceState =- 'accepted' | 'awaitingAcceptance' | 'awaitingDecision' | 'errored' | 'inProgress' | 'rejected';--export const goalAcceptanceState = (- status: string,- latestRunStatus?: string | null,-): GoalAcceptanceState | undefined => {- switch (status) {- case 'accepted': {- return 'accepted';- }- case 'delivered': {- return latestRunStatus === 'passed' ? 'awaitingAcceptance' : 'awaitingDecision';- }- case 'errored': {- return 'errored';- }- case 'pending':- case 'planned':- case 'repairing':- case 'verifying': {- return 'inProgress';- }- case 'rejected': {- return 'rejected';- }- default: {- return undefined;- }- }-};--/**- * Whether the final acceptance has earned its report view: the acceptance Task- * finished (its node resolved) and the only thing left is the owner's sign-off,- * or it was already signed off. Anything short of that — still running, lost,- * failed, parked on a gate — is ordinary work and keeps the ordinary row.- */-export const isFinalAcceptanceReady = (- nodeStatus: string,- state: GoalAcceptanceState | undefined,-): boolean => nodeStatus === 'resolved' && (state === 'awaitingAcceptance' || state === 'accepted');-interface ArtifactLike {agentDocumentId?: string;createdAt: Date;@@ -95,11 +45,3 @@ export const pickFinalDeliverable = (title: picked.title,};};--interface RoundLike {- run: { status: string | null };-}--/** Rounds arrive in round order; the newest one decides the state. */-export const latestRunStatus = (rounds: RoundLike[]): string | null | undefined =>- rounds.at(-1)?.run.status;diff --git a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.tsindex 9684e00de2b..faaa0113899 100644--- a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts+++ b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts@@ -16,6 +16,7 @@ import {isRunningNode,isTroubledTaskNode,opensOnResultSurface,+ scopeGraphView,} from './goalGraphViewModel';const T0 = new Date('2026-08-01T00:00:00Z');@@ -124,6 +125,33 @@ describe('buildGoalGraphView', () => {expect(view.byId.p1.seq).toBeUndefined();});+ /**+ * Regression: a task retired before any attempt started had no attempt to+ * carry the reason, so the result page listed it as dropped with no why.+ */+ it('records why a node was given up, even without an attempt', () => {+ const view = buildGoalGraphView(+ snapshot({+ events: [+ event('w1', 'updated', 5, 'Store API rate-limited twice'),+ event('w1', 'retired', 10, 'Switched to public reviews'),+ event('w2', 'updated', 5, 'Discount data has no public source'),+ event('w2', 'rejected', 10),+ ],+ nodes: [+ node('w1', { status: 'retired', updatedAt: at(10) }),+ node('w2', { status: 'rejected', updatedAt: at(10) }),+ node('w3', { status: 'resolved', updatedAt: at(10) }),+ ],+ }),+ NOW,+ );++ expect(view.byId.w1.closedReason).toBe('Switched to public reviews');+ expect(view.byId.w2.closedReason).toBe('Discount data has no public source');+ expect(view.byId.w3.closedReason).toBeUndefined();+ });+it('builds the attempt ledger from the event trail', () => {const view = buildGoalGraphView(snapshot({@@ -458,6 +486,66 @@ describe('buildGoalGraphView', () => {});});+ /**+ * Regression: the wrap-up report is registered as a `goal_report` Work+ * produced by the wrap-up node, and surfaced as one more deliverable — in the+ * 交付物 list and as a step of the derived 探索过程. It describes the result;+ * the page reads it from `report`.+ */+ it('keeps the goal report out of the deliverables', () => {+ const work = (type: 'document' | 'goal_report', id: string) => ({+ identifier: null,+ resourceId: type === 'document' ? 'docs_1' : null,+ status: null,+ title: id,+ type,+ url: null,+ workId: `wk-${id}`,+ });+ const view = buildGoalGraphView(+ snapshot({+ nodes: [node('w1'), node('wrap')],+ workVersions: [+ {+ createdAt: at(5),+ id: 'l1',+ nodeId: 'w1',+ relation: 'produced',+ work: work('document', 'deliverable'),+ workVersionId: 'v1',+ },+ {+ createdAt: at(6),+ id: 'l2',+ nodeId: 'wrap',+ relation: 'produced',+ work: work('goal_report', 'report'),+ workVersionId: 'v2',+ },+ ],+ }),+ NOW,+ );++ expect(view.artifacts.map((artifact) => artifact.workVersionId)).toEqual(['v1']);+ expect(view.byId.wrap.artifacts).toEqual([]);+ });++ it('narrows a view to a set of nodes with only the edges inside it', () => {+ const view = buildGoalGraphView(+ snapshot({+ edges: [edge('w2', 'w1', 'depends_on'), edge('w3', 'w2', 'depends_on')],+ nodes: [node('w1'), node('w2'), node('w3')],+ }),+ NOW,+ );+ const scoped = scopeGraphView(view, new Set(['w1', 'w2']));++ expect(scoped.nodes.map((item) => item.node.id)).toEqual(['w1', 'w2']);+ expect(scoped.edges.map((item) => item.id)).toEqual(['w2-w1-depends_on']);+ expect(scoped.frontier.every((item) => item.view.node.id !== 'w3')).toBe(true);+ });+it('opens a generated file at the url its version metadata carries', () => {const view = buildGoalGraphView(snapshot({diff --git a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.tsindex 1f00d49582d..97cb7b69a5d 100644--- a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts+++ b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts@@ -6,6 +6,9 @@ import type {GoalGraphSnapshot,GoalItem,GoalNodeAcceptance,+ GoalNodeWorkVersionRelation,+ GoalReportState,+ GoalSpend,WorkType,} from '@lobechat/types';import { experimentMembers } from '@lobechat/utils/goalGraph';@@ -57,9 +60,21 @@ export interface GoalArtifactView {*/agentDocumentId?: string;createdAt: Date;+ /** `file` Work only — its file-store id, which acceptance evidence cites. */+ fileId?: string;+ /** `file` Work only — size in bytes. */+ fileSize?: number;identifier: string | null;+ /** `file` Work only — MIME type. */+ mimeType?: string;/** The task node that produced it — the goal-level list has no other owner. */nodeId: string;+ /**+ * How the node relates to the version: `produced` it, or took it as `input`.+ * One version can be linked to several nodes; its producer is the one that+ * owns it on a goal-level list.+ */+ relation?: GoalNodeWorkVersionRelation;/** Canonical resource identity; the document id an in-app link addresses. */resourceId: string | null;title: string | null;@@ -81,6 +96,12 @@ export interface GoalNodeView {attempts: GoalAttempt[];/** Unresolved `depends_on` targets — why this node cannot start. */blockers: GoalGraphNode[];+ /**+ * Why a rejected / retired node was given up: the reason on its closing+ * event, else the last note recorded before it. Read off the trail directly+ * so a node closed without ever starting an attempt still says why.+ */+ closedReason?: string;/** Pending user decision opened on this node. */decision?: GoalGraphDecision;dependsOn: string[];@@ -188,6 +209,10 @@ export interface GoalGraphView {needsYou: number;/** Views in graph creation order. */nodes: GoalNodeView[];+ /** The wrap-up report, once the Goal-level acceptance has ended. */+ report?: GoalReportState;+ /** Runs and dollars spent so far; absent on write-path snapshots. */+ spend?: GoalSpend;}const leaseTimeoutMs = (goal: GoalItem) =>@@ -273,6 +298,15 @@ const buildAttempts = (node: GoalGraphNode, events: GoalGraphEvent[]): GoalAttemreturn attempts;};+const closedReasonOf = (node: GoalGraphNode, events: GoalGraphEvent[]): string | undefined => {+ if (node.status !== 'rejected' && node.status !== 'retired') return undefined;+ const own = events.filter(+ (e) => e.entityType === 'node' && e.entityId === node.id && !!e.reason?.trim(),+ );+ const closing = own.findLast((e) => e.eventType === 'rejected' || e.eventType === 'retired');+ return (closing ?? own.findLast((e) => e.eventType === 'updated'))?.reason?.trim();+};+export const buildGoalGraphView = (snapshot: GoalGraphSnapshot,now: number = Date.now(),@@ -286,7 +320,9 @@ export const buildGoalGraphView = (events,goal,nodes,+ report,runHeartbeats,+ spend,workVersions,} = snapshot;const nodeById = new Map(nodes.map((node) => [node.id, node]));@@ -316,14 +352,17 @@ export const buildGoalGraphView = (// Only Works that were named by the read-time join can be shown, and the// responsible task's own `task` Work is execution bookkeeping rather than a- // deliverable — it would otherwise head every task's list with itself.+ // deliverable — it would otherwise head every task's list with itself. The+ // wrap-up `goal_report` describes the result rather than being part of it;+ // the page reads it from `report`, never as a deliverable.const artifactsByNode = new Map<string, GoalArtifactView[]>();for (const link of workVersions) {- if (!link.work || link.work.type === 'task') continue;+ if (!link.work || link.work.type === 'task' || link.work.type === 'goal_report') continue;const artifact: GoalArtifactView = {createdAt: link.createdAt,identifier: link.work.identifier,nodeId: link.nodeId,+ relation: link.relation,resourceId: link.work.resourceId,title: link.work.title,type: link.work.type,@@ -332,6 +371,9 @@ export const buildGoalGraphView = (workId: link.work.workId,workVersionId: link.workVersionId,...(link.work.agentDocumentId ? { agentDocumentId: link.work.agentDocumentId } : {}),+ ...(link.work.fileId ? { fileId: link.work.fileId } : {}),+ ...(link.work.fileSize !== undefined ? { fileSize: link.work.fileSize } : {}),+ ...(link.work.mimeType ? { mimeType: link.work.mimeType } : {}),};artifactsByNode.set(link.nodeId, [...(artifactsByNode.get(link.nodeId) ?? []), artifact]);}@@ -352,6 +394,7 @@ export const buildGoalGraphView = (node.kind === 'experiment' ? experimentMembers(snapshot, node.id) : new Set<string>();const nodeDecisions = decisionsByNode.get(node.id) ?? [];const attempts = buildAttempts(node, events);+ const closedReason = closedReasonOf(node, events);const open = attempts.at(-1);const isRunningAttempt = node.status === 'active' && open?.outcome === 'running';// Liveness = the newer of the node row (moves on observations / status@@ -389,6 +432,7 @@ export const buildGoalGraphView = (...(acceptances?.[node.id] ? { acceptance: acceptances[node.id] } : {}),...(assignees?.[node.id] ? { assigneeAgentId: assignees[node.id] } : {}),attempts,+ ...(closedReason ? { closedReason } : {}),blockers: (dependsOn.get(node.id) ?? []).map((id) => nodeById.get(id)).filter((dep): dep is GoalGraphNode => !!dep && !TERMINAL_NODE_STATUSES.has(dep.status)),@@ -470,8 +514,29 @@ export const buildGoalGraphView = (goal,needsYou: frontier.filter((item) => item.rank === 0).length,nodes: views,+ report,+ spend,};};+/**+ * The same graph narrowed to a set of nodes: edges, frontier and blocked rows+ * keep only what stays inside. `edges` overrides the edge set for a host that+ * already projected its own (the experiment scope).+ */+export const scopeGraphView = (+ graph: GoalGraphView,+ nodeIds: ReadonlySet<string>,+ edges?: GoalGraphEdge[],+): GoalGraphView => ({+ ...graph,+ blocked: graph.blocked.filter((view) => nodeIds.has(view.node.id)),+ edges:+ edges ??+ graph.edges.filter((edge) => nodeIds.has(edge.sourceNodeId) && nodeIds.has(edge.targetNodeId)),+ frontier: graph.frontier.filter((item) => nodeIds.has(item.view.node.id)),+ nodes: graph.nodes.filter((view) => nodeIds.has(view.node.id)),+});+const resolvedTime = (node: GoalGraphNode) =>(node.resolvedAt ?? node.updatedAt ?? node.createdAt).getTime();diff --git a/src/features/AgentGoals/ProcessControl/goalResultState.test.ts b/src/features/AgentGoals/ProcessControl/goalResultState.test.tsnew file mode 100644index 00000000000..f4016cf3adb--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/goalResultState.test.ts@@ -0,0 +1,774 @@+import { GOAL_ACCEPTANCE_TASK_TITLE, GOAL_REPORT_TASK_TITLE } from '@lobechat/const/goal';+import type { GoalReportState } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import type { GoalGraphView, GoalNodeView } from './goalGraphViewModel';+import {+ buildAbandonedNodes,+ buildCriterionOutcomes,+ buildResultTrail,+ buildStoryChapters,+ buildUserDecisions,+ type CheckLike,+ deriveGoalResultStatus,+ deriveSignOffState,+ findFinalAcceptanceView,+ findGoalAcceptanceGate,+ findOpenChangeRequest,+ hasGoalResult,+ latestRoundRunId,+ resultTrailSource,+} from './goalResultState';++const node = (+ status: string,+ { acceptance = true, title = GOAL_ACCEPTANCE_TASK_TITLE } = {},+): GoalNodeView =>+ ({+ acceptance: acceptance ? { id: 'acc-1', status: 'delivered' } : undefined,+ node: { id: `n-${status}-${title}`, kind: 'task', status, title },+ }) as unknown as GoalNodeView;++const graph = (+ goalStatus: string,+ nodes: GoalNodeView[],+ {+ artifacts = [] as unknown[],+ decisions = [] as unknown[],+ findings = [] as unknown[],+ gates = [] as GoalNodeView[],+ } = {},+) =>+ ({+ artifacts,+ byId: Object.fromEntries([...nodes, ...gates].map((view) => [view.node.id, view])),+ decisions,+ findings,+ goal: { status: goalStatus },+ nodes: [...nodes, ...gates],+ }) as unknown as GoalGraphView;++/** The gate node the coordinator opens (via `leads_to`) on a failed Task. */+const gateNode = (subject: GoalNodeView, id = 'gate-1') =>+ ({+ gateSubjectId: subject.node.id,+ node: { id, kind: 'decision', status: 'waiting', title: 'Choose how to recover failed task' },+ }) as unknown as GoalNodeView;++const gateDecision = (+ gate: GoalNodeView,+ {+ resolvedAt = undefined as Date | undefined,+ resolvedOptionId = undefined as string | undefined,+ } = {},+) => ({+ id: `d-${gate.node.id}-${resolvedOptionId ?? 'pending'}`,+ nodeId: gate.node.id,+ options: [+ { id: 'retry', label: 'Retry goal acceptance' },+ { id: 'retire', label: 'Abandon goal acceptance' },+ { id: 'fail', label: 'Fail goal' },+ ],+ question:+ 'Goal-level acceptance did not pass. Retry Goal acceptance, abandon it, or fail this Goal?',+ recommendedOptionId: 'retry',+ status: resolvedOptionId ? 'resolved' : 'pending',+ ...(resolvedOptionId ? { resolvedAt, resolvedByUserId: 'u1', resolvedOptionId } : {}),+});++/** A Goal the owner sent back for changes: reopened, its acceptance node active again. */+const reopened = (goalStatus: string) =>+ ({+ ...graph(goalStatus, [node('active')]),+ goal: {+ config: {+ changeRequest: {+ comment: 'Add a day-one agenda',+ requestedAt: '2026-09-29T00:00:00.000Z',+ taskId: 'task-acc',+ },+ },+ status: goalStatus,+ },+ }) as unknown as GoalGraphView;++describe('owner change request', () => {+ it('keeps the result page on a Goal reopened for changes', () => {+ expect(hasGoalResult(reopened('running'))).toBe(true);+ expect(findOpenChangeRequest(reopened('running'))?.comment).toBe('Add a day-one agenda');+ });++ it('reads 修改中 while the rework runs, not 等你验收', () => {+ expect(+ deriveGoalResultStatus({+ acceptanceStatus: 'rejected',+ changesRequested: !!findOpenChangeRequest(reopened('running')),+ goalStatus: 'running',+ unmetCriteria: 0,+ }),+ ).toBe('revising');+ // The rework's new round delivered, the Goal not yet re-achieved.+ expect(+ deriveGoalResultStatus({+ acceptanceStatus: 'delivered',+ changesRequested: true,+ goalStatus: 'running',+ unmetCriteria: 0,+ }),+ ).toBe('revising');+ });++ it('waits on sign-off again once the rework is achieved', () => {+ const achieved = reopened('achieved');+ expect(findOpenChangeRequest(achieved)).toBeUndefined();+ expect(+ deriveGoalResultStatus({+ acceptanceStatus: 'delivered',+ changesRequested: !!findOpenChangeRequest(achieved),+ goalStatus: 'achieved',+ unmetCriteria: 0,+ }),+ ).toBe('awaitingSignOff');+ });++ it('lets a gate the rework opened take over from 修改中', () => {+ expect(+ deriveGoalResultStatus({+ acceptanceStatus: 'delivered',+ changesRequested: true,+ gate: 'pending',+ goalStatus: 'review',+ unmetCriteria: 1,+ }),+ ).toBe('awaitingDecision');+ });+});++describe('hasGoalResult', () => {+ /**+ * Regression: a finished Goal wrapped its delivery inside the 当前任务 section+ * of the process view. The result gets its own tab once the Goal is done.+ */+ it('offers a result once the final acceptance task resolved', () => {+ expect(hasGoalResult(graph('review', [node('resolved')]))).toBe(true);+ });++ it('offers a result for an achieved Goal without a final acceptance task', () => {+ expect(hasGoalResult(graph('achieved', []))).toBe(true);+ });++ it('keeps a running Goal on the process view', () => {+ expect(hasGoalResult(graph('running', [node('active')]))).toBe(false);+ expect(hasGoalResult(graph('running', [node('resolved', { acceptance: false })]))).toBe(false);+ expect(hasGoalResult(graph('running', [node('resolved', { title: 'Other task' })]))).toBe(+ false,+ );+ });+});++describe('hasGoalResult for a Goal that stopped', () => {+ /**+ * Regression: a failed or canceled Goal kept only the process view, so the+ * partial result it did produce had no page to be reviewed or continued from.+ */+ it('offers a result for a failed or canceled Goal that produced something', () => {+ expect(hasGoalResult(graph('failed', [], { artifacts: [{}] }))).toBe(true);+ expect(hasGoalResult(graph('canceled', [], { findings: [{}] }))).toBe(true);+ });++ it('keeps a stopped Goal with no output on the process view', () => {+ expect(hasGoalResult(graph('failed', []))).toBe(false);+ expect(hasGoalResult(graph('canceled', []))).toBe(false);+ });++ it('does not open a result for a running Goal just because it has output', () => {+ expect(hasGoalResult(graph('running', [], { artifacts: [{}] }))).toBe(false);+ });+});++describe('hasGoalResult for a Goal acceptance that ended unmet', () => {+ /**+ * Regression (acceptance b92f4920): the Goal-level acceptance failed and the+ * coordinator parked the Goal in `review` behind a retry / fail gate. The+ * acceptance node is `waiting`, not `resolved`, so no result tab showed and+ * the owner was asked to decide without seeing which criteria failed.+ */+ it('offers a result while the acceptance gate waits on the owner', () => {+ const acceptance = node('waiting');+ const gate = gateNode(acceptance);+ const view = graph('review', [acceptance], {+ decisions: [gateDecision(gate)],+ gates: [gate],+ });++ expect(hasGoalResult(view)).toBe(true);+ expect(findGoalAcceptanceGate(view)).toMatchObject({ kind: 'pending' });+ });++ it('keeps the result through the retry the owner chose', () => {+ const acceptance = node('active');+ const gate = gateNode(acceptance);+ const view = graph('running', [acceptance], {+ decisions: [gateDecision(gate, { resolvedAt: new Date(1), resolvedOptionId: 'retry' })],+ gates: [gate],+ });++ expect(hasGoalResult(view)).toBe(true);+ expect(findGoalAcceptanceGate(view)?.kind).toBe('retrying');+ });++ it('keeps the result after the owner failed the Goal, even with no output', () => {+ const acceptance = node('retired');+ const gate = gateNode(acceptance);+ const view = graph('failed', [acceptance], {+ decisions: [gateDecision(gate, { resolvedAt: new Date(1), resolvedOptionId: 'fail' })],+ gates: [gate],+ });++ expect(hasGoalResult(view)).toBe(true);+ expect(findGoalAcceptanceGate(view)?.kind).toBe('decided');+ });++ it('reads the newest gate when a retried acceptance failed again', () => {+ const acceptance = node('waiting');+ const first = gateNode(acceptance, 'gate-1');+ const second = gateNode(acceptance, 'gate-2');+ const view = graph('review', [acceptance], {+ decisions: [+ gateDecision(first, { resolvedAt: new Date(1), resolvedOptionId: 'retry' }),+ gateDecision(second),+ ],+ gates: [first, second],+ });++ expect(findGoalAcceptanceGate(view)).toMatchObject({+ decision: { nodeId: 'gate-2' },+ kind: 'pending',+ });+ });++ it('ignores gates opened on ordinary Tasks', () => {+ const task = node('waiting', { title: 'Write the draft' });+ const gate = gateNode(task);+ const view = graph('review', [task], { decisions: [gateDecision(gate)], gates: [gate] });++ expect(findGoalAcceptanceGate(view)).toBeUndefined();+ expect(hasGoalResult(view)).toBe(false);+ });+});++describe('deriveGoalResultStatus', () => {+ it('reads a pending Goal-acceptance gate as waiting on the owner’s call', () => {+ expect(+ deriveGoalResultStatus({+ acceptanceStatus: 'errored',+ gate: 'pending',+ goalStatus: 'review',+ unmetCriteria: 2,+ }),+ ).toBe('awaitingDecision');+ });++ it('moves to revising after retry, and to partial after the owner fails the Goal', () => {+ expect(+ deriveGoalResultStatus({+ acceptanceStatus: 'verifying',+ gate: 'retrying',+ goalStatus: 'running',+ unmetCriteria: 2,+ }),+ ).toBe('revising');+ expect(+ deriveGoalResultStatus({+ acceptanceStatus: 'rejected',+ gate: 'decided',+ goalStatus: 'failed',+ unmetCriteria: 2,+ }),+ ).toBe('partial');+ expect(+ deriveGoalResultStatus({+ acceptanceStatus: 'delivered',+ gate: 'decided',+ goalStatus: 'canceled',+ unmetCriteria: 2,+ }),+ ).toBe('partial');+ });++ it('reads an achieved, unsigned Goal as waiting on the owner', () => {+ expect(+ deriveGoalResultStatus({+ acceptanceStatus: 'delivered',+ goalStatus: 'achieved',+ unmetCriteria: 0,+ }),+ ).toBe('awaitingSignOff');+ expect(deriveGoalResultStatus({ goalStatus: 'achieved', unmetCriteria: 0 })).toBe(+ 'awaitingSignOff',+ );+ });++ it('reads an accepted delivery as signed off', () => {+ expect(+ deriveGoalResultStatus({+ acceptanceStatus: 'accepted',+ goalStatus: 'achieved',+ unmetCriteria: 0,+ }),+ ).toBe('signedOff');+ });++ it('reads a failed or canceled Goal as a partial result', () => {+ expect(deriveGoalResultStatus({ goalStatus: 'failed', unmetCriteria: 0 })).toBe('partial');+ expect(+ deriveGoalResultStatus({+ acceptanceStatus: 'delivered',+ goalStatus: 'canceled',+ unmetCriteria: 0,+ }),+ ).toBe('partial');+ });++ it('reads an unachieved Goal whose acceptance found unmet criteria as partial', () => {+ expect(+ deriveGoalResultStatus({+ acceptanceStatus: 'delivered',+ goalStatus: 'review',+ unmetCriteria: 1,+ }),+ ).toBe('partial');+ });+});++describe('deriveSignOffState', () => {+ /**+ * Regression (T-558 acceptance): after the owner failed the Goal at its+ * acceptance gate, the unmet round left the acceptance `delivered` and the+ * page still offered 接受交付 / 提出修改 on a failed Goal.+ */+ it('reads a Goal the owner failed at the acceptance gate as stopped', () => {+ expect(deriveSignOffState('delivered', 'failed', 'decided')).toBe('stopped');+ // 放弃任务 ends the Goal as canceled — the same stopped strip.+ expect(deriveSignOffState('delivered', 'canceled', 'decided')).toBe('stopped');+ expect(deriveSignOffState('accepted', 'failed', 'decided')).toBe('accepted');+ });++ it('opens sign-off only on an acceptance the server can still decide', () => {+ expect(deriveSignOffState('delivered', 'achieved')).toBe('open');+ expect(deriveSignOffState('errored', 'review')).toBe('open');+ expect(deriveSignOffState('accepted', 'achieved')).toBe('accepted');+ expect(deriveSignOffState('rejected', 'achieved')).toBe('changesRequested');+ expect(deriveSignOffState('repairing', 'running')).toBe('changesRequested');+ expect(deriveSignOffState('verifying', 'review')).toBe('unavailable');+ expect(deriveSignOffState(undefined, 'achieved')).toBe('unavailable');+ });++ /**+ * Regression: a failed Goal whose acceptance the coordinator rejected read+ * "your feedback went back to the Agent" though the owner never asked for+ * changes and nothing is running.+ */+ it('reads a stopped Goal with nothing to sign as stopped, not as changes requested', () => {+ expect(deriveSignOffState('rejected', 'failed')).toBe('stopped');+ expect(deriveSignOffState(undefined, 'canceled')).toBe('stopped');+ // A stopped Goal whose delivery still waits on the owner keeps its sign-off.+ expect(deriveSignOffState('delivered', 'failed')).toBe('open');+ });+});++describe('buildCriterionOutcomes', () => {+ const criteria = [+ { id: 'c1', title: 'Covers every source' },+ { id: 'c2', title: 'Cites evidence' },+ { id: 'c3', title: 'Has a summary' },+ ];+ const check = (+ id: string,+ runId: string,+ verdict: string,+ extra: Partial<CheckLike['result']> = {},+ evidence: CheckLike['evidence'] = [],+ ): CheckLike => ({+ evidence,+ id,+ result: {+ id: `r-${id}-${runId}`,+ sourceCriterionId: id,+ status: verdict === 'uncertain' ? 'passed' : verdict,+ verdict,+ verifyRunId: runId,+ ...extra,+ },+ });++ /**+ * Regression: the result page only linked to the acceptance, so the owner+ * could not see which criterion held and which did not. Each criterion now+ * carries the latest round's verdict, a one-line evidence summary and, when+ * unmet, the reason.+ */+ it('maps each criterion to the latest round result, in criteriaIds order', () => {+ const outcomes = buildCriterionOutcomes({+ checks: [+ check('c2', 'run-2', 'failed', {+ toulmin: {+ evidence: 'Two claims have no source',+ reasoning: 'Sources are missing\nmore',+ },+ }),+ check(+ 'c1',+ 'run-2',+ 'passed',+ { toulmin: { evidence: '## All 12 sources covered\ndetails' } },+ [{ description: 'Source table', id: 'e1', type: 'markdown' }],+ ),+ ],+ criteria,+ criteriaIds: ['c1', 'c2', 'c3'],+ latestRunId: 'run-2',+ });++ expect(outcomes.map((o) => [o.criterion.id, o.state])).toEqual([+ ['c1', 'passed'],+ ['c2', 'failed'],+ ['c3', 'unjudged'],+ ]);+ expect(outcomes[0].summary).toBe('All 12 sources covered');+ expect(outcomes[0].reason).toBeUndefined();+ expect(outcomes[0].evidence.map((e) => e.id)).toEqual(['e1']);+ expect(outcomes[1].summary).toBe('Two claims have no source');+ expect(outcomes[1].reason).toBe('Sources are missing');+ expect(outcomes[2].evidence).toEqual([]);+ });++ it('ignores results from earlier rounds', () => {+ const outcomes = buildCriterionOutcomes({+ checks: [check('c1', 'run-1', 'passed')],+ criteria,+ criteriaIds: ['c1'],+ latestRunId: 'run-2',+ });+ expect(outcomes[0].state).toBe('unjudged');+ });++ it('matches on sourceCriterionId even when the check row id differs', () => {+ const outcomes = buildCriterionOutcomes({+ checks: [{ ...check('c1', 'run-2', 'passed'), id: 'plan-item-7' }],+ criteria,+ criteriaIds: ['c1'],+ latestRunId: 'run-2',+ });+ expect(outcomes[0].state).toBe('passed');+ });++ it('treats an uncertain verdict as undecided and a failure without toulmin via suggestion', () => {+ const outcomes = buildCriterionOutcomes({+ checks: [+ check('c1', 'run-2', 'uncertain'),+ check('c2', 'run-2', 'failed', { suggestion: 'Add the missing citations' }),+ ],+ criteria,+ criteriaIds: ['c1', 'c2'],+ latestRunId: 'run-2',+ });+ expect(outcomes.map((o) => o.state)).toEqual(['unjudged', 'failed']);+ expect(outcomes[1].reason).toBe('Add the missing citations');+ });++ it('skips criterion ids whose rows are gone', () => {+ expect(+ buildCriterionOutcomes({ checks: [], criteria, criteriaIds: ['gone', 'c1'] }).map(+ (o) => o.criterion.id,+ ),+ ).toEqual(['c1']);+ });+});++describe('latestRoundRunId', () => {+ it('picks the highest round index', () => {+ expect(+ latestRoundRunId([{ run: { id: 'b', roundIndex: 2 } }, { run: { id: 'a', roundIndex: 1 } }]),+ ).toBe('b');+ expect(latestRoundRunId([])).toBeUndefined();+ });+});++describe('buildUserDecisions', () => {+ const decision = (id: string, extra: Record<string, unknown>) =>+ ({+ id,+ options: [+ { id: 'a', label: 'Option A' },+ { id: 'b', label: 'Option B' },+ ],+ question: `Question ${id}`,+ resolution: null,+ resolvedAt: null,+ resolvedByAgentId: null,+ resolvedByUserId: null,+ resolvedOptionId: null,+ status: 'resolved',+ ...extra,+ }) as any;++ it('keeps only decisions a person resolved, oldest first', () => {+ const views = buildUserDecisions([+ decision('late', {+ resolvedAt: new Date(2000),+ resolvedByUserId: 'u1',+ resolvedOptionId: 'b',+ }),+ decision('agent', {+ resolvedAt: new Date(1500),+ resolvedByAgentId: 'agt',+ resolvedOptionId: 'a',+ }),+ decision('open', { status: 'pending' }),+ decision('early', {+ resolution: 'Ship it',+ resolvedAt: new Date(1000),+ resolvedByUserId: 'u1',+ }),+ ]);++ expect(views.map((v) => [v.decision.id, v.choice])).toEqual([+ ['early', 'Ship it'],+ ['late', 'Option B'],+ ]);+ });++ it('omits a missing choice or time instead of inventing one', () => {+ const [view] = buildUserDecisions([decision('bare', { resolvedByUserId: 'u1' })]);+ expect(view.choice).toBeUndefined();+ expect(view.resolvedAt).toBeUndefined();+ });+});++describe('buildAbandonedNodes', () => {+ it('lists rejected and retired tasks with the reason that ended them', () => {+ const task = (id: string, status: string, attempts: unknown[] = []) =>+ ({ attempts, node: { id, kind: 'task', status, title: id } }) as unknown as GoalNodeView;++ const abandoned = buildAbandonedNodes({+ nodes: [+ task('done', 'resolved'),+ task('retired', 'retired', [+ { outcome: 'failed', reason: 'First try' },+ { outcome: 'retired', reason: 'Source site is down' },+ ]),+ task('rejected', 'rejected'),+ {+ ...task('closed-early', 'retired'),+ closedReason: 'Goal canceled before it started',+ } as GoalNodeView,+ ],+ });++ expect(abandoned.map((a) => [a.view.node.id, a.reason])).toEqual([+ ['retired', 'Source site is down'],+ ['rejected', undefined],+ ['closed-early', 'Goal canceled before it started'],+ ]);+ });+});++describe('findFinalAcceptanceView', () => {+ it('picks the resolved final acceptance task', () => {+ const accepted = node('resolved');+ expect(findFinalAcceptanceView({ nodes: [node('active'), accepted] })).toBe(accepted);+ });+});++describe('buildResultTrail', () => {+ const at = (minutes: number) => new Date(Date.UTC(2026, 8, 28, 0, minutes));+ const view = (id: string, kind: string, minutes: number, producedBy?: string) =>+ ({+ node: { createdAt: at(minutes), id, kind, resolvedAt: at(minutes), title: id },+ producedBy: producedBy ? { id: producedBy } : undefined,+ }) as unknown as GoalNodeView;+ const artifact = (id: string, nodeId: string, minutes: number) =>+ ({ createdAt: at(minutes), nodeId, workVersionId: id }) as any;++ /**+ * Regression: the result tab listed 交付物 and 结论 as two unrelated lists,+ * leaving no path from a conclusion to the files behind it. Each step now+ * carries both, joined on the task that produced them.+ */+ it('joins conclusions and deliverables on the task that produced them, in order', () => {+ const taskA = view('task-a', 'task', 10);+ const taskB = view('task-b', 'task', 5);+ const idle = view('task-idle', 'task', 1);+ const findingA = view('finding-a', 'finding', 11, 'task-a');+ const findingB = view('finding-b', 'finding', 6, 'task-b');+ const orphan = view('finding-orphan', 'finding', 20);++ const trail = buildResultTrail({+ artifacts: [artifact('v-a', 'task-a', 12), artifact('v-b', 'task-b', 7)],+ byId: { 'task-a': taskA, 'task-b': taskB, 'task-idle': idle },+ findings: [findingA, orphan, findingB],+ });++ expect(trail.map((step) => step.key)).toEqual(['task-b', 'task-a', 'unattributed']);+ expect(trail[0].findings).toEqual([findingB]);+ expect(trail[0].artifacts.map((a) => a.workVersionId)).toEqual(['v-b']);+ expect(trail[1].findings).toEqual([findingA]);+ expect(trail[2].findings).toEqual([orphan]);+ expect(trail[2].view).toBeUndefined();+ });+});++describe('buildResultTrail without the wrap-up Task', () => {+ const at = (minutes: number) => new Date(Date.UTC(2026, 8, 28, 0, minutes));+ const task = (id: string, title: string, minutes: number) =>+ ({+ node: { createdAt: at(minutes), id, kind: 'task', resolvedAt: at(minutes), title },+ }) as unknown as GoalNodeView;++ /**+ * Regression: the wrap-up Task that writes the Goal report showed up in the+ * derived trail as the last step of the work it describes.+ */+ it('leaves the wrap-up Task and its output out of the derived trail', () => {+ const work = task('task-a', 'Collect sources', 1);+ const wrapUp = task('wrap', GOAL_REPORT_TASK_TITLE, 9);+ const finding = {+ node: { createdAt: at(10), id: 'f-wrap', kind: 'finding', resolvedAt: at(10), title: 'x' },+ producedBy: { id: 'wrap' },+ } as unknown as GoalNodeView;++ const trail = buildResultTrail({+ artifacts: [+ { createdAt: at(2), nodeId: 'task-a', workVersionId: 'v-a' } as any,+ { createdAt: at(9), nodeId: 'wrap', workVersionId: 'v-wrap' } as any,+ ],+ byId: { 'task': work, 'task-a': work, 'wrap': wrapUp },+ findings: [finding],+ });++ expect(trail.map((step) => step.key)).toEqual(['task-a']);+ });+});++describe('resultTrailSource', () => {+ const metadata = {+ chapters: [+ {+ detours: [],+ findingIds: [],+ narrative: 'We started from the brief.',+ nodeIds: ['task-a'],+ title: 'Reading the brief',+ workVersionIds: [],+ },+ ],+ graphCursor: 'evt-1',+ headline: 'Shipped the report',+ nextSteps: [],+ };+ const latest = {+ content: '# Report',+ createdAt: new Date(),+ metadata,+ version: 1,+ workId: 'wk-report',+ workVersionId: 'v-report',+ };+ const report = (state: Partial<GoalReportState>) => ({+ report: {+ dispatch: { acceptanceKey: 'k', dispatchedAt: '', nodeId: 'wrap', trigger: 'accepted' },+ status: 'completed',+ ...state,+ } as GoalReportState,+ });++ /**+ * The section switches between three states as the wrap-up run moves: it+ * says the storyline is being written, then shows it, and falls back to the+ * derived trail whenever there is no storyline to show.+ */+ it('shows the organizing state while the wrap-up run is in flight', () => {+ expect(resultTrailSource(report({ status: 'running' })).kind).toBe('pending');+ // A report from an earlier acceptance result is being rewritten: not current.+ expect(resultTrailSource(report({ latest, status: 'running' })).kind).toBe('pending');+ });++ it('shows the storyline once the report is submitted', () => {+ const source = resultTrailSource(report({ latest, status: 'completed' }));+ expect(source.kind).toBe('story');+ expect(source.kind === 'story' && source.metadata.headline).toBe('Shipped the report');+ });++ it('falls back to the derived trail without a report or when the run failed', () => {+ expect(resultTrailSource({}).kind).toBe('derived');+ expect(resultTrailSource(report({ status: 'failed' })).kind).toBe('derived');+ expect(resultTrailSource(report({ latest, status: 'failed' })).kind).toBe('derived');+ expect(resultTrailSource(report({ status: 'completed' })).kind).toBe('derived');+ });++ it('falls back when the stored storyline does not parse', () => {+ const broken = { ...latest, metadata: { headline: 'x' } as any };+ expect(resultTrailSource(report({ latest: broken, status: 'completed' })).kind).toBe('derived');+ });+});++describe('buildStoryChapters', () => {+ const view = (id: string, kind: string) =>+ ({ node: { id, kind, title: id } }) as unknown as GoalNodeView;++ it('resolves each chapter against the graph, in report order, with its detours', () => {+ const byId = {+ 'dead': view('dead', 'task'),+ 'f-1': view('f-1', 'finding'),+ 'task-a': view('task-a', 'task'),+ 'task-b': view('task-b', 'task'),+ };+ const chapters = buildStoryChapters(+ {+ artifacts: [{ nodeId: 'task-b', workVersionId: 'v-1' } as any],+ byId,+ },+ {+ chapters: [+ {+ detours: [+ {+ kind: 'dead_end',+ lesson: 'Check the API first',+ nodeIds: ['dead', 'gone'],+ reason: 'The API was retired',+ title: 'Scraping the old API',+ },+ ],+ findingIds: ['f-1', 'task-a', 'missing'],+ narrative: 'First',+ nodeIds: ['task-a'],+ title: 'Find the source',+ workVersionIds: [],+ },+ {+ detours: [],+ findingIds: [],+ narrative: 'Then',+ nodeIds: ['task-b'],+ title: 'Write it up',+ workVersionIds: ['v-1', 'v-gone'],+ },+ ],+ },+ );++ expect(chapters.map((chapter) => chapter.chapter.title)).toEqual([+ 'Find the source',+ 'Write it up',+ ]);+ // Only findings that exist and are findings become list items.+ expect(chapters[0].findings.map((item) => item.node.id)).toEqual(['f-1']);+ // The local map: main path plus detour nodes still on the graph.+ expect(chapters[0].mapNodeIds).toEqual(['task-a', 'dead']);+ expect(chapters[0].detourNodeIds).toEqual(['dead']);+ expect(chapters[1].artifacts.map((item) => item.workVersionId)).toEqual(['v-1']);+ expect(chapters[1].detourNodeIds).toEqual([]);+ });+});diff --git a/src/features/AgentGoals/ProcessControl/goalResultState.ts b/src/features/AgentGoals/ProcessControl/goalResultState.tsnew file mode 100644index 00000000000..e08a1573ee3--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/goalResultState.ts@@ -0,0 +1,542 @@+import { GOAL_REPORT_TASK_TITLE } from '@lobechat/const/goal';+import type {+ AcceptanceStatus,+ GoalChangeRequest,+ GoalGraphDecision,+ GoalReportChapter,+ GoalReportMetadata,+ GoalReportVersion,+ ToulminVerdict,+} from '@lobechat/types';+import { GoalReportMetadataSchema } from '@lobechat/types';++import { isGoalAcceptanceTask } from './coordinatorCopy';+import type { GoalArtifactView, GoalGraphView, GoalNodeView } from './goalGraphViewModel';++/**+ * Whether a Goal has an outcome to hand over, which is what earns it the+ * 结果交付 tab.+ *+ * A finished Goal: its final acceptance Task resolved (the result waits on the+ * owner's sign-off, whatever the Goal's own status says), or the Goal was+ * marked achieved without one. A Goal-level acceptance that ended unmet has an+ * outcome too: the gate it opens asks the owner to retry or give up, and the+ * criteria it judged unmet are what that call is made from — so the tab shows+ * while the gate waits, and stays through the retry it may start. A Goal that failed or was canceled still hands+ * over whatever it produced — the partial result is what the owner decides the+ * next step from — so it earns the tab too, as long as something came out. A+ * running Goal keeps the single process view: a result tab there would show a+ * draft as if it were the delivery.+ */++/** The Goal's resolved final acceptance Task, when there is one. */+export const findFinalAcceptanceView = (+ graph: Pick<GoalGraphView, 'nodes'>,+): GoalNodeView | undefined =>+ graph.nodes.find(+ (view) => isGoalAcceptanceTask(view) && view.node.status === 'resolved' && !!view.acceptance,+ );++/** The Goal-level acceptance, settled or not — the one sign-off acts on. */+export const findGoalAcceptanceView = (+ graph: Pick<GoalGraphView, 'nodes'>,+): GoalNodeView | undefined =>+ findFinalAcceptanceView(graph) ??+ graph.nodes.findLast((view) => isGoalAcceptanceTask(view) && !!view.acceptance);++const STOPPED_GOAL_STATUSES = new Set(['canceled', 'failed']);+const TERMINAL_ACCEPTANCE_NODE_STATUSES = new Set(['resolved', 'rejected', 'retired']);++/**+ * The decision gate the coordinator opened after the Goal-level acceptance+ * ended unmet, as the result page reads it:+ *+ * - `pending` — the gate waits on the owner (retry / fail the Goal).+ * - `retrying` — the owner chose retry and the acceptance is running again.+ * - `decided` — the owner closed the gate some other way (the Goal was+ * failed, or the acceptance has since passed).+ */+export type GoalAcceptanceGate =+ | { decision: GoalGraphDecision; kind: 'pending'; subject: GoalNodeView }+ | { decision: GoalGraphDecision; kind: 'decided' | 'retrying'; subject: GoalNodeView };++export const findGoalAcceptanceGate = (+ graph: Pick<GoalGraphView, 'byId' | 'decisions'>,+): GoalAcceptanceGate | undefined => {+ const subjectOf = (decision: GoalGraphDecision) => {+ const subjectId = graph.byId[decision.nodeId]?.gateSubjectId;+ const subject = subjectId ? graph.byId[subjectId] : undefined;+ return subject && isGoalAcceptanceTask(subject) ? subject : undefined;+ };++ const pending = graph.decisions.findLast(+ (decision) => decision.status === 'pending' && !!subjectOf(decision),+ );+ if (pending) return { decision: pending, kind: 'pending', subject: subjectOf(pending)! };++ const decided = graph.decisions+ .filter((decision) => decision.status === 'resolved' && !!subjectOf(decision))+ .sort((a, b) => (a.resolvedAt?.getTime() ?? 0) - (b.resolvedAt?.getTime() ?? 0))+ .at(-1);+ if (!decided) return undefined;++ const subject = subjectOf(decided)!;+ const retrying =+ decided.resolvedOptionId === 'retry' &&+ !TERMINAL_ACCEPTANCE_NODE_STATUSES.has(subject.node.status);+ return { decision: decided, kind: retrying ? 'retrying' : 'decided', subject };+};++/** Goal statuses in which an owner's change request is still being worked. */+const REWORKING_GOAL_STATUSES = new Set(['paused', 'review', 'running']);++/**+ * The owner's 提出修改 the Goal was reopened for, while it is still open. The+ * request stays on the Goal after the rework lands; once the Goal is achieved+ * (or stopped) again it no longer describes where the result stands.+ */+export const findOpenChangeRequest = (+ graph: Pick<GoalGraphView, 'goal'>,+): GoalChangeRequest | undefined => {+ const request = graph.goal.config?.changeRequest;+ return request && REWORKING_GOAL_STATUSES.has(graph.goal.status) ? request : undefined;+};++/** Anything the Goal left behind that a partial result page can show. */+export const hasGoalOutput = (+ graph: Pick<GoalGraphView, 'artifacts' | 'findings' | 'report'>,+): boolean => graph.artifacts.length > 0 || graph.findings.length > 0 || !!graph.report?.latest;++export const hasGoalResult = (+ graph: Pick<+ GoalGraphView,+ 'artifacts' | 'byId' | 'decisions' | 'findings' | 'goal' | 'nodes' | 'report'+ >,+): boolean =>+ graph.goal.status === 'achieved' ||+ !!findFinalAcceptanceView(graph) ||+ !!findGoalAcceptanceGate(graph) ||+ // Sent back for changes: the delivery being reworked is still the result.+ !!findOpenChangeRequest(graph) ||+ (STOPPED_GOAL_STATUSES.has(graph.goal.status) && hasGoalOutput(graph));++/**+ * Where the result stands for its owner, as the first screen says it:+ *+ * - `awaitingDecision` — the Goal-level acceptance ended unmet and its gate+ * waits on the owner: retry, or fail the Goal.+ * - `revising` — the owner chose retry, or sent the delivery back for+ * changes; the Goal is being reworked and accepted again.+ * - `partial` — the Goal stopped (failed / canceled), or its acceptance+ * judged a criterion unmet: what exists is a partial result.+ * - `signedOff` — the owner accepted the delivery.+ * - `awaitingSignOff` — achieved, and the owner has not signed yet.+ */+export type GoalResultStatus =+ 'awaitingDecision' | 'awaitingSignOff' | 'partial' | 'revising' | 'signedOff';++export const deriveGoalResultStatus = ({+ acceptanceStatus,+ changesRequested,+ gate,+ goalStatus,+ unmetCriteria,+}: {+ acceptanceStatus?: AcceptanceStatus;+ /** An open change request, from {@link findOpenChangeRequest}. */+ changesRequested?: boolean;+ /** The Goal-acceptance gate's state, from {@link findGoalAcceptanceGate}. */+ gate?: GoalAcceptanceGate['kind'];+ goalStatus: string;+ /** Criteria the latest acceptance round judged unmet. */+ unmetCriteria: number;+}): GoalResultStatus => {+ if (acceptanceStatus === 'accepted') return 'signedOff';+ if (STOPPED_GOAL_STATUSES.has(goalStatus)) return 'partial';+ if (gate === 'pending') return 'awaitingDecision';+ if ((gate === 'retrying' || changesRequested) && goalStatus !== 'achieved') return 'revising';+ if (goalStatus !== 'achieved' && unmetCriteria > 0) return 'partial';+ return 'awaitingSignOff';+};++/**+ * What the sign-off strip can do right now. Only a settled acceptance waits on+ * the owner (`delivered`, or `errored` — the server takes a decision on both);+ * an accepted one is closed, and one rejected on a live Goal is back with the+ * Agent. A Goal that stopped (failed / canceled) with nothing left to sign has+ * ended: its way forward is to continue from what it left, not a sign-off.+ */+export type GoalSignOffState = 'accepted' | 'changesRequested' | 'open' | 'stopped' | 'unavailable';++export const deriveSignOffState = (+ acceptanceStatus: AcceptanceStatus | undefined,+ goalStatus: string,+ gate?: GoalAcceptanceGate['kind'],+): GoalSignOffState => {+ if (acceptanceStatus === 'accepted') return 'accepted';+ // The owner already ended the Goal at its acceptance gate. The unmet round+ // leaves the acceptance `delivered`, but offering to accept a delivery the+ // owner just judged failed would undo that call.+ if (gate === 'decided' && STOPPED_GOAL_STATUSES.has(goalStatus)) return 'stopped';+ if (acceptanceStatus === 'delivered' || acceptanceStatus === 'errored') return 'open';+ if (STOPPED_GOAL_STATUSES.has(goalStatus)) return 'stopped';+ if (acceptanceStatus === 'rejected' || acceptanceStatus === 'repairing')+ return 'changesRequested';+ return 'unavailable';+};++// ---------------------------------------------------------------------------+// 验收标准 × 结果+// ---------------------------------------------------------------------------++export interface CriterionLike {+ description?: string | null;+ id: string;+ title: string;+}++export interface CheckResultLike {+ id: string;+ sourceCriterionId: string | null;+ status: string;+ suggestion?: string | null;+ toulmin?: ToulminVerdict | null;+ verdict?: string | null;+ verifyRunId: string | null;+}++export interface EvidenceLike {+ content?: string | null;+ description?: string | null;+ documentId?: string | null;+ fileId?: string | null;+ fileName?: string | null;+ fileUrl?: string | null;+ id: string;+ type: string;+}++export interface CheckLike {+ evidence: EvidenceLike[];+ /** The union row id — `sourceCriterionId ?? checkItemId`. */+ id: string;+ result?: CheckResultLike;+}++export type CriterionOutcomeState = 'failed' | 'passed' | 'unjudged';++export interface CriterionOutcome {+ criterion: CriterionLike;+ evidence: EvidenceLike[];+ /** Why it is unmet (or undecided); absent for a met criterion. */+ reason?: string;+ resultId?: string;+ state: CriterionOutcomeState;+ /** One line of what the evidence showed. */+ summary?: string;+}++/** First meaningful line of a prose field, stripped of markdown lead-ins. */+export const firstLine = (text?: string | null): string | undefined =>+ text+ ?.split('\n')+ .map((line) => line.replace(/^[#>*\-\s]+/, '').trim())+ .find(Boolean);++const outcomeState = (result: CheckResultLike): CriterionOutcomeState => {+ if (result.verdict === 'passed' || (!result.verdict && result.status === 'passed'))+ return 'passed';+ if (result.verdict === 'failed' || (!result.verdict && result.status === 'failed'))+ return 'failed';+ return 'unjudged';+};++/**+ * Each acceptance criterion of the Goal against what the latest Goal-level+ * acceptance round found.+ *+ * Criteria come in `goal.config.acceptance.criteriaIds` order. Only results of+ * the latest round count: an earlier round's verdict is history, and showing it+ * beside the current one would say the Goal met a bar it has since failed (or+ * the reverse). A result is matched on the criterion it was planned from+ * (`sourceCriterionId`), falling back to the union row id, which is the same+ * value for criterion-sourced checks. A criterion the round never judged stays+ * on the list as undecided rather than disappearing.+ */+export const buildCriterionOutcomes = ({+ checks,+ criteria,+ criteriaIds,+ latestRunId,+}: {+ checks: CheckLike[];+ criteria: CriterionLike[];+ criteriaIds: string[];+ latestRunId?: string;+}): CriterionOutcome[] => {+ const criterionById = new Map(criteria.map((criterion) => [criterion.id, criterion]));+ const latest = checks.filter(+ (check) => !!check.result && !!latestRunId && check.result.verifyRunId === latestRunId,+ );+ const checkFor = (criterionId: string) =>+ latest.find((check) => check.result!.sourceCriterionId === criterionId) ??+ latest.find((check) => !check.result!.sourceCriterionId && check.id === criterionId);++ return criteriaIds.flatMap((id): CriterionOutcome[] => {+ const criterion = criterionById.get(id);+ if (!criterion) return [];+ const check = checkFor(id);+ if (!check?.result) return [{ criterion, evidence: [], state: 'unjudged' }];++ const { result } = check;+ const state = outcomeState(result);+ const toulmin = result.toulmin ?? undefined;+ const summary =+ firstLine(toulmin?.evidence) ??+ firstLine(check.evidence.find((item) => item.description)?.description);+ const reason =+ state === 'passed'+ ? undefined+ : (firstLine(toulmin?.counterEvidence) ??+ firstLine(toulmin?.reasoning) ??+ firstLine(result.suggestion));++ return [+ {+ criterion,+ evidence: check.evidence,+ ...(reason ? { reason } : {}),+ resultId: result.id,+ state,+ ...(summary ? { summary } : {}),+ },+ ];+ });+};++/** The newest round of an acceptance, by its round index. */+export const latestRoundRunId = (+ rounds: { run: { id: string; roundIndex: number | null } }[],+): string | undefined =>+ rounds.reduce<{ id: string; roundIndex: number } | undefined>((latest, { run }) => {+ const roundIndex = run.roundIndex ?? 0;+ return !latest || roundIndex >= latest.roundIndex ? { id: run.id, roundIndex } : latest;+ }, undefined)?.id;++// ---------------------------------------------------------------------------+// 你做过的决定 / 没有完成+// ---------------------------------------------------------------------------++export interface UserDecisionView {+ /** The option label the owner picked, or their free-text resolution. */+ choice?: string;+ decision: GoalGraphDecision;+ question: string;+ resolvedAt?: Date;+}++/**+ * Decisions a person made on this Goal, oldest first. An agent resolving a+ * gate by itself is not the owner's decision, and a canceled gate decided+ * nothing — neither belongs on "what you decided".+ */+export const buildUserDecisions = (decisions: GoalGraphDecision[]): UserDecisionView[] =>+ decisions+ .filter((decision) => decision.status === 'resolved' && !!decision.resolvedByUserId)+ .map((decision) => {+ const option = decision.options?.find((item) => item.id === decision.resolvedOptionId);+ const choice = option?.label ?? decision.resolution?.trim() ?? undefined;+ return {+ ...(choice ? { choice } : {}),+ decision,+ question: decision.question,+ ...(decision.resolvedAt ? { resolvedAt: decision.resolvedAt } : {}),+ };+ })+ .sort((a, b) => (a.resolvedAt?.getTime() ?? 0) - (b.resolvedAt?.getTime() ?? 0));++export interface AbandonedNodeView {+ reason?: string;+ view: GoalNodeView;+}++/**+ * Task nodes the Goal gave up on — rejected or retired — with the reason+ * recorded when it closed them, falling back to the attempt that ended it.+ */+export const buildAbandonedNodes = (graph: Pick<GoalGraphView, 'nodes'>): AbandonedNodeView[] =>+ graph.nodes+ .filter(+ (view) =>+ view.node.kind === 'task' &&+ (view.node.status === 'rejected' || view.node.status === 'retired'),+ )+ .map((view) => {+ const reason = firstLine(+ view.closedReason ??+ view.attempts.findLast((attempt) => attempt.outcome !== 'running' && attempt.reason)+ ?.reason,+ );+ return { ...(reason ? { reason } : {}), view };+ });++/**+ * Work Tasks the Goal ran, for the scale line. The coordinator's own acceptance+ * and wrap-up Tasks check and describe the work; they are not part of it.+ */+export const countGoalTasks = (graph: Pick<GoalGraphView, 'nodes'>): number =>+ graph.nodes.filter(+ (view) =>+ view.node.kind === 'task' &&+ !isGoalAcceptanceTask(view) &&+ view.node.title !== GOAL_REPORT_TASK_TITLE,+ ).length;++/** The coordinator's wrap-up Task, which writes the report about the Goal. */+export const isGoalReportTaskView = (view: Pick<GoalNodeView, 'node'>): boolean =>+ view.node.kind === 'task' && view.node.title === GOAL_REPORT_TASK_TITLE;++/**+ * One step of the result's audit trail: the work that ran, what it concluded,+ * and what it produced. `view` is absent for conclusions no task claims.+ */+export interface ResultTrailStep {+ artifacts: GoalArtifactView[];+ findings: GoalNodeView[];+ key: string;+ view?: GoalNodeView;+}++const settledAt = (view: GoalNodeView) => (view.node.resolvedAt ?? view.node.createdAt).getTime();++/**+ * How the result was reached, in the order it happened.+ *+ * Conclusions and deliverables are two views of the same work: a conclusion is+ * what a task found out, a deliverable is what it wrote down. Shown as separate+ * lists they read as loose parts with no way in. Joined on the task that+ * produced them, each step reads top-down — the claim first, then the files+ * that back it, then (one click deeper) the run itself — which is the order a+ * reviewer audits in. Steps that concluded and produced nothing are left out:+ * the trail is about output, the process tab already lists every task.+ */+export const buildResultTrail = (+ graph: Pick<GoalGraphView, 'artifacts' | 'byId' | 'findings'>,+): ResultTrailStep[] => {+ const steps = new Map<string, ResultTrailStep>();+ const orphans: GoalNodeView[] = [];++ const stepOf = (nodeId: string) => {+ let step = steps.get(nodeId);+ if (!step) {+ step = { artifacts: [], findings: [], key: nodeId, view: graph.byId[nodeId] };+ steps.set(nodeId, step);+ }+ return step;+ };++ for (const finding of graph.findings) {+ const producer = finding.producedBy && graph.byId[finding.producedBy.id];+ if (producer && isGoalReportTaskView(producer)) continue;+ if (producer) stepOf(producer.node.id).findings.push(finding);+ else orphans.push(finding);+ }+ for (const artifact of graph.artifacts) {+ if (graph.byId[artifact.nodeId]) stepOf(artifact.nodeId).artifacts.push(artifact);+ }++ const ordered = [...steps.values()]+ // The wrap-up Task describes the result; it is not a step toward it.+ .filter((step) => step.view && !isGoalReportTaskView(step.view))+ .sort((a, b) => settledAt(a.view!) - settledAt(b.view!));+ for (const step of ordered) {+ step.findings.sort((a, b) => settledAt(a) - settledAt(b));+ step.artifacts.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());+ }++ if (orphans.length > 0)+ ordered.push({+ artifacts: [],+ findings: orphans.sort((a, b) => settledAt(a) - settledAt(b)),+ key: 'unattributed',+ });+ return ordered;+};++// ---------------------------------------------------------------------------+// 探索过程 — the wrap-up storyline, or the derived trail+// ---------------------------------------------------------------------------++/**+ * Where the 探索过程 section reads from:+ *+ * - `pending` — the wrap-up agent is writing the storyline right now; the+ * graph poll swaps it in when it lands.+ * - `story` — the storyline submitted for the latest acceptance result.+ * - `derived` — no report, the run failed, or its metadata does not parse:+ * the trail {@link buildResultTrail} derives from the graph.+ */+export type ResultTrailSource =+ | { kind: 'derived' }+ | { kind: 'pending' }+ | { kind: 'story'; metadata: GoalReportMetadata; report: GoalReportVersion };++export const resultTrailSource = (graph: Pick<GoalGraphView, 'report'>): ResultTrailSource => {+ const { report } = graph;+ if (report?.status === 'running') return { kind: 'pending' };+ if (report?.status !== 'completed' || !report.latest) return { kind: 'derived' };++ // Stored metadata went through the same schema on submit; re-checking here+ // keeps a row written by an older schema from breaking the page.+ const parsed = GoalReportMetadataSchema.safeParse(report.latest.metadata);+ if (!parsed.success) return { kind: 'derived' };+ return { kind: 'story', metadata: parsed.data, report: report.latest };+};++export interface StoryChapterView {+ artifacts: GoalArtifactView[];+ chapter: GoalReportChapter;+ /** Detour nodes still on the graph, called out on the chapter's local map. */+ detourNodeIds: string[];+ findings: GoalNodeView[];+ index: number;+ /** Main-path nodes plus detour nodes — what the chapter's local map shows. */+ mapNodeIds: string[];+}++const unique = (ids: string[]) => [...new Set(ids)];++/**+ * The storyline's chapters, in the order the report wrote them, with their+ * references resolved against the live graph. A reference the graph no longer+ * carries is dropped rather than rendered as an empty row.+ */+export const buildStoryChapters = (+ graph: Pick<GoalGraphView, 'artifacts' | 'byId'>,+ metadata: Pick<GoalReportMetadata, 'chapters'>,+): StoryChapterView[] => {+ const artifactByVersion = new Map(+ graph.artifacts.map((artifact) => [artifact.workVersionId, artifact]),+ );+ const onGraph = (id: string) => !!graph.byId[id];++ return metadata.chapters.map((chapter, index) => {+ const detourNodeIds = unique(chapter.detours.flatMap((detour) => detour.nodeIds)).filter(+ onGraph,+ );+ return {+ artifacts: unique(chapter.workVersionIds).flatMap((id) => {+ const artifact = artifactByVersion.get(id);+ return artifact ? [artifact] : [];+ }),+ chapter,+ detourNodeIds,+ findings: unique(chapter.findingIds).flatMap((id) => {+ const view = graph.byId[id];+ return view?.node.kind === 'finding' ? [view] : [];+ }),+ index,+ mapNodeIds: unique([...chapter.nodeIds.filter(onGraph), ...detourNodeIds]),+ };+ });+};diff --git a/src/features/AgentGoals/ProcessControl/index.tsx b/src/features/AgentGoals/ProcessControl/index.tsxindex e6ee56b83df..bc78eb0f81f 100644--- a/src/features/AgentGoals/ProcessControl/index.tsx+++ b/src/features/AgentGoals/ProcessControl/index.tsx@@ -16,6 +16,7 @@ import Deliverables from './Deliverables';import Findings from './Findings';import Frontier from './Frontier';import { buildGoalGraphView } from './goalGraphViewModel';+import GoalResultTabs from './GoalResultTabs';import Graph from './Graph';import {isGoalClosed,@@ -27,8 +28,10 @@ import {/*** The process-control band of the goal detail page: what can move now* (frontier), the map of how the goal got here, what it believes, and what it- * has been doing. Renders only for goals that actually carry a Goal Graph —- * a plain task-carried goal has no nodes and keeps the page it always had.+ * has been doing. Once the goal finishes, this becomes the 执行过程 tab behind+ * its 结果交付 (see `GoalResultTabs`). Renders only for goals that actually+ * carry a Goal Graph — a plain task-carried goal has no nodes and keeps the+ * page it always had.*/interface ProcessControlProps {@@ -97,7 +100,7 @@ const ProcessControl = memo<ProcessControlProps>(/>);- return (+ const process = (<Flexbox gap={20}>{hasExperiments && map}<Flexbox gap={12}>@@ -182,6 +185,8 @@ const ProcessControl = memo<ProcessControlProps>(/></Flexbox>);++ return <GoalResultTabs graph={graph} key={goalId} process={process} onSelect={select} />;},);diff --git a/src/features/AgentGoals/ProcessControl/useGoalResultData.test.ts b/src/features/AgentGoals/ProcessControl/useGoalResultData.test.tsnew file mode 100644index 00000000000..d41446ed1b8--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/useGoalResultData.test.ts@@ -0,0 +1,99 @@+import { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';+import { renderHook, waitFor } from '@testing-library/react';+import { createElement, type ReactNode } from 'react';+import { SWRConfig } from 'swr';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { GoalGraphView } from './goalGraphViewModel';+import { useGoalResultData } from './useGoalResultData';++const mocks = vi.hoisted(() => ({+ getAcceptanceBundle: vi.fn(),+ getCriteria: vi.fn(),+}));++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ useActiveWorkspaceId: () => undefined,+}));+vi.mock('@/services/verify', () => ({+ verifyService: {+ getAcceptanceBundle: mocks.getAcceptanceBundle,+ getCriteria: mocks.getCriteria,+ },+}));++const wrapper = ({ children }: { children: ReactNode }) =>+ createElement(+ SWRConfig,+ { value: { dedupingInterval: 0, provider: () => new Map(), shouldRetryOnError: false } },+ children,+ );++/** A Goal whose final acceptance Task carries acceptance `acc-1`. */+const graphWith = (acceptanceStatus: string, nodeStatus: string) =>+ ({+ goal: { config: { acceptance: { criteriaIds: ['crit-1'] } }, id: 'goal-1' },+ nodes: [+ {+ acceptance: { id: 'acc-1', status: acceptanceStatus },+ node: {+ id: 'node-acceptance',+ kind: 'task',+ status: nodeStatus,+ title: GOAL_ACCEPTANCE_TASK_TITLE,+ },+ },+ ],+ }) as unknown as GoalGraphView;++const bundle = (status: string) => ({+ acceptance: { status },+ canReview: true,+ checks: [],+ rounds: [],+});++describe('useGoalResultData', () => {+ beforeEach(() => {+ mocks.getAcceptanceBundle.mockReset();+ mocks.getCriteria.mockReset();+ mocks.getCriteria.mockResolvedValue([{ id: 'crit-1', title: 'Works' }]);+ });++ /**+ * Regression: after 提出修改 the rework keeps the same acceptance id, so the+ * bundle stayed on the rejected round — the sign-off bar kept reading 修改中+ * and hid the review actions until a reload.+ */+ it('re-reads the acceptance once the polled graph moves it on after a rework', async () => {+ mocks.getAcceptanceBundle.mockResolvedValueOnce(bundle('rejected'));+ const { rerender, result } = renderHook(({ graph }) => useGoalResultData(graph), {+ initialProps: { graph: graphWith('rejected', 'active') },+ wrapper,+ });+ await waitFor(() => expect(result.current.acceptanceStatus).toBe('rejected'));++ mocks.getAcceptanceBundle.mockResolvedValueOnce(bundle('delivered'));+ rerender({ graph: graphWith('delivered', 'resolved') });++ await waitFor(() => expect(result.current.acceptanceStatus).toBe('delivered'));+ expect(mocks.getAcceptanceBundle).toHaveBeenCalledTimes(2);+ });++ /**+ * Regression: a failed read fell back to empty data, so criteria rendered as+ * unjudged and the sign-off vanished with no error and no way to retry.+ */+ it('reports a failed read instead of passing empty data off as a result', async () => {+ mocks.getAcceptanceBundle.mockRejectedValueOnce(new Error('network down'));+ const { result } = renderHook(() => useGoalResultData(graphWith('delivered', 'resolved')), {+ wrapper,+ });+ await waitFor(() => expect(result.current.error).toBeInstanceOf(Error));++ mocks.getAcceptanceBundle.mockResolvedValueOnce(bundle('delivered'));+ await result.current.retry();+ await waitFor(() => expect(result.current.error).toBeUndefined());+ expect(result.current.acceptanceStatus).toBe('delivered');+ });+});diff --git a/src/features/AgentGoals/ProcessControl/useGoalResultData.ts b/src/features/AgentGoals/ProcessControl/useGoalResultData.tsnew file mode 100644index 00000000000..0e37477b4e8--- /dev/null+++ b/src/features/AgentGoals/ProcessControl/useGoalResultData.ts@@ -0,0 +1,75 @@+import { useClientDataSWR } from '@/libs/swr';+import { verifyService } from '@/services/verify';++import type { GoalGraphView } from './goalGraphViewModel';+import {+ buildCriterionOutcomes,+ type CheckLike,+ type CriterionOutcome,+ findGoalAcceptanceView,+ latestRoundRunId,+} from './goalResultState';++/**+ * Keyed by the graph's view of the acceptance as well as its id. A rework keeps+ * the same acceptance id, so an id-only key held the rejected round until a+ * reload; the polled graph moving the acceptance (or its Task node) on is what+ * re-reads the bundle.+ */+export const goalResultAcceptanceKey = (acceptanceId: string, graphState: string) =>+ ['goal-result-acceptance', acceptanceId, graphState] as const;++/**+ * What the result page reads beyond the graph: the Goal-level acceptance+ * bundle (rounds, check results, evidence) and the criteria it was judged+ * against. The graph only knows the acceptance id and status; the verdict per+ * criterion lives in the verify records, which are the source of truth — the+ * page never restates them from anywhere else.+ */+export const useGoalResultData = (graph: GoalGraphView) => {+ const acceptanceView = findGoalAcceptanceView(graph);+ const acceptanceId = acceptanceView?.acceptance?.id;+ const criteriaIds = graph.goal.config?.acceptance?.criteriaIds ?? [];++ const graphState = `${acceptanceView?.acceptance?.status}:${acceptanceView?.node.status}`;+ const bundle = useClientDataSWR(+ acceptanceId ? goalResultAcceptanceKey(acceptanceId, graphState) : null,+ () => verifyService.getAcceptanceBundle(acceptanceId!),+ // Keep the page on the last bundle while the next state loads, instead of+ // dropping back to skeletons every time the graph moves.+ { keepPreviousData: true },+ );+ const criteria = useClientDataSWR(+ criteriaIds.length > 0+ ? ['goal-acceptance-criteria', graph.goal.id, criteriaIds.join(',')]+ : null,+ () => verifyService.getCriteria(criteriaIds),+ );++ const outcomes: CriterionOutcome[] = buildCriterionOutcomes({+ checks: (bundle.data?.checks ?? []) as unknown as CheckLike[],+ criteria: criteria.data ?? [],+ criteriaIds,+ latestRunId: latestRoundRunId(bundle.data?.rounds ?? []),+ });++ // A failed read must not pass for a result: empty checks would render every+ // criterion as unjudged and a missing bundle would hide the sign-off.+ const error = bundle.error ?? criteria.error;++ return {+ acceptanceId,+ // The bundle is fresher than the graph snapshot right after a sign-off.+ acceptanceStatus: bundle.data?.acceptance.status ?? acceptanceView?.acceptance?.status,+ canReview: bundle.data?.canReview ?? false,+ error,+ isLoading:+ (!!acceptanceId && bundle.isLoading && !bundle.data) ||+ (criteriaIds.length > 0 && criteria.isLoading),+ mutateAcceptance: bundle.mutate,+ outcomes,+ retry: () => Promise.all([bundle.mutate(), criteria.mutate()]),+ };+};++export type GoalResultData = ReturnType<typeof useGoalResultData>;diff --git a/src/features/Portal/Goal/Body.tsx b/src/features/Portal/Goal/Body.tsxindex c880fa9ef94..f84ec108424 100644--- a/src/features/Portal/Goal/Body.tsx+++ b/src/features/Portal/Goal/Body.tsx@@ -13,6 +13,7 @@ import Deliverables from '@/features/AgentGoals/ProcessControl/Deliverables';import Findings from '@/features/AgentGoals/ProcessControl/Findings';import Frontier from '@/features/AgentGoals/ProcessControl/Frontier';import { buildGoalGraphView } from '@/features/AgentGoals/ProcessControl/goalGraphViewModel';+import GoalResultTabs from '@/features/AgentGoals/ProcessControl/GoalResultTabs';import Graph from '@/features/AgentGoals/ProcessControl/Graph';import {isGoalClosed,@@ -30,6 +31,7 @@ import { useOpenGoalPage } from './useOpenGoalPage';/*** The whole goal beside the conversation that planned it: header metrics, what* can move now, the exploration map, then what it produced, concluded and did.+ * A finished goal leads with its 结果交付 tab and keeps all of that as 执行过程.* Fetches the graph itself (polling while the server advances it), so it works* on any surface that hosts the Portal. Every click drills further down the same* view stack — node → task → topic — and Back returns here.@@ -84,87 +86,96 @@ const Body = memo(() => {<Flexbox flex={1} gap={20} padding={16} style={{ minHeight: 0, overflowY: 'auto' }}><GoalHeaderMetrics goalId={goalId} />{hasGraph && (- <>- <Frontier- actions={actions}- canEdit={canEdit && !isGoalClosed(graph)}- graph={graph}- planning={planning}- onSelect={select}- />- <Graph- graph={graph}- key={goalId}- planning={planning}- extra={- openGoalPage && (- <ActionIcon- aria-label={t('goalProcess.portal.openPage')}- icon={Maximize2}- size={'small'}- title={t('goalProcess.portal.openPage')}- onClick={openGoalPage}- />- )- }- onSelect={select}- />- <Accordion- defaultValue={['deliverables', 'findings', 'activity']}- gap={0}- indicatorPlacement="inline"- styles={{ header: { paddingBlock: 6, paddingInline: 0 } }}- items={[- {- children: (- <Flexbox className={styles.section}>- <Deliverables graph={graph} />- </Flexbox>- ),- key: 'deliverables',- title: (- <Flexbox horizontal align={'center'} gap={8}>- <Text fontSize={14} weight={600}>- {t('goalProcess.deliverables.title')}- </Text>- {graph.artifacts.length > 0 && (- <Tag size={'small'}>{graph.artifacts.length}</Tag>- )}- </Flexbox>- ),- },- {- children: (- <Flexbox className={styles.section}>- <Findings graph={graph} onSelect={select} />- </Flexbox>- ),- key: 'findings',- title: (- <Flexbox horizontal align={'center'} gap={8}>- <Text fontSize={14} weight={600}>- {t('goalProcess.findings.title')}- </Text>- {graph.findings.length > 0 && <Tag size={'small'}>{graph.findings.length}</Tag>}- </Flexbox>- ),- },- {- children: (- <Flexbox className={styles.section}>- <Activity graph={graph} onSelect={select} />- </Flexbox>- ),- key: 'activity',- title: (- <Text fontSize={14} weight={600}>- {t('goalProcess.activity.title')}- </Text>- ),- },- ]}- />- </>+ <GoalResultTabs+ graph={graph}+ key={goalId}+ process={+ <Flexbox gap={20}>+ <Frontier+ actions={actions}+ canEdit={canEdit && !isGoalClosed(graph)}+ graph={graph}+ planning={planning}+ onSelect={select}+ />+ <Graph+ graph={graph}+ key={goalId}+ planning={planning}+ extra={+ openGoalPage && (+ <ActionIcon+ aria-label={t('goalProcess.portal.openPage')}+ icon={Maximize2}+ size={'small'}+ title={t('goalProcess.portal.openPage')}+ onClick={openGoalPage}+ />+ )+ }+ onSelect={select}+ />+ <Accordion+ defaultValue={['deliverables', 'findings', 'activity']}+ gap={0}+ indicatorPlacement="inline"+ styles={{ header: { paddingBlock: 6, paddingInline: 0 } }}+ items={[+ {+ children: (+ <Flexbox className={styles.section}>+ <Deliverables graph={graph} />+ </Flexbox>+ ),+ key: 'deliverables',+ title: (+ <Flexbox horizontal align={'center'} gap={8}>+ <Text fontSize={14} weight={600}>+ {t('goalProcess.deliverables.title')}+ </Text>+ {graph.artifacts.length > 0 && (+ <Tag size={'small'}>{graph.artifacts.length}</Tag>+ )}+ </Flexbox>+ ),+ },+ {+ children: (+ <Flexbox className={styles.section}>+ <Findings graph={graph} onSelect={select} />+ </Flexbox>+ ),+ key: 'findings',+ title: (+ <Flexbox horizontal align={'center'} gap={8}>+ <Text fontSize={14} weight={600}>+ {t('goalProcess.findings.title')}+ </Text>+ {graph.findings.length > 0 && (+ <Tag size={'small'}>{graph.findings.length}</Tag>+ )}+ </Flexbox>+ ),+ },+ {+ children: (+ <Flexbox className={styles.section}>+ <Activity graph={graph} onSelect={select} />+ </Flexbox>+ ),+ key: 'activity',+ title: (+ <Text fontSize={14} weight={600}>+ {t('goalProcess.activity.title')}+ </Text>+ ),+ },+ ]}+ />+ </Flexbox>+ }+ onSelect={select}+ />)}</Flexbox>);diff --git a/src/features/Portal/GoalReport/Body.tsx b/src/features/Portal/GoalReport/Body.tsxnew file mode 100644index 00000000000..0f52e9e32e2--- /dev/null+++ b/src/features/Portal/GoalReport/Body.tsx@@ -0,0 +1,142 @@+import { Flexbox, Markdown } from '@lobehub/ui';+import { Skeleton, Tag, Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { memo, type ReactNode, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import AsyncError from '@/components/AsyncError';+import Graph from '@/features/AgentGoals/ProcessControl/Graph';+import { chapterMap } from '@/features/AgentGoals/ProcessControl/Graph/chapterMap';+import { useChatStore } from '@/store/chat';+import { chatPortalSelectors } from '@/store/chat/selectors';++import { useReportChapter, useReportGraph } from './useReportGraph';++/**+ * The Goal report beside the result page. Both views read the live graph+ * snapshot, so a report rewritten after a new acceptance result replaces what+ * the panel shows instead of leaving a stale copy open.+ */++const styles = createStaticStyles(({ css }) => ({+ detour: css`+ padding-block: 10px;+ padding-inline: 12px;+ border: 1px dashed ${cssVar.colorWarningBorder};+ border-radius: ${cssVar.borderRadius};++ background: ${cssVar.colorWarningBg};+ `,+ scroll: css`+ overflow-y: auto;+ flex: 1;+ min-height: 0;+ `,+}));++const Frame = ({ children }: { children: ReactNode }) => (+ <Flexbox className={styles.scroll} gap={16} padding={16}>+ {children}+ </Flexbox>+);++const Loading = () => (+ <Frame>+ <Skeleton height={20} radius={4} width={'48%'} />+ <Skeleton height={14} radius={4} />+ <Skeleton height={14} radius={4} />+ <Skeleton height={14} radius={4} width={'64%'} />+ </Frame>+);++const Unavailable = ({ children }: { children: string }) => (+ <Frame>+ <Text type={'secondary'}>{children}</Text>+ </Frame>+);++export const ReportBody = memo(() => {+ const { t } = useTranslation('chat');+ const view = useChatStore(chatPortalSelectors.goalReportView);+ const { error, isLoading, mutate, story } = useReportGraph(view?.goalId);++ if (!view) return null;+ if (isLoading) return <Loading />;+ if (error && !story) return <AsyncError error={error} onRetry={() => void mutate()} />;+ if (!story) return <Unavailable>{t('goalProcess.result.story.unavailable')}</Unavailable>;++ const content = story.report.content?.trim();++ return (+ <Frame>+ <Text fontSize={16} weight={600}>+ {story.metadata.headline}+ </Text>+ {content ? (+ <Markdown variant={'chat'}>{content}</Markdown>+ ) : (+ <Text type={'secondary'}>{t('goalProcess.result.story.reportEmpty')}</Text>+ )}+ </Frame>+ );+});++ReportBody.displayName = 'GoalReportBody';++export const ChapterBody = memo(() => {+ const { t } = useTranslation('chat');+ const view = useChatStore(chatPortalSelectors.goalReportChapterView);+ const drillIntoGoalNode = useChatStore((s) => s.drillIntoGoalNode);+ const { error, graph, isLoading, mutate, story } = useReportGraph(view?.goalId);+ const chapter = useReportChapter(graph, story, view?.chapterIndex);++ // The map reuses the exploration graph narrowed to this chapter: its main+ // path and the nodes it strayed onto, with the strays called out and joined+ // back to where they forked.+ const map = useMemo(+ () => (graph && chapter ? chapterMap(graph, chapter.mapNodeIds) : undefined),+ [graph, chapter],+ );+ const highlightedIds = useMemo(() => new Set(chapter?.detourNodeIds ?? []), [chapter]);++ if (!view) return null;+ if (isLoading) return <Loading />;+ if (error && !story) return <AsyncError error={error} onRetry={() => void mutate()} />;+ if (!chapter || !map)+ return <Unavailable>{t('goalProcess.result.story.chapterMissing')}</Unavailable>;++ return (+ <Frame>+ <Flexbox gap={8}>+ {chapter.chapter.detours.map((detour, index) => (+ <Flexbox className={styles.detour} gap={4} key={index}>+ <Flexbox horizontal align={'center'} gap={8}>+ <Tag color={'warning'} size={'small'}>+ {t(`goalProcess.result.story.detourKind.${detour.kind}`)}+ </Tag>+ <Text weight={600}>{detour.title}</Text>+ </Flexbox>+ <Text fontSize={13}>{detour.reason}</Text>+ <Text fontSize={13} type={'secondary'}>+ {`${t('goalProcess.result.story.lesson')}:${detour.lesson}`}+ </Text>+ </Flexbox>+ ))}+ </Flexbox>+ <Text fontSize={12} type={'secondary'}>+ {t('goalProcess.result.story.mapHint')}+ </Text>+ {map.graph.nodes.length > 0 && (+ <Graph+ bridges={map.bridges}+ graph={map.graph}+ highlightedIds={highlightedIds}+ key={`${view.goalId}:${view.chapterIndex}`}+ onSelect={(nodeId) => drillIntoGoalNode(view.goalId, nodeId)}+ />+ )}+ </Frame>+ );+});++ChapterBody.displayName = 'GoalReportChapterBody';diff --git a/src/features/Portal/GoalReport/Title.tsx b/src/features/Portal/GoalReport/Title.tsxnew file mode 100644index 00000000000..a908a5e421a--- /dev/null+++ b/src/features/Portal/GoalReport/Title.tsx@@ -0,0 +1,39 @@+import { Text } from '@lobehub/ui/base-ui';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { useChatStore } from '@/store/chat';+import { chatPortalSelectors } from '@/store/chat/selectors';+import { oneLineEllipsis } from '@/styles';++import { useReportChapter, useReportGraph } from './useReportGraph';++const TitleText = ({ children }: { children: string }) => (+ <Text className={oneLineEllipsis} style={{ flex: '0 1 auto', fontSize: 14, minWidth: 0 }}>+ {children}+ </Text>+);++export const ReportTitle = memo(() => {+ const { t } = useTranslation('chat');+ return <TitleText>{t('goalProcess.result.story.reportTitle')}</TitleText>;+});++ReportTitle.displayName = 'GoalReportTitle';++export const ChapterTitle = memo(() => {+ const { t } = useTranslation('chat');+ const view = useChatStore(chatPortalSelectors.goalReportChapterView);+ const { graph, story } = useReportGraph(view?.goalId);+ const chapter = useReportChapter(graph, story, view?.chapterIndex);++ return (+ <TitleText>+ {chapter+ ? `${t('goalProcess.result.story.mapTitle')} · ${chapter.chapter.title}`+ : t('goalProcess.result.story.mapTitle')}+ </TitleText>+ );+});++ChapterTitle.displayName = 'GoalReportChapterTitle';diff --git a/src/features/Portal/GoalReport/index.ts b/src/features/Portal/GoalReport/index.tsnew file mode 100644index 00000000000..ae90bcdccec--- /dev/null+++ b/src/features/Portal/GoalReport/index.ts@@ -0,0 +1,9 @@+import { type PortalImpl } from '../type';+import { ChapterBody, ReportBody } from './Body';+import { ChapterTitle, ReportTitle } from './Title';++/** The Goal report's full text, opened from the result page's 探索过程. */+export const GoalReport: PortalImpl = { Body: ReportBody, Title: ReportTitle };++/** One storyline chapter's local map — its main path and the detours off it. */+export const GoalReportChapter: PortalImpl = { Body: ChapterBody, Title: ChapterTitle };diff --git a/src/features/Portal/GoalReport/useReportGraph.ts b/src/features/Portal/GoalReport/useReportGraph.tsnew file mode 100644index 00000000000..546c5daac3e--- /dev/null+++ b/src/features/Portal/GoalReport/useReportGraph.ts@@ -0,0 +1,38 @@+import { useMemo } from 'react';++import {+ buildGoalGraphView,+ type GoalGraphView,+} from '@/features/AgentGoals/ProcessControl/goalGraphViewModel';+import {+ buildStoryChapters,+ resultTrailSource,+ type StoryChapterView,+} from '@/features/AgentGoals/ProcessControl/goalResultState';+import { goalSelectors, useGoalStore } from '@/store/goal';++/**+ * The goal graph a report view reads, shared by SWR key with the result page+ * that opened it — so the panel follows the same poll and never holds a copy+ * of the report that the page has already moved past.+ */+export const useReportGraph = (goalId?: string) => {+ const useFetchGoalGraph = useGoalStore((s) => s.useFetchGoalGraph);+ const { error, isLoading, mutate } = useFetchGoalGraph(goalId);+ const snapshot = useGoalStore(goalSelectors.goalGraph(goalId ?? ''));+ const graph = useMemo(() => (snapshot ? buildGoalGraphView(snapshot) : undefined), [snapshot]);+ const source = graph ? resultTrailSource(graph) : undefined;+ const story = source?.kind === 'story' ? source : undefined;++ return { error, graph, isLoading: isLoading && !snapshot, mutate, story };+};++export const useReportChapter = (+ graph: GoalGraphView | undefined,+ story: ReturnType<typeof useReportGraph>['story'],+ chapterIndex?: number,+): StoryChapterView | undefined =>+ useMemo(() => {+ if (!graph || !story || chapterIndex === undefined) return undefined;+ return buildStoryChapters(graph, story.metadata)[chapterIndex];+ }, [graph, story, chapterIndex]);diff --git a/src/features/Portal/portalWidth.ts b/src/features/Portal/portalWidth.tsindex 64412ba2499..5530a8efa06 100644--- a/src/features/Portal/portalWidth.ts+++ b/src/features/Portal/portalWidth.ts@@ -36,6 +36,8 @@ const VIEW_MIN_WIDTH: PortalWidths = {[PortalViewType.Goal]: CHAT_PORTAL_TOOL_UI_WIDTH,[PortalViewType.GoalMetric]: CHAT_PORTAL_TOOL_UI_WIDTH,[PortalViewType.GoalNode]: CHAT_PORTAL_TOOL_UI_WIDTH,+ [PortalViewType.GoalReport]: CHAT_PORTAL_TOOL_UI_WIDTH,+ [PortalViewType.GoalReportChapter]: CHAT_PORTAL_TOOL_UI_WIDTH,[PortalViewType.TaskDetail]: CHAT_PORTAL_TOOL_UI_WIDTH,[PortalViewType.TaskResult]: CHAT_PORTAL_TOOL_UI_WIDTH,[PortalViewType.Thread]: CHAT_PORTAL_TOOL_UI_WIDTH,@@ -58,6 +60,10 @@ const VIEW_DEFAULT_WIDTH: PortalWidths = {// activity feed into one column — wider than the reading column, but the// full document width crowds the page it sits next to.[PortalViewType.GoalNode]: CHAT_PORTAL_TASK_WIDTH,+ // A written report reads like a document; the chapter map needs room to lay+ // out a path with its branches.+ [PortalViewType.GoalReport]: CHAT_PORTAL_WIDE_WIDTH,+ [PortalViewType.GoalReportChapter]: CHAT_PORTAL_WIDE_WIDTH,[PortalViewType.TaskDetail]: CHAT_PORTAL_TASK_WIDTH,[PortalViewType.TaskResult]: CHAT_PORTAL_TASK_WIDTH,};diff --git a/src/features/Portal/router.tsx b/src/features/Portal/router.tsxindex dd5c96084d0..dc54a7e5b0d 100644--- a/src/features/Portal/router.tsx+++ b/src/features/Portal/router.tsx@@ -17,6 +17,7 @@ import { FilePreview } from './FilePreview';import { Goal } from './Goal';import { GoalMetric } from './GoalMetric';import { GoalNode } from './GoalNode';+import { GoalReport, GoalReportChapter } from './GoalReport';import { GroupThread } from './GroupThread';import { HomeBody, HomeTitle } from './Home';import { LocalFile } from './LocalFile';@@ -48,6 +49,8 @@ const VIEW_COMPONENTS: Record<PortalViewType, PortalImpl> = {[PortalViewType.Goal]: Goal,[PortalViewType.GoalMetric]: GoalMetric,[PortalViewType.GoalNode]: GoalNode,+ [PortalViewType.GoalReport]: GoalReport,+ [PortalViewType.GoalReportChapter]: GoalReportChapter,[PortalViewType.LocalFile]: LocalFile,[PortalViewType.MessageDetail]: MessageDetail,[PortalViewType.ToolUI]: Plugins,diff --git a/src/features/Work/descriptors.tsx b/src/features/Work/descriptors.tsxindex 24bcbdc53db..56a7ee9210a 100644--- a/src/features/Work/descriptors.tsx+++ b/src/features/Work/descriptors.tsx@@ -1,5 +1,6 @@import { classifyEditedFile, getBasename } from '@lobechat/builtin-tools/fileEditScan';import {+ type ListedWorkType,type WorkListItem,workProviderOfResourceType,type WorkSkillProvider,@@ -156,7 +157,7 @@ const getFileWorkPath = (item: WorkItemOfType<'file'>): string | null =>getFileWorkMetadata(item)?.filePath ?? item.description?.trim() ?? null;export const WORK_TYPE_DESCRIPTORS: {- [T in WorkType]: WorkTypeDescriptor<WorkItemOfType<T>>;+ [T in ListedWorkType]: WorkTypeDescriptor<WorkItemOfType<T>>;} = {document: {getDescription: (item) => item.description?.trim() ?? null,@@ -287,9 +288,6 @@ export const getWorkTypeDescriptor = <Item extends WorkListItem | WorkSummaryIte// genuinely be missing even though the compile-time map looks total. The// re-narrowing casts are safe — a registry entry keyed by `item.type` accepts// exactly that type's item, which `Item` is.- const descriptors = WORK_TYPE_DESCRIPTORS as Record<- WorkType,- WorkTypeDescriptor<Item> | undefined- >;+ const descriptors = WORK_TYPE_DESCRIPTORS as Partial<Record<WorkType, WorkTypeDescriptor<Item>>>;return descriptors[item.type] ?? (FALLBACK_WORK_TYPE_DESCRIPTOR as WorkTypeDescriptor<Item>);};diff --git a/src/features/WorkGallery/const.tsx b/src/features/WorkGallery/const.tsxindex 77259577304..466027d697b 100644--- a/src/features/WorkGallery/const.tsx+++ b/src/features/WorkGallery/const.tsx@@ -1,4 +1,4 @@-import type { WorkSkillProvider, WorkType } from '@lobechat/types';+import type { ListedWorkType, WorkSkillProvider } from '@lobechat/types';/*** `?works=` values: the per-type keys (task / document) plus the per-PROVIDER@@ -16,7 +16,7 @@ export type WorkGalleryKey = 'all' | 'document' | 'github' | 'linear' | 'task';*/export interface WorkGalleryFilter {provider?: WorkSkillProvider;- type?: WorkType;+ type?: ListedWorkType;}const FILTER_BY_KEY = new Map<WorkGalleryKey, WorkGalleryFilter>([diff --git a/src/services/work.ts b/src/services/work.tsindex 5d115ddbf47..21c613b604f 100644--- a/src/services/work.ts+++ b/src/services/work.ts@@ -1,5 +1,6 @@import { TaskApiName, TaskIdentifier } from '@lobechat/builtin-tool-task';import type {+ ListedWorkType,RegisterDocumentWorkParams,RegisterSkillToolResultWorkParams,RegisterTaskWorkParams,@@ -7,7 +8,6 @@ import type {WorkListItem,WorkSkillProvider,WorkSummaryItem,- WorkType,WorkVersionEventItem,WorkVersionEventMap,WorkVersionItem,@@ -76,7 +76,7 @@ class WorkService {limit?: number;originAgentId?: string | null;provider?: WorkSkillProvider;- type?: WorkType | null;+ type?: ListedWorkType | null;visibility?: WorkVisibility;}): Promise<WorkSummaryPage> =>lambdaClient.work.listByWorkspace.query({ ...params, includeFileWorks: true });diff --git a/src/store/chat/slices/portal/action.ts b/src/store/chat/slices/portal/action.tsindex 9ba324fbb15..ad0bc0ac4db 100644--- a/src/store/chat/slices/portal/action.ts+++ b/src/store/chat/slices/portal/action.ts@@ -728,6 +728,16 @@ export class ChatPortalActionImpl {);};+ /** The wrap-up report's full text, read beside the result page. */+ openGoalReport = (goalId: string): void => {+ this.#get().pushPortalView({ goalId, type: PortalViewType.GoalReport });+ };++ /** One storyline chapter's local map: its main path and the detours off it. */+ openGoalReportChapter = (goalId: string, chapterIndex: number): void => {+ this.#get().pushPortalView({ chapterIndex, goalId, type: PortalViewType.GoalReportChapter });+ };+openGoalMetric = (goalId: string, metric: GoalMetricKind): void => {this.#get().pushPortalView({ goalId, metric, type: PortalViewType.GoalMetric });};diff --git a/src/store/chat/slices/portal/initialState.ts b/src/store/chat/slices/portal/initialState.tsindex 677936f738a..fb14a7ca829 100644--- a/src/store/chat/slices/portal/initialState.ts+++ b/src/store/chat/slices/portal/initialState.ts@@ -19,6 +19,8 @@ export enum PortalViewType {Goal = 'goal',GoalMetric = 'goalMetric',GoalNode = 'goalNode',+ GoalReport = 'goalReport',+ GoalReportChapter = 'goalReportChapter',GroupThread = 'groupThread',Home = 'home',LocalFile = 'localFile',@@ -72,6 +74,8 @@ export type PortalViewData =| { goalId: string; type: PortalViewType.Goal }| { goalId: string; metric: GoalMetricKind; type: PortalViewType.GoalMetric }| { goalId: string; nodeId: string; type: PortalViewType.GoalNode }+ | { goalId: string; type: PortalViewType.GoalReport }+ | { chapterIndex: number; goalId: string; type: PortalViewType.GoalReportChapter }| { acceptanceId: string; type: PortalViewType.Acceptance }| { acceptanceId: string; checkId: string; type: PortalViewType.AcceptanceCheck }| { agentId: string; type: PortalViewType.AgentDetail }diff --git a/src/store/chat/slices/portal/selectors.ts b/src/store/chat/slices/portal/selectors.tsindex 14caa3fac14..dc8690f9f36 100644--- a/src/store/chat/slices/portal/selectors.ts+++ b/src/store/chat/slices/portal/selectors.ts@@ -267,6 +267,9 @@ const goalPortalId = (s: ChatStoreState): string | undefined =>getViewData(s, PortalViewType.Goal)?.goalId;const goalNodeView = (s: ChatStoreState) => getViewData(s, PortalViewType.GoalNode);const goalMetricView = (s: ChatStoreState) => getViewData(s, PortalViewType.GoalMetric);+const goalReportView = (s: ChatStoreState) => getViewData(s, PortalViewType.GoalReport);+const goalReportChapterView = (s: ChatStoreState) =>+ getViewData(s, PortalViewType.GoalReportChapter);// Topic chat selectors — the second, side-by-side topic opened in the portalconst portalTopicId = (s: ChatStoreState): string | undefined => {@@ -352,6 +355,8 @@ export const chatPortalSelectors = {goalMetricView,goalNodeView,goalPortalId,+ goalReportChapterView,+ goalReportView,// Local file dataactiveLocalFileId,diff --git a/src/store/goal/action.test.ts b/src/store/goal/action.test.tsindex 56d852b172e..8d8d050c705 100644--- a/src/store/goal/action.test.ts+++ b/src/store/goal/action.test.ts@@ -55,6 +55,23 @@ describe('GoalAction', () => {},);+ it('keeps polling a finished goal while its wrap-up report is being written', () => {+ useGoalStore.getState().useFetchGoalGraph('goal-1');+ const options = vi.mocked(useClientDataSWR).mock.calls.at(-1)?.[2] as {+ refreshInterval: (graph?: unknown) => number;+ };++ expect(+ options.refreshInterval({ goal: { status: 'achieved' }, report: { status: 'running' } }),+ ).toBeGreaterThan(0);+ expect(+ options.refreshInterval({ goal: { status: 'achieved' }, report: { status: 'completed' } }),+ ).toBe(0);+ expect(+ options.refreshInterval({ goal: { status: 'failed' }, report: { status: 'failed' } }),+ ).toBe(0);+ });+it('does not poll before the first snapshot arrives', () => {useGoalStore.getState().useFetchGoalGraph('goal-1');const options = vi.mocked(useClientDataSWR).mock.calls.at(-1)?.[2] as {diff --git a/src/store/goal/action.ts b/src/store/goal/action.tsindex 5cfee7d7066..b1faf631ca1 100644--- a/src/store/goal/action.ts+++ b/src/store/goal/action.ts@@ -191,8 +191,13 @@ export class GoalActionImpl {'useFetchGoalGraph/success',);},+ // The wrap-up report is written after the Goal settles, so a finished+ // Goal keeps polling until its report run ends and the storyline lands.refreshInterval: (graph) =>- graph && SERVER_ADVANCING_STATUSES.has(graph.goal.status) ? GOAL_GRAPH_POLL_INTERVAL : 0,+ graph &&+ (SERVER_ADVANCING_STATUSES.has(graph.goal.status) || graph.report?.status === 'running')+ ? GOAL_GRAPH_POLL_INTERVAL+ : 0,revalidateOnFocus: true,});